<?php
namespace Admin\Controller;

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

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

    public function lists($p=1)
    {

        $this->checkListOrCountAuthRestMap($map,[]);

        $show_data_power = (is_administrator()|| session('user_auth')['show_data']);
        $this->assign('show_data_power', $show_data_power);
        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['p.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'], null);
//                dd($zid);
                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['p.id'] = $promoteid;
                    }else{
                        $map['p.id'] = 0;
                    }
                }else{
                    $map['p.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['p.status'] = I('status');
        }

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

        if (I("promote_level")) {
            $map['p.level'] = I("promote_level");
        }
        if (strlen(I('company_belong'))) {
            $map['p.company_belong'] = I("company_belong");
        }

        if (!is_null(I('admin_uid', null))) {
            $map['p.admin_id'] = I('admin_uid');
        }

        $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 = [];
                $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 (!empty($re_data['data'])) {
                    $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]);
                }
            }
        }


        //为数据权限添加
        setPowerPromoteIds($map, 'p.id');
        $list_data = D(self::model_name)
                    ->alias("p")
                    ->field("p.*,IFNULL(m.nickname,'无') admin_nickname,IFNULL(b.account,'暂无') b_account,IFNULL(if(substring_index(substring_index(p.`chain`,'/',2),'/',-1)='',p.id,substring_index(substring_index(p.`chain`,'/',2),'/',-1)),0) top_id")
                    ->join("sys_member m on p.admin_id = m.uid","left")
                    ->join("tab_business_affairs b on p.ba_id = b.id","left")
                    ->where($map)->order('id DESC');

        if(isset($_REQUEST['export'])){
            $list_data = $list_data->select(false);
        }else{
            $list_data =  $list_data->page($p, $row)->select(false);
        }
        
        $list_data = M()->table("(".$list_data.") a")->field("a.*,pr.account top_account")->join("tab_promote pr on a.top_id = pr.id")->select();
        $list_data = D(self::model_name)->parseListData($list_data);
        $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]);
                    }
                }
            }
        }
        //导出
        if(isset($_REQUEST['export'])){

            $GetData = $_GET;
            unset($GetData['export']);
            addOperationLog(['op_type'=>3,'key'=>getNowDate(),'url'=>U(CONTROLLER_NAME.'/'.ACTION_NAME,$GetData),'menu'=>"推广员-推广员管理-推广员列表-导出"]);

            data2csv($list_data,'推广员列表',array(
                "id"=>"推广员ID",
                "account"=>"推广员账号",
                "mobile_phone"=>"手机号码",
                "balance_coin"=>"平台币余额",
                "pay_amount"=>"总流水",
                "create_time"=>"注册时间",
                "last_login_time"=>"最后登录时间",
                "level_name"=>"渠道类型",
                "top_account"=>"所属会长",
                "company_belong_str"=>"公会归属",
                "company_relation_str"=>"公会关系",
                "admin_nickname"=>"归属管理员",
                "b_account"=>"商务专员",
                "status_str"=>"状态",
                "ver_status"=>"身份状态",
                "oa_associated_str"=>"oa关联"
            ));
        }
        $count = D(self::model_name)->alias("p")->where($map)->count();
        $page = set_pagination($count, $row);
        if ($page) {
            $this->assign('_page', $page);
        }
        $admins = M('member')->field('uid,nickname')->select();
        $this->assign('admins', $admins);
        $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);
    }

    private function accountExist($account, $id = null)
    {
        $res = M('promote', 'tab_')->where(['account' => $account])->field('id')->find();
        if ($res) {
           return $id != $res['id'];
        } else {
           return false;
        }
    }

    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, $company_id = null,
                        $withdraw_show = null,$withdraw_done = null,$can_view_recharge = null)
    {
        if (IS_POST) {
            if (C('PROMOTE_AUTO_AUDIT') == 1) {
                $status = 1;
            }
            if ($this->accountExist($account)) {
                $this->error('该账号已存在');
            }
            if(!empty($mobile_phone)){
                //判断手机格式
                if (!preg_match("/^1[3456789]{1}\d{9}$/", $mobile_phone)) {
                    $this->error('手机格式错误');
                }
                $res = M('promote', 'tab_')->where(['mobile_phone' => $mobile_phone])->field('id')->find();
                if ($res) {
                    $this->error('该手机号已存在');
                }
            }
            $company_belong = $_REQUEST['company_belong'] ?? 0;
            $company_relation = $_REQUEST['company_relation'] ?? 0;
            if($company_id && $company_id > 0){
                //新增跟随系统
                $company_info = M("PromoteCompany","tab_")->field("company_belong,develop_type")->where("id = {$company_id}")->find(); 
                $company_belong = $company_info['company_belong'];
                $company_relation = $company_info['develop_type'];
            }
            $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,
                'company_id' => $company_id,
                'company_belong' => $company_belong,
                'company_relation' => $company_relation,
                'withdraw_show'=>$withdraw_show,
                'withdraw_done'=>$withdraw_done,
                'can_view_recharge'=>$can_view_recharge
            );

            if (preg_match('/^[a-zA-Z0-9]{6,15}$/', $account)==false) {
                $this->error('账号只能是6-15位字母或数字');
            }
            if ($company_id < 0) {
                $this->error('请选择推广公司');
            }
            $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);
                } */

                addOperationLog(['op_type'=>0,'key'=>$account,'op_name'=>'新增推广员','url'=>U('Promote/lists'),'menu'=>'推广员-推广员管理-推广员列表-新增推广员']);

                session('user_auth_promote_ids', null);
                $this->success("添加成功", U('lists'));
            } else {
                $this->error('添加失败');
            }
        } else {
            $this->meta_title ='新增渠道信息';
            $this->m_title = '推广员列表';
            $companys = M('promote_company', 'tab_')->where(['status' => 1])->select();
            $this->assign('companys', $companys);
            $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 getWithdrawDone() {

        $company_id = I('company_id');
        $promote_id = I('promote_id');

        $map = [];
        if (!$company_id) {
            $this->ajaxReturn(['status'=>0]);
        } else {
            $map['company_id'] = $company_id;
        }

        if ($promote_id){
            $map['id'] = ['neq',$promote_id];
        }

        $withdraw_done = D('Promote')
            ->field("sum(withdraw_done) withdraw_done")
            ->where($map)
            ->find();

        if ($withdraw_done['withdraw_done']>0) {
            $this->ajaxReturn(['status'=>1]);
        } else {
            $this->ajaxReturn(['status'=>0]);
        }
    }

    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位字母或数字');
            }
            $promote = M("promote", "tab_")
                ->where(array("id" => $_POST['id']))
                ->field('id, level, company_belong, company_relation, company_id')
                ->find();
            $data['account'] = I('post.account');
            if ($this->accountExist($data['account'], $_POST['id'])) {
                $this->error('该账号已存在');
            }
            $company_id = I('company_id');
            if ($company_id <0 && $promote['level'] ==1) {
                $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);
            $data['email'] = I('post.email');
            $data['withdraw_show'] = $_POST['withdraw_show'];
            $data['withdraw_done'] = $_POST['withdraw_done'];
            $data['can_view_recharge'] = $_POST['can_view_recharge'];

            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);
            }

            if ($promote['level'] ==1) {//如果是会长才能修改的选项
                if (!is_null($company_id)) {
                    $data['company_id'] = $company_id;//推广公司
                    if($company_id == 0){
                        $data['company_belong'] = 0;
                    }else{
                        $data['company_belong'] = M("PromoteCompany","tab_")->field("company_belong")->where("id = {$company_id}")->find()['company_belong'];
                    }
                }
                // $data['company_relation'] = I('company_relation');//工会关系
            }
            $settlementType = intval(I('settlement_type', 1));
            if (!empty(I('settlement_type')) && in_array($settlementType, [1, 2])) {
                $data['settlement_type'] = $settlementType;
            }

            M("promote", "tab_")->where(["company_id"=>$company_id])->save(['withdraw_done'=>0]);
//            echo  M("promote", "tab_")->_sql();die();
            $res = M("promote", "tab_")->where(array("id"=>$_POST['id']))->save($data);
            if ($res !== false) {
                if ($promote['level'] == 1) {//修改会长底下推广员的推广公司
                    $array = array();
                    if ($promote['company_id'] != $company_id) {
                        //内外团关系也要跟着公司走
                        if($company_id == 0){
                            $array['company_belong'] = 0;
                        }else{
                            $array['company_belong'] = M("PromoteCompany","tab_")->field("company_belong")->where("id = {$company_id}")->find()['company_belong'];
                        }
                        $array['company_id'] = I('company_id');
                    }
//                    if ($promote['company_belong'] != I('company_belong')) {
//                        $array['company_belong'] = I('company_belong');
//                    }
//                    if ($promote['company_relation'] != I('company_relation')) {
//                        $array['company_relation'] = I('company_relation');
//                    }
                    if ($array) {
                        $res = M("promote", "tab_")->where("chain like '%/{$_POST['id']}/%'")->save($array);
                    }

                }

                addOperationLog(['op_type'=>1,
                    'key'=>$data['account'],
                    'op_name'=>'编辑推广员',
                    'url'=>U('Promote/edit',['id'=>$_POST['id']]),
                    'menu'=>'推广员-推广员管理-推广员列表-编辑推广员']);

                $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());

            $companys = M('promote_company', 'tab_')->where(['status' => 1])->select();
            $this->assign("is_admin",is_administrator());
            $show_data_power = (is_administrator()|| session('user_auth')['show_data']);
            $this->assign('show_data_power', $show_data_power);
            $this->assign('companys', $companys);
            $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']);

//        echo M()->_sql();die();

        if ($set) {
            if ($_REQUEST['status']==1) {
                $select=M('promote', 'tab_')->where($map)->select();
                foreach ($select as $key => $value) {
                    if ($count=="000000") {
                        $a++;
                    }

                    addOperationLog(['op_type'=>1,'key'=>$value['account'],'op_name'=>'编辑审核解锁','url'=>U('Promote/lists'),'menu'=>'推广员-推广员管理-推广员列表-编辑审核解锁']);

                }
                $this->success('操作成功');/**,已通知'.$a.'人'*/
            } else {
                $select=M('promote', 'tab_')->where($map)->select();
                foreach ($select as $key => $value) {

                    addOperationLog(['op_type'=>1,'key'=>$value['account'],'op_name'=>'编辑审核锁定','url'=>U('Promote/lists'),'menu'=>'推广员-推广员管理-推广员列表-编辑审核锁定']);

                }
                $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++;
                    }

                    addOperationLog(['op_type'=>1,'key'=>$value['account'],'op_name'=>'编辑资质审核','url'=>U('Promote/lists'),'menu'=>'推广员-推广员管理-推广员列表-编辑资质审核']);

                }
                $this->success('操作成功');/**,已通知'.$a.'人'*/
            } else {

                $select=M('promote', 'tab_')->where($map)->select();
                foreach ($select as $key => $value) {

                    addOperationLog(['op_type'=>1,'key'=>$value['account'],'op_name'=>'编辑拒绝身份通过','url'=>U('Promote/lists'),'menu'=>'推广员-推广员管理-推广员列表-编辑拒绝身份通过']);

                }

                $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->checkListOrCountAuthRestMap($map,[]);

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

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

    /**
    *渠道充值
    */
    public function spend_list()
    {
        if(!array_key_exists("timeStart",$_REQUEST)){
            $this->redirect(ACTION_NAME, array('timeStart' => date('Y-m-d',strtotime('-30 day')),"timeEnd"=>date('Y-m-d')));
        }
        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 use index(promote_time)',
            '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(M('Spend use index(promote_time)',"tab_")->where($map1)->sum('pay_amount'));//累计充值
        $ttotal = null_to_0(M('Spend use index(promote_time)',"tab_")->where(['pay_time' => total(1, false)])->where($map2)->sum('pay_amount'));//昨日充值
        $ytotal = null_to_0(M('Spend use index(promote_time)',"tab_")->where(['pay_time' => total(5, false)])->where($map2)->sum('pay_amount'));//今日充值
//         dd($total,$ttotal,$ytotal);
        $this->assign('total', $total);
        $this->assign('ttotal', $ttotal);
        $this->assign('ytotal', $ytotal);
        $user = A('Spend', 'Event');

        $this->checkListOrCountAuthRestMap($map,[]);

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

        $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->checkListOrCountAuthRestMap($map,[]);

        $this->m_title = '会长代充记录';
        $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/agent_list','status'=>1])->find());
        $show_data_power = (is_administrator()|| session('user_auth')['show_data']);
        $this->assign('show_data_power', $show_data_power);
        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) {

            if ($val == 0) {
                addOperationLog(['op_type'=>1,'key'=>getNowDate(),'op_name'=>'关闭自动审核','url'=>U('Promote/lists'),'menu'=>'推广员-推广员管理-推广员列表-关闭自动审核']);
            } else if ($val == 1) {
                addOperationLog(['op_type'=>1,'key'=>getNowDate(),'op_name'=>'开启自动审核','url'=>U('Promote/lists'),'menu'=>'推广员-推广员管理-推广员列表-开启自动审核']);
            }

            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }

    public function del_promote()
    {
        if (IS_AJAX) {
            M()->startTrans();

            $data = M('promote', 'tab_')->where("id={$_POST['id']} ")->find();

            $result = M('promote', 'tab_')->where("chain like '%/{$_POST['id']}/%' or id={$_POST['id']} ")->delete();
            if ($result) {
                M()->commit();

                addOperationLog(['op_type'=>2,'key'=>$data['account'],'op_name'=>'删除推广员','url'=>U('Promote/lists'),'menu'=>'推广员-推广员管理-推广员列表-删除推广员']);

                $this->ajaxReturn(array('status'=>1,'msg'=>'删除成功'));
            } else {
                M()->rollback();
                $this->ajaxReturn(array('status'=>0,'msg'=>'删除失败'));
            }
        }
    }

    //获取推广员可推广游戏
    public function getPromoteGame()
    {
        if (IS_AJAX) {
            //获取所有游戏
            $promoteId = I('id', 0, 'intval');
            $promote = M('promote', 'tab_')->field('id,account,game_ids,company_id')->where(['id'=>$promoteId])->find();
            $company = M('promote_company', 'tab_')->field('game_ids')->where(['id' => $promote['company_id']])->find();
            $data = [];
            if (is_null($company)) {
                $games = M('game', 'tab_')
                    ->field('relation_game_id id,relation_game_name game_name,short')
                    ->where(['game_status'=>1, 'down_port'=>1])
                    ->group("relation_game_id")
                    ->select();
                $data['data']['game_list'] = empty($games) ? '' : $games;
            } elseif ($company['game_ids'] == '') {
                $data['data']['game_list'] = [];
            } else {
                $companyGameIds = explode(',', $company['game_ids']);
                $games = M('game', 'tab_')
                    ->field('relation_game_id id,relation_game_name game_name,short')
                    ->where(['game_status'=>1, 'down_port'=>1, 'id' => ['in', $companyGameIds]])
                    ->group("relation_game_id")
                    ->select();
                $data['data']['game_list'] = empty($games) ? '' : $games;
            }
            
            if (empty($promote['game_ids'])) {
                $promote['game_ids'] = [];
            } else {
                $this->changeGameidToRelationGameid($promote['game_ids']);
                $promote['game_ids'] = explode(',', $promote['game_ids']);
            }
            $data['data']['promote_info'] = empty($promote) ? '' : $promote;
            $data['msg'] = '请求成功';
            $data['code'] = 1;

            $this->ajaxReturn($data);
            exit;
        }
    }
    //普通游戏id转唯一游戏id
    protected function changeGameidToRelationGameid(&$ids)
    {
        $rid = M('game', 'tab_')->field('relation_game_id')->where(["id"=>["in",$ids]])->group("relation_game_id")->select();
        if($rid){
            $ids = implode(",",array_column($rid,'relation_game_id'));
        }
    }


    //更新推广员可推广游戏
    public function savePromoteGame()
    {
        if (IS_AJAX) {
            $id = I('promote_id', 0, 'intval');
            if (empty($id)) {
                $this->ajaxReturn(['code'=>0,'msg'=>'请选择推广员']);
            }
            $promoter = M('promote', 'tab_')->where(['id'=>$id])->find();
            if (empty($promoter)) {
                $this->ajaxReturn(['code'=>0,'msg'=>'未找到推广员']);
            }
            $game_ids = I('game_ids', '');
            if (!empty($game_ids)) {
                $game_ids = implode(',', $game_ids);
                $this->changeRelationGameidToGameid($game_ids);
            } else {
                $game_ids = 0;
            }
            // 获取下级id
            $childrens = M('promote', 'tab_')->where("chain like '{$promoter['chain']}{$promoter['id']}/%'")->select();
            $res = M('promote', 'tab_')->where(['id'=>['in', $childrens? array_merge([$id], array_column($childrens, 'id')) : [$id] ]])->save(['game_ids'=>$game_ids]);
            if ($res) {
                $this->ajaxReturn(['code'=>1,'msg'=>'更新成功']);
            } else {
                $this->ajaxReturn(['code'=>0,'msg'=>'数据未发生变化']);
            }
        }
    }
    //唯一游戏id转普通游戏id
    protected function changeRelationGameidToGameid(&$ids)
    {
        $rid = M('game', 'tab_')->field('id')->where(["relation_game_id"=>["in",$ids]])->select();
        if($rid){
            $ids = implode(",",array_column($rid,'id'));
        }
    }

    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"));
    }

    public function linkInfo() {
        $link = $_REQUEST['link'];

        $applyServe = new ApplyService();
        $identifier = $applyServe->getPageIdentifier($link);
        if (!$identifier) {
            $this->assign('error', '链接异常');
            return $this->display();
        }
        $promoteId = 0;
        $gameId = 0;
        $createdAt = '无法获知';
        $expiresIn = 0;
        $realType = 0;
        if (isset($identifier['code'])) {
            $result = $applyServe->decodeApplyCode($identifier['code']);
            if (!$result) {
                $this->assign('error', '解码异常');
                return $this->display();
            }
            $promoteId = $result['promote_id'];
            $gameId = $result["game_id"];
            $expiresIn = $result['expires_in'];
            $createdAt = $result['created_at'];
            $realType = $result['type'];
        } else if(isset($identifier['promote_id']) && isset($identifier['game_id'])) {
            $promoteId = $identifier['promote_id'];
            $gameId = $identifier["game_id"];
            $realType = $identifier['type'];
        }

        $promoteInfo = M('promote','tab_')->field('account')->where(['id'=>$promoteId])->find();
        $params['account'] = $promoteInfo['account'];
        $gameInfo = M('game','tab_')->field('game_name')->where(['id'=>$gameId])->find();
        $params['game_name'] = $gameInfo['game_name'];
        
        if($expiresIn == 0) {
            $params['expires_in'] = "永久性";
        }else if($expiresIn > 0) {
            $params['expires_in'] = $expiresIn;
        }
        $params['created_at'] = $createdAt;
        if($realType == 1) {
            $params['type'] = '下载链接';
        } else if($realType == 2) {
            $params['type'] = '落地页链接';
        }
        $this->assign('params',$params);
        $this->display();
    }

    /**
     *推广公会归属管理
     */
    public function belong($p = 1)
    {
        if (strlen(I('company_relation'))) {
            $map['pb.company_relation'] = I('company_relation');
        }
        if (isset($_REQUEST['company_belong'])) {
            $map['p.company_belong'] = $_REQUEST['company_belong'];
        }

        if (strlen(I('verify_status'))) {
            $map['verify_status'] = I('verify_status');
        }
        if (I('account')) {
            $map['p.account'] = array('like','%'.I('account').'%');
        }

        if (!is_null(I('can_view_recharge', null))) {
            $map['pb.can_view_recharge'] = I('can_view_recharge');
        }

        if (!is_null(I('company_type', null))) {
            $map['pb.company_type'] = I('company_type');
        }

        if (!is_null(I('company_id', null))) {
            $map['p.company_id'] = I('company_id');
        }

        if (!is_null(I('admin_id', null))) {
            $map['p.admin_id'] = I('admin_id');
        }
        $this->m_title = '推广公会归属管理';
        $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/belong','status'=>1])->find());
        if (isset($_REQUEST['row'])) {
            $row = $_REQUEST['row'];
        } else {
            $row = 10;
        }

        //为数据权限添加
        setPowerPromoteIds($map, 'pb.promote_id');
        $model = M('promote_belong', 'tab_');
        $default_company = C('DEFAULT_COMPANY');
        $field = "
            pb.id,pb.promote_id,pb.verify_status,pb.company_relation,pb.remark,pb.can_view_recharge,pb.approver_name,pb.applicant_name,pb.verify_time,pb.applicant_time,pb.company_type,
            IFNULL(pc.company_name,'{$default_company}') company_name,
            p.company_belong,p.account,p.mobile_phone,p.admin_id,p.ver_status,p.status,p.create_time
        ";
        $list_data = $model->alias('pb')
            ->join('left join tab_promote as p on p.id=pb.promote_id')
            ->join('left join tab_promote_company as pc on pc.id = p.company_id')
            ->where($map)
            ->field($field)
            ->page($p, $row)
            ->order('verify_status asc,applicant_time asc')
            ->select();
//        dd($model->_sql());
    //    dd($list_data);
        $count = $model->alias('pb') ->join('left join tab_promote as p on p.id=pb.promote_id')->where($map)->count();
        $page = set_pagination($count, $row);
        if ($page) {
            $this->assign('_page', $page);
        }
        $companys = M('promote_company', 'tab_')->field('id, company_name')->select();
        $admins = M('member')->field('uid,nickname')->select();
        $show_data_power = (is_administrator()|| session('user_auth')['show_data']);
        $this->assign('show_data_power', $show_data_power);
        $this->assign('list_data', $list_data);
        $this->assign('companys', $companys);
        $this->assign('admins', $admins);
        $this->display();
    }

    public function belong_add($promote_id=null, $company_belong = null, $company_relation = null, $remark = null, $can_view_recharge = null, $company_type = null)
    {
        if (IS_POST) {
            if (empty($promote_id)) {
                $this->error('请选择会长');
            }
            $data = array(
                'promote_id' => $promote_id,
                // 'company_belong' => $company_belong,
                'company_relation' => $company_relation,
                'can_view_recharge' => $can_view_recharge,
                'company_type' => $company_type,
                'verify_status' => 0,
                'remark' => $remark,
                'applicant_id' => getAdmin(),
                'applicant_name' => getAdmin('username'),
                'applicant_time' => time(),
            );
            $count = M('promote_belong', 'tab_')->where(['promote_id' => $promote_id])->count();
            if ($count) {
                $this->error('已存在该会长的归属记录');
            }
            $res = M('promote_belong', 'tab_')->add($data);
            if ($res) {

                $promote = M('promote','tab_')->where(['id'=>$promote_id])->find();

                addOperationLog(['op_type'=>0,'key'=>$promote['account'],'op_name'=>'工会归属申请','url'=>U('Promote/belong'),'menu'=>'推广员-推广员管理-推广公会归属管理-工会归属申请']);

                $this->success("申请成功", U('belong'));
            } else {
                $this->error('申请失败');
            }
        } else {
            $this->meta_title ='工会归属申请';
            $this->m_title = '工会归属管理';
            $companys = M('promote_company', 'tab_')->where(['status' => 1])->select();
            $this->assign('companys', $companys);
            $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/lists/type/1','status'=>1])->find());
            $this->display();
        }
    }

    public function belong_edit($promote_id=null, $company_belong = null, $company_relation = null, $remark = null, $can_view_recharge = null, $company_type = null)
    {
        if (IS_POST) {
            if (empty($promote_id)) {
                $this->error('请选择会长');
            }
            $data = array(
                'promote_id' => $promote_id,
                'company_relation' => $company_relation,
                'can_view_recharge' => $can_view_recharge,
                'company_type' => $company_type,
                'verify_status' => 0,
                'remark' => $remark,
                'applicant_id' => getAdmin(),
                'applicant_name' => getAdmin('username'),
                'applicant_time' => time(),
            );
            $res = M('promote_belong', 'tab_')->where(['id' => I('id')])->save($data);
            if ($res) {

                $promote = M('promote','tab_')->where(['id'=>$promote_id])->find();

                addOperationLog(['op_type'=>1,'key'=>$promote['account'],'op_name'=>'编辑工会归属申请','url'=>U('Promote/belong_edit',['id'=>I('id')]),'menu'=>'推广员-推广员管理-推广公会归属管理-编辑工会归属申请']);

                $this->success("编辑成功", U('belong'));
            } else {
                $this->error('编辑失败');
            }
        } else {
            $this->meta_title ='工会归属申请';
            $this->m_title = '工会归属管理';
            $data = M('promote_belong', 'tab_')->where(['id' => I('id')])->find();
            $this->assign('data', $data);
            $this->assign('commonset', M('Kuaijieicon')->where(['url'=>'Promote/lists/type/1','status'=>1])->find());
            $this->display();
        }
    }

    /**
     *工会归属审批
     */
    public function belong_verify()
    {
        $verify_status = $_REQUEST['verify_status'];
        $res = M('promote_belong', 'tab_')->where(['id' => ['in', I('ids')]])->save([
            'verify_status' => $verify_status,
            'approver_id' => getAdmin(),
            'approver_name' => getAdmin('username'),
            'verify_time' => time()
        ]);


        if (!is_null($res) ) {
            if ($verify_status == 1) {//审核通过才修改推广员的归属关系
                $promote_belongs = M('promote_belong', 'tab_')->where(['id' => ['in', I('ids')]])->select();
                foreach ($promote_belongs as $promote_belong) {
                    $update = [
                        'company_relation' => $promote_belong['company_relation'],
                        'can_view_recharge' => $promote_belong['can_view_recharge'],
                        'account_type' => $promote_belong['company_type']
                    ];
                    $res = M("promote", "tab_")
                        ->where("chain like '%/{$promote_belong['promote_id']}/%' or id={$promote_belong['promote_id']} ")
                        ->save($update);

                    $promoteData = M('promote','tab_')->field('account')->where(['id'=>$promote_belong['promote_id']])->find();
                    addOperationLog(['op_type'=>1,'key'=>$promoteData['account'],'op_name'=>'推广公会归属审核通过','url'=>U('Promote/belong'),'menu'=>'推广员-推广员管理-推广公会归属管理-推广公会归属审核通过']);

                }
            } else if ($verify_status == 2) {

                $promote_belongs = M('promote_belong', 'tab_')->where(['id' => ['in', I('ids')]])->select();
                foreach ($promote_belongs as $promote_belong) {

                    $promoteData = M('promote','tab_')->field('account')->where(['id'=>$promote_belong['promote_id']])->find();
                    addOperationLog(['op_type'=>1,'key'=>$promoteData['account'],'op_name'=>'推广公会归属审核拒绝','url'=>U('Promote/belong'),'menu'=>'推广员-推广员管理-推广公会归属管理-推广公会归属审核拒绝']);

                }
            }

            $this->success("操作成功", U('belong'));
        } else {
            $this->error('操作失败');
        }
    }


    public function certification()
    {
        if ($_POST) {
            $promoteId = intval(I('post.id', 0));
            if (empty($promoteId)) {
                $this->error('参数异常');
            }

            $promote = D('promote')->field('real_name, idcard, mobile_phone')->where(array('id' => $promoteId))->find();
            if (empty($promote)) {
                $this->error('参数异常');
            }
            if (empty($promote['real_name']) || $promote['real_name'] != I('post.real_name', '')) {
                if (empty($_POST['real_name'])) {
                    $this->error('真实姓名不能为空');
                }
                $save['real_name'] = I('post.real_name', '');
            }
            if (empty($promote['idcard']) || $promote['idcard'] != I('post.idcard', '')) {
                if (empty($_POST['idcard'])) {
                    $this->error('身份证号码不能为空');
                }
                if(!is_idcard($_POST['idcard'])) {
                    $this->error('证件号码错误');
                }
                $save['idcard'] = I('post.idcard', '');
            }
            if (empty($promote['mobile_phone']) || $promote['mobile_phone'] != I('post.mobile_phone', '')) {
                if (empty($_POST['mobile_phone'])) {
                    $this->error('手机号码不能为空');
                }
                $patternPhone = "/^1[3|5|7|8]\\d{9}$/i";
                if(!preg_match($patternPhone, $_POST['mobile_phone'])) {
                    $this->error("手机号码格式不合法");
                }
                $save['mobile_phone'] = I('post.mobile_phone', '');
            }
            if (empty($_POST['idcarpic'])) {
                $this->error('身份证证件照不能为空');
            }
            if (empty($_POST['s_province'])) {
                $this->error('联系省份不能为空');
            }
            if (empty($_POST['s_city'])) {
                $this->error('联系地级市不能为空');
            }
            if (empty($_POST['s_county'])) {
                $this->error('联系市、县级市不能为空');
            }
            if (empty($_POST['s_address'])) {
                $this->error('详细地址不能为空');
            }
            if (empty($_POST['email'])) {
                $this->error('邮箱不能为空');
            }
            $patternEmail = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
            if (!preg_match($patternEmail, $_POST['email'])) {
                $this->error('邮箱地址错误');
            }
            if (empty($_POST['account_type'])) {
                $this->error('账户类型不能为空');
            }
            if (empty($_POST['bank_name'])) {
                $this->error('开户银行不能为空');
            }
            if (empty($_POST['bank_account'])) {
                $this->error('银行户名不能为空');
            }
            $patternBankAccount = "/^[\x{4e00}-\x{9fa5}]{2,}$/u";
            if (!preg_match($patternBankAccount, $_POST['bank_account'])) {
                $this->error('银行卡开户人姓名错误');
            }
            if (empty($_POST['bank_card'])) {
                $this->error('卡号不能为空');
            }
            $patternBankCard = "/^\d{10,19}$/u";
            if (!preg_match($patternBankCard, $_POST['bank_card'])) {
                $this->error('卡号格式错误');
            }

            $save['id'] = $promoteId;
            $save['ver_status'] = 1;
            $save['idcarpic'] = I('post.idcarpic', '');
            $save['address'][] = I('post.s_province', '') . ',' . I('post.s_city', '') . ',' . I('post.s_county', '');
            $save['address'][] = I('post.s_address', '');
            $save['address'] = json_encode($save['address']);
            $save['email'] = I('post.email', '');
            $save['account_type'] = intval(I('post.account_type', 1));
            $save['bank_name'] = I('post.bank_name', '');
            $save['bank_account'] = I('post.bank_account', '');
            $save['bank_card'] = I('post.bank_card', '');
            if (isset($_POST['businesspic'])) {
                $save['businesspic'] = I('post.businesspic', '');
            }
            if (isset($_POST['agreementpic'])) {
                $save['agreementpic'] = I('post.agreementpic', '');
            }
            if (isset($_POST['anothpic'])) {
                $save['anothpic'] = I('post.anothpic', '');
            }

            $result = D('promote')->save($save);
            if ($result === false) {
                $this->error('操作失败');
            } else {

                $promoteData = M('promote','tab_')->field('account')->where(['id'=>$promoteId])->find();

                addOperationLog(['op_type'=>1,'key'=>$promoteData['account'],'op_name'=>'资质认证','url'=>U('Promote/certification',['id'=>$promoteId]),'menu'=>'推广员-推广员管理-推广员列表-资质认证']);

                $this->success('操作成功');
            }
        } else {
            $promoteId = intval(I('id', 0));
            if ($promoteId <= 0) {
                $this->error('参数错误');
            }

            $promote = D('promote')->where(array('id' => $promoteId))->find();
            $promote['idcarpic_array'] = $promote['idcarpic'] ? explode(',', $promote['idcarpic']) : [];
            $promote['businesspic_array'] = $promote['businesspic'] ? explode(',', $promote['businesspic']) : [];
            $promote['agreementpic_array'] = $promote['agreementpic'] ? explode(',', $promote['agreementpic']) : [];
            $promote['anothpic_array'] = $promote['anothpic'] ? explode(',', $promote['anothpic']) : [];
            $promote['address'] = json_decode($promote['address'], true);
            if (!empty($promote['address'])) {
                foreach ($promote['address'] as &$address) {
                    $address = explode(',', $address);
                }
            }

            $this->assign('records', $promote);
            $this->assign('meta_title', '资质认证');
            $this->display();
        }
    }
}