<?php
namespace Admin\Controller;

use mysql_xdevapi\Exception;
use User\Api\PromoteApi;
use User\Api\UserApi;
use Org\XiguSDK\Xigu;
use Base\Service\PromoteService;

/**
 * 后台首页控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class PromoteController extends ThinkController
{
    const model_name = 'Promote';

    public function lists($p=1)
    {
        switch ($_GET['type']) {
            case '':
            case 1:
                $this->promoteList($p);
                break;
            default:
                $this->siteApplyList($p);
                break;
        }
    }

    private function promoteList($p)
    {
        // if (isset($_REQUEST['promote_id'])) {
        //     $promoteid = $_REQUEST['promote_id'];
        //     unset($_REQUEST['promote_id']);
        //     if (isset($_REQUEST['parent_id'])) {
        //         $parent_id = $_REQUEST['parent_id'];
        //         unset($_REQUEST['parent_id']);
        //         if ($promoteid == $parent_id) {
        //             $map['id'] = $promoteid;
        //         }
        //     } else {
        //         $map['id'] = $promoteid;
        //     }
        // } else {
            $promoteid = false;
            if (isset($_REQUEST['promote_id'])) {
                $promoteid = $_REQUEST['promote_id'];

                $map['id'] = $_REQUEST['promote_id'];
            }
            if (isset($_REQUEST['parent_id'])) {
                if ($_REQUEST['parent_id']=='全部') {
                    unset($_REQUEST['parent_id']);
                }
                $zid=get_zi_promote_id($_REQUEST['parent_id']);
                if ($zid) {
                    $zid=$zid.','.$_REQUEST['parent_id'];
                } else {
                    $zid=$_REQUEST['parent_id'];
                }
                //判断自己是否在里面
                $zidarr = explode(",",$zid);
                if ($promoteid > 0 ) {
                    if (in_array($promoteid,$zidarr)) {
                        # code...
                        $map['id'] = $promoteid;
                    }else{
                        $map['id'] = 0;
                    }
                }else{
                    $map['id']=array('in',$zid);
                }
                // 
                unset($_REQUEST['parent_id']);
            }
            
        if (isset($_REQUEST['admin_id'])) {
            if ($_REQUEST['admin_id']=="全部") {
                unset($_REQUEST['admin']);
            } else {
                $map['ba_id']=$_REQUEST['admin_id'];
            }
        }
        if (I('status') || I('status', -1) == 0) {
            $map['status'] = I('status');
        }

        if (I('ver_status') || I('ver_status', -1) == 0) {
            $map['ver_status'] = I('ver_status');
        }

        if (I("promote_level")) {
            $map['level'] = I("promote_level");
        }
        $this->m_title = '推广员列表';
        $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/lists/type/1','status'=>1])->find());
        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }

        if (I('oa_associated', -1) != -1) {
            $map['oa_associated'] = I('oa_associated');
            $oa_data = [];
            for ($i = 1; $i > 0; $i++) {
                $arr['time'] = time();
                $arr['page'] = $i;
                $arr['pageSize'] = 1000;
                ksort($arr);
                reset($arr);
                $sign = md5(http_build_query($arr) . C('GET_INFO_KEY'));
                $arr['sign'] = $sign;
                $re_data = curl_post(C('OA.formalUrl') . '/api/wanmeng/platformAccount', $arr);
                $re_data = json_decode($re_data, true);
                if ($re_data['code'] == 1) {
                    $oa = $re_data['data'];
                    $oa_data = array_merge($oa_data, $oa);
                } else {
                    break;
                }
            }

            // $promote =  D(self::model_name)->field('id,account')->where(['oa_associated' => 0])->order('id DESC')->select(); //只获取之前未关联
            $promote =  D(self::model_name)->field('id,account,oa_associated')->order('id DESC')->select(); //全部重新获取
            $oa_data = array_column($oa_data, 'platform_account');
            foreach ($promote as $k => $v) {
                $v['account'] = trim($v['account']);
                $oa_val = (in_array($v['account'], $oa_data)) ? 1: 0;
                if ($v['oa_associated'] != $oa_val) {
                    M('promote', 'tab_')->where(['id' => $v['id']])->setField(['oa_associated' => $oa_val]);
                }
            }
        }

        // dump($map);die();
        //为数据权限添加
        setPowerPromoteIds($map, 'id');
        $list_data = D(self::model_name)->where($map)->order('id DESC')->page($p, $row)->select();
        
        $oa_data = [];
        if (I('oa_associated', -1) == -1) {
            foreach ($list_data as $k => $v) {
                // $list_data[$k]['account'] = trim($v['account']);
                // if($v['oa_associated'] != 1) {
                $oa_data[] = trim($v['account']);
                // }
            }
            if (!empty($oa_data)) {
                $arr['time'] = time();
                $arr['account'] = implode(",", $oa_data);
                ksort($arr);
                reset($arr);
                $sign = md5(http_build_query($arr) . 'wmkjtx_kj213');
                $arr['sign'] = $sign;
                $re_data = curl_post(C('OA.formalUrl') . '/api/wanmeng/verifyBind', $arr);
                $re_data = json_decode($re_data, true)['data'];
                foreach ($list_data as $k => $v) {
                    $oa_val = $re_data[trim($v['account'])];
                    if ($v['oa_associated'] != $oa_val) {
                        $list_data[$k]['oa_associated'] = $oa_val;
                        M('promote', 'tab_')->where(['id' => $v['id']])->setField(['oa_associated' => $oa_val]);
                    }
                }
            }
        }
        $count = D(self::model_name)->where($map)->count();
        $page = set_pagination($count, $row);
        if ($page) {
            $this->assign('_page', $page);
        }
        $this->assign('list_data', $list_data);
        $this->display();
    }

    private function siteApplyList($p)
    {
        if (isset($_REQUEST['promote_id'])) {
            $map['promote_id']=$_REQUEST['promote_id'];
            unset($_REQUEST['promote_id']);
        }
        if (isset($_REQUEST['url_type'])) {
            $map['url_type']=$_REQUEST['url_type'];
            unset($_REQUEST['url_type']);
        }
        if (isset($_REQUEST['status'])) {
            $map['status']=$_REQUEST['status'];
            unset($_REQUEST['status']);
        }
        $this->assign('show_status', 1);

        $this->m_title = '混服申请';
        $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/lists/type/2','status'=>1])->find());

        //为数据权限添加
        setPowerPromoteIds($map);
        parent::lists('SiteApply', $p, $map);
    }

    public function add($account=null, $password=null, $second_pwd=null, $real_name=null, $email=null, $mobile_phone=null, $bank_name=null, $bank_card=null, $admin=null, $status=null, $ba_id = null)
    {
        if (IS_POST) {
            if (C('PROMOTE_AUTO_AUDIT') == 1) {
                $status = 1;
            }
            $data = array('account'=>$account,'password'=>$password,'second_pwd'=>$second_pwd,'real_name'=>$real_name,'email'=>$email,'mobile_phone'=>$mobile_phone,'bank_name'=>$bank_name,'bank_card'=>$bank_card,'admin_id'=>session('user_auth')['uid'],'status'=>$status,'ba_id'=>$ba_id);

            if (preg_match('/^[a-zA-Z0-9]{6,15}$/', $account)==false) {
                $this->error('账号只能是6-15位字母或数字');
            }

            $promoteService = new PromoteService();
            $status = $promoteService->addPromote($data);
            if ($status) {
                /* if(isset($_REQUEST['ba_id'])) {
                    $ba = new \Admin\Model\BusinessAffairsModel();
                    $ba->add_child($_REQUEST['ba_id'],$res);
                } */
                $this->success("添加成功", U('lists'));
            } else {
                $this->error($res);
            }
        } else {
            $this->meta_title ='新增渠道信息';
            $this->m_title = '推广员列表';
            $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/lists/type/1','status'=>1])->find());
            $this->display();
        }
    }

    public function del($model = null, $ids=null)
    {
        $model = M('Model')->getByName(self::model_name);
        /*通过Model名称获取Model完整信息*/
        parent::del($model["id"], $ids);
    }
    //代充删除
    public function agent_del($model = null, $ids=null)
    {
        $model = M('Model')->getByName('Agent');
        /*通过Model名称获取Model完整信息*/
        parent::del($model["id"], $ids);
    }
    public function edit($id=0)
    {
        $id || $this->error('请选择要查看的用户!');
        $model = M('Model')->getByName(self::model_name); /*通过Model名称获取Model完整信息*/
        $data = array();
        if (IS_POST) {
            if (empty(I('post.account'))) {
                $this->error('渠道账号不能为空');
            }
            if (preg_match('/^[a-zA-Z0-9]{6,15}$/', I('post.account'))==false) {
                $this->error('账号只能是6-15位字母或数字');
            }
            $data['account'] = I('post.account');
            $map1['id'] = array('neq',$_POST['id']);
            $map1['account'] = $data['account'];

            $pdata = D('Promote')->where($map1)->find();

            if ($pdata) {
                $this->error('渠道账号已存在');
            }
            empty(I('post.id')) ?  : $data['id'] =I('post.id');
            empty(I('post.password')) ?  : $data['password'] =I('post.password');
            empty(I('post.second_pwd')) ?  : $data['second_pwd'] =I('post.second_pwd');
            empty(I('post.status')) ?  : $data['status'] =I('post.status');
            empty(I('post.child_game_permission')) ?  : $data['child_game_permission'] =I('post.child_game_permission');
            empty(I('post.mark1')) ? : $data['mark1'] =I('post.mark1');
            empty(I('post.mark2')) ? : $data['mark2'] = I('post.mark2');
            $data['ba_id'] = I('ba_id');
            $pwd = trim($_POST['password']);
            $second_pwd = trim($_POST['second_pwd']);
            $use = new UserApi();
            $data['password']=think_ucenter_md5($pwd, UC_AUTH_KEY);
            $data['second_pwd']=think_ucenter_md5($second_pwd, UC_AUTH_KEY);
            if (empty($pwd)) {
                unset($data['password']);
            }
            if (empty($second_pwd)) {
                unset($data['second_pwd']);
            }

            $ba_id = D('Promote')->field("ba_id")->find($id);
            if ($ba_id['ba_id'] != $_REQUEST['ba_id'] && $_REQUEST['ba_id']!='') {
                $ba = new \Admin\Model\BusinessAffairsModel();
                $ba->update_child($ba_id['ba_id'], $_REQUEST['ba_id'], $id);
            }

            $res=M("promote", "tab_")->where(array("id"=>$_POST['id']))->save($data);
            if ($res !== false) {
                $this->success("修改成功", U('lists'));
            } else {
                $this->error("修改失败");
            }
        } else {
            $model = D('Promote');
            $data = $model->find($id);
            $data['bank_area']=explode(',', $data['bank_area']);
            $idcardpic = $data["idcarpic"];
            $businesspic = $data['businesspic'];
            $agreementpic = $data["agreementpic"];
            $anothpic = $data["anothpic"];
            if (!empty($idcardpic)) {
                $idcardpicArr = explode(',', $idcardpic);
                foreach ($idcardpicArr as $key => $value) {
                    $idcardImg[$key] = get_cover($value, 'path');
                }
            }
            if (!empty($businesspic)) {
                $businesspicArr = explode(',', $businesspic);
                foreach ($businesspicArr as $key => $value1) {
                    $businesspicImg[$key] = get_cover($value1, 'path');
                }
            }
            if (!empty($agreementpic)) {
                $agreementpicArr = explode(',', $agreementpic);
                foreach ($agreementpicArr as $key => $value2) {
                    $agreementpicImg[$key] = get_cover($value2, 'path');
                }
            }
            if (!empty($anothpic)) {
                $anothpicArr = explode(',', $anothpic);
                foreach ($anothpicArr as $key => $value3) {
                    $anothpicImg[$key] = get_cover($value3, 'path');
                }
            }
            $this->assign("agreementpicimg", $agreementpicImg);
            $this->assign('businesspicImg', $businesspicImg);
            $this->assign('idcardimg', $idcardImg);
            $this->assign('anothpicimg', $anothpicImg);
            $this->assign('data', $data);
            $this->meta_title ='编辑渠道信息';

            $this->m_title = '推广员列表';
            $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/lists/type/1','status'=>1])->find());


            $this->display();
        }
    }
    //设置状态
    public function set_status($model='Promote')
    {
        if (empty($_REQUEST['ids'])) {
            $this->error('请选择要操作的数据');
        }
        if (isset($_REQUEST['model'])) {
            $model=$_REQUEST['model'];
            unset($_REQUEST['model']);
        }
        $a=0;
        $map['id']=array('in',$_REQUEST['ids']);
        $set=M('promote', 'tab_')->where($map)->setField('status', $_REQUEST['status']);
        if ($set) {
            if ($_REQUEST['status']==1) {
                $select=M('promote', 'tab_')->where($map)->select();
                foreach ($select as $key => $value) {
                    if ($count=="000000") {
                        $a++;
                    }
                }
                $this->success('操作成功');/**,已通知'.$a.'人'*/
            } else {
                $this->success('操作成功');
            }
        } else {
            $this->success('操作失败');
        }
    }
    
    /**
    *资质审核
    */
    public function idcar_status($model='Promote')
    {
        if (empty($_REQUEST['ids'])) {
            $this->error('请选择要操作的数据');
        }
        if (isset($_REQUEST['model'])) {
            $model=$_REQUEST['model'];
            unset($_REQUEST['model']);
        }
        $a=0;
        $map['id']=array('in',$_REQUEST['ids']);
        $set = M('promote', 'tab_')->where($map)->setField('ver_status', $_REQUEST['status']);
        if ($set) {
            if ($_REQUEST['status']==1) {
                $select=M('promote', 'tab_')->where($map)->select();
                foreach ($select as $key => $value) {
                    if ($count=="000000") {
                        $a++;
                    }
                }
                $this->success('操作成功');/**,已通知'.$a.'人'*/
            } else {
                $this->success('操作成功');
            }
        } else {
            $set=M('promote', 'tab_')->where($map)->setField('ver_status', 2);
            $this->success('操作失败');
        }
    }

    /**
    *短信发送
    */
    public function send_sms($phone)
    {
        /// 产生手机安全码并发送到手机且存到session
        $rand = rand(100000, 999999);
        $xigu = new Xigu(C('sms_set.smtp'));
        $param = $rand.",".'1';
        $result = json_decode($xigu->sendSM(C('sms_set.smtp_account'), $phone, C('sms_set.smtp_notice_port'), $param), true);
        $result['create_time'] = time();
        #TODO 短信验证数据

        return$result['send_status']; // '000000'
    }


    //设置对账状态yyh
    public function set_check_status($model='Promote')
    {
        if (isset($_REQUEST['model'])) {
            $model=$_REQUEST['model'];
            unset($_REQUEST['model']);
        }
        parent::set_status($model);
    }
    /**
    *渠道注册列表
    */
    public function ch_reg_list()
    {
        if (isset($_REQUEST['game_name'])) {
            if ($_REQUEST['game_name']=='全部') {
                unset($_REQUEST['game_name']);
            } else {
                $map['fgame_name']=$_REQUEST['game_name'];
                unset($_REQUEST['game_name']);
            }
        }
        $map['tab_user.promote_id'] = array("neq",0);
        if (isset($_REQUEST['promote_name'])) {
            if ($_REQUEST['promote_name']=='全部') {
                unset($_REQUEST['promote_name']);
            } elseif ($_REQUEST['promote_name']=='自然注册') {
                $map['tab_user.promote_id']=array("elt",0);
                unset($_REQUEST['promote_name']);
            } else {
                $promoteid = get_promote_id($_REQUEST['promote_name']);
                $map['tab_user.promote_id']=array('eq',get_promote_id($_REQUEST['promote_name']));
                unset($_REQUEST['promote_name']);

                if (isset($_REQUEST['parent_id'])) {
                    $parent_id = get_promote_id($_REQUEST['parent_id']);
                    if ($promoteid == $parent_id) {
                        $map['tab_user.promote_id'] = $promoteid;
                    } else {
                        $parent_id = get_promote_id($_REQUEST['parent_id']);
                    }
                } else {
                    $map['tab_user.promote_id'] = $promoteid;
                }
            }
        } else {
            if (isset($_REQUEST['parent_id'])) {
                $parent_id = get_promote_id($_REQUEST['parent_id']);
                $pro = M('promote', 'tab_')->field('id,account')->where("chain like '%/{$parent_id}/%'")->select();
                $pro_ids = array_column($pro, 'id');
                $pro_ids[] = get_promote_id($_REQUEST['parent_id']);
                if (!empty($pro_ids)) {
                    $map['tab_user.promote_id'] = ['in',$pro_ids];
                } else {
                    $map['tab_user.promote_id'] = array('eq',-1);
                }
            }
        }
        if (isset($_REQUEST['ba_id'])) {
            $map['ba_id'] = $_REQUEST['ba_id'];
        }
        if (isset($_REQUEST['is_check'])&&$_REQUEST['is_check']!="请选择") {
            $map['is_check']=$_REQUEST['is_check'];
            unset($_REQUEST['is_check']);
        }
        if (isset($_REQUEST['account'])) {
            $map['tab_user.account']=array('like','%'.$_REQUEST['account'].'%');
            unset($_REQUEST['account']);
        }
        if (isset($_REQUEST['time-start'])&&isset($_REQUEST['time-end'])) {
            $map['register_time']=array('BETWEEN',array(strtotime($_REQUEST['time-start']),strtotime($_REQUEST['time-end'])+24*60*60-1));
            unset($_REQUEST['time-start']);
            unset($_REQUEST['time_end']);
        } elseif (isset($_REQUEST['time-start'])) {
            $map['register_time'] = ['GT',strtotime(I('time-start'))];
            unset($_REQUEST['time-start']);
        } elseif (isset($_REQUEST['time-end'])) {
            $map['register_time'] = ['LT',strtotime(I('time-end'))+86399];
            unset($_REQUEST['time-end']);
        }
        if (isset($_REQUEST['start'])&&isset($_REQUEST['end'])) {
            $map['register_time']=array('BETWEEN',array(strtotime($_REQUEST['start']),strtotime($_REQUEST['end'])+24*60*60-1));
            unset($_REQUEST['start']);
            unset($_REQUEST['end']);
        } elseif (isset($_REQUEST['start'])) {
            $map['register_time'] = ['GT',strtotime(I('start'))];
            unset($_REQUEST['start']);
        } elseif (isset($_REQUEST['end'])) {
            $map['register_time'] = ['LT',strtotime(I('end'))+86399];
            unset($_REQUEST['end']);
        }
        $map['puid'] = 0;
        //为数据权限添加
        setPowerPromoteIds($map);
        $model = array(
            'm_name' => 'User',
            'join'   => 'tab_promote ON tab_user.promote_id = tab_promote.id',
            'fields' => array(
                                'tab_user.id',
                                'tab_user.account',
                                'tab_user.fgame_name',
                                'tab_user.nickname',
                                'tab_user.email',
                                'tab_user.phone',
                                'promote_id',
                                'tab_user.parent_id',
                                'tab_user.register_time',
                                'tab_user.register_way',
                                'tab_user.register_ip',
                                'promote_account',
                                'tab_user.parent_name',
                                'is_check',
                                'tab_promote.ba_id'
                            ),
            'key'    => array('tab_user.account','tab_game.fgame_name'),
            'map'    => $map,
            'order'  => 'register_time desc',
            'title'  => '渠道注册',
            'template_list' =>'ch_reg_list',
        );
        $map1 = array('tab_user.promote_id'=>array('neq',0),'puid'=>0);
        $map2['register_time'] = total(1, false);
        $map3['register_time'] = total(5, false);
        //为数据权限添加
        setPowerPromoteIds($map1);
        setPowerPromoteIds($map2);
        setPowerPromoteIds($map3);
        $total = D($model['m_name'])->join('tab_promote ON tab_user.promote_id = tab_promote.id')->where($map1)->count();
        $ttotal=D($model['m_name'])->join('tab_promote ON tab_user.promote_id = tab_promote.id')->where($map2)->where(array('tab_user.promote_id'=>array('neq',0),'puid'=>0))->count();
        $ytotal=D($model['m_name'])->join('tab_promote ON tab_user.promote_id = tab_promote.id')->where($map3)->where(array('tab_user.promote_id'=>array('neq',0),'puid'=>0))->count();
        $this->assign('total', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);
        $user = A('User', 'Event');

        $this->m_title = '实时注册';
        $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/ch_reg_list','status'=>1])->find());


        $user->user_join_v1($model, $_GET['p']);
    }

    /**
    *渠道充值
    */
    public function spend_list()
    {
        if (isset($_REQUEST['game_name'])) {
            if ($_REQUEST['game_name']=='全部') {
                unset($_REQUEST['game_name']);
            } else {
                $map['game_name']=$_REQUEST['game_name'];
                unset($_REQUEST['game_name']);
            }
        }
        if (!empty($_REQUEST['server_id'])) {
            $map['server_name']=$_REQUEST['server_id'];
            unset($_REQUEST['server_id']);
        }
        if (!empty($_REQUEST['pay_order_number'])) {
            $map['pay_order_number']=array('like','%'.$_REQUEST['pay_order_number'].'%');
            unset($_REQUEST['pay_order_number']);
        }


        if (isset($_REQUEST['pay_way'])) {
            $map['pay_way'] = get_pay_way_map($_REQUEST['pay_way']);
            unset($_REQUEST['pay_way']);
        }

        if (isset($_REQUEST['user_account'])) {
            $map['user_account']=array('like','%'.$_REQUEST['user_account'].'%');
            unset($_REQUEST['user_account']);
        }
        if (isset($_REQUEST['spend_ip'])) {
            $map['spend_ip']=array('like','%'.$_REQUEST['spend_ip'].'%');
            unset($_REQUEST['spend_ip']);
        }

        if (isset($_REQUEST['timeStart'])&&isset($_REQUEST['timeEnd'])) {
            $map['pay_time']=array('BETWEEN',array(strtotime($_REQUEST['timeStart']),strtotime($_REQUEST['timeEnd'])+24*60*60-1));
            unset($_REQUEST['timeStart']);
            unset($_REQUEST['timeEnd']);
        } elseif (isset($_REQUEST['timeStart'])) {
            $map['pay_time'] = ['GT',strtotime(I('timeStart'))];
            unset($_REQUEST['timeStart']);
        } elseif (isset($_REQUEST['timeEnd'])) {
            $map['pay_time'] = ['LT',strtotime(I('timeEnd'))+86399];
            unset($_REQUEST['timeEnd']);
        }
        if (isset($_REQUEST['start'])&&isset($_REQUEST['end'])) {
            $map['pay_time']=array('BETWEEN',array(strtotime($_REQUEST['start']),strtotime($_REQUEST['end'])+24*60*60-1));
            unset($_REQUEST['start']);
            unset($_REQUEST['end']);
        } elseif (isset($_REQUEST['start'])) {
            $map['pay_time'] = ['GT',strtotime(I('start'))];
            unset($_REQUEST['start']);
        } elseif (isset($_REQUEST['end'])) {
            $map['pay_time'] = ['LT',strtotime(I('end'))+86399];
            unset($_REQUEST['end']);
        }

        if (isset($_REQUEST['promote_name'])) {
            if ($_REQUEST['promote_name']=='全部') {
                unset($_REQUEST['promote_name']);
            } elseif ($_REQUEST['promote_name']=='自然注册') {
                $map['promote_id']=array("lte",0);
                unset($_REQUEST['promote_name']);
            } else {
                $map['promote_id']=get_promote_id($_REQUEST['promote_name']);
                unset($_REQUEST['promote_name']);
                if (!empty(I('parent_id')) && $map['promote_id']) {
                    if (I('parent_id') == $map['promote_id']) {
                    } else {
                        $pro = M('promote', 'tab_')->field('id')->where("chain like '%/{$_REQUEST['parent_id']}/%' or id={$_REQUEST['parent_id']}")->select();

                        if (!$pro) {
                            $map['promote_id'] = array('eq',999999999);
                        }
                    }
                } else {
                }
            }
        } else {
            if (!empty(I('parent_id'))) {
                $pro = M('promote', 'tab_')->field('id')->where("chain like '%/{$_REQUEST['parent_id']}/%'")->select();
                $pro_ids = array_column($pro, 'id');
                $pro_ids[] = I('parent_id');
                if (!empty($pro_ids)) {
                    $map['promote_id'] = ['in',$pro_ids];
                } else {
                    $map['promote_id'] = array('eq',999999999);
                }
            } else {
                $map['promote_id']=array("gt",0);
            }
        }


        if (isset($_REQUEST['ba_id'])) {
            $all_promote_id = array_column(get_admin_promotes($_REQUEST['ba_id'], 'ba_id'), 'id');
            if (empty($all_promote_id)) {
                $all_promote_id[]=-1;
            }

            $map['promote_id']=array($map['promote_id'],array('in',implode(',', $all_promote_id)),'and');
        }

        //为数据权限添加
        setPowerPromoteIds($map);
//        dd($map);
        $model = array(
            'm_name' => 'Spend',
            'map'    => $map,
            'order'  => 'id desc',
            'title'  => '渠道充值',
            'template_list' =>'spend_list',
        );
        $map1 = $map;
        $map1['pay_status']=1;

        $map2 = [
          'pay_status' => 1,
          'promote_id' => ["gt", 0],
        ];
        //为数据权限添加
        setPowerPromoteIds($map2);
        $total = null_to_0(D('Spend')->where($map1)->sum('pay_amount'));
        $ttotal = null_to_0(D('Spend')->where('pay_time'.total(1))->where($map2)->sum('pay_amount'));
        $ytotal = null_to_0(D('Spend')->where('pay_time'.total(5))->where($map2)->sum('pay_amount'));

        $this->assign('total', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);
        $user = A('Spend', 'Event');

        $this->m_title = '实时充值';
        $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/spend_list','status'=>1])->find());


        $user->list_($model, $_GET['p']);
    }

    /**
    *代充记录
    */
    public function agent_list()
    {
        $map['promote_id'] = array("neq",0);
        if (isset($_REQUEST['user_account'])) {
            $map['user_account']=array('like','%'.$_REQUEST['user_account'].'%');
            unset($_REQUEST['user_account']);
        }
        if (isset($_REQUEST['pay_status'])) {
            $map['pay_status']=$_REQUEST['pay_status'];
            unset($_REQUEST['pay_status']);
        }
        if (isset($_REQUEST['promote_name'])) {
            if ($_REQUEST['promote_name']=='全部') {
                unset($_REQUEST['promote_name']);
            } elseif ($_REQUEST['promote_name']=='自然注册') {
                $map['promote_id']=array("elt",0);
                unset($_REQUEST['promote_name']);
            } else {
                $map['promote_id']=get_promote_id($_REQUEST['promote_name']);
                unset($_REQUEST['promote_name']);
                unset($_REQUEST['promote_id']);
            }
        }
        if (isset($_REQUEST['time-start'])&&isset($_REQUEST['time-end'])) {
            $map['create_time']=array('BETWEEN',array(strtotime($_REQUEST['time-start']),strtotime($_REQUEST['time-end'])+24*60*60-1));
            unset($_REQUEST['time-start']);
            unset($_REQUEST['time_end']);
        } elseif (isset($_REQUEST['time-start'])) {
            $map['create_time']=array('BETWEEN',array(strtotime($_REQUEST['time-start']),time()));
            unset($_REQUEST['time-start']);
            unset($_REQUEST['time_end']);
        } elseif (isset($_REQUEST['time-end'])) {
            $map['create_time']=array('BETWEEN',array(0,strtotime($_REQUEST['time-end'])+24*60*60-1));
            unset($_REQUEST['time-start']);
            unset($_REQUEST['time_end']);
        }
        if (isset($_REQUEST['start'])&&isset($_REQUEST['end'])) {
            $map['create_time']=array('BETWEEN',array(strtotime($_REQUEST['start']),strtotime($_REQUEST['end'])+24*60*60-1));
            unset($_REQUEST['start']);
            unset($_REQUEST['end']);
        }
        if (isset($_REQUEST['game_name'])) {
            if ($_REQUEST['game_name']=='全部') {
                unset($_REQUEST['game_name']);
            } else {
                $map['game_name']=$_REQUEST['game_name'];
                unset($_REQUEST['game_name']);
            }
        }
        empty(I('promote_id')) || $map['promote_id'] = I('promote_id');
        $map['pay_status'] = 1;

        //为数据权限添加
        setPowerPromoteIds($map);
        $map1 = $map;
        $map1['pay_status'] = 1;

        $map2 = array('pay_status'=>1);
        setPowerPromoteIds($map2);
        $total = D('Agent')->field('sum(amount) amount,sum(real_amount) real_amount')->where($map1)->find();
        $ttotal = D('Agent')->field('sum(amount) amount,sum(real_amount) real_amount')->where('create_time'.total(1))->where($map2)->find();
        $ytotal = D('Agent')->field('sum(amount) amount,sum(real_amount) real_amount')->where('create_time'.total(5))->where($map2)->find();
        $this->assign('total', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);

        $this->m_title = '会长代充记录';
        $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/agent_list','status'=>1])->find());


        parent::order_lists('Agent', $_GET["p"], $map);
    }
    /**
    *代充额度
    */
    public function pay_limit()
    {
        if (isset($_REQUEST['account'])) {
            if ($_REQUEST['account']=='全部') {
                unset($_REQUEST['account']);
            }
            $map['account']=array('like','%'.$_REQUEST['account'].'%');
            unset($_REQUEST['account']);
        }
        $row=10;
        $map['pay_limit']=array('gt','0');
        $page = intval($_GET['p']);
        $page = $page ? $page : 1; //默认显示第一页数据
        $arraypage=$page;
        $model=D('Promote');
        $data=$model
        ->field('id,account,pay_limit,set_pay_time,pay_limit_game')
        ->where($map)
        ->select();

        $count=count($data);
        if ($count > $row) {
            $page = new \Think\Page($count, $row);
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
            $this->assign('_page', $page->show());
        }
        if ($_REQUEST['data_order']!='') {
            $data_order=reset(explode(',', $_REQUEST['data_order']));
            $data_order_type=end(explode(',', $_REQUEST['data_order']));
            $this->assign('userarpu_order', $data_order);
            $this->assign('userarpu_order_type', $data_order_type);
        }
        $data=my_sort($data, $data_order_type, (int)$data_order);
        $size=$row;//每页显示的记录数
        $pnum = ceil(count($data) / $size); //总页数,ceil()函数用于求大于数字的最小整数
        //用array_slice(array,offset,length) 函数在数组中根据条件取出一段值;array(数组),offset(元素的开始位置),length(组的长度)
        $data = array_slice($data, ($arraypage-1)*$size, $size);
        $this->assign('list_data', $data);
        $this->meta_title ='代充额度';
        $this->display();
    }

    public function pay_limit_add()
    {
        $limit=D("Promote");
        if (IS_POST) {
            if (trim($_REQUEST['promote_id'])=='') {
                $this->error("请选择推广员账号");
            }
            $preg=trim($_REQUEST['limits']);
            if ($preg=='') {
                $this->error("请输入代充额度");
            }
            if (!preg_match('/^[1-9]\d*$/', $preg)) {
                $this->error("请输入大于0的整数");
            }
            $data['id']=$_REQUEST['promote_id'];
            $data['pay_limit']=$preg;
            $find=$limit->where(array("id"=>$data['id']))->find();
            if ($find['pay_limit']!=0&&$find['set_pay_time']!=null) {
                $this->error("已经设置过该渠道", U('pay_limit'));
            } else {
                $limit->where(array("id"=>$data['id']))->setField('pay_limit', $preg);
                $limit->where(array("id"=>$data['id']))->setField('set_pay_time', time());
                $limit->where(array("id"=>$data['id']))->setField('pay_limit_game', $_REQUEST['pay_limit_game']);
                $this->success("添加成功!", U('pay_limit'));
            }
        } else {
            $this->meta_title ='新增代充额度';
            $this->display();
        }
    }
    public function pay_limit_del()
    {
        $limit=D("Promote");
        if (empty($_REQUEST['ids'])) {
            $this->error('请选择要操作的数据');
        }
        if (isset($_REQUEST['ids'])) {
            $id=$_REQUEST['ids'];
        }
        if (is_array($id)) {
            $map['id']=array('in',$id);
        } else {
            $map['id']=$id;
        }
        $limit
         ->where($map)
         ->setField('pay_limit', '0');
        $this->success("删除成功!", U('pay_limit'));
    }
    public function pay_limit_edit()
    {
        $limit=D("Promote");
        if (IS_POST) {
            if (trim($_REQUEST['promote_id'])=='') {
                $this->error("请选择管理员推广员");
            }
            $preg=trim($_REQUEST['limits']);
            if ($preg=='') {
                $this->error("请输入代充额度");
            }
            if (!preg_match('/^[1-9]\d*$/', $preg)) {
                $this->error("请输入大于0的整数");
            }
            $data['id']=$_REQUEST['promote_id'];
            $edit=$limit->where(array("id"=>$data['id']))->setField('pay_limit', $preg);
            $limit->where(array("id"=>$data['id']))->setField('set_pay_time', time());
            $limit->where(array("id"=>$data['id']))->setField('pay_limit_game', $_REQUEST['pay_limit_game']);
            if ($edit===false) {
                $this->error('数据未更改');
            } else {
                $this->success("编辑成功!", U('pay_limit'));
            }
        } else {
            $edit_data=$limit
            ->where(array('id'=>$_REQUEST['ids']))
            ->find();
            $this->assign('edit_data', $edit_data);
            $this->meta_title ='编辑代充额度';
            $this->display();
        }
    }

    /**
    *删除混服申请数据
    */
    public function delSiteApply()
    {
        $ids = array_unique((array)I('post.ids', 0));
        if (empty($ids)) {
            $this->error('请选择要操作的数据!');
        }
        $model = D('SiteApply');
        $map['id']=array("in",$ids);
        if ($model->where($map)->delete()) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败!');
        }
    }

    /**
    *审核混服申请数据
    */
    public function checkSiteApply($ids=null)
    {
        $ids = array_unique((array)I('post.ids', 0));
        if (empty($ids)) {
            $this->error('请选择要操作的数据!');
        }
        $model = D('SiteApply');
        $map['id']=array("in",$ids);
        if ($model->where($map)->setField(['status'=>1])) {
            $this->success('审核成功');
        } else {
            $this->error('审核失败!');
        }
    }

    public function set_config_auto_audit($val='', $config_key='')
    {
        $config['value'] = $val;
        $res = M('config')->where(array('name'=>$config_key))->save($config);
        S('DB_CONFIG_DATA', null);
        if ($res !== false) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    public function del_promote()
    {
        if (IS_AJAX) {
            M()->startTrans();
            $result = M('promote', 'tab_')->where("chain like '%/{$_POST['id']}/%' or id={$_POST['id']} ")->delete();
            if ($result) {
                M()->commit();
                $this->ajaxReturn(array('status'=>1,'msg'=>'删除成功'));
            } else {
                M()->rollback();
                $this->ajaxReturn(array('status'=>0,'msg'=>'删除失败'));
            }
        }
    }

    //获取推广员可推广游戏
    public function getPromoteGame()
    {
        if (IS_AJAX) {
            //获取所有游戏
            $game_list = M('game', 'tab_')->field('id,game_name,short')->where(['game_status'=>1,'down_port'=>1])->select();
            $data['data']['game_list'] = empty($game_list) ? '' : $game_list;
            //获取推广员信息
            $promote_info = M('promote', 'tab_')->field('id,account,game_ids')->where(['id'=>I('id', 0, 'intval')])->find();
            if (!empty($promote_info['game_ids'])) {
                $promote_info['game_ids'] = explode(',', $promote_info['game_ids']);
            }
            $data['data']['promote_info'] = empty($promote_info) ? '' : $promote_info;

            $data['msg'] = '请求成功';
            $data['code'] = 1;

            $this->ajaxReturn($data);
            exit;
        }
    }


    //更新推广员可推广游戏
    public function savePromoteGame()
    {
        if (IS_AJAX) {
            $id = I('promote_id', 0, 'intval');
            if (empty($id)) {
                $this->ajaxReturn(['code'=>0,'msg'=>'请选择推广员']);
            }
            $game_ids = I('game_ids', '');
            if (!empty($game_ids)) {
                $game_ids = implode(',', $game_ids);
            } else {
                $game_ids = 0;
            }
            $res = M('promote', 'tab_')->where(['id'=>$id])->save(['game_ids'=>$game_ids]);
            if ($res) {
                $this->ajaxReturn(['code'=>1,'msg'=>'更新成功']);
            } else {
                $this->ajaxReturn(['code'=>0,'msg'=>'数据未发生变化']);
            }
        }
    }

    public function shortCutMenu($p = 1)
    {
        $page = intval($p);
        $page = $page ? $page : 1; //默认显示第一页数据
        $row=10;

        $this->meta_title = '快捷菜单管理';
        $this->m_title = '站点设置(推广员后台)';

        $list = M("quick_menu", "tab_")->page($page, $row)->select();

        $count = M("quick_menu", "tab_")->count();

        $page = set_pagination($count, $row);
        if ($page) {
            $this->assign('_page', $page);
        }

        $this->assign('list', $list);
        $this->display();
    }

    public function shortCutMenuEdit()
    {
        $id = I("id");
        $where['id'] = $id;

        $data = M("quick_menu", "tab_")->where($where)->find();

        $this->assign("data", $data);
        $this->meta_title = '快捷菜单管理编辑';
        $this->m_title = '站点设置(推广员后台)';
        $this->display();
    }

    public function shortCutMenuSave()
    {
        $where['id'] = I("id");
        $save['icon'] = I("icon");
        $save['name'] = I("name");

        M('quick_menu', 'tab_')->startTrans();  //事物
        try {
            M('quick_menu', 'tab_')->where($where)->save($save);
        } catch (Exception $e) {
            M('quick_menu', 'tab_')->rollback();//回滚
        }
        M('quick_menu', 'tab_')->commit();    //提交事物

        $this->success('保存成功', U("promote/shortCutMenu"));
    }
}