<?php
/**
 * CRM设定
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: wzy<wangzhenya@suxuantech.cn> 2017-10-27 $
 */
namespace app\crm\controller;
use app\index\controller\Base;
use think\Exception;
use think\Queue;
use app\common\lib\mcInterface;

class Setting extends Base{
    /**
     * @cc 消费能力设定
     * */
    public function storeSet()
    {
        //获取品牌列表
        $brand = controller('crm/Setting','lib')->getBrandList();
        $this->assign('brand',$brand);
        $id = input('request.id');
        $shop_name = trim(input('request.shop_name'));
        //获取店面列表
        $shop = controller('crm/Setting','lib')->getShopList($id,$shop_name);
        $this->assign('shop',$shop);
        //获取数据条数
        $count = controller('crm/Setting','lib')->getShopListCount($id,$shop_name);
        $this->assign('count',$count);
        $this->assign('shop_name',$shop_name);
        return $this->fetch();
    }
    //分页用接口
    function getStoreJson(){
        $shop_name = trim(input('request.shop_name'));
        $res = controller('crm/Setting','lib')->getStoreJson($shop_name);
        return json($res);
    }
    /**
     * @cc 删除店面
     * */
    function  delStore(){
        return controller('crm/Setting','lib')->delStore(input('post.id'));
    }
    //查看店面
    function  editStore(){
        $id = input('post.id');
        return controller('crm/Setting','lib')->editStore($id);
    }
    //修改店面
    function updateStore(){
        //通过店名获取其简码sn
        $receiv_shop_code = input('post.receiv_shop_code');
        $code = controller('crm/Setting','lib')->getShopSN($receiv_shop_code);
        $param = input('post.');
        $param['shop_code'] = get_rand_string(4,1).get_rand_string(6,2);
        $param['receiv_shop_code'] = $code;
        return controller('crm/Setting','lib')->updateStore($param);
    }
    public function  setStore(){
        if(check_login()){
            if(IS_POST){
                $params['brandclass'] = input('post.brandClass');
                $params['shop_name'] = input('post.shopName');
                $params['shop_code'] = get_rand_string(4,1).get_rand_string(6,2);
                $params['sn'] = input('post.sn');
                $params['numberorder'] = input('post.numberOrder');
                $params['shopaddress'] = input('post.shopAddress');
                $params['receiv_shop_code'] = input('post.receivShopcode');

                $res = controller('crm/Setting','lib')->setStore($params);
                if($res){
                    return true;
                }else{
                    return false;
                }
            }
        }
    }
    public function getPositionListByDepartmentId(){
        //岗位
        $position_info = controller('crm/Setting','lib')->get_position_list(['department_id'=>input('param.department_id')]);
        return $position_info;
    }
    public function getPositionList(){
        //岗位
        $position_info = controller('crm/Setting','lib')->get_position_list(['shop_code'=>session('shop_code')]);
        return $position_info;
    }
    public function getDepartmentList(){
        //岗位
        $dep = controller('crm/Setting','lib')->get_department_list(['shop_code'=>session('shop_code')]);
        return $dep;
    }
    public function getDepartmentStaff(){
        $department_id = input('post.department_id');
        //部门下的人员
        $staff = controller('crm/Customer','lib')->get_staff_list(['department_id'=>$department_id]);
        return $staff;
    }
    //业务目标设定页面
    public function goalSet()
    {
        // 权限
        $auth = check_right('menu1512028704');
        if (!$auth) {
           return $this->redirect('/');
        }
        $staff_id = session('staff_id');

        //可操作店
        $shop = getShops(['staff_id'=>session('staff_id')]);
        $this->assign('shop',$shop);
        //员工信息
        $staff_info = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>$staff_id));
        //部门
        $dep_info = controller('crm/Setting','lib')->department_list(['shop_code'=>session('shop_code')]);
        $this->assign('dep_info',$dep_info);

        //来源渠道
        $channel=controller("Customer","lib")->getChannel();
        $this->assign("channel",$channel);
        //省
        $data['type']=1;
        $province=controller("Customer","lib")->Address($data);
        $this->assign("province",$province);
        $month = getthemonth(date('Y-m-d'));
        $this->assign("start_day",$month[0]);
        $this->assign("last_day",$month[1]);
        //目标列表  新改:不取target,只取部分,电商取:毛客资,有效客资,有效率;
        //网销取 成交量(订单量),邀约量,进店量,进店率,订单转换率(订单/接入客资量),A,B,C客量,一销实收,总实收,一销均价
        if(session('is_marketing') == 1){//电商
            $kpi = array(
                [
                    'id'=> 'newCustomerNum',
                    'name'=>'毛客资量'
                ],
                [
                    'id'=> 'validCustomerNumber',
                    'name'=>'有效客资量'
                ],
                [
                    'id'=> 'valueCustomerRate',
                    'name'=>'客资有效率'
                ],
            );
        }elseif(session('is_marketing') == 3 || session('is_marketing') == 4){
            $kpi = array(
                [
                    'id'=> 'inviteIntoCustomerNumber',
                    'name'=>'邀约进店客资量'
                ],
                [
                    'id'=> 'actualIntoCustomerNumber',
                    'name'=>'实际进店客资量'
                ],
                [
                    'id'=> 'intoValueRate',
                    'name'=>'进店转化率'
                ],
                [
                    'id'=> 'orderNumber',
                    'name'=>'新单量'
                ],
                [
                    'id'=> 'aCustomerNum',
                    'name'=>'A客转化率'
                ],
                [
                    'id'=> 'bCustomerNum',
                    'name'=>'B客转化率'
                ],
                [
                    'id'=> 'cCustomerNum',
                    'name'=>'C客转化率'
                ],
                [
                    'id'=> 'oneFact',
                    'name'=>'一销实收'
                ],
                [
                    'id'=> 'dealAmount',
                    'name'=>'营收'
                ],
                [
                    'id'=> 'oneAVG',
                    'name'=>'一销均价'
                ],
                [
                    'id'=> 'budgetAmount',
                    'name'=>'预算'
                ],
                [
                    'id'=> 'performanceAmount',
                    'name'=>'业绩'
                ],
            );
        }else{
            $kpi = array(
                [
                    'id'=> 'newCustomerNum',
                    'name'=>'毛客资量'
                ],
                [
                    'id'=> 'validCustomerNumber',
                    'name'=>'有效客资量'
                ],
                [
                    'id'=> 'valueCustomerRate',
                    'name'=>'客资有效率'
                ],
                [
                    'id'=> 'inviteIntoCustomerNumber',
                    'name'=>'邀约进店客资量'
                ],
                [
                    'id'=> 'actualIntoCustomerNumber',
                    'name'=>'实际进店客资量'
                ],
                [
                    'id'=> 'intoValueRate',
                    'name'=>'进店转化率'
                ],
                [
                    'id'=> 'orderNumber',
                    'name'=>'新单量'
                ],
                [
                    'id'=> 'aCustomerNum',
                    'name'=>'A客转化率'
                ],
                [
                    'id'=> 'bCustomerNum',
                    'name'=>'B客转化率'
                ],
                [
                    'id'=> 'cCustomerNum',
                    'name'=>'C客转化率'
                ],
                [
                    'id'=> 'oneFact',
                    'name'=>'一销实收'
                ],
                [
                    'id'=> 'dealAmount',
                    'name'=>'营收'
                ],
                [
                    'id'=> 'oneAVG',
                    'name'=>'一销均价'
                ],
                [
                    'id'=> 'budgetAmount',
                    'name'=>'预算'
                ],
                [
                    'id'=> 'performanceAmount',
                    'name'=>'业绩'
                ],
            );
        }
//        $kpi = controller('crm/Setting','lib')->getKPIList();
        $this->assign('kpi',$kpi);
        $this->assign('staff_info',$staff_info['data']);
        $this->assign('month',intval(date('m')));
        $this->assign('year_month',date('Y-m'));
        $this->assign('title','业务目标设定');
        return $this->fetch('goalset');
    }
    /**
     * @cc 查询目标
     * */
    public function editGoal(){
        // 权限
        $auth = check_right('menu1512028704');
        if (!$auth) {
           return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->editGoal(input('post.id'));
        return $res;
    }
    //查询目标
    public function updateGoal(){
        // 权限
        $auth = check_right('menu1512028704');
        if (!$auth) {
           return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->updateGoal(input('post.'));
        return json($res);
    }
    /**
     * @cc 删除目标
     * */
    public function delGoal(){
        // 权限
        $auth = check_right('menu1512028704');
        if (!$auth) {
           return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->delGoal(input('post.id'));
        return $res;
    }
    /**
     * @cc 添加目标
     * */
    public function addGoal(){
        //可操作店
        $shop = getShops(['staff_id'=>session('staff_id')]);
        $this->assign('shop',$shop);
        //渠道
        $channel = controller('crm/Customer','lib')->getChannel();
        $this->assign('channel',$channel);
        //省
        $param['type'] = 1;
        $province = controller('crm/Customer','lib')->address($param);
        $this->assign('province',$province);
        if(session('is_marketing') == 1){//电商
            $kpi = array(
                [
                    'id'=> 'newCustomerNum',
                    'name'=>'毛客资量'
                ],
                [
                    'id'=> 'validCustomerNumber',
                    'name'=>'有效客资量'
                ],
                [
                    'id'=> 'valueCustomerRate',
                    'name'=>'客资有效率'
                ],
            );
        }elseif(session('is_marketing') == 3 || session('is_marketing') == 4){
            $kpi = array(
                [
                    'id'=> 'inviteIntoCustomerNumber',
                    'name'=>'邀约进店客资量'
                ],
                [
                    'id'=> 'actualIntoCustomerNumber',
                    'name'=>'实际进店客资量'
                ],
                [
                    'id'=> 'intoValueRate',
                    'name'=>'进店转化率'
                ],
                [
                    'id'=> 'orderNumber',
                    'name'=>'新单量'
                ],
                [
                    'id'=> 'aCustomerNum',
                    'name'=>'A客转化率'
                ],
                [
                    'id'=> 'bCustomerNum',
                    'name'=>'B客转化率'
                ],
                [
                    'id'=> 'cCustomerNum',
                    'name'=>'C客转化率'
                ],
                [
                    'id'=> 'oneFact',
                    'name'=>'一销实收'
                ],
                [
                    'id'=> 'dealAmount',
                    'name'=>'营收'
                ],
                [
                    'id'=> 'oneAVG',
                    'name'=>'一销均价'
                ],
                [
                    'id'=> 'budgetAmount',
                    'name'=>'预算'
                ],
                [
                    'id'=> 'performanceAmount',
                    'name'=>'业绩'
                ],
            );
        }else{
            $kpi = array(
                [
                    'id'=> 'newCustomerNum',
                    'name'=>'毛客资量'
                ],
                [
                    'id'=> 'validCustomerNumber',
                    'name'=>'有效客资量'
                ],
                [
                    'id'=> 'valueCustomerRate',
                    'name'=>'客资有效率'
                ],
                [
                    'id'=> 'inviteIntoCustomerNumber',
                    'name'=>'邀约进店客资量'
                ],
                [
                    'id'=> 'actualIntoCustomerNumber',
                    'name'=>'实际进店客资量'
                ],
                [
                    'id'=> 'intoValueRate',
                    'name'=>'进店转化率'
                ],
                [
                    'id'=> 'orderNumber',
                    'name'=>'新单量'
                ],
                [
                    'id'=> 'aCustomerNum',
                    'name'=>'A客转化率'
                ],
                [
                    'id'=> 'bCustomerNum',
                    'name'=>'B客转化率'
                ],
                [
                    'id'=> 'cCustomerNum',
                    'name'=>'C客转化率'
                ],
                [
                    'id'=> 'oneFact',
                    'name'=>'一销实收'
                ],
                [
                    'id'=> 'totalFact',
                    'name'=>'总实收'
                ],
                [
                    'id'=> 'dealAmount',
                    'name'=>'营收'
                ],
                [
                    'id'=> 'oneAVG',
                    'name'=>'一销均价'
                ],
                [
                    'id'=> 'budgetAmount',
                    'name'=>'预算'
                ],
                [
                    'id'=> 'performanceAmount',
                    'name'=>'业绩'
                ],
            );
        }
        $this->assign('kpi',$kpi);
        $id = input('param.id');
        $info = db('crm_s_kpi_staffgoal')->where('id',$id)->find();
        $info['month'] = $info['month'] ? : date("Y-m");
        // echo db()->getLastSql();exit;
        $this->assign('info',$info);
        //市
        if($info['province_id']){
            $param['type'] = 2;
            $param['pid'] = $info['province_id'];
            $city = controller('crm/Customer','lib')->address($param);
            $this->assign('city',$city);
        }
        if($info['flag'] == 'department'){
            $dep = controller('crm/Customer','controller')->getDepartmentList(['shop_code'=>$info['shop_code']]);
            $this->assign('dep',$dep);
        }elseif($info['flag'] == 'group'){
            $dep = controller('crm/Customer','controller')->getDepartmentList(['shop_code'=>$info['shop_code']]);
            $this->assign('dep',$dep);
            // 0609 eric
            $group = db('c_staff_group')->where('department_id',$info['department_id'])->select();
            $this->assign('group',$group);
        }elseif($info['flag'] == 'position'){
            $dep = controller('crm/Customer','controller')->getDepartmentList(['shop_code'=>$info['shop_code']]);
            $this->assign('dep',$dep);
            $position = controller('crm/Setting','lib')->get_position_list(['department_id'=>$info['department_id']]);
            $this->assign('position',$position);
        }elseif($info['flag'] == 'staff'){
            $dep = controller('crm/Customer','controller')->getDepartmentList(['shop_code'=>$info['shop_code']]);
            $this->assign('dep',$dep);
            $staff = $this->getDepartmentStaff(['department_id'=>$info['department_id']]);
            $this->assign('staff',$staff);
        }
        return $this->fetch();
    }
    //业务目标设定
    public function setGoal(){
        // 权限
        $auth = check_right('menu1512028704');
        if (!$auth) {
           return $this->redirect('/');
        }
        $param = input('post.');
        $res = controller('crm/Setting','lib')->setGoal($param);
        return json($res);
    }
    public function getGoalJSON(){
        $main_position_code = input('param.');
        $res = controller('crm/Setting','lib')->getGoalJSON($main_position_code);
        return json($res);
    }
    // public function groupSet(){
    //     // 权限
    //     $auth = check_right('menu1512028478');
    //     if (!$auth) {
    //         return $this->redirect('/');
    //     }
    //     //小组信息 
    //     $group_info = db('CStaffGroup')->alias('a')->join('c_staff_group_relation b','a.id=b.group_id')->where('b.staff_id',session('staff_id'))->find();
    //     $this->assign('group_info',$group_info);
    //     //是否是管理员
    //     $isAdmin = controller('crm/Setting','lib')->isGroupAdmin();
    //     $this->assign('isAdmin',$isAdmin['is_admin']);
    //     //是否是小组成员
    //     $isGroupStaff = controller('crm/Setting','lib')->isGroupStaff();
    //     $this->assign('isGroupStaff',$isGroupStaff['group_id']);
    //     return $this->fetch();
    // }
    /**
     * @cc 编辑小组
     * */
    // public function editGroup(){
    //     $id = input('param.id');
    //     //小组信息
    //     $group_info = db('CStaffGroup')->where('id',$id)->find();
    //     $this->assign('group_info',$group_info);
    //     //部门信息
    //     $department = controller('crm/Setting','lib')->department_list(['shop_code'=>session('shop_code')]);
    //     $this->assign('department',$department);
    //     //获取无小组人员信息
    //     if($group_info['department_id']){
    //         $no_group_staff = controller('crm/Setting','lib')->getNoGroupStaff(array('department_id'=>$group_info['department_id'],'shop_code'=>session('shop_code')));
    //     }else{
    //         $no_group_staff = controller('crm/Setting','lib')->getNoGroupStaff(array('shop_code'=>session('shop_code')));
    //     }
    //     $this->assign('no_group_staff',$no_group_staff['data']);
    //     //当前小组所有人员
    //     $inGroupStaffInfo = controller('crm/Setting','lib')->getInGroupStaffInfo($id);
    //     $this->assign('inGroupStaffInfo',$inGroupStaffInfo['data']);
    //     //所以人员，包含兼职
    //     $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>session('shop_code')]);
    //     $this->assign('staff',$staff);
    //     //所有管理员，不包含组长
    //     $res = sx_call('5a18e3fa516a1',['staff_id'=>$group_info['admin']]);
    //     if($res['code'] == 200){
    //         $this->assign('admin',$res['data']);
    //     }
    //     return $this->fetch();
    // }
    //岗位下的人员
    public function getPositionStaffs(){
        $data = input();
        return controller('crm/Setting','lib')->positionStaffs($data);
    }
    // 根据部门id获取部门下的员工 如果有小组，unset掉
    public function getDepartmentStaffs($department_id){
        // $url = '5a0e6f272bb38';
        $arr = array('department_id'=>$department_id,'get_leave'=>2,'get_main'=>2);
        // $staffs = sx_call($url, $arr);
        // $staffs = $staffs['data'];

        $mc = new \app\common\lib\mcInterface();
        $staffs = $mc->getStaffByDepartment($arr);
        // var_dump($staffs);
        // exit;
        //所有人员
        //部门下的小组 0609
        $groups = db('c_staff_group')->where('department_id',$department_id)->where('shop_code',session('shop_code'))->field('id')->select();
        $ids = array_column($groups,'id');
        //小组成员 0606
        $groupStaffs = $mc->getStaffInfoByGid(array('group_id' => $ids));
        unset($mc);

        // $groupStaffs = db('c_staff_group_relation')->where('group_id','in',$ids)->column('staff_id,group_id');
        $groupStaffs = array_keys($groupStaffs);
        //去掉已有小组的人
        foreach($staffs as $k=>$v){
            if(in_array($v['id'],$groupStaffs)){
                unset($staffs[$k]);
            }
        }
        return array_merge($staffs,[]);
    }
    // 0609
    public function getDepartmentStaffsInGroup(){
        $groupId = input('param.id');
        $info = db('CStaffGroupRelation')->where('group_id',$groupId)->field('staff_id')->select();
        $ar = array();
        foreach($info as $ke=>$va){
            array_push($ar,$va['staff_id']);
        }
        $ids = implode(',',$ar);
        //请求接口，通过id获取名字
        // $url = "5a18e3fa516a1";
        // $res = sx_call($url,array('staff_id'=>$ids));
        $mc = new \app\common\lib\mcInterface();
        $res = $mc->getStaffByIds(array('staff_id'=>$ids));

        if($res !== false){
            return $res;
        }else{
            return [];
        }
    }
    // 0609
    public function getGroupToJSON(){
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('c_staff_group')->where('shop_code',session('shop_code'))->select();
        $count = db('c_staff_group')->where('shop_code',session('shop_code'))->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return json($result);
    }
    /**
     * @cc 添加编辑小组
     * */
    public function addGroup(){
        $param = input('post.');
        // 权限
        $auth = check_right('menu1512028478');
        if (!$auth) {
            $js = array('code'=>600,'msg'=>'您没权限操作');
            return json($js);
        }
        $res = controller('crm/Setting','lib')->addGroup($param);
        return $res;
    }
    /**
     * @cc 删除并清空小组
     * */
    public function delGroup(){
        // 权限
        $auth = check_right('menu1512028478');
        $auth1 = check_right('menu1535542292');//删除小组
        $param = input();
        if (!$auth && !$auth1) {
            $js = array('code'=>600,'msg'=>'您没权限操作');
            return json($js);
        }
        return controller('crm/Setting','lib')->delGroup($param);
    }
    /**
     * @cc 删除小组人员
     * */
    public function delFromGroup(){
        // 权限
        // $auth = check_right('menu1512028478');
        // if (!$auth) {
        //     $js = array('code'=>600,'msg'=>'您没权限操作');
        //     return json($js);
        // }
        return controller('crm/Setting','lib')->delFromGroup(input('post.staff_id'));
    }
    /**
     * @cc 添加人员入组
     * */
    public function addToGroup(){
        // 权限
        $auth = check_right('menu1512028478');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addToGroup(input('post.staff_id'));
    }
    //客资分配设定
    public function fpSet(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        //获取员工小组列表 0609
        // $group = controller('crm/Setting','lib')->getGroupList();
        // $this->assign('group',$group);
        //获取渠道
        $qudao = controller('crm/Setting','lib')->getQudao();
        $this->assign('qudao',$qudao);
        //获取默认规则
        $default= controller('crm/Setting','lib')->getDefaultRule();
        $this->assign('default',$default);

        //分配开关
        $switch = db_config('fp_switch_'.session('shop_code'));
        $this->assign('switch',$switch);
        //接收开关
        $auto_jr = db_config('auto_jr_'.session('shop_code'));
        $this->assign('auto_jr',$auto_jr);
        //字段分配开关时间
        $fp_time = db_config('fp_time_'.session('shop_code'));
        $this->assign('fp_time',$fp_time);

        //分配过期时间
        $timeout = db_config('fp_timeout_'.session('shop_code'));
        $this->assign('timeout',$timeout);
        //离线是否分配
        $not_online_is_fp = db_config('not_online_is_fp_'.session('shop_code'));
        $this->assign('not_online_is_fp',$not_online_is_fp);

        $tar = new \app\crm\lib\Target();
        $ap = $tar->getAllTarget();
        $this->assign('ap',$ap);
        $this->assign('title','客资分配设定');
        return $this->fetch();
    }
    // 分配设定页面
    public function fpIframe(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        $inp = input();
        $currentShopCode = session('shop_code');
        // echo $currentShopCode;
        $res = [];
        if($inp){
            $res = controller('crm/Setting','lib')->getFPIframeInfo($inp['id']);
        }
        $conditions = array(
            'customer_channel'=>'渠道名称',
            // 'customer_source'=>'客户来源',
            // 'customer_area'=>'客户分区',
            'customer_region'=>'地域',
            'add_organize'=>'提报人',
            'default'=>'默认',
        );

        $this->assign('conditions',$conditions);

        // 归属店
        $gs_shop_code = controller('crm/Statistics', 'lib')->getShops(session('brandclass_id'));
        $this->assign('gs_shop_code',$gs_shop_code);

        $conditionValues = [];
        $mcInterface = new mcInterface();
        switch ($res['customer_condition']) {
            case 'customer_channel':
                $channel_ids = explode(',', $res['customer_value']);
                $fpChannelList = [];
                foreach ($channel_ids as $k => $v) {
                    $fpChannelList[$k]['channel_id'] = $v;
                    $fpChannelList[$k]['channel_name'] = db('crm_s_channel')->where('id',$v)->value('channel_name');
                }
                $this->assign('fpChannelList',$fpChannelList);
                # 获取所选渠道的那个店的所有三级渠道列表。
                $selChannelList = controller('crm/Setting','lib')->getShopChannelListById($res['customer_value']);
                //获取所有应提报给我店客资的所有店列表
                $addShoplist = $mcInterface->getAddcustomerShopList($currentShopCode);
                $temp[] = ['value'=>'0','text'=>'请选择','select'=>0];
                foreach ((array)$addShoplist as $key => $value) {
                    # 在循环店时，如果有某个店的渠道，是当前已选择的渠道的店时，店默认选中，并记下标记
                    # 因为如果调整了，有可能所选渠道不在提报给我的店列表内，后面不能显示渠道列表，而是让用户重选店。
                    if($selChannelList[0]['shop_code'] == $value['shop_code']){
                        $res['customer_channel_shop_code'] = $value['shop_code'];
                        $temp[] = ['value'=>$value['shop_code'],'text'=>$value['shop_name'],'select'=>1,'title'=>'channelshoplist'];
                    }else{
                        $temp[] = ['value'=>$value['shop_code'],'text'=>$value['shop_name'],'select'=>0,'title'=>'channelshoplist'];
                    }
                }
                unset($addShoplist);
                if($temp){
                    $conditionValues[] = $temp;
                }
                unset($temp);
                if($res['customer_channel_shop_code']){
                    //如果有某个渠道店被选中，则处理渠道 列表。
                    $temp[] = ['value'=>'0','text'=>'请选择','select'=>0];
                    foreach ($selChannelList as $key => $value) {
                        if($res['customer_value'] == $value['id']){
                            $temp[] = ['value'=>$value['id'],'text'=>$value['channel_name'],'select'=>1,'title'=>'channellist'];
                        }else{
                            $temp[] = ['value'=>$value['id'],'text'=>$value['channel_name'],'select'=>0,'title'=>'channellist'];
                        }

                    }
                    if($temp){
                        $conditionValues[] = $temp;

                    }
                    unset($temp);

                }
                unset($selChannelList);
                break;
            case 'customer_source':
                $customerResource = $mcInterface->getCustomerResource();
                $temp[] = ['value'=>'0','text'=>'请选择','select'=>0];
                foreach ($customerResource as $key => $value) {
                    if($res['customer_value'] == $value['id']){
                        $temp[] = ['value'=>$value['id'],'text'=>$value['cus_name'],'select'=>1];
                    }else{
                        $temp[] = ['value'=>$value['id'],'text'=>$value['cus_name'],'select'=>0];
                    }
                }
                if($temp){
                    $conditionValues[] = $temp;

                }
                unset($temp);
                break;
            case 'customer_area':
                $customerArea = $mcInterface->getCustomerArea();
                $temp[] = ['value'=>'0','text'=>'请选择','select'=>0];
                foreach ($customerArea as $key => $value) {
                    if($res['customer_value'] == $value['id']){
                        $temp[] = ['value'=>$value['id'],'text'=>$value['area_name'],'select'=>1];
                    }else{
                        $temp[] = ['value'=>$value['id'],'text'=>$value['area_name'],'select'=>0];
                    }
                }
                if($temp){
                    $conditionValues[] = $temp;

                }
                unset($temp);
                unset($customerArea);
                break;
            case 'customer_region':
                $region = explode(',',$res['customer_value']);
                $tt = [];
                foreach($region as $k=>$v){
                    $tt[$k]['value'] = $v;
                    $tem = explode('-',$v);
                    $tt[$k]['name'] = end($tem);
                }
                $this->assign('region',$tt);
                $type = explode('-', $res['customer_value']);

                $type = strtolower($type[0]);//shop,department,staff
                $val = str_replace($type.'-', '', $res['customer_value']);
                $selRegion = '';
                $selProvince = 0;
                $selCity = 0;
                if($type == 'city'){
                    $city = controller('crm/Customer','lib')->address(['id'=>$val]);//市信息 包含省id
                    $region = controller('crm/Customer','lib')->address(['id'=>$city[0]['pid']]);//地域信息
                    $selRegion = $region[0]['pid'];
                    $selProvince = $city[0]['pid'];
                    $selCity = $val;
                    $provinceList = controller('crm/Customer','lib')->address(['pid'=>$region[0]['pid']]);
                    $cityList = controller('crm/Customer','lib')->address(['pid'=>$city[0]['pid']]);
                }elseif($type == 'province'){
                    $province = controller('crm/Customer','lib')->address(['type'=>1,'id'=>$val]);//市信息 包含省id
                    $selRegion = $province[0]['pid'];
                    $selProvince = $val;
                    $provinceList = controller('crm/Customer','lib')->address(['pid'=>$province[0]['pid']]);
                    $cityList = controller('crm/Customer','lib')->address(['pid'=>$val]);
                }else{
                    $selRegion = $val;
                    $provinceList = controller('crm/Customer','lib')->address(['pid'=>$val]);
                }
                $customerRegin = $mcInterface->getCustomerRegin();
                // $customerRegin = $mcInterface->getCustomerRegin();
                $temp[] = ['value'=>'0','text'=>'请选择','select'=>0];
                foreach ($customerRegin as $key => $value) {
                    if($selRegion == $value['id']){
                        $temp[] = ['value'=>$value['id'],'text'=>$value['region_name'],'select'=>1,'title'=>'region'];
                    }else{
                        $temp[] = ['value'=>$value['id'],'text'=>$value['region_name'],'select'=>0,'title'=>'region'];
                    }
                }
                if($temp){
                    $conditionValues[] = $temp;
                }
                unset($temp);
                //省
                $temp[] = ['value'=>'0','text'=>'请选择省','select'=>0];
                foreach($provinceList as $k=>$v){
                    if($selProvince == $v['id']){
                        $temp[] = ['value'=>$v['id'],'text'=>$v['name'],'select'=>1,'title'=>'provincelist'];
                    }else{
                        $temp[] = ['value'=>$v['id'],'text'=>$v['name'],'select'=>0,'title'=>'provincelist'];
                    }
                }
                if($temp){
                    $conditionValues[] = $temp;
                }
                unset($temp);
                //市
                $temp[] = ['value'=>'0','text'=>'请选择市','select'=>0];
                foreach($cityList as $k=>$v){
                    if($selCity == $v['id']){
                        $temp[] = ['value'=>$v['id'],'text'=>$v['name'],'select'=>1,'title'=>'citylist'];
                    }else{
                        $temp[] = ['value'=>$v['id'],'text'=>$v['name'],'select'=>0,'title'=>'citylist'];
                    }
                }
                if($temp){
                    $conditionValues[] = $temp;
                }
                unset($temp);

                unset($customerRegin);
                break;
            case 'add_organize':
                $staff = explode(',',$res['customer_value']);
                $tt = [];
                foreach($staff as $k=>$v){
                    $tt[$k]['value'] = $v;
                    $tem = explode('-',$v);
                    $tt[$k]['name'] = end($tem);
                }
                $this->assign('region',$tt);
                //按提报人分配，
                $type = explode('-', $res['customer_value']);
                $type = strtolower($type[0]);//shop,department,staff
                $val = str_replace($type.'-', '', $res['customer_value']);
                $selShopcode = '';
                $selDepartment = 0;
                $selStaffid = 0;
                if($type == 'staff'){
                    $selStaffid = $val;
                    $staffInfo = $mcInterface->getStaffById(intval($val));
                    $selDepartment = $staffInfo['department_id'];
                    $selShopcode = $staffInfo['shop_code'];
                    $staffList = $mcInterface->getStaffListByDepartmentId($selDepartment);
                    $departmentList = $mcInterface->getDepartmentByShopcode($selShopcode);
                }
                if($type == 'department'){
                    $selDepartment = $val;
                    $departmentInfo = $mcInterface->getDepartmentById($val);
                    $selShopcode = $departmentInfo['shop_code'];
                    $departmentList = $mcInterface->getDepartmentByShopcode($selShopcode);
                }

                if($type == 'shop'){
                    $selShopcode = $val;
                }
                //店
                $shopList = $mcInterface->getBrandShopList(session('brandclass'));
                $temp[] = ['value'=>'0','text'=>'请选择店','select'=>0];
                foreach ($shopList as $key => $value) {
                    if($selShopcode == $value['shop_code']){
                        $temp[] = ['value'=>$value['shop_code'],'text'=>$value['shop_name'],'select'=>1,'title'=>'staffshoplist'];
                    }else{
                        $temp[] = ['value'=>$value['shop_code'],'text'=>$value['shop_name'],'select'=>0,'title'=>'staffshoplist'];
                    }
                }
                if($temp){
                    $conditionValues[] = $temp;
                }
                unset($temp);
                //部门
                $temp[] = ['value'=>'0','text'=>'请选择部门','select'=>0];
                if($departmentList){
                    foreach ($departmentList as $key => $value) {
                        if($selDepartment == $value['id']){
                            $temp[] = ['value'=>$value['id'],'text'=>$value['department_name'],'select'=>1,'title'=>'staffdepartmentlist'];
                        }else{
                            $temp[] = ['value'=>$value['id'],'text'=>$value['department_name'],'select'=>0,'title'=>'staffdepartmentlist'];
                        }
                    }
                }
                if($temp){
                    $conditionValues[] = $temp;

                }
                unset($temp);
                //员工
                $temp[] = ['value'=>'0','text'=>'请选择员工','select'=>0];
                if($staffList){
                    foreach ($staffList as $key => $value) {
                        if($selStaffid == $value['id']){
                            $temp[] = ['value'=>$value['id'],'text'=>$value['staffname'],'select'=>1,'title'=>'stafflist'];
                        }else{
                            $temp[] = ['value'=>$value['id'],'text'=>$value['staffname'],'select'=>0,'title'=>'stafflist'];
                        }
                    }
                }
                if($temp){
                    $conditionValues[] = $temp;

                }
                unset($temp);
                break;
            case 'default':
                break;
            default:
                $res['customer_condition'] = 'customer_channel';
                $addShoplist = $mcInterface->getAddcustomerShopList($currentShopCode);
                $temp[] = ['value'=>'0','text'=>'请选择','select'=>0];
                foreach ((array)$addShoplist as $key => $value) {
                    $temp[] = ['value'=>$value['shop_code'],'text'=>$value['shop_name'],'select'=>0,'title'=>'channelshoplist'];
                }
                if($temp){
                    $conditionValues[] = $temp;
                }
                unset($temp);
                break;
        }
        // var_dump($conditionValues);exit;
        $this->assign('conditionValues',$conditionValues);

        if ($res['staff_type']) {
            switch ($res['staff_type']) {
                case 'department_name':
                    $id = json_decode($res['staff_value'], true);
                    $res['department_id'] = $id[0]['department_id'];
                    break;
                case 'position_name':
                    $id = json_decode($res['staff_value'], true);
                    $res['position_id'] = $id[0]['position_id'];
                    break;
                case 'group_name':
                    $id = json_decode($res['staff_value'], true);
                    $res['group_id'] = $id[0]['group_id'];
                    break;
                case 'staff_name':
                    $res['staff_value'] = json_decode($res['staff_value'],true);
                    break;
                default:
                    break;
            }
        }
        // $res['staff_value'] = json_decode($res['staff_value'],true);

        $this->assign('res',$res);
        $staff = controller('crm/Customer','lib')->get_staff_list(['shop_code'=>$res['belong_shop_code']]);
        // $staff = controller('crm/Customer','lib')->get_staff_list(['shop_code'=>session('shop_code')]);belong_shop_code
        $this->assign('staff',$staff);
        /*
        //部门
                $department = controller('crm/Setting','lib')->get_department_list();
                $this->assign('department',$department);
                //岗位
                $position = controller('crm/Setting','lib')->get_position_list(['shop_code'=>session('shop_code')]);
                $this->assign('position',$position);
                //小组列表
                $group_list = controller('crm/Setting','lib')->getGroupList();
                $this->assign('group_list',$group_list);
        */

        //获取渠道
        //$qudao = controller('crm/Setting','lib')->getQudao();
        //$this->assign('qudao',$qudao);
        //部门
        $dParam['shop_code'] = $res['belong_shop_code'];
        $department = controller('crm/Setting','lib')->get_department_list($dParam);
        // var_dump($department);exit;
        $this->assign('department',$department);
        //岗位
        $pParam['shop_code'] = $res['belong_shop_code'];
        $position = controller('crm/Setting','lib')->get_position_list($pParam);
        $this->assign('position',$position);
        //获取员工小组列表
        $gParam['shop_code'] = $res['belong_shop_code'];
        // $group = controller('crm/Setting','lib')->getGroupList($gParam);
        $this->assign('group',$group);
        // $tar = new \app\crm\lib\Target();
        $target = array(
            [
                'id'=>  'inviteIntoCustomerNumber',
                'name'=> '邀约进店客资量'
            ],
            [
                'id'=>  'actualIntoCustomerNumber',
                'name'=> '实际进店客资量'
            ],
            [
                'id'=>  'orderNumber',
                'name'=> '成交量'
            ],
            [
                'id'=>  'telVisitNumber',
                'name'=> '电访量'
            ],
            [
                'id'=>  'orderValueRate',
                'name'=> '订单转换率'
            ],
            [
                'id'=>  'intoValueRate',
                'name'=> '进店转换率'
            ],
            [
                'id'=>  'dealAmount',
                'name'=> '成交金额'
            ],
            [
                'id'=>  'ACustomerRate',
                'name'=> 'A客转换率'
            ],
        );
        // $ap = $tar->getAllTarget();
        $this->assign('ap',$target);
        return $this->fetch();
    }
    /**
     * @cc 添加默认规则
     * */
    public function addDefaultFPSet(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->addDefaultFPSet(input('post.'));
        return $res;
    }
    /**
     * @cc 上移规则
     * */
    public function upOrderSort(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->upOrderSort(input('post.'));
        return $res;
    }
    /**
     * @cc 下移规则
     * */
    public function downOrderSort(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->downOrderSort(input('post.'));
        return $res;
    }
    //渠道列表
    public function getcustomer_channel(){
        //获取渠道
        $qudao = controller('crm/Setting','lib')->getQudao();
        return json_encode($qudao);
    }
    public function getCustomerConditionData(){
        //获取所有应提报给我店客资的所有店列表
        $mcInterface = new mcInterface();
        $type = input('type');
        $temp[] = ['value'=>'0','text'=>'请选择','select'=>0];
        switch ($type) {
            case 'customer_channel':
                //点击渠道，获取店的列表。
                $addShoplist = $mcInterface->getAddcustomerShopList(session('shop_code'));
                // var_dump($addShoplist);exit;
                if($addShoplist === false){
                    $addShoplist[0]['shop_code'] = session('shop_code');
                    $addShoplist[0]['shop_name'] = session('shop_name');
                }
                foreach ((array)$addShoplist as $key => $value) {
                    # 在循环店时，如果有某个店的渠道，是当前已选择的渠道的店时，店默认选中，并记下标记
                    # 因为如果调整了，有可能所选渠道不在提报给我的店列表内，后面不能显示渠道列表，而是让用户重选店。

                    $temp[] = ['value'=>$value['shop_code'],'text'=>$value['shop_name'],'select'=>0,'title'=>'channelshoplist'];
                }
                break;
            case 'customer_source':
                $customerResource = $mcInterface->getCustomerResource();
                if($customerResource === false){
                    break;
                }
                foreach ($customerResource as $key => $value) {
                    $temp[] = ['value'=>$value['id'],'text'=>$value['cus_name'],'select'=>0];
                }
                break;
            case 'customer_area':
                $customerArea = $mcInterface->getCustomerArea();
                if($customerArea === false){
                    break;
                }
                foreach ($customerArea as $key => $value) {
                    $temp[] = ['value'=>$value['id'],'text'=>$value['area_name'],'select'=>0];
                }
                break;
            case 'customer_region':
                $customerRegin = $mcInterface->getCustomerRegin();
                if($customerRegin === false){
                    break;
                }
                foreach ($customerRegin as $key => $value) {
                    $temp[] = ['value'=>$value['id'],'text'=>$value['region_name'],'title'=>'region','select'=>0];
                }
                break;
            case 'channelshoplist':
                //下拉渠道门店选择时，获取此店下的所有门店
                $channelList = controller('crm/Setting','lib')->getQudao(input('shop_code'));
                if($channelList === false){
                    break;
                }
                foreach ($channelList as $key => $value) {
                    $temp[] = ['value'=>$value['id'],'text'=>$value['channel_name'],'select'=>0,'title'=>'channellist'];
                }
                break;
            case 'add_organize':
                //按提报员工，获取门店列表让员工选
                $shopList = $mcInterface->getBrandShopList(session('brandclass'));
                if($shopList === false){
                    break;
                }
                $temp = null;
                $temp[] = ['value'=>'0','text'=>'请选择店','select'=>0];
                foreach ($shopList as $key => $value) {
                    $temp[] = ['value'=>$value['shop_code'],'text'=>$value['shop_name'],'select'=>0,'title'=>'staffshoplist'];
                }
                break;
            case 'staffshoplist':
                //按提报员工，选了门店后，出部门列表,或店下的员工。
                $departmentList = $mcInterface->getDepartmentByShopcode(input('shop_code'));
                if($departmentList === false){
                    break;
                }
                $temp = null;
                $temp[] = ['value'=>'0','text'=>'请选择部门','select'=>0];
                foreach ($departmentList as $key => $value) {
                    $temp[] = ['value'=>$value['id'],'text'=>$value['department_name'],'select'=>0,'title'=>'staffdepartmentlist'];
                }
                /*
                $staffList = $mcInterface->getStaffListByShopcode(input('shop_code'));
                $tempstaff[] = ['value'=>'0','text'=>'请选择员工','select'=>0];
                foreach ($staffList as $key => $value) {
                    $tempstaff[] = ['value'=>$value['shop_code'],'text'=>$value['staffname'],'select'=>0,'title'=>'stafflist'];
                }
                */
                //$temp = ['dep_list'=>$tempdep,'staff_list'=>$tempstaff];
                break;
            case 'staffdepartmentlist':
                $staffList = $mcInterface->getStaffListByDepartmentId(input('department_id'));
                if($staffList === false){
                    break;
                }
                $temp = null;
                $temp[] = ['value'=>'0','text'=>'请选择员工','select'=>0];
                foreach ($staffList as $key => $value) {
                    $temp[] = ['value'=>$value['id'],'text'=>$value['staffname'],'select'=>0,'title'=>'stafflist'];
                }
                break;
            case 'region':
                $provinceList = controller('crm/Customer','lib')->address(['type'=>1,'pid'=>input('region')]);
                if($provinceList === false){
                    break;
                }
                $temp = null;
                $temp[] = ['value'=>'0','text'=>'请选择省份','select'=>0];
                foreach ($provinceList as $key => $value) {
                    $temp[] = ['value'=>$value['id'],'text'=>$value['name'],'select'=>0,'title'=>'provincelist'];
                }
                break;
            case 'province':
                $provinceList = controller('crm/Customer','lib')->address(['type'=>2,'pid'=>input('province_id')]);
                if($provinceList === false){
                    break;
                }
                $temp = null;
                $temp[] = ['value'=>'0','text'=>'请选择城市','select'=>0];
                foreach ($provinceList as $key => $value) {
                    $temp[] = ['value'=>$value['id'],'text'=>$value['name'],'select'=>0,'title'=>'citylist'];
                }
                break;
            default:
                $temp = ['error'=>1,'msg'=>'不支持的方法。'];
                break;
        }

        return json($temp);
    }
    //来源列表
    public function getcustomer_source(){
        //获取渠道
        $cource = controller('crm/Setting','lib')->getcustomer_cource();
        return json_encode($cource);
    }
    //地域列表
    public function getcustomer_region(){
        //获取渠道
        $region = controller('crm/Setting','lib')->getcustomer_region();
        return json_encode($region);
    }
    //分区列表
    public function getcustomer_area(){
        //获取渠道
        $area = controller('crm/Setting','lib')->getcustomer_area();
        return json_encode($area);
    }
    //部门列表  20200813
    public function getdepartment_name(){
        $param = input('post.');
        $area = controller('crm/Setting','lib')->getdepartment($param);
        return json_encode($area);
    }
    //岗位列表
    public function getposition_name(){
        $param = input('post.');
        $area = controller('crm/Setting','lib')->getposition($param);
        return json_encode($area);
    }
    //小组列表
    public function getgroup_name(){
        $param = input('post.');
        $area = controller('crm/Setting','lib')->getGroupList($param);
        return json_encode($area);
    }
    //人员列表
    public function getstaff_name(){
        $param = input('post.');
        $shop_code = $param['shop_code'] ? $param['shop_code'] : session('shop_code');
        $all = controller('crm/Customer','lib')->get_staff_list(['shop_code'=>$shop_code]);
        // var_dump($all);
        return json_encode($all);
    }
    //员工搜索
    public function searchStaff(){
        $key_words = input('param.key_words');
        $data = array(
            'key_words'=>$key_words,
            'shop_code'=>session('shop_code')
        );
        $data['get_leave'] = 2;
        // $url = '5aec138a7bae9';
        // $info = sx_call($url,$data);
        $mc = new \app\common\lib\mcInterface();
        $info = $mc->searchStaff($data);

        if($info !== false){
            return array('code'=>200,'data'=>$info);
        }else{
            return array('code'=>100,'msg'=>'未查询到数据','data'=>'');
        }
    }
    public function searchStaffGroup(){
        $key_words = input('param.key_words');
        $params = array(
            'key_words'=>$key_words,
            'shop_code'=>session('shop_code')
        );
        $params['get_leave'] = 2;
        // $url = '5aec138a7bae9';
        // $info = sx_call($url,$data);
        $mc = new \app\common\lib\mcInterface();
        $info = $mc->searchStaff($params);

        if($info !== false){
            $data = $info;
            $ids = array_column($data,'id');
            // 0609
            $groupInfo = db('c_staff_group_relation')->alias('r')->join('c_staff_group g','g.id=r.group_id')
                        ->where('r.staff_id','in',$ids)
                        ->group('r.staff_id')
                        ->column('g.group_name,r.staff_name,r.staff_id,g.shop_name','r.staff_id');
            $inGroup = [];
            $noGroup = [];
            foreach($data as $k=>$v){
                if(!empty($groupInfo[$v['id']])){
                    $inGroup[] = $groupInfo[$v['id']];
                }else{
                    $noGroup[] = [
                      'id'=>$v['id'],
                      'staffname'=>$v['staffname'],
                    ];
                }
            }
            return array('code'=>200,'inGroup'=>$inGroup,'noGroup'=>$noGroup);
        }else{
            return array('code'=>100,'msg'=>'未查询到数据','data'=>'');
        }
    }
    //分配设定列表
    public function FPListJSON(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->FPListJSON();
        return json($res);
    }
    /**
     * @cc 增加分配规则
     * */
    public function addFPSet(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        // var_dump(input('post.'));exit;
        return controller('crm/Setting','lib')->addFPSet(input('post.'));
       // return $this->fetch('fpSet');
    }
    /**
     * @cc 删除分配规则
     * */
    public function delFPSet(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->delFPSet(input('post.id'));
        return $res;
    }
    //客资提醒设定
    public function remindSet()
    {
        // 权限
        $auth = check_right('menu1512028590');
        if (!$auth) {
            return $this->redirect('/');
        }
        $remind1 = controller('crm/Setting','lib')->remindList1();
        $this->assign('remind1',$remind1);
        $remind2 = controller('crm/Setting','lib')->remindList2();
        $this->assign('remind2',$remind2);
        $remind3 = controller('crm/Setting','lib')->remindList3();
        $this->assign('remind3',$remind3);
        $next_before_minute = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','next_before_minute')->find();
        $this->assign('next_before_minute',$next_before_minute);
        $yyjd_before_minute = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','yyjd_before_minute')->find();
        $this->assign('yyjd_before_minute',$yyjd_before_minute);
        $yyjd_after_minute = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','yyjd_after_minute')->find();
        $this->assign('yyjd_after_minute',$yyjd_after_minute);
        //登录提醒
        $login = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','login')->find();
        if(!empty($login)){
            $login['send_method'] = explode(',',$login['send_method']);
        }
        //标记有效提醒
        $valid = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','valid')->find();
        if(!empty($valid)){
            $valid['send_method'] = explode(',',$valid['send_method']);
        }
        if(!empty($valid)){
            $valid['send_receive'] = explode(',',$valid['send_receive']);
        }
        $this->assign('valid',$valid);
        //驳回提醒
        $bh = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','bh')->find();
        if(!empty($bh)){
            $bh['send_method'] = explode(',',$bh['send_method']);
        }
        if(!empty($bh)){
            $bh['send_receive'] = explode(',',$bh['send_receive']);
        }
        //反驳回提醒
        $fbh = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','fbh')->find();
        if(!empty($fbh)){
            $fbh['send_method'] = explode(',',$fbh['send_method']);
        }
        if(!empty($fbh)){
            $fbh['send_receive'] = explode(',',$fbh['send_receive']);
        }
        //手动分配提醒
        $sd = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','sd')->find();
        if(!empty($sd)){
            $sd['send_method'] = explode(',',$sd['send_method']);
        }
        if(!empty($sd)){
            $sd['send_receive'] = explode(',',$sd['send_receive']);
        }
        //自动分配提醒
        $auto = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','auto')->find();
        if(!empty($auto)){
            $auto['send_method'] = explode(',',$auto['send_method']);
        }
        if(!empty($auto)){
            $auto['send_receive'] = explode(',',$auto['send_receive']);
        }
        //进店提醒
        $jd = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','jd')->find();
        if(!empty($jd)){
            $jd['send_method'] = explode(',',$jd['send_method']);
        }
        if(!empty($jd)){
            $jd['send_receive'] = explode(',',$jd['send_receive']);
        }
        //订单提醒
        $order = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','order')->find();
        if(!empty($order)){
            $order['send_method'] = explode(',',$order['send_method']);
        }
        if(!empty($order)){
            $order['send_receive'] = explode(',',$order['send_receive']);
        }
        if(session('shop_type') == 2){
            //宝宝生日提醒
            $bb_birthday = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','bb_birthday')->find();
            if(!empty($bb_birthday)){
                $bb_birthday['send_method'] = explode(',',$bb_birthday['send_method']);
            }
            if(!empty($bb_birthday)){
                $bb_birthday['send_receive'] = explode(',',$bb_birthday['send_receive']);
            }
            //预产期提醒
            $ready = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','ready')->find();
            if(!empty($ready)){
                $ready['send_method'] = explode(',',$ready['send_method']);
            }
            if(!empty($ready)){
                $ready['send_receive'] = explode(',',$ready['send_receive']);
            }
        }
        //结婚纪念日提醒
        $marry = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','marry')->find();
        if(!empty($marry)){
            $marry['send_method'] = explode(',',$marry['send_method']);
        }
        if(!empty($marry)){
            $marry['send_receive'] = explode(',',$marry['send_receive']);
        }
        //客户生日提醒
        $c_birthday = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','c_birthday')->find();
        if(!empty($c_birthday)){
            $c_birthday['send_method'] = explode(',',$c_birthday['send_method']);
        }
        if(!empty($c_birthday)){
            $c_birthday['send_receive'] = explode(',',$c_birthday['send_receive']);
        }
        //配偶提醒
        $m_birthday = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','m_birthday')->find();
        if(!empty($m_birthday)){
            $m_birthday['send_method'] = explode(',',$m_birthday['send_method']);
        }
        if(!empty($m_birthday)){
            $m_birthday['send_receive'] = explode(',',$m_birthday['send_receive']);
        }
        //登记人客资被分配提醒
        $c_allocation = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','c_allocation')->find();
        if(!empty($c_allocation)){
            $c_allocation['send_method'] = explode(',',$c_allocation['send_method']);
        }
        if(!empty($c_allocation)){
            $c_allocation['send_receive'] = explode(',',$c_allocation['send_receive']);
        }
        //追踪人客资被转走提醒
        $c_transfer = db('crm_s_reminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','c_transfer')->find();
        if(!empty($c_transfer)){
            $c_transfer['send_method'] = explode(',',$c_transfer['send_method']);
        }
        if(!empty($c_transfer)){
            $c_transfer['send_receive'] = explode(',',$c_transfer['send_receive']);
        }

        $this->assign('c_transfer',$c_transfer);
        $this->assign('c_allocation',$c_allocation);
        $this->assign('login',$login);
        $this->assign('valid',$valid);
        $this->assign('bh',$bh);
        $this->assign('fbh',$fbh);
        $this->assign('sd',$sd);
        $this->assign('auto',$auto);
        $this->assign('jd',$jd);
        $this->assign('order',$order);
        $this->assign('bb_birthday',$bb_birthday);
        $this->assign('ready',$ready);
        $this->assign('marry',$marry);
        $this->assign('c_birthday',$c_birthday);
        $this->assign('m_birthday',$m_birthday);
        $this->assign('title','客资提醒设定');
        return $this->fetch();
    }
    /**
     * @cc 提醒快捷开关
     * */
    public function remindSwitch(){
        // 权限
        $auth = check_right('menu1512028590');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->remindSwitch(input('post.'));
        return $res;
    }
    //客资提醒查询
    public function editRemind()
    {
        // 权限
        $auth = check_right('menu1512028590');
        if (!$auth) {
            return $this->redirect('/');
        }
        controller('crm/Setting','lib')->editRemind(input('post.'));
        $this->redirect('remindSet');
    }
    /**
     * @cc 客资提醒删除
     * */
    public function delRemind()
    {
        // 权限
        $auth = check_right('menu1512028590');
        if (!$auth) {
            return $this->redirect('/');
        }
        $remind = controller('crm/Setting','lib')->delRemind(input('post.id'));
        return $remind;
    }
    /**
     * @cc 客资提醒添加
     * */
    public function remindAdd(){
        // 权限
        $auth = check_right('menu1512028590');
        if (!$auth) {
            return $this->redirect('/');
        }
        $param = input('post.');
        $res = controller('crm/Setting','lib')->remindAdd($param);
        return $res;
    }
    // 渠道返点设定
    public function setRebates(){
        $param = input('');
        if(!$param['ids']){
            return json(['code'=>202,'msg'=>'请选择渠道']);
        }
        if(!$param['start']){
            return json(['code'=>202,'msg'=>'开始时间不能为空']);
        }
        if(!$param['end']){
            return json(['code'=>202,'msg'=>'结束时间不能为空']);
        }
        if(!$param['rebates'] && $param['rebates'] != 0){
            return json(['code'=>202,'msg'=>'利率不能为空']);
        }

        db()->startTrans();
        try {
            foreach ($param['ids'] as $key => $value) {
                if($value['id']){
                    db('crm_s_channel')->where("id",$value['id'])->update(['rebates'=>$param['rebates'],'rebates_start_time'=>$param['start'],'rebates_end_time'=>$param['end']]);
                    $log = '【'.session('staff_name').'】 于'.date('Y-m-d H:i:s',time()).' 设置渠道ID为：【'.$value['id'].'】，利率开始时间为【'.$param['start'].'】，利率结束时间为【'.$param['end'].'】利率为【'.$param['rebates'].'】';
                    action_log($log,[]);
                }
            }
            db()->commit();
            return json(['code'=>200,'msg'=>'设置成功']);
        } catch (Exception $e) {
            db()->rollback();
            return json(['code'=>202,'msg'=>'设置失败！','data'=>$e->getMessage()]);
        }
    }
    /**
     * @cc渠道花费设定
     * 针对于每家设置不一样的情况下，标准版可以做成多个方法，然后在客户菜单的配置好
     * 也不会影响后续升级
     * 此版作为标准版，以桔子为标准，后续如果有不能兼容的，增加方法名如：channelFeeLuoma()
     * @return [type] [description]
     * @author songdemei <songdemei@suxuantech.cn>
     */
    public function channelFee(){
        $auth = check_right('menu1512650793');
        if(\think\Request::instance()->isAjax() || input('export') == 1){
            $ret = [
                'code'=>0,
                'msg'=>'',
                'data'=>'',
            ];
            if(!$auth){
                $ret['code'] = 1;
                $ret['msg'] = '您没有权限进行操作。';
                return $ret;
            }
            //保存
            $input = input('param.');
            //AJAX操作 列表编辑
            if($input['edit']){
                $search_date = $input['search_date'];
                $province_id = $input['province_id'] ? $input['province_id'] : 0;
                $city_id = $input['city_id'] ? $input['city_id'] : 0;
                $department_id = $input['department_id']? $input['department_id']:0;
                $province_name = $input['province_name'] ? $input['province_name'] : null;
                $city_name = $input['city_name'] ? $input['city_name'] : null;
                $department_name = $input['department_name']? $input['department_name']:null;
                $channel_id = $input['channel_id'] ? $input['channel_id'] : 0;

                $belong_shop_code = $input['belong_shop_code'] ? $input['belong_shop_code'] : NULL;
                $belong_shop_name = $input['belong_shop_name'] ? $input['belong_shop_name'] : NULL;

                if(empty($channel_id)){
                    $ret['code'] = 1;
                    $ret['msg'] = '未获取到渠道ID';
                    return $ret;
                }
                $cost = $input['cost']? $input['cost']:0;
                $day = trim($input['day'],'cost_');
                if(empty($day)){
                    $ret['code'] = 1;
                    $ret['msg'] = '未获取要修改的时间';
                    return $ret;
                }
                $costDate = substr($search_date, 0,4).'-'.substr($search_date, 4,2).'-'.sprintf("%02d", $day).' 00:00:00';

                /**
                 * TODO:
                 *
                 * 1.对日期进行验证，查看是否允许添加此日期的
                 * 2.看城市和部门有没有传，如查传了，就保存成城市和部门的花费，如果没传，城市和部门设置为null，表示不按城市或部门进行设置
                 * 3.取相同条件的花费，看表里有没有，如果有，则更新cost字段。如果没有，添加一条。
                 */
                $data['province_id'] = $province_id ? $province_id : 0;
                $data['province_name'] = $province_name ? $province_name : null;
                $data['city_id'] = $city_id ? $city_id : 0;
                $data['city_name'] = $city_name ? $city_name : null;
                $data['department_id'] = $department_id ? $department_id : 0;
                $data['department_name'] = $department_name ? $department_name : null;
                $data['channel_id'] = $channel_id;
                $data['belong_shop_code'] = $belong_shop_code ? $belong_shop_code : null;
                $data['belong_shop_name'] = $belong_shop_name ? $belong_shop_name : null;
                if($day < 10){
                    $day = '0'.$day;
                }
                $cost_date = date('Y-m-d',strtotime($search_date.$day));
                $cost = $input['cost'];
                $channelInfo = db('crm_s_channel')->where('id',$channel_id)->where("find_in_set('".session('shop_code')."',share_shops)")->find();

                $res = db('crm_s_channel_cost')->where('department_id',$data['department_id'])->where('channel_id', $data['channel_id'])->where('city_id',$data['city_id'])->where('province_id',$data['province_id'])->where('brandclass_id', session('brandclass_id'))->where('shop_code',session('shop_code'))->where('cost_date', $cost_date)->where('belong_shop_code', $data['belong_shop_code'])->find();
                db()->startTrans();
                try{
                    if(!empty($res)){//修改
                        $up = array(
                            'update_time'=>date('Y-m-d H:i:s'),
                            'cost'=>$cost,
                            'cost_date'=>$cost_date
                        );
                        $update = array(
                            'cost_avg'=>$cost,
                            'cost_time'=>$cost_date
                        );
                        //修改花费时间  默认7天
                        $a = db_config('accounting_channel_cost_'.session('shop_code'));
                        $edit_default = $a ? $a : 7;

                        if(strtotime($res['create_time'])+$edit_default*86400 < time()){
                            $ret['code'] = 3;
                            $ret['msg'] = '修改失败,已超过最大编辑时限!';
                            return $ret;
                        }
                        db('crm_s_channel_cost')->where('department_id',$data['department_id'])->where('channel_id', $data['channel_id'])->where('city_id',$data['city_id'])->where('province_id',$data['province_id'])->where('brandclass_id', session('brandclass_id'))->where('cost_date', $cost_date)->where('belong_shop_code', $data['belong_shop_code'])->update($up);
                        db('crm_c_customer_cost')->where('channel_id', $data['channel_id'])->where('city_id',$data['city_id'])->where('province_id',$data['province_id'])->where('brandclass_id', session('brandclass_id'))->where('shop_code',session('shop_code'))->where('cost_time', $cost_date)->where('belong_shop_code', $data['belong_shop_code'])->update($update);
                        $old = '';
                        $old .= '操作店面：'.$res['shop_name'].'<br/>';
                        if($res['belong_shop_name'])$old .= '归属店：'.$res['belong_shop_name'].'<br/>';
                        if($res['department_name'])$old .= '部门：'.$res['department_name'].'<br/>';
                        if($res['region_name'])$old .= '地域：'.$res['region_name'].'<br/>';
                        if($res['province_name'])$old .= '省：'.$res['province_name'].'<br/>';
                        if($res['city_name'])$old .= '市：'.$res['city_name'].'<br/>';
                        $old .= '渠道：'.$res['channel_name'].'<br/>';
                        $old .= '花费：'.$res['cost'].'<br/>';
                        $old .= '日期：'.$res['cost_date'].'<br/>';

                        $new = '';
                        $new .= '操作店面：'.$res['shop_name'].'<br/>';
                        if($res['belong_shop_name'])$new .= '归属店：'.$res['belong_shop_name'].'<br/>';
                        if($res['department_name'])$new .= '部门：'.$res['department_name'].'<br/>';
                        if($res['region_name'])$new .= '地域：'.$res['region_name'].'<br/>';
                        if($res['province_name'])$new .= '省：'.$res['province_name'].'<br/>';
                        if($res['city_name'])$new .= '市：'.$res['city_name'].'<br/>';
                        $new .= '渠道：'.$res['channel_name'].'<br/>';
                        $new .= '花费：'.$cost.'<br/>';
                        $new .= '日期：'.$cost_date.'<br/>';

                        action_log($new,$old,0,session('staff_id'),session('staff_name'));
                    }else{//新增
                        //录入花费时间  默认7天
                        $b = db_config('accounting_channel_cost_'.session('shop_code'));
                        $insert_default = $b ? $b : 7;
                        if(strtotime($cost_date)+$insert_default*86400 < time()){
                            $ret['code'] = 3;
                            $ret['msg'] = '添加失败,已超过最大添加时限!';
                            return $ret;
                        }
                        $ins = array(
                            'shop_code'=>session('shop_code'),
                            'shop_name'=>session('shop_name'),
                            'channel_class_id'=>$channelInfo['channel_class_id'],
                            'channel_class_name'=>$channelInfo['channel_class_name'],
                            'channel_info_id'=>$channelInfo['channel_info_id'],
                            'channel_info_name'=>$channelInfo['channel_info_name'],
                            'channel_id'=>$data['channel_id'],
                            'channel_name'=>$channelInfo['channel_name'],
                            'province_id' => $data['province_id'],
                            'province_name' => $data['province_name'],
                            'city_id' => $data['city_id'],
                            'city_name' => $data['city_name'],
                            'department_id' => $data['department_id'],
                            'department_name' => $data['department_name'],
                            'brandclass_id'=>session('brandclass_id'),
                            'create_time'=>date('Y-m-d H:i:s'),
                            'cost'=>$cost,
                            'cost_date'=>$cost_date,
                            'belong_shop_code'=>$data['belong_shop_code'],
                            'belong_shop_name'=>$data['belong_shop_name'],
                        );
                        $insert = array(
                            'shop_code'=>session('shop_code'),
                            'channel_class_id'=>$channelInfo['channel_class_id'],
                            'channel_class_name'=>$channelInfo['channel_class_name'],
                            'channel_info_id'=>$channelInfo['channel_info_id'],
                            'channel_info_name'=>$channelInfo['channel_info_name'],
                            'channel_id'=>$data['channel_id'],
                            'channel_name'=>$channelInfo['channel_name'],
                            'region_id'=>$data['region_id'],
                            'region_name'=>$data['region_name'],
                            'province_id' => $data['province_id'],
                            'province_name' => $data['province_name'],
                            'city_id' => $data['city_id'],
                            'city_name' => $data['city_name'],
                            'brandclass_id'=>session('brandclass_id'),
                            'cost_time'=>$cost_date,
                            'cost_avg'=>$cost,
                            'belong_shop_code'=>$data['belong_shop_code'],
                            'belong_shop_name'=>$data['belong_shop_name'],
                        );

                        if(!empty($data['province_id'])){
                            $region = controller("Customer","lib")->getRegionByProvinceId(['id'=>$data['province_id']]);
                            $ins['region_id'] = $region['id'];
                            $ins['region_name'] = $region['region_name'];
                            $insert['region_id'] = $region['id'];
                            $insert['region_name'] = $region['region_name'];
                        }
                        db('crm_s_channel_cost')->insert($ins);

                        db('crm_c_customer_cost')->insert($insert);
                        $new = '';
                        $new .= '操作店面：'.$ins['shop_name'].'<br/>';
                        if($ins['belong_shop_name'])$new .= '归属店：'.$ins['belong_shop_name'].'<br/>';
                        if($ins['department_name'])$new .= '部门：'.$ins['department_name'].'<br/>';
                        if($ins['region_name'])$new .= '地域：'.$ins['region_name'].'<br/>';
                        if($ins['province_name'])$new .= '省：'.$ins['province_name'].'<br/>';
                        if($ins['city_name'])$new .= '市：'.$ins['city_name'].'<br/>';
                        $new .= '渠道：'.$ins['channel_name'].'<br/>';
                        $new .= '花费：'.$ins['cost'].'<br/>';
                        $new .= '日期：'.$ins['cost_date'].'<br/>';
                        action_log($new,[],0,session('staff_id'),session('staff_name'));
                    }
                    db()->commit();
                    $ret['code'] = 200;
                    $ret['msg'] = '操作成功';
                    return $ret;
                }catch (\Exception $e){
                    db()->rollback();
                    $ret['code'] = 2;
                    $ret['msg'] = '操作失败';
                    $ret['data'] = $e->getMessage();
                    return $ret;
                }
            }else{
                //列表、导出
                //修改花费时间  默认7天
                $a = db_config('accounting_channel_cost_'.session('shop_code'));
                $editDay = $a ? $a : 7;//TODO:最多可以修改最近几天的数据，默认1天，要按店做成系统配置，
                //另外，如何动态控制table 的可编辑单元格，需要研究一下。
                $departmentId = input('param.department_id');
                $cityId = input('param.city_id');
                $provinceId = input('param.province_id');
                $belong_shop_code = input('param.belong_shop_code');
                $is_rebates = input('is_rebates');
                $where = [];
                $sql = ' 1=1 ';
                if($departmentId){
                    $where['department_id'] = $departmentId;
                }else{
                    $sql .= ' and (department_id=0 or department_id is null) ';
                }
                if($provinceId){
                    $where['province_id'] = $provinceId;
                }else{
                    $sql .= ' and (province_id=0 or province_id is null) ';
                }
                if($cityId){
                    $where['city_id'] = $cityId;
                }else{
                    $sql .= ' and (city_id=0 or city_id is null) ';
                }
                if($belong_shop_code){
                    $where['belong_shop_code'] = $belong_shop_code;
                }else{
                    $sql .= ' and (belong_shop_code="" or belong_shop_code is null) ';
                }
                $month = input('param.search_date');
                $month = $month?$month:date('Ym');
                $start = substr($month, 0,4).'-'.substr($month, 4,2).'-01 00:00:00';
                $end = date('Y-m-d H:i:s',strtotime('+1 month',strtotime($start)) - 1);

                if(input('param.channel_name')){
                    $channel_name = explode(',',trim(input('param.channel_name')));
                }

                if(!empty($channel_name)){
                    // $channelList = db('crm_s_channel')->where('shop_code',session('shop_code'))->order('order_sort')->where('channel_name','in',$channel_name)->select();
                    $channelList = $channels = db('crm_s_channel')->where('channel_name', 'in' ,$channel_name)->order('order_sort asc')->select();
                }else{
                    $channelList = controller('crm/Customer', 'lib')->getChannel(session('shop_code'));
                    // $channelList = db('crm_s_channel')->where('shop_code',session('shop_code'))->order('order_sort')->select();
                }
                $data = [];
                $arr = [];
                $total = 0;
                foreach($channelList as $channel) {
                    $data[$channel['id']]['channel_name_show'] = $channel['channel_class_name'].'->'.$channel['channel_info_name'].'->'.$channel['channel_name'];
                    $data[$channel['id']]['channel_id'] = $channel['id'];
                    // 返点比例
                    $data[$channel['id']]['rebates'] = $channel['rebates'] ? $channel['rebates'] : 0;
                    // 返点设置开始结束时间
                    $data[$channel['id']]['rebates_start_time'] = $channel['rebates_start_time'] ? date('Y-m-d', strtotime($channel['rebates_start_time'])) : '';
                    $data[$channel['id']]['rebates_end_time'] = $channel['rebates_end_time'] ? date('Y-m-d', strtotime($channel['rebates_end_time'])) :'';
                }

                if(!empty($channel_name)){
                    $res = db('crm_s_channelCost')->where('shop_code',session('shop_code'))->where($where)->where('channel_name','in',$channel_name)->where('cost_date','between',[$start,$end])->where($sql)->order('cost_date desc')->select();
                }else{
                    $res = db('crm_s_channelCost')->where('shop_code',session('shop_code'))->where($where)->where('cost_date','between',[$start,$end])->where($sql)->order('cost_date desc')->select();
                }
                // 查看返点时 只看返点金额，不看输入金额
                $nolyShowRebates = db_config('noly_show_rebates'.session('brandclass_id'));
                
                $arr['channel_name_show'] = '总计';

                foreach ($res as $key => $value) {
                    $day = intval(substr($value['cost_date'], 8,2));
                    // $data[$value['channel_id']] = [
                    //     'channel_name_show' => $value['channel_class_name'].'->'.$value['channel_info_name'].'->'.$value['channel_name'],
                    //     'cost_'.$day=>sprintf('%.2f',$value['cost']),
                    //     'channel_id'=>$value['channel_id'],
                    // ];
                    $data[$value['channel_id']]['channel_name_show'] = $value['channel_class_name'].'->'.$value['channel_info_name'].'->'.$value['channel_name'];
                    if($is_rebates == 1){
                        $rebates = 0;
                        if ($data[$value['channel_id']]['rebates_start_time']<= $value['cost_date'] && $data[$value['channel_id']]['rebates_end_time']>=$value['cost_date'] && $data[$value['channel_id']]['rebates']>0) {
                            $rebates = $value['cost'] ? sprintf( "%.4f", $value['cost']/(1+($data[$value['channel_id']]['rebates']/100)) ) : 0;
                        }else{
                            $rebates = $value['cost'];
                        }
                        if ($nolyShowRebates==1) {
                            $data[$value['channel_id']]['cost_'.$day] = $rebates;
                            $data[$value['channel_id']]['input_total'] += $rebates;
                        }else{
                            $data[$value['channel_id']]['cost_'.$day] = sprintf('%.2f',$value['cost']).'/'.$rebates;
                            $data[$value['channel_id']]['input_total'] += $rebates;
                        }
                    }else{
                        $data[$value['channel_id']]['cost_'.$day] = sprintf('%.2f',$value['cost']);
                    }
                    // $data[$value['channel_id']]['cost_'.$day] = sprintf('%.2f',$value['cost']);
                    $data[$value['channel_id']]['channel_id'] = $value['channel_id'];
                    if((strtotime($value['create_time']))+($editDay*86400) < time()){
                        //xx天可以修改
                        $data[$value['channel_id']]['text-'.$day] = 0;
                    }else{
                        $data[$value['channel_id']]['text-'.$day] = 1;
                    }
                    // 横向总计
                    $data[$value['channel_id']]['total'] += $value['cost'];
                    // 纵向总计
                    $arr['cost_'.$day] += $value['cost'];
                    $arr['total'] += $value['cost'];
                    $arr['input_cost_total'] += $rebates;
                    $arr['cost'][$day] += $value['cost'];
                    $arr['input_cost'][$day] += $rebates;;
                }
                // var_dump($arr);die;
                $day = 1;
                $endDay = intval(substr($end, 8,2));
                if($is_rebates == 1){
                    // 横向总计
                    foreach ($data as $key => $value) {
                        if ($nolyShowRebates==1) {
                            $data[$key]['total'] = $value['input_total'];
                        }else{
                            $data[$key]['total'] = $value['total'].'/'.$value['input_total'];
                        }
                    }
                    // 纵向总计
                    $arrArr = [];
                    $arrArr['channel_name_show'] = '总计';
                    foreach($arr['cost'] as $k2=>$v2){
                        if ($nolyShowRebates==1) {
                            $arrArr['cost_'.$k2] = $arr['input_cost'][$k2];
                        }else{
                            $arrArr['cost_'.$k2] = $v2.'/'.$arr['input_cost'][$k2];
                        }
                    }
                    if ($nolyShowRebates==1) {
                        $arrArr['total'] = $arr['input_cost_total'];
                    }else{
                        $arrArr['total'] = $arr['total'].'/'.$arr['input_cost_total'];
                    }
                    $data[] = $arrArr;
                }else{
                    $data[] = $arr;
                }
                /*
                while ($day <= $endDay ) {
                    $dayArr[$day] = substr($end, 8,2);
                    $day++;
                }
                */
                // print_r($data);exit;
                if(input('export')){
                    //导出
                    $this->exportChannelFee($data,$start,$end);
                    die;
                }

                $ret['data'] = array_values($data);
                return $ret;
            }
            die;
        }
        //非ajax操作
        if (!$auth) {
            return $this->redirect('/');
        }
        // 如果session里没有shop_code
        if (!session('shop_code')) {
            $shops = [];
            // 20200418
            $mc = new mcInterface();
            $mcParam['staff_id'] = session('staff_id');
            // 如果有事业部 根据事业部查该员工在该事业部下的可操作店
            if (session('brandclass_id')) {
                $mcParam['brandclass_id'] = session('brandclass_id');
                $shops =  $mc->getWorkShop($mcParam);
            }else{
                $shops =  $mc->getWorkShop($mcParam);
            }
            $this->assign('shops',$shops);
        }
        //客资分区
        // $region=controller("crm/Setting","lib")->getcustomer_region();
        // $this->assign("region",$region);
        //部门信息
        $department = controller('crm/Setting','lib')->department_list(['shop_code'=>session('shop_code')]);
        $this->assign('dep',$department);

        $now = date('Y-m');
        for ($i=0; $i < 5; $i++) {
            if($i === 0){
                $timeList[] = [
                    'value' => date("Ym",strtotime("$now -$i month")),
                    'text'  => date("Y年m月",strtotime("$now -$i month")),
                    'select'=> 1,
                ];
            }else{
                $timeList[] = [
                    'value' => date("Ym",strtotime("$now -$i month")),
                    'text'  => date("Y年m月",strtotime("$now -$i month")),
                    'select'=> 0,
                ];
            }
        }
        $this->assign('timeList',$timeList);
        //来源渠道
        $channel = getChannelJson(session('shop_code'));
        $this->assign("channel", json_encode($channel));
        //维度
        $method = db_config('cost_method_'.session('shop_code'));
        if($method == 'belong' && (session('valid_date') == 0)){
            $array = [
                'brandclass_id' => session('brandclass_id'),
                'staff_id' => session('staff_id'),
                'shop_type' => session('shop_type'),
                'shop_code' => session('shop_code'),
                'belong_shop_code' => session('belong_shop_code'),
                'belong_shop_name' => session('belong_shop_name'),
            ];
            $belong = getBelongShop($array);
            $this->assign("belong",$belong);
        }else{
            $data = ['type'=>1];
            $address=controller("Customer","lib")->address($data);
            $this->assign("address",$address);
        }
        $this->assign('method',$method ? $method : 'region');
        return $this->fetch();
    }
    public function exportChannelFee($data,$start,$end){
        if(!$data || !$start || !$end){
            echo json(['code'=>401,'msg'=>'未找到任何花费数据']);
            die;
        }
        $daies = ceil((strtotime($end) - strtotime($start))/86400);
        $excelData = [];
        $header = ['渠道名称'];
        $body = [];
        $total = [];
        //处理数据
        foreach ($data as $key => $value) {
            //处理所有数据，
            $tmp[] = $value['channel_name_show'];
            $rowTotal = 0;
            for($i=1;$i<=$daies;$i++){
                $tmp[] = sprintf('%.2f',$value['cost_'.$i]);
                $rowTotal = $rowTotal + $value['cost_'.$i];
                $total[$i] = $total[$i] + $value['cost_'.$i];
            }
            $tmp[] = sprintf('%.2f',$rowTotal);
            $total['total'] = $total['total'] + $rowTotal;
            $body[] = $tmp;
            unset($tmp);
        }

        //处理总计
        //$tmp[] = "总计：";
        for($i=1;$i<=$daies;$i++){
            $header[] = $i.'日';
         //   $tmp[] = sprintf('%.2f',$total[$i]);
        }
       // $tmp[] = sprintf('%.2f',$total['total']);;
        //$body[] = $tmp;
        $header[] = '合计';
        //$excelData = array_unshift($body,$header);
        controller("crm/Customer", "lib")->export($header, $body, '花费数据'.'.xlsx');

        //var_dump($body);
    }
    //花费导出
    public function costExport(){
        $data = input();
        $departmentId = input('param.department_id');
        $cityId = input('param.city_id');
        $provinceId = input('param.province_id');
        $belong_shop_code = input('param.belong_shop_code');
        $where = [];
        $sql = ' 1=1 ';
        if($departmentId){
            $where['department_id'] = $departmentId;
        }else{
            $sql .= ' and (department_id=0 or department_id is null) ';
        }
        if($provinceId){
            $where['province_id'] = $provinceId;
        }else{
            $sql .= ' and (province_id=0 or province_id is null) ';
        }
        if($cityId){
            $where['city_id'] = $cityId;
        }else{
            $sql .= ' and (city_id=0 or city_id is null) ';
        }
        if($belong_shop_code){
            $where['belong_shop_code'] = $belong_shop_code;
        }else{
            $sql .= ' and (belong_shop_code="" or belong_shop_code is null) ';
        }
        $month = input('param.search_date');
        $month = $month?$month:date('Ym');
        $start = substr($month, 0,4).'-'.substr($month, 4,2).'-01 00:00:00';
        $end = date('Y-m-d H:i:s',strtotime('+1 month',strtotime($start)) - 1);
        $days = date('t',strtotime($data['search_date']));

        if(!empty($channel_name)){
            $channel_name = explode(',',$data['channel_name']);
            $res = db('crm_s_channelCost')->where('shop_code',session('shop_code'))->where($where)->where('channel_name','in',$channel_name)->where('cost_date','between',[$start,$end])->where($sql)->order('cost_date desc')->select();
        }else{
            $res = db('crm_s_channel_cost')->where('shop_code',session('shop_code'))->where($where)->where('cost_date','between',[$start,$end])->where($sql)->order('cost_date desc')->select();
        }
        $export = [];
        $arr = [];
        $arr['channel_name_show'] = '总计';
        for($i=1;$i<=$days;$i++){
            $arr['cost_'.$i] = '';
        }
        $arr['total'] = '';
        foreach ($res as $key => $value) {
            $day = intval(substr($value['cost_date'], 8,2));

            $export[$value['channel_id']]['channel_name_show'] = $value['channel_class_name'].'->'.$value['channel_info_name'].'->'.$value['channel_name'];
            for($i=1;$i<=$days;$i++){
                array_push($export[$value['channel_id']]['cost_'.$i],'');
            }
            $export[$value['channel_id']]['cost_'.$day] = $value['cost'] ? sprintf('%.2f',$value['cost']) : '';
            // $export[$value['channel_id']]['channel_id'] = $value['channel_id'];

            //纵向总计
            $export[$value['channel_id']]['total'] += $value['cost'];
            //横向总计
            $arr['cost_'.$day] += $value['cost'];
            $arr['total'] += $value['cost'];
        }
        if(!empty($channel_name)){
            $channelList = db('crm_s_channel')->where('shop_code',session('shop_code'))->where('order_sort')->where('channel_name','in',$channel_name)->select();
        }else{
            $channelList = db('crm_s_channel')->where('shop_code',session('shop_code'))->where('order_sort')->select();
        }
        foreach($channelList as $channel) {
            $export[$channel['id']]['channel_name_show'] = $channel['channel_class_name'].'->'.$channel['channel_info_name'].'->'.$channel['channel_name'];
            // $export[$channel['id']]['channel_id'] = $channel['id'];
        }
        $export[] = $arr;
        $title = ['渠道名称'];
        for($i=1;$i<=$days;$i++){
            array_push($title,$i.'日');
        }
        array_push($title,'总计');
        controller("crm/Customer", "lib")->export($title, $export, $data['search_date'].'花费导出'.'.xlsx');
    }
    public function channelFee_zjs(){
        $auth = check_right('menu1512650793');
        if(\think\Request::instance()->isAjax() || input('export') == 1){
            $ret = [
                'code'=>0,
                'msg'=>'',
                'data'=>'',
            ];
            if(!$auth){
                $ret['code'] = 1;
                $ret['msg'] = '您没有权限进行操作。';
                return $ret;
            }
            //保存
            $input = input('param.');
            //AJAX操作 列表编辑
            if($input['edit']){

                $search_date = $input['search_date'];

                $channel_id = $input['channel_id'] ? $input['channel_id'] : NULL;
                $channel_name = $input['channel_name'] ? $input['channel_name'] : NULL;
                $belong_shop_code = $input['belong_shop_code'] ? $input['belong_shop_code'] : NULL;
                $belong_shop_name = $input['belong_shop_name'] ? $input['belong_shop_name'] : NULL;

                if(empty($channel_id)){
                    $ret['code'] = 1;
                    $ret['msg'] = '未获取到部门ID';
                    return $ret;
                }
                $cost = $input['cost']? $input['cost']:0;
                $day = trim($input['day'],'cost_');
                if(empty($day)){
                    $ret['code'] = 1;
                    $ret['msg'] = '未获取要修改的时间';
                    return $ret;
                }
                $costDate = substr($search_date, 0,4).'-'.substr($search_date, 4,2).'-'.sprintf("%02d", $day).' 00:00:00';

                /**
                 * TODO:
                 *
                 * 1.对日期进行验证，查看是否允许添加此日期的
                 * 2.看城市和部门有没有传，如查传了，就保存成城市和部门的花费，如果没传，城市和部门设置为null，表示不按城市或部门进行设置
                 * 3.取相同条件的花费，看表里有没有，如果有，则更新cost字段。如果没有，添加一条。
                 */


                $data['belong_shop_code'] = $belong_shop_code ? $belong_shop_code : null;
                $data['belong_shop_name'] = $belong_shop_name ? $belong_shop_name : null;
                if($day < 10){
                    $day = '0'.$day;
                }
                $cost_date = date('Y-m-d',strtotime($search_date.$day));
                $cost = $input['cost'];


                $res = db('crm_s_channel_cost')->where('channel_id',$data['channel_id'])->where('brandclass_id', session('brandclass_id'))->where('cost_date', $cost_date)->where('belong_shop_code', $data['belong_shop_code'])->find();
                db()->startTrans();
                try{
                    if(!empty($res)){//修改
                        $up = array(
                            'update_time'=>date('Y-m-d H:i:s'),
                            'cost'=>$cost,
                            'cost_date'=>$cost_date
                        );
                        $update = array(
                            'cost_avg'=>$cost,
                            'cost_time'=>$cost_date
                        );
                        //修改花费时间  默认7天
                        $a = db_config('edit_channel_cost_'.session('shop_code'));
                        $edit_default = $a ? $a : 7;

                        if(strtotime($res['create_time'])+$edit_default*86400 < time()){
                            $ret['code'] = 3;
                            $ret['msg'] = '修改失败,已超过最大编辑时限!';
                            return $ret;
                        }
                        db('crm_s_channel_cost')->where('channel_id',$data['channel_id'])->where('brandclass_id', session('brandclass_id'))->where('cost_date', $cost_date)->where('belong_shop_code', $data['belong_shop_code'])->update($up);
                        db('crm_c_customer_cost')->where('channel_id', $data['channel_id'])->where('brandclass_id', session('brandclass_id'))->where('cost_time', $cost_date)->where('belong_shop_code', $data['belong_shop_code'])->update($update);
                        $old = '';
                        $old .= '操作店面：'.$res['shop_name'].'<br/>';
                        if($res['belong_shop_name'])$old .= '归属店：'.$res['belong_shop_name'].'<br/>';
                        if($res['department_name'])$old .= '渠道：'.$input['channel_name'].'<br/>';
                        $old .= '花费：'.$res['cost'].'<br/>';
                        $old .= '日期：'.$res['cost_date'].'<br/>';

                        $new = '';
                        $new .= '操作店面：'.$res['shop_name'].'<br/>';
                        if($res['belong_shop_name'])$new .= '归属店：'.$res['belong_shop_name'].'<br/>';
                        $new .= '渠道：'.$input['channel_name'].'<br/>';
                        $new .= '花费：'.$cost.'<br/>';
                        $new .= '日期：'.$cost_date.'<br/>';

                        action_log($new,$old,0,session('staff_id'),session('staff_name'));
                    }else{//新增
                        //录入花费时间  默认7天
                        $b = db_config('lr_channel_cost_'.session('shop_code'));
                        $insert_default = $b ? $b : 7;
                        if(strtotime($cost_date)+$insert_default*86400 < time()){
                            $ret['code'] = 3;
                            $ret['msg'] = '添加失败,已超过最大添加时限!';
                            return $ret;
                        }
                        $ins = array(
                            'shop_code'=>session('shop_code'),
                            'shop_name'=>session('shop_name'),
                            'channel_class_id'=>0,
                            'channel_class_name'=>NULL,
                            'channel_info_id'=>0,
                            'channel_info_name'=>NULL,
                            'channel_id'=>$input['channel_id'],
                            'channel_name'=>$input['channel_name'],
                            'province_id' => 0,
                            'province_name' =>NULL,
                            'city_id' => 0,
                            'city_name' => NULL,
                            'department_id' => 0,
                            'department_name' => NULL,
                            'brandclass_id'=>session('brandclass_id'),
                            'create_time'=>date('Y-m-d H:i:s'),
                            'cost'=>$cost,
                            'cost_date'=>$cost_date,
                            'belong_shop_code'=>$data['belong_shop_code'],
                            'belong_shop_name'=>$data['belong_shop_name'],
                        );
                        $insert = array(
                            'shop_code'=>session('shop_code'),
                            'channel_class_id'=>0,
                            'channel_class_name'=>NULL,
                            'channel_info_id'=>0,
                            'channel_info_name'=>NULL,
                            'channel_id'=>$input['channel_id'],
                            'channel_name'=>$input['channel_name'],
                            'region_id'=>0,
                            'region_name'=>NULL,
                            'province_id' => 0,
                            'province_name' => NULL,
                            'city_id' => 0,
                            'city_name' => NULL,
                            'brandclass_id'=>session('brandclass_id'),
                            'cost_time'=>$cost_date,
                            'cost_avg'=>$cost,
                            'belong_shop_code'=>$data['belong_shop_code'],
                            'belong_shop_name'=>$data['belong_shop_name'],
                        );


                        db('crm_s_channel_cost')->insert($ins);

                        db('crm_c_customer_cost')->insert($insert);
                        $new = '';
                        $new .= '操作店面：'.$ins['shop_name'].'<br/>';
                        if($ins['belong_shop_name'])$new .= '归属店：'.$ins['belong_shop_name'].'<br/>';
                        $new .= '渠道：'.$input['channel_name'].'<br/>';
                        $new .= '花费：'.$ins['cost'].'<br/>';
                        $new .= '日期：'.$ins['cost_date'].'<br/>';
                        action_log($new,[],0,session('staff_id'),session('staff_name'));
                    }
                    db()->commit();
                    $ret['code'] = 200;
                    $ret['msg'] = '操作成功';
                    return $ret;
                }catch (\Exception $e){
                    db()->rollback();
                    $ret['code'] = 2;
                    $ret['msg'] = '操作失败';
                    $ret['data'] = $e->getMessage();
                    return $ret;
                }
            }else{
                //列表、导出
                //修改花费时间  默认7天
                $a = db_config('edit_channel_cost_'.session('shop_code'));
                $editDay = $a ? $a : 7;//TODO:最多可以修改最近几天的数据，默认1天，要按店做成系统配置，
                //另外，如何动态控制table 的可编辑单元格，需要研究一下。
                $belong_shop_code = input('param.belong_shop_code');
                $where = [];
                $sql = ' 1=1 ';

                $month = input('param.search_date');
                $month = $month?$month:date('Ym');
                $start = substr($month, 0,4).'-'.substr($month, 4,2).'-01 00:00:00';
                $end = date('Y-m-d H:i:s',strtotime('+1 month',strtotime($start)) - 1);

                //部门信息
                $interface = new mcInterface();
                $res =  $interface->getDepartmentByShopcode($belong_shop_code);
                $info = db('crm_s_channel_cost')->where('channel_name','in',array_column($res,'department_name'))->where('shop_code',session('shop_code'))->where('belong_shop_code',$belong_shop_code)->where('cost_date','between',[$start,$end])->select();
                $temp = [];
                foreach($info as $k=>$v){
                    $temp[$v['channel_name'].intval(substr($v['cost_date'], 8,2))] = $v['cost'];
                }

                $data = [];
                $arr = [];
                $total = 0;
                $arr['channel_name_show'] = '总计';

                foreach ($info as $key => $value) {
                    $day = intval(substr($value['cost_date'], 8,2));
                    $data[$value['channel_id']]['channel_name_show'] = $value['channel_name'];
                    $cost = $value['cost'];
                    $data[$value['channel_id']]['cost_'.$day] = sprintf('%.2f',$cost);
                    $data[$value['channel_id']]['id'] = $value['id'];
                    if((strtotime($value['create_time']))+($editDay*86400) < time()){
                        //xx天可以修改
                        $data[$value['channel_id']]['text-'.$day] = 0;
                    }else{
                        $data[$value['channel_id']]['text-'.$day] = 1;
                    }
                    //纵向总计
                    $data[$value['channel_id']]['total'] += $cost;
                    //横向总计
                    $arr['cost_'.$day] += $cost;
                    $arr['total'] += $cost;
                }

                foreach($res as $channel) {
                    $data[$channel['id']]['channel_name_show'] = $channel['department_name'];
                    $data[$channel['id']]['id'] = $channel['id'];
                }

                $data[] = $arr;

                if(input('export')){
                    //导出
                    $this->exportChannelFee($data,$start,$end);
                    die;
                }
                $ret['data'] = array_values($data);
                return $ret;
            }
            die;
        }
        //非ajax操作
        if (!$auth) {
            return $this->redirect('/');
        }

        for ($i=0; $i < 5; $i++) {
            if($i === 0){
                $timeList[] = [
                    'value'=>date('Ym',strtotime('-'.$i.' month')),
                    'text'=>date('Y年m月',strtotime('-'.$i.' month')),
                    'select'=>1,
                ];
            }else{
                $timeList[] = [
                    'value'=>date('Ym',strtotime('-'.$i.' month')),
                    'text'=>date('Y年m月',strtotime('-'.$i.' month')),
                    'select'=>0,
                ];
            }

        }
        $this->assign('timeList',$timeList);
        $array = [
            'brandclass_id' => session('brandclass_id'),
            'staff_id' => session('staff_id'),
            'shop_type' => session('shop_type'),
            'shop_code' => session('shop_code'),
            'belong_shop_code' => session('belong_shop_code'),
            'belong_shop_name' => session('belong_shop_name'),
        ];
        $belong = getBelongShop($array);
        $this->assign("belong",$belong);

        return $this->fetch();
    }
    //根据所选省查询以下市、根据市查询以下县
    public function searchCity(){
        $data = input('post.');
        $res = controller('crm/Customer','lib')->address($data);
        return $res;
    }
    //渠道返点设定
    public function qdReturn()
    {
        // 南宁qqbaby  2021-03-24
        if (!customize('nnqqbaby')) {
            return $this->redirect('/');
        }
        // 权限
        $auth = check_right('menu1513343947');
        if (!$auth) {
            return $this->redirect('/');
        }
        $channel = controller('crm/Setting','lib')->getChannelclass();
        $this->assign('channel',$channel);
        //获取渠道
        $qudao = controller('crm/Setting','lib')->getChannelInfo();
        $this->assign('qudao',$qudao);
        //地域
        $data['type']=1;
        $address=controller("Customer","lib")->address($data);
        $this->assign("address",$address);
        //客资分区
        // $region=controller("crm/Setting","lib")->getcustomer_region();
        // $this->assign("region",$region);
        $this->assign("return_month",date('Y-m',strtotime('-1 month')));
        //渠道
        $ch = controller('crm/Customer','lib')->getChannel();
        $this->assign('ch',$ch);
        $data['type']=1;
        $address=controller("Customer","lib")->address($data);
        $this->assign("address",$address);
        return $this->fetch();
    }
    //检查上月是否设置渠道花费
    public function checkCostReturn(){
        return controller("crm/Setting","lib")->checkCostReturn(input('post.'));
    }
    //根据渠道类型名获取其渠道来源名
    public function getChannelByName(){
        return controller('crm/Setting','lib')->getChannelByName(input('param.'));
    }
    //沟通流程设定
    public function workFlow()
    {
        // 权限
        $auth = check_right('menu1512028684');
        if (!$auth) {
            return $this->redirect('/');
        }
        $this->assign('title','沟通流程设定');
        return $this->fetch();
    }
    //业务流程列表
    public function getworkflowToJSON()
    {
        // 权限
        $auth = check_right('menu1512028684');
        if (!$auth) {
            return $this->redirect('/');
        }
        $step_content = input('request.step_content');
        $res = controller('crm/Setting','lib')->getworkflowToJSON($step_content);
        return json($res);
    }
    /**
     * @cc 修改流程
     * */
    public function editWalkFlow(){
        // 权限
        $auth = check_right('menu1512028684');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->editWalkFlow(input('post.'));
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    /**
     * @cc 删除流程
     * */
    public function delWalkFlow(){
        // 权限
        $auth = check_right('menu1512028684');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->delWalkFlow(input('post.id'));
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    //业务流程列表
    public function addWorkFlow()
    {
        // 权限
        $auth = check_right('menu1512028684');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->addWorkFlow(input('post.'));
        if($res){
            return $this->redirect('workFlow');
        }else{
            return $this->redirect('workFlow');
        }

    }
    /**
     * @cc 自动分配开关
     * */
    public function auto_fp(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->auto_fp(input('post.'));
        return ($res);
    }
    /**
     * @cc 自动接收开关
     * */
    public function auto_jr(){
        $res = controller('crm/Setting','lib')->auto_jr(input('post.'));
        return ($res);
    }
    /**
     * @cc 自动分配接收时间
     * */
    public function auto_fp_timeout(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->auto_fp_timeout(input('time'));
        return ($res);
    }
    /**
     * @cc 自动分配开启时间区间
     * */
    public function setFPTime(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->setFPTime(input('post.'));
        return ($res);
    }
    //渠道类型列表
    public function getchannelclassToJSON()
    {
        $channelclass = input('request.');
        // 南宁qqbaby  2021-03-22
        if (customize('nnqqbaby')) {
            $res = controller('crm/Setting','lib')->getchannelclassToQqbbJSON($channelclass);

            // 导出  南宁qqbaby  2021-05-18
            if ($channelclass['daochu'] == 1) {
                $title=array('部门','录入人','渠道类型','来源渠道','渠道账号','城市','品牌','设定日期','总花费','展现量','点击量','客资量','客资分配量','有效客资量','客资成本','有效客资成本','有效率','关注量','私信量','有效表单','添加时间','修改时间');

                $daochu_txt = [];
                foreach ($res['data'] as $key => $value) {
                    if ($key !== '合计') {
                        $daochu_txt[$key]['department_name'] = $value['department_name'] ?: '';
                        $daochu_txt[$key]['cost_staff'] = $value['cost_staff'] ?: '';
                        $daochu_txt[$key]['channel_class_name'] = $value['channel_class_name'] ?: '';
                        $daochu_txt[$key]['channel_info_name'] = $value['channel_info_name'] ?: '';
                        $daochu_txt[$key]['channel_name'] = $value['channel_name'] ?: '';
                        $daochu_txt[$key]['city_name'] = $value['city_name'] ?: '';
                        $daochu_txt[$key]['b_name'] = $value['b_name'] ?: '';
                        $daochu_txt[$key]['cost_date'] = $value['cost_date'] ?: '';
                        $daochu_txt[$key]['cost'] = $value['cost'] ?: 0;
                        $daochu_txt[$key]['show_num'] = $value['show_num'] ?: 0;
                        $daochu_txt[$key]['click_num'] = $value['click_num'] ?: 0;
                        $daochu_txt[$key]['kz'] = $value['kz'] ?: 0;
                        $daochu_txt[$key]['fp'] = $value['fp'] ?: 0;
                        $daochu_txt[$key]['kz_youxiao'] = $value['kz_youxiao'] ?: 0;
                        $daochu_txt[$key]['kz_cb'] = $value['kz_cb'] ?: 0;
                        $daochu_txt[$key]['kz_youxiao_cb'] = $value['kz_youxiao_cb'] ?: 0;
                        $daochu_txt[$key]['yxl'] = $value['yxl'] ?: '0%';
                        $daochu_txt[$key]['subscribe_num'] = $value['subscribe_num'] ?: 0;
                        $daochu_txt[$key]['private_num'] = $value['private_num'] ?: 0;
                        $daochu_txt[$key]['effective_form'] = $value['effective_form'] ?: 0;
                        $daochu_txt[$key]['create_time'] = $value['create_time'] ?: '';
                        $daochu_txt[$key]['update_time'] = $value['update_time'] ?: '';
                    }
                }

                $file = 'daochuTable.xlsx';
                controller("crm/Customer","lib")->export($title,$daochu_txt,$file);
            }
        }else{
            $res = controller('crm/Setting','lib')->getchannelclassToJSON($channelclass);
        }
        return json($res);
    }
    //渠道类型列表
    public function getChannelReturnToJSON()
    {
        $channelclass = input('request.');
        $res = controller('crm/Setting','lib')->getChannelReturnToJSON($channelclass);
        return json($res);
    }
    /**
     * @cc 删除渠道类型设定
     * */
    function  delQDType(){
        // 权限
        $auth = check_right('menu1512650793');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delQDType(input('post.id'));
    }
    /**
     * @cc 删除渠道返点设定
     * */
    function  delQDReturn(){
        // 权限
        $auth = check_right('menu1513343947');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delQDReturn(input('post.id'));
    }
    /**
     * @cc 修改渠道类型设定
     * */
    function  editQDType(){
        // 权限
        $auth = check_right('menu1512650793');
        if (!$auth) {
            return $this->redirect('/');
        }
        if (customize('qqbaby')) {
            return controller('crm/Setting','lib')->editQDTypeQqbb(input('post.'));
        }else{
            return controller('crm/Setting','lib')->editQDType(input('post.'));
        }
    }
    /**
     * @cc 修改渠道返点设定
     * */
    function  editQDReturn(){
        // 权限
        $auth = check_right('menu1513343947');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->editQDReturn(input('post.'));
    }
    /**
     * @cc 新增渠道类型
     * */
    function addQDType(){
        // 权限
        $auth = check_right('menu1512650793');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addQDType(input('post.'));
    }
    /**
     * @cc 新增渠道返点
     * */
    function addQDReturn(){
        // 权限
        $auth = check_right('menu1513343947');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addQDReturn(input('post.'));
    }
    /**
     * @cc 微信模板设定
     * */
    public function pushModal()
    {
        $wx_template_name = input('post.wx_template_name');
        $this->assign('wx_template_name',$wx_template_name);
        $this->assign('title','微信模板设定');
        return $this->fetch();
    }
    //微信模板列表
    public function getWXModalToJSON()
    {
        $wx_template_name = input('request.wx_template_name');
        $res = controller('crm/Setting', 'lib')->getWXModalToJSON($wx_template_name);
        return json($res);
    }
    /**
     * @cc 删除微信模板设定
     * */
    function  delWXModal(){
        return controller('crm/Setting','lib')->delWXModal(input('post.id'));
    }
    /**
     * @cc 增加微信模板
     * */
    public function addWXModal(){
        // 权限
        $auth = check_right('menu1512029583');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addWXModal(input('post.'));
    }
    //短信模板设定
    public function modalSet()
    {
        // 权限
        $auth = check_right('menu1512029583');
        if (!$auth) {
            return $this->redirect('/');
        }
        $mtemplate_name = input('post.mtemplate_name');
        $this->assign('mtemplate_name',$mtemplate_name);
        $this->assign('title','短信模板设定');
        return $this->fetch();
    }
    public function findMModal(){
        $id = input('request.id');
        $res = controller('crm/Setting', 'lib')->findMModal($id);
        $this->assign('detail',$res);
        return $this->fetch('modalSet');
    }
    /**
     * @cc 增加短信模板
     * */
    public function addModal(){
        // 权限
        $auth = check_right('menu1512029583');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addModal(input('post.'));
    }
    /**
     * @cc 修改微信模板设定
     * */
    function  editWXModal(){
        return controller('crm/Setting','lib')->editWXModal(input('post.'));
    }
    /**
     * @cc 修改短信模板设定
     * */
    function  editMModal(){
        // 权限
        $auth = check_right('menu1512029583');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->editMModal(input('post.'));
    }
    /**
     * @cc 删除短信模板设定
     * */
    function  delMModal(){
        // 权限
        $auth = check_right('menu1512029583');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delMModal(input('post.id'));
    }
    //追踪失败原因列表
    public function getModalToJSON()
    {
        $mtemplate_name = input('request.mtemplate_name');
        $res = controller('crm/Setting', 'lib')->getModalToJSON($mtemplate_name);
        return json($res);
    }
    //追踪失败原因页面
    public function fileReason()
    {
        // 权限
        $auth = check_right('menu1512029560');
        if (!$auth) {
            return $this->redirect('/');
        }
        $reason = input('post.reason');
        $reason_list = controller('crm/Setting','lib')->getModalToJSON($reason);
        $this->assign('reason',$reason);
        $this->assign('reason_list',$reason_list);
        $this->assign('title','追踪失败原因设定');
        return $this->fetch();
    }
    //驳回原因页面
    public function RejectReason()
    {
        // 权限
        $auth = check_right('menu1521784361');
        if (!$auth) {
            return $this->redirect('/');
        }
        $this->assign('title','驳回原因设定');
        return $this->fetch();
    }
    //驳回原因列表
    public function getRejectReasonToJSON()
    {
        $reason = input('request.reason');
        $res = controller('crm/Setting','lib')->getRejectReasonToJSON($reason);
        return json($res);
    }
    //追踪失败原因列表
    public function getReasonToJSON()
    {
        $reason = input('request.reason');
        $res = controller('crm/Setting','lib')->getReasonToJSON($reason);
        return json($res);
    }
    /**
     * @cc 追踪失败原因设定
     * */
    public function setReason()
    {
        // 权限
        $auth = check_right('menu1512029560');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->setReason(input('post.'));
        return $res;
    }
    /**
     * @cc 驳回原因设定
     * */
    public function setRejectReason()
    {
        // 权限
        $auth = check_right('menu1521784361');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->setRejectReason(input('post.'));
        return $res;
    }
    /**
     * @cc 删除追踪失败原因设定
     * */
    function  delFileReason(){
        // 权限
        $auth = check_right('menu1512029560');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delFileReason(input('post.id'));
    }
    /**
     * @cc 删除驳回原因设定
     * */
    function  delRejectReason(){
        // 权限
        $auth = check_right('menu1521784361');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delRejectReason(input('post.id'));
    }
    /**
     * @cc 修改驳回原因设定
     * */
    function  editRejectReason(){
        // 权限
        $auth = check_right('menu1521784361');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->editRejectReason(input('post.'));
    }
    /**
     * @cc 修改追踪失败原因设定
     * */
    function  editReason(){
        // 权限
        $auth = check_right('menu1512029560');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->editReason(input('post.'));
    }
    //五维图设定
    public function biao()
    {
        // 权限
        $auth = check_right('menu1512028736');
        if (!$auth) {
            return $this->redirect('/');
        }
        //获取职位信息
        $position =  controller('crm/Setting','lib')->get_position_list(['shop_code'=>session('shop_code')]);
        $tar = new \app\crm\lib\Target();
        $ap = $tar->getAllTarget();
        $this->assign('ap',$ap);
        $this->assign('position',$position);
        $this->assign('title','五维图设定');
        return $this->fetch();
    }
    //五维图列表
    function getTuToJSON(){
        $res = controller('crm/Setting','lib')->getTuToJSON(input('param.'));
        return json($res);
    }
    /**
     * @cc 删除五维图
     * */
    public function delTu(){
        // 权限
        $auth = check_right('menu1512028736');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delTu(input('param.id'));
    }
    function get_photo(){
        echo controller('crm/Setting','lib')->get_staff_photo(session('staff_id'));
    }
    public function getTu(){
        $tu =  controller('crm/Setting','lib')->getTu();
       // $res = array('a'=> "[".$tu['indicator']."]",'b'=>"[".$tu['data']."]");
        echo json_encode($tu) ;
        exit();
    }

    //能力设定
    public function abilitySet(){
        // 权限
        $auth = check_right('menu1512028736');
        if (!$auth) {
            return $this->redirect('/');
        }
        //获取职位信息
        $position =  controller('crm/Setting','lib')->getPostitionList();
        $this->assign('position',$position);
        //获取设定信息
        $ability =  controller('crm/Setting','lib')->getAbilityList();
        $this->assign('ability',$ability);
        return $this->redirect('biao');
    }
    /**
     * @cc 增加五维图
     * */
    public function addAbility(){
        // 权限
        $auth = check_right('menu1512028736');
        if (!$auth) {
            return $this->redirect('/');
        }
        $ability = input('post.');
        $res = controller('crm/Setting','lib')->abilitySet($ability);
        return $res;
    }
    public function getAbility(){
        $ability = input('post.');
        $res = controller('crm/Setting','lib')->getAbility($ability);
        return $res;
    }
    //电访备注
    public function telphoneRemark(){
        // 权限
        $auth = check_right('menu1512029635');
        if (!$auth) {
            return $this->redirect('/');
        }
        $remark = controller('crm/Setting','lib')->getRemarkList();
        $this->assign('remark',$remark);
        $this->assign('title','电访备注设定');
        return $this->fetch();
    }
    //电访备注列表
    public function getTelphoneRemarkToJSON()
    {
        $telremark = input('request.telremark');
        $res = controller('crm/Setting','lib')->getTelphoneRemarkToJSON($telremark);
        return json($res);
    }
      /**
     * @cc 增加电访备注
     * */
    public function addtelphoneRemark(){
        // 权限
        $auth = check_right('menu1512029635');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addtelphoneRemark(input('post.'));
    }
      /**
     * @cc 修改电访备注
     * */
    function  edittelphoneRemark(){
        // 权限
        $auth = check_right('menu1512029635');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->edittelphoneRemark(input('post.'));
    }
      /**
     * @cc 删除电访备注
     * */
    function  deltelphoneRemark(){
        // 权限
        $auth = check_right('menu1512029635');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->deltelphoneRemark(input('post.id'));
    }
    //客资标记
    public function trackingKmarker(){
        // 权限
        $auth = check_right('menu1513213883');
        if (!$auth) {
            return $this->redirect('/');
        }
        // $remark = controller('crm/Setting','lib')->gettrackingKmarkerList();
        // $this->assign('remark',$remark);
        if (customize('nnqqbaby')) {
            $this->assign('nnqqbaby','1');
        }
        $this->assign('title','客资标记设定');
        return $this->fetch();
    }
    //客资标记列表
    public function getTrackingKmarkerToJSON()
    {
        $tracksign = input('request.tracksign');
        $res = controller('crm/Setting','lib')->getTrackingKmarkerToJSON($tracksign);
        return json($res);
    }
      /**
     * @cc 增加客资标记
     * */
    public function addtrackingKmarker(){
        // 权限
        $auth = check_right('menu1513213883');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addtrackingKmarker(input('post.'));
    }
      /**
     * @cc 修改客资标记
     * */
    function  edittrackingKmarker(){
        // 权限
        $auth = check_right('menu1513213883');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->edittrackingKmarker(input('post.'));
    }
      /**
     * @cc 删除客资标记
     * */
    function  deledittrackingKmarker(){
        // 权限
        $auth = check_right('menu1513213883');
        if (!$auth) {
            return $this->redirect('/');
        }
        $signId = input('post.id');

        // 取配置
        $signA = config('signA');
        $aid = $signA[session('shop_code')];
        if ($aid == $signId) {
            $return = ['error'=>'1','msg'=>'A标记为设置标记，无法删除。'];
            return $return;
        }

        return controller('crm/Setting','lib')->deledittrackingKmarker($signId);
    }

    //功能菜单设定
    function menuSet(){
        // 权限
        // $auth = check_right('menu1512029909');
        // if (!$auth) {
        //     return $this->redirect('/');
        // }
        $get = input('get.');
        if ($get['sign']!='gm') {
            return $this->redirect('/');
        }
        $data=controller('crm/Setting',"lib")->getMenuJSON();
        $this->assign('data',$data);

        //$menu=controller('crm/Setting',"lib")->getMenuList();
        //$this->assign('menu',$menu);
        return $this->fetch();
    }

    //功能菜单列表
    function getMenuJSON(){
        $res = controller("crm/Setting","lib")->getMenuJSON(input());
        return json($res);
    }

    public function addMenuSet(){
        // 权限
        // $auth = check_right('menu1512029909');
        // if (!$auth) {
        //     return $this->redirect('/');
        // }
        $id= input('get.id');
        
        if($id){
            $detail=db('crm_s_menu')->where('id',$id)->find();
            $this->assign('detail',$detail);
            $data=controller('crm/Setting',"lib")->getMenuList();
            $this->assign('data',$data);
            return  $this->fetch();
        }else{
            $data=controller('crm/Setting',"lib")->getMenuList();
            $this->assign('data',$data);
            return  $this->fetch();
        }
    }

    /**
     * @cc 新增菜单
     * */
    public function addMenu(){
        // 权限
//        $auth = check_right('menu1512029909');
//        if (!$auth) {
//            return $this->redirect('/');
//        }
        return controller('crm/Setting','lib')->addMenu(input('post.'));
    }

    // 修改功能
    // function  editMenu(){
    //    $res= controller('crm/Setting','lib')->editMenu(input('post.'));
    //    return $res;
    // }
    /**
     * @cc 删除菜单
     * */
    function  delMenu(){
        // 权限
        $auth = check_right('menu1512029909');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delMenu(input('post.id'));
    }

    /**
     * @cc 修改菜单
     * */
    function editStatus(){
        // 权限
//        $auth = check_right('menu1512029909');
//        if (!$auth) {
//            return $this->redirect('/');
//        }
        return controller('crm/Setting','lib')->editStatus(input('post.'));
    }

    //权限设定
    public function permission(){
        $auth = check_right('menu1512029925');
        if (!$auth) {
            return $this->redirect('/');
        }
        if(session('is_belong')==1){
            $brand=controller('crm/Setting','lib')->brandclass_list();
            $department=controller('crm/Setting','lib')->department_list(array('grade_type'=>session('is_belong')));
            $position=controller("crm/Setting","lib")->get_position_list(array('grade_type'=>session('is_belong'),'department_id'=>'zero'));
        }
        if(session('is_belong')==2){
            $shop=controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass')));
            $department=controller('crm/Setting','lib')->department_list(array('grade_type'=>session('is_belong'),'brandclass'=>session('brandclass')));
            $position=controller("crm/Setting","lib")->get_position_list(array('grade_type'=>session('is_belong'),'brandclass'=>session('brandclass'),'department_id'=>'zero'));
        }

        if(session('is_belong')==3||session('is_belong')==4){
            $department=controller('crm/Setting','lib')->department_list(array('shop_code'=>session('shop_code')));
            $position=controller("crm/Setting","lib")->get_position_list(array('grade_type'=>3,'shop_code'=>session('shop_code')));
        }
        $this->assign('is_belong',session('is_belong'));
        $this->assign('brand',$brand);
        $this->assign('shop',$shop);
        $this->assign('department',$department);
        $this->assign('position',$position);
        return $this->fetch();
    }
    public function permissionSync(){
        $originPosition = input('position_code');
        $auth = check_right('menu1512029925');

        if(request()->isPost()){
            $ret = ['code' => 1,'msg'=>''];
            if (!$auth) {
                $ret['code'] = 505;
                $ret['msg'] = '授权失败，请确定您有此功能操作权限。';
                return json($ret);
            }
            if(!$originPosition){
                $ret['code'] = 500;
                $ret['msg'] = '无效的岗位编号';
                return json($ret);
            }
            $positions = input('positions');
            $positionArr = explode(',', $positions);
            $originRight = db('crm_s_position_menu')->where('position_code',$originPosition)->find();
            if(!$originRight){
                $ret['code'] = 501;
                $ret['msg'] = '原岗位没有设置权限，请设置';
                return json($ret);
            }
            $data = [];
            foreach ($positionArr as $position) {
                if($position == $originPosition){
                    continue;
                }
                $data[] = ['position_code'=>$position,'menu_code'=>$originRight['menu_code']];
            }
            if(empty($data)){
                $ret['code'] = 503;
                $ret['msg'] = '没有数据需要更新，请选择要同步的目标岗位。';
                return json($ret);
            }
            db()->startTrans();
            try{
                db('crm_s_position_menu')->where('position_code','in',$positionArr)->delete();
                db('crm_s_position_menu')->insertAll($data);
                action_log($positionArr,$originRight,0,session(['staff_id']),session(['staff_name']));
                cache('CRM_menu_*',null);
                cache('CRM_menuAll',null);
                cache('CRM_menuAllS',null);
                db()->commit();
            }catch(\Exception $e){
                db()->rollback();
                $ret['code'] = 502;
                $ret['msg'] = '操作失败：'.$e->getMessage();
                return json($ret);
            }
            return json($ret);
        }
        if (!$auth) {
            return $this->redirect('/');
        }
        if(!$originPosition){
            die('无效的岗位编号');
        }
        if(session('is_belong')==1){
            $brand=controller('crm/Setting','lib')->brandclass_list();
            $department=controller('crm/Setting','lib')->department_list(array('grade_type'=>session('is_belong')));
            $position=controller("crm/Setting","lib")->get_position_list(array('grade_type'=>session('is_belong'),'department_id'=>'zero'));
        }
        if(session('is_belong')==2){
            $shop=controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass')));
            $department=controller('crm/Setting','lib')->department_list(array('grade_type'=>session('is_belong'),'brandclass'=>session('brandclass')));
            $position=controller("crm/Setting","lib")->get_position_list(array('grade_type'=>session('is_belong'),'brandclass'=>session('brandclass'),'department_id'=>'zero'));
        }

        if(session('is_belong')==3||session('is_belong')==4){
            $department=controller('crm/Setting','lib')->department_list(array('shop_code'=>session('shop_code')));
            $position=controller("crm/Setting","lib")->get_position_list(array('grade_type'=>3,'shop_code'=>session('shop_code')));
        }
        $this->assign('is_belong',session('is_belong'));
        $this->assign('brand',$brand);
        $this->assign('shop',$shop);
        $this->assign('originPosition',$originPosition);
        $this->assign('department',$department);
        $this->assign('position',$position);
        return $this->fetch();
    }

    public function bran_link(){
        $brand=input('post.');
        $msg['shop']=controller('crm/Customer','lib')->get_shop(array('brandclass'=>$brand['brandclass']));
        $msg['department']=controller('crm/Setting','lib')->department_list(array('grade_type'=>2,'brandclass'=>$brand['brandclass']));
        $msg['position']=controller("crm/Setting","lib")->get_position_list(array('grade_type'=>2,'brandclass'=>$brand['brandclass'],'department_id'=>'zero'));
        if($msg){
            $this->success("查询成功",'/',$msg);
        }
    }
    public function shop_link(){
        $shop=input('post.');
        $msg['department']=controller('crm/Setting','lib')->department_list(array('grade_type'=>3,'shop_code'=>$shop['shop_code']));
        $msg['position']=controller("crm/Setting","lib")->get_position_list(array('grade_type'=>3,'shop_code'=>$shop['shop_code'],'department_id'=>'zero'));
        if($msg){
            $this->success("查询成功",'/',$msg);
        }
    }

    public function department_link(){
        $data=input('post.');
        $department['department_id']=(int)$data['department'];
        $msg['position']=controller("crm/Setting","lib")->get_position_list(array('department_id'=>$department['department_id']));

        if($msg){
            $this->success("查询成功",'/',$msg);
        }
    }

    public function link_search(){
        $data=input('post.');
        if($data['brandclass']){
            $brandclass=$data['brandclass']=='undefined'?session('brandclass'):$data['brandclass'];
        }else{
            $brandclass='zero';
        }
        if(empty($data['shop_code'])){
            $shop_code='zero';
        }else{
            $shop_code=$data['shop_code']=='undefined'?session('shop_code'):$data['shop_code'];
        }
        $department_id='zero';
        $msg['department']=controller('crm/Setting','lib')->department_list(array('brandclass'=>$brandclass,'shop_code'=>$shop_code));
        $msg['position']=controller("crm/Setting","lib")->get_position_list(array('brandclass'=>$brandclass,'shop_code'=>$shop_code,'department_id'=>$department_id));
        if($msg){
            $this->success("查询成功",'/',$msg);
        }
    }

    //当前登录人权限
    // public  function get_menu(){
    //     $auth=getAuth($type='auth');
    //     $menu=array_column($auth,'id');
    //     $this->success('查询成功','/',$menu);
    // }

    //递归后功能菜单数据
    public function  getPermissionJSON(){
        $menu = include(APP_PATH.'menu.php');
        $menuCustomize = include(APP_PATH.'menu_customize.php');
        $allMenu = getAllMenu($menu,$menuCustomize);

        $param['position_code'] = input('param.position_code')?:session('main_position_code');
        $allow = controller('Setting','lib')->getJurisdiction($param);
        // dump($allow);die;
        $res = controller('Setting','lib')->getAllMenuTree($allMenu,$allow);
        return ['code'=>200,'data'=>$res];
        // return controller('Setting','lib')->getPermissionJSON();
    }
    //递归后报表设定
    public function  getShopJSON(){
        return controller('crm/Setting','lib')->getShopJSON(input());
    }

    /**
     * @cc 授权
     * */
    public function authorise(){
        $data=input('post.');
        $data['session_main_work_type'] = session('main_work_type');
        $data['session_work_type'] = session('work_type');
        $data['session_main_position_code'] = session('main_position_code');
        return controller("crm/Setting","lib")->authorise($data);
    }

    //根据岗位查询其功能权限
    public function getPositionMenu(){
        $position_code=input('post.position_code');
        return controller("crm/Setting","lib")->getPositionMenu($position_code);
    }


    //追踪标记
    public function markSet(){
        // 权限
        $auth = check_right('menu1512898027');
        if (!$auth) {
            return $this->redirect('/');
        }
        return $this->fetch();
    }
    /**
     * @cc 新增追踪标记
     * */
    public function addMark(){
         // 权限
        $auth = check_right('menu1512898027');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller("crm/Setting","lib")->getMark(input('id'),'id,mark_name,mark_color');
        $this->assign('res',$res);
        $this->assign('ros',controller("crm/Setting","lib")->getSignColor());
        return $this->fetch();
    }
    /**
     * @cc 删除追踪标记颜色
     * */
    public function delMarkColor(){
        $id = input('param.id');
        db()->startTrans();
        try{
            db('crm_s_markset')->where('id',$id)->update(['mark_color'=>NULL]);
            db()->commit();
            return array('code'=>200,'msg'=>'颜色清除成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'颜色清除失败','data'=>$e->getMessage());
        }

    }
    /**
     * @cc 删除客资标记颜色
     * */
    public function delSignColor(){
        $id = input('param.id');
        db()->startTrans();
        try{
            db('crm_s_tracksign')->where('id',$id)->update(['sign_color'=>NULL]);
            db()->commit();
            return array('code'=>200,'msg'=>'颜色清除成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'颜色清除失败','data'=>$e->getMessage());
        }

    }
    /**
     * @cc 新增客资标记
     * */
    public function addSign(){
        $res = controller("crm/Setting","lib")->getSign(input('id'),'id,sign_color,tracksign,protect_day');
        $this->assign('res',$res);
        if (customize('nnqqbaby')) {
            $this->assign('nnqqbaby','1');
        }
        $this->assign('ros',controller("crm/Setting","lib")->getMarkColor());
        return $this->fetch();
    }
    /**
     * @cc 删除追踪标记
     * */
    public function delMark(){
         // 权限
        $auth = check_right('menu1512898027');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller("crm/Setting","lib")->delMark(input('id'));
        return $res;
    }
    public function getmarktojson(){
        $res = controller("crm/Setting","lib")->getMarkToJSON(input('param.'));
        return json($res);
    }
    /**
     * @cc 修改追踪标记
     * */
    public function editMark(){
         // 权限
        $auth = check_right('menu1512898027');
        if (!$auth) {
            return $this->redirect('/');
        }
        $param = input('post.');
        $res = controller("crm/Setting","lib")->editMark($param);
        return ($res);
    }


    //会所名称设定
    public function clubNameSet(){
        // 权限
        $auth = check_right('menu1591943564');
        if (!$auth) {
            return $this->redirect('/');
        }
        return $this->fetch();
    }
    //获取会所名称数据
    public function getclubtojson(){
        $param = input();

        $data['club_name'] = trim($param['club_name']);
        $data['brandclass_id'] = session('brandclass_id');
        $res = controller("crm/Setting","lib")->getClubToJSON($data);
        return json($res);
    }
    //添加会所
    public function addClub(){
        // 权限
        $auth = check_right('menu1591943564');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller("crm/Setting","lib")->getClub(input('id'),'id,club_name');
        $this->assign('res',$res);
        return $this->fetch();
    }

    /**
     * @cc 修改追踪标记
     * */
    public function editClub(){
         // 权限
        $auth = check_right('menu1591943564');
        if (!$auth) {
            return $this->redirect('/');
        }
        $param = input('post.');
        $res = controller("crm/Setting","lib")->editClub($param);
        return ($res);
    }
    /**
     * @cc 删除追踪标记
     * */
    public function delClub(){
         // 权限
        $auth = check_right('menu1591943564');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller("crm/Setting","lib")->delClub(input('id'));
        return $res;
    }





    //获取成本设定
    public function obtainCost(){
        // 权限
        $auth = check_right('menu1513855331');
        if (!$auth) {
            return $this->redirect('/');
        }
        return $this->fetch();
    }
    /**
     * @cc 获取成本设定添加
     * */
    public function addObtainCost(){
         // 权限
        $auth = check_right('menu1513855331');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addObtainCost(input('post.'));
    }
    /**
     * @cc 获取成本设定编辑
     * */
    public function editObtainCost(){
         // 权限
        $auth = check_right('menu1513855331');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->editObtainCost(input('post.'));
        return $res;
    }
    /**
     * @cc 获取成本设定删除
     * */
    public function delObtainCost(){
         // 权限
        $auth = check_right('menu1513855331');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delObtainCost(input('post.'));
    }
    public function getObtainCostToJSON(){
        $res = controller('crm/Setting','lib')->getObtainCostToJSON(input('param.cost'));
        return json($res);
    }
    //呼叫前缀
    public function callPrefix(){
        // 权限
        $auth = check_right('menu1537348792');
        if (!$auth) {
            return $this->redirect('/');
        }
        $centerData = db('crm_s_call_center')->where("id",db_config('call_id'))->find();
        $this->assign('centerData',$centerData);
        return $this->fetch();
    }
    /**
     * @cc 增加呼叫前缀
     * */
    public function addCallPrefix(){
        // 权限
        $auth = check_right('menu1537348792');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addCallPrefix(input('post.'));
    }
    /**
     * @cc 编辑呼叫前缀
     * */
    public function editCallPrefix(){
        // 权限
        $auth = check_right('menu1537348792');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->editCallPrefix(input('post.'));
    }
    /**
     * @cc 删除呼叫前缀
     * */
    public function delCallPrefix(){
        // 权限
        $auth = check_right('menu1537348792');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delCallPrefix(input('post.'));
    }
    public function getCallPrefixToJSON(){
        $res = controller('crm/Setting','lib')->getCallPrefixToJSON(input('param.name'));
        return json($res);
    }
    //呼叫中心
    public function callCenterSet(){
        // 权限
        $auth = check_right('menu1537348792');
        if (!$auth) {
            return $this->redirect('/');
        }
        return $this->fetch();
    }
    /**
     * @cc 新增呼叫中心
     * */
    public function addCallCenter(){
        // 权限
        $auth = check_right('menu1537348792');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addCallCenter(input('post.'));
    }
    /**
     * @cc 编辑呼叫中心
     * */
    public function editCallCenter(){
        // 权限
        $auth = check_right('menu1537348792');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->editCallCenter(input('post.'));
    }
    /**
     * @cc 删除呼叫中心
     * */
    public function delCallCenter(){
        // 权限
        $auth = check_right('menu1537348792');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delCallCenter(input('post.'));
    }
    public function getCallCenterToJSON(){
        $res = controller('crm/Setting','lib')->getCallCenterToJSON(input('param.name'));
        return json($res);
    }
    //呼叫中心列表
    public function callManList(){
        //店面下人员
        $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>session('shop_code')]);
        $this->assign('staff',$staff);
        if(SYSTEM_AUTH_ADMIN || check_right('menu1561718791')){
            $this->assign('auth',1);
        }
        return $this->fetch();
    }
    public function callManListJSON(){
        $param = input();
        $limit = $param['limit'] ? $param['limit'] : 100;
        $page = $param['page'] ? $param['page'] : 1;
        if($param['user']){
            $where['user'] = array('like','%'.trim($param['user']).'%');
        }
        $result['code'] = 0;
        $result['msg'] = '';
        
        if(check_right('menu1561718791')){
            $result['data'] = db('crm_s_call_man')->where('shop_code',session('shop_code'))->where($where)->select();
            $result['count'] = db('crm_s_call_man')->where('shop_code',session('shop_code'))->where($where)->count();
        }else{
            $result['data'] = db('crm_s_call_man')->where('shop_code',session('shop_code'))->where('staff_id',session('staff_id'))->limit($limit)->page($page)->select();
            $result['count'] = db('crm_s_call_man')->where('shop_code',session('shop_code'))->where('staff_id',session('staff_id'))->count();
        }
        // exit;
        return json($result);
    }
    /**
     * @cc 坐席删除
     * */
    public function delCallMan(){
        $data = input('post.');
        $info1 = db('crm_s_call_man')->where('staff_id',$data['staff_id'])->find();
        db()->startTrans();
        try{
            db('crm_s_call_man')->where('staff_id',$data['staff_id'])->delete();
            session('user',null);
            session('pwd',null);
            action_log('删除坐席：'.$info1['user'],[],0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'坐席删除成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'坐席删除失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 呼叫中心坐席设置
     * */
    public function callCenterUserSet(){
        $data = input();
        $param['user'] = trim($data['user']);
        $param['pwd'] = trim($data['pwd']);
        $param['staff_id'] = $data['staff_id'];
        $info = getStaffInfoById($data['staff_id']);
        $param['staff_name'] = $info['staff_name'] ? $info['staff_name'] : $info['staffname'];
        $param['shop_code'] = session('shop_code');
        $param['shop_name'] = session('shop_name');
        $param['department_id'] = $info['department_id'];
        $param['department_name'] = $info['department_name'];
        $param['group_id'] = session('group_id');
        $param['group_name'] = session('group_name');

        $call = db('crm_s_call_center')->where('id',db_config('call_id'))->find();
        if(!$data['exten_type'] && $call['call_name'] == '呼叫中心(七陌)'){
            return array('code'=>100,'msg'=>'七陌 的 类型 不能为空!','data'=>'');
        }
        $param['exten_type'] = $data['exten_type'];

        if($data['staff_id']){
            $info1 = db('crm_s_call_man')->where('staff_id',$data['staff_id'])->find();
            db()->startTrans();
            try{
                if($info1['staff_id']){
                    db('crm_s_call_man')->where('staff_id',$data['staff_id'])->update($param);
                }else{
                    db('crm_s_call_man')->insertGetId($param);
                }
                session('user',$param['user']);
                session('pwd',$param['pwd']);
                action_log($param,$info1,0,session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>200,'msg'=>'呼叫中心坐席设置成功','data'=>$param);
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'呼叫中心坐席设置失败','data'=>$e->getMessage());
            }
        }else{
            return array('code'=>300,'msg'=>'未找到员工ID，不能设置','data'=>'');
        }
    }
    //首页岗位显示设定
    public function homeShowSet(){
        // 权限
        $auth = check_right('menu1514430518');
        if (!$auth) {
            return $this->redirect('/');
        }
        //部门
        $dep_info = controller('crm/Setting','lib')->department_list(['shop_code'=>session('shop_code')]);
        $this->assign('department',$dep_info);
        //店面下的岗位
        $position_info = controller('crm/Setting','lib')->get_position_list(['shop_code'=>session('shop_code')]);
        foreach($position_info as $k=>$v){
            if($v['department_id'] != 0){
                unset($position_info[$k]);
            }
        }
        $this->assign('position',$position_info);
        return $this->fetch();
    }
    /**
     * @cc 新增客资简析
     * */
    public function homeShowAdd(){
        // 权限
        $auth = check_right('menu1514430518');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->homeShowAdd(input('post.'));
        return $res;
    }
    /**
     * @cc 编辑客资简析
     * */
    public function homeShowEdit(){
        // 权限
        $auth = check_right('menu1514430518');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->homeShowEdit(input('post.'));
        return $res;
    }
    public function editHomeShow(){
        // 权限
        $auth = check_right('menu1514430518');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = db('crm_s_home_show')->find(input('param.id'));
        $res['content'] = explode(',',$res['content']);
        $res['time'] = explode(',',$res['time']);
        if(!$res['department_id']){
            $position = controller('crm/Setting','lib')->get_position_list(['position_code'=>$res['position_code']]);
            $res['department_id'] = $position[0]['department_id'];
        }
        //部门
        $dep_info = controller('crm/Setting','lib')->department_list(['shop_code'=>session('shop_code')]);
        $this->assign('department',$dep_info);
        //店面下的岗位
        $position_info = controller('crm/Setting','lib')->get_position_list(['shop_code'=>session('shop_code'),'department_id'=>$res['department_id']]);
        if($res['department_id'] == 0){
            foreach($position_info as $k=>$v){
                if($v['department_id'] != 0){
                    unset($position_info[$k]);
                }
            }
        }


        $this->assign('info',$res);
        $this->assign('position',$position_info);
        return $this->fetch();
    }
    /**
     * @cc 删除客资简析
     * */
    public function homeShowDel(){
        // 权限
        $auth = check_right('menu1514430518');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->homeShowDel(input('post.'));
        return $res;
    }
    public function homeShowJSON(){
        $res = controller('crm/Setting','lib')->homeShowJSON(input('param.'));
        return json($res);
    }
    //渠道补充
    public function channel(){
        // 权限
        $auth = check_right('menu1516949559');
        if (!$auth) {
            return $this->redirect('/');
        }
        $channel = controller('crm/Setting','lib')->getChannelclass();
        $this->assign('channel',$channel);
        $this->assign('channel_class',$channel);
        // var_dump($channel);
        // die;
        //客资标记
        if(session('shop_code')){
            $sign = db('crm_s_tracksign')->where('shop_code',session('shop_code'))->select();
            $this->assign('sign',$sign);
            $this->assign('showsign',1);
        }
        $shops = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id')]);
        $this->assign('shops',$shops);
        return $this->fetch();
    }
    public function getTransferChannel(){
        $params = input("");
        $channel = controller('crm/Customer','lib')->getChannel();

        foreach ($channel as $key => $value) {
            foreach($params['data'] as $k2 => $v2){
                if($value['id'] == $v2['id']){
                    unset($channel[$key]);
                    continue;
                }
            }
        }

        $channelArr = [];
        foreach($channel as $key=>$value){
            $channelArr[] = $value;
        }

        return array('code'=>200,'msg'=>'获取成功','data'=>$channelArr);
    }
    //渠道客资转移
    public function transferChannel(){
        $params = input("");

        $channelData = db("crm_s_channel")->where('id',$params['channel_id'])->find();

        $channel_id = [];
        foreach($params['data'] as $key=>$value){
            $channel_id[] = $value['id'];
        }
        $customerData = db("crm_c_customerinfo")->where("customer_channel_id","in",$channel_id)->field("id")->select();
        if(!$customerData){
            return json(['code'=>202,'msg'=>'所选渠道下没有客资!']);
        }
        $customer_id = [];
        $oldlog = [];
        foreach ($customerData as $key => $value) {
            $customer_id[] = $value['id'];
            $oldlog[$key]['customer_id'] = $value['id'];
            $oldlog[$key]['customer_channel_id'] = $value['customer_channel_id'];
            $oldlog[$key]['customer_channel'] = $value['customer_channel'];
        }

        try{
            db("crm_c_customerinfo")->where("id","in",$customer_id)->update(['customer_channel_id'=>$channelData['id'],'customer_channel'=>$channelData['channel_name']]);
        }catch(Exception $e){
            return json(['code'=>202,'msg'=>'转移失败，原因:'.$e->getMessage()]);
        }
        $logdata['customer_id'] = $customer_id;
        $logdata['customer_channel'] = $channelData['channel_name'];
        $logdata['customer_channel_id'] = $channelData['id'];
        action_log($logdata,$oldlog,0,session('staff_id'),session('staff_name'));
        return json(['code'=>200,'msg'=>"转移成功"]);
    }
    /**
     * @cc 添加渠道名称
     * */
    public function addChannel(){
        // 权限
        $auth = check_right('menu1516949559');
        if (!$auth) {
            return $this->redirect('/');
        }
        // 20210201
        $param = input();
        if (!trim($param['channel_name'])) {
            return array('code'=>99,'msg'=>'请填写渠道名称','data'=>$param);
        }
        $channelInfo = db('crm_s_channel')->where('channel_name',trim($param['channel_name']))->find();
        if ($channelInfo) {
            $msg = '渠道名称与'.$channelInfo['shop_name'].'创建的渠道同名。';
            return array('code'=>99,'msg'=>$msg,'data'=>$channelInfo);
        }
        $res = controller('crm/Setting','lib')->addChannel($param);
        return $res;
    }
    /**
     * @cc 查询渠道分享
     * */
    public function getShareShops(){
        $data = input();
        $shops = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id')]);

        $shareShops = db('crm_s_channel')->where('id', (int)$data['id'])->value('share_shops');
        $shareShops = explode(',', $shareShops);
        $return = [];
        foreach ($shops as $key => $value) {
            $return[$key]['shop_name'] = $value['shop_name'];
            $return[$key]['shop_code'] = $value['shop_code'];
            if ( in_array($value['shop_code'],$shareShops) ) {
                $return[$key]['select'] = 1;
            }else{
                $return[$key]['select'] = 0;
            }
        }
        return json($return);
    }
    /**
     * @cc 修改渠道名称
     * */
    public function editchannel(){
        // 权限
        $auth = check_right('menu1516949559');
        if (!$auth) {
            return $this->redirect('/');
        }
        // 20210201
        $param = input();
        if (!trim($param['channel_name'])) {
            return array('code'=>99,'msg'=>'请填写渠道名称','data'=>$param);
        }
        $channelId = (int)$param['id'];
        $channelInfo = db('crm_s_channel')->where('channel_name',trim($param['channel_name']))->where('id','<>',$channelId)->find();
        if ($channelInfo) {
            $msg = '渠道名称与'.$channelInfo['shop_name'].'创建的渠道同名。';
            return array('code'=>99,'msg'=>$msg,'data'=>$channelInfo);
        }
        $res = controller('crm/Setting','lib')->editchannel($param);
        return $res;
    }
    /**
     * @cc 删除渠道名称
     * */
    public function delChannel(){
        // 权限
        $auth = check_right('menu1516949559');
        if (!$auth) {
            return $this->redirect('/');
        }
        
        $res = controller('crm/Setting','lib')->delChannel(input('post.id'));
        return $res;
    }

    public function getChannelToJSON(){
        $param = input('param.');
        $data['page'] = $param['page'];
        $data['limit'] = $param['limit'];
        $data['channel_class_id'] = $param['channel_class_id'];
        $data['channel_info_id'] = $param['channel_info_id'];
        $data['channel_name'] = $param['channel_name'];
        $data['shop_code'] = $param['shop_code'];
        // var_dump($data);die;
        $res = controller('crm/Setting','lib')->getChannelToJSON($data);
        foreach($res['data'] as $key=>$value){
            $res['data'][$key]['rebates_start_time'] = $value['rebates_start_time'] ? date('Y-m-d',strtotime($value['rebates_start_time'])) : '';
            $res['data'][$key]['rebates_end_time'] = $value['rebates_end_time'] ? date('Y-m-d',strtotime($value['rebates_end_time'])) : '';
        }
        return json($res);
    }
    public function getChannelByCid(){
        $res = controller('crm/Setting','lib')->getChannelByCid(input('param.cid'));

        // 南宁qqbaby  2021-03-22
        if (customize('nnqqbaby')) {
            $staffTrench = controller('crm/Setting','lib')->staffTrenchs(input('param.cost_staff_id'));

            if ($staffTrench['trench']) {
                $arr_staffTrench = explode(",",trim($staffTrench['trench'],","));
                if (count($arr_staffTrench) > 0) {
                    foreach ($res as $k => $v) {
                        if (!in_array($v['channel_name'],$arr_staffTrench)) {
                            unset($res[$k]);
                        }
                    }
                }
            }
        }

        return ($res);
    }
    public function province(){
        // 权限
        $auth = check_right('menu1517560908');
        if (!$auth) {
            return $this->redirect('/');
        }
        return $this->fetch();
    }
    public function getMyProvince(){
        //当前店面设定的省市区
        $info = db('crm_s_shop_address')->where('shop_code',session('shop_code'))->field('id')->select();
        return array_column($info,'id');
    }
    //省市区json
    public function getProvinceJSON(){
        return controller('crm/Setting','lib')->getProvinceJSON();
    }
    public function crmProvinceSet(){
        // 权限
        $auth = check_right('menu1517560908');
        if (!$auth) {
            return $this->redirect('/');
        }
        $id = input('post.id');
        return controller('crm/Setting','lib')->crmProvinceSet($id);
    }

    /*  ———————————————————————————————————————— 客资交换（爆破）活动 开始 ————————————————————————————————————————  */
    // 客资交换（客资爆破） 页面
    public function customerSwap(){
        // 权限
        $auth = check_right('menu1521091523');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        // // 查询事业部下所有的店
        // $mcInterface = new mcInterface();
        // $shopList = $mcInterface->getBrandShops(session('brandclass'));

        // $bShop = [];
        // foreach ($shopList as $key => $value) {
        //     if ($bShop[$value['belong_shop_code']]['shop_code'] != $value['belong_shop_code']) {
        //         $bShop[$value['belong_shop_code']]['shop_code'] = $value['belong_shop_code'];
        //         $bShop[$value['belong_shop_code']]['shop_name'] = $value['belong_shop_name'];
        //     }
        // }
        // sort($bShop);
        // $this->assign('bShop', $bShop);

        // 查询当前店下所有的员工
        // $mcInterface = new mcInterface();
        // $staffs = $mcInterface->getStaffsByShopCode(session('shop_code'));

        // $this->assign('staffs', $staffs);

        // 是否是管理员
        // $work_type=explode(',',trim(session('main_work_type').','.session('work_type'),','));
        // if(in_array(SYSTEM_AUTH_ADMIN,$work_type)) {
        //     $power = 1;
        // }else{
        //     $power = 0;
        // }
        // $this->assign('power', $power);

        // 查看爆破设定权限
        $auth = check_right('menu1521093152');
        if ($auth) {
            $addSwap = 1;
        }else{
            $addSwap = 0;
        }

        // 查看客资添加权限
        $auth = check_right('menu1521093203');
        if ($auth) {
            $addCustoemr = 1;
        }else{
            $addCustoemr = 0;
        }

        $this->assign('addSwap', $addSwap);
        $this->assign('addCustoemr', $addCustoemr);
        $this->assign('title', '客资爆破活动');
        return $this->fetch();
    }
    // 获取该店下员工
    public function getCustomerSwapStaffs(){
        // 权限 爆破设定
        $auth = check_right('menu1521091523');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        // 查询当前店下所有的员工
        $mcInterface = new mcInterface();
        $staffs = $mcInterface->getStaffsByShopCode(session('shop_code'));
        foreach ($staffs as $key => $value) {
            $return[$key]['id'] = $value['id'];
            $return[$key]['staffname'] = $value['staffname'];
        }
        return $return;
    }

    // 获取客资爆破列表
    public function getCustomerSwap(){
        // 权限
        $auth = check_right('menu1521091523');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $where = [
            'shop_code' => session('shop_code'),
            'is_del' => 1,
        ];
        $findData['where'] = $where;
        $findData['order'] = 'id desc';
        $findData['field'] = 'id,swap_name,customer_start,customer_end, swap_staff_ids, swap_staff_names, start_date, end_date, create_time, update_time, status';

        $swapList = controller('crm/Setting', 'lib')->getSwapList($findData);
        // 活动状态（1：未开始；2：已开始；3：已结束）
        foreach ($swapList as $key => $value) {
            switch ($value['status']) {
                case '1':
                    $status = '未开始';
                    break;
                case '2':
                    $status = '已开始';
                    break;
                case '3':
                    $status = '已结束';
                    break;
            }
            $swapList[$key]['status'] = $status;
        }
        unset($findData);
        $return = ['code'=>0, 'msg'=>'', 'count'=>count($swapList), 'data'=>$swapList];
        return json($return);
    }

    /**
     * @cc 添加客资爆破设定
     * */
    public function customerSwapSet(){
        // 权限
        $auth = check_right('menu1521093152');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $data = input('post.');
        $today = date('Y-m-d');

        if ($data['startDate'] >= $data['endDate']) {
            $return = array('code'=>1,'msg'=>'活动结束时间应大于活动开始时间');
        }else if ($today > $data['startDate']) {
            $return = array('code'=>1,'msg'=>'活动开始时间应大于'.$today);
        }else if ($today >= $data['endDate']) {
            $return = array('code'=>1,'msg'=>'活动结束时间应大于'.$data['startDate']);
        }else if ($today < $data['customer_start']) {
            $return = array('code'=>1,'msg'=>'客资筛选时间应小于当前时间'.$data['startDate']);
        }else if ($data['customer_end'] < $data['customer_start']) {
            $return = array('code'=>1,'msg'=>'客资筛选结束时间应大于客资筛选开始时间'.$data['startDate']);
        }else{
            $return = controller('crm/Setting', 'lib')->setCustomerSwap($data);
        }

        return json($return);
    }

    /**
     * @cc 获取客资爆破编辑详情
     * */
    public function getCustomerSwapInfo(){
        // 权限
        $auth = check_right('menu1521093152');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $data = input('post.');
        $where = ['id'=>(int)$data['id'], 'shop_code'=>session('shop_code')];
        $swapInfo = db('crm_s_swapset')->where($where)->find();

        if ($swapInfo) {
            $mcInterface = new mcInterface();
            $staffs = $mcInterface->getStaffsByShopCode(session('shop_code'));
            $swap_staff_ids = explode(',',$swapInfo['swap_staff_ids']);
            foreach ($staffs as $key => $value) {
                $return[$key]['id'] = $value['id'];
                $return[$key]['staffname'] = $value['staffname'];
                $is_in = in_array($value['id'], $swap_staff_ids);
                if ($is_in) {
                    $return[$key]['checked'] = 1;
                }else{
                    $return[$key]['checked'] = 2;
                }
            }
        }else{
            $return = ['code'=>1,'msg'=>'活动信息不存在'];
        }
        return $return;
    }

    /**
     * @cc 客资爆破活动编辑
     * */
    public function customerSwapEdit(){
        // 权限
        $auth = check_right('menu1521093152');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $data = input('post.');
        $editData['where'] = ['id'=>(int)$data['id'], 'shop_code'=>session('shop_code')];
        $editData['data']  = $data;
        $editData['type']  = 'edit';

        $result = controller('crm/Setting', 'lib')->editCustomerSwap($editData);

        if ($result['code'] == 200) {
            return array('code'=>200,'msg'=>'编辑客资爆破活动成功');
        }else{
            return array('code'=>$result['code'],'msg'=>'编辑客资爆破活动失败','data'=>$result['data']);
        }
    }

    /**
     * @cc 客资爆破活动删除
     * */
    public function customerSwapDel(){
        // 权限
        $auth = check_right('menu1521093152');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $data = input('post.');
        $editData['where'] = ['id'=>(int)$data['id'], 'shop_code'=>session('shop_code')];
        $editData['type']  = 'del';
        $result = controller('crm/Setting', 'lib')->editCustomerSwap($editData);

        unset($editData);
        switch ($result['code']) {
            case '1':
                $return = ['code'=>1, 'msg'=>'活动不存在'];
                break;
            case '2':
                $return = ['code'=>2, 'msg'=>'活动结束不能删除活动'];
                break;
            case '3':
                $return = ['code'=>3, 'msg'=>'活动开始不能删除活动'];
                break;
            case '4':
                $return = ['code'=>4, 'msg'=>'操作失败', 'data'=>db()->getLastSql()];
                break;
            case '200':
                $return = ['code'=>200,'msg'=>'删除客资成功'];
                break;
        }
        return json($return);
    }

    // 添加爆破客资页面
    public function addCustomerSwap(){
        // 权限
        $auth = check_right('menu1521093203');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有添加客资的权限，请先设置权限');
            return json($return);
        }
        // 客资状态(有效待确定)  有电话号码的   未成交的所有顾客  之前流失的顾客    消费类型(婚纱照)  日期
        // 消费类型，进店状态，是否有效，预约进店时间，客资筛选时间，成交状态，
        $id = (int)input('get.id');
        $swapInfo = db('crm_s_swapset')->where('id', $id)->find();

        if (!$swapInfo) {
            $returnData = array('code'=>100,'error'=>'1','msg'=>'活动信息不存在');
            return $returnData;
        }

        if ($swapInfo['status'] == 2) {
            $returnData = array('code'=>101,'error'=>'1','msg'=>'活动已经开始，不能添加客资');
            return $returnData;
        }

        if ($swapInfo['status'] == 3) {
            $returnData = array('code'=>102,'error'=>'1','msg'=>'活动已经结束，不能添加客资');
            return $returnData;
        }
        // 没有查看所有客资权限，并且不在参与人员中
        $allCustomer = check_right('menu1512637269');
        if (!$allCustomer) {
            $swap_staff_ids = db('crm_s_swapset')->where('id', $id)->value('swap_staff_ids');
            $swap_staff_ids = explode(',', $swap_staff_ids);

            // 员工 不在 参与人员中
            $is_in = in_array(session('staff_id'), $swap_staff_ids);
            if (!$is_in) {
                $return = array('error'=>'1','msg'=>'您没有参与该次客资爆破，请确认。');
                return json($return);
            }
        }

        $this->assign('swap_id', $id);
        $consumptionType=controller("Customer","lib")->consumptionType();
        $this->assign('consumptionType', $consumptionType);

        // 店下所有的部门
        $param['shop_code'] = session('shop_code');
        $department = controller('crm/Setting', 'lib')->department_list($param);
        $this->assign('department', $department);
        $num = count($department);
        if ($num == 1) {
            // 部门下的人 （包括兼职）
            // $url = '5a0e6f272bb38';
            $data['department_id'] = $department[0]['id'];
            $data['get_leave'] = 2;
            // $res = sx_call($url, $data);
            $mc = new \app\common\lib\mcInterface();
            $res = $mc->getStaffByDepartment($data);
            if ($res !== false) {
                $staffs = $res;
            }else{
                $staffs = [];
            }

            $this->assign('staffs', $staffs);
        }else{
            $staffs = [];
            $this->assign('staffs', $staffs);
        }
        // var_dump($staffs);exit;
        return $this->fetch();
    }

    // 查询爆破客资
    public function searchCustomerSwap_old(){
        // 权限
        $auth = check_right('menu1521093203');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $data = input('post.');
        $swap_id = (int)$data['swap_id'];
        $swapInfo = db('crm_s_swapset')->where('id', $swap_id)->find();

        $start = date('Y-m-d 00:00:00', strtotime($swapInfo['customer_start']));
        $end   = date('Y-m-d 23:59:59', strtotime($swapInfo['customer_end']));
        // var_dump($swapInfo);
        // exit;
        $staff_id = session('staff_id');

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['sales_staff_id'] = $staff_id;
        $where['is_success'] = 2;

        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        if ($data['is_intostore']) {
            $where['is_intostore'] = $data['is_intostore'];
        }
        if ($data['is_valid']) {
            $where['is_valid'] = $data['is_valid'];
        }
        switch ($data['contact']) {
            case '1':
                $sql = ' customer_tel IS NOT NULL ';
                break;
            case '2':
                $sql = ' customer_wechat IS NOT NULL ';
                break;
            case '3':
                $sql = ' customer_qq IS NOT NULL ';
                break;
        }
        $custoemrList = db('crm_c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where('dj_day', 'between time', [$start, $end])
            // ->where('yjd_day', 'null')
            ->field('id,customer_number,customer_name,sign_name,sales_staff')
            ->order('id desc')
            ->select();
        // echo db()->getLastSql();exit;
        return json($custoemrList);
    }
    // 查询爆破客资 动态表格获取数据
    public function searchCustomerSwap(){
        // 权限
        $auth = check_right('menu1521093203');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $data = input('get.');

        $swap_id = (int)$data['swap_id'];

        $swapInfo = db('crm_s_swapset')->where('id', $swap_id)->find();

        $start = date('Y-m-d 00:00:00', strtotime($swapInfo['customer_start']));
        $end   = date('Y-m-d 23:59:59', strtotime($swapInfo['customer_end']));
        // var_dump($swapInfo);
        // exit;
        $staff_id = session('staff_id');

        $where['is_status'] = 1;
        $where['c_from'] = 1;
        // $where['sales_staff_id'] = $staff_id;
        $where['shop_code'] = session('shop_code');
        $where['is_success'] = 2;

        if ($data['consultation_type_id']) {
            $where['consultation_type_id'] = $data['consultation_type_id'];
        }
        if ($data['is_intostore']) {
            $where['is_intostore'] = $data['is_intostore'];
        }
        if ($data['is_valid']) {
            $where['is_valid'] = $data['is_valid'];
        }

        switch ($data['contact']) {
            case '1':
                $sql = ' customer_tel IS NOT NULL ';
                break;
            case '2':
                $sql = ' customer_wechat IS NOT NULL ';
                break;
            case '3':
                $sql = ' customer_qq IS NOT NULL ';
                break;
        }

        if (!empty($data['staffs'])) {
            $staffs = implode($data['staffs'], ',');
            $staff_sql = ' sales_staff_id IN ('.$staffs.') ';
        }

        if ($data['yjd_day']) {
            $yjd_day = date('Y-m-d H:i:s', strtotime($data['yjd_day']));
            $yjd_sql = " yjd_day < '$yjd_day'";
        }

        $custoemrList = db('crm_c_customerinfo')
            ->where($where)
            ->where($sql)
            ->where($yjd_sql)
            ->where($staff_sql)
            ->where('dj_day', 'between time', [$start, $end])
            ->field('id,customer_number,customer_name,sign_name,sales_staff')
            ->order('id desc')
            ->select();
        $returnData = [
            'code'  => 0,
            'msg'   => '',
            'count' => count($custoemrList),
            'data'  => $custoemrList,
        ];
        return json($returnData);
    }

    /**
     * @cc 添加 参与爆破的客资
     * */
    public function actionCustomerSwap(){
        // 权限
        $auth = check_right('menu1521093203');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $data = input('post.');
        // var_dump($data);
        // exit;
        $swap_id = (int)$data['sid'];
        $cid = json_decode($data['cid'], true);
        $ids = implode(',', $cid);
        $day = date('Y-m-d H:i:s');
        $staff_id = session('staff_id');
        $swap_number = db('crm_s_swapset')->where('id', $swap_id)->value('swap_number');
        $sNumbers = db('crm_c_swap_customer')
            ->where('swap_number',$swap_number)
            // ->where('sales_staff_id', $staff_id)
            ->column('customer_number');

        // 插入到客资交换表中的数据
        $inData = [];
        // 是否添加过客资  如果添加过客资，需要排重
        if ($sNumbers) {
            $cNumbers = db('crm_c_customerinfo')->where('id', 'in', $ids)->field('id,customer_number,is_valid,yjd_day,is_intostore,is_success,brandclass_id,brandclass,shop_code,shop_name')->select();

            // 取两个数组的差集合
            // $result=array_diff($a1,$a2);
            foreach ($cNumbers as $key => $value) {
                $is_in = in_array($value['customer_number'], $sNumbers);
                if (!$is_in) {
                    $inData[$key] = [
                        'swap_number'       => $swap_number,
                        'customer_number'   => $value['customer_number'],
                        'c_is_valid'        => $value['is_valid'],
                        'c_yjd_day'         => $value['yjd_day'],
                        'c_is_intostore'    => $value['is_intostore'],
                        'c_is_success'      => $value['is_success'],
                        // 'sales_staff_id'    => $staff_id,
                        'brandclass_id'     => $value['brandclass_id'],
                        'brandclass'        => $value['brandclass'],
                        'shop_code'         => $value['shop_code'],
                        'shop_name'         => $value['shop_name'],
                        'create_time'       => $day,
                    ];
                }
            }
        }else{
            // 该员工 参与 客资爆破的 客资列表
            $customtList = db('crm_c_customerinfo')
                ->where('id', 'in', $ids)
                ->field('id,customer_number,is_valid,is_intostore,is_success,brandclass_id,brandclass,shop_code,shop_name')
                ->select();
            // 重新随机分配，记录客资爆破表，并且，客资表要标记这些客资参与活动
            $day = date('Y-m-d H:i:s');
            foreach ($customtList as $key => $value) {
                // $saveData[$key] = ['id'=>$value['id'],'is_act'=>2];
                $inData[$key] = [
                    'swap_number'       => $swap_number,
                    'customer_number'   => $value['customer_number'],
                    'c_is_valid'        => $value['is_valid'],
                    'c_is_intostore'    => $value['is_intostore'],
                    'c_is_success'      => $value['is_success'],
                    // 'sales_staff_id'    => session('staff_id'),
                    'brandclass_id'     => $value['brandclass_id'],
                    'brandclass'        => $value['brandclass'],
                    'shop_code'         => $value['shop_code'],
                    'shop_name'         => $value['shop_name'],
                    'create_time'       => $day,
                ];
            }
        }

        db()->startTrans();
        try {
            // 批量插入爆破表
            $resS = db('crm_c_swap_customer')->insertAll($inData);
            db()->commit();
            // 成功， 加日志
            history_log($cid,$sNumbers,'',session('staff_id'),session('staff_name'));
            $retrunData = array('code'=>200,'msg'=>'添加客资成功');
        } catch (Exception $e) {
            db()->rollback();
            $retrunData = array('code'=>200,'msg'=>'添加客资失败','data'=>$e->getMessage());
        }
        return $retrunData;
    }

    // 客资交换 （客资爆破） 开始  （系统内置客资筛选条件）
    public function customerSwapStart_old(){
        // 权限
        $auth = check_right('menu1521093152');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        $today = date('Y-m-d');
        $id = (int)input('post.id');
        $swap = db('crm_s_swapset')->where('id',$id)->where('is_del', 1)->find();
        if (!$swap) {
            $return = ['code'=>1, 'msg'=>'活动不存在'];
            return json($return);
        }
        if ($swap['status'] == 2) {
            $return = ['code'=>1, 'msg'=>'活动已经开始'];
            return json($return);
        }else if ($swap['status'] == 3) {
            $return = ['code'=>2, 'msg'=>'活动已经结束'];
            return json($return);
        }

        // 根据客资开始时间和人员取客资
        $where['is_status'] = 1;
        $where['c_from'] = 1;
        $where['consultation_type_id'] = HS_TYPE;
        $where['is_intostore'] = 1;
        $where['is_success'] = 2;
        $where['is_valid'] = 1;
        $where['is_loss'] = 2;
        // 婚纱类型，未进店、没有成交、标记为有效、没有标记不在追踪、不存在预约进店时间，且登记时间在活动标记范围内  的客资
        $customtList = db('crm_c_customerinfo')
            ->where($where)
            ->where('dj_day', 'between time', [$swap['customer_start'], date('Y-m-d 23:59:59', strtotime($swap['customer_end']))])
            ->where('sales_staff_id', 'in', $swap['swap_staff_ids'])
            ->where('yjd_day','null')
            ->field('id,customer_number,is_valid,is_intostore,is_success,brandclass_id,brandclass,shop_code,shop_name')
            ->select();
        // 待交换的员工数组
        $temp = explode(',',$swap['swap_staff_ids']);
        foreach ($temp as $key => $value) {
            // var_dump($value);
            $info = getStaffInfoById($value);
            // var_dump($info);

            $staffs[$value]['staff_id'] = $value;
            $staffs[$value]['staff_name'] = $info['staffname'];
            $staffs[$value]['staff_number'] = $info['staffnumber'];
        }
        // $staff7 = getStaffInfoById(5);
        // var_dump($staff7);
        // exit;
        // 插入到客资交换表中的数据
        $inData = [];
        // 更新客资表的数据
        $saveData = [];
        // 重新随机分配，记录客资爆破表，并且，客资表要标记这些客资参与活动
        $day = date('Y-m-d H:i:s');
        foreach ($customtList as $key => $value) {
            $saveData[$key] = ['id'=>$value['id'],'is_act'=>2];

            // 随机取人
            $sid = array_rand($temp, 1);
            $inData[$key] = [
                'swap_number'       => $swap['swap_number'],
                'customer_number'   => $value['customer_number'],
                'c_is_valid'        => $value['is_valid'],
                'c_is_intostore'    => $value['is_intostore'],
                'c_is_success'      => $value['is_success'],
                'sales_staff_id'    => $staffs[$sid]['staff_id'],
                'sales_staff_name'  => $staffs[$sid]['staff_name'],
                'sales_staff_number'=> $staffs[$sid]['staff_number'],
                'brandclass_id'     => $value['brandclass_id'],
                'brandclass'        => $value['brandclass'],
                'shop_code'         => $value['shop_code'],
                'shop_name'         => $value['shop_name'],
                'create_time'       => $day,
            ];
        }

        // 这里需要一个action_log

        db()->startTrans();
        try {
            // 批量更新客资表
            $cInfo = Model('C_customerinfo');
            $resC = $cInfo->saveAll($saveData);

            // 批量插入爆破表
            $resS = db('crm_c_swap_customer')->insertAll($inData);

            // 更新爆破设定表
            $swapData['status']=2;
            $swapData['update_time'] = $day;
            $res = db('crm_s_swapset')->where('id', $id)->update($swapData);
            db()->commit();
            // 成功， 加日志
            history_log($swapData,$swap,'',session('staff_id'),session('staff_name'));
            $retrunData = array('code'=>200,'msg'=>'活动开启');
        } catch (Exception $e) {
            db()->rollback();
            $retrunData = array('code'=>200,'msg'=>'开启失败','data'=>$e->getMessage());
        }
        return $retrunData;
    }

    public function checkCustomerSwap(){
        // 权限
        $auth = check_right('menu1521093152');
        if (!$auth) {
            $returnData = array('code'=>100,'msg'=>'没有该权限，请联系管理员！');
            return $returnData;
        }
        $id = (int)input('post.id');
        $swapInfo = db('crm_s_swapset')->where('id', $id)->find();
        if (!$swapInfo) {
            $returnData = array('code'=>100,'msg'=>'活动信息不存在');
            return $returnData;
        }
        if ($swapInfo['status'] == 2) {
            $returnData = array('code'=>101,'msg'=>'活动已经开始');
            return $returnData;
        }
        if ($swapInfo['status'] == 3) {
            $returnData = array('code'=>102,'msg'=>'活动已经结束');
            return $returnData;
        }
        return array('code' => 200, 'msg'=>'success');
    }
    // 开始爆破页面
    public function startCustomerSwap(){
        // 权限
        $auth = check_right('menu1521093152');
        if (!$auth) {
            $this->assign('error',1);
            $this->assign('msg','没有该权限，请联系管理员');
            return $this->fetch();
//            $returnData = array('code'=>100,'msg'=>'没有该权限，请联系管理员！');
//            return $returnData;
//            exit;
        }

        $id = (int)input('get.id');
        $this->assign('swap_id', $id);
        $swapInfo = db('crm_s_swapset')->where('id', $id)->find();

        if (!$swapInfo) {
            $this->assign('error',1);
            $this->assign('msg','活动信息不存在');
            return $this->fetch();
//            $returnData = array('code'=>100,'msg'=>'活动信息不存在');
//            return $returnData;
        }

        if ($swapInfo['status'] == 2) {
            $this->assign('error',1);
            $this->assign('msg','活动已经开始');
            return $this->fetch();
//            $returnData = array('code'=>101,'msg'=>'活动已经开始');
//            return $returnData;
        }

        if ($swapInfo['status'] == 3) {
            $this->assign('error',1);
            $this->assign('msg','活动已经结束');
            return $this->fetch();
//            $returnData = array('code'=>102,'msg'=>'活动已经结束');
//            return $returnData;
        }

        // 查询所有参与爆破的客资
        $num = db('crm_c_swap_customer')
            ->where('swap_number', $swapInfo['swap_number'])
            ->count();
        if ($num) {
            $this->assign('num', $num);
        }else{
            $this->assign('error',1);
            $this->assign('msg','爆破活动暂无客资，请先添加客资');
            return $this->fetch();
//            $returnData = array('code'=>103,'msg'=>'爆破活动暂无客资，请先添加客资');
//            return $returnData;
        }

        // 员工列表
        $staffs = [];
        $staff_ids  = explode(',', $swapInfo['swap_staff_ids']) ;
        $staff_names= explode(',', $swapInfo['swap_staff_names']) ;
        foreach ($staff_ids as $key => $value) {
            $staffs[$key]['staff_id'] = $value;
            $staffs[$key]['staff_name'] = $staff_names[$key];
        }
        $this->assign('staffs', $staffs);
        return $this->fetch();
    }

    /**
     * @cc 开始 客资爆破
     * */
    public function customerSwapStart(){
        // 权限
        $auth = check_right('menu1521093152');
        if (!$auth) {
            $returnData = array('code'=>99,'msg'=>'没有该权限，请联系管理员！');
            return $returnData;
            exit;
        }

        $data = input('post.');
        $id = (int)$data['swap_id'];
        unset($data['swap_id']);
        $swapInfo = db('crm_s_swapset')->where('id', $id)->find();

        if (!$swapInfo) {
            $returnData = array('code'=>100,'msg'=>'活动信息不存在');
            return $returnData;
        }

        if ($swapInfo['status'] == 2) {
            $returnData = array('code'=>101,'msg'=>'活动已经开始');
            return $returnData;
        }

        if ($swapInfo['status'] == 3) {
            $returnData = array('code'=>102,'msg'=>'活动已经结束');
            return $returnData;
        }

        // 查询所有参与爆破的客资
        $cInfo = db('crm_c_swap_customer')
            ->where('swap_number', $swapInfo['swap_number'])
            ->column('customer_number');
        $swap_num = count($cInfo);

        if ($swap_num < 0) {
            $returnData = array('code'=>103,'msg'=>'爆破活动暂无客资，请先添加客资');
            return $returnData;
        }
        $num = 0;
        foreach ($data as $key => $value) {
            $num += $value;
        }
        if ($num > $swap_num) {
            $returnData = array('code'=>104,'msg'=>'待分配客资数小于0，请重新设置');
            return $returnData;
        }

        // 查询所有参与爆破的客资详情
        $cNumbers = implode(',', $cInfo);
        $customtList = db('crm_c_customerinfo')->alias('c')
            ->join('crm_c_swap_customer s', 's.customer_number=c.customer_number')
            ->where('s.customer_number', 'in', $cNumbers)
            ->field('s.id,c.id as cid,c.customer_number,c.is_valid,c.yjd_day,c.yjd_action_day,c.is_intostore,c.is_success,c.brandclass_id,c.brandclass,c.shop_code,c.shop_name')
            ->select();
        // 员工信息
        $staffs = [];
        foreach ($data as $key => $value) {
            $info = getStaffInfoById($key);

            $staffs[$key]['staff_id']      = $key;
            $staffs[$key]['staff_name']    = $info['staffname'];
            $staffs[$key]['staff_number']  = $info['staffnumber'];
            // 将要获得多少爆破客资
            $staffs[$key]['will_swap_num'] = $value;
        }

        $staffs = my_sort($staffs,'will_swap_num');
        // 更新客资交换表中的数据
        $sData = [];
        // 更新客资表的数据
        $cData = [];

        foreach ($customtList as $key => $value) {
            $temp = end($staffs);
            if ($temp['will_swap_num'] > 0) {
                $sData[$key] = [
                    'id'                => $value['id'],
                    'c_is_valid'        => $value['is_valid'],
                    'c_yjd_day'         => $value['yjd_day'],
                    'c_is_intostore'    => $value['is_intostore'],
                    'c_is_success'      => $value['is_success'],
                    'sales_staff_id'    => $temp['staff_id'],
                    'sales_staff_name'  => $temp['staff_name'],
                    'sales_staff_number'=> $temp['staff_number'],
                ];
                $staff_key = count($staffs)-1;
                $staffs[$staff_key]['will_swap_num']--;
                if ($staffs[$staff_key]['will_swap_num']==0) {
                    unset($staffs[$staff_key]);
                }
            }else{
                // 随机取人
                $sid = array_rand($staffs, 1);

                $sData[$key] = [
                    'id'                => $value['id'],
                    'c_is_valid'        => $value['is_valid'],
                    'c_yjd_day'         => $value['yjd_day'],
                    'c_is_intostore'    => $value['is_intostore'],
                    'c_is_success'      => $value['is_success'],
                    'sales_staff_id'    => $staffs[$sid]['staff_id'],
                    'sales_staff_name'  => $staffs[$sid]['staff_name'],
                    'sales_staff_number'=> $staffs[$sid]['staff_number'],
                ];
            }

            // 更新客资信息
            $cData[$key] = ['id'=>$value['cid'],'is_act'=>2];
        }
        unset($staffs);
        unset($customtList);
        // 这里需要一个action_log


        db()->startTrans();
        try {
            // 批量更新客资表
            $cInfo = Model('c_customerinfo');
            $resC = $cInfo->saveAll($cData);

            // 批量更新爆破表
            $sInfo = Model('c_swap_customer');
            $resS = $sInfo->saveAll($sData);

            // 更新爆破设定表
            $swapData['status']=2;
            $swapData['update_time'] = date('Y-m-d H:i:s');
            $res = db('crm_s_swapset')->where('id', $id)->update($swapData);
            db()->commit();
            // 成功， 加日志
            history_log($swapData,$swapInfo,'',session('staff_id'),session('staff_name'));
            $retrunData = array('code'=>200,'msg'=>'活动开启');
        } catch (Exception $e) {
            db()->rollback();
            $retrunData = array('code'=>200,'msg'=>'开启失败','data'=>$e->getMessage());
        }
        return $retrunData;
    }

    /**
     * @cc 结束 客资爆破
     * */
    public function customerSwapEnd(){
        // 权限
        // $auth = check_right('menu1521093152');
        // if (!$auth) {
        //     controller('crm/Index','controller')->index();
        //     exit;
        // }
        $id = (int)input('post.id');
        $swapInfo = db('crm_s_swapset')->where('id', $id)->find();

        if (!$swapInfo) {
            $returnData = array('code'=>100,'msg'=>'活动信息不存在');
            return $returnData;
        }

        if ($swapInfo['status'] == 1) {
            $returnData = array('code'=>101,'msg'=>'活动还未开始');
            return $returnData;
        }

        if ($swapInfo['status'] == 3) {
            $returnData = array('code'=>102,'msg'=>'活动已经结束');
            return $returnData;
        }
        $customtList = db('crm_c_customerinfo')->alias('c')
            ->join('crm_c_swap_customer s', 's.customer_number=c.customer_number')
            ->where('s.swap_number', $swapInfo['swap_number'])
            ->field('s.id,s.sales_staff_id,s.sales_staff_name,s.sales_staff_number,c.id as cid,c.customer_number,c.is_valid,c.yjd_day,c.yjd_action_day,c.is_intostore,c.is_success,c.brandclass_id,c.brandclass,c.shop_code,c.shop_name,c.sales_staff,c.sales_staff_id as staff_id,c.sales_staff_number as staff_number')
            ->select();
        // echo db()->getLastSql();
        // exit;
        // 更新客资交换表中的数据
        $sData = [];
        // 更新客资表的数据
        $cData = [];
        foreach ($customtList as $key => $value) {
            // 交换表 更新最新状态
            $sData[$key] = [
                'id'           => $value['id'],
                'is_valid'     => $value['is_valid'],
                'yjd_day'      => $value['yjd_day'],
                'is_intostore' => $value['is_intostore'],
                'is_success'   => $value['is_success'],
            ];

            // 标记进客进店  客资表状态修改
            if ($value['is_intostore'] == 2) {
                $cData[$key] = [
                    'id' => $value['cid'],
                    'sales_staff' => $value['sales_staff_name'],
                    'sales_staff_id' => $value['sales_staff_id'],
                    'sales_staff_number' => $value['sales_staff_number'],
                    'is_act' => 1,
                ];
            }
            // 其他标记
            else{
                $cData[$key] = [
                    'id' => $value['cid'],
                    'sales_staff' => $value['sales_staff'],
                    'sales_staff_id' => $value['staff_id'],
                    'sales_staff_number' => $value['staff_number'],
                    'is_act' => 1,
                ];
            }
        }
        // var_dump($cData);
        // var_dump($sData);
        // exit;

        // 这里需要一个action_log

        db()->startTrans();
        try {
            // 批量更新客资表
            $cInfo = Model('c_customerinfo');
            $resC = $cInfo->saveAll($cData);
            // var_dump($res);
            // 批量更新爆破表
            $sInfo = Model('c_swap_customer');
            $resS = $sInfo->saveAll($sData);

            // 更新爆破设定表
            $swapData['status']=3;
            $swapData['update_time'] = date('Y-m-d H:i:s');
            $res = db('crm_s_swapset')->where('id', $id)->update($swapData);
            db()->commit();
            // 成功， 加日志
            history_log($swapData,$swapInfo,'',session('staff_id'),session('staff_name'));
            $retrunData = array('code'=>200,'msg'=>'活动结束');
        } catch (Exception $e) {
            db()->rollback();
            $retrunData = array('code'=>200,'msg'=>'操作失败','data'=>$e->getMessage());
        }
        return $retrunData;
    }

    // 客资交换 （客资爆破） 详情
    public function customerSwapTable(){
        // 权限
        $auth = check_right('menu1521093152');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }

        $id = (int)input('get.sid');
        $swapInfo = db('crm_s_swapset')->where('id', $id)->find();
        $start = date('Y-m-d 00:00:00', strtotime($swapInfo['start_date']));
        $end   = date('Y-m-d 23:59:59', strtotime($swapInfo['end_date']));
        $swap_staff_ids = explode(',',$swapInfo['swap_staff_ids']);
        $returnData = [];
        foreach ($swap_staff_ids as $key => $value) {
            $info = getStaffInfoById($value);
            $returnData[$key]['staff_name'] = $info['staffname'];
            // 拨打客资总数
            $returnData[$key]['tel_number'] = db('crm_c_swap_customer')->where('sales_staff_id', $value)->count('id');
            // 预约进店时间在活动期间的
            $returnData[$key]['yjd_number'] = db('crm_c_swap_customer')->where('sales_staff_id', $value)->where('yjd_day', 'between time', [$start, $end])->count('id');
            // 活动外进店 （实际进店 进店进客）
            $returnData[$key]['cyjd_number'] = db('crm_c_customerinfo')
                ->where('is_act', 1)
                ->where('sales_staff_id', $value)
                ->where('is_intostore', 2)
                ->where('syjd_day', 'between time', [$start, $end])
                ->count('id');
            // 活动内进店 （实际进店 进店进客）
            $returnData[$key]['into_number']= db('crm_c_swap_customer')->where('sales_staff_id', $value)->where('is_intostore', 2)->count('id');
            // 活动内成交
            $returnData[$key]['success_num']= db('crm_c_swap_customer')->where('sales_staff_id', $value)->where('is_success', 1)->count('id');
        }
        $need = (int)input('get.need');
        // 导出
        if ($need == 1) {
            $title=array('网销人员','拨打客资数','活动期间预进店数','活动外进店','活动内进店','活动内成交');

            $file = 'customerSwapTable.xlsx';
            controller("crm/Customer","lib")->export($title,$returnData,$file);
        }else{
            $this->assign('returnData', $returnData);
            $this->assign('title', '客资爆破统计数据');
            return $this->fetch();
        }
    }
    /*  ———————————————————————————————————————— 客资交换（爆破）活动 结束 ————————————————————————————————————————  */
    //统计报表列表
    public function statistics_list(){
        // $info = db('crm_s_menu')
        //     ->where('fid',5)
        //     ->where('menu_code','<>','menu1523775076')
        //     ->order('sort asc')
        //     ->select();
        // $res = db_config('statistics_'.session('shop_code'));
        // foreach($info as $k=>$v){
        //     if(in_array($v['id'],$res['ids'])){
        //         $info[$k]['is_checked'] = 1;
        //     }else{
        //         $info[$k]['is_checked'] = 0;
        //     }
        // }
        // $this->assign('info',$info);

        //判断是否有report_type_name，没有的话crm_s_report_form表生成一次
        $report_form = db("crm_s_report_form")->field("report_type_name")->where("report_type_name","not null")->group("report_type_name")->select();
        if (count($report_form)==0) {
            $type_arr = array(1=>'电商',2=>'实体店',3=>'网销',4=>'转介绍');
            foreach ($type_arr as $key => $value) {
                db('crm_s_report_form')->where('report_type',$key)->update(["report_type_name"=>$value]);
            }
        }
        $type_arr = db("crm_s_report_form")->where("report_type_name","not null")->group("report_type_name")->column("report_type_name");

        $this->assign('type_arr',$type_arr);
        return $this->fetch();
    }
    public function statisticsLists(){
        $info = db('crm_s_menu')
            ->where('fid',5)
            ->where('menu_code','<>','menu1523775076')
            ->order('sort asc')
            ->select();
        $res = db_config('statistics_'.session('shop_code'));
        foreach($info as $k=>$v){
            if(in_array($v['id'],$res['ids'])){
                $info[$k]['is_checked'] = 1;
            }else{
                $info[$k]['is_checked'] = 0;
            }
        }
        $this->assign('info',$info);
        return $this->fetch();
    }
    public function statistics_list_data(){
        $data = input();
        // 20200630
        $param['report_type_name'] = $data['report_type_name'];
        $param['page'] = $data['page'];
        $param['limit'] = $data['limit'];
        return controller('crm/Setting','lib')->statistics_list_data($param);
    }
    //店面返点标准设定
    public function shop_return_setting(){
        // 权限
        $auth = check_right('menu1521280345');
        if (!$auth) {
            return $this->redirect('/');
        }
        //获取渠道
        $channel = controller('crm/Customer','lib')->getChannel();
        $this->assign('channel',$channel);
        return $this->fetch();
    }
    /**
     * @cc 增加 店面返点标准
     * */
    public function addShopReturnSetting(){
        $data = input();
        return controller('crm/Setting','lib')->addShopReturnSetting($data);
    }
    /**
     * @cc 编辑 店面返点标准
     * */
    public function editShopReturnSetting(){
        $data = input();
        return controller('crm/Setting','lib')->editShopReturnSetting($data);
    }
    /**
     * @cc 删除 店面返点标准
     * */
    public function delShopReturnSetting(){
        $data = input();
        return controller('crm/Setting','lib')->delShopReturnSetting($data);
    }
    public function getShopReturnSettingToJSON(){
        $param = input();
        $limit = $param['limit'] ? $param['limit'] : 10;
        $page = $param['page'] ? $param['page'] : 1;
        $result['code'] = 0;
        $result['msg'] = '';
        $result['data'] = db('crm_s_shop_return_rule')->where('shop_code',session('shop_code'))->where('brandclass_id',session('brandclass_id'))->limit($limit)->page($page)->select();
        $result['count'] = db('crm_s_shop_return_rule')->where('shop_code',session('shop_code'))->where('brandclass_id',session('brandclass_id'))->count();
        return json($result);

    }
    /**
     * @cc erp开关设定
     * */
    public function erpSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input('post.');

        if(empty($data)){
            $erp = db_config('sx_erp_'.session('brandclass_id'));
            $this->assign('erp_switch',$erp);//ERP开关
            // 颜色配置
            // 2020-08-05 去掉列表页选中颜色
            // $on_select_color = db_config('on_select_color');
            // $this->assign('on_select_color',$on_select_color);
            // $hover_color = db_config('hover_color');
            // $this->assign('hover_color',$hover_color);
            // 2020-08-05 去掉隔行变色
            // $alt_row_color = db_config('alt_row_color');
            // $this->assign('alt_row_color',$alt_row_color);
            $success_color = db_config('success_color');
            $this->assign('success_color',$success_color);
            $into_color = db_config('into_color');
            $this->assign('into_color',$into_color);
            $loss_color = db_config('loss_color');
            $this->assign('loss_color',$loss_color);
            $erp_loss_color = db_config('erp_loss_color');
            $this->assign('erp_loss_color',$erp_loss_color);
            $int_no_suc_color = db_config('int_no_suc_color');
            $this->assign('int_no_suc_color',$int_no_suc_color);
            $unvalid_color = db_config('unvalid_color');
            $this->assign('unvalid_color',$unvalid_color);
            $yy_no_into_color = db_config('yy_no_into_color');
            $this->assign('yy_no_into_color',$yy_no_into_color);
            $bh_color = db_config('bh_color');
            $this->assign('bh_color',$bh_color);
            $bh_color_fan = db_config('bh_color_fan');
            $this->assign('bh_color_fan',$bh_color_fan);
            $urgent_color = db_config('urgent_color');
            $this->assign('urgent_color',$urgent_color);
            $service_end = db_config('service_end');
            $this->assign('service_end',$service_end);
            $service_start = db_config('service_start');
            $this->assign('service_start',$service_start);
            $service_no = db_config('service_no');
            $this->assign('service_no',$service_no);
            /*--------------------- 录入配置--------------------- */
            // 客资录入类型
            $customer_type = explode(',', db_config('customer_type_'.session('shop_code')));
            if (!$customer_type) {
                // 当前店面是否为转介绍客资接入店
                $mc = new \app\common\lib\mcInterface();
                $shopInfo = $mc->getShopInfo(array('shop_code' => session('shop_code')));
                // var_dump($shopInfo);
                // 如果是转介绍客资接入店，
                if ($shopInfo[0]['is_dig'] == 1) {
                    $customer_type[0]=2;
                }else{
                    $customer_type[0]=1;
                }
            }
            // var_dump($customer_type);
            $this->assign('customer_type', $customer_type);
            // 手机号地址配置
            $this->assign('teladdress',grtTelAddressRegular());
            // 手机归属地接口密钥
            $secret_key = db_config('sx_secret_key_'.session('shop_code'));
            $this->assign('secret_key',$secret_key);
            // 转介绍次数限制
            $num = db_config('zhuanjieshao_number_'.session('shop_code'));
            $this->assign('zhuanjieshao_number',$num);
            // 客资提报归属店配置
            $shops = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id')]);
            $this->assign('shops',$shops);
            //已设置的归属店
            $checked_shop = db_config('dj_shops_'.session('shop_code'));
            if(!is_array($checked_shop)){
                $checked_shop = json_decode($checked_shop,true);
            }
            $check1 = array_column($checked_shop,'shop_code');
            $this->assign('check',$check1);
            // 录入(导入)短信模板
            // $model = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('status',1)->select();
            // $this->assign('model_dj',$model);
            // 客资有效期
            $this->assign('valid_date',session('valid_date'));
            // 客资过期判定规则
            $rule = db_config('valid_date_rule');
            $this->assign('rule',$rule);
            // 录入客资 填写时间 是否为当天
            $this->assign( 'record_day',db_config('record_day_'.session('shop_code')) );
            // 客资重复审核配置 这个暂时不用了
            // $examine= db_config('cus_examine_'.session('shop_code'));
            // $this->assign('examine',$examine);
            // 客资过期录入是否提示设定 这个暂时不用了
            // $valid_date_notice = db_config('valid_date_notice');
            // $this->assign('valid_date_notice',$valid_date_notice);
            // 客资重复是否提示  这个暂时不用了
            // $cus_repeat_notice = db_config('cus_repeat_notice');
            // $this->assign('cus_repeat_notice',$cus_repeat_notice);
            // 客资排重排除范围  这个暂时不用了
            //客资不判重配置--哪些状的客资不作判断范围内，默认情况是已订单和已删除客资，在此基础上再增加如无效，不再追踪等
            //传为逗号分隔，如：unvalid,lossed
            $unrepeatStatus = explode(',', db_config('unrepeat_status'));
            $this->assign('unrepeat_status',$unrepeatStatus);
            //排重方式
            $this->assign('customer_repeat_method',db_config('customer_repeat_method'));

            // 录入必选项配置
            $lrMust = db_config('lr_must_'.session('brandclass_id'));
            $lrMust = explode(',',$lrMust);
            $this->assign('lrMust',$lrMust);
            // 录入隐藏
            $hidden = db_config('lr_hidden_'.session('brandclass_id'));
            $hidden = explode(',',$hidden);
            $this->assign('lrHidden',$hidden);

            /*--------------------- 录入配置--------------------- */

            $erp = db_config('sx_erp_'.session('brandclass_id'));
            $this->assign('erp_switch',$erp);//ERP开关
            $secret_key = db_config('sx_secret_key_'.session('shop_code'));
            $this->assign('secret_key',$secret_key);//短信秘钥
            $sms = db_config('sms_'.session('shop_code'));
            $this->assign('sms',$sms);//短信账号

            //当前店本地城市配置
            $param['type'] = 2;
            $param['shop_code'] = session('shop_code');
            $city = controller('crm/Customer','lib')->address($param);
            $this->assign('city',$city);
            $city_id = db_config('sx_city_id_'.session('brandclass_id'));
            $this->assign('city_id',$city_id);//当前城市
            
            //事业部下的网销店
            $shops = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id')]);
            $this->assign('shops',$shops);
            //已设置的归属店
            $checked_shop = db_config('dj_shops_'.session('shop_code'));
            if(!is_array($checked_shop)){
                $checked_shop = json_decode($checked_shop,true);
            }
            $check1 = array_column($checked_shop,'shop_code');
            $this->assign('check',$check1);

            //电访必选项配置
            $dfMust = db_config('df_must_'.session('brandclass_id'));
            $dfMust = explode(',',$dfMust);
            $this->assign('dfMust',$dfMust);

            //电访必选项配置
            $dfHidden = db_config('df_hidden_'.session('brandclass_id'));
            $dfHidden = explode(',',$dfHidden);
            $this->assign('dfHidden',$dfHidden);
            // 店内所有人
            $mc = new \app\common\lib\mcInterface();
            $shop_staff = $mc->getStaffs( array('shop_code'=>session('shop_code')) );
            $this->assign('shop_staff',$shop_staff);
            // 驳回客资接收人 （设定） 
            $reject_staff = db_config('reject_staff_'.session('shop_code'));
            $this->assign('reject_staff',$reject_staff);
            //订单后配置
            $ddMust = db_config('dd_must_'.session('brandclass_id'));
            $ddMust = explode(',',$ddMust);
            $this->assign('ddMust',$ddMust);
            // 订单客资是否允许分配：
            $orderCusIsAllowFp = db_config('orderCusIsAllowFp_'.session('brandclass_id'));
            $this->assign('orderCusIsAllowFp',$orderCusIsAllowFp);
            // 启用预约进店排控
            $yjd_ctrl_set = db_config('yjd_ctrl_set_'.session('shop_code'));
            $this->assign('yjd_ctrl_set',$yjd_ctrl_set);
            $yjd_time_area=db('crm_l_yjd_ctrl')->where('shop_code',session('shop_code'))->field('time_area')->order('id')->group('time_area')->select();
            $this->assign('yjd_time_area',$yjd_time_area);
            $intentionShop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id'),'is_marketing'=>2]);
            $this->assign('intentionShop',$intentionShop);
            
            // 客资录入类型
            $customer_type = explode(',', db_config('customer_type_'.session('shop_code')));
            $mc = new \app\common\lib\mcInterface();
            if (!$customer_type) {
                // 当前店面是否为转介绍客资接入店
                $shopInfo = $mc->getShopInfo(array('shop_code' => session('shop_code')));
                // var_dump($shopInfo);
                // 如果是转介绍客资接入店，
                if ($shopInfo[0]['is_dig'] == 1) {
                    $customer_type[0]=2;
                }else{
                    $customer_type[0]=1;
                }
            }
            // var_dump($customer_type);
            $this->assign('customer_type', $customer_type);
            // exit;
            
            //预约短信模板
            $yyModel  = db_config('yy_sms_model_'.session('shop_code'));
            $this->assign('yyModel',$yyModel);

            //上门拍短信模板
            $smpModel  = db_config('smp_sms_model_'.session('shop_code'));
            $this->assign('smpModel',$smpModel);

            //催拍短信模板
            $cuipaiModel  = db_config('cuipai_sms_model_'.session('shop_code'));
            $this->assign('cuipaiModel',$cuipaiModel);

            //短信模板
            $model = $mc->getSMSModel();
            $this->assign('model',$model);
            $is_send_sms = db_config('is_send_sms_'.session('shop_code'));
            $this->assign('is_send_sms',$is_send_sms);//录入时是否发送短信
            
            //录入状态设定
            $valid = db_config('valid_'.session('brandclass_id'));
            $this->assign('valid',$valid);

            //网付订单是否可收款
            $set_order_money = db_config('set_order_money_'.session('brandclass_id'));
            $this->assign('set_order_money',$set_order_money);
            
            //数据大屏地址
            $bg_controller = db_config('bg_controller');
            $this->assign('bg_controller',$bg_controller);
            
            //转介绍次数
            $num = db_config('zhuanjieshao_number_'.session('shop_code'));
            $this->assign('zhuanjieshao_number',$num);
            $new_cus = db_config('mobile_new_cus_'.session('shop_code'));
            $this->assign('new_cus',$new_cus);

            //已关联订单的上门禁止再开单
            $tohomeDisableDoubleOrder = db_config('tohome_disable_double_order');
            $this->assign('tohomeDisableDoubleOrder',$tohomeDisableDoubleOrder);

            //分配清除最后追踪时间：
            $allocationLastTrackingTime = db_config('allocation_last_tracking_time');
            $this->assign('allocationLastTrackingTime',$allocationLastTrackingTime);

            //花费配置
            //录入
            $lr = db_config('lr_channel_cost_'.session('shop_code'));
            $this->assign('lr',$lr);
            //修改
            $edit = db_config('edit_channel_cost_'.session('shop_code'));
            $this->assign('edit',$edit);
            //核算
            $accounting = db_config('accounting_channel_cost_'.session('shop_code'));
            //
            $this->assign('accounting',$accounting);
            //维度
            $method = db_config('cost_method_'.session('shop_code'));
            $this->assign('cost_method',$method);
            //erp判定规则
            $erp_order = db_config('erp_order_'.session('brandclass_id'));
            $this->assign('erp_order',$erp_order);
            //erp判定规则
            $mobile_input = db_config('mobile_input_'.session('shop_code'));
            $this->assign('mobile_input',$mobile_input);
            //列表页配置
            $list = listJQgrid();
            $this->assign('list',$list);
            $check_list = db_config('shop_column_'.session('shop_code'));
            $check_list = explode(',',$check_list);
            $this->assign('check_list',$check_list);
            //列表页搜索项隐藏配置
            $search = db_config('list_search_hidden_'.session('brandclass_id'));
            if($search){
                $search = explode(',',$search);
            }
            $this->assign('search_list',$search);
            //坐席配置
            $call = db('crm_s_call_center')->select();
            // if (count($call)>0) {
                $this->assign('callCenter',true);
                $this->assign('call',$call);
                // $call_user =  db('crm_s_call_man')->where('staff_id',session('staff_id'))->find();
                // $this->assign('call_user',$call_user);
                $call_id =  db_config('call_id');
                $this->assign('call_id',$call_id);
            // };
            

            //查询是否包含离职人员
            $is_leave = db_config('is_leave');
            $this->assign('is_leave',$is_leave);
            //自动标记有效
            $auto_valid = db_config('auto_valid_'.session('brandclass_id'));
            $this->assign('auto_valid',$auto_valid);
            //自动标记无效
            $auto_unvalid = db_config('auto_unvalid_'.session('brandclass_id'));
            $this->assign('auto_unvalid',$auto_unvalid);
            // 醉唐风 客资分配之后，一个月内无法成单，回到客资池，待分配
            $unorderReturn = db_config('unorderReturn_'.session('brandclass_id'));
            $this->assign('unorderReturn',$unorderReturn);
            // 醉唐风 网付订单收款 达到标准 自动进店 设定
            $onlinecash = db_config('onlinecash_'.session('brandclass_id'));
            $this->assign('onlinecash',$onlinecash['onlinecash']);
            $this->assign('onlinecash_radio',$onlinecash['onlinecash_name']);
            //网付邀约     网付订单，未达到进店标准，是否可以邀约
            $this->assign('onlinecash_invite',db_config('onlinecash_invite_'.session('brandclass_id')));
            
            //customerMatchMethod客资匹配算法-桔子定制，10天内追踪的算网销，其他不算，单独写个算法
            $customerMatchMethod = db_config('customer_match_method');
            $this->assign('customerMatchMethod',$customerMatchMethod);
            //列表页时间默认
            $list_date = db_config('list_date');
            $this->assign('list_date',$list_date);
            //列表页查询是否包含erp客资设定
            $list_search_is_in_erp = db_config('list_search_is_in_erp',$data['list_search_is_in_erp']);
            $this->assign('list_search_is_in_erp',$list_search_is_in_erp);

            // 列表页 搜索点查询按键查所有选项卡的数量：
            $list_customerinfo_refreshnumber = db_config('list_customerinfo_refreshnumber');
            $this->assign('list_customerinfo_refreshnumber',$list_customerinfo_refreshnumber);

            //网付订单意向店面设定
            $intention_shop = db_config('intention_shop');
            $this->assign('intention_shop',$intention_shop);
            //同一客资是否允许多次订单
            $one_order = db_config('one_customer_more_order');
            $this->assign('one_customer_more_order',$one_order);
            //体验拍可重复时间设定
            $repeat_experience_day = db_config('repeat_experience_day');
            $this->assign('repeat_experience_day',$repeat_experience_day);
            //无网销是否允许转单/上门
            $is_zhuanorder_not_wx = db_config('is_zhuanorder_not_wx');
            $is_sm_not_wx = db_config('is_sm_not_wx');
            $this->assign('is_zhuanorder_not_wx',$is_zhuanorder_not_wx);
            $this->assign('is_sm_not_wx',$is_sm_not_wx);

            //分配客资设定(时间区间)
            $distribution_guest_information_date = db_config('distribution_guest_information_date_'.session('brandclass_id'));
            $this->assign('distribution_guest_information_date',$distribution_guest_information_date);
            //分配客资设定(业绩选择)
            $distribution_guest_information_yeji = db_config('distribution_guest_information_yeji_'.session('brandclass_id'));
            $this->assign('distribution_guest_information_yeji',$distribution_guest_information_yeji);

            //进客
            $enterGuest = db_config('enterGuest');
            $this->assign('enterGuest',$enterGuest);

            //2021-03-18 南宁qqbaby 定制
            if (customize('nnqqbaby')) {
                $valid_day_to_fp = db_config('valid_day_to_fp_'.session('brandclass_id'));
                $this->assign('valid_day_to_fp',$valid_day_to_fp);
            }
                $max_into_day = db_config('max_into_day_'.session('shop_code'));
                $this->assign('max_into_day',$max_into_day);
                $into_valid_day = db_config('into_valid_day');
                $this->assign('into_valid_day',$into_valid_day);
            //南宁qqbaby定制内容是否显示
            $this->assign('is_nnqqbaby',customize('nnqqbaby')?1:2);

            $staff = controller('crm/Setting','lib')->telAddress();
            $this->assign('teladdress',grtTelAddressRegular());
            $this->assign('staff',$staff);
            
            return $this->fetch();
        }else{
            if(session('brandclass_id')){
                $old = db_config('sx_erp_'.session('brandclass_id'));
                $res = db_config('sx_erp_'.session('brandclass_id'),$data['is_open']);
                if($res){
                    action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                    return array('code'=>200,'msg'=>'ERP设定成功','data'=>'');
                }else{
                    return array('code'=>100,'msg'=>'ERP设定失败','data'=>'');
                }
            }else{
                return array('code'=>300,'msg'=>'未找到事业部ID，不能设置','data'=>'');
            }
        }
    }
    //手机地址配置 保存
    public function telAddressMate(){
        $val = trim(input('param.val'),",");
        return controller('crm/Setting','lib')->telAddressMate($val);
    }
    //获取排程量
    public function getPCNum(){
        $shop = input('param.shop');
        $num = db_config('paicheng_'.$shop);
        return $num;
    }
    /**
     * @cc 自动标记有效设定
     * */
    public function autoValidSet(){
        $data = input();
        if(session('shop_code')){
            $old = db_config('auto_valid_'.session('brandclass_id'));
            if(empty($data['auto_valid'])){
                $res = db('crm_c_sysconfig')->where('ckey','auto_valid_'.session('brandclass_id'))->delete();
            }else{
                $res = db_config('auto_valid_'.session('brandclass_id'),$data['auto_valid']);
            }
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                if(empty($data['auto_valid'])){
                    return array('code'=>200,'msg'=>'自动标记有效关闭成功','data'=>'');
                }else{
                    return array('code'=>200,'msg'=>'客资未处理 '.$data['auto_valid'].' 天后自动标记有效配置成功','data'=>'');
                }
            }else{
                if(empty($data['auto_valid'])){
                    return array('code'=>100,'msg'=>'自动标记有效关闭失败','data'=>'');
                }else{
                    return array('code'=>100,'msg'=>'客资未处理 '.$data['auto_valid'].' 天后自动标记有效配置失败','data'=>'');
                }
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 自动标记无效设定
     * */
    public function autoUnValidSet(){
        $data = input();
        if(session('shop_code')){
            $old = db_config('auto_unvalid_'.session('brandclass_id'));
            if(empty($data['auto_unvalid'])){
                $res = db('crm_c_sysconfig')->where('ckey','auto_unvalid_'.session('brandclass_id'))->delete();
            }else{
                $res = db_config('auto_unvalid_'.session('brandclass_id'),$data['auto_unvalid']);
            }
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                if(empty($data['auto_unvalid'])){
                    return array('code'=>200,'msg'=>'自动标记无效关闭成功','data'=>'');
                }else{
                    return array('code'=>200,'msg'=>'客资未处理 '.$data['auto_unvalid'].' 天后自动标记无效配置成功','data'=>'');
                }
            }else{
                if(empty($data['auto_unvalid'])){
                    return array('code'=>100,'msg'=>'自动标记无效关闭失败','data'=>'');
                }else{
                    return array('code'=>100,'msg'=>'客资未处理 '.$data['auto_unvalid'].' 天后自动标记无效配置失败','data'=>'');
                }
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 修改排程
     * */
    public function editpc(){
        $data = input();
        if($data['shop_code']){
            $where['shop_code'] = $data['shop_code'];
        }else{
            return array('code'=>105,'msg'=>'未选择店面，不能设置','data'=>'');
        }
        if($data['area_id']){
            $where['area_id'] = $data['area_id'];
        }else{
            $where['area_id'] = NULL;
        }
        if($data['time']){
            $where['time'] = $data['time'];
        }else{
            $where['time'] = NULL;
        }
        $arr = [
            'num' => $data['num'],
            'staff_id' => session('staff_id'),
            'staff_name' => session('staff_name'),
            'ip' => get_client_ip(),
            'shop_code' => $data['shop_code'],
            'shop_name' => $data['shop_name'],
            'area_id' => $data['area_id'] ? $data['area_id'] : NULL,
            'area_name' => !empty($data['area_id']) ? $data['area_name'] : NULL,
            'time' => $data['time'] ? $data['time'] : NULL,
            'create_time'=> date('Y-m-d H:i:s')
        ];
        $set = db('crm_l_pc_setting_log')->where('setting_date',date('Y-m-d'))->where($where)->where('id','<>',$data['id'])->find();
        if($set){
            return array('code'=>102,'msg'=>'已有此排程，不能修改','data'=>'');
        }
        $res = db('crm_l_pc_setting_log')->where('id',$data['id'])->find();
        if($res['setting_date'] < date('Y-m-d')){
            return array('code'=>101,'msg'=>'已是之前排程，不能修改','data'=>'');
        }
        try{
            db('crm_l_pc_setting_log')->where('id',$data['id'])->update($arr);
            db()->commit();
            action_log($data,$res,0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'每天排程次数设定成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'每天排程次数设定失败','data'=>$e->getMessage());
        }
    }
        
    /**
     * @cc 批量删除排程
     * */
    public function delMorePC(){
        $data = input();
        $old = db('crm_l_pc_setting_log')->where('id','in',$data['id'])->select();
        $msg = '';
        foreach($old as $k=>$v){
            $msg .= '删除的排程设定ID为【'.$v['id'].'】;店面：【'.$v['shop_name'].'】;';
            if($v['area_id']){
                $msg .= '分区：【'.$v['area_name'].'】;';
            }else{
                $msg .= '分区：【任意分区】;';
            }
            if($v['time']){
                $msg .= '时间点：【'.$v['time'].'】;';
            }else{
                $msg .= '时间点：【任意时间点】;';
            }
        }
        db()->startTrans();
        try{
            db('crm_l_pc_setting_log')->where('id','in',$data['id'])->delete();
            action_log($data['id'],$msg,0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'批量删除排程成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'批量删除排程失败','data'=>$e->getMessage());
        }
    }

    /**
     * @cc 按时间段设置排程
     * */
    public function addPcByWeek(){
        if(request()->isAjax()){
            $data = input();
            $time = getDateFromRange($data['start'],$data['end']);

            if($data['shop_code']){
                $where['shop_code'] = $data['shop_code'];
            }else{
                return array('code'=>105,'msg'=>'未选择店面，不能设置','data'=>'');
            }

            if($data['area_id']){
                $where['area_id'] = $data['area_id'];
            }else{
                $where['area_id'] = NULL;
            }
            if($data['time']){
                $where['time'] = $data['time'];
            }else{
                $where['time'] = NULL;
            }
            $res = db('crm_l_pc_setting_log')->where($where)->where('setting_date','in',[$data['start'],$data['end']])->find();
            if($res){
                return array('code'=>101,'msg'=>'当天已有此排程，不能设置','data'=>'');
            }
            $temp = [];
            $new_time = [];
            foreach($time as $k=>$v){
                $week = date('w',strtotime($v));
                // if($week != 0 && $week!= 6){ //去掉周六周日
                    $temp[$v] = $week;
                    $new_time[] = $v;
                // }
            }

            $arr = [];
            $logs = [];
            foreach($new_time as $k=>$v){
                $num = 0;
                if($temp[$v] == 1){
                    $num = $data['one'] ? intval($data['one']): 0;
                }elseif($temp[$v] == 2){
                    $num = $data['two'] ? intval($data['two']): 0;
                }elseif($temp[$v] == 3){
                    $num = $data['three'] ? intval($data['three']): 0;
                }elseif($temp[$v] == 4){
                    $num = $data['four'] ? intval($data['four']): 0;
                }elseif($temp[$v] == 5){
                    $num = $data['five'] ? intval($data['five']): 0;
                }elseif($temp[$v] == 6){
                    $num = $data['six'] ? intval($data['six']): 0;
                }elseif($temp[$v] == 0){
                    $num = $data['seven'] ? intval($data['seven']): 0;
                }
                if($num > 0){
                    $pc = [
                        'num' => $num,
                        'setting_date'=> $v,
                        'staff_id' => session('staff_id'),
                        'staff_name' => session('staff_name'),
                        'ip' => get_client_ip(),
                        'shop_code' => $data['shop_code'],
                        'shop_name' => $data['shop_name'],
                        'area_id' => $data['area_id'] ? $data['area_id'] : NULL,
                        'area_name' => !empty($data['area_id']) ? $data['area_name'] : NULL,
                        'time' => $data['time'] ? $data['time'] : NULL,
                        'create_time'=> date('Y-m-d H:i:s')
                    ];
                    $log['module']     = 'crm';
                    $log['controller'] = 'Setting';
                    $log['action']     = 'addPcByWeek';
                    $log['old_data']   = json_encode([]);
                    $log['data']       = json_encode($pc);
                    $log['customer_id']= 0;
                    $log['staff_name'] = session('staff_name');
                    $log['staff_id']   = session('staff_id');
                    $log['ip']         = get_client_ip();
                    $log['create_time']= date('Y-m-d H:i:s');
                    $logs[] = $log;
                    $arr[] = $pc;
                }
            }
            try{
                db('crm_l_pc_setting_log')->insertAll($arr);
                db('crm_action_log','db_logs')->insertAll($logs);

                db()->commit();
                return array('code'=>200,'msg'=>'每天排程次数设定成功','data'=>'');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'每天排程次数设定失败','data'=>$e->getMessage());
            }
        }else {
            $id = input('param.id');
            $res = db('crm_l_pc_setting_log')->where('id', $id)->find();
            $this->assign('info', $res);
            //分区
            $area = controller('crm/Customer', 'lib')->areaSet(['brandclass_id' => session('brandclass_id')]);
            $this->assign('area', $area);
            //拍照店
            $shop = controller('crm/Customer', 'lib')->get_shop(['brandclass_id' => session('brandclass_id')]);
            $this->assign('shop', $shop);
            return $this->fetch();
        }
    }

    /**
     * @cc 删除排程
     * */
    public function delpc(){
        $id = input('param.id');
        db()->startTrans();
        try{
            db('crm_l_pc_setting_log')->where('id',$id)->delete();
            db()->commit();
            return array('code'=>200,'msg'=>'每天排程次数设定失败','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'每天排程次数设定失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 删除上门排程
     * */
    
    public function getPCToJSON(){
        $data = input();
        $page = $data['page'] ? $data['page'] : 1;
        $limit = $data['limit'] ? $data['limit'] : 20;
        $where = [];
        if($data['setting_date']) $where['setting_date'] = trim($data['setting_date']);
        if($data['shop_code']) $where['shop_code'] = trim($data['shop_code']);
        if($data['area_id']) $where['area_id'] = intval($data['area_id']);
        if($data['time']) $where['time'] = trim($data['time']);
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_l_pc_setting_log')
            ->where($where)
            ->where('pc_type',1)
            ->order('shop_code,setting_date desc,time desc')
            ->page($page)
            ->limit($limit)
            ->select();
        foreach($res as $k=>$v){
            if($v['setting_date'] >= date('Y-m-d')){
                $res[$k]['is_show'] = 1;
            }else{
                $res[$k]['is_show'] = 0;
            }
        }
        $count = db('crm_l_pc_setting_log')->where('pc_type',1)->where($where)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    
    /**
     * @cc 移动端新客资录入开关
     * */
    public function mobileNewCusSet(){
        $data = input();
        if(session('shop_code')){
            $old = db_config('mobile_new_cus_'.session('shop_code'));
            $res = db_config('mobile_new_cus_'.session('shop_code'),$data['mobile_new_cus']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'移动端新客资录入开关设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'移动端新客资录入开关设定失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面编码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 已关联订单的上门禁止再开单：
     * */
    public function tohomeDisableDoubleOrder(){
        $data = input();
        $old = db_config('mobile_new_cus_'.session('shop_code'));
        $old = db_config('tohome_disable_double_order');
        $res = db_config('tohome_disable_double_order',$data['tohome_disable_double_order']);
        if($res){
            action_log($data,[$old],0,session('staff_id'),session('staff_name'));
            // $log = $data['tohome_disable_double_order']==1?'打开':'关闭';
            return array('code'=>200,'msg'=>'设定成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'设定失败','data'=>'');
        }
    }
    // 分配清除最后追踪时间：
    public function allocationLastTrackingTime(){
        $data = input();
        $old = db_config('allocation_last_tracking');
        $res = db_config('allocation_last_tracking',$data['allocation_last_tracking']);
        if($res){
            action_log($data,[$old],0,session('staff_id'),session('staff_name'));
            // $log = $data['allocation_last_tracking']==1?'打开':'关闭';
            return array('code'=>200,'msg'=>'设定成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'设定失败','data'=>'');
        }
    }
    /**
     * @cc 查询人员时是否包含离职人员
     * */
    public function isLeaveSet(){
        $data = input();
            $old = db_config('is_leave');
            $res = db_config('is_leave',$data['is_leave']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'查询人员时是否包含离职人员设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'查询人员时是否包含离职人员设定失败','data'=>'');
            }
    }
    /**
     * @cc 列表页时间默认设定
     * */
    public function listDateDefault(){
        $data = input();
            $old = db_config('list_date');
            $res = db_config('list_date',$data['list_date']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'列表页时间默认设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'列表页时间默认设定失败','data'=>'');
            }
    }
    /**
     * @cc 列表页查询是否包含erp客资设定
     * */
    public function listSearchIsInErp(){
        $data = input();
            $old = db_config('list_search_is_in_erp');
            $res = db_config('list_search_is_in_erp',$data['list_search_is_in_erp']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'列表页查询是否包含ERP客资设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'列表页查询是否包含ERP客资设定失败','data'=>'');
            }
    }
    /**
     * @cc 意向店面设定
     * */
    public function intentionShopSet(){
        $data = input();
        $old = db_config('intention_shop');
        $res = db_config('intention_shop',$data['intention_shop']);
        if($res){
            action_log($data,[$old],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'意向店面设定成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'意向店面设定失败','data'=>'');
        }
    }
    /**
     * @ auth  eric 190123 预约进店排程 设定 0309
     * */
    public function addYjdCtrl(){
        if(request()->isAjax()){
            $data = input('post.');
            db_config('add_yjd_ctrl_'.$data['shop_code'], json_encode($data));
            $time_area = getDateFromRange($data['startTime'], $data['endTime']);
            $date = date('Y-m-d H:i:s');
            $inArr = [];
            foreach ($time_area as $key => $value) {
                $temp['shop_code']= $data['shop_code'];
                $temp['shop_name']= $data['shop_name'];
                $temp['use_day']  = $value;
                $week = date('w', strtotime($value));
                switch ($week) {
                    case '0':
                        // 周日
                        $w = 'sun';
                        break;
                    case '1':
                        // 周一
                        $w = 'mon';
                        break;
                    case '2':
                        // 周二
                        $w = 'tue';
                        break;
                    case '3':
                        // 周三
                        $w = 'wed';
                        break;
                    case '4':
                        // 周四
                        $w = 'thu';
                        break;
                    case '5':
                        // 周五
                        $w = 'fri';
                        break;
                    case '6':
                        // 周六
                        $w = 'sat';
                        break;
                }
                foreach ($data['time_start'] as $k => $v) {
                    $temp['week'] = $w;
                    $temp['num']  = $data[$w][$k];
                    $temp['time_area'] = substr($v,0,5).'-'.substr($data['time_end'][$k],0,5);
                    $temp['start']= $v;
                    $temp['end']  = $data['time_end'][$k];
                    $temp['create_time'] = $date;
                    array_push($inArr, $temp);
                }
            }
            // var_dump($inArr);
            // exit;
            $whereDel['shop_code'] = $data['shop_code'];
            db()->startTrans();
            try{
                db('crm_l_yjd_ctrl')->where($whereDel)
                    ->where('use_day', '>=', $data['startTime'])
                    ->where('use_day', '<=', $data['endTime'])
                    ->delete();
                db('crm_l_yjd_ctrl')->insertAll($inArr);
                // db('crm_action_log','db_logs')->insertAll($logs);
                db()->commit();
                return array('code'=>200,'msg'=>'设定成功','data'=>'');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'设定失败','data'=>$e->getMessage());
            }
        }else {
            // 之前保存过
            $old_data = db_config('add_yjd_ctrl_'.session('shop_code'));
            // var_dump($old_data);
            // exit;
            //拍照店
            $shop = controller('crm/Customer', 'lib')->get_shop(['brandclass_id' => session('brandclass_id')]);
            $this->assign('shop', $shop);
            // 开始结束时间
            $start= date('Y-m-01');
            $end  = date('Y-m-d', strtotime("$start +1 month -1 day"));
            $this->assign('start',$start);
            $this->assign('end',$end);
            if ($old_data) {
                if (!is_array($old_data)) {
                    $old_data = json_decode($old_data,true);
                }               
                $yjdinfo['shop_code'] = $old_data['shop_code'];
                $temp = [];
                foreach ($old_data['time_start'] as $key => $value) {
                    $temp[$key]['time_start'] = $value;
                    $temp[$key]['time_end'] = $old_data['time_end'][$key];
                    $temp[$key]['mon'] = $old_data['mon'][$key];
                    $temp[$key]['tue'] = $old_data['tue'][$key];
                    $temp[$key]['wed'] = $old_data['wed'][$key];
                    $temp[$key]['thu'] = $old_data['thu'][$key];
                    $temp[$key]['fri'] = $old_data['fri'][$key];
                    $temp[$key]['sat'] = $old_data['sat'][$key];
                    $temp[$key]['sun'] = $old_data['sun'][$key];
                }
                $yjdinfo['data'] = $temp;
                $this->assign('yjdinfo',$yjdinfo);
                unset($old_data,$temp);
            }
            return $this->fetch();
        }
    }
    /**
     * @ auth  eric 190123 预约进店排程 编辑
     * */
    public function eidtYjdCtrl(){
        if(request()->isAjax()){
            $data = input('post.');
            $date = date('Y-m-d H:i:s');
            $where['id'] = (int)$data['id'];
            $old = db('crm_l_yjd_ctrl')->where($where)->find();

            $inData['num'] = (int)$data['num'];
            $inData['update_time'] = $date;

            db()->startTrans();
            try{
                db('crm_l_yjd_ctrl')->where($where)->update($inData);
                $newStr = $old['shop_name'].'；'.$old['use_day'].'；'.$old['time_area'].'；'.(int)$data['num'];
                $oldStr = $old['shop_name'].'；'.$old['use_day'].'；'.$old['time_area'].'；'.(int)$old['num'];
                action_log($newStr,$oldStr,'',session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>200,'msg'=>'修改成功','data'=>'');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'修改失败','data'=>$e->getMessage());
            }
        }else {
            $id = (int)input('param.id');
            $info = db('crm_l_yjd_ctrl')->where('id', $id)->find();
            switch ($info['week']) {
                case 'sun':
                    $info['week'] = '周日';
                    break;
                case 'mon':
                    $info['week'] = '周一';
                    break;
                case 'tue':
                    $info['week'] = '周二';
                    break;
                case 'wed':
                    $info['week'] = '周三';
                    break;
                case 'thu':
                    $info['week'] = '周四';
                    break;
                case 'fri':
                    $info['week'] = '周五';
                    break;
                case 'sat':
                    $info['week'] = '周六';
                    break;
            }
            
            $this->assign('info', $info);
            // //分区
            // $area = controller('crm/Customer', 'lib')->areaSet(['brandclass_id' => session('brandclass_id')]);
            // $this->assign('area', $area);
            //拍照店
            $shop = controller('crm/Customer', 'lib')->get_shop(['brandclass_id' => session('brandclass_id')]);
            $this->assign('shop', $shop);
            return $this->fetch();
        }
    }
    /**
     * @ auth  eric 190123 预约进店排程 删除
     * */
    public function delYjdCtrl(){
        $id  = input('post.id');
        $date= date('Y-m-d H:i:s');
        $update['is_del'] = 2;
        $update['update_time'] = $date;
        $oldInfo = db('crm_l_yjd_ctrl')->where('id', $id)->find();
        $res = db('crm_l_yjd_ctrl')->where('id', $id)->update($update);

        // 日志
        $log['module'] = 'crm';
        $log['controller'] = 'Setting';
        $log['action'] = 'delYjdCtrl';
        $log['old_data'] = '';
        $log['data'] = '删除预约进店排程。店面：'.$oldInfo['shop_name'].'。时间区间：'.$oldInfo['use_day'].' '.$oldInfo['time_area'].'。数量：'.$oldInfo['num'];
        $log['staff_name'] = session('staff_name');
        $log['staff_id'] = session('staff_id');
        $log['ip'] = get_client_ip();
        $log['create_time'] = $date;
        db('crm_action_log','db_logs')->insert($log);
        if ($res === false) {
            $return['code'] = 100;
            $retrun['msg']  = '删除失败';
            $retrun['data'] = db()->getLastSql();
        }else{
            $return['code'] = 200;
            $retrun['msg']  = '删除成功';
        }
        return $return;
    }
    /**
     * @ auth  eric 190123 预约进店排程 列表
     * */
    public function getYjdData(){
        $data = input();

        $page = $data['page'] ? $data['page'] : 1;
        $limit = $data['limit'] ? $data['limit'] : 20;

        $where['is_del'] = 1;
        $where['shop_code'] = session('shop_code');

        if ($data['time_area']) {
            $where['time_area'] = $data['time_area'];
        }
        if ($data['inte_shop']) {
            $where['shop_code'] = $data['inte_shop'];
        }

        if ($data['use_start']) {
            $sql_start = 'use_day >= "'.date('Y-m-d',strtotime($data['use_start'])).'"';
        }else{
            $sql_start = 'use_day >= "'.date('Y-m-d').'"';
        }

        if ($data['use_end']) {
            $sql_end = 'use_day <= "'.date('Y-m-d',strtotime($data['use_end'])).'"';
        }else{
            $sql_end = 'use_day <= "'.date('Y-m-d').'"';
        }

        $res = db('crm_l_yjd_ctrl')
            ->where($where)
            ->where($sql_start)
            ->where($sql_end)
            ->order('sort asc')
            ->page($page)
            ->limit($limit)
            ->select();
        // echo db()->getLastSql();
        // var_dump($res);
        // exit;
        $result['code'] = 0;
        $result['msg'] = '';

        if($res){
            foreach ($res as $key => $value) {
                switch ($value['week']) {
                    case 'sun':
                        $res[$key]['week'] = '周日';
                        break;
                    case 'mon':
                        $res[$key]['week'] = '周一';
                        break;
                    case 'tue':
                        $res[$key]['week'] = '周二';
                        break;
                    case 'wed':
                        $res[$key]['week'] = '周三';
                        break;
                    case 'thu':
                        $res[$key]['week'] = '周四';
                        break;
                    case 'fri':
                        $res[$key]['week'] = '周五';
                        break;
                    case 'sat':
                        $res[$key]['week'] = '周六';
                        break;
                }
            }

            $result['data'] = $res;
            $result['count']= db('crm_l_yjd_ctrl')->where($where)->where($sql_start)->where($sql_end)->count();
        }else{
            $result['data'] = array();
            $result['count']= 0;
        }
        return json($result);
    }
    /**
     * @ auth  eric 190123 预约进店排程 启用
     * */
    public function setYjdCtrl(){
        $data = input('post.');

        if(session('shop_code')){
            $old = db_config('yjd_ctrl_set_'.session('shop_code'));
            $res = db_config('yjd_ctrl_set_'.session('shop_code'),$data['is_open']);
            if($res){
                if ($old === 0) {
                    $oldstr = '关闭';
                }else if ($old === 1) {
                    $oldstr = '开启';
                }else{
                    $oldstr = '未启用';
                }
                if ($data['is_open']==1) {
                    $newstr = '开启预约进店排控';
                }else{
                    $newstr = '关闭预约进店排控';
                }
                action_log($newstr,'',0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'ERP设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'ERP设定失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'店面编码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 同一客资是否允许多次订单设定
     * */
    public function oneCustomerMoreOrderSet(){
        $data = input();
            $old = db_config('one_customer_more_order');
            $res = db_config('one_customer_more_order',$data['one_customer_more_order']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'同一客资是否允许多次订单设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'同一客资是否允许多次订单设定失败','data'=>'');
            }
    }
    /**
     * @cc 无网销是否允许转单设定
     * */
    public function isZhuanorderNotWX(){
        $data = input();
            $old = db_config('is_zhuanorder_not_wx');
            $res = db_config('is_zhuanorder_not_wx',$data['is_zhuanorder_not_wx']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'无网销是否允许转单设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'无网销是否允许转单设定失败','data'=>'');
            }
    }
    /**
     * @cc 无网销是否允许上门设定
     * */
    public function isSmNotWX(){
        $data = input();
            $old = db_config('is_sm_not_wx');
            $res = db_config('is_sm_not_wx',$data['is_sm_not_wx']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'无网销是否允许上门设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'无网销是否允许上门设定失败','data'=>'');
            }
    }
    /**
     * @cc 体验拍可重复时间设定
     * */
    public function repeatExperienceDaySet(){
        $data = input();
            $old = db_config('repeat_experience_day');
            $res = db_config('repeat_experience_day',$data['repeat_experience_day']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'体验拍可重复时间设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'体验拍可重复时间设定失败','data'=>'');
            }
    }
    /**
     * @cc 分配客资设定(时间区间)
     * */
    public function distributionGuestInformationDate(){
        $data = input();
        if(session('shop_code')){
            $old = db_config('distribution_guest_information_date_'.session('brandclass_id'));
            if(empty($data['distribution_guest_information_date'])){
                $res = db('crm_c_sysconfig')->where('ckey','distribution_guest_information_date_'.session('brandclass_id'))->delete();
            }else{
                $res = db_config('distribution_guest_information_date_'.session('brandclass_id'),$data['distribution_guest_information_date']);
            }
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'分配客资设定(时间区间)设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'分配客资设定(时间区间)设定失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }

    }
    /**
     * @cc 分配客资设定(业绩选择)
     * */
    public function distributionGuestInformationYeji(){
        $data = input();
        if(session('shop_code')){
            $old = db_config('distribution_guest_information_yeji_'.session('brandclass_id'));
            if(empty($data['distribution_guest_information_yeji'])){
                $res = db('crm_c_sysconfig')->where('ckey','distribution_guest_information_yeji_'.session('brandclass_id'))->delete();
            }else{
                $res = db_config('distribution_guest_information_yeji_'.session('brandclass_id'),$data['distribution_guest_information_yeji']);
            }
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'分配客资设定(业绩选择)设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'分配客资设定(业绩选择)设定失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    // 驳回客资接收人 设定 20200513
    public function setRejectStaff(){
        $data = input();
        $old = db_config('reject_staff_'.session('shop_code'));
        $res = db_config('reject_staff_'.session('shop_code'),$data['reject_staff']);
        if($res){
            action_log($data,[$old],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'驳回客资接收人设定成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'驳回客资接收人设定失败','data'=>'');
        }
    }
    /**
     * @cc 列表页字段配置
     * */
    public function listJQgridSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            db()->startTrans();   
            
            try{
                action_log($data,[db_config('shop_column_'.session('shop_code')),db_config('shop_column_name_'.session('shop_code'))],0,session('staff_id'),session('staff_name'));
                db_config('shop_column_'.session('shop_code'),$data['column'] ? $data['column'] : null);
                db_config('shop_column_name_'.session('shop_code'),$data['name'] ? $data['name'] : null);
                db()->commit();
                return array('code'=>200,'msg'=>'列表页字段配置成功','data'=>'');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'列表页字段配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 列表页搜索项隐藏配置
     * */
    public function listSearchSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('brandclass_id')){
            db()->startTrans();
            try{
                $old = cache('list_search_hidden_'.session('brandclass_id'));
                db_config('list_search_hidden_'.session('brandclass_id'),trim($data['column'],','));
                db()->commit();
                action_log($data,$old,0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'列表页搜索项隐藏配置成功','data'=>'');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'列表页搜索项隐藏配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到事业部，不能设置','data'=>'');
        }
    }
    /**
     * @cc 客资提报归属店设定
     * */
    public function shopSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        $shop = explode(',',$data['shop']);
        $name = explode(',',$data['name']);
        $shops = [];
        foreach($shop as $k=>$v){
            if($v){
                $shops[] = ['shop_code'=>$shop[$k],'shop_name'=>$name[$k]];
            }
        }
        if(session('shop_code')){
            $old = db_config('dj_shops_'.session('shop_code'));
            $res = db_config('dj_shops_'.session('shop_code'),json_encode($shops));
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'客资提报归属店配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'客资提报归属店配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 客资审核设定
     * */
    public function cusExamineSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $examine = db_config('cus_examine_'.session('shop_code'));
            $res = db_config('cus_examine_'.session('shop_code'),$data['cus_examine']);
            if($res){
                action_log($data,[$examine],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'客资重复审核配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'客资重复审核配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    
    /**
     * @cc 呼叫中心选择
     * */
    public function callCenterChooseSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        // $callinfo = db('crm_s_call_center')->where('id',1)->find();
        $data = input();

        if($data['call_name']){
            $callinfo = db('crm_s_call_center')->where('call_name',$data['call_name'])->find();
        }else{
            $callinfo = '';
        }

        
        if(!$data['ip']){

            if(!$callinfo){
                return array('code'=>100,'msg'=>'域名不能为空','data'=>'');
            }else{
                try{
                    db()->startTrans();
                    //清除呼叫中心
                    db_config('call_id',null);
                    db('crm_s_call_center')->where('call_name',$data['call_name'])->delete();
                    action_log('删除呼叫中心设定',$callinfo,0,session('staff_id'),session('staff_name'));
                    db()->commit();
                    return array('code'=>200,'msg'=>'清除除呼叫中心成功','data'=>'');
                }catch(\Exception $e){
                    db()->rollback();
                    return array('code'=>100,'msg'=>'清除除呼叫中心失败：'.$e->getMessage(),'data'=>'');
                }
            }
            
        }
        //新增或修改。
        if(!$data['call_name']){
            return array('code'=>100,'msg'=>'驱动不能为空','data'=>'');
        }
        if(!$data['port'] && $data['call_name'] != '呼叫中心(七陌)'){
            return array('code'=>100,'msg'=>'端口不能为空','data'=>'');
        }
        if(!$data['accountid'] && $data['call_name'] == '呼叫中心(七陌)'){
            return array('code'=>100,'msg'=>'七陌 的 账号 不能为空!','data'=>'');
        }
        if(!$data['secret'] && $data['call_name'] == '呼叫中心(七陌)'){
            return array('code'=>100,'msg'=>'七陌 的 密码 不能为空!','data'=>'');
        }

        // $call = db_config('call_id');
        // //配置表 值 固定为 id=1
        // if($call != 1){
        //     $res = db_config('call_id',1);    
        // }

        try{
            db()->startTrans();
            if($callinfo){
                db('crm_s_call_center')->where('id',$callinfo['id'])->update($data);    
            }else{
                $callinfo['id'] = db('crm_s_call_center')->insertGetId($data);
            }

            db_config('call_id',$callinfo['id']);

            action_log($data,$callinfo,0,session('staff_id'),session('staff_name'));
            db()->commit();
        }catch(Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'呼叫中心设置失败'.$e->getMessage(),'data'=>'');
        }

        return array('code'=>200,'msg'=>'呼叫中心设置成功','data'=>'');
    }
    
    /**
     * @cc 移动端介绍人是否可输入设置
     * */
    public function mobileInputSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $input = db_config('mobile_input_'.session('shop_code'));
            $res = db_config('mobile_input_'.session('shop_code'),$data['mobile_input']);
            if($res){
                action_log($data,[$input],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'移动端介绍人是否可输入配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'移动端介绍人是否可输入配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 转介绍次数设定
     * */
    public function zhuanjieshaoNumberSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $num = db_config('zhuanjieshao_number_'.session('shop_code'));
            $res = db_config('zhuanjieshao_number_'.session('shop_code'),$data['num']);
            if($res){
                action_log($data,[$num],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'每天转介绍次数配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'每天转介绍次数配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc ERP转订单规则判定配置
     * */
    public function ERPZhandingdanSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('brandclass_id')){
            $order = db_config('erp_order_'.session('brandclass_id'));
            $res = db_config('erp_order_'.session('brandclass_id'),$data['erp_order']);
            if($res){
                action_log($data,[$order],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'ERP转订单规则判定配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'ERP转订单规则判定配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到事业部，不能设置','data'=>'');
        }
    }
    /**
     * @cc 预约短信模板设定
     * */
    public function yyModelSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $yy = db_config('yy_sms_model_'.session('shop_code'));
            $res = db_config('yy_sms_model_'.session('shop_code'),$data['yy_sms_model']);
            if($res){
                action_log($data,[$yy],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'预约短信模板配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'预约短信模板配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 上门拍短信模板设定
     * */
    public function smpModelSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $yy = db_config('smp_sms_model_'.session('shop_code'));
            $res = db_config('smp_sms_model_'.session('shop_code'),$data['smp_sms_model']);
            if($res){
                action_log($data,[$yy],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'上门拍短信模板配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'上门拍短信模板配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 催拍短信模板设定
     * */
    public function cuipaiModelSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $yy = db_config('cuipai_sms_model_'.session('shop_code'));
            $res = db_config('cuipai_sms_model_'.session('shop_code'),$data['cuipai_sms_model']);
            if($res){
                action_log($data,[$yy],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'催拍短信模板配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'催拍短信模板配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }

    /**
     * @cc 客资提报必选项设定
     * */
    public function lrSet(){
        // 权限
        $data = input();
        $set = trim($data['set'],',');
        if(session('brandclass_id')){
            if(empty($set)){
                $set = null;
            }
            $old = db_config('lr_must_'.session('brandclass_id'));
            $res = db_config('lr_must_'.session('brandclass_id'),$set);
            $lr = explode(',',$set);
            $hidden = db_config('lr_hidden_'.session('brandclass_id'));//录入隐藏字段
            $hidden = explode(',',$hidden);
            $arr = array_intersect($lr,$hidden);
            $new = [];
            foreach($hidden as $k=>$v){
                if(!in_array($v,$arr)){
                    $new[] = $v;
                }
            }
            $new_hidden = implode(',',$new);
            db_config('lr_hidden_'.session('brandclass_id'),$new_hidden);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'客资录入必选项配置成功','data'=>db_config('lr_must_'.session('brandclass_id')));
            }else{
                return array('code'=>100,'msg'=>'客资录入必选项配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到事业部，不能设置','data'=>'');
        }
    }
    /**
     * @cc 电访必选项设定
     * */
    public function dfSet(){
        // 权限
        $data = input();
        $set = empty($data['set'])?null:$data['set'];
        if(session('brandclass_id')){
            $old = db_config('df_must_'.session('brandclass_id'));
            $res = db_config('df_must_'.session('brandclass_id'),$set);
            $df = explode(',',$set);
            $hidden = db_config('df_hidden_'.session('brandclass_id'));//录入隐藏字段
            $hidden = explode(',',$hidden);
            $arr = array_intersect($df,$hidden);
            $new = [];
            foreach($hidden as $k=>$v){
                if(!in_array($v,$arr)){
                    $new[] = $v;
                }
            }
            $new_hidden = implode(',',$new);
            db_config('df_hidden_'.session('brandclass_id'),$new_hidden);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'客资追踪必选项配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'客资追踪必选项配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到事业部，不能设置','data'=>'');
        }
    }
    /**
     * @cc 订单后配置
     * */
    public function ddSet(){
        // 权限
        $data = input();
        $set = empty($data['set'])?null:$data['set'];
        if(session('brandclass_id')){
            $old = db_config('dd_must_'.session('brandclass_id'));
            $res = db_config('dd_must_'.session('brandclass_id'),$set);
            $df = explode(',',$set);
            $hidden = db_config('dd_hidden_'.session('brandclass_id'));//录入隐藏字段
            $hidden = explode(',',$hidden);
            $arr = array_intersect($df,$hidden);
            $new = [];
            foreach($hidden as $k=>$v){
                if(!in_array($v,$arr)){
                    $new[] = $v;
                }
            }
            $new_hidden = implode(',',$new);
            db_config('dd_hidden_'.session('brandclass_id'),$new_hidden);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'客资追踪必选项配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'客资追踪必选项配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到事业部，不能设置','data'=>'');
        }
    }
    /**
     * @cc 订单客资是否允许分配
     * */
    public function orderCusIsAllowFpSet(){
        $data = input();
        $old = db_config('orderCusIsAllowFp_'.session('brandclass_id'));
        $res = db_config('orderCusIsAllowFp_'.session('brandclass_id'),$data['orderCusIsAllowFp']);
        // var_dump(session('shop_code'));die;
        if($res){
            action_log($data,[$old],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'设定成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'设定失败','data'=>'');
        }
    }

    // 2021-07-21 列表页 搜索点查询按键查所有选项卡的数量：
    public function listCustomerinfoRefreshnumber(){
        $data = input();
        $old = db_config('list_customerinfo_refreshnumber');
        $res = db_config('list_customerinfo_refreshnumber',$data['list_customerinfo_refreshnumber']);
        // var_dump(session('shop_code'));die;
        if($res){
            action_log($data,[$old],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'设定成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'设定失败','data'=>'');
        }
    }
    /**
     * @cc 短信发送设定
     * */
    public function smsSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $sms = db_config('sms_'.session('shop_code'));
            $res = db_config('sms_'.session('shop_code'),$data['sms']);
            if($res){
                action_log($data,[$sms],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'短信账号配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'短信账号配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 客资状态显示设定
     * */
    public function lrValidSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('brandclass_id')){
            $valid = db_config('valid_'.session('brandclass_id'));
            $res = db_config('valid_'.session('brandclass_id'),$data['valid']);
            if($res){
                action_log($data,[$valid],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'客资录入状态配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'客资录入状态配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到事业部，不能设置','data'=>'');
        }
    }
    /**
     * @cc 客资过期录入是否提示设定
     * */
    public function lrValidDateNoticeSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        $valid_date = db_config('valid_date_notice');
        $res = db_config('valid_date_notice',$data['valid_date_notice']);
        if($res){
            action_log($data,[$valid_date],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'客资过期录入是否提示配置成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'客资过期录入是否提示配置失败','data'=>'');
        }
    }
    /**
     * @cc 客资重复是否提示设定
     * */
    public function cusRepeatNoticeSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        $old = $new = '客资重复是否提示：';
        $cus_repeat = db_config('cus_repeat_notice');
        $res = db_config('cus_repeat_notice',$data['cus_repeat_notice']);
        if($res){
            $old .= $cus_repeat ? '提示' : '不提示';
            $new .= $data['cus_repeat_notice'] ? '提示' : '不提示';
            action_log($new,$old,0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'客资重复录入是否提示配置成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'客资重复录入是否提示配置失败','data'=>'');
        }
    }
    /**
     * @cc 客资过期判定规则
     * */
    public function lrValidDateRuleSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        $valid_date = db_config('valid_date_rule');
        $res = db_config('valid_date_rule',$data['valid_date_rule']);
        if($res){
            action_log($data,[$valid_date],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'客资过期判定规则配置成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'客资过期判定规则配置失败','data'=>'');
        }
    }
    /**
     * @cc 录入时是否发送短信设定
     * */
    public function isSendSmsSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $sms = db_config('is_send_sms_'.session('shop_code'));
            $res = db_config('is_send_sms_'.session('shop_code'),$data['sms']);
            if($res){
                action_log($data,[$sms],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'录入(导入)时短信模板配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'录入(导入)时短信模板配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 录入客资是 填写日期 是否为 当天
     * */
    public function recordDaySet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $recordDay = db_config('record_day_'.session('shop_code'));
            $res = db_config('record_day_'.session('shop_code'),$data['recordDay']);
            if($res){
                action_log($data,[$recordDay],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'录入客资填写日期配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'录入客资填写日期配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 手机归属地秘钥设定
     * */
    public function pswSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();

        if(session('shop_code')){
            $psw = db_config('sx_secret_key_'.session('shop_code'));
            $res = db_config('sx_secret_key_'.session('shop_code'),$data['psw']);
            if($res){
                action_log($data,[$psw],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'短信秘钥设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'短信秘钥设定失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }

    }
    /**
     * @cc 本地配置
     * */
    public function citySet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();

        if(session('brandclass_id')){
            $city_id = db_config('sx_city_id_'.session('brandclass_id'));
            $res = db_config('sx_city_id_'.session('brandclass_id'),$data['city_id']);
            if($res){
                action_log($data,[$city_id],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'本地配置设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'本地配置设定失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到事业部，不能设置','data'=>'');
        }

    }

    public function orderSource(){
        // 权限
        $auth = check_right('menu1522225258');
        if (!$auth) {
            return $this->redirect('/');
        }
        //获取渠道
        $channel = controller('crm/Customer','lib')->getChannel();
        $this->assign('channel',$channel);
        return $this->fetch();
    }
    /**
     * @cc 增加订单来源
     * */
    public function addSource(){
        $data = input();
        return controller('crm/Setting','lib')->addSource($data);
    }
    /**
     * @cc 编辑订单来源
     * */
    public function editSource(){
        $data = input();
        return controller('crm/Setting','lib')->editSource($data);
    }
    /**
     * @cc 删除订单来源
     * */
    public function delSource(){
        $data = input();
        return controller('crm/Setting','lib')->delSource($data);
    }
    public function getSourceToJSON(){
        $param = input();
        $limit = $param['limit'] ? $param['limit'] : 100;
        $page = $param['page'] ? $param['page'] : 1;
        $result['code'] = 0;
        $result['msg'] = '';
        $result['data'] = db('crm_s_order_source')->where('shop_code',session('shop_code'))->where('is_delete',1)->limit($limit)->page($page)->select();
        $result['count'] = db('crm_s_order_source')->where('shop_code',session('shop_code'))->where('is_delete',1)->count();
        return json($result);

    }
    public function getOrderSource(){
        $shop_code = input('param.shop_code') ? input('param.shop_code') : session('shop_code');
        $res = db('crm_s_order_source')->where('shop_code',$shop_code)->where('is_delete',1)->select();
        return $res;
    }
    //订单来源设定--end
    //客资录入接口设置
    public function customerInterface(){
        //客户来源
        $source=controller("Customer","lib")->source(array('shop_code'=>session('shop_code')));
        $this->assign("source",$source);
        $lrMust = db_config('lr_must_'.session('brandclass_id'));
        $lrMust = trim($lrMust,',');
        $lrMust = explode(',',$lrMust);
        $this->assign('jslrMust',$lrMust);;
        return $this->fetch();
    }
    /**
     * @cc 增加客资录入接口设置
     * */
    public function addCustomerInterface(){
        $data = input();
        return controller('crm/Setting','lib')->addCustomerInterface($data);
    }
    /**
     * @cc 编辑客资录入接口设置
     * */
    public function editCustomerInterface(){
        $data = input();
        return controller('crm/Setting','lib')->editCustomerInterface($data);
    }
    public function getCustomerInterfaceToJSON(){
        $result['code'] = 0;
        $result['msg'] = '';
        $page = input('param.page') ? input('param.page') : 1;
        $limit = input('param.limit') ? input('param.limit') : 10;
        $res = db('crm_s_customer_interface')->where('shop_code',session('shop_code'))->where('is_delete',2)->field('id,url,field_config,create_time,update_time,create_staff_name,status')->select();
        $count = db('crm_s_customer_interface')->where('is_delete',2)->where('shop_code',session('shop_code'))->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    /**
     * @cc 启用客资录入接口设置
     * */
    public function openCustomerInterface(){
        $id = input('param.id');
        db()->startTrans();
        try{
            db('crm_s_customer_interface')->where('id',$id)->update(['status'=>1]);
            action_log($id,['status'=>2],0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'启用成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'启用失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 关闭客资录入接口设置
     * */
    public function closeCustomerInterface(){
        $id = input('param.id');
        db()->startTrans();
        try{
            db('crm_s_customer_interface')->where('id',$id)->update(['status'=>2]);
            action_log($id,['status'=>2],0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'禁用成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'禁用失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 删除客资录入接口设置
     * */
    public function delCustomerInterface(){
        $id = input('param.id');
        db()->startTrans();
        try{
            db('crm_s_customer_interface')->where('id',$id)->update(['is_delete'=>1]);
            action_log($id,[],0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'删除成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除失败','data'=>$e->getMessage());
        }
    }
    public function interfaceDetail()
    {
        $id = input('param.id');
        $this->assign('id', $id);
        return $this->fetch();
    }

    public function interfaceDetailJSON(){
        $id = input('param.id');
        $result['code'] = 0;
        $result['msg'] = '';
        $page = input('param.page') ? input('param.page') : 1;
        $limit = input('param.limit') ? input('param.limit') : 10;
        $res = db('crm_s_customer_interface_detail')->where('pid', $id)->page($page)->limit($limit)->order('create_time desc')->select();
        foreach($res as $k=>$v){
            $res[$k] = decodeUnicode($v);
        }
        $count = db('crm_s_customer_interface_detail')->where('pid', $id)->page($page)->limit($limit)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    /**
     * @cc 列表页颜色设置
     * */
    public function colorSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();

        $res = db_config($data['color_name'],$data['color']);
        if($res){
            return array('code'=>200,'msg'=>'颜色设定成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'颜色设定失败','data'=>'');
        }
    }

    //清除颜色
    public function colorCancel(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }

        $key = input('color_name');
        try{
            db_config($key,null);
            return array('code'=>200,'msg'=>'颜色清除成功','data'=>'');

        }catch (\Exception $e){

            return array('code'=>100,'msg'=>'颜色清除失败','data'=>'');
        }


    }


    /**
     * @cc 报表显示设置设置
     * */
    public function setSta(){
        $ids = input();
        $res = db_config('statistics_'.session('shop_code'),json_encode($ids));
        if($res === false){
            return array('code'=>100,'msg'=>'报表显示设置失败');
        }else{
            return array('code'=>200,'msg'=>'报表显示设置成功');
        }
    }
    /*---------------消费类型--------start--------------------*/
    public function consultationType(){
        // 这个方法应该不用了，儿童版消费类型设置在了erp，不调mc接口了
        return [];
        // $url = "59fd58574204a";
        // $res = sx_call($url, []);
        // if ($res['code'] == 200) {
        //     $info = $res['data'];
        //     $this->assign('info',$info);
        // }
        // return $this->fetch();
    }
    /**
     * @cc 添加子消费类型
     * */
    public function addConsumptionType(){
        $data = input();
        $param['pid'] = $data['pid'];
        $param['pname'] = $data['pname'];
        $param['consumption_name'] = $data['consumption_name'];
        $param['create_time'] = date('Y-m-d H:i:s');
        $param['create_staff_id'] = session('staff_id');
        $param['create_staff'] = session('staff_name');
        $param['brandclass_id'] = session('brandclass_id');
        $param['brandclass'] = session('brandclass');
        if(empty($param['consumption_name'])){
            return array('code'=>100,'msg'=>'子消费类型不能为空','data'=>'');
        }else{
            $oldInfo = db('crm_s_consumptiontype')
                ->where('consumption_name',$param['consumption_name'])
                ->where('is_delete',2)
                ->where('brandclass_id',session('brandclass_id'))
                ->value('id');
            if(!empty($oldInfo)){
                return array('code'=>400,'msg'=>'子消费类型重复','data'=>'');
            }
        }

        db()->startTrans();
        try{
            db('crm_s_consumptiontype')->insert($param);
            db()->commit();
            action_log($param,[],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'添加子消费类型成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'添加子消费类型失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 编辑子消费类型
     * */
    public function editConsumptionType(){
        $data = input();
        if(!$data['id']){
            return array('code'=>300,'msg'=>'参数有误','data'=>'');
        }
        $oldInfo = db('crm_s_consumptiontype')
            ->where('id',$data['id'])
            ->where('is_delete',2)
            ->where('brandclass_id',session('brandclass_id'))
            ->find();
        //检查重复
        $id = db('crm_s_consumptiontype')
            ->where('consumption_name',$data['consumption_name'])
            ->where('is_delete',2)
            ->where('id','<>',$data['id'])
            ->where('brandclass_id',session('brandclass_id'))
            ->value('id');
        if($id){
            return array('code'=>400,'msg'=>'子消费类型重复','data'=>'');
        }
        $param['pid'] = $data['pid'];
        $param['pname'] = $data['pname'];
        $param['consumption_name'] = $data['consumption_name'];
        $param['update_time'] = date('Y-m-d H:i:s');
        $param['update_staff_id'] = session('staff_id');
        $param['update_staff'] = session('staff_name');
        $param['brandclass_id'] = session('brandclass_id');
        $param['brandclass'] = session('brandclass');
        db()->startTrans();
        try{
            db('crm_s_consumptiontype')->where('id',$data['id'])->update($param);
            db()->commit();
            action_log($param,$oldInfo,0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'修改子消费类型成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'修改子消费类型失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 删除子消费类型
     * */
    public function delConsumptionType(){
        $id = input('param.id');
        $oldInfo = db('crm_s_consumptiontype')
            ->where('id',$id)
            ->find();
        $param['delete_time'] = date('Y-m-d H:i:s');
        $param['delete_staff_id'] = session('staff_id');
        $param['delete_staff'] = session('staff_name');
        $param['is_delete'] = 1;
        db()->startTrans();
        try{
            db('crm_s_consumptiontype')->where('id',$id)->update($param);
            db()->commit();
            action_log($param,$oldInfo,0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'删除子消费类型成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除子消费类型失败','data'=>$e->getMessage());
        }
    }
    function getConsumptionTypeJSON()
    {
        $data = input();
        $page = $data['page'] ? $data['page'] : 1;
        $limit = $data['limit'] ? $data['limit'] : 20;
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_consumptiontype')->where('brandclass_id',session('brandclass_id'))->where('is_delete',2)->page($page)->limit($limit)->select();
        $count = db('crm_s_consumptiontype')->where('brandclass_id',session('brandclass_id'))->where('is_delete',2)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return json($result);
    }
    /*---------------消费类型--------end----------------------*/
    /*---------------其他花费设定--------start----------------------*/
    public function anotherCost(){
        // 南宁qqbaby  2021-03-24
        if (!customize('nnqqbaby')) {
            return $this->redirect('/');
        }
        // 权限
        $auth = check_right('menu1524225422');
        if (!$auth) {
            return $this->redirect('/');
        }
        return $this->fetch();
    }
    /**
     * @cc 增加其他花费
     * */
    public function addAnotherCost(){
        $param = input();
        $data['name'] = trim($param['name']);
        $data['cost'] = trim($param['cost']);
        $data['cost_date'] = trim($param['cost_date']);
        $data['create_time'] = date('Y-m-d H:i:s');
        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('shop_name');
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');

        $time = explode(' - ',$data['cost_date']);
        $date = getDates($time[0],$time[1]);

        db()->startTrans();
        try{
            $id = db('crm_s_another_cost')->insertGetId($data);

            $avg = sprintf('%.4f',$data['cost']/count($date));
            $last_avg = $data['cost']-$avg*count($date)+$avg;
            //插入详情表
            $ins = [];
            for($i=0;$i<count($date)-1;$i++){
                $dData['pid'] = $id;
                $dData['name'] = $data['name'];
                $dData['cost_avg'] = $avg;
                $dData['cost_date'] = $date[$i];
                $dData['create_time'] = date('Y-m-d H:i:s');
                $dData['shop_code'] = session('shop_code');
                $dData['shop_name'] = session('shop_name');
                $dData['brandclass_id'] = session('brandclass_id');
                $dData['brandclass'] = session('brandclass');
                array_push($ins,$dData);
            }
            $last = array(
                'pid' => $id,
                'name' => $data['name'],
                'cost_avg' => $last_avg,
                'cost_date' => $date[count($date)-1],
                'create_time' => date('Y-m-d H:i:s'),
                'shop_code' => session('shop_code'),
                'shop_name' => session('shop_name'),
                'brandclass_id' => session('brandclass_id'),
                'brandclass' => session('brandclass'),
            );
            array_push($ins,$last);
            db('crm_s_another_cost_detail')->insertAll($ins);
            action_log($data,[],0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'添加其它花费成功','data'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'添加其它花费失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 编辑其他花费
     * */
    public function editAnotherCost(){
        $param = input();
        $id = intval($param['id']);
        $data['name'] = trim($param['name']);
        $data['cost'] = trim($param['cost']);
        $data['cost_date'] = trim($param['cost_date']);
        $data['update_time'] = date('Y-m-d H:i:s');

        $time = explode(' - ',$data['cost_date']);
        $date = getDates($time[0],$time[1]);
        db()->startTrans();
        try{
            db('crm_s_another_cost')->where('id',$id)->update($data);
            db('crm_s_another_cost_detail')->where('pid',$id)->delete();
            $avg = sprintf('%.4f',$data['cost']/count($date));
            $last_avg = $data['cost']-$avg*count($date)+$avg;
            //插入详情表
            $ins = [];
            for($i=0;$i<count($date)-1;$i++){
                $dData['pid'] = $id;
                $dData['name'] = $data['name'];
                $dData['cost_avg'] = $avg;
                $dData['cost_date'] = $date[$i];
                $dData['create_time'] = date('Y-m-d H:i:s');
                $dData['shop_code'] = session('shop_code');
                $dData['shop_name'] = session('shop_name');
                $dData['brandclass_id'] = session('brandclass_id');
                $dData['brandclass'] = session('brandclass');
                array_push($ins,$dData);
            }
            $last = array(
                'pid' => $id,
                'name' => $data['name'],
                'cost_avg' => $last_avg,
                'cost_date' => $date[count($date)-1],
                'create_time' => date('Y-m-d H:i:s'),
                'shop_code' => session('shop_code'),
                'shop_name' => session('shop_name'),
                'brandclass_id' => session('brandclass_id'),
                'brandclass' => session('brandclass'),
            );
            array_push($ins,$last);
            db('crm_s_another_cost_detail')->insertAll($ins);
            action_log($data,[],0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'修改其它花费成功','data'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'修改其它花费失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 删除其他花费
     * */
    public function delAnotherCost(){
        $param = input();
        db()->startTrans();
        try{
            db('crm_s_another_cost')->where('id',$param['id'])->delete();
            db('crm_s_another_cost_detail')->where('pid',$param['id'])->delete();
            action_log($param,[],0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'删除其它花费成功','data'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除其它花费失败','data'=>$e->getMessage());
        }
    }
    public function anotherCostJSON(){
        $data = input();
        $page = $data['page'] ? $data['page'] : 1;
        $limit = $data['limit'] ? $data['limit'] : 10;
        $where = ' 1=1 ';
        if($data['name']){
            $where .= " and name like '%".trim($data['name'])."%'";
        }
        if($data['create_time']){
            $time = explode(' - ',$data['create_time']);
            $time1 = $time[0];
            $time2 = $time[1].' 23:59:59';
            $where .= ' and create_time between "'.$time1.'" and "'.$time2.'"';
        }
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_another_cost')->where('shop_code',session('shop_code'))->where($where)->page($page)->limit($limit)->order('create_time desc')->select();
        $count = db('crm_s_another_cost')->where('shop_code',session('shop_code'))->where($where)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return json($result);
    }
    /*---------------其他花费设定--------end----------------------*/
    //报表设定
    public function reportForm(){
        // $consumptionType = controller('crm/Customer','lib')->consumptionType(['brandclass_id']);
        // $this->assign('consumptionType',$consumptionType);
        // $res = db_config('sta_default_consumptionType_'.session('shop_code'));
        // $this->assign('sta_default_consumptionType',$res);
        // $data = input();
        // if($data['psd'] != 509){
        //     $this->redirect('/');
        // }
        //事业部
        // $info = sx_call('5a38840b15ba9',[]);
        $mc = new \app\common\lib\mcInterface();
        $temp_staff = $mc->getBrand($param);

        if($info !== false){
            $this->assign('brandclassInfo',$info);
        }
        return $this->fetch();
    }

    public function staSetSub(){
        $data = input();
        $count = count($data['shop_code']);
        $bid = $data['brandclass'];

        db()->startTrans();
        for($i=0;$i<$count;$i++){
            $key = $data['shop_code'][$i];

            $all = $data['all_cus_'.$key] ? implode(',',$data['all_cus_'.$key]) : 0;
            $valid = $data['valid_'.$key] ? implode(',',$data['valid_'.$key]) : 0;
            $into = $data['into_'.$key] ? implode(',',$data['into_'.$key]) :0;
            $order = $data['order_'.$key] ? implode(',',$data['order_'.$key]) : 0;

            $is_marketing = $data[$key.'_is_marketing'];
            //查询有无数据
            $id = db('crm_s_sta_setting')->where('shop_code',$key)->value('id');
            if($id){
                $inc = [
                    'shop_code'=>$key,
                    'all_customer_consumptiontype'=>$all,
                    'valid_customer_consumptiontype'=>$valid,
                    'into_customer_consumptiontype'=>$into,
                    'order_customer_consumptiontype'=>$order,
                    'update_time'=>date('Y-m-d H:i:s'),
                    'is_marketing'=>$is_marketing,
                    'brandclass_id'=>$bid
                ];
            }else{
                $inc = [
                    'shop_code'=>$key,
                    'all_customer_consumptiontype'=>$all,
                    'valid_customer_consumptiontype'=>$valid,
                    'into_customer_consumptiontype'=>$into,
                    'order_customer_consumptiontype'=>$order,
                    'create_time'=>date('Y-m-d H:i:s'),
                    'is_marketing'=>$is_marketing,
                    'brandclass_id'=>$bid
                ];
            }

            try{
                if($id){
                    db('crm_s_sta_setting')->where('shop_code',$key)->update($inc);
                    // echo db()->getLastSql();die;
                }else{
                    db('crm_s_sta_setting')->insert($inc);
                    // echo db()->getLastSql();die;
                }

                db()->commit();
            }catch (Exception $e){
                print_r($e->getMessage());die;
                db()->rollback();
            }
        }
        action_log($data,[],0,session('staff_id'),session('staff_name'));
        return true;
    }
    //新版报表
    public function new_sta_list(){
        return $this->fetch();
    }
    //新版报表
    public function new_sta_list_json(){
        $type = session('is_marketing');
        $level  = session('is_belong');
        $result['code'] = 0;
        $result['msg'] = '';
        $list = db('crm_s_report_form')->where('report_type',$type)->select();
        foreach($list  as $k=>$v){
            if(!getReportFormAuth($v['code']) && session('main_work_type') != SYSTEM_AUTH_ADMIN){
                unset($list[$k]);
            }
        }
        foreach($list as $k=>$v){
            $list[$k]['index'] = $k+1;
        }
        $result['data'] = $list;
        $result['count'] = count($list);
        return json($result);
    }
    //部门下的小组
    public function getGroupByDepId(){
        $did = input('param.department_id');
        //部门下的小组 0609
        $mc = new \app\common\lib\mcInterface();
        $group = $mc->getGroupInfoByDid(array('department_id' => $did));
        // $groups = db('c_staff_group')->where('department_id',$did)->select();
        return $groups;
    }
    //客资录入设置
    public function cusLrSet(){
        //短信模板
        $model = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('status',1)->select();
        $this->assign('model',$model);
        $is_send_sms = db_config('is_send_sms_'.session('shop_code'));
        $this->assign('is_send_sms',$is_send_sms);//录入时是否发送短信
        //录入必选项配置
        $lrMust = db_config('lr_must_'.session('brandclass_id'));
        $lrMust = explode(',',$lrMust);
        $this->assign('lrMust',$lrMust);
        //录入状态设定
        $valid = db_config('valid_'.session('brandclass_id'));
        $this->assign('valid',$valid);
        $hidden = db_config('lr_hidden_'.session('brandclass_id'));
        $hidden = explode(',',$hidden);
        $this->assign('lrHidden',$hidden);
        return $this->fetch();
    }
    /**
     * @cc 客资提报必选项设定
     * */
    public function lrHiddenSet(){
        // 权限
        $data = input();
        $set = trim($data['set'],',');
        if(session('brandclass_id')){
            $lrMust = db_config('lr_must_'.session('brandclass_id'));
            $lrMustArr = explode(',',$lrMust);
            $hidden = explode(',',$set);
            $arr = array_intersect($lrMustArr,$hidden);
            if(!empty($lrMust) && !empty($arr)){
                return array('code'=>101,'msg'=>'选择字段中含有录入必选项字段,不能设置','data'=>'');
            }
            if (!$set) {
                $set = NULL;
            }
            $res = db_config('lr_hidden_'.session('brandclass_id'),$set);
            if($res){
                return array('code'=>200,'msg'=>'客资录入字段隐藏配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'客资录入字段隐藏配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到事业部，不能设置','data'=>'');
        }
    }
    /**
     * @cc 客资提报必选项设定
     * */
    public function DfHiddenSet(){
        // 权限
        $data = input();

        $set = trim($data['set'],',');
        if(session('brandclass_id')){
            $dfMust = db_config('df_must_'.session('brandclass_id'));
            $dfMust = explode(',',$dfMust);
            $hidden = explode(',',$set);
            $arr = array_intersect($dfMust,$hidden);
            if ($data['set']) {
                if(!empty($arr)){
                    return array('code'=>101,'msg'=>'选择字段中含有录入必选项字段,不能设置','data'=>'');
                }                
            }
            if (!$set) {
                $set = NULL;
            }
            $res = db_config('df_hidden_'.session('brandclass_id'),$set);
            if($res){
                return array('code'=>200,'msg'=>'客资录入字段隐藏配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'客资录入字段隐藏配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到事业部，不能设置','data'=>'');
        }
    }
    //报表设置列表
    function formList(){
        //已添加
        $info = db('crm_s_report_form')->where('status',2)->order("sort")->select();
        $this->assign('info',$info);
        //未添加
        $info1 = db('crm_s_report_form')->where('status',1)->order("sort")->select();
        $this->assign('info1',$info1);
        $this->assign('title','报表设置');
        return $this->fetch();
    }
    /**
     * @cc 添加编辑报表
     * */
    function addForm(){

        if(request()->isPost()){
            $data = input('post.');
            $report = [];
            $id = 0;
            $time = date('Y-m-d H:i:s');
            //设置查询对象和报表id
            foreach($data as $k=>$v){
                $id = $v['id'];
                $report[$k]['brandclass_id'] = $v['brandclass_id'] ? $v['brandclass_id'] : null;
                $report[$k]['shop_code'] = $v['shop_code'] ? $v['shop_code'] : null;
                $report[$k]['form_id'] = $v['id'];
                $report[$k]['create_time'] = $time;
                $sort = $v['sort'];
                $report_type_name = $v['report_type_name'] ? : "电商";
                unset($data[$k]['brandclass_id']);
                unset($data[$k]['shop_code']);
                unset($data[$k]['id']);
                unset($data[$k]['sort']);
                unset($data[$k]['report_type_name']);
            }
            db('crm_s_report_detail')->where('form_id',$id)->delete();//删除此报表权限
            //报表查询权限
            foreach($data as $k=>$v){
                foreach($v as $key=>$val){
                    $report_auth_detail = '';
                    if(empty($val['auth_position_code'])){
                        return array('code'=>103,'data'=>'','msg'=>'岗位不能为空');
                    }
                    $report[$k]['report_auth'] .= $val['auth_position_code'].',';
                    $report_auth_detail .= 'auth_brandclass_id='.$val['auth_brandclass_id'].',';
                    $report_auth_detail .= 'auth_shop_code='.$val['auth_shop_code'].',';
                    $report_auth_detail .= 'auth_department_id='.$val['auth_department_id'].',';
                    $report_auth_detail .= 'auth_position_code='.$val['auth_position_code'].',';
                }
                $report[$k]['report_auth'] = trim($report[$k]['report_auth'],',');
                $report[$k]['report_auth_detail'] = trim($report_auth_detail,',');
            }

            db()->startTrans();
            try{
                //设置访问权限
                db('crm_s_report_detail')->insertAll($report);
                //设置添加报表 status=2
                db('crm_s_report_form')->where('id',$id)->update(['status'=>2,'sort'=>$sort,'report_type_name'=>$report_type_name]);
                db()->commit();
                action_log($data,[],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'data'=>'','msg'=>'报表设置成功');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'data'=>$e->getMessage(),'msg'=>'报表设置失败');
            }
        }else{
            $data = input();
            set_time_limit(0);
            //报表信息
            $info = db('crm_s_report_form')->where('id',$data['id'])->find();
            $info['report_type_name'] = $info['report_type_name'] ?: "电商";
            $this->assign('info',$info);
            //报表查看权限
            $auth = db('crm_s_report_detail')->where('form_id',$data['id'])->select();
            foreach($auth as $k=>$v){
                if($v['brandclass_id']){
                    $auth[$k]['shop'] = cache('b_shop_'.$v['brandclass_id']);
                    if(empty($auth[$k]['shop'])){
                        $auth[$k]['shop'] = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>$v['brandclass_id']]);
                        cache('b_shop_'.$v['brandclass_id'],$auth[$k]['shop'],10*60);
                    }
                }
                $position_code = explode(',',$v['report_auth']);
                foreach($position_code as $kkk=>$vvv){
                    $position = cache('position_'.$vvv);
                    if(empty($position)){
                        $position = controller('crm/Setting','lib')->get_position_list(['position_code'=>$vvv]);
                        cache('position_'.$vvv,$position,10*60);
                    }
                    $auth[$k]['position'][$kkk]['auth_brand'] = $position[0]['brandclass_id'];
                    $auth[$k]['position'][$kkk]['auth_shop'] = $position[0]['shop_code'];
                    $auth[$k]['position'][$kkk]['auth_department'] = $position[0]['department_id'];
                    $auth[$k]['position'][$kkk]['auth_position'] = $vvv;
                    $auth[$k]['position'][$kkk]['shop'] = cache('shop_position_'.$position[0]['brandclass_id']);
                    if(empty($auth[$k]['position'][$kkk]['shop'])){
                        $auth[$k]['position'][$kkk]['shop']= controller('crm/Customer','lib')->get_shop(['brandclass_id'=>$position[0]['brandclass_id']]);//店
                        cache('department_'.$position[0]['shop'],$auth[$k]['position'][$kkk]['shop'],10*60);
                    }
                    $auth[$k]['position'][$kkk]['department'] = cache('department_'.$position[0]['shop_code']);
                    if(empty($auth[$k]['position'][$kkk]['department'])){
                        $auth[$k]['position'][$kkk]['department'] = controller('crm/Setting','lib')->department_list(['shop_code'=>$position[0]['shop_code']]);//部门
                        cache('department_'.$position[0]['shop_code'],$auth[$k]['position'][$kkk]['department'],10*60);
                    }
                    $auth[$k]['position'][$kkk]['position'] = cache('position_'.$position[0]['department_id']);
                    if(empty($auth[$k]['position'][$kkk]['position'])){
                        $auth[$k]['position'][$kkk]['position']  = controller('crm/Setting','lib')->get_position_list(['department_id'=>$position[0]['department_id']]);//岗位
                        cache('position_'.$position[0]['department_id'],$auth[$k]['position'][$kkk]['position'],10*60);
                    }
                }
            }
            // print_r($auth);die;
            $this->assign('auth',$auth);
            //事业部
            $brand = controller('crm/Customer','lib')->getBrandClass();
            $this->assign('brand',$brand);
            //编辑时已有的查询对象和权限
            $detail = db('crm_s_report_detail')->where('form_id',$data['id'])->select();
            $this->assign('detail',$detail);

            $this->assign('title','添加编辑报表');
            return $this->fetch();
        }
    }
    //部门下的岗位
    public function getPositionByDepId(){
        $dep = input();
        $info =controller("crm/Setting","lib")->get_position_list($dep);
        return $info;
    }
    //花费设定
    public function costSet(){
        //录入
        $lr = db_config('lr_channel_cost_'.session('shop_code'));
        $this->assign('lr',$lr);
        //修改
        $edit = db_config('edit_channel_cost_'.session('shop_code'));
        $this->assign('edit',$edit);
        //核算
        $accounting = db_config('accounting_channel_cost_'.session('shop_code'));
        $this->assign('accounting',$accounting);
        return $this->fetch();
    }
    /**
     * @cc 录入花费时间设定
     * */
    public function lrChannelCostSet(){
        $data = input();
        $old = db_config('lr_channel_cost_'.session('shop_code'));
        if(session('shop_code')){
            $res = db_config('lr_channel_cost_'.session('shop_code'),$data['day']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'花费录入时间配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'花费录入时间配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 核算花费时间设定
     * */
    public function accountingChannelCostSet(){
        $data = input();
        $old = db_config('accounting_channel_cost_'.session('shop_code'));
        if(session('shop_code')){
            $res = db_config('accounting_channel_cost_'.session('shop_code'),$data['day']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'核算录入时间配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'核算录入时间配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 修改花费时间设定
     * */
    public function editChannelCostSet(){
        $data = input();
        $old = db_config('edit_channel_cost_'.session('shop_code'));
        if(session('shop_code')){
            $res = db_config('edit_channel_cost_'.session('shop_code'),$data['day']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'花费修改时间配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'花费修改时间配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 花费录入维度
     * */
    public function channelCostMethodSet(){
        $data = input();
        if(session('shop_code')){
            $old = db_config('cost_method_'.session('shop_code'));
            $res = db_config('cost_method_'.session('shop_code'),$data['method']);
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'花费录入维度配置成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'花费录入维度配置失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 客资排重范围
     * */
    public function unrepeatStatusSave(){
        $old = json_encode(db_config('unrepeat_status'));
        $data = input('unrepeat_status');
        $data = $data?$data:null;
        $res = db_config('unrepeat_status',$data);
        action_log('客资排重排除范围修改为：'.json_encode($data),$old,0,session('staff_id'),session('staff_name'));
        if($res){
            return array('code'=>200,'msg'=>'配置成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'配置失败','data'=>'');
        }
    }
    /**
    * 客资排重方式
    */
    public function customerRepeatMethod(){
        $repeatMethod = input('customer_repeat_method');
        $old = json_encode(db_config('customer_repeat_method'));
        $res = db_config('customer_repeat_method',$repeatMethod?$repeatMethod:null);
        $name = [
            '6j1'=>'按渠道排重',
            'xaf'=>'按胎数排重',
            'all'=>'全局排重'
        ];
        action_log('客资排重方式改为：'.$repeatMethod.'['.$name[$repeatMethod].']',$old,0,session('staff_id'),session('staff_name'));
        if($res){
            return array('code'=>200,'msg'=>'配置成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'配置失败','data'=>'');
        }
    }
    /**
     * @cc 客资录入类型
     * */
    public function customerTypeSet(){
        $data = input('customer_type');
        $data = $data?$data:null;
        $res = db_config('customer_type_'.session('shop_code'),$data);
        if($res){
            return array('code'=>200,'msg'=>'配置成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'配置失败','data'=>'');
        }

    }
    //第三方配置
    public function customerForms(){
        if(request()->isAjax()){
            $result['code'] = 0;
            $result['msg'] = '';
            $res = db('crm_s_third')->where('brandclass_id',session('brandclass_id'))->field('id,url,columns,add_shop_name,dj_staff,belong_shop_name,customer_cource,create_staff')->order('id desc')->select();
            $count = db('crm_s_third')->where('brandclass_id',session('brandclass_id'))->count();
            if($res){
                foreach($res as $k=>$v){
                    $res[$k]['url'] = url('crm/Index/forms',['id'=>$v['id']],'',true);
                }
                $result['data'] = $res;
                $result['count'] = $count;
            }else{
                $result['data'] = array();
            }
            return ($result);
        }
        return $this->fetch();
    }
    /**
     * @cc 增加提报表单
     * */
    public function addCustomerForms(){
        $params = input();
        if(request()->isPost()){
            $token = strtoupper(md5(md5(get_rand_string().time())));
            $data['columns'] = implode(',',$params['col']);
            unset($data['col']);
            // $data['url'] = url('Index/third');
            $data['token'] = $token;
            $data['add_shop_code'] = $params['add_shop_code'] ? $params['add_shop_code'] : session('shop_code');
            $data['add_shop_name'] = $params['add_shop_name'] ? $params['add_shop_name'] : session('shop_name');
            $data['belong_shop_code'] = $params['belong_shop_code'] ? $params['belong_shop_code'] : session('belong_shop_code');
            $data['belong_shop_name'] = trim($params['belong_shop_name']) ? $params['belong_shop_name'] : session('belong_shop_name');
            $data['create_staff_id'] = session('staff_id');
            $data['create_staff'] = session('staff_name');
            $data['dj_staff_id'] = $params['dj_staff_id'];
            $data['dj_staff'] = $params['dj_staff'];
            $data['customer_cource_id'] = $params['customer_cource_id'];
            $data['customer_cource'] = $params['customer_cource'];
            $data['brandclass_id'] = session('brandclass_id');
            $data['brandclass'] = session('brandclass');
            $data['create_time'] = date('Y-m-d H:i:s');
            // print_r($data);die;
            db()->startTrans();
            try{
                db('crm_s_third')->insert($data);
                db()->commit();
                action_log($data,[],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'客资提报表单配置成功','data'=>'');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>100,'msg'=>'客资提报表单配置失败','data'=>$e->getMessage());
            }
        }else{
            $info = db('crm_s_third')->where('id',$params['id'])->find();
            $info['columns'] = explode(',',$info['columns']);
            $this->assign('info',$info);
            if(session('is_belong') == 1){
                $addShop = controller('crm/Customer','lib')->get_shop();
            }elseif(session('is_belong') == 2){
                $addShop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id')]);
            }else{
                $addShop = [
                    0=>[
                        'shop_code'=>session('shop_code'),
                        'shop_name'=>session('shop_name'),
                    ],
                ];
            }
            if(session('belong_shop_code')){
                $shop = [
                    0=>[
                        'shop_code'=>session('belong_shop_code'),
                        'shop_name'=>session('belong_shop_name'),
                    ],
                ];
            }else{
                $param = [
                    'brandclass_id' => $info['brandclass_id'] ? $info['brandclass_id'] : session('brandclass_id'),
                    'staff_id' => session('staff_id'),
                    'shop_type' => session('shop_type'),
                    'shop_code' => $info['add_shop_code'] ? $info['add_shop_code'] : session('shop_code'),
                    'belong_shop_code' => session('belong_shop_code'),
                    'belong_shop_name' => session('belong_shop_name'),
                ];

                $shop = getBelongShop($param);
                if($shop['code']){
                    $shop = [];
                }
            }
            $this->assign('addShop',$addShop);
            $this->assign('shop',$shop);
            $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>$info['add_shop_code'] ? $info['add_shop_code'] : session('shop_code')]);
            $this->assign('staff',$staff);
            $source = controller('crm/Customer','lib')->source(['brandclass_id'=>session('brandclass_id')]);
            $this->assign('source',$source);

            return $this->fetch();
        }
    }
    /**
     * @cc 编辑提报表单
     * */
    public function editCustomerForms(){
        $params = input();
        $data['columns'] = implode(',',$params['col']);
        unset($data['col']);
        if(!$params['add_shop_name']) unset($params['add_shop_name']);
        if(!$params['belong_shop_name']) unset($params['belong_shop_name']);
        $data['create_staff_id'] = session('staff_id');
        $data['create_staff'] = session('staff_name');
        $data['dj_staff_id'] = $params['dj_staff_id'];
        $data['dj_staff'] = $params['dj_staff'];
        $data['customer_cource_id'] = $params['customer_cource_id'];
        $data['customer_cource'] = $params['customer_cource'];
        $data['add_shop_code'] = $params['add_shop_code'] ? $params['add_shop_code'] : session('shop_code');
        $data['add_shop_name'] = $params['add_shop_name'] ? $params['add_shop_name'] : session('shop_name');
        $data['belong_shop_code'] = $params['belong_shop_code'] ? $params['belong_shop_code'] : session('belong_shop_code');
        $data['belong_shop_name'] = $params['belong_shop_name'] ? $params['belong_shop_name'] : session('belong_shop_name');
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        $data['create_time'] = date('Y-m-d H:i:s');
        $old =  db('crm_s_third')->where('id',$params['id'])->find();
        db()->startTrans();
        try{
            db('crm_s_third')->where('id',$params['id'])->update($data);
            db()->commit();
            action_log($data,$old,0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'客资提报表单配置修改成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'客资提报表单配置修改失败','data'=>$e->getMessage());
        }
    }
    public function customerFormsDetail(){
        if(request()->isAjax()){
            $id = input('param.id');
            $result['code'] = 0;
            $result['msg'] = '';
            $page = input('param.page') ? input('param.page') : 1;
            $limit = input('param.limit') ? input('param.limit') : 20;
            $res = db('crm_s_third_detail')->where('pid', $id)->page($page)->limit($limit)->order('create_time desc')->select();
            foreach($res as $k=>$v){
                $res[$k] = decodeUnicode($v);
            }
            $count = db('crm_s_third_detail')->where('pid', $id)->count();
            if($res){
                $result['data'] = $res;
                $result['count'] = $count;
            }else{
                $result['data'] = array();
            }
            return ($result);
        }
        $id = input('param.id');
        $this->assign('id', $id);
        return $this->fetch();
    }

    // 醉唐风 客资分配之后，一个月内无法成单，回到客资池，待分配 设定
    /**
     * @cc 客资回收设定
     * */
    public function unorderReturn(){
        $data = input();
        $res = db_config('unorderReturn_'.session('brandclass_id'),$data['unorderReturn']);
        if($res){
            action_log($data,[],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'设置成功。','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'设置失败。','data'=>'');
        }
    }
    // 醉唐风 网付订单收款 达到标准 自动进店 设定
    /**
     * @cc 自动进店设定
     * */
    public function onlinecash(){
        $data = input();
        if ($data['onlinecash_radio']=='实收款') {
            $datas['onlinecash_id'] = 1;
        }else if ($data['onlinecash_radio']=='占比') {
            $datas['onlinecash_id'] = 2;
        }
        $datas['onlinecash_name'] = $data['onlinecash_radio'];
        $datas['onlinecash'] = $data['onlinecash'];
        $datas = json_encode($datas);
        $res = db_config('onlinecash_'.session('brandclass_id'),$datas);
        if($res){
            action_log($data,[],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'设置成功。','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'设置失败。','data'=>'');
        }
    }
    /**
     * @cc 网付邀约  网付订单，未达到进店标准，是否可以邀约
     * */ 
    public function onlinecashInvite(){
        $data = input();
        $res = db_config('onlinecash_invite_'.session('brandclass_id'),$data['onlinecash_invite']);
        if($res){
            action_log($data,[],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'设置成功。','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'设置失败。','data'=>'');
        }
    }
    /**
     * @cc客资匹配算法设定
     *
     * @return [type] [description]
     */
    public function customerMatchMethod(){
        $data = input();
        $res = db_config('customer_match_method',$data['method']);
        if($res){
            action_log($data,[],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'设置成功。','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'设置失败。','data'=>'');
        }
    }

    //排程设定
    public function pcSet(){
        //排程设置
        if(session('shop_type') == 2){
            // 分区
            $area_list = controller('crm/Customer', 'lib')->areaSet();
            $this->assign('area', $area_list);
            //拍照店
            $shop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id')]);
            $this->assign('shop',$shop);
            $pc = db_config('paicheng_'.session('shop_code'));
            $this->assign('pc',$pc);
            return $this->fetch();
        }
    }

    
    //店面目标设置
    public function shop_goal_set(){
        //可操作店
        $shop = getShops(['staff_id'=>session('staff_id')]);
        $this->assign('shop',$shop);
        return $this->fetch();
    }
    /**
     * @cc 添加店面目标
     * */
    public function addShopGoal(){
        $data = input();
        //查看本月是否已有设定
        $res = db('crm_s_shop_goal')->where('month',date('Y-m'))->where('shop_code',$data['shop_code'])->value('id');
        if($res){
            return array('code'=>100,'msg'=>'本月已有目标，无法添加');
        }
        $arr = [
            'shop_code'=>$data['shop_code'] ? trim($data['shop_code']) : NULL,
            'shop_name'=>$data['shop_name'] ? trim($data['shop_name']) : NULL,
            'fact'=>$data['fact'] ? intval($data['fact']) : NULL,
            'jd'=>$data['jd'] ? intval($data['jd']) : NULL,
            'order'=>$data['order'] ? intval($data['order']) : NULL,
            'cus'=>$data['cus'] ? intval($data['cus']) : NULL,
            'cost'=>$data['cost'] ? intval($data['cost']) : NULL,
            'action_time'=> date('Y-m-d H:i:s'),
            'month'=> date('Y-m'),
            'ip'=>get_client_ip(),
            'staff_id'=>session('staff_id'),
            'staff_name'=>session('staff_name'),
            'brandclass_id'=>session('brandclass_id'),
            'brandclass'=>session('brandclass'),
        ];
        try{
            db('crm_s_shop_goal')->insert($arr);
            action_log($arr,[],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'店面目标设置成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>105,'msg'=>'店面目标设置失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 编辑店面目标
     * */
    public function editShopGoal(){
        $data = input();
        $id = intval($data['id']);
        //查看本月是否已有设定
        $info = db('crm_s_shop_goal')->where('id',$id)->find();
        if($info['month'] != date('Y-m')){
            return array('code'=>100,'msg'=>'不是本月目标，无法编辑');
        }
        $arr = [
            'fact'=>$data['fact'] ? intval($data['fact']) : NULL,
            'jd'=>$data['jd'] ? intval($data['jd']) : NULL,
            'order'=>$data['order'] ? intval($data['order']) : NULL,
            'cus'=>$data['cus'] ? intval($data['cus']) : NULL,
            'cost'=>$data['cost'] ? intval($data['cost']) : NULL,
            'action_time'=> date('Y-m-d H:i:s'),
            'ip'=>get_client_ip(),
            'staff_id'=>session('staff_id'),
            'staff_name'=>session('staff_name'),
        ];
        try{
            db('crm_s_shop_goal')->where('id',$id)->update($arr);
            action_log($arr,$info,0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'店面目标设置成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>105,'msg'=>'店面目标设置失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 删除店面目标
     * */
    public function delShopGoal(){
        $id = input('param.id');
        try{
            db('crm_s_shop_goal')->where('id',$id)->delete();
            action_log($id,[],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'店面目标删除成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>105,'msg'=>'店面目标删除失败','data'=>$e->getMessage());
        }
    }
    //店面目标列表
    public function getshopGoalToJSON(){
        $param = input();
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 100;
        $where = [];
        if($param['shop_code'])$where['shop_code'] = trim($param['shop_code']);
        if($param['month'])$where['month'] = trim($param['month']);
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_s_shop_goal')->where($where)
            ->order('id desc')
            ->page($page)
            ->limit($limit)
            ->select();
        $count = db('crm_s_shop_goal')->where($where)->count();
        if($res){
            $month = date('Y-m');
            foreach($res as $k=>$v){
                if($v['month'] == $month){
                    $res[$k]['is_show'] = 1;
                }else{
                    $res[$k]['is_show'] = 0;
                }
            }
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }


    // -------------------------- 新版自动分配设定 录入店==>归属店 开始 暂停 -------------------------- //

    // -------------------------- 新版自动分配设定 录入店==>归属店 结束 暂停 -------------------------- //
    /*--------------------------其它设置start --------------------------*/
    public function anotherSetting(){
        $channel = controller('crm/Customer','lib')->getChannel();
        $this->assign('channel',$channel);
        return $this->fetch();
    }
    /**
     * @cc 增加广告信息录入
     * */
    public function addAnotherSetting(){
        $data = input('post.');
        $res = db('crm_s_another_setting')
            ->where('channel_id',intval($data['channel_id']))
            ->where('time',trim($data['time']))
            ->where('staff_id',session('staff_id'))
            ->where('shop_code',session('shop_code'))
            ->where('brandclass_id',session('brandclass_id'))
            ->value('id');
        if($res){
            return array('code'=>101,'msg'=>'已有此设置，不能添加','data'=>'');
        }
        $arr = [
            'channel_id'        => intval($data['channel_id']),
            'channel_name'      => trim($data['channel_name']),
            'exposure'          => intval($data['exposure']),
            'click'             => intval($data['click']),
            'show'              => intval($data['show']),
            'fans'              => intval($data['fans']),
            'time'              => trim($data['time']),
            'staff_id'    => session('staff_id'),
            'staff_name'       => session('staff_name'),
            'group_id'    => session('group_id'),
            'group_name'       => session('group_name'),
            'department_id'    => session('department_id'),
            'department_name'       => session('department_name'),
            'brandclass_id'    => session('brandclass_id'),
            'brandclass'       => session('brandclass'),
            'shop_code'        => session('shop_code'),
            'shop_name'        => session('shop_name'),
            'create_time'      => date('Y-m-d H:i:s'),
        ];
        db()->startTrans();
        try{
            db('crm_s_another_setting')->insert($arr);
            db()->commit();
            action_log($arr,[],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'添加成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'添加失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 编辑广告信息
     * */
    public function editAnotherSetting(){
        $data = input('post.');
        $old = db('crm_s_another_setting')->where('id',intval($data['id']))->find();
        $res = db('crm_s_another_setting')
            ->where('id','<>',intval($data['id']))
            ->where('channel_id',intval($data['channel_id']))
            ->where('time',trim($data['time']))
            ->where('staff_id',session('staff_id'))
            ->where('shop_code',session('shop_code'))
            ->where('brandclass_id',session('brandclass_id'))
            ->value('id');
        if($res){
            return array('code'=>101,'msg'=>'已有此设置，不能修改','data'=>'');
        }
        $arr = [
            'channel_id'        => intval($data['channel_id']),
            'channel_name'      => trim($data['channel_name']),
            'exposure'          => intval($data['exposure']),
            'click'             => intval($data['click']),
            'show'              => intval($data['show']),
            'fans'              => intval($data['fans']),
            'time'              => trim($data['time']),
            'update_time'      => date('Y-m-d H:i:s'),
        ];
        db()->startTrans();
        try{
            db('crm_s_another_setting')->where('id',intval($data['id']))->update($arr);
            db()->commit();
            action_log($arr,$old,0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'修改成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'修改失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 删除广告信息
     * */
    public function delAnotherSetting(){
        $data = input('post.');
        $old = db('crm_s_another_setting')->where('id',intval($data['id']))->find();
        db()->startTrans();
        try{
            db('crm_s_another_setting')->where('id',intval($data['id']))->delete();
            db()->commit();
            action_log([],$old,0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'删除成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除失败','data'=>$e->getMessage());
        }
    }
    //其它设置列表
    public function anotherSettingJSON(){
        $data = input();
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $data['page'] ? $data['page'] : 1;
        $limit = $data['limit'] ? $data['limit'] : 100;
        if($data['channel_id']) $where['channel_id'] = $data['channel_id'];
        if($data['time']) $where['time'] = trim($data['time']);
        if(check_right('menu1512637269')) {//查看所有客资权限
            $auth['shop_code'] = session('shop_code');
        }elseif(check_right('menu1531471639')){//查看部门客资权限
            $auth['department_id'] = session('department_id');
        }elseif(check_right('menu1529653231')) {//查看小组客资权限
            $auth['group_id'] = session('group_id');
        }
        $result['count'] = db('crm_s_another_setting')->where($where)->where($auth)->order('id desc')->count();
        $result['data'] = db('crm_s_another_setting')->where($where)->where($auth)->order('time desc')->limit($limit)->page($page)->select();
        foreach($result['data'] as $k=>$v){
            if($v['staff_id'] == session('staff_id')){
                $result['data'][$k]['edit'] = 1;
            }else{
                $result['data'][$k]['edit'] = 0;
            }
        }
        return(($result)) ;
    }
    /*--------------------------其它设置end --------------------------*/
    /*----------提醒设置------start-------------------*/
    /**
     * @cc 操作提醒设定
     * */
    public function editValidRemind(){
        $param = input();
        $data['id'] = $param['id'];
        $data['remind_type'] = $param['remind_type'];
        $data['send_method'] = trim($param['send_method'],',');
        $data['send_receive'] = trim($param['send_receive'],',');
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');

        if(empty($param['send_method']) && !empty($param['send_receive'])){
            return array('code'=>80,'msg'=>'请选择提醒方式');
        }
        if(empty($param['send_receive']) && !empty($param['send_method']) && $param['id'] != 'login'){
            return array('code'=>90,'msg'=>'请选择提醒人员');
        }
        //查询本店有误设置
        $res = db('crm_s_reminditemset')->where('id',$param['id'])->where('brandclass_id',session('brandclass_id'))->find();
        $old = '提醒名称：【'.$res['remind_type'].'】，';
        $old .= '提醒方式：【'.$res['send_method'].'】，';
        $old .= '提醒人员：【'.$res['send_receive'].'】，';
        $old .= '设置事业部：【'.$res['brandclass'].'】';

        $new = '提醒名称：【'.$data['remind_type'].'】，';
        $new .= '提醒方式：【'.$data['send_method'].'】，';
        $new .= '提醒人员：【'.$data['send_receive'].'】，';
        $new .= '设置事业部：【'.$data['brandclass'].'】';

        db()->startTrans();
        try{
            if(empty($res)){
                db('crm_s_reminditemset')->insert($data);
            }else{
                db('crm_s_reminditemset')->where('id',$param['id'])->where('brandclass_id',session('brandclass_id'))->update($data);
            }
            db()->commit();
            action_log($new,$old,0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>$param['remind_type'].'提醒设置成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>$param['remind_type'].'提醒设置失败','data'=>$e->getMessage());
        }
    }

    /*----------提醒设置------end---------------------*/
    /*----------人员渠道匹配设置------start-------------------*/
    public function staffTrenchMate_List(){
        $mc = new \app\common\lib\mcInterface();
        $staff = $mc->getAllStaffListByShopcode(array('shop_code' => session('shop_code')));
        // $staff = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('shop_code')]);
        // var_dump($staff);
        // exit;
        $this->assign('staff_name',$staff);
        $channel = controller('crm/Setting','lib')->getQudao(session('shop_code'));
        $channels = array_column($channel,"channel_name");
        $staffTrench = controller('crm/Setting','lib')->staffTrench(session('shop_code'));
        $arr_staffTrench = array();
        foreach ($staffTrench as $key => $value) {
            $arr_staffTrench[$value['staff_id']] = explode(",",trim($value['trench'],","));
        }
        foreach ($staff as $key => $value) {
            $staff[$key]['trench'] = $arr_staffTrench[$value['id']];
            $staff[$key]['trench_arr'] = $channels;
        }
        foreach ($staff as $k => $v) {
            foreach ($v['trench_arr'] as $ke => $va) {
                if (in_array($va,$arr_staffTrench[$v['id']])) {
                    //$staff[$k]['trench_arr_type'][$ke] = 1;
                    $staff[$k]['trench_arr_types'] .= '<input class="elem-check" type="checkbox" names="'.$v['staffname'].'" name="'.$v['id'].'" value="'.$va.'" title="'.$va.'" lay-skin="primary" checked>';
                }else{
                    //$staff[$k]['trench_arr_type'][$ke] = 0;
                    $staff[$k]['trench_arr_types'] .= '<input class="elem-check" type="checkbox" names="'.$v['staffname'].'" name="'.$v['id'].'" value="'.$va.'" title="'.$va.'" lay-skin="primary">';
                }
            }
        }
        $page = input('param.page');
        $list = controller('crm/Setting','lib')->page_array(5,$page,$staff);
        $pages = controller('crm/Setting','lib')->show_array(ceil(count($staff)/5),"/crm/Setting/staffTrenchMate_List");
        $this->assign('list',$list);
        $this->assign('page',$pages);
        return $this->fetch();
    }
    /**
     * @cc 人员渠道匹配
     * */
    public function staffTrenchMate(){
        $data = input('param.');
        $data['trench'] = implode(",", array_unique(explode(",", trim($data['trench'],","))));
        $data['shop_code'] = session('shop_code');
        $staffTrench = controller('crm/Setting','lib')->staffTrenchMate($data);
        if ($staffTrench) {
            return array('code'=>200,'msg'=>'人员渠道匹配成功');
        }else{
            return array('code'=>100,'msg'=>'人员渠道匹配失败');
        }
    }
    public function staffTrenchWhere(){
        if (!input('param.staff_id')) {
            return array('code'=>100,'msg'=>'请选择人员','data'=>'');
        }
        $staff = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('shop_code')]);
        $channel = controller('crm/Setting','lib')->getQudao(session('shop_code'));
        $channels = array_column($channel,"channel_name");
        $staffTrench = controller('crm/Setting','lib')->staffTrench(session('shop_code'));
        $arr_staffTrench = array();
        foreach ($staffTrench as $key => $value) {
            $arr_staffTrench[$value['staff_id']] = explode(",",trim($value['trench'],","));
        }
        foreach ($staff as $key => $value) {
            $staff[$key]['trench'] = $arr_staffTrench[$value['id']];
            $staff[$key]['trench_arr'] = $channels;
        }
        foreach ($staff as $k => $v) {
            foreach ($v['trench_arr'] as $ke => $va) {
                if (in_array($va,$arr_staffTrench[$v['id']])) {
                    $staff[$k]['trench_arr_type'][$ke] = 1;
                }else{
                    $staff[$k]['trench_arr_type'][$ke] = 0;
                }
            }
        }
        foreach ($staff as $k => $v) {
            if (input('param.staff_id')&&input('param.staff_id')==$v['id']) {
                $where_arr = $v;
            }
        }
        if ($where_arr) {
            $html = '<td style="color:red">查询</td>';
            $html .= '<td style="color:red">'.$where_arr['staffname'].'</td>';
            $html .= '<td class="list layui-form" lay-filter="test'.$where_arr['id'].'"><div class="layui-btn layui-btn-fluid all-btn" data-id="'.$where_arr['id'].'">全选</div>&nbsp;<div class="layui-btn layui-btn-fluid reverse-btn" data-id="'.$where_arr['id'].'">反选</div>&nbsp;';
            foreach ($where_arr['trench_arr'] as $key => $value) {
                $html .= '<input class="elem-check" type="checkbox" names="'.$where_arr['staffname'].'" name="'.$where_arr['id'].'" value="'.$value.'" title="'.$value.'" lay-skin="primary" ';
                if ($where_arr['trench_arr_type'][$key]==1) {
                    $html .= 'checked>';
                }else{
                    $html .= '>';
                }
            }
            $html .= '<div class="layui-btn layui-btn-fluid save-btn" data-id="'.$where_arr['id'].'">保存确认</div></td>';
            return array('code'=>200,'msg'=>'成功','data'=>$html);
        }else{
            return array('code'=>300,'msg'=>'没有查到','data'=>$where_arr);
        }
    }
    /*----------人员渠道匹配设置------end-------------------*/
    /*----------标签设定------start-------------------*/
    public function labelSetting(){
        $info = db('crm_s_label_cat')->where('brandclass_id',session('brandclass_id'))->where('status',2)->select();
        $this->assign('info',$info);
        return $this->fetch();
    }
    /**
     * @cc 添加标签分类
     * */
    public function addLabelCat(){
        $param = input();
        $id = db('crm_s_label_cat')->where('brandclass_id',session('brandclass_id'))->where('status',2)->where('cat_name',$param['cat_name'])->value('id');
        if($id){
            return array('code'=>100,'msg'=>'标签分类名称重复');
        }
        $data['cat_name'] = trim($param['cat_name']);
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        $log = '添加标签分类：'.$param['cat_name'];
        db()->startTrans();
        try{
            db('crm_s_label_cat')->insert($data);
            action_log($log,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'标签分类设置成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>110,'msg'=>'标签分类设置失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 修改标签分类
     * */
    public function editLabelCat(){
        $param = input();
        $id = db('crm_s_label_cat')->where('brandclass_id',session('brandclass_id'))->where('status',2)->where('cat_name',$param['cat_name'])->value('id');
        if($id && $id != $param['id']){
            return array('code'=>100,'msg'=>'标签分类名称重复');
        }
        $data['cat_name'] = trim($param['cat_name']);
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        db()->startTrans();
        try{
            $res = db('crm_s_label_cat')->where('id',$param['id'])->update($data);
            if($res){
                $log = '修改标签分类：'.$param['cat_name'];
                action_log($log,'',0,session('staff_id'),session('staff_name'));
            }
            cache('label_'.session('brandclass_id'),NULL);
            db()->commit();
            return array('code'=>200,'msg'=>'标签分类设置成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>110,'msg'=>'标签分类设置失败','data'=>$e->getMessage());
        }
    }
    public function getLabelCatJSON(){
        $param = input();
        $result['code'] = 0;
        $result['msg'] = '';
        if($param['cat_name']){
            $result['count'] = db('crm_s_label_cat')->where('brandclass_id',session('brandclass_id'))->where('cat_name','like','%'.$param['cat_name'].'%')->field('id,cat_name')->where('status',2)->order('id desc')->count();
            $result['data'] = db('crm_s_label_cat')->where('brandclass_id',session('brandclass_id'))->where('cat_name','like','%'.$param['cat_name'].'%')->field('id,cat_name')->where('status',2)->order('id desc')->select();
        }else{
            $result['count'] = db('crm_s_label_cat')->where('status',2)->where('brandclass_id',session('brandclass_id'))->order('id desc')->count();
            $result['data'] = db('crm_s_label_cat')->where('status',2)->where('brandclass_id',session('brandclass_id'))->field('id,cat_name')->order('id desc')->select();
        }
        return(($result)) ;
    }
    public function getLabelJSON(){
        $param = input();
        $result['code'] = 0;
        $result['msg'] = '';
        $limit = $param['limit'];
        $page = $param['page'];
        if($param['cat_name']){
            $result['count'] = db('crm_s_label')->where('brandclass_id',session('brandclass_id'))->where('cat_name','like','%'.$param['cat_name'].'%')->where('is_delete',2)->order('id desc')->count();
            $result['data'] = db('crm_s_label')->where('brandclass_id',session('brandclass_id'))->where('cat_name','like','%'.$param['cat_name'].'%')->where('is_delete',2)->order('label_cat_id desc')->page($page)->limit($limit)->select();
        }else{
            $result['count'] = db('crm_s_label')->where('is_delete',2)->where('brandclass_id',session('brandclass_id'))->order('label_cat_id desc')->count();
            $result['data'] = db('crm_s_label')->where('is_delete',2)->where('brandclass_id',session('brandclass_id'))->page($page)->limit($limit)->order('id desc')->select();
        }
        return(($result)) ;
    }
    /**
     * @cc 删除标签名称
     * */
    public function delLabelCate(){
        $id = input('post.id');
        db()->startTrans();
        try{
            db('crm_s_label_cat')->where('id',$id)->update(['status'=>1]);
            action_log('删除名称为：'.input('post.cat_name').'的标签分类','',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'标签分类删除成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>110,'msg'=>'标签分类删除失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 删除标签名称
     * */
    public function delLabel(){
        $id = input('post.id');
        db()->startTrans();
        try{
            db('crm_s_label')->where('id',$id)->update(['is_delete'=>1]);
            action_log('删除名称为：'.input('post.label_name').' 的标签','',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'标签名称删除成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>110,'msg'=>'标签名称删除失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 添加标签名称
     * */
    public function addLabelName(){
        $param = input();
        $id = db('crm_s_label')->where('brandclass_id',session('brandclass_id'))->where('is_delete',2)->where('label_name',$param['label_name'])->value('id');
        if($id){
            return array('code'=>100,'msg'=>'标签名称重复');
        }
        $data['label_cat_id'] = intval($param['label_cat_id']);
        $data['label_cat_name'] = trim($param['label_cat_name']);
        $data['label_name'] = trim($param['label_name']);
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        $data['create_time'] = date('Y-m-d H:i:s');
        $log = '添加标签名称：'.$data['cat_name'].'=>'.$data['label_name'];
        db()->startTrans();
        try{
            db('crm_s_label')->insert($data);
            action_log($log,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'标签名称设置成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>110,'msg'=>'标签名称设置失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 修改标签名称
     * */
    public function editLabelName(){
        $param = input();
        $id = db('crm_s_label')->where('brandclass_id',session('brandclass_id'))->where('is_delete',2)->where('label_name',$param['label_name'])->value('id');
        if($id && $id != $param['id']){
            return array('code'=>100,'msg'=>'标签名称重复');
        }
        $data['label_cat_id'] = intval($param['label_cat_id']);
        $data['label_cat_name'] = trim($param['label_cat_name']);
        $data['label_name'] = trim($param['label_name']);
        $data['brandclass_id'] = session('brandclass_id');
        $data['brandclass'] = session('brandclass');
        $data['update_time'] = date('Y-m-d H:i:s');
        db()->startTrans();
        try{
            $res = db('crm_s_label')->where('id',$param['id'])->update($data);
            if($res){
                $log = '修改标签名称：'.$data['cat_name'].'=>'.$data['label_name'];
                action_log($log,'',0,session('staff_id'),session('staff_name'));
            }
            cache('label_'.session('brandclass_id'),NULL);
            db()->commit();
            return array('code'=>200,'msg'=>'标签名称设置成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>110,'msg'=>'标签名称设置失败','data'=>$e->getMessage());
        }
    }
    /*----------标签设定------end-------------------*/

    // 设定客资列表 tab 中相关列的时间查询区间
    public function getTabTimearea(){
        $shop_code = session('shop_code');
        // 孕妈
        $ymTimeare = db_config('ymTimeare_'.$shop_code);
        if (!$ymTimeare) {
            $ymTimeare = db_config('default_ymTimeare');
        }
        $this->assign('ym',$ymTimeare);
        // 出生
        $csTimeare = db_config('csTimeare_'.$shop_code);
        if (!$csTimeare) {
            $csTimeare = db_config('default_csTimeare');
        }
        $this->assign('cs',$csTimeare);
        // 满月
        $myTimeare = db_config('myTimeare_'.$shop_code);
        if (!$myTimeare) {
            $myTimeare = db_config('default_myTimeare');
        }
        $this->assign('my',$myTimeare);
        // 百天
        $btTimeare = db_config('btTimeare_'.$shop_code);
        if (!$btTimeare) {
            $btTimeare = db_config('default_btTimeare');
        }
        $this->assign('bt',$btTimeare);
        // 半岁
        $bsTimeare = db_config('bsTimeare_'.$shop_code);
        if (!$bsTimeare) {
            $bsTimeare = db_config('default_bsTimeare');
        }
        $this->assign('bs',$bsTimeare);
        // 周岁
        $zsTimeare = db_config('zsTimeare_'.$shop_code);
        if (!$zsTimeare) {
            $zsTimeare = db_config('default_zsTimeare');
        }
        $this->assign('zs',$zsTimeare);

        return $this->fetch();
    }
    public function setTabTimearea(){
        $data = input();
        $shop_code = session('shop_code');
        if($shop_code){
            if ($data['type']=='ym') {
                $key = 'ymTimeare_';
            }else if ($data['type']=='cs') {
                $key = 'csTimeare_';
            }else if ($data['type']=='my') {
                $key = 'myTimeare_';
            }else if ($data['type']=='bt') {
                $key = 'btTimeare_';
            }else if ($data['type']=='bs') {
                $key = 'bsTimeare_';
            }else if ($data['type']=='zs') {
                $key = 'zsTimeare_';
            }else{
                return array('code'=>201,'msg'=>'设定类型错误，请重试','data'=>'');
            }
            $timeArea['start'] = $data['start'];
            $timeArea['end'] = $data['end'];
            $old = db_config($key.$shop_code);
            $res = db_config($key.$shop_code, json_encode($timeArea));
            if($res){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'设定失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'操作店面信息，无法设置','data'=>'');
        }
    }
    /**
     * 总实收目标设定
     * 使用crm_s_kpi_staffgoal表，只操作flag=shop kpi_id=totalFact 的记录，
     * @return [type] [description]
     * @author songdemei <songdemei@suxuantech.cn>
     */
    public function totalFactKpi(){
        
    }
    /**
     * 根据shop_code 获取店下的部门   
     * @param  shop_code
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getDepartmentByShop(){
        $param = input();
        $departmentList = controller('crm/Setting','lib')->department_list(array('shop_code'=>$param['shop_code']));
        return $departmentList;
    }

    // 大屏目标设定页面
    public function bgGoalset(){
        $mc = new \app\common\lib\mcInterface();
        // 大屏目标设定（全部）
        // if (check_right('menu1569317527')) {
            $shopList = [];
            $brand = $mc->getBrand();
            if (count($brand)==1) {
                $brand[0]['select'] = 1;
                $temp = $mc->getBrandShops($brand[0]['brandclass']);
                foreach ($temp as $key => $value) {
                    $shopList[$key]['shop_code'] = $value['shop_code'];
                    $shopList[$key]['shop_name'] = $value['shop_name'];
                }
            }
        // }
        // 大屏目标设定（本店）
        // else if (check_right('menu1569319176')) {
            if(session('brandclass_id')){
                $brand[0]['id'] = session('brandclass_id');
                $brand[0]['brandclass'] = session('brandclass');
                $brand[0]['select'] = 1;
            }

            if(session('shop_code')){
                $shopList[0]['shop_code'] = session('shop_code');
                $shopList[0]['shop_name'] = session('shop_name');
                $shopList[0]['select'] = 1;
            }

        // }else{
        //     controller('crm/Index','controller')->index();
        //     exit;
        // }

        $this->assign('pinci',db('crm_c_sysconfig')->where('ckey',CSYSCONFIG_PINCI)->value('cvalue'));
        $this->assign('jiage',json_decode(db('crm_c_sysconfig')->where('ckey',CSYSCONFIG_JIAGEQUJIAN)->value('cvalue'),true));
        
        $this->assign('brand',$brand);
        $this->assign('shopList',$shopList);
        $merge = config('big_screen_shop_merge');
        if($merge){
            $this->assign('merge',$merge);
        }

        //斑马大屏 取值店设定
        $this->assign('cdtsyx',customize('cdtsyx'));
        $banma = db('crm_c_sysconfig')->where('ckey','banmaDapingShop')->find();
        $bamadp = $banma['cvalue'] ? json_decode($banma['cvalue'],true) : [];
        $this->assign('bamadp',$bamadp);
        //店 
        $shopData = $mc->getBrandShops(session('brandclass'));
        $this->assign('shopData',$shopData);

        $goal = db('crm_s_goal_name')->select();
        $this->assign('goal',$goal);
        return $this->fetch();
    }
    // 列表页接口
    public function monthGoalJSON(){
        $data = input();
        $result['code'] = 0;
        $result['msg'] = '';
        $limit = $data['limit'] ? $data['limit'] : 20;
        $page = $data['page'] ? $data['page'] : 1;
        $where = [];
        if($data['goal_name']) $where['goal_name'] = trim($data['goal_name']);
        if($data['month']) $where['month'] = trim($data['month']);
        $res = db('crm_s_goal')->where('year is not null')->where('month is not null')->where('day is null')->where($where)->limit($limit)->page($page)->order('create_time desc')->select();
        $count = db('crm_s_goal')->where('year is not null')->where('month is not null')->where('day is null')->where($where)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return json($result);
    }
    // 添加目标
    public function addMonthGoal(){
        $param = input();
        $time = date('Y-m-d H:i:s');
        $year = explode('-',$param['month']);

        $id = db('crm_s_goal')->where('goal_name',$param['goal_name'])->where('method',$param['method'])->where('key',$param['shop_code'])->where('name',$param['shop_name'])->where('year',$year[0])->where('month',$param['month'])->value('id');
        if($id){
            return array('code'=>90,'msg'=>'已有此月目标，不能新增！');
        }
        $month['name'] = $param['shop_name'];
        $month['key'] = $param['shop_code'];
        $month['shop_code'] = $param['shop_code'];

        $month['goal_name'] = $param['goal_name'];
        $month['goal_value'] = trim($param['goal_value']);
        $month['method'] = $param['method'];
        $month['year'] = $year[0];
        $month['month'] = $param['month'];
        $month['status'] = $param['status'];
        $month['create_time'] = $time;

        try{
            db('crm_s_goal')->insert($month);

            $log = '【'.session('staff_name').'】 于'.date('Y-m-d H:i:s').' 新增【'.$month['month'].'月】【'.$month['name'].'】的【'.$month['goal_name'].'】目标，目标值为【'.$month['goal_value'].'】;';
            db()->commit();
            action_log($log,[]);
            return array('code'=>200,'msg'=>'目标新增成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'目标新增失败','data'=>$e->getMessage());
        }
    }
    // 列修改月目标
    public function columnEditMonthGoal(){
        $param = input();
        $info = db('crm_s_goal')->where('id',$param['id'])->find();

        try{
            db('crm_s_goal')->where('id',$param['id'])->update([$param['field']=>$param['goal_value']]);
            $log = '【'.session('staff_name').'】 于'.date('Y-m-d H:i:s').' 通过列编辑修改【'.$info['month'].'月】【'.$info['name'].'】的【'.$info['goal_name'].'】目标值，改为：【'.$param['goal_value'].'】;';
            db()->commit();
            action_log($log,[]);
            return array('code'=>200,'msg'=>'目标修改成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'目标修改失败','data'=>$e->getMessage());
        }
    }
    // 修改月目标
    public function editMonthGoal(){
        $param = input();
        $year = explode('-',$param['month']);
        $info = db('crm_s_goal')->where('method',$param['method'])->where('month',$param['month'])->where('goal_name',$param['goal_name'])->where('key',$param['shop_code'])->where('name',$param['shop_name'])->where('id','<>',intval($param['id']))->find();
        if(!empty($info)){
            return array('code'=>90,'msg'=>'已有此月目标，不能修改！');
        }
        $month['goal_name'] = $param['goal_name'];
        $month['goal_value'] = ($param['goal_value']);
        $month['method'] = $param['method'];
        $month['shop_code'] = $param['shop_code'];
        $month['key'] = $param['shop_code'];
        $month['name'] = $param['shop_name'];
        $month['year']  = $year[0];
        $month['month'] = $param['month'];
        $month['status'] = $param['status'];

        try{
            db('crm_s_goal')->where('id',$param['id'])->update($month);
            $log = '【'.session('staff_name').'】 于'.date('Y-m-d H:i:s').' 修改【'.$info['month'].'月】【'.$info['name'].'】的【'.$info['goal_name'].'】目标，目标：【'.$param['goal_name'].'】，目标值【'.$month['goal_value'].'】，月份：【'.$month['month'].'月】;';
            db()->commit();
            action_log($log,[]);
            return array('code'=>200,'msg'=>'目标修改成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'目标修改失败','data'=>$e->getMessage());
        }
    }
    // 删除月目标
    public function delMonthGoal(){
        $id = input('id');
        $time = date('Y-m-d H:i:s');
        $info = db('crm_s_goal')->where('id',(int)$id)->find();
        db()->startTrans();
        try{
            $res = db('crm_s_goal')->where('id',(int)$id)->delete();
            $log = '【'.session('staff_name').'】 于'.$time.' 删除【'.$info['month'].'月】【'.$info['name'].'】的【'.$info['goal_name'].'】目标，目标值为【'.$info['goal_value'].'】;';
            db()->commit();
            action_log($log,[]);
            return array('code'=>200,'msg'=>'目标删除成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'','data'=>$e->getMessage());
        }
    }
    //大屏频次/价格区间设定
    public function bggoalSetData(){
        $params = input('');
        if($params['key'] == 'pinci'){
            $ckey = CSYSCONFIG_PINCI;
        }elseif($params['key'] == 'jiage'){
            $ckey = CSYSCONFIG_JIAGEQUJIAN;
            $jiage['name'] = $params['name'];
            $jiage['one'] = $params['one'];
            $jiage['two'] = $params['two'];
            if(!empty($params['one']) && !empty($params['two'])){
                $params['value'] = json_encode($jiage);
            }
        }
        db()->startTrans();
        try{
            $data = db('crm_c_sysconfig')->where('ckey',$ckey)->find();
            if($data){
                $res = db('crm_c_sysconfig')->where('ckey',$ckey)->update(['cvalue'=>$params['value']]);
            }else{
                $res = db('crm_c_sysconfig')->insert(['ckey'=>$ckey,'cvalue'=>$params['value']]);
            }
            $log = '【'.session('staff_name').'】 于'.$time.' 修改【'.$ckey.'】的值,设置为【'.$params['value'].'】;';
            db()->commit();
            action_log($log,[]);
            return array('code'=>200,'msg'=>'设置成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'设置失败，请重试','data'=>$e->getMessage());
        }
       

    }


    /**
     * @cc 网付订单是否可收款
     * */
    public function set_order_money(){
        $data = input();
        $old = db_config('set_order_money_'.session('brandclass_id'));
        $res = db_config('set_order_money_'.session('brandclass_id'),$data['set_order_money']);
        if($res){
            action_log($data,[$old],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'转订单是否可输入金额设定成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'转订单是否可输入金额设定失败','data'=>'');
        }
    }
    /**
     * 数据大屏地址
    **/
    public function bigscreen(){
        $data = input();
        $old = db_config('bg_controller');
        $res = db_config('bg_controller',$data['bigscreen']);
        if($res){
            action_log($data,[$old],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'数据大屏地址设定成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'数据大屏地址设定失败','data'=>'');
        }
    }
    /**
    * 系统字典
    * */
    public function systemDictionary(){

        if (check_right('menu1516949559')) {    //渠道名称
            $this->assign('this_tab','menu1516949559');
        }else if (check_right('menu1513213883')) { //客资标记
            $this->assign('this_tab','menu1513213883');
        }else if (check_right('menu1512898027')) { //追踪标记
            $this->assign('this_tab','menu1512898027');
        }else if (check_right('menu1512028684')) { //追踪阶段
            $this->assign('this_tab','menu1512028684');
        }else if (check_right('menu1521784361')) { //驳回原因
            $this->assign('this_tab','menu1521784361');
        }else if (check_right('menu1512029560')) { //不在驳回原因
            $this->assign('this_tab','menu1512029560');
        }else if (check_right('menu1591943564')) { //会所设定
            $this->assign('this_tab','menu1591943564');
        }else if (check_right('menu1517560908')) { //省市设定
            $this->assign('this_tab','menu1517560908');
        }else if (check_right('menu1512029583')) { //短信模板设定
            $this->assign('this_tab','menu1512029583');
        }else if (check_right('menu1537348792')) { //呼叫中心设定
            $this->assign('this_tab','menu1537348792');
        }

        return $this->fetch();
    }


    /**
     * 集团数据大盘设定
    */
    public function dapanDataGetJson(){
        
        $shop_name = input("post.shop_name");
        $day = input("post.day");
        if($shop_name == '爱婴中心'){
            $data[0]['target'] = '医院拍摄';
            $data[1]['target'] = 'DCC邀约量';
            $data[2]['target'] = '上门率';
            $data[3]['target'] = '拍摄率';
            $data[4]['target'] = '成交率';
            $data[5]['target'] = '均值';
            $data[6]['target'] = '业绩';
        }elseif($shop_name == '门店中心'){
            $data[0]['target'] = '选片率';
            $data[1]['target'] = '成交率';
            $data[2]['target'] = '套系续订律';
            $data[3]['target'] = '体验转单率';
            $data[4]['target'] = '均值';
            // $data[5]['target'] = '服务建议率';
            $data[5]['target'] = '业绩';
        }elseif($shop_name == '研发中心'){
            $data[0]['target'] = '拍摄完成率';
            $data[1]['target'] = '后期建议率';
            $data[2]['target'] = '拍摄建议率';
            $data[3]['target'] = '引导建议率';
            $data[4]['target'] = '服务建议率';
            $data[5]['target'] = '化妆建议率';
            $data[6]['target'] = '拍摄服务建议率';
        }elseif($shop_name == '研发中心-1'){
            $shop_name = '研发中心';
            $data[0]['target'] = '摄影部样片';
            $data[1]['target'] = '微电影样片';
            $data[2]['target'] = '月获奖人次';
            $data[3]['target'] = '获取天数';
            $data[4]['target'] = '产品内返率';
            $data[5]['target'] = '产品外返率';
        }elseif($shop_name == '客服中心'){
            $data[0]['target'] = '开放量';
            $data[1]['target'] = '预约量';
            $data[2]['target'] = '到店量';
            $data[3]['target'] = '到店率';
            $data[4]['target'] = '日运转率';
        }elseif($shop_name == '客服中心-1'){
            $shop_name = '客服中心';
            $data[0]['target'] = '当天';
            $data[1]['target'] = '7天';
            $data[2]['target'] = '15天';
            $data[3]['target'] = '30天';
            $data[4]['target'] = '60天';
        }elseif($shop_name == '网销中心'){
            $data[0]['target'] = '客资';
            $data[1]['target'] = '客资单价';
            $data[2]['target'] = '有效率';
            $data[3]['target'] = '成交率';
            $data[4]['target'] = 'ROI';
            $data[5]['target'] = '业绩';
        }elseif($shop_name == '微电影'){
            $data[0]['target'] = '拍摄量';
            $data[1]['target'] = '选片量';
            $data[2]['target'] = '出单率';
            $data[3]['target'] = '均值';
            $data[4]['target'] = '业绩';
        }elseif($shop_name == '服务督察组'){
            $data[0]['target'] = '拨打量';
            $data[1]['target'] = '有效率';
            $data[2]['target'] = '服务满意度';
            $data[3]['target'] = '差评解决率';
            $data[4]['target'] = '服务建议率';
        }elseif($shop_name == '人事部'){
            $data[0]['target'] = '总编制';
            $data[1]['target'] = '储备编制';
            $data[2]['target'] = '人效';
            $data[3]['target'] = '重要岗位招聘进度';
            $data[4]['target'] = '普通岗位招聘进度';
            $data[5]['target'] = '面试量';
            $data[6]['target'] = '通过量';
            $data[7]['target'] = '试岗量';
        }elseif($shop_name == '人事部-1'){
            $shop_name = '人事部';
            $data[0]['target'] = '7日试岗流失率';
            $data[1]['target'] = '15日试岗流失率';
            $data[2]['target'] = '自离率';
            $data[3]['target'] = '门店试岗流失率';
            $data[4]['target'] = '本月增减人数';
            $data[5]['target'] = '离职率最高部门';
        }elseif($shop_name == '莉帝希雅'){
            $data[0]['target'] = '拍摄量';
            $data[1]['target'] = '门店订单量';
            $data[2]['target'] = '剩余拍摄量';
            $data[3]['target'] = '均值';
            $data[4]['target'] = '网销客资';
            $data[5]['target'] = '网销业绩';
            $data[6]['target'] = '部门业绩';
        }elseif($shop_name == '市场部'){
            $data[0]['target'] = '客资数据';
            $data[1]['target'] = '体验到店率';
            $data[2]['target'] = '均值';
            $data[3]['target'] = '投放费用';
            $data[4]['target'] = '业绩';
        }elseif($shop_name == '回客组'){
            $data[0]['target'] = '总客资量';
            $data[1]['target'] = '有效率';
            $data[2]['target'] = '成交单量';
            $data[3]['target'] = '均值';
            $data[4]['target'] = '业绩';
        }
        $start = date('Y-m-d 00:00:00',strtotime($day));
        $end = date('Y-m-d 23:59:59',strtotime($day));
        $bggData = db('crm_s_bggoalset')->where('shop_name',$shop_name)->where('day',['between',[$start,$end]])->select();

        foreach ($data as $key => $value) {
            foreach ($bggData as $k2 => $v2) {
                if($value['target'] == $v2['target']){
                    $data[$key] = $v2;
                }
            }
        }

        $return['data']=$data;
        $return['code']=0;
        return $return;
    }

    //数据大盘设定 修改
    public function dapanDataSet(){
        $params = input("");

        if(!$params['value']){
            //return json(['code'=>202,'msg'=>'未获取到修改值！','data'=>'']);
        }
        if(!$params['field']){
            return json(['code'=>202,'msg'=>'未获取到修改字段！','data'=>'']);
        }
        if(!$params['shop_name']){
            return json(['code'=>202,'msg'=>'未获取到修改店面！','data'=>'']);   
        }
        if(!$params['day']){
            return json(['code'=>202,'msg'=>'未获取到时间！','data'=>'']);   
        }

        $start = date('Y-m-d 0:0:0',strtotime($params['day']));
        $end = date('Y-m-d 23:59:59',strtotime($params['day']));

        db()->startTrans(); 
        try {

            //标准值为一个月的统一值
            if($params['field'] == 'biaozhun'){

                //选中月份的所有日期
                $j = date("t",$params['day']); //获取选中月份的总天数
                $start_time = strtotime(date('Y-m-01',strtotime($params['day']))); //获取本月第一天时间戳4102
                $array = array();
                for($i=0;$i<$j;$i++){
                    $array[] = date('Y-m-d',$start_time+$i*86400); //每隔一天赋值给数组1653
                }
                foreach ($array as $key => $value) {
                    $dayStart = date('Y-m-d 0:0:0',strtotime($value));
                    $dayEnd = date('Y-m-d 23:59:59',strtotime($value));
                    $isDayData = db('crm_s_bggoalset')
                            ->where('target',$params['data']['target'])
                            ->where('shop_name',$params['shop_name'])
                            ->where('day',['between',[$dayStart,$dayEnd]])
                            ->find();
                    if($isDayData){
                        db('crm_s_bggoalset')->where('id',$isDayData['id'])->update(['biaozhun'=>$params['value'],'update_time'=>date('Y-m-d H:i:s',time())]);
                    }else{
                        db('crm_s_bggoalset')->insert(['day'=>$value,'biaozhun'=>$params['value'],'shop_name'=>$params['shop_name'],'target'=>$params['data']['target'],'create_time'=>date('Y-m-d H:i:s',time())]);
                    }
                }

            }else{

                //1、检测要修改的值数据是否存在
                $isData = db('crm_s_bggoalset')
                    ->where('target',$params['data']['target'])
                    ->where('shop_name',$params['shop_name'])
                    ->where('day',['between',[$start,$end]])
                    ->find();

                //2、修改 or 添加
                if($isData){

                    $updateArr = [
                        $params['field']=>$params['value'],
                        'update_time'=>date('Y-m-d H:i:s',time()),
                    ];

                    db('crm_s_bggoalset')->where('id',$isData['id'])->update($updateArr);

                }else{

                    $addArr = [
                        $params['field'] => $params['value'],
                        'shop_name'=>$params['shop_name'],
                        'target'=>$params['data']['target'],
                        'day'=>$params['day'],
                        'create_time'=>date('Y-m-d H:i:s',time())
                    ];

                    db('crm_s_bggoalset')->insert($addArr);

                }
            }
            db()->commit();
            return json(['code'=>200,'msg'=>'更新成功']);
        } catch (Exception $e) {
            db()->rollback();
            return json(['code'=>202,'msg'=>'更新失败,'.$e->getMessage()]); 
        }
    }

    // 进客
    public function enterGuest(){
        $data = input();
        $old = db_config('enterGuest');
        $res = db_config('enterGuest',$data['enterGuest']);
        // var_dump(session('shop_code'));die;
        if($res){
            action_log($data,[$old],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'设定成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'设定失败','data'=>'');
        }
    }


    // -------------------------- 南宁定制 start ------------------------- //
    //花费品牌设定 db
    public function brandset(){
        // 权限
        $auth = check_right('menu1587367259');
        if (!$auth) {
            return $this->redirect('/');
        }
        $keyword = input('post.name');
        if(\think\Request::instance()->isAjax()){
            $res = controller('crm/Setting','lib')->getBrandSet($keyword);
            return json($res);
        }
        $this->assign('name',$keyword);
        $this->assign('title','品牌设定');
        return $this->fetch();
    }
    //设定花费品牌
    public function setBrand(){
        $name = input('name');
        $sort = input('sort') ? input('sort') : 0;
        $id = input('id');

        if(!$name){
            return ['code'=>201,'msg'=>'请填写品牌名'];
        }

        $data = [
            'name' => $name,
            'sort' => $sort,
        ];

        db()->startTrans();
        if($id){
            $data['update_staff_id'] = session('staff_id');
            $data['update_staff_name'] = session('staff_name');
            $data['update_time'] = date('Y-m-d H:i:s');
            $res = db('crm_s_brandset')->where('id',$id)->update($data);
        }else{
            $data['add_staff_id'] = session('staff_id');
            $data['add_staff_name'] = session('staff_name');
            $data['add_time'] = date('Y-m-d H:i:s');
            $res = db('crm_s_brandset')->insert($data);
        }
        if($res === false){
            db()->rollback();
            return ['code'=>204,'msg'=>'品牌操作失败，请稍后重试！'];
        }else{
            action_log(input('post.'),'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return ['code'=>200,'msg'=>'操作成功！'];
        }
    }
    function delBrand($id){
        db()->startTrans();
        $res = db('crm_s_brandset')->where('id',$id)->delete();
        if($res !== false){
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return ['code'=>200,'msg'=>'操作成功！'];
        }else{
            db()->rollback();
            return ['code'=>204,'msg'=>'品牌删除失败，请稍后重试！'];
        }
    }
    //粉丝互动录入
    public function fans(){
        // 南宁qqbaby  2021-03-24
        if (!customize('nnqqbaby')) {
            return $this->redirect('/');
        }
        if(request()->instance()->isAjax()){

            $params = input('request.');
            $res = controller('crm/Setting','lib')->getFansToJSON($params);
            return json($res);
        }
        // 权限
        $auth = check_right('menu1587463964');
        if (!$auth) {
            return $this->redirect('/');
        }
        $channel = controller('crm/Setting','lib')->getChannelclass();
        $this->assign('channel',$channel);
        //获取渠道
        $qudao = controller('crm/Setting','lib')->getChannelInfo();
        $this->assign('qudao',$qudao);
        //渠道
        $ch = controller('crm/Customer','lib')->getChannel();
        $this->assign('ch',$ch);
        //城市
        $data['type']=2;
        $address=controller("crm/Customer","lib")->address($data);
        $this->assign("address",$address);

        $shop_code = session('shop_code');
        $staff = getShopStaffs(['shop_code'=>$shop_code]);
        $this->assign("staff",$staff);

        //来源渠道
        $channels = getChannelJson(session('shop_code'));
        $this->assign("channels", json_encode($channels));

        $edit_channel_cost_date = db_config('edit_channel_cost_'.session('shop_code'));
        $lr_channel_cost_date = db_config('lr_channel_cost_'.session('shop_code'));
        $this->assign('edit_channel_cost_date',$edit_channel_cost_date);
        $this->assign('lr_channel_cost_date',$lr_channel_cost_date);
        return $this->fetch();
    }
    /**
     * @cc 新增粉丝互动量
     * */
    function addFans(){
        // 权限
        $auth = check_right('menu1587463964');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addFans(input('post.'));
    }
    /**
     * @cc 删除粉丝互动量
     * */
    function  delFans(){
        // 权限
        $auth = check_right('menu1587463964');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delFans(input('post.id'));
    }
    
    /**
     * @cc 分配后客资状态时限
     * */
    public function validDayToFp(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $sms = db_config('valid_day_to_fp_'.session('brandclass_id'));
            $res = db_config('valid_day_to_fp_'.session('brandclass_id'),$data['valid_day_to_fp'] ? $data['valid_day_to_fp'] : null);
            if($res){
                action_log($data,[$sms],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'客资状态时限设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'客资状态时限设定失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 分配后客资状态时限
     * */
    public function maxIntoDay(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $old = db_config('max_into_day_'.session('shop_code'));
            $new = db_config('max_into_day_'.session('shop_code'),$data['max_into_day'] ? $data['max_into_day'] : null);
            if($new){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'最长邀约进店时间设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'最长邀约进店时间设定失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    /**
     * @cc 分配后客资状态时限
     * */
    public function intoValidDay(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $old = db_config('into_valid_day');
            $new = db_config('into_valid_day',$data['into_valid_day'] ? $data['into_valid_day'] : null);
            if($new){
                action_log($data,[$old],0,session('staff_id'),session('staff_name'));
                return array('code'=>200,'msg'=>'邀约进店有效时间设定成功','data'=>'');
            }else{
                return array('code'=>100,'msg'=>'邀约进店有效时间设定失败','data'=>'');
            }
        }else{
            return array('code'=>300,'msg'=>'未找到店面简码，不能设置','data'=>'');
        }
    }
    //客资渠道设定
    public function channelNnqq()
    {
        // 南宁qqbaby  2021-03-22
        if (!customize('nnqqbaby')) {
            return $this->redirect('/');
        }
        // 权限
        $auth = check_right('menu1512650793');
        if (!$auth) {
            return $this->redirect('/');
        }
        $channel = controller('crm/Setting','lib')->getChannelclass();
        $this->assign('channel',$channel);
        //获取渠道
        $qudao = controller('crm/Setting','lib')->getChannelInfo();
        $this->assign('qudao',$qudao);

        // 省
        $data['type']=1;
        $province=controller("Customer","lib")->address($data);
        $this->assign("province",$province);
        //城市
        $data['type']=2;
        $address=controller("Customer","lib")->address($data);
        $this->assign("address",$address);

        //部门信息
        $department = controller('crm/Setting','lib')->department_list(['shop_code'=>session('shop_code')]);
        foreach ($department as $k => $v) {
            if ($v['id'] == session('department_id')) {
                $department[$k]['selected'] = 1;
                $mc = new \app\common\lib\mcInterface();
                $staffs = $mc->getStaffByDepartment( array('department_id'=>session('department_id'), 'get_main'=>2) );
                $costStaff = [];
                foreach ($staffs as $key => $value) {
                    $costStaff[$key]['id'] = $value['id'];
                    $costStaff[$key]['staffname'] = $value['staffname'];
                    if ($value['id'] == session('staff_id')) {
                        $costStaff[$key]['selected'] =1;
                    }
                }
                $this->assign('cost_staff',$costStaff);
            }
        }
        $this->assign('dep',$department);

        //品牌
        $brand = db('crm_s_brandset')->order('sort asc')->select();
        $this->assign('brand',$brand);

        //来源渠道
        $channels = getChannelJson(session('shop_code'));
        $this->assign("channels", json_encode($channels));

        $mc = new \app\common\lib\mcInterface();
        $staffArr = $mc->getStaffByDepartment( array('department_id'=>session('department_id'), 'get_main'=>2) );
        
        $this->assign('staffArr',$staffArr);

        $edit_channel_cost_date = db_config('edit_channel_cost_'.session('shop_code'));
        $lr_channel_cost_date = db_config('lr_channel_cost_'.session('shop_code'));
        $this->assign('edit_channel_cost_date',$edit_channel_cost_date);
        $this->assign('lr_channel_cost_date',$lr_channel_cost_date);
        return $this->fetch();
    }
    public function addQDTypeQqbb($value='')
    {
        // 南宁qqbaby  2021-03-22
        if (!customize('nnqqbaby')) {
            return $this->redirect('/');
        }
        // 权限
        $auth = check_right('menu1512650793');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input('post.');
        if (!$data['province_id'] && $data['city_id']) {
            $province = db('crm_s_shop_address')->alias('a')
                ->join('crm_s_shop_address b', 'a.pid=b.id','left')
                ->where('a.id',$data['city_id'])->where('b.type',1)
                ->field('b.id,b.name')->find();
            if ($province) {
                $data['province_id']  = $province['id'];
                $data['province_name']= $province['name'];
            }
            $data['city_id']   = $data['city_id'];
            $data['city_name'] = $data['city_name'];
        }
        
        return controller('crm/Setting','lib')->addQDTypeQqbb($data);
    }
    //渠道充值
    public function channelRecharge()
    {
        // 南宁qqbaby  2021-03-22
        if (!customize('nnqqbaby')) {
            return $this->redirect('/');
        }
        // 权限
        $auth = check_right('menu1619506707');
        if (!$auth) {
            return $this->redirect('/');
        }
        $channel = controller('crm/Setting','lib')->getChannelclass();
        $this->assign('channel',$channel);
        //获取渠道
        $qudao = controller('crm/Setting','lib')->getChannelInfo();
        $this->assign('qudao',$qudao);

        // 省
        $data['type']=1;
        $province=controller("Customer","lib")->address($data);
        $this->assign("province",$province);
        //城市
        $data['type']=2;
        $address=controller("Customer","lib")->address($data);
        $this->assign("address",$address);

        //来源渠道
        $channels = getChannelJson(session('shop_code'));
        $this->assign("channels", json_encode($channels));

        $mc = new \app\common\lib\mcInterface();
        $staffArr = $mc->getStaffByDepartment( array('department_id'=>session('department_id'), 'get_main'=>2) );
        
        $this->assign('staffArr',$staffArr);

        $edit_channel_cost_date = db_config('edit_channel_cost_'.session('shop_code'));
        $lr_channel_cost_date = db_config('lr_channel_cost_'.session('shop_code'));
        $this->assign('edit_channel_cost_date',$edit_channel_cost_date);
        $this->assign('lr_channel_cost_date',$lr_channel_cost_date);
        return $this->fetch();
    }
    //渠道充值列表
    public function getchannelrechargeJSON()
    {
        $channelclass = input('request.');

        if (customize('nnqqbaby')) {
            $res = controller('crm/Setting','lib')->getchannelrechargeQqbbJSON($channelclass);
            return json($res);
        }
    }
    public function addChannelRecharge()
    {

        if (!customize('nnqqbaby')) {
            return $this->redirect('/');
        }
        $data = input('post.');
        if (!$data['province_id'] && $data['city_id']) {
            $province = db('crm_s_shop_address')->alias('a')
                ->join('crm_s_shop_address b', 'a.pid=b.id','left')
                ->where('a.id',$data['city_id'])->where('b.type',1)
                ->field('b.id,b.name')->find();
            if ($province) {
                $data['province_id']  = $province['id'];
                $data['province_name']= $province['name'];
            }
            $data['city_id']   = $data['city_id'];
            $data['city_name'] = $data['city_name'];
        }
        
        return controller('crm/Setting','lib')->addChannelRecharge($data);
    }

    // 删除渠道充值
    function  delChannelRecharge(){
        // 权限
        $auth = check_right('menu1619506707');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->delChannelRecharge(input('post.id'));
    }
    // -------------------------- 南宁定制 end ------------------------- //


    // -------------------------- 威海斑马 start ------------------------- //
    //斑马大屏 取值店设定
    public function banmaDapingShop(){
        $params = input('');
        $ckey = 'banmaDapingShop';
        // print_r($params);
        $msg = 1;
        $data = [];
        foreach ($params['bm_name'] as $key => $value) {
            if (!$value) {
                $msg = 2;
            }
            $data[$key]['name'] = $value;
        }
        foreach (array_count_values($params['bm_name']) as $key => $value) {
            if ($value > 1) {
                $msg = 3;
            }
        }
        foreach ($params['bm_sd_shop_d'] as $key => $value) {
            if (!$value) {
                $msg = 2;
            }
            $data[$key]['shop_code_d'] = $value;
        }
        foreach ($params['bm_sd_shop_s'] as $key => $value) {
            if (!$value) {
                $msg = 2;
            }
            $data[$key]['shop_code_s'] = $value;
        }
        if ($msg == 2) {
            return array('code'=>100,'msg'=>'请填写名称及选择店面');
        }
        if ($msg == 3) {
            return array('code'=>101,'msg'=>'名称不能相同！请重新填写。');
        }
        $data = json_encode($data);

        db()->startTrans();
        try{
            $res = db('crm_c_sysconfig')->where('ckey','banmaDapingShop')->find();
            if($res){
                $res = db('crm_c_sysconfig')->where('ckey',$ckey)->update(['cvalue'=>$data]);
            }else{
                $res = db('crm_c_sysconfig')->insert(['ckey'=>$ckey,'cvalue'=>$data]);
            }
            $log = '【'.session('staff_name').'】 于'.date("Y-m-d H:i:s").' 修改【'.$ckey.'】的值,设置为【'.$data.'】;';
            db()->commit();
            action_log($log,[]);
            return array('code'=>200,'msg'=>'设置成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'设置失败，请重试','data'=>$e->getMessage());
        }
    }
    // -------------------------- 威海斑马 end ------------------------- //

}
