<?php
/**
 * 推荐设置控制器
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
namespace Admin\Controller;
class ShareBonusController extends BaseController
{
    public function _initialize()
    {
        // parent::_initialize();
        // $is_auth=check_use_auth("NationalCustomers");
        // if($is_auth['status']==0){
        //     $this->error('该版本没有此权限',$is_auth['url']);return;
        // }
        $status_type=array('0'=>'全部','1'=>'未开始','2'=>'进行中','3'=>'已完成');$this->assign('status_type',$status_type);
    }

    public function index(){
        $postdata=I('param.');$this->assign($postdata);
        if($postdata){
            $start_time=strtotime($postdata['start_time']);
            $end_time=strtotime($postdata['end_time']);
            if($start_time>0)$map['addtime'][]=array('egt',$start_time);
            if($end_time>0)$map['addtime'][]=array('lt',$end_time);
            if($start_time==0 || $end_time==0){
                $this->error('请选择时间');return;
            }
            //根据时间统计出所有参与分红的会员及其三种权重数
            $result=share_bonus($start_time,$end_time);
            $orderinfo = M('OrderInfo')->where($map)->field("count(id) as num,sum(goods_allmoney) as goodsmoney,sum(profit) as profit")->find();
            $this->assign($orderinfo);
            $this->assign('list',$result['user_money']);
        }
        $this->display();
    }

    public function share(){
        $postdata=I('param.');
        // $return=array('return'=>0,'msg'=>'');
        if($postdata){
            if(format_decimal($postdata['money'])<=0){
                $this->error('请填写分红金额');return;
                // $return['msg']='请填写分红金额';$this->ajaxReturn($return);
            }
            $start_time=strtotime($postdata['start_time']);
            $end_time=strtotime($postdata['end_time']);
            $where['start_time']=$start_time;
            $where['end_time']=$end_time;
            $share_info=M('ShareLog')->where($where)->field(true)->find();
            if($share_info){
                if($share_info['status']==2){
                    $this->success('本时间段内分红已完成');
                }else{
                    if($share_info['stop_key']==0){//还未开始
                        $this->fafang($share_info['id'],1);
                    }else{
                        $this->fafang($share_info['id'],2);  //继续发放
                    }
                }
            }else{
                //根据时间统计出所有参与分红的会员及其三种权重数
                $result=share_bonus($start_time,$end_time);
                // print_r($result);die;
                $data['user_num']=$result['log']['user_num']; //分红总人数
                $data['sum_weight']=$result['log']['sum_weight'];//此次分红总权重数
                $data['user_money']=serialize($result['user_money']);//此次所有参与分红的会员及其三种权重数
                //添加分红记录
                $data['start_time']=$start_time;
                $data['end_time']=$end_time;
                $data['money']=format_decimal($postdata['money']);
                $data['status']=0;
                $id=M('ShareLog')->add($data);
                if($id){
                    // $return['id']=$id;
                    // $return['status']=1;
                    $this->fafang($id,1);
                }
            }
        }
    }

    public function fafang($id,$type){
        if(!$id)$this->error('参数错误');
        $map=array();
        $map['id']=$id;
        $share_info=M('ShareLog')->where($map)->field(true)->find();
        if($share_info['status']<=1){
            $user_money=unserialize($share_info['user_money']);
            if($type==2){
                $num=intval($share_info['stop_key'])+1;
                array_splice($user_money,0,$num);
            }
            $single_weight=$share_info['money']/$share_info['sum_weight']; //分红金额 (元/权重)
            $single_weight=floor($single_weight*100)/100;
            if($user_money){
                $length=count($user_money)-1;
                foreach ($user_money as $key => $value) {
                    $money=$value['user_weight']*$single_weight;
                    $msg="将赠".idtoname($value['uid'],'Member','username;nickname').'分红佣金：'.$money;
                    if($money>0){
                        $data['stop_key']=$key;
                        if($key==$length){
                            $data['status']=2;
                        }else{
                            $data['status']=1;
                        }
                        $res=M('ShareLog')->where($map)->save($data);
                        if($res!=false)$a_log=account_change($value['uid'],$money,8,20,$msg,0,true,0,$id);
                        if($a_log != false){
                            $jidu=$key+1;
                            if($key==$length){
                                $this->success('分红完成');
                            }else{
                                echo '发放进行中...[请不要关闭网页].当前已发放:'.$jidu.'人';
                            }
                        }  
                    }
                }
            }
        }else{
            $this->success('分红完成');
        }
    }

    /**
     * 分红记录
     */
    public function share_log(){
        $postdata=I('param.');$this->assign($postdata);
        $map=array();
        if(intval($postdata['status']) > 0)$map['status']=intval($postdata['status'])-1;
        if($postdata['start_time'])$map['start_time']=array('egt',strtotime($postdata['start_time']));
        if($postdata['end_time'])$map['end_time']=array('elt',strtotime($postdata['end_time']));
        $list=$this->lists('ShareLog',$map);
        $this->assign('list',$list);
        $this->display();
    }

    /**
     * 继续发放、开始发放
     */
    public function share_bonus(){
        $postdata=I('param.');
        $this->fafang($postdata['id'],$postdata['type']);
    }
    /**
     * 读取推荐设置的数据
     */
    public function setting(){
        $res = M('Config')->field('value')->where("name='SHAREBONUS'")->find();
        $val = unserialize($res['value']);
        $memberrank = M('MemberRank')->where('status = 1')->field('id,name')->select();
        foreach ($memberrank as $key => $value) {
            $new[$value['id']]=$value['name'];
        }
        $this->assign('level', $new);
        $this->assign('config', $val['config']);
        $this->assign('item', $val['item']);
        $this->assign('t_performance', $val['t_performance']);
        $this->assign('g_performance', $val['g_performance']);
        $this->display();
    }

    /**
     * 修改推荐设置的数据
     */
    public function update(){
        $postdata = I('post.');
        $level_weight = $t_performance = $g_performance =array();
        $temp['config'] = array(
            'fh_level' => $postdata['fh_level'],        //分红等级条件
            'child_level' => $postdata['child_level'],   //下级X等级会员
            'child_level_num' => $postdata['child_level_num'], //下级n个X等级会员
        );
        //等级权重 start
        foreach ($postdata['level_weight'] as $key => $v) {
            if (empty($v)) continue;
            $level_weight[$key]['level_weight'] = $v;
        }
        $temp['item'] = $level_weight;
        //等级权重 end
        
        //团队业绩权重 start
        foreach ($postdata['t_money'] as $k => $val) {
            if (empty($val) && empty($postdata['t_money_weight'][$k])) continue;
            $t_performance[$k]['t_money'] = $val;
            $t_performance[$k]['t_money_weight'] = $postdata['t_money_weight'][$k];
        }
        $temp['t_performance'] = $t_performance;
        //团队业绩权重 end
        
        //个人业绩权重 start
        foreach ($postdata['g_money'] as $k => $val) {
            if (empty($val) && empty($postdata['g_money_weight'][$k])) continue;
            $g_performance[$k]['g_money'] = $val;
            $g_performance[$k]['g_money_weight'] = $postdata['g_money_weight'][$k];
        }
        $temp['g_performance'] = $g_performance;
        //个人业绩权重 end
        
        $temp = serialize($temp);
        $where['name'] = 'SHAREBONUS';
        $res = M('Config')->field('value')->where($where)->find();
        $data['value'] = $temp;
        if (empty($res)) {
            $data['name'] = 'SHAREBONUS';
            $save = M('Config')->data($data)->add();
        } else {
            $save = M('Config')->data($data)->where($where)->save();
        }
        if (!empty($save) || $save == 0) {
            $this->success('修改分红奖励成功',U('Admin/ShareBonus/setting'));
        } else {
            $this->error('修改分红奖励失败',U('Admin/ShareBonus/setting'));
        }
    }
}
?>