<?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');
        //员工信息
        $staff_info = getStaffInfoById($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'=>'一销均价'
                ],
            );
        }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'=>'一销均价'
                ],
            );
        }
        // if(file_exists(ROOT_PATH.DS.'runtime'.DS.'Suxuan.php')){
        //     //判断授权码是否是 阳光贝贝
        //     $filename = ROOT_PATH.DS.'runtime'.DS.'Suxuan.php';
        //     $sq_arr = include($filename);
        //     if ($sq_arr['product_id'] == config('product_id')) {
                $kpi[count($kpi)] = array('id'=> 'erpResultsTheForehead','name'=>'ERP业绩额');
                $kpi[count($kpi)] = array('id'=> 'erpRevenuePosition','name'=>'ERP收入额');
                $kpi[count($kpi)] = array('id'=> 'storefrontAccomplish','name'=>'店面成交');
                $kpi[count($kpi)] = array('id'=> 'LoveBabyAccomplish','name'=>'爱婴成交');
                $kpi[count($kpi)] = array('id'=> 'photogrammetry','name'=>'摄影量');
                $kpi[count($kpi)] = array('id'=> 'serviceTheGuest','name'=>'客服入客');
                $kpi[count($kpi)] = array('id'=> 'LoveBabyRecharge','name'=>'爱婴充值');
                $kpi[count($kpi)] = array('id'=> 'AfterTheSamplePin','name'=>'样后实销');
                $kpi[count($kpi)] = array('id'=> 'TheSolidPinAverage','name'=>'实销均价');
                $kpi[count($kpi)] = array('id'=> 'StoreTopUp','name'=>'店面充值');
        //     }
        // }
        // $kpi = controller('crm/Setting','lib')->getKPIList();
        // */
        $kpi = config('kpi');
        $this->assign('kpi',$kpi);
        $this->assign('staff_info',$staff_info);
        $this->assign('month',intval(date('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'=>'一销均价'
                ],
            );
        }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'=>'一销均价'
                ],
            );
        }
        // if(file_exists(ROOT_PATH.DS.'runtime'.DS.'Suxuan.php')){
        //     //判断授权码是否是 阳光贝贝
        //     $filename = ROOT_PATH.DS.'runtime'.DS.'Suxuan.php';
        //     $sq_arr = include($filename);
        //     if ($sq_arr['product_id'] == config('product_id')) {
                // $kpi[count($kpi)] = array('id'=> 'erpResultsTheForehead','name'=>'ERP业绩额');
                // $kpi[count($kpi)] = array('id'=> 'erpRevenuePosition','name'=>'ERP收入额');
                // $kpi[count($kpi)] = array('id'=> 'storefrontAccomplish','name'=>'店面成交');
                // $kpi[count($kpi)] = array('id'=> 'LoveBabyAccomplish','name'=>'爱婴成交');
                // $kpi[count($kpi)] = array('id'=> 'photogrammetry','name'=>'摄影量');
                // $kpi[count($kpi)] = array('id'=> 'serviceTheGuest','name'=>'客服入客');
                // $kpi[count($kpi)] = array('id'=> 'LoveBabyRecharge','name'=>'爱婴充值');
                // $kpi[count($kpi)] = array('id'=> 'AfterTheSamplePin','name'=>'样后实销');
                // $kpi[count($kpi)] = array('id'=> 'TheSolidPinAverage','name'=>'实销均价');
                // $kpi[count($kpi)] = array('id'=> 'StoreTopUp','name'=>'店面充值');
        //     }
        // }
        // */
        $kpi = config('kpi');
        $this->assign('kpi',$kpi);
        $id = input('param.id');
        $info = db('SKpiStaffgoal')->where('id',$id)->find();
        $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);
            $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 goalNameSet(){
        return $this->fetch();
    }
    /**
     * @cc 添加目标名称
     * */
    public function addGoalName(){
        $param = input();
        $data['goal_name'] = trim($param['goal_name']);
        $res = db('s_goal_name')->where('goal_name',$data['goal_name'])->value('id');
        if($res){
            return array('code'=>100,'msg'=>'已存在此目标名称，不能添加');
        }
        $data['create_time'] = date('Y-m-d H:i:s');
        db()->startTrans();
        try{
            db('s_goal_name')->insert($data);
            $time = date('Y-m-d H:i:s');
            $log = '【'.session('staff_name').'】 于'.$time.' 添加目标名称由【'.$data['goal_name'].'】';
            action_log($log,[]);
            db()->commit();
            return array('code'=>200,'msg'=>'添加成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>101,'msg'=>'添加失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 修改目标名称
     * */
    public function editGoalName(){
        $param = input();
        $data['goal_name'] = trim($param['goal_name']);

        // $goal_name = db('s_goal_name')->where('id',$param['id'])->value('goal_name');
        // $res = db('s_goal')->where('goal_name',$goal_name)->value('id');
        // if($res){
        //     return array('code'=>100,'msg'=>'已设置此名称的目标，不能修改');
        // }
        // $res = db('s_goal_name')->where('id','<>',$param['id'])->where('goal_name',$data['goal_name'])->value('id');
        // if($res){
        //     return array('code'=>100,'msg'=>'已存在此目标名称，不能修改');
        // }
        db()->startTrans();
        try{
            db('s_goal_name')->where('id',$param['id'])->update($data);
            $time = date('Y-m-d H:i:s');
            $log = '【'.session('staff_name').'】 于'.$time.' 修改目标名称由【'.$goal_name.'】改为【'.$data['goal_name'].'】';
            action_log($log,[]);
            db()->commit();
            return array('code'=>200,'msg'=>'修改成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>101,'msg'=>'修改失败','data'=>$e->getMessage());
        }
    }
    /**
     * @cc 删除目标名称
     * */
    public function delGoalName(){
        $goal_name = input('param.goal_name');
        // $res = db('s_goal')->where('goal_name',$goal_name)->value('id');
        // if($res){
        //     return array('code'=>100,'msg'=>'已设置此名称的目标，不能删除');
        // }
        db()->startTrans();
        try{
            db('s_goal_name')->where('goal_name',$goal_name)->delete();
            $time = date('Y-m-d H:i:s');
            $log = '【'.session('staff_name').'】 于'.$time.' 删除目标名称【'.$goal_name.'】';
            action_log($log,[]);
            db()->commit();
            return array('code'=>200,'msg'=>'删除成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>101,'msg'=>'删除失败','data'=>$e->getMessage());
        }
    }
    public function goalNameJSON(){
        $data = input();
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('s_goal_name')->order('create_time desc')->select();
        $count = db('s_goal_name')->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return json($result);
    }

    // 大屏目标设定
    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('brand',$brand);
        $this->assign('shopList',$shopList);
        $merge = config('big_screen_shop_merge');
        if($merge){
            $this->assign('merge',$merge);
        }
        $goal = db('crm_s_goal_name')->select();
        $this->assign('goal',$goal);
        return $this->fetch();
    }
    /**
     * @cc 新增月目标
     * */
    public function addMonthGoal(){
        $param = input();
        $time = date('Y-m-d H:i:s');
        $year = explode('-',$param['month']);

        $id = db('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('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());
        }
    }

    /**
     * @cc 列修改月目标
     * */
    public function columnEditMonthGoal(){
        $param = input();
        $info = db('s_goal')->where('id',$param['id'])->find();

        try{
            db('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());
        }
    }
    /**
     * @cc 修改月目标
     * */
    public function editMonthGoal(){
        $param = input();
        $year = explode('-',$param['month']);
        $info = db('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('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());
        }
    }
    /**
     * @cc 删除月目标
     * */
    public function delMonthGoal(){
        $id = input('id');
        $time = date('Y-m-d H:i:s');
        $info = db('s_goal')->where('id',(int)$id)->find();
        db()->startTrans();
        try{
            // $count = db('s_goal')->where('method',$info['method'])->where('year',$info['year'])->where('month',$info['month'])->where('goal_name',$info['goal_name'])->where('key',$info['key'])->where('name',$info['name'])->delete();
            $res = db('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());
        }
    }
    /**
     * @cc 月目标
     * */
    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('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('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);
    }
    // --------------------------------  目标相关  ---------------------------- //

    // -------------------------------- 小组设定相关 start --------------------------------//
    /**
     * 小组设定页面
     * @param  
     * @return page
     * @author lilong<lilong@suxuantech.cn>
     */
    public function groupSet(){
        // 权限
        $auth = check_right('menu1512028478');
        if (!$auth) {
            return $this->redirect('/');
        }
        // //小组信息
        // $group_info = db('c_staff_group')->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();
    }
    /**
     * 小组设定页面展示数据
     * @param  
     * @return json
     * @author lilong<lilong@suxuantech.cn>
     */
    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);
    }

    /**
     * 新增/编辑小组 页面
     * @param  id   编辑小组时的组ID
     * @return page
     * @author lilong<lilong@suxuantech.cn>
     */
    public function editGroup(){
        // /*
        $data = input();
        $gId = (int)$data['id'];
        if ($gId) {
            // 小组信息
            $group_info = db('CStaffGroup')->where('id',$gId)->find();
            $this->assign('group_info',$group_info);
            // 小组人员列表
            $inGroupStaffInfo = controller('crm/Setting','lib')->getInGroupStaffInfo($gId);
            $this->assign('inGroupStaffInfo',$inGroupStaffInfo);
            // var_dump($inGroupStaffInfo);die;
            // 部门人员列表 20200312
            $departStaffList = $this->getDepartmentStaffs($group_info['department_id']);
            // var_dump($departStaffList);die;
            foreach ($inGroupStaffInfo as $key => $value) {
                if ($value['is_admin'] == 1) {
                    $temp['id'] = $value['id'];
                    $temp['staffname'] = $value['staffname'];
                    $temp['staffnumber'] = $value['staffnumber'];
                    $temp['is_admin'] = 1;
                    array_push($departStaffList, $temp);
                }
            }
            $this->assign('departStaffList',$departStaffList);
            // 所有管理员，不包含组长
            $res = sx_call('5a18e3fa516a1',['staff_id'=>$group_info['admin']]);
            if($res['code'] == 200){
                $this->assign('admin',$res['data']);
            }
        }
        // 部门列表 无小组的人员列表 所有人列表
        $department = controller('crm/Setting','lib')->department_list(['shop_code'=>session('shop_code')]);
        $this->assign('department',$department);
        // 无小组的人员列表
        $no_group_staff = controller('crm/Setting','lib')->getNoGroupStaff(array('shop_code'=>session('shop_code')));
        $this->assign('no_group_staff',$no_group_staff['data']);
        //所有人员，包含兼职
        $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>session('shop_code')]);
        $this->assign('staff',$staff);
        // */
        return $this->fetch();
    }
    /**
     * 新增/编辑小组 实现
     * @param  id   编辑小组时的组ID
     * @return page
     * @author lilong<lilong@suxuantech.cn>
     */
    public function editGroupAction(){
        $data = input();
        // 权限
        $auth = check_right('menu1512028478');
        if (!$auth) {
            $js = array('code'=>600,'msg'=>'您没权限操作');
            return json($js);
        }

        $param['id'] = (int)$data['id'];
        // 判断小组名称是否填写
        if (!trim($data['group_name'])) {
            $retrun = array('code'=>100,'msg'=>'请填写小组名称');
            return json($retrun);
        }else{
            $param['group_name'] = trim($data['group_name']);
        }
        // 判断是否选择小组所属部门
        if (!(int)$data['department_id'] || !trim($data['department_name'])) {
            $retrun = array('code'=>101,'msg'=>'请选择小组所属部门');
            return json($retrun);
        }else{
            $param['department_id'] = (int)$data['department_id'];
            $param['department_name'] = trim($data['department_name']);
        }
        // 判断是否选择小组组长
        if (!(int)$data['create_staff_id'] || !trim($data['create_staff_name'])) {
            $retrun = array('code'=>102,'msg'=>'请选择小组组长');
            return json($retrun);
        }else{
            $param['create_staff_id'] = (int)$data['create_staff_id'];
            $param['create_staff_name'] = trim($data['create_staff_name']);
        }
        
        $param['member'] = trim($data['member']);
        $param['admin'] = trim($data['admin']);
        $res = controller('crm/Setting','lib')->addGroup($param);
        return $res;
    }
    //岗位下的人员
    public function getPositionStaffs(){
        $data = input();
        return controller('crm/Setting','lib')->positionStaffs($data);
    }
    // 根据部门id获取部门下的员工 如果有小组，unset掉
    public function getDepartmentStaffs($department_id){
        $mc = new mcInterface();
        $arrDep = array('department_id'=>$department_id,'get_leave'=>2,'get_main'=>2);
        $departStaffList = $mc->getStaffByDepartp($arrDep);
        //所有人员
        $staffs = $departStaffList;
        //部门下的小组
        $groups = db('c_staff_group')->where('department_id',$department_id)->where('shop_code',session('shop_code'))->field('id')->select();
        $ids = array_column($groups,'id');
        //小组成员
        $groupStaffs = db('c_staff_group_relation')->where('group_id','in',$ids)->column('staff_id,group_id');
        $groupStaffs = array_keys($groupStaffs);
        //去掉已有小组的人
        $staffs = [];
        foreach($departStaffList as $k=>$v){
            if(!in_array($v['id'],$groupStaffs)){
                $temp['id'] = $v['id'];
                $temp['staffname'] = $v['staffname'];
                $temp['staffnumber'] = $v['staffnumber'];
                array_push($staffs, $temp);
            }
        }
        // var_dump($staffs);die;
        return array_merge($staffs,[]);
    }
    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));
        if($res['code'] == 200){
            return $res['data'];
        }else{
            return [];
        }
    }
    /**
     * @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'));
    }
    // -------------------------------- 小组设定相关 end --------------------------------//

    // -------------------------------- 客资自动分配规则设定 start --------------------------------//
    //客资分配设定
    public function fpSet(){
        // 权限
        $auth = check_right('menu1512009199');
        if (!$auth) {
            return $this->redirect('/');
        }
        //获取员工小组列表
        $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();
    }
    // 分配设定页面 20200515
    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']);
        }
        // var_dump($res);die;
        $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);

        // 选中的归属店下的所有组 20200516
        if ($res['belong_shop_code'] && $res['staff_type']=='group_name') {
            $groups = controller('crm/Setting',"lib")->getGroupList( array('shop_code'=>$res['belong_shop_code']) );
            $selectGroups = json_decode($res['staff_value'],true);
            $this->assign('selectGroups',$selectGroups);
            $gids = '';
            foreach ($groups as $key => $value) {
                foreach ($selectGroups as $k => $v) {
                    if ($value['id']==$v['group_id']) {
                        $groups[$key]['select'] = '1';
                        $gids .= $value['id'].',';
                        continue;
                    }
                }
            }
            $this->assign('groups',$groups);
            $gids = trim($gids,',');
            $this->assign('gids',$gids);
        }
        if ($res['fp_staffs']) {
            $fpStaffs = json_decode($res['fp_staffs'],true);
            $this->assign('fpStaffs',$fpStaffs);
            $this->assign('renyuan_show','set_group1');
        }else{
            $this->assign('renyuan_show','set_group2');
        }
        // var_dump($groups);
        // die;
        $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('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':
                    $idArr = json_decode($res['staff_value'], true);
                    $ids = [];
                    foreach ($idArr as $key => $value) {
                        $ids[] = $value['group_id'];
                    }
                    // $res['group_id'] = $ids;
                    // $this->assign('allgids',json_encode($ids));
                    break;
                case 'staff_name':
                    $res['staff_value'] = json_decode($res['staff_value'],true);
                    break;
                default:
                    break;
            }
        }
        $this->assign('allgids',$ids ? json_encode($ids) : []);
        // $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);
    }
    //部门列表
    public function getdepartment_name(){
        $param = input('post.');
        $area = controller('crm/Setting','lib')->getdepartment($param);
        return json_encode($area['data']);
    }
    //岗位列表
    public function getposition_name(){
        $param = input('post.');
        $area = controller('crm/Setting','lib')->getposition($param);
        return json_encode($area['data']);
    }
    //小组列表
    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]);
        return json_encode($all);
    }
    //员工搜索
    public function searchStaff(){
        $key_words = input('param.key_words');
        $data = array(
            'key_words'=>$key_words,
            'shop_code'=>session('shop_code')
        );
        $url = '5aec138a7bae9';
        $data['get_leave'] = 2;
        $info = sx_call($url,$data);
        if($info['code'] == 200){
            return array('code'=>200,'data'=>$info['data']);
        }else{
            return array('code'=>100,'msg'=>'未查询到数据','data'=>'');
        }
    }
    public function searchStaffGroup(){
        $key_words = input('param.key_words');
        $data = array(
            'key_words'=>$key_words,
            'shop_code'=>session('shop_code')
        );
        $url = '5aec138a7bae9';
        $data['get_leave'] = 2;
        $info = sx_call($url,$data);
        if($info['code'] == 200){
            $data = $info['data'];
            $ids = array_column($data,'id');
            $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;
    }
    // 根据小组ID获取组员
    public function getGroupStaff(){
        $param = input();
        $group_ids = $param['group_id'];
        $gids = '';
        foreach ($group_ids as $key => $value) {
            $gids .= $value.',';
        }
        $gids = trim($gids,',');
        $staffs= controller("crm/Setting","lib")->getGroupStaff($gids);

        return $staffs;
    }
    // -------------------------------- 客资自动分配规则设定 end --------------------------------//
    //客资提醒设定
    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('SReminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','next_before_minute')->find();
        $this->assign('next_before_minute',$next_before_minute);
        $yyjd_before_minute = db('SReminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','yyjd_before_minute')->find();
        $this->assign('yyjd_before_minute',$yyjd_before_minute);
        $yyjd_after_minute = db('SReminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','yyjd_after_minute')->find();
        $this->assign('yyjd_after_minute',$yyjd_after_minute);
        //登录提醒
        $login = db('SReminditemset')->where('brandclass_id',session('brandclass_id'))->where('id','login')->find();
        if(!empty($login)){
            $login['send_method'] = explode(',',$login['send_method']);
        }
        //标记有效提醒
        $valid = db('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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('SReminditemset')->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']);
        }
        $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;
    }
    /**
     * @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'];
                $input_cost = $input['cost'];
                $channelInfo = db('s_channel')->where('id',$channel_id)->where('FIND_IN_SET("'.session('shop_code').'",share_shops)')->find();
                
                if(strtotime($cost_date) >= strtotime($channelInfo['rebates_start_time']) && strtotime($cost_date) <= strtotime($channelInfo['rebates_end_time']) && $channelInfo['rebates'] > 0){
                    // $cost = sprintf("%.4f",$cost*((100-$channelInfo['rebates'])/100));
                    $input_cost = $cost - sprintf("%.4f",$input_cost*($channelInfo['rebates']/100));
                }

                $res = db('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,
                            'input_cost'=>$input_cost
                        );
                        $update = array(
                            'cost_avg'=>$cost,
                            'cost_time'=>$cost_date
                        );
                        //修改花费时间  默认7天
                        $a = db_config('accounting_channel_cost_'.session('shop_code'));
                        // $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('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('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'));
                        // $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'=>$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'],
                            'input_cost'=>$input_cost
                        );
                        $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('s_channel_cost')->insert($ins);

                        db('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')));
                }
                $data = [];
                $arr = [];
                $total = 0;

                if(!empty($channel_name)){
                    $channelList = db('s_channel')->where('FIND_IN_SET("'.session('shop_code').'",share_shops)')->order('order_sort asc')->where('channel_name','in',$channel_name)->select();
                }else{
                    $channelList = db('s_channel')->where('FIND_IN_SET("'.session('shop_code').'",share_shops)')->order('order_sort asc')->select();
                }

                // $channelList = controller('crm/Customer','lib')->getChannel();
                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'])) :'';
                }

                $arr['channel_name_show'] = '总计';
                if(!empty($channel_name)){
                    $res = db('SChannelCost')->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('SChannelCost')->where('shop_code',session('shop_code'))->where($where)->where('cost_date','between',[$start,$end])->where($sql)->order('cost_date desc')->select();
                }
                // var_dump($data);die;
                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'];
                        }
                        $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']]['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;
                }
                // die;
                $day = 1;
                $endDay = intval(substr($end, 8,2));
                if($is_rebates == 1){
                    //纵向总计
                    foreach ($data as $key => $value) {
                        $data[$key]['total'] = $value['total'].'/'.$value['input_total'];
                    }
                    $arrArr = [];
                    $arrArr['channel_name_show'] = '总计';
                    foreach($arr['cost'] as $k2=>$v2){
                        $arrArr['cost_'.$k2] = $v2.'/'.$arr['input_cost'][$k2];
                    }
                    $arrArr['total'] = $arr['total'].'/'.$arr['input_cost_total'];
                    $data[] = $arrArr;
                }else{
                    $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('/');
        }

        //客资分区
        $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');
        // 长春摩西
        // if(date('m') > 5){
        //     $ix = date('m');
        // }else{
        //     $ix = 5;
        // }
        // for ($i=0; $i < $ix; $i++) {
        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)){
        if($method == 'belong'){
            $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('SChannelCost')->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('SChannelCost')->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('s_channel')->where('FIND_IN_SET("'.session('shop_code').'",share_shops)')->where('order_sort')->where('channel_name','in',$channel_name)->select();
        }else{
            $channelList = db('s_channel')->where('FIND_IN_SET("'.session('shop_code').'",share_shops)')->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('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('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('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('s_channel_cost')->insert($ins);

                        db('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('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 qdType()
    {
        // 权限
        $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);
        //渠道
        $ch = controller('crm/Customer','lib')->getChannel();
        $this->assign('ch',$ch);
        $data['type']=1;
        $address=controller("Customer","lib")->address($data);
        $this->assign("address",$address);
        //客资分区
        $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);
        $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 searchCity(){
        $data = input('post.');
        $res = controller('crm/Customer','lib')->address($data);
        return $res;
    }
    //渠道返点设定
    public function qdReturn()
    {
        // 权限
        $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.'));
        if ($res['code']==200) {
            // 如果已经设定自动分配提醒
            $is_set = db('s_reminditemset')->where('id','auto')->where('brandclass_id',session('brandclass_id'))->count();
            if ($is_set) {
                return $res;
            }else{
                $remindData['id'] = 'auto';
                $remindData['remind_type']  = '自动分配提醒';
                $remindData['brandclass_id']= session('brandclass_id');
                $remindData['brandclass']   = session('brandclass');
                $remindData['send_method']  = 'tan';
                $remindData['send_receive'] = 'sales';
                $remindRes = db('s_reminditemset')->insert($remindData);
                if ($remindRes===false) {
                    return array('code' => 201, 'msg'=>'操作成功，自动设定提醒失败，请手动设定');
                }
                return $res;
            }
        }
        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.');
        $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('/');
        }
        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);
        $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('/');
        }
        $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('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('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('s_position_menu')->where('position_code','in',$positionArr)->delete();
                db('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');
        // $auth = session('crm_auth');
        $menu = include(APP_PATH.'menu.php');
        $menuCustomize = include(APP_PATH.'menu_customize.php');
        $auth = getAuthMenu($menu,'auth',$menuCustomize);
            
        $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('crm/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('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('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');
        $this->assign('res',$res);
        $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 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('menu1514183289');
        if (!$auth) {
            return $this->redirect('/');
        }
        return $this->fetch();
    }
    /**
     * @cc 增加呼叫前缀
     * */
    public function addCallPrefix(){
        // 权限
        $auth = check_right('menu1514183289');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->addCallPrefix(input('post.'));
    }
    /**
     * @cc 编辑呼叫前缀
     * */
    public function editCallPrefix(){
        // 权限
        $auth = check_right('menu1514183289');
        if (!$auth) {
            return $this->redirect('/');
        }
        return controller('crm/Setting','lib')->editCallPrefix(input('post.'));
    }
    /**
     * @cc 删除呼叫前缀
     * */
    public function delCallPrefix(){
        // 权限
        $auth = check_right('menu1514183289');
        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')->delCallPrefix(input('post.'));
    }
    public function getCallCenterToJSON(){
        $res = controller('crm/Setting','lib')->getCallCenterToJSON(input('param.name'));
        return json($res);
    }
    //首页岗位显示设定
    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('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('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')]);
        // var_dump($shops);die;
        $this->assign('shops',$shops);
        return $this->fetch();
    }
    /**
     * @cc 查询渠道分享
     * */
    public function getShareShops(){
        $data = input();
        $shops = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id')]);
        // var_dump($shops);die;
        $shareShops = db('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 addChannel(){
        // 权限
        $auth = check_right('menu1516949559');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->addChannel(input('post.'));
        return $res;
    }
    /**
     * @cc 修改渠道名称
     * */
    public function editchannel(){
        // 权限
        $auth = check_right('menu1516949559');
        if (!$auth) {
            return $this->redirect('/');
        }
        $res = controller('crm/Setting','lib')->editchannel(input('post.'));
        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(){
        $res = controller('crm/Setting','lib')->getChannelToJSON(input('param.'));
        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'));
        return ($res);
    }
    public function province(){
        // 权限
        $auth = check_right('menu1517560908');
        if (!$auth) {
            return $this->redirect('/');
        }
        return $this->fetch();
    }
    public function getMyProvince(){
        //当前店面设定的省市区
        $info = db('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('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('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('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);
            if ($res['code'] == 200) {
                $staffs = $res['data'];
            }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('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('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('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('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('s_swapset')->where('id', $swap_id)->value('swap_number');
        $sNumbers = db('c_swap_customer')
            ->where('swap_number',$swap_number)
            // ->where('sales_staff_id', $staff_id)
            ->column('customer_number');

        // 插入到客资交换表中的数据
        $inData = [];
        // 是否添加过客资  如果添加过客资，需要排重
        if ($sNumbers) {
            $cNumbers = db('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('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('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('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('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('c_swap_customer')->insertAll($inData);

            // 更新爆破设定表
            $swapData['status']=2;
            $swapData['update_time'] = $day;
            $res = db('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('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) {
            $returnData = array('code'=>100,'msg'=>'没有该权限，请联系管理员！');
            return $returnData;
            exit;
        }

        $id = (int)input('get.id');
        $this->assign('swap_id', $id);
        $swapInfo = db('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;
        }

        // 查询所有参与爆破的客资
        $num = db('c_swap_customer')
            ->where('swap_number', $swapInfo['swap_number'])
            ->count();
        if ($num) {
            $this->assign('num', $num);
        }else{
            $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('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('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('c_customerinfo')->alias('c')
            ->join('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('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('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('c_customerinfo')->alias('c')
            ->join('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('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('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('c_swap_customer')->where('sales_staff_id', $value)->count('id');
            // 预约进店时间在活动期间的
            $returnData[$key]['yjd_number'] = db('c_swap_customer')->where('sales_staff_id', $value)->where('yjd_day', 'between time', [$start, $end])->count('id');
            // 活动外进店 （实际进店 进店进客）
            $returnData[$key]['cyjd_number'] = db('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('c_swap_customer')->where('sales_staff_id', $value)->where('is_intostore', 2)->count('id');
            // 活动内成交
            $returnData[$key]['success_num']= db('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('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;
            }
        }
        // dump($info);die;
        $this->assign('info',$info);
        return $this->fetch();
    }
    public function statisticsLists(){
        $info = db('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(){
        return controller('crm/Setting','lib')->statistics_list_data(input());
    }
    //店面返点标准设定
    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('s_shop_return_rule')->where('shop_code',session('shop_code'))->where('brandclass_id',session('brandclass_id'))->limit($limit)->page($page)->select();
        $result['count'] = db('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开关
            $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);//当前城市
            //颜色
            $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);
            $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);
            $urgent_color = db_config('urgent_color');
            $this->assign('urgent_color',$urgent_color);
            //事业部下的网销店
            $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);
            // 是否发送预约进店短信
            $yjd_dx = db_config('yjd_dx_'.session('brandclass_id'));
            $this->assign('yjd_dx',$yjd_dx);
            // 订单客资是否允许分配：
            $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('l_yjd_ctrl')->where('shop_code',session('shop_code'))->field('time_area')->group('time_area')->select();
            $yjd_time_area=db('l_yjd_ctrl')->where('shop_code',session('shop_code'))->field('time_area')->order('id')->group('time_area')->select();
            // var_dump($yjd_time_area);die;
            $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);
            //客资重复审核配置
            $examine= db_config('cus_examine_'.session('shop_code'));
            $this->assign('examine',$examine);
            // 客资录入类型
            $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;
            //短信模板
            $model = $mc->getSMSModel();
            $this->assign('model',$model);
            //预约短信模板
            $yyModel  = db_config('yy_sms_model_'.session('shop_code'));
            $this->assign('yyModel',$yyModel);

            $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);
            //客资过期录入是否提示设定
            $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);
            //客资过期判定规则
            $rule = db_config('valid_date_rule');
            $this->assign('rule',$rule);
            $hidden = db_config('lr_hidden_'.session('brandclass_id'));
            $hidden = explode(',',$hidden);
            $this->assign('lrHidden',$hidden);
            //转介绍次数
            $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);
            //花费配置
            //录入
            $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('SCallCenter')->select();
            $this->assign('call',$call);
            $call_user =  db('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')));
            //客资不判重配置--哪些状的客资不作判断范围内，默认情况是已订单和已删除客资，在此基础上再增加如无效，不再追踪等
            //传为逗号分隔，如：unvalid,lossed
            $unrepeatStatus = explode(',', db_config('unrepeat_status'));
            $this->assign('unrepeat_status',$unrepeatStatus);
            //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);

            //网付订单意向店面设定
            $yyjd_shop = db_config('yyjd_shop');
            $this->assign('yyjd_shop',$yyjd_shop);
            //网付订单意向店面设定
            $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);
            // 手机号 正则配置
            $telAddress = controller('crm/Setting','lib')->telAddress();
            $this->assign('telAddress',$telAddress);
            $this->assign('teladdress',grtTelAddressRegular());
            //不同资讯类型的客资，可以重复
            $validDate= db_config('cus_validdate_'.session('shop_code'));
            $this->assign('validDate',$validDate);
            $this->assign('valid_date',session('valid_date'));
            //登录状态
            $login_status = db_config('login_status_'.session('brandclass_id'));
            $this->assign('login_status',$login_status);
            // 客资列表也显示的追踪记录的条数
            $tracking_num = db_config('tracking_num_'.session('brandclass_id'));
            $tracking_num = $tracking_num ? $tracking_num : 3;
            $this->assign('tracking_num',$tracking_num);
            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('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('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('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('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('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 addpc(){
        if(request()->isAjax()){
            $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'],
                'setting_date'=> date('Y-m-d'),
                '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')
            ];
            $res = db('l_pc_setting_log')->where($where)->where('setting_date',date('Y-m-d'))->find();
            try{
                if($res){
                    return array('code'=>101,'msg'=>'当天已有此排程，不能添加','data'=>'');
                }else{
                    db('l_pc_setting_log')->insert($arr);
                }
                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{
            $id = input('param.id');
            $res = db('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 delMorePC(){
        $data = input();
        $old = db('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('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('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('l_pc_setting_log')->insertAll($arr);
                db('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('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('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());
        }
    }
    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('l_pc_setting_log')
            ->where($where)
            ->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('l_pc_setting_log')->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 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 yyjdShopSet(){
        $data = input();
        $old = db_config('yyjd_shop');
        $res = db_config('yyjd_shop',$data['yyjd_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'=>'');
        }
    }
    /**
     * @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'];
            $whereDel['shop_code'] = $data['shop_code'];
            db()->startTrans();
            try{
                db('l_yjd_ctrl')->where($whereDel)
                    ->where('use_day', '>=', $data['startTime'])
                    ->where('use_day', '<=', $data['endTime'])
                    ->delete();
                db('l_yjd_ctrl')->insertAll($inArr);
                // db('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);
            // var_dump($shop);die;
            // 开始结束时间
            $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();
        }
    }
    public function getYjdSet(){
        $params = input('post.');
        $shop_code = $params['shop_code'] ? $params['shop_code'] : session('shop_code');
        $yjdinfo = [];
        $old_data = db_config('add_yjd_ctrl_'.$shop_code);
        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 = $temp;
            unset($old_data,$temp);
        }
        // var_dump($yjdinfo);die;
        return json($yjdinfo);
    }
    /**
     * @ 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('l_yjd_ctrl')->where($where)->find();

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

            db()->startTrans();
            try{
                db('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('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('l_yjd_ctrl')->where('id', $id)->find();
        $res = db('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('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('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('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 login_status(){
        $data = input();
            $old = db_config('login_status_'.session('brandclass_id'));
            $res = db_config('login_status_'.session('brandclass_id'),$data['login_status']);
            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 tracking_num(){
        $data = input();
        $old = db_config('tracking_num_'.session('brandclass_id'));
        $res = db_config('tracking_num_'.session('brandclass_id'),$data['tracking_num']);
        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 yjdDxSet(){
        $data = input();
        $old = db_config('yjd_dx_'.session('brandclass_id'));
        $res = db_config('yjd_dx_'.session('brandclass_id'),$data['yjd_dx']);
        // 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 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-06-23 列表页 搜索点查询按键查所有选项卡的数量：
    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 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 cusValidDateSet(){
        // 权限
        $auth = check_right('menu1522207375');
        if (!$auth) {
            return $this->redirect('/');
        }
        $data = input();
        if(session('shop_code')){
            $validDate = db_config('cus_validdate_'.session('shop_code'));
            $res = db_config('cus_validdate_'.session('shop_code'),$data['cus_validDate']);
            if($res){
                action_log($data,[$validDate],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('/');
        }
        $data = input();
        $call = db_config('call_id');
        $res = db_config('call_id',$data['call_id']);
        if($res){
            action_log($data,[$call],0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'呼叫中心选择成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'呼叫中心选择失败','data'=>'');
        }
    }
    //呼叫中心列表
    public function callManList(){
        //店面下人员
        $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>session('shop_code')]);
        $this->assign('staff',$staff);
        if(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;

        $result['code'] = 0;
        $result['msg'] = '';
        if(check_right('menu1561718791')){
            if($param['user']){
                $result['data'] = db('s_call_man')->where('shop_code',session('shop_code'))->where('user|staff_name','like','%'.trim($param['user']).'%')->limit($limit)->page($page)->select();
                $result['count'] = db('s_call_man')->where('shop_code',session('shop_code'))->where('user|staff_name','like','%'.trim($param['user']).'%')->count();
            }else{
                $result['data'] = db('s_call_man')->where('shop_code',session('shop_code'))->limit($limit)->page($page)->select();
                $result['count'] = db('s_call_man')->where('shop_code',session('shop_code'))->count();
            }
        }else{
            $result['data'] = db('s_call_man')->where('shop_code',session('shop_code'))->where('staff_id',session('staff_id'))->limit($limit)->page($page)->select();
            $result['count'] = db('s_call_man')->where('shop_code',session('shop_code'))->where('staff_id',session('staff_id'))->count();
        }

        return json($result);
    }
    /**
     * @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'];

        $group = db('c_staff_group')->alias('g')
            ->join('c_staff_group_relation r','g.id=r.group_id','left')
            ->where('r.staff_id',$data['staff_id'])
            ->field('g.id,g.group_name')
            ->find();

        $param['group_id'] = $group['id'];
        $param['group_name'] = $group['group_name'];
        if($data['staff_id']){
            $info1 = db('s_call_man')->where('staff_id',$data['staff_id'])->find();
            db()->startTrans();
            try{
                if($info1['staff_id']){
                    db('s_call_man')->where('staff_id',$data['staff_id'])->update($param);
                }else{
                    db('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'=>'');
        }
    }
    /**
     * @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 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 = $data['set'];
        if(session('brandclass_id')){
            if(empty($set)){
                $set = null;
            }
            $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 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 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('s_order_source')->where('shop_code',session('shop_code'))->where('is_delete',1)->limit($limit)->page($page)->select();
        $result['count'] = db('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('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);
        //客资标签
        $cat = cache('label_'.session('brandclass_id'));
        if(empty($cat)){
            $cat = db('s_label_cat')->where('brandclass_id',session('brandclass_id'))->select();
            foreach($cat as $k=>$v){
                $cat[$k]['cat_name'] = $v['cat_name'];
                $cat[$k]['label'] = db('s_label')->where('brandclass_id',session('brandclass_id'))->where('label_cat_id',$v['id'])->select();
                if(empty($cat[$k]['label'])){
                    unset($cat[$k]);
                }
            }
            cache('label_'.session('brandclass_id'),$cat);
        }

        $this->assign('cat',$cat);
        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('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('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('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('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('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('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('s_customer_interface_detail')->where('pid', $id)->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();
        // if($data['color'] == 'FFFFFF'){
        //     $data['color'] = '';
        // }
        $res = db_config($data['color_name'],$data['color']);
        if($res){
            return array('code'=>200,'msg'=>'颜色设定成功','data'=>'');
        }else{
            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(){
        $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('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('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('s_consumptiontype')
            ->where('id',$data['id'])
            ->where('is_delete',2)
            ->where('brandclass_id',session('brandclass_id'))
            ->find();
        //检查重复
        $id = db('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('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('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('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('s_consumptiontype')->where('brandclass_id',session('brandclass_id'))->where('is_delete',2)->page($page)->limit($limit)->select();
        $count = db('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(){
        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('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('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('s_another_cost')->where('id',$id)->update($data);
            db('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('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('s_another_cost')->where('id',$param['id'])->delete();
            db('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 '%".$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('s_another_cost')->where('shop_code',session('shop_code'))->where($where)->page($page)->limit($limit)->order('create_time desc')->select();
        $count = db('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',[]);
        if($info['code'] == 200){
            $this->assign('brandclassInfo',$info['data']);
        }
        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('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('s_sta_setting')->where('shop_code',$key)->update($inc);
//                    echo db()->getLastSql();die;
                }else{
                    db('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('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');
        //部门下的小组
        $groups = db('c_staff_group')->where('department_id',$did)->select();
        return $groups;
    }
    //客资录入设置
    public function cusLrSet(){
        //短信模板
        $model = db('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 = $data['set'] ? trim($data['set'],',') : null;
        if(session('brandclass_id')){
            $lrMust = db_config('lr_must_'.session('brandclass_id'));

            $lrMust = $lrMust ? explode(',',$lrMust) : null;
            $hidden = $set ? explode(',',$set) : null;
            if(empty($lrMust) && empty($hidden)){
                $arr = [];
            }else{
                $arr = array_intersect($lrMust,$hidden);
            }

            if(!empty($arr)){
                return array('code'=>101,'msg'=>'选择字段中含有录入必选项字段,不能设置','data'=>'');
            }

            $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 = $data['set'] ? trim($data['set'],',') : null;
        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'=>'');
                }                
            }
            $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('s_report_form')->where('status',2)->select();
        $this->assign('info',$info);
        //未添加
        $info1 = db('s_report_form')->where('status',1)->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;
                unset($data[$k]['brandclass_id']);
                unset($data[$k]['shop_code']);
                unset($data[$k]['id']);
            }
            db('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('s_report_detail')->insertAll($report);
                //设置添加报表 status=2
                db('s_report_form')->where('id',$id)->update(['status'=>2]);
                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('s_report_form')->where('id',$data['id'])->find();
            $this->assign('info',$info);
            //报表查看权限
            $auth = db('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('s_report_detail')->where('form_id',$data['id'])->select();
            $this->assign('detail',$detail);

            $this->assign('title','添加编辑报表');
            return $this->fetch();
        }
    }

    public function delForm(){
        $data = input();
        $fid = (int)$data['fid'];
        if(!$fid){
            return array('code'=>100,'msg'=>'未获取到报表ID，不能删除','data'=>'');
        }
        $fInfo = db('s_report_form')->where('id',$fid)->find();
        if (!$fInfo) {
            return array('code'=>101,'msg'=>'未获取到报表信息','data'=>db()->getLastSql());
        }
        db()->startTrans();
        try {
            // 将报表设置为未选择
            db('s_report_form')->where('id',$fid)->update(array('status' => 1));
            // 删除报表
            db('s_report_detail')->where('form_id',$fid)->delete();
            // 删除权限
            $menuInfo = db('s_menu')->where('menu_code',$fInfo['code'])->find();
            db('s_menu')->where('menu_code',$fInfo['code'])->delete();
            db()->commit();
            history_log($fInfo,$menuInfo,0,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'删除报表成功','data'=>'');
        } catch (Exception $e) {
            db()->rollback();
            return array('code'=>105,'msg'=>'删除报表失败','data'=>$e->getMessage());
        }
    }
    /*
     * @cc 清空报表
     * */
    function clearForm(){
        $id = input('id');
        if(empty($id)){
            return array('code'=>100,'msg'=>'未获取到报表ID，不能清空','data'=>'');
        }
        db()->startTrans();
        try{
            db('s_report_detail')->where('form_id',$id)->delete();
            db()->commit();
            action_log('清空报表ID为：'.$id.'的配置',[],0);
            return array('code'=>200,'msg'=>'报表清空成功','data'=>'');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>105,'msg'=>'清空报表失败','data'=>$e->getMessage());
        }
    }
    //部门下的岗位
    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(){
        $data = input('unrepeat_status');
        $data = $data?$data:null;
        $res = db_config('unrepeat_status',$data);
        if($res){
            return array('code'=>200,'msg'=>'配置成功','data'=>'');
        }else{
            return array('code'=>100,'msg'=>'配置失败','data'=>'');
        }
    }
    /**
     * @cc 客资录入类型
     * */
    public function customerTypeSet(){
        $data = trim(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('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('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'] = $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');
            db()->startTrans();
            try{
                db('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('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('s_third')->where('id',$params['id'])->find();
        db()->startTrans();
        try{
            db('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('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('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('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('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('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('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('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('s_shop_goal')->where($where)
            ->order('id desc')
            ->page($page)
            ->limit($limit)
            ->select();
        $count = db('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('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('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('s_another_setting')->where('id',intval($data['id']))->find();
        $res = db('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('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('s_another_setting')->where('id',intval($data['id']))->find();
        db()->startTrans();
        try{
            db('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('s_another_setting')->where($where)->where($auth)->order('id desc')->count();
        $result['data'] = db('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('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('s_reminditemset')->insert($data);
            }else{
                db('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(){
        $staff = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('shop_code')]);
        $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('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('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('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('s_label_cat')->where('brandclass_id',session('brandclass_id'))->where('status',2)->where('cat_name',$param['cat_name'])->value('id');
        if($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('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'));
            }
            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('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('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('s_label_cat')->where('status',2)->where('brandclass_id',session('brandclass_id'))->order('id desc')->count();
            $result['data'] = db('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('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('s_label')->where('brandclass_id',session('brandclass_id'))->where('cat_name','like','%'.$param['cat_name'].'%')->where('is_delete',2)->order('id desc')->page($page)->limit($limit)->select();
        }else{
            $result['count'] = db('s_label')->where('is_delete',2)->where('brandclass_id',session('brandclass_id'))->order('id desc')->count();
            $result['data'] = db('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('s_label_cat')->where('id',$id)->update(['status'=>1]);
            action_log('删除名称为：'.input('post.cat_name').'的标签分类','',0,session('staff_id'),session('staff_name'));
            db()->commit();
            $cat = cache('label_'.session('brandclass_id'),NULL);
            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('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 delLabelCat(){
        $id = input('post.id');
        $info = db('s_label')->where('label_cat_id',$id)->where('is_delete',2)->where('brandclass_id',session('brandclass_id'))->select();
        if(!empty($info)){
            return array('code'=>100,'msg'=>'此分类下有标签，暂不能删除！');
        }
        db()->startTrans();
        try{
            db('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 addLabelName(){
        $param = input();
        $id = db('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('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('s_label')->where('brandclass_id',session('brandclass_id'))->where('is_delete',2)->where('label_name',$param['label_name'])->value('id');
        if($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('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'));
            }
            db()->commit();
            return array('code'=>200,'msg'=>'标签名称设置成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>110,'msg'=>'标签名称设置失败','data'=>$e->getMessage());
        }
    }
    /*----------标签设定------end-------------------*/
    /*----------人员登录状态------start-------------------*/
    public function staffStatus(){
        //部门
        $mc = new \app\common\lib\mcInterface();
        $department = $mc->getDepartmentByShopcode(session('shop_code'));
        $this->assign('department',$department);
        //岗位
        $position = $mc->getPosition(['shop_code'=>session('shop_code')]);
        $this->assign('position',$position);
        //人员
        $staff = $mc->getStaffInfo(['shop_code'=>session('shop_code')]);
        $this->assign('staff',$staff);
        return $this->fetch();
    }
    public function staffStatusJSON(){
        $param = input();
        $result['code'] = 0;
        $result['msg'] = '';
        $p = [];
        $p['shop_code'] = session('shop_code');
        if(check_right('menu1512637269')){
            if($param['staff_id']){ //本店权限
                $p['id'] = $param['staff_id'];
            }
        }else{ //本人权限
            $p['id'] = session('staff_id');
        }

        if($param['staff_name']){
            $p['staffname'] = $param['staff_name'];
        }
        if($param['department_id']){
            $p['department_id'] = $param['department_id'];
        }
        if($param['position_code']){
            $p['main_position_code'] = $param['position_code'];
        }
        $mc = new \app\common\lib\mcInterface();
        $staff = $mc->getStaffInfo($p);
        $return = [];
        foreach($staff as $k=>$v){
            $staffInfo = getStaffInfoById($v['id']);
            $return[$k]['id'] = $v['id'];
            $return[$k]['staff_name'] = $v['staffname'];
            $return[$k]['main_position_name'] = $v['main_position_name'] ? $v['main_position_name'] : '';
            $return[$k]['department_name'] = $v['department_name'] ? $v['department_name'] : '';
            $return[$k]['status'] = $staffInfo['status'] ? $staffInfo['status'] : 0;
        }
        $result['count'] = count($staff);
        $result['data'] = $return;
        return(($result)) ;
    }
    /*----------人员登录状态------end-------------------*/
    /*----------预计婚期相关------start-------------------*/
    /**
     * 预计婚期设定页面
     * 
     * @return page
     * @author lilong<lilong@suxuantech.cn>
     */
    public function readyMarrydaySet(){
        $auth = check_right('menu1582510236');
        if (!$auth) {
            return $this->redirect('/');
        }
        return $this->fetch();
    }
    /**
     * 预计婚期设定数据
     * 
     * @return page
     * @author lilong<lilong@suxuantech.cn>
     */
    public function getMerryDayToJSON(){
        $where['brandclass_id'] = session('brandclass_id');
        $where['is_delete'] = 2;
        $return['code'] = 0;
        $return['msg'] = '';
        $returnData = db('s_merry_day_set')->where($where)->select();
        if ($returnData) {
            $return['data'] = $returnData;
            $result['count'] = db('s_merry_day_set')->where($where)->count();
        }else{
            $return['data'] = [];
            $return['count']= 0;
        }
        return ($return);
    }
    /**
     * 新增预计婚期页面
     * 
     * @return page
     * @author lilong<lilong@suxuantech.cn>
     */
    public function addMerryDay(){
        return $this->fetch();
    }
    /**
     * 新增预计婚期实现
     *
     * @param  merry_day
     * 
     * @return page
     * @author lilong<lilong@suxuantech.cn>
     */
    public function addMerryDayAction(){
        $data = input();

        if (!trim($data['ready_marry_day'])) {
            return array('code'=>100,'msg'=>'请输入预计婚期','data'=>$data);
        }
        $where['ready_marry_day'] = trim($data['ready_marry_day']);
        $where['brandclass_id'] = session('brandclass_id');
        $has = db('s_merry_day_set')->where($where)->find();
        if ($has) {
            return array('code'=>101,'msg'=>'存在相同的‘预计婚期’，请确认','data'=>trim($data['ready_marry_day']));
        }

        $inData['ready_marry_day']= trim($data['ready_marry_day']);
        $inData['brandclass_id']  = session('brandclass_id');
        $inData['brandclass']  = session('brandclass');
        $inData['create_time'] = date('Y-m-d H:i:s');

        db()->startTrans();
        try {
            db('s_merry_day_set')->insert($inData);
            action_log('添加预计婚期：'.trim($data['ready_marry_day']),'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'添加成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code'=>101,'msg'=>'添加失败','data'=>$e->getMessage());
        }
    }
    /**
     * 删除预计婚期
     *
     * @param  merry_day
     * 
     * @return page
     * @author lilong<lilong@suxuantech.cn>
     */
    public function delReadyMarryday(){
        $data = input();
        $id = (int)$data['id'];
        if (!$id) {
            return array('code'=>100,'msg'=>'未获取到ID','data'=>$data['id']);
        }
        $where['id'] = $id;
        $where['is_delete'] = 2;
        $has = db('s_merry_day_set')->where($where)->find();
        if (!$has) {
            return array('code'=>102,'msg'=>'未查到到对应数据，请确认','data'=>$data['id']);
        }
        $upData['is_delete']= 1;
        $upData['update_time'] = date('Y-m-d H:i:s');

        db()->startTrans();
        try {
            db('s_merry_day_set')->where('id',$id)->update($upData);
            action_log('删除预计婚期：'.trim($has['ready_marry_day']),'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'删除成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code'=>101,'msg'=>'删除失败','data'=>$e->getMessage());
        }
    }
    /**
     * 编辑预计婚期页面
     *
     * @param  id
     * @param  merry_day
     * 
     * @return page
     * @author lilong<lilong@suxuantech.cn>
     */
    public function editReadyMarryday(){
        $data = input();
        $id = (int)$data['id'];
        
        $where['id'] = $id;
        $where['is_delete'] = 2;
        $info = db('s_merry_day_set')->where($where)->find();
        
        $this->assign('info',$info);
        return $this->fetch('addmerryday');
    }
    /**
     * 编辑预计婚期
     *
     * @param  id
     * @param  merry_day
     * 
     * @return page
     * @author lilong<lilong@suxuantech.cn>
     */
    public function editReadyMarrydayAction(){
        $data = input();
        $id = (int)$data['id'];
        if (!$id) {
            return array('code'=>100,'msg'=>'未获取到ID','data'=>$data['id']);
        }

        $where['id'] = $id;
        $where['is_delete'] = 2;
        $has = db('s_merry_day_set')->where($where)->find();
        if (!$has) {
            return array('code'=>102,'msg'=>'未查到到对应数据，请确认','data'=>$data['id']);
        }
        unset($where);
        $ready_marry_day = trim($data['ready_marry_day']);
        if (!$ready_marry_day) {
            return array('code'=>101,'msg'=>'请输入预计婚期','data'=>trim($data['ready_marry_day']));
        }

        $where['ready_marry_day'] = $ready_marry_day;
        $where['brandclass_id'] = session('brandclass_id');
        $has = db('s_merry_day_set')->where($where)->find();
        if ($has) {
            return array('code'=>102,'msg'=>'存在相同的‘预计婚期’，请确认','data'=>trim($data['ready_marry_day']));
        }
        $upData['ready_marry_day']= $ready_marry_day;
        $upData['update_time'] = date('Y-m-d H:i:s');

        db()->startTrans();
        try {
            db('s_merry_day_set')->where('id',$id)->update($upData);
            action_log('修改预计婚期，由：'.$has['ready_marry_day'].'：修改为：'.$ready_marry_day,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'修改成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code'=>101,'msg'=>'修改失败','data'=>$e->getMessage());
        }
    }
    /*----------预计婚期相关------end-------------------*/
    // 20200430 添加报表
    public function addFormToMenu(){
        $param = input();
        $fid = (int)$param['fid'];
        if (!$fid) {
            $return['code'] = 100;
            $return['msg']  = '没有获取到报表ID';
            $return['data'] = json_encode($param);
            return $return;
        }
        $formInfo = db('s_report_form')->where('id',$fid)->find();
        if (empty($formInfo)) {
            $return['code'] = 101;
            $return['msg']  = '没有获取到报表信息';
            $return['data'] = db()->getLastSql();
            return $return;
        }
        $menuId = db('s_menu')->where('id','between',[REPORT_ID,REPORT_ID_END])->value('MAX(id)');
        
        if ($menuId>REPORT_ID_END-1) {
            $return['code'] = 102;
            $return['msg']  = '报表超出总额限制';
            $return['data'] = db()->getLastSql();
            return $return;
        }
        if(!$menuId){
            $menuId = intval(REPORT_ID) -1; //默认起始ID减1，因为后面又加了一个1
        }
        // 写到menu表的数据
        $inMenu['id'] = $menuId+1;
        $inMenu['menu_name'] = $formInfo['report_name'];
        $inMenu['fid'] = REPORT_ID-1;
        $inMenu['menu_code'] = $formInfo['code'];
        $inMenu['menu_url'] = $formInfo['report_url'];
        $inMenu['status'] = 0;
        $inMenu['sort'] = 10;
        // 写到detail表的数据，为了兼容之前
        $dInfo = db('s_report_detail')->where('form_id',$fid)->find();
        if (empty($dInfo)) {
            $inDetail['form_id'] = $formInfo['id'];
        }

        db()->startTrans;
        try {
            db('s_menu')->insert($inMenu);
            if ($inDetail) {
                db('s_report_detail')->insert($inDetail);
            }
            db('s_report_form')->where('id',$fid)->update(array('status' => 2));
            db()->commit();
            $return['code'] = 200;
            $return['msg']  = '报表添加完成';
            $return['data'] = '';
        } catch (\Exception $e) {
            db()->rollback();
            $return['code'] = 201;
            $return['msg']  = '报表添加失败';
            $return['data'] = $e->getMessage();
        }
        return $return;
    }

    //返点设置
    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('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()]);
        }

    }

    /**
    * 系统字典
    * */
    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();
    }
}