<?php
/**
 * CRM 基本模块
 * 默认接口方法，此方法内定议基础框架所需要的方法，用于验证模块合法性，模块版本，对接基础架构中需要的方法
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\crm\controller;
use app\crm\lib\Target;
use think\Cache;
use app\index\controller\Base;
use think\Exception;
use think\Log;
use think\Request;
use think\Response;
use think\Session;
use PHPExcel_IOFactory;
use PHPExcel;
use Excel5;
use think\Controller;
use app\common\lib\redisQueue;
use app\common\lib\erpInterface;
use app\common\lib\mcInterface;
class Customer extends Base{

    public function check(){
        echo date('Y-m-d H:i:s',strtotime('372'));die;
        echo '<pre>';
        print_r(session('belong_shop_name'));die;
        /*if(request()->isAjax()){
            $staff_name = input('staff_name');
            $info = controller('crm/Customer','lib')->get_staff_list(['staffname'=>$staff_name]);
            if($info[0]['password']){
                return think_decrypt($info[0]['password']);
            }else{
                return '未查询到此员工';

                
            }
        }else{
            return $this->fetch();
        }*/
        print_r(think_decrypt('MDAwMDAwMDAwMIWLraqAqIiW'));die;
        $res = getStaffInfoById(session('staff_id'));
        print_r($res);die;

        $isTable = isTableExist('crm_c_customer_intostore');
        print_r($isTable);die;
        return $this->fetch();
    }
    public  function test(){
        $kf['kf_id'] = 1;
        $kfNewMsg = cache('kfNewMsg_'.$kf['kf_id']);
        var_dump($kfNewMsg);die;
        if (!$kfNewMsg) {
            $kf_new_msg = db('crm_s_wx_talk')->where('kf_id',$kf['kf_id'])->order('time')->select();
            cache('kfNewMsg_'.$kf['kf_id'],$kf_new_msg);
            $kfNewMsg = $kf_new_msg;
        }
        var_dump($kfNewMsg);die;

        $sql ="select * from information_schema.`COLUMNS` where TABLE_SCHEMA= 'sx_crm' and TABLE_NAME = 'c_customerinfo'";
        $info  = db()->where($sql)->select();


        $image = \think\Image::open(ROOT_PATH.'public/img/modal4.jpg');
        //读取图片添加水印，下方是接收图片添加为水印
        // $photo = \think\Image::open(request()->file('photo'));
        // $name = \think\Image::open(request()->file('nick_name'));
        // 
        // 
        // $ewm = \think\Image::open(request()->file('ewm'));
        $arr = input('post.');
        $photo_x = $arr['photo_x'] ? $arr['photo_x'] : 10;
        $photo_y = $arr['photo_y'] ? $arr['photo_y'] : 10;
        $name_x = $arr['name_x'] ? $arr['name_x'] : 150;
        $name_y = $arr['name_y'] ? $arr['name_y'] : 50;
        $ewm_x = $arr['ewm_x'] ? $arr['ewm_x'] : 0;
        $ewm_y = $arr['ewm_y'] ? $arr['ewm_y'] : $image->height()-195;
        $path = '/upload/'.time().'.jpg';
        // 给原图左上角添加水印并保存
        $image->resize_img(ROOT_PATH.'public/img/head-img.png',$path);//压缩
        $img = $image->test(ROOT_PATH.'public/img/head-img.png',$path);//裁剪成圆形
        $image->water($img,[$photo_x,$photo_y]);
        // 给原图左上角添加文字水印并保存
        $image->text('素玄科技',ROOT_PATH.'public/font/fonts/HYQingKongTiJ.ttf',30,'#00000000',[$name_x,$name_y]);
        //左下角加二维码水印
        $image->water(ROOT_PATH.'public/img/ewm.jpg',[$ewm_x,$ewm_y]);
        $image->save(ROOT_PATH.'public'.$path);

        $this->assign('path',$path);
        return $this->fetch();
    }
    /**
     * @cc 自动接收开关
     * 清除模版缓存 不删除 temp目录
     */
    public function clear_temp_ahce() {
        $my_files = (array)glob(TEMP_PATH . '/*.php');
        array_map(
            function($v){
                if(file_exists($v))
                    @unlink($v);
            }, $my_files
        );
        @unlink(ROOT_PATH.'public/login.html');//登录缓存文件
        //清除session
        session('position_list',null);
        session('brandclass_list',null);
        cache('source',null);
        cache('crm_access_model',null);
        cache('crm_area',null);
        cache('crm_region',null);
        cache('crm_source',null);
        cache('crm_intention',null);
        cache('crm_orderAddress',null);
        cache('crm_consulation_shop',null);
        cache('channel',null);
        cache('crm_channel_*',null);
        cache('all_channel_*',null);
        cache('accessModel',null);
        cache('intention',null);
        cache('areaSet',null);
        cache('capacity',null);
        session('consumptionType_*',null);
        session('orderAddress',null);
        session('positions_'.session('staff_id'),null);
        //追踪记录缓存
        // cache('track_log_*',null);
        //设定缓存
        cache('db_config_*',null);
        //提醒缓存
        cache('remind_*',null);
        //部门缓存
        cache('department',null);
        //客资简析缓存
        cache('one_fact_*',null);
        cache('one_avg_*',null);
        cache('total_fact_*',null);
        cache('crm_consultation_type_*',null);
        cache('consumptionType_*',null);
        //自定义列
        cache('colColumn_'.session('staff_id').'_'.session('shop_type'),null);
        cache('colNames_'.session('staff_id').'_'.session('shop_type'),null);
        cache('colModel_'.session('staff_id').'_'.session('shop_type'),null);

        //颜色
        cache('sign_color_'.session('shop_code'),null);
        cache('sales_sign_color_'.session('shop_code'),null);

        //追踪记录缓存
        cache('track_log_*',null);

        cache('companyInfo',null);//清除组织架构缓存
        cache('shopAllStaffs_*',null);
        cache('staffs_type_list_21_*',null);
        // cache('staffs_*',null);
        //清除菜单缓存
        cache('CRM_menuAll',null);
        cache('CRM_menuAllS',null);
        cache('CRM_menu_p15156347814477',null);
        cache('CRM_menu_position1512878846',null);
        cache('fpRuleStaffs_*',null);
        cache('work_type_'.session('staff_id'),null);//工作类型缓存
        // 转订单的缓存
        cache('brandInfo',null);
        cache('shopInfo',null);
        cache('shopInfo_*',null);
        cache('orderType_*',null);
        cache('ordertype_*',null);
        cache('areaInfo_*',null);
        cache('marketInfo_*',null);
        cache('networkInfo_*',null);
        cache('priceInfo_*',null);
        cache('shootInfo_*',null);
        cache('fullInfo_*',null);
        cache('sourceInfo_*',null);
        cache('photo_*',null);
        cache('staffname_*',null);
        cache('setting_list',null);//设定操作
        cache('brand_valid_date_*',null);
        cache('new_brand_valid_date_*',null);
        cache('label_*',null);
        cache('erChannel_*',null);
        cache('crm_tree_address',null);
        
        erpInterface::cleanCache();
        mcInterface::cleanCache();
        //linux下没有缓存文件会报错，清除前必须判断文件存不存在
        // array_map( 'unlink', glob(TEMP_PATH.'*.php' ) );
    }
    public function index(){
        // $ip = '220.181.108.102';
        // dump($_SESSION);die;
        // $res = controller('crm/Customer','lib')->getDepartment();
        // $res = array_column($res,'id,department_name','id');
        // $arr = [];
        // foreach($res[1]['shop'] as $key=>$val){
        //     array_push($arr,$key);
        // }
        // print_r($res);
        // die;
        // $res = array(
        //     'sql'=>array(
        //         'is_fp'=>'2,4',
        //         'is_already_sk'=>1,
        //     ),
        //     'order_by'=> ' is_valid asc,dj_day desc '
        // );
        //  print_r(json_encode($res));die;
        // 获取个人信息
        // echo 'start';die;
        //echo microtime(true)."==";
        
        $staffId = input('param.id');
        if(!empty($staffId)){
            $staffId = $staffId;
        }else{
            $staffId = session('staff_id');
        }
        if($staffId == session('staff_id')){
            //当前人
            $info = session('');
            $info['staffname'] = session('staff_name');
        }else{
            $info = cache("staffInfo_".$staffId);
        }

        if(!$info){
            $info = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>$staffId));//个人信息
            if(empty($info['data'])){
                alert('查看有误，无信息','/');
                exit();
            }
            $this->assign('info',$info['data']);
        }else{
            $info['data'] = [
                'id' => $info['staff_id'],
                'staffname' => $info['staffname'],
                'shop_code' => $info['shop_code'],
                'main_position_code' => $info['main_position_code'],
            ];
            $this->assign('info',['id'=>$info['staff_id'],'staffname'=>$info['staffname']]);
        }        
        //根据主岗位获取显示内容
        $res = db('crm_s_home_show')
               ->where('shop_code',$info['data']['shop_code'])
               ->where('position_code',$info['data']['main_position_code'])
               ->find();
        $content = explode(',',$res['content']);
        $this->assign('content',$content);
        //查询同组小伙伴
        $mc = new \app\common\lib\mcInterface();
        $group_info = $mc->getStaffInfoByGid(['group_id'=>session('group_id')]);
        //$gId = array($staffId);??????
        $gId = [];
        foreach($group_info as $k=>$v){
         //   $group_info[$k]['photo'] = controller('crm/Setting','lib')->get_staff_photo($v['id']);
            $group_info[$k]['status'] = controller('crm/Customer','lib')->getStaffOnlineStatus($v['staff_id']);
            array_push($gId,$v['staff_id']);
        }

        //有查看小组权限并且在小组中
        if($staffId != session('staff_id')){
            if(!check_right('menu1512987394')){
                alert('您无此权限或不在本小组中','/');
                exit();
            }
        }
        
        $this->assign('group_info',$group_info);
        $where = '';
        if(input('param.times') == 'month'){
            $where = 'month';
        }elseif(input('param.times') == 'last_month'){
            $where = 'last month';
        }elseif(input('param.times') == 'week'){
            $where = 'week';
        }elseif(input('param.times') == 'last_week'){
            $where = 'last week';
        }elseif(input('param.times') == 'today'){
            $where = 'today';
        }else{
            $where = 'today';
        }
        $times = input('param.times') ? input('param.times') : 'today';
        $this->assign('times',input('param.times'));
        $tar = new Target();
        //时间
        $day = getdateArea($times);
        $arr = array(
            'start_day' => $day[0],
            'end_day'   => $day[1],
            'staff_id'  => $staffId,
            'shop_code'=> $info['data']['shop_code'],
        );

        /*//目标
        $aim = controller('crm/Customer','lib')->get_aim(array('info'=>$info['data'],'where'=>$where,'staff_id'=>$staffId,'position_code'=>$info['data']['main_position_code']));
        $this->assign('aim',$aim);

        //业绩
        $yeji = 0;
        for($i=0;$i<=count($aim);$i++){
            if($aim[$i]['reach'] > 100){
                $aim[$i]['reach'] = 100;
            }
            $yeji = $yeji+$aim[$i]['reach'];
        }
        $this->assign('yeji',round($yeji/count($aim),2));*/

        /* //短消息
         $message = controller('crm/Customer','lib')->message_list();
         $this->assign('message',$message);
         //通知
         $notice = controller('crm/Customer','lib')->notice_list();
         $this->assign('notice',$notice);*/
        $positions = session('positions_'.session('staff_id'));
        if(empty($positions)){
            $positions = controller('crm/Customer','lib')->getPositions();
        }
        $this->assign('positions',$positions);
        // 每天提醒三天内收到的，但未邀约进店的未成单的客资。
        $res = controller('crm/Customer', 'lib')->three_day_remind();
        //根据主岗位获取显示内容
        $res = db('crm_s_home_show')->where('shop_code',$info['data']['shop_code'])->where('position_code',$info['data']['main_position_code'])->find();
        $res['content'] = explode(',',$res['content']);
        $res['time'] = explode(',',$res['time']);
        $this->assign('res',$res);
        //判断当前岗位有无五维图
        $wu = db('crm_s_staff_ability')->where('position_name',$info['main_position_name'])->where('shop_code',$info['shop_code'])->value('id');

        $this->assign('wu',$wu);
        $this->assign('title','首页');
        return view('home');
    }
    public function getAIM(){
        $data = input();
        $info = getStaffInfoById($data['staff_id']);
        $info['shop_code'] = session('shop_code');
        //目标
        $aim = controller('crm/Customer','lib')->get_aim(array('info'=>$info,'staff_id'=>$info['staff_id'],'position_code'=>$info['main_position_code']));
        //业绩
        $yeji = 0;
        for($i=0;$i<=count($aim);$i++){
            if($aim[$i]['reach'] > 100){
                $aim[$i]['reach'] = 100;
            }
            $yeji = $yeji+$aim[$i]['reach'];
        }
        if(empty($aim)){
            $ret = array('code'=>100,'data'=>'');
        }else{
            $ret = array('code'=>200,'data'=>$aim,'yeji'=>round($yeji/count($aim),2));
        }
        return json($ret);
    }
    public function getIndexData(){
        $data = ['code'=>200,'msg'=>'','data'=>[]];
        $staffId = input('param.id');
        if(empty($staffId)){
            $staffId = session('staff_id');
        }
        if($staffId == session('staff_id')){
            //当前人
            $info = session('');
            $info['staffname'] = session('staff_name');
        }else{
            $info = cache("staffInfo_".$staffId);
        }

        if(!$info){
            $info = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>$staffId));//个人信息
            if(empty($info['data'])){
                $data['code'] = 500;
                $data['msg'] = '查看有误，无法获取当前员工信息';
                echo json_encode($data);
                exit();
            }
        }else{
            $info['data'] = [
                'id' => $info['staff_id'],
                'staffname' => $info['staffname'],
                'shop_code' => $info['shop_code'],
                'main_position_code' => $info['main_position_code'],
            ];
        }
        if(check_right('menu1512637269')) {//查看所有客资权限
            $staff_id =  controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>$info['data']['shop_code']]);
            $staff_id = array_column($staff_id,'id');
            $staffId = implode(',',$staff_id);
        }elseif(check_right('menu1531471639')){//查看部门客资权限
            $staff_id = controller('crm/Customer')->getDepartmentStaffs(session('department_id'));
            $staff_id = array_column($staff_id,'id');
            $staffId = implode(',',$staff_id);
        }elseif(check_right('menu1529653231')) {//查看小组客资权限
            $mc = new \app\common\lib\mcInterface();
            $staff_id = $mc->getStaffInfoByGid(['group_id'=>session('group_id')]);
            $staff_id = array_column($staff_id,'id');
            $staffId = implode(',',$staff_id);
        }
        //根据主岗位获取显示内容
        $res = db('crm_s_home_show')->where('shop_code',$info['data']['shop_code'])->where('position_code',$info['data']['main_position_code'])->find();
        $content = explode(',',$res['content']);
        $time = explode(',',$res['time']);
        foreach($time as $k=>$v){
            if($v == 'this_month'){
                $where = 'month';
            }elseif($v == 'last_month'){
                $where = 'last month';
            }elseif($v == 'this_week'){
                $where = 'week';
            }elseif($v == 'last_week'){
                $where = 'last week';
            }elseif($v == 'today'){
                $where = 'today';
            }elseif($v == 'yestoday'){
                $where = 'yestoday';
            }
            $tar = new Target();
            //时间
            $day = getdateArea($v);

            $arr = array(
                'start_day' => $day[0],
                'end_day'   => $day[1],
                'staff_id'  => $staffId,
                'department_id'  => $info['department_id'],
                'shop_code'=> $info['data']['shop_code'],
            );

            if(in_array('花费',$content)){
                $cost = $tar->cost($arr);
                $data['data'][$v]['cost'] = ['id'=>'cost','value'=>ceil($cost)];
            }

            // $allCRM = controller('crm/Customer','lib')->all_crm($info['data'],$where);
            if(in_array('毛客资',$content)){
                $allCRM = $tar->newCustomerNum($arr);
                $data['data'][$v]['allCRM'] = ['id'=>'allCRM','value'=>$allCRM];
            }
            // $validCRM = controller('crm/Customer','lib')->valid_crm($info['data'],$where);
            if(in_array('有效客资',$content)){
                $validCRM = $tar->validCustomerNumber($arr);
                $data['data'][$v]['validCRM'] = ['id'=>'validCRM','value'=>$validCRM];
            }
             if(in_array('有效客资(登记时间)',$content)){
                $validDJ = $tar->validCustomerNumberDJ($arr);
                $data['data'][$v]['validDJ'] = ['id'=>'validDJ','value'=>$validDJ];
            }
            // $validOrder = controller('crm/Customer','lib')->order_crm($info['data'],$where);
            // && strpos($params['staff_id'],',')
            if(in_array('有效新单',$content)){
                $validOrder = $tar->orderNumber($arr);
                $data['data'][$v]['validOrder'] = ['id'=>'validOrder','value'=>$validOrder];
            }
             if(in_array('总订单(订单开始时间)',$content)){
                 $order = $tar->orderNumberStart($arr);
                 $data['data'][$v]['order'] = ['id'=>'order','value'=>$order];
             }
            if(in_array('毛客资成本',$content)){
                $all_cost = $tar->ObtainCost($arr);
                $data['data'][$v]['all_cost'] = ['id'=>'all_cost','value'=>sprintf('%.2f',$all_cost)];
            }
            if(in_array('新单成本',$content)){
                $order_cost = $tar->newOrderCost($arr);
                $data['data'][$v]['order_cost'] = ['id'=>'order_cost','value'=>sprintf('%.2f',$order_cost)];
            }

            if(in_array('获取电话',$content)){
                $tel = controller('crm/Customer','lib')->getTelCount($arr);
                $data['data'][$v]['tel'] = ['id'=>'tel','value'=>$tel];
            }
            if(in_array('电话转换率',$content)){
                $tel = controller('crm/Customer','lib')->getTelCount($arr);
                $validCRM = $tar->validCustomerNumber($arr);
                $data['data'][$v]['telRate'] = ['id'=>'telRate','value'=>sprintf('%.1f',$tel/$validCRM*100)."%"];
            }

            if(in_array('QQ/微信',$content)){
                $qq = controller('crm/Customer','lib')->getQQCount($arr);
                $data['data'][$v]['qq'] = ['id'=>'qq','value'=>$qq];
            }

            // $validJD = controller('crm/Customer','lib')->validJD($info['data'],$where);
            if(in_array('有效进店',$content)){
                $validJD = $tar->actualIntoCustomerNumber($arr);
                $data['data'][$v]['validJD'] = ['id'=>'validJD','value'=>$validJD];
            }
            if(in_array('走单',$content)){
                $zd = $tar->zouDan($arr);
                $data['data'][$v]['zd'] = ['id'=>'zd','value'=>$zd];
            }
            if(in_array('网付订单',$content)){
                $line = $tar->orderOnline($arr);
                $data['data'][$v]['orderOnline'] = ['id'=>'orderOnline','value'=>$line];
            }
            if(in_array('毛客资进店率',$content)){
                $mkzZD = $tar->mkzToJDRate($arr);
                $data['data'][$v]['mkzZD'] = ['id'=>'mkzZD','value'=>sprintf('%.1f',$mkzZD*100).'%'];
            }
            if(in_array('毛客资订单率',$content)){
                $mkzOrder = $tar->mkzToOrderRate($arr);
                $data['data'][$v]['mkzOrder'] = ['id'=>'mkzOrder','value'=>sprintf('%.1f',$mkzOrder*100).'%'];
            }
            if(in_array('无效新单',$content)){
                // $invalidOrder = controller('crm/Customer','lib')->invalidOrder($info['data'],$where);
                $invalidOrder = $tar->unvalidOrder($arr);
                $data['data'][$v]['invalidOrder'] = ['id'=>'invalidOrder','value'=>$invalidOrder];
            }
            if(in_array('营收',$content)){
                // $fact = controller('crm/Customer','lib')->fact($info['data'],$where);
                $fact = $tar->dealAmount($arr);
                $data['data'][$v]['fact'] = ['id'=>'fact','value'=>$fact];
            }

            if(in_array('流失客资',$content)){
                $loss = controller('crm/Customer','lib')->loss($arr);
                $data['data'][$v]['loss'] = ['id'=>'loss','value'=>$loss];
            }
            if(in_array('待追踪',$content)){
                $jdwd_crm = controller('crm/Customer','lib')->jdwd_crm($arr);
                $data['data'][$v]['jdwd_crm'] = ['id'=>'jdwd_crm','value'=>$jdwd_crm];
            }
            // $jd_crm = controller('crm/Customer','lib')->jd_crm($info['data'],$where);
            /*if(in_array('邀约',$content)){
                $jd_crm = $tar->inviteIntoCustomerNumber($arr);
                $data['data'][$v]['jd_crm'] = ['id'=>'jd_crm','value'=>$jd_crm];
            }*/
            if(in_array('A客资',$content)){
                $cus_a = $tar->aCustomerNum($arr);
                $data['data'][$v]['cus_a'] = ['id'=>'cus_a','value'=>$cus_a];
            }
            if(in_array('有效率',$content)){
                //有效率  有效/所有
                $valid = $tar->valueCustomerRate($arr);
                // $this->assign('youxiao',sprintf('%.2f',($validCRM/$allCRM)*100));
                $data['data'][$v]['youxiao'] = ['id'=>'youxiao','value'=>sprintf('%.1f',$valid*100)."%"];
            }

            if(in_array('进店率',$content)){
                //进店转化率 进店/有效
                $zhuanhua = $tar->intoValueRate($arr);
                // $this->assign('zhuanhua',sprintf('%.2f',($validOrder/$jd_crm)*100));
                $data['data'][$v]['zhuanhua'] = ['id'=>'zhuanhua','value'=>sprintf('%.1f',$zhuanhua*100)."%"];
            }
            /*if(in_array('进店率',$content)){
                //进店率  进店 进客/预约
                $jindian = $tar->valueCustomerIntoRate($arr);
                // $this->assign('jindian',sprintf('%.2f',($jd_crm/$validCRM)*100));
                $data['data'][$v]['jindian'] = ['id'=>'jindian','value'=>sprintf('%.1f',$jindian*100)."%"];
            }*/
            if(in_array('订单转换率',$content)){
                //成交率  DT/YT  YT：标记有效；DT：有效成单数
                // $sucOrder = controller('crm/Customer','lib')->sucOrder($info['data'],$where);
                $orderzhuanhuan = $tar->orderValueRate($arr);
                $data['data'][$v]['orderzhuanhuan'] = ['id'=>'orderzhuanhuan','value'=>sprintf('%.1f',$orderzhuanhuan*100)."%"];
            }
            if(in_array('成交率',$content)){
                //成交率  DT/YT  YT：进店；DT：有效成单数
                // $sucOrder = controller('crm/Customer','lib')->sucOrder($info['data'],$where);
                $chengjiao = $tar->succRate($arr);
                $data['data'][$v]['chengjiao'] = ['id'=>'chengjiao','value'=>sprintf('%.1f',$chengjiao*100)."%"];
            }
            /*if(in_array('邀约转化率',$content)){
                //  邀约进店/有效
                // $factIn = controller('crm/Customer','lib')->factIn($info['data'],$where);
                // $makeIn = controller('crm/Customer','lib')->makeIn($info['data'],$where);
                $factIn = $tar->validCustomerNumber($arr);
                $makeIn = $tar->inviteIntoCustomerNumber($arr);
                $data['data'][$v]['yyzh'] = ['id'=>'yyzh','value'=>sprintf('%.1f',($factIn/$makeIn)*100)."%"];
            }*/
            if(in_array('A客转化率',$content)){
                //  A客/有效
                $ake = $tar->ACustomerRate($arr);
                // $this->assign('ake',sprintf('%.2f',($cus_a/$validCRM)*100));
                $data['data'][$v]['ake'] = ['id'=>'ake','value'=>sprintf('%.1f',$ake*100)."%"];
            }
            if(in_array('一销实收',$content)){
                //  A客/有效
                $one_fact = cache('one_fact_'.$where.'_'.$arr['staff_id']);
                if(empty($one_fact)){
                    $one_fact = $tar->oneFact($arr);
                    cache('one_fact_'.$where.'_'.$arr['staff_id'],$one_fact,3600);
                }
                $data['data'][$v]['one_fact'] = ['id'=>'one_fact','value'=>sprintf('%.2f',$one_fact)];
            }
            if(in_array('一销均价',$content)){
                //  套系/订单量
                $one_avg = cache('one_avg_'.$where.'_'.$arr['staff_id']);
                if(empty($one_avg)){
                    $one_avg = $tar->oneAVG($arr);
                    cache('one_avg_'.$where.'_'.$arr['staff_id'],$one_avg,3600);
                }
                $data['data'][$v]['one_avg'] = ['id'=>'one_avg','value'=>sprintf('%.2f',$one_avg)];
            }
            if(in_array('总实收',$content)){
                $total_fact = cache('total_fact_'.$where.'_'.$arr['staff_id']);
                if(empty($total_fact)){
                    $total_fact = $tar->totalFact($arr);
                    cache('total_fact_'.$where.'_'.$arr['staff_id'],$total_fact,3600);
                }
                $data['data'][$v]['total_fact'] = ['id'=>'total_fact','value'=>sprintf('%.2f',$total_fact)];
            }

            /*$total =  controller('crm/Customer','lib')->get_total_count($info['data'],$where);
            $data['total'] = $total;
            //沟通进度和条数
            if(check_right('menu1512637269') || $info['data']['main_work_type'] == RECEIVE_WORK_TYPE){
                $seles =  controller('crm/Customer','lib')->get_seles_count($info['data'],$where);
                $data['seles'] = $seles;
            }*/
        }
        return json($data);
    }
    public function checkLogin(){
        echo check_login();
    }
    /*
    * 插入手机归属地信息
    * */
    public function insTelInfo(){
        $res = controller('crm/Customer','lib')->insTelInfo(input('param.tel'));
        return $res;
    }
    /*
    * 查询手机归属地信息
    * */
    public function getTelInfo(){
        $res = controller('crm/Customer','lib')->getTelInfo(input('post.'));
        return $res;
    }
    public function jqgrid(){
        //表格自定义
        // $jq_name = [ '客户编号', '追踪日期', '名字', '追踪阶段', '手机','接单点', '介绍人', '追踪人' ];
        if(session('staff_id')){
            $jqgrid = cache('jqgrid_'.session('staff_id'));
            // dump(($jqgrid));die;
            // $jqgrid['name'] = $jqgrid['name'] ? $jqgrid['name'] : [];
            $jqgrid['model'] = json_encode($jqgrid['model']);
            return $jqgrid;
        }

        // $this->assign('jq_name',json_encode($jqgrid['name']));
        // $this->assign('jq_model',json_encode($jqgrid['model']));
        // $this->assign('jq_name',json_encode($jq_name));
    }
    public function upload_photo(){
        // 获取表单上传文件 例如上传了001.jpg
        $type = checkFileType($_FILES['file']['tmp_name']);

        switch($type){
            case 'png':
            case 'jpg':
                $file = request()->file('file');
                // 移动到框架应用根目录/public/uploads/ 目录下
                $info = $file->move(ROOT_PATH.'public' . DS . 'upload/'.'pic',session('staff_id').'.jpg');
                if($info){
                    // 成功上传后 返回上传信息
                    return json(array('state'=>1,'path'=>$info->getSaveName()."?rand=".  get_rand_string()));
                }else{
                    // 上传失败返回错误信息
                    return json(array('state'=>0,'msg'=>'上传失败'));
                }
            break;
            case 'wav':
                $id = intval(input('post.id'));
                if(empty($id)){
                    return json(array('state'=>0,'msg'=>'id为空，不能上传'));
                }
                $file = request()->file('file');
                // 移动到框架应用根目录/public/uploads/ 目录下
                $path = '/public' . DS . 'upload/'.'audio/'.date('Y-m-d',time());
                $name = date('YmdHis',time()).'-'.session('staff_id').'.wav';
                $info = $file->move($path,$name);
                if($info){
                    //路径插入数据库
                    $append_type= intval(input('post.append_type'));
                    if($append_type){//用于区分是电访记录还是新老客户记录
                        db('crm_c_salestrackinginfo')->where('id',$id)->update(['audio_path'=>$path.'/'.$name]);
                    }else{
                        db('crm_c_call_registration')->where('id',$id)->update(['audio_path'=>$path.'/'.$name]);
                    }

                    // 成功上传后 返回上传信息
                    return json(array('state'=>1,'msg'=>'上传成功','path'=>$path.'/'.$name));
                }else{
                    // 上传失败返回错误信息
                    return json(array('state'=>0,'msg'=>'上传失败'));
                }
            break;
            default:
                return json(array('state'=>0,'msg'=>'上传文件类型错误'));
                break;
        }
    }
    public function getMessage(){
        $message = controller('crm/Customer','lib')->message_list(input('post.send_type'));
        return json_encode($message);
    }
    public function getNotice(){
        $message = controller('crm/Customer','lib')->message_list(2);
        return json_encode($message);
    }

    //修改信息，通知
    /*
     * @cc 修改信息，通知
     * */
    public function update_message(){
        $id = input('post.id');
        $res= controller('crm/Customer','lib')->update_message($id);
        $whereCount=[
            'receive_id' => session('staff_id'),
            'read_status'=> 0,
            'is_delete'  => 0
        ];
        $noRead = db('crm_c_message')->where($whereCount)->count();
        return $noRead;
    }
    
    //获取最后活动时间
    public function getStaffOnlineStatus($staff_id){
        return controller('crm/Customer','lib')->getStaffOnlineStatus($staff_id);
    }
    //修改在线状态
    public function update_status(){
        $status = input('post.status');
        $res = controller('crm/Customer','lib')->update_status($status);
        return $res;
    }
    public function getCustomerList(){
        $info = controller('crm/Customer','lib')->get_staff_info(['staff_id'=>input('post.staff_id')]);
        $res = controller('crm/Customer','lib')->getCustomerList($info['data'],input('param.times'),input('seles_step'));
        return json($res);
    }
    public function getHomeTu(){
        $res = controller('crm/Customer','lib')->getHomeTu(input('staff_id'),input('param.times'));
        return $res;
    }
    //沟通进度
    public function seles_step(){
        return controller('crm/Customer','lib')->get_seles_step();
    }

    // 移动端首页
    public function wx_index(){
        // 员工信息
        $staff = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>session('staff_id')));
        $this->assign('staff',$staff['data']);
        // 店面信息
        $shopInfo = controller('crm/Customer', 'lib')->get_shop(array('shop_code'=>session('shop_code')));
        $this->assign('shop',$shopInfo[0]);
        //本月任务
        $renwu = controller('crm/Customer','lib')->getRenwu(date('m'));
        $this->assign('renwu',$renwu);
        //本月提报
        $tibao = controller('crm/Customer','lib')->getMonthTB();
        $this->assign('tibao',$tibao);
        //本月转换率
        $zhuanhuan = controller('crm/Customer','lib')->getMonthZH();
        $this->assign('zhuanhuan',$zhuanhuan);

        // 查看大屏
        $staff_id = session('staff_id');
        $is_in = controller('crm/Bigscreen', 'lib')->checkBigScreenAuth();
        if ($is_in) {
            $bigScreen = 1;
        }else{
            $bigScreen = 2;
        }
        $this->assign('bigScreen',$bigScreen);
        $bg_controller = config('bg_controller');
        $sid = think_encrypt($staff_id);
        if ($bg_controller) {
            $bs_url = '/crm/'.$bg_controller.'/mobile?sid='.$sid;
        }else{
            $bs_url = '/crm/Bigscreen/mobile?sid='.$sid;
        }
        $this->assign('bs_url',$bs_url);
        /* //事业部大屏
        $b_auth = check_right('menu1526378178');
        $this->assign('b_auth',$b_auth);*/
        //离线开关
        $this->assign('switch',db_config('not_online_is_fp_'.session('staff_id')));
        //在线状态
        $staffInfo = cache('staffInfo_'.session('staff_id'));
        $this->assign('status',$staffInfo['status']);
        $new_cus = db_config('mobile_new_cus_'.session('shop_code'));
        $this->assign('new_cus',$new_cus);
        //判断是不是网销，摄影师，导师，销售
        $work_type = [1,3,21,22,25];
        $staff_work_type = explode(',',session('work_type'));
        $jiaoji = array_intersect($work_type,$staff_work_type);
        if(empty($jiaoji)){
            $experience = false;
        }else{
            $experience = true;
        }
        $this->assign('experience',$experience);
        return $this->fetch('ucenter');
    }
    public function logOut(){
        $staffId = session('staff_id');
        controller('crm/Customer','lib')->logOut($staffId);
        if(is_weixin()){
            $this->redirect('crm/Index/wxLogin');
        }else{
            $this->redirect('crm/Index/index');
        }
    }
    public function show_pwd(){
        return $this->fetch('update_pwd');
    }
    public function bindWeixin(){
        $staffId = session('staff_id');
        $mc = new \app\common\lib\mcInterface();

        if(IS_POST === true){
            $password = input('post.password');
            // $res = sx_call('5a221c9548d47', ['staffname'=>session('staff_name'),'password'=>$password]);
            $res = $mc->checkPassword(['staffname'=>session('staff_name'),'password'=>$password]);
            if($res['code'] == 200){
                $bindCode = get_rand_string(16);
                cache('bindWX_'.$staffId ,['code'=>$bindCode,'staffname'=>session('staff_name'),'password'=>$password,'state'=>'init'],60);
                $url = Url('bindWeixin',['stff_id'=>$staffId,'bind_code'=>$bindCode,'act'=>'showqrcode']);
                $url = Url('bindWeixin','','',true);
                $url = strpos($url,'?')?($url . '&'):($url.'?');
                $url = $url.'staff_id='.$staffId.'&bind_code='.$bindCode.'&act=showqrcode';
                return json(['code'=>200,'bind_code'=>$bindCode,'staff_id'=>$staffId,'img_url'=>$url]);
            }else{
                return json(['code'=>500,'msg'=>'验证失败，可能密码错误。']);
            }
            exit();
        }
        $act=input('get.act');
        if($act == 'showqrcode'){
            $bindCode = input('get.bind_code');
            $staffId = input('get.staff_id');
            $url = Url('index/bindWeixin','','',true);
            $url = strpos($url,'?')?($url . '&'):($url.'?');
            $url = $url.'staff_id='.$staffId.'&bind_code='.$bindCode;
            $qrcode = new \Endroid\QrCode\QrCode();
            $qrcode->setText($url);
            echo $qrcode->writeString();
        }
        if($act == 'getbind'){
            //手机端绑定界面
            $res = cache('bindWX_'.$staffId );
            if($res && $res['state'] == 'binded'){
                return json(['code'=>200,'msg'=>'绑定成功','data'=>['state'=>'binded']]);
                exit();
            }elseif(!$res){
                return json(['code'=>503,'msg'=>'绑定失败或二维码已过期，请重试','data'=>[]]);
                exit();
            }
            return json(['code'=>200,'msg'=>'','data'=>[]]);     
            //return $this->fetch('bind_page');
            exit();

        }
        // $staffInfo = sx_call('5a18e3fa516a1', ['staff_id'=>$staffId]);
        $staffInfo = $mc->getStaffByIds(['staff_id'=>$staffId]);
        $this->assign('staffInfo',$staffInfo[0]);
        return $this->fetch();
    }
    public function edit_pwd(){
        $param['staff_id'] = session('staff_id');
        $param['newPassword'] = input('post.newPassword');
        $param['oldPassword'] = input('post.oldPassword');
        // $param['turestaffname'] = input('post.turestaffname');
        $res = controller('crm/Customer','lib')->update_pwd($param);
        return $res;
    }
    //微信修改密码界面
    public function wx_update_pwd(){
        return $this->fetch();
    }
    //客资提报记录
    public function customerTiBao(){
        $search = input('param.');
        $tibao = controller('crm/Customer','lib')->customerTiBao($search);
        // print_r($search);die;
        $this->assign('count',$tibao['count']);
        unset($tibao['count']);
        $this->assign('tibao',$tibao);
        $this->assign('flag',$search['flag']);
        $this->assign('search',$search['search']);
        $this->assign('time1',$search['time1']);
        $this->assign('time2',$search['time2']);
        $this->assign('time',$search['time']==2 ? 2 : 0);
        return $this->fetch('quoterecord');
    }
    public function tibaoNum(){

        $data = input();
        $start = $data['start'] ? date('Y-m-d',strtotime($data['start'])) : date('Y-m-d');
        $end = $data['end'] ? date('Y-m-d 23:59:59',strtotime($data['end'])).' ' : date('Y-m-d 23:59:59');
        $where['dj_day'] = array('between',[$start,$end]);
        $where['is_status'] = 1;
        if($data['customer_channel']){
            $where['customer_channel'] = trim($data['customer_channel']);
        }
        $where['add_shop_code'] = session('shop_code');
        //查询是否包含erp客资设定
        $list_search_is_in_erp = db_config('list_search_is_in_erp',$data['list_search_is_in_erp']);
        if($list_search_is_in_erp != 1){
            $where['c_from'] = 1;
        }
        $where['dj_staff_id'] = array('in',getStaffAuth());
        $count = controller('crm/Customer','lib')->appGetCustomerNumber($where);
        $channel = controller('crm/Customer','lib')->getChannel();
        $this->assign('channel',$channel);
        if(Request::instance()->isAjax()){
            return ['count'=>$count,'customer_channel'=>$data['customer_channel'],'start'=>date('Y-m-d',strtotime($start)),'end'=>date('Y-m-d',strtotime($end))];
        }else{
            $this->assign('count',$count);
            $this->assign('start',date('Y-m-d'));
            $this->assign('end',date('Y-m-d'));
            return $this->fetch();
        }
    }
    public function salesNum(){
        $data = input();
        $start = $data['start'] ? date('Y-m-d',strtotime($data['start'])) : date('Y-m-d');
        $end = $data['end'] ? date('Y-m-d 23:59:59',strtotime($data['end'])) : date('Y-m-d 23:59:59');
        $where['jr_day'] = array('between',[$start,$end]);
        $where['is_status'] = 1;
        $where['shop_code'] = session('shop_code');
        //查询是否包含erp客资设定
        $list_search_is_in_erp = db_config('list_search_is_in_erp',$data['list_search_is_in_erp']);
        if($list_search_is_in_erp != 1){
            $where['c_from'] = 1;
        }
        $where['sales_staff_id'] = array('in',getStaffAuth());
        $count = controller('crm/Customer','lib')->appGetCustomerNumber($where);
        if(Request::instance()->isAjax()){
            return ['count'=>$count,'start'=>date('Y-m-d',strtotime($start)),'end'=>date('Y-m-d',strtotime($end))];
        }else{
            $this->assign('count',$count);
            $this->assign('start',date('Y-m-d'));
            $this->assign('end',date('Y-m-d'));
            return $this->fetch();
        }
    }
    //客资提报ajax
    public function customerTBAJAX(){
        $param = input('post.');
        $tibao = controller('crm/Customer','lib')->customerTiBao($param);

        unset($tibao['count']);
        if(!empty($tibao)){
            return ($tibao);
        }
    }
    //客资提报记录
    public function customerTiBaoByTime(){
        $time = input('time');
        $tibao = controller('crm/Customer','lib')->customerTiBaoByTime($time);
        $this->assign('tibao',$tibao);
        $this->assign('time',date('Y-m-d',time()));
        return $this->fetch('quoterecord');
    }
    //客资提报记录
    public function customerTiBaoBT(){
        $time = input('post.');
        $tibao = controller('crm/Customer','lib')->customerTiBaoBT($time);
        $this->assign('tibao',$tibao);

        $this->assign('time1',$time[0]);
        $this->assign('time2',$time[1]);
        $this->assign('time',date('Y-m-d',time()));
        return $this->fetch('quoterecord');
    }
    //移动端提报页面 20200118
    public function keziTB(){
        //客户意向
        $intention=controller("crm/Customer","lib")->intention(array('shop_code'=>session('shop_code')));
        $this->assign('intention',$intention);
        //客户来源
        $source=controller("crm/Customer","lib")->source(array('shop_code'=>session('shop_code')));
        $this->assign("source",$source);
        //获取方式
        $accessModel=controller("crm/Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
        $this->assign("accessModel",$accessModel);
        //来源渠道
        // $channel=controller("Customer","lib")->channel(array('shop_code'=>session('shop_code')));
        $channel=controller("crm/Customer","lib")->getChannel();
        $this->assign("channel",$channel);
        //出生医院
        $hos = controller('crm/Customer','lib')->getHospital();
        $this->assign("hospital",$hos);
        //消费类型
        $consumptionType=controller("crm/Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        //客资地域
        $region=controller("crm/Customer","lib")->region(array('shop_code'=>session('shop_code')));
        $this->assign("region",$region);
        //分区
        $area=controller("crm/Customer","lib")->areaSet(array('shop_code'=>session('shop_code')));
        $this->assign("area",$area);
        //意向店面
        $intention_shop = controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass'),
            'is_marketing'=>2));
        $this->assign('intention_shop',$intention_shop);
        $this->assign('address',$this->getProvinceApp());
        //查询归属地是否筛客
        /*$b_is_sk = controller("Customer", "lib")->is_sk(session('belong_shop_code'));
        if($b_is_sk == 1 || session('is_sk') == 1){echo 111;die;
            $this->assign('is_sk',1);
            $this->assign('sklist',controller("Customer", "lib")->sklist('',24));
        }*/
        $param = [
            '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($param);


        $this->assign('shop',$belong);
        // 录入必选项配置
        $lrMust = db_config('lr_must_'.session('brandclass_id'));
        $lrMust = trim($lrMust,',');
        $lrMust = explode(',',$lrMust);
        //成都网销中心录入客资 ‘获取方式’为必填项
        if(session('shop_code') == 'TSYX13' && !in_array('access_model',$lrMust)){
            $lrMust[] = 'access_model';
        }
        $this->assign('lrMust',($lrMust));
        $this->assign('jslrMust',json_encode($lrMust));
        // 录入字段隐藏配置
        $hidden = db_config('lr_hidden_'.session('brandclass_id'));
        $hidden = trim($hidden,',');
        $hidden = explode(',',$hidden);
        $this->assign('lrHidden',$hidden);
        return $this->fetch();
    }
    //移动端二维码
    public function myqrcode(){
        $param = input('param.');
        $param['customer_channel'] = urlencode($param['customer_channel']);
        if($param['introducer_name']){
            $param['introducer_name'] = urlencode($param['introducer_name']);
        }

        unset($param['/crm/customer/myqrcode_html']);
        $a = arrayToParams($param);
        $u = strpos($_SERVER['HTTP_HOST'],'http://') ? $_SERVER['HTTP_HOST']:'http://'.$_SERVER['HTTP_HOST'];
        $u .= "/crm/index/appTB?";
        if($param['customer_type'] == 2){
            $url = $u."dj_staff_id=".session('staff_id')."&dj_staff_number=".session('staff_number')."&dj_staff=".urlencode(session('staff_name'))."&shop_code=".$param['shop_code']."&brandclass_id=".session('brandclass_id')."&brandclass=".urlencode(session('brandclass'))."&add_shop_code=".session('belong_shop_code')."&add_shop_name=".urlencode(session('belong_shop_name')).'&'.$a;
        }else{
            $url = $u."dj_staff_id=".session('staff_id')."&dj_staff_number=".session('staff_number')."&dj_staff=".urlencode(session('staff_name'))."&brandclass_id=".session('brandclass_id')."&brandclass=".urlencode(session('brandclass'))."&add_shop_code=".session('belong_shop_code')."&add_shop_name=".urlencode(session('belong_shop_name'))."shop_code=".'&'.$a;
        }
        $qrcode = new \Endroid\QrCode\QrCode();
        $qrcode->setText($url);
        echo $qrcode->writeString();
        exit();
    }
    public function qrcode(){
        $param = input('post.');
        $mc = new \app\common\lib\mcInterface();
        // $channel = sx_call('59fd5e729e5a8',array('id'=>$param['channel_id']));//渠道名称
        $channel = $mc->getChannelInfo(array('id'=>$param['channel_id']));
        $this->assign('channel',$channel[0]);
        
        // $shop = sx_call('5a005e0038270',array('shop_code'=>$param['shop_code']));//提交店面信息
        $shop = $mc->getChannelInfo(array('shop_code'=>$param['shop_code']));
        $this->assign('shop',$shop[0]);
        $this->assign('customer_type',$param['customer_type']);
        return $this->fetch();
    }
    // 移动端转介绍页面
    public function jieshaoTB(){
        //客户意向
        $intention=controller("Customer","lib")->intention(array('shop_code'=>session('shop_code')));
        $this->assign('intention',$intention);
        //接入店面信息
        $shop = controller('Customer','lib')->getShopInfo(array('brandclass'=>session('brandclass'),'is_dig'=>1));
        $this->assign('shop',$shop['data']);
        //客户来源
        $source=controller("Customer","lib")->source(array('shop_code'=>session('shop_code')));
        $this->assign("source",$source);
        //获取方式
        $accessModel=controller("Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
        $this->assign("accessModel",$accessModel);
        //来源渠道
        // $info = controller("Customer","lib")->get_staff_info(array('staff_id'=>session('staff_id')));
        // $this->assign("info",$info['data']);
        // $channel=controller("Customer","lib")->channel(array('shop_code'=>session('shop_code')));jies
        // $this->assign("channel",$channel);
        //消费类型
        $consumptionType=controller("Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        //客资地域
        $region=controller("Customer","lib")->region(array('shop_code'=>session('shop_code')));
        $this->assign("region",$region);
        //分区
        // $area=controller("Customer","lib")->areaSet(array('shop_code'=>session('shop_code')));
        // $this->assign("area",$area);
        //查询归属地是否筛客
        // $b_is_sk = controller("Customer", "lib")->is_sk(session('belong_shop_code'));
        // if($b_is_sk == 1 || session('is_sk') == 1){
            // $this->assign('is_sk',1);
            // $this->assign('sklist',controller("Customer", "lib")->sklist('',24));
        // }
        //移动端介绍人是否可输入
        $mobile_input = db_config('mobile_input_'.session('shop_code'));
        $this->assign("mobile_input",$mobile_input);
        // $this->assign('address',$this->getProvinceApp());
        $babypastel = customize('babypastel');
        if ($babypastel) {
            $this->assign('babypastel','1');
            $this->assign("babypastel",$babypastel);
            $channel=controller("crm/Customer","lib")->getChannel();
            $this->assign("channel",$channel);
        }
        return $this->fetch();
    }
    //移动端介绍人搜索
    public function searchCustomers(){
        $customer=controller("Customer","lib")->customerNameSearch(input('param.customer_name'));
        return $customer;
    }
    //移动端客户详情
    public function kzdetails(){
        $info = controller("Customer","lib")->getCustomerInfo(input('param.id'));
        $track = controller("Customer","lib")->getCustomerTrackInfos(input('param.id'));
        $this->assign('info',$info);
        $this->assign('track',$track);
        return $this->fetch();
    }
    //表格数据 json格式
    /*   public function customerListData(){
           $data = input('post.');
           $detail=controller("Customer","lib")->customerListData($data);
           echo  json_encode($detail);
       }
    */
    public function check_right(){
        $code = input('post.');
        if(check_right($code['code'])){
            $num=1;
        }else{
            $num=5;
        }
        $this->success('验证权限成功', '/',$num);
    }
    //检测是否有店面信息
    public function check_shop_message(){
        $shop_code=session('shop_code');
        $shop_name=session('shop_name');
        if(empty($shop_code)&&empty($shop_name)){
            $returnData = array('code' => 100,'msg' =>'此用户没有店面信息');
        }else{
            $returnData = array('code' => 1,'msg' =>'有店面信息');
        }
        return json($returnData);

    }
    public function customer_list(){
        //列表页搜索项隐藏配置
        $search = db_config('list_search_hidden_'.session('brandclass_id'));
        if($search){
            $search = explode(',',$search);
        }else{
            $search = ['sales_staff','dj_staff','customer_intention','customer_channel','fp_status','jd_status','succ_status','cus_from','phone'];
        }

        $this->assign('search_list',$search);



        return $this->fetch();
    }
    //刷新表格上方选项卡数据量值
    public function refreshNumber(){
        $data = input('post.');
        $num=controller("Customer","lib")->searchNum($data);
        $this->success('刷新成功', '/',$num);
    }
    // 获取各个下拉框的值
    public function getSelectDataList($param=[]){
        // 二级渠道 来源渠道 
        $erChannel = controller("crm/Customer","lib")->getErChannel(session('shop_code'));
        $return['erChannel'] = $erChannel;
        // 三级渠道 渠道名称  --通过二级渠道下拉获取
        // $channel = controller("crm/Customer","lib")->getChannel(session('shop_code'));
        // $return['channel'] = $channel;
        // 获取方式 
        $accessModel=controller("crm/Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
        $return['accessModel'] = $accessModel;
        // 消费类型   不从mc里取了，取erp的设定
        $consumptionType = controller("crm/Customer","lib")->consumptionType();
        $return['consumptionType'] = $consumptionType;
        // 客户意向 
        $intention=controller("crm/Customer","lib")->intention(array('shop_code'=>session('shop_code')));
        $return['intention'] = $intention;
        // 客户来源 
        $source = controller("crm/Customer","lib")->source(array('shop_code'=>session('shop_code')));
        $return['source'] = $source;
        // 客资标记 
        $tracksign=controller("crm/Setting","lib")->gettrackingKmarkerList();
        $return['tracksign'] = $tracksign;
        // 推广人 
        $tgParam['shop_code'] = session('shop_code');
        $tgParam['work_type'] = KZTB_WORK_TYPE;
        $tgParam['all'] = 2;
        $recommendStaff = getShopStaffs($tgParam);
        $return['recommendStaff'] = $recommendStaff;
        // 意向店面 
        $intentionShops = controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass'),'is_marketing'=>2));
        $return['intentionShops'] = $intentionShops;
        //所有短信模板
        $smsmodel = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('status',1)->field('id,mtemplate_name')->select();
        $this->assign('smsmodel',$smsmodel);
        // 出生医院 
        $hospital = controller('crm/Customer','lib')->getHospital();
        $return['hospital'] = $hospital;
        // 入住会所 ，
        $clubData = db("crm_s_club")->where("brandclass_id",session("brandclass_id"))->select();
        $return['clubData'] = $clubData;
        // 医拍摄影师 
        $ypParam['shop_code'] = session('shop_code');
        $ypParam['work_type'] = PZ_WORK_TYPE;
        $photo_cameraman = getShopStaffs($ypParam);
        $return['photo_cameraman'] = $photo_cameraman;
        // 医拍摄影助理 
        $zlParam['shop_code'] = session('shop_code');
        $zlParam['work_type'] = SYZL_WORK_TYPE;
        $photo_assistant = getShopStaffs($zlParam);
        $return['photo_assistant'] = $photo_assistant;
        // 宝宝性别
        $baby_sex = config('baby_sex');
        if(empty($baby_sex)){
            $baby_sex = [
                ['sex'=>'男',],['sex'=>'女',],
            ];
        }
        $return['baby_sex'] = $baby_sex;
        //上海优尼克定制
        if(customize('shynk')){
            //意向套系
            $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);        
            $orderInfo = $erpInterface->getCreateOrderInfo(['shop_code'=>session('shop_code')]);
            $orderInfo['dt_s_packageset'] = my_sort($orderInfo['dt_s_packageset'],'package_price','SORT_ASC');
            $return['package'] = $orderInfo['dt_s_packageset'];

            // 三级渠道 单独 提取
            // $customer_channel = controller('crm/Setting','lib')->getChannelByCid();
            // $return['customer_channel'] = $customer_channel;

            // //客户分区
            // $area = controller('crm/Customer','lib')->areaSets();
            // $return['area'] = $area;
        }
        // 客资状态 有效无效等
        $validArr = [];
        if(check_right('menu1546854995')){
            $temp['id']  = 1;
            $temp['name']= '有效';
            $temp['sele']= 0;
            $validArr[] = $temp;
        }
        // 标记待定
        $temp['id']  = 2;
        $temp['name']= '待定';
        $temp['sele']= 0;
        $validArr[] = $temp;
        // 标记无效
        if(check_right('menu1517129331')){
            $temp['id']  = 3;
            $temp['name']= '无效';
            $temp['sele']= 0;
            $validArr[] = $temp;
        }
        $return['validArr'] = $validArr;
        // 追踪标记
        $mark=controller("crm/Customer","lib")->markSet(array('shop_code'=>session('shop_code')));
        $return['mark'] = $mark;
        // 追踪阶段
        $selesStep = controller('crm/Customer','lib')->get_seles_step();
        $return['selesStep'] = $selesStep;
        // 客资标签
        $cat = cache('label_'.session('brandclass_id'));
        if(empty($cat)){
            $cat = db('crm_s_label_cat')->where('brandclass_id',session('brandclass_id'))->where('status',2)->select();
            foreach($cat as $k=>$v){
                $cat[$k]['cat_name'] = $v['cat_name'];
                $cat[$k]['label'] = db('crm_s_label')->where('brandclass_id',session('brandclass_id'))->where('label_cat_id',$v['id'])->where('is_delete',2)->select();
                if(empty($cat[$k]['label'])){
                    unset($cat[$k]);
                }
            }
            cache('label_'.session('brandclass_id'),$cat);
        }
        $return['cat'] = $cat;
        // 驳回原因
        $reject = db('crm_s_reject_reason')->where('shop_code',session('shop_code'))->select();
        $return['reject'] = $reject;
        // 不再追踪原因
        $noTrackReason = db('crm_s_file_reason')->where('shop_code',session('shop_code'))->select();
        $return['noTrackReason'] = $noTrackReason;
        //省
        $province = controller('crm/Customer','lib')->address(['type'=>1,'shop_code'=>session('shop_code')]);
        $return['province'] = $province;

        //可操作店(拍照店)
        $mc = new \app\common\lib\mcInterface();
        $return['shops'] = $mc->getShopInfo(['shop_code'=>session('work_shop'),'is_photo'=>1]);

        return json(['code'=>200,'msg'=>'','data'=>$return]);
    }
    //客资列表、查询
    public function customerList(){
        if(Request::instance()->isAjax()){
            
            $data = input();
            // var_dump($data);
            // exit;
            // 客资状态
            $is_valid = $data['is_valid'] ? $data['is_valid'] : '1,2,3,4,5';
            cookie('valid', $is_valid);
            
            // var_dump($arr);
            // exit;
            // 客资爆破 
            // if($data['tab'] == 100){
            //     $detail=controller("Customer","lib")->customerListData_bp($data);
            // }
            // else{
            //     // if ($data['']) {
            //     //     # code...
            //     // }
            //     $detail=controller("Customer","lib")->customerListData($data);
            // }
            if (!$data['tab']) {
                $auth=getAuth($type='auth');
                $menuCode= array_column($auth,'menu_code');
                $allRab = [//客资列表的tab
                    'menu1512698495',//全部     1
                    'menu1524450329',//今日需追踪    17
                    'menu1512698635',//未分配   3
                    'menu1512698552',//未追踪   2
                    'menu1564454831',//孕妈追踪 21
                    'menu1564454848',//出生追踪 22
                    'menu1564454860',//满月追踪 23
                    'menu1564454873',//百天追踪 24
                    'menu1564454884',//半岁追踪 25
                    'menu1564454900',//周岁追踪 26
                    'menu1512698717',//已订单   5
                    'menu1513395549',//不再追踪 7
                ];
                $allRab = array_intersect($allRab,$menuCode);
                if (in_array('menu1512698495',$allRab)) {
                    $data['tab'] = '1';
                }else if (in_array('menu1524450329',$allRab)) {
                    $data['tab'] = '17';
                }else if (in_array('menu1512698635',$allRab)) {
                    $data['tab'] = '3';
                }else if (in_array('menu1512698552',$allRab)) {
                    $data['tab'] = '2';
                }else if (in_array('menu1564454831',$allRab)) {
                    $data['tab'] = '21';
                }else if (in_array('menu1564454848',$allRab)) {
                    $data['tab'] = '22';
                }else if (in_array('menu1564454860',$allRab)) {
                    $data['tab'] = '23';
                }else if (in_array('menu1564454873',$allRab)) {
                    $data['tab'] = '24';
                }else if (in_array('menu1564454884',$allRab)) {
                    $data['tab'] = '25';
                }else if (in_array('menu1564454900',$allRab)) {
                    $data['tab'] = '26';
                }else if (in_array('menu1512698717',$allRab)) {
                    $data['tab'] = '5';
                }else if (in_array('menu1513395549',$allRab)) {
                    $data['tab'] = '7';
                }
            }

            if ($data['tab'] == 7) {
                $data['is_loss'] = 1;
            }
            // var_dump($data);die;
            $detail=controller("crm/Customer","lib")->customerListData($data);
            echo json_encode($detail);
        }else{
            //优尼可定制内容是否显示
            $this->assign('is_shynk',customize('shynk')?1:2);
            //南宁qqbaby定制内容是否显示
            $this->assign('is_nnqqbaby',customize('nnqqbaby')?1:2);

            //从客户管理中链接过来，查看某条客资信息
            $client_customer_id = input('client_customer_id');
            $this->assign('client_customer_id',$client_customer_id?$client_customer_id:0);

            $menu = include(APP_PATH.'menu.php');
            $menuCustomize = include(APP_PATH.'menu_customize.php');
            $auth = getAuthMenu($menu,'auth',$menuCustomize);

            //查看是否有客资列表的权限 2020-08-07
            if (!check_right('menu1512735953')) {
                $this->redirect("/crm/Customer/prompt?msg=您的账户现在没有权限，请您联系管理员跟您分配对应的权限，重新登录进入系统使用。");
                // $res = getAuthMenu($menu,'menu',$menuCustomize);
                // $redirect_url = '';
                // if (count($res['list']) > 0) {
                //     foreach ($res['list'] as $key => $value) {
                //         if ($value['status'] == 1) {
                //             $redirect_url = $value['menu_url'];break;
                //         }
                //     }
                // }
                // if (strlen($redirect_url) > 0) {
                //     $this->redirect($redirect_url);
                // }else{
                //     $this->redirect("/crm/Customer/prompt?msg=您的账户现在没有权限，请您联系管理员跟您分配对应的权限，重新登录进入系统使用。");
                // }
            }            

            //查看一年内客资
            if(check_right('menu1546854888') && session('main_work_type') != 22){
                $this->assign('yearCus',1);
            }else{
                $this->assign('yearCus',0);
            }

            // $auth=getAuth($type='auth');
            $newAuth = controller('crm/Setting','lib')->arrayDuoZhuanEr($auth['list']);
            $menuCode= array_column($newAuth,'menu_code');
            
            // var_dump($menuCode);die;
            $allRightMenu = [//要控制的所有右键菜单
                'menu1512971662',//客资追踪
                'menu1519631971',//右键-客资标记
                'menu1519635403',//右键-筛客
                'menu1519632099',//右键-追踪标记
                'menu1519633870',//右键-预约进店
                'menu1519633923',//右键-转订单
                'menu1519633959',//右键-编辑订单
                'menu1520675106',//右键-撤销
                'menu1522653972',//右键-介绍人修改
                'menu1519633436',//右键-不再追踪
                // 'menu1517129299',//标有效
                'menu1546854995',//标有效
                'menu1517129331',//标无效
                'menu1517278817',//客资驳回
                'menu1517278844',//客资反驳回
                'menu1512971646',//发送短信
                'menu1512970623',//客资分配
                'menu1512970667',//修改客资
                'menu1512970570',//删除客资
                'menu1571906153',//预约上门
            ];
            //预约进店控制 设置在 追踪配置 里 进店
            if (db_config('enterGuest') != 1) {
                unset($allRightMenu[4]);//menu1519633870
            }
            // 查询是否为某组的管理员  20200613
            $mc = new \app\common\lib\mcInterface();
            $gParam['brandclass_id'] = session('brandclass_id') ? session('brandclass_id') : NULL;
            $gParam['shop_code'] = session('shop_code') ? session('shop_code') : NULL;
            if ($gParam['shop_code']) {
                $gParam['department_id'] = NULL;
            }else{
                $gParam['department_id'] = session('department_id') ? session('department_id') : NULL;
            }
            $gParam['staff_id'] = session('staff_id');
            $groupInfo = $mc->getGroupInfo($gParam);
            // var_dump($groupInfo);
            // die;
            if ($groupInfo) {
                $this->assign('group',1);
            }else{
                $this->assign('group',0);
            }
            $rightMenuList = array_intersect($allRightMenu,$menuCode);
            $this->assign('right_menu_list', $rightMenuList);
            $allRab = [//客资列表的tab
                'menu1512698495',//全部
                'menu1524450329',//今日需追踪
                'menu1512698635',//未分配
                'menu1512698552',//未追踪
                'menu1564454831',//孕妈追踪
                'menu1564454848',//出生追踪
                'menu1564454860',//满月追踪
                'menu1564454873',//百天追踪
                'menu1564454884',//半岁追踪
                'menu1564454900',//周岁追踪
                'menu1512698717',//已订单
                'menu1513395549',//不再追踪
            ];
            $allRab = array_intersect($allRab,$menuCode);
            if (in_array('menu1512698495',$allRab)) {
                $this->assign('this_tab','menu1512698495');
            }else if (in_array('menu1524450329',$allRab)) {
                $this->assign('this_tab','menu1524450329');
            }else if (in_array('menu1512698635',$allRab)) {
                $this->assign('this_tab','menu1512698635');
            }else if (in_array('menu1512698552',$allRab)) {
                $this->assign('this_tab','menu1512698552');
            }else if (in_array('menu1564454831',$allRab)) {
                $this->assign('this_tab','menu1564454831');
            }else if (in_array('menu1564454848',$allRab)) {
                $this->assign('this_tab','menu1564454848');
            }else if (in_array('menu1564454860',$allRab)) {
                $this->assign('this_tab','menu1564454860');
            }else if (in_array('menu1564454873',$allRab)) {
                $this->assign('this_tab','menu1564454873');
            }else if (in_array('menu1564454884',$allRab)) {
                $this->assign('this_tab','menu1564454884');
            }else if (in_array('menu1564454900',$allRab)) {
                $this->assign('this_tab','menu1564454900');
            }else if (in_array('menu1512698717',$allRab)) {
                $this->assign('this_tab','menu1512698717');
            }else if (in_array('menu1513395549',$allRab)) {
                $this->assign('this_tab','menu1513395549');
            }
            
            $is_valid = cookie('valid') ? cookie('valid') : '1,2,3,4,5';
            $is_valid = explode(',', $is_valid);
            $this->assign('valid', $is_valid);
            // $data = input();
            // if($data['id']){
            //     $this->assign("cid",$data['id']);
            // }

            //客资转移用
            $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>session('shop_code')]);
            $this->assign('staff',$staff);
            //来源渠道
            $channel = getChannelJson(session('shop_code'));
            $this->assign("channel", json_encode($channel));
            //客户来源
            $source=controller("Customer","lib")->source(array('shop_code'=>session('shop_code')));

            $this->assign("source",$source);
            //获取方式
            //$accessModel=controller("Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
            //$this->assign("accessModel",$accessModel);
            //客户意向
            $intention=controller("Customer","lib")->intention(array('shop_code'=>session('shop_code')));
            $this->assign("intention",$intention);
            $this->assign("intention1",$intention);
            //消费类型
            $consumptionType=controller("Customer","lib")->consumptionType();
            $this->assign("consumptionType",$consumptionType);
            //客资地域
            $region=controller("Customer","lib")->region(array('shop_code'=>session('shop_code')));
            $this->assign("region",$region);
            //分区
            $area=controller("Customer","lib")->areaSet(array('shop_code'=>session('shop_code')));
            $this->assign("area",$area);
            //追踪标记
            $mark=controller("Customer","lib")->markSet(array('shop_code'=>session('shop_code')));
            $this->assign("mark",$mark);
            $this->assign("mark1",$mark);
            //客户标记
            $sign=controller('crm/Setting','lib')->gettrackingKmarkerList();
            $this->assign("sign",$sign);
            //意向店面
            $intentionShop=controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass'),'is_marketing'=>2));
            $this->assign('intentionShop',$intentionShop);
            //消费能力
            $capacity=controller("Customer","lib")->capacity(array('shop_code'=>session('shop_code')));
            $this->assign("capacity",$capacity);
            //所有已成单客资
            //$customer_name=db('crm_c_customerinfo')->where(array('is_success'=>1))->select();
            //$this->assign("customers",$customer_name);
            //客户地址
            $data['type']=1;
            $address=controller("Customer","lib")->address($data);
            $this->assign("address",$address);
            //登录人搜索下拉框 根据权限显示
            if(check_right('menu1512637269')){
                if(session('is_belong')==1){
                    $staff_list=controller("Customer","lib")->get_staff_lists();
                }elseif(session('is_belong')==2){
                    $staff_list=controller("Customer","lib")->get_staff_lists(array('brandclass'=>session
                    ('brandclass')));
                }elseif(session('is_belong')==3||session('is_belong')==4){
                    $staff_list=controller("Customer","lib")->get_staff_lists(array('shop_code'=>session('shop_code')));
                }
            }

            $this->assign("staff_list",$staff_list);
            //短信模板
            $mod = controller("crm/Setting","lib")->getModalToJSON();
            $this->assign("model",$mod['data']);
            //追踪阶段
            $seles = controller('crm/Customer','lib')->get_seles_step();
            $this->assign("seles",$seles);
            $this->assign("seless",$seles);
            //追踪失败原因
            $reason = controller('crm/Customer','lib')->get_reason();
            $this->assign("reason",$reason);
            //呼叫前缀
            $prefix = controller('crm/Customer','lib')->getCallPrefix();
            $this->assign("prefix",$prefix);
            //应用是否安装
            $this->assign('is_install',is_install('sx_erp'));
            $this->assign('title','客资');
            //品牌下的店面
            $shops = controller('crm/Customer','lib')->getShopInfo(['brandclass_id'=>session('brandclass_id')]);
            $this->assign('shops',$shops['data']);
            
            $menu=getAuth($type='auth');
            $this->assign('menu',$menu);

            $custom = $this->getCustomColumn();

            $check_list = db_config('shop_column_name_'.session('shop_code'));//店面自定义列
            $check_list = strlen($check_list)>0 ? explode(',',trim($check_list,',')) :  [];
            $column = db_config('shop_column_'.session('shop_code'));//店面自定义列
            $column = strlen($column)>0 ? explode(',',trim($column,',')) :  [];

            $this->assign('colModel',$custom['custom_model'] ? json_decode($custom['custom_model'],true) : json_encode($column));
            $this->assign('colNames',$custom['custom_name'] ? json_decode($custom['custom_name'],true) : json_encode($check_list));

            //列表页搜索项隐藏配置
            $search = db_config('list_search_hidden_'.session('brandclass_id'));
            if($search){
                $search = explode(',',$search);
            }
            $this->assign('search_list',$search);

            //检查当前店是否开启爆破活动，并且活动已开始，在有效时间内
            $is_bp = db('crm_s_swapset')
                ->where('shop_code',session('shop_code'))
                ->where('status',2)
                ->where('start_date','<=',date('Y-m-d'))
                ->where('end_date','>=',date('Y-m-d'))
                ->value('id');
            // echo db()->getLastSql();
            // exit;
            $this->assign('is_bp',$is_bp);
            //客资无效原因
            $unValidReason = controller('crm/Customer','lib')->getUnValidReason();
            $this->assign('unValidReason',$unValidReason);
            //呼叫中心
            if(db_config('call_id')){
                $call = db('crm_s_call_center')->where('id',db_config('call_id'))->find();
                $this->assign('callCenter',$call);
                $callMan = db('crm_s_call_man')->where('staff_id',session('staff_id'))->find();
                $this->assign('callMan',$callMan);
            }
            // $this->assign('callCenter',config('call_center'));
            //要在登录时放点session或cookie里
            // $this->assign('callCenter','shenou');//要在登录时放点session或cookie里

            // $this->assign('is_swap', $is_swap);
            //颜色
            // 2020-08-05 去掉列表页选中颜色 2020-08-05 列表页鼠标跟随颜色
            // $on_select_color = db_config('on_select_color');
            // $this->assign('on_select_color',$on_select_color ? $on_select_color : 'ffd7dc');
            // $hover_color = db_config('hover_color');
            // $this->assign('hover_color',$hover_color ? $hover_color : 'ffe1c9');
            $service_end = db_config('service_end');
            $this->assign('service_end',$service_end);
            $service_start = db_config('service_start');
            $this->assign('service_start',$service_start);
            $service_no = db_config('service_no');
            $this->assign('service_no',$service_no);
            // 2020-08-05 去掉隔行变色
            // $alt_row_color = db_config('alt_row_color');
            // $this->assign('alt_row_color',$alt_row_color);
            $success_color = db_config('success_color');
            $this->assign('success_color',$success_color);
            $into_color = db_config('into_color');
            $this->assign('into_color',$into_color);
            $loss_color = db_config('loss_color');
            $this->assign('loss_color',$loss_color);
            $erp_loss_color = db_config('erp_loss_color');
            $this->assign('erp_loss_color',$erp_loss_color);
            $int_no_suc_color = db_config('int_no_suc_color');
            $this->assign('int_no_suc_color',$int_no_suc_color);
            $yy_no_into_color = db_config('yy_no_into_color');
            $this->assign('yy_no_into_color',$yy_no_into_color);
            $bh_color = db_config('bh_color');
            $this->assign('bh_color',$bh_color);
            $bh_color_fan = db_config('bh_color_fan');
            $this->assign('bh_color_fan',$bh_color_fan);
            $unvalid_color = db_config('unvalid_color');
            $this->assign('unvalid_color',$unvalid_color);
            $urgent_color = db_config('urgent_color');
            $this->assign('urgent_color',$urgent_color);
            $color = salesSignColor();
            $this->assign('color',json_encode($color));
            $sign_color = signColor();
            $this->assign('sign_color',json_encode($sign_color));
            //电访必选项配置
            $dfMust = db_config('df_must_'.session('brandclass_id'));
            $dfMust = trim($dfMust,',');
            $dfMust = explode(',',$dfMust);
            $this->assign('dfMust',json_encode($dfMust));
            //客资重复审核配置
            $examine= db_config('cus_examine_'.session('shop_code'));
            $this->assign('examine',$examine);
            if(customize('nnqqbaby')){
                $max_into_day = db_config('max_into_day_'.session('shop_code'));
                // $max_into_day_date = date('Y-m-d',strtotime('+'.$max_into_day.' day'));
                $this->assign('max_into_day',$max_into_day);
            }
            $b_is_sk = controller("crm/Customer", "lib")->is_sk(session('belong_shop_code'));
	        // 客资提归属店或者当前店开启筛客
	        if($b_is_sk == 1 || session('is_sk') == 1){
	            $this->assign('isSk',true);
	        }else{
	            $this->assign('isSk',false);
	        }
            //列表页时间
            $list_date = db_config('list_date');
            if($list_date == 'week'){
                $start = date('Y-m-d',strtotime('-1 week'));
                $end=date('Y-m-d');
            }elseif($list_date == 'day'){
                $start=date('Y-m-d');
                $end=date('Y-m-d');
            }else{
                $start=date('Y-m-01');
                $end=date('Y-m-d');
            }
            if(ini('search.fullmobile')){
                $this->assign('fullmobile',1);
            }
            $this->assign('start',$start);
            $this->assign('end',$end);
            // 新版新增客资页面 开始 20200928
            	// 填写日期 默认今天
            	if ( db_config('record_day_'.session('shop_code'))=='today' ) {
            		$this->assign('record_day', date('Y-m-d'));
            	}else{
            		$this->assign('record_day', '');
            	}
                // 录入客资必选项
                $this->assign('lrMust',$this->getLrMust());
                // 录入必选项定制 录入时显示 20200106

                if (ini('lr_must.shop_code')==session('shop_code')) {
                    // 判断字段是否存在
                    $column = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>ini('lr_must.field')));
                    if ($column) {
                        $select = explode(',', ini('lr_must.select'));
                        $this->assign("xaf_field1",ini('lr_must.field'));
                        $this->assign("xaf_fieldname1",ini('lr_must.fieldname'));
                        $this->assign("xaf_select1",$select);
                    }
                }

                // 录入客资隐藏项
                $lrHidden = getLrHidden(session('brandclass_id'));
                $this->assign('lrHidden',$lrHidden);
                // 先暂时这样 后面想想有没有其他的办法 
                $allLrSelect = [
                    'channel_info',// 来源渠道
                    'customer_channel',// 渠道名称
                    'access_model',// 获取方式
                    'consultation_type',// 消费类型
                    'customer_intention',// 客户意向
                    'customer_cource',// 客户来源
                    'tracksign',// 客资标记
                    'recommend_staff',// 推广人
                    'consulation_shop',// 意向店面
                    'is_valid',// 客资状态
                    'baby_address',// 出生医院
                    'hospital_photo_cameraman',// 医拍摄影师
                    'hospital_photo_assistant',// 医拍助理
                    'club_name',// 入住会所
                ];
                foreach ($allLrSelect as $key => $value) {
                    if ( in_array($value, $lrHidden) ) {
                        unset($allLrSelect[$key]);
                    }
                }
                $allLrSelect = implode(',', $allLrSelect);
                $this->assign('all_lr_select',$allLrSelect);
                // 标记有效 客资状态 是否隐藏 应该根据当前 员工的权限
                $validArr = [];
                if(check_right('menu1546854995')){
                    $temp['id']  = 1;
                    $temp['name']= '有效';
                    $temp['sele']= 0;
                    $validArr[] = $temp;
                }
                // 标记待定
                $temp['id']  = 2;
                $temp['name']= '待定';
                $temp['sele']= 0;
                $validArr[] = $temp;
                // 标记无效
                if(check_right('menu1517129331')){
                    $temp['id']  = 3;
                    $temp['name']= '无效';
                    $temp['sele']= 0;
                    $validArr[] = $temp;
                }
                $this->assign('validArr',$validArr);
                // 宝宝性别
                $baby_sex = config('baby_sex');
                if(empty($baby_sex)){
                    $baby_sex = [
                        ['sex'=>'男',],['sex'=>'女',],
                    ];
                }
                $this->assign('baby_sex',$baby_sex);
                //客户地址
                $addrParam['type']=1;
                $addrParam['shop_code']=session('shop_code');
                $province=controller("crm/Customer","lib")->address($addrParam);
                if (count($province)==1) {
                    $province[0]['selected']=1;
                    //城市
                    $data['type']=2;
                    $data['pid'] =$province[0]['id'];
                    $city=controller("crm/Customer","lib")->address($data);
                    $this->assign("city",$city);
                    unset($data);
                }
                $this->assign("province",$province);
                // 客资录入类型  查看设定
                $customer_type = explode(',', db_config('customer_type_'.session('shop_code')));
                $only = '';
                foreach ($customer_type as $key => $value) {
                    if (!$value) { // 如果没有设定
                        $mc = new \app\common\lib\mcInterface();
                        $shopInfo = $mc->getShopInfo(array('shop_code' => session('shop_code')));
                        if ($shopInfo[0]['is_dig'] == 1) { // 如果是转介绍客资接入店
                            $only = '2';
                        }else{ // 只有新客资，没有转介绍
                            $only = '1'; 
                        }
                    }else{
                        $only .= $value.',';
                    }
                }
                $only = trim($only,',');
                if ($only == '1') {
                    $only = 'new';
                }else if ($only == '2') {
                    $only = 'zjs';
                }else{
                    $only = 'all';
                }
                $this->assign('only', $only);
                // 介绍人是否可输入
                $mobile_input = db_config('mobile_input_'.session('shop_code'));
                $this->assign("mobile_input",$mobile_input);
                // babypastel 录转介绍客资的时候 可以录入渠道
                $babypastel = customize('babypastel');
                // var_dump($babypastel);die;
                if ($babypastel) {
                    $this->assign('babypastel','1');
                }else{
                    $this->assign('babypastel','2');
                }
                // 判断南宁定制
                $nnqqbaby = customize('nnqqbaby');
                if ($nnqqbaby) {
                    $this->assign('nnqqbaby','1');
                }else{
                    $this->assign('nnqqbaby','2');
                }
                // 判断石家庄时光定制
                if (customize('sjzsgbaby')) {
                    $this->assign('sjzsgbaby','1');
                }else{
                    $this->assign('sjzsgbaby','2');
                }
                // 输出页面
               // $this->assign('add_new_child_customer_page',$this->fetch('add_new_child_customer'));
            // 新版新增客资页面 结束

            // 新版 电访 页面 开始 20201022
                //追踪必选项配置
                $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);

                // 2021-04-15 上海优尼可 crm客资列表查询项客资渠道控件修改为列出3级客资的下拉框并支持搜索
                if (customize('shynk')) {
                    $customer_channel = controller('crm/Setting','lib')->getChannelByCid();
                    $this->assign('customer_channel',$customer_channel);
                }

                // 客资标签
                $cat = cache('label_'.session('brandclass_id'));
                if(empty($cat)){
                    $cat = db('crm_s_label_cat')->where('brandclass_id',session('brandclass_id'))->where('status',2)->select();
                    foreach($cat as $k=>$v){
                        $cat[$k]['cat_name'] = $v['cat_name'];
                        $cat[$k]['label'] = db('crm_s_label')->where('brandclass_id',session('brandclass_id'))->where('label_cat_id',$v['id'])->where('is_delete',2)->select();
                        if(empty($cat[$k]['label'])){
                            unset($cat[$k]);
                        }
                    }
                    cache('label_'.session('brandclass_id'),$cat);
                }
                // var_dump($cat);
                // exit;
                $this->assign('cat',$cat);


                // 输出页面
                $this->assign('dianfang_new',$this->fetch('dianfang_new'));
                // var_dump($this->fetch('dianfang_new'));die;

            //2021-07-21
            $list_customerinfo_refreshnumber = db_config('list_customerinfo_refreshnumber') ?: 2;
            $this->assign('list_customerinfo_refreshnumber',$list_customerinfo_refreshnumber);

            //2021-07-26 消息带有url地址 客资id数据
            $this->assign('tk_k',input('get.k'));
            $this->assign('tk_id',input('get.id'));


            // 新版新增客资页面 结束
            return view('customer_child');
        }
    }
    // 新版新增客资界面
    public function add_new_child_customer(){
        return $this->fetch();
    }
    // 获取客资录入 必选项
    public function getLrMust(){
        return getLrMust(session('brandclass_id'),session('shop_code'));
    }
    
    // 录入专用  当前账号的可操作店 作为 登记店面、部门、组、人  根据登记店面获取 追踪店面、部门、组、人 20200929
    public function getLrSystemStaffs($param=[]){
        $param = $param ? $param : input();
        // 登记店面 取 当前账号的可操作店
        $djParam = [
            'staff_id'=> session('staff_id'),
            'brandclass_id'=> session('brandclass_id'),
            'shop_type' => session('shop_type')
        ];
        $tempShops = getShops($djParam);
        $djShops = [];
        $shop_code = [];//追踪店面
        foreach ($tempShops as $k => $v) {
            $temp['shop_code'] = $v['shop_code'];
            $temp['shop_name'] = $v['shop_name'];
            if (cookie('add_shop_code') && cookie('add_shop_code')==$v['shop_code']) {
                $temp['selected']  = 1;
                $add_shop_code = $v['shop_code'];
                $add_shop_name = $v['shop_name'];
            }else if (!cookie('add_shop_code') && session('shop_code')==$v['shop_code']) {
                $temp['selected']  = 1;
                $add_shop_code = $v['shop_code'];
                $add_shop_name = $v['shop_name'];
            }else{
                $temp['selected']  = 0;
            }
            $djShops[] = $temp;
            $temp = [];
        }
        $data['djShops'] = $djShops;
        // 如果存在选中的登记店面 需要 该店下的 部门
        if ($add_shop_code) {
            // var_dump(cookie('dj_department_id'));die;
            // 登记部门
            $tempDepartment = $this->getDList(['shop_code'=>$add_shop_code]);
            $djDepartments = [];
            foreach ($tempDepartment as $k => $v) {
                $temp['department_id'] = $v['id'];
                $temp['department_name'] = $v['department_name'];
                if (
                    cookie('dj_department_id') 
                    && cookie('dj_department_id')==$v['id']
                    && $add_shop_code == $v['shop_code']
                ) {
                    $temp['selected']  = 1;
                    $djDepartmentId = $v['id'];
                }else if (
                    !cookie('dj_department_id') 
                    && session('department_id')==$v['id']
                    && $add_shop_code == $v['shop_code']
                ) {
                    $temp['selected']  = 1;
                    $djDepartmentId = $v['id'];
                }else{
                    $temp['selected']  = 0;
                }
                $djDepartments[] = $temp;
                $temp = [];
            }
            $data['djDepartments'] = $djDepartments;
            // 该店下所有人 包括兼职
            if($djDepartmentId){
                $tempStaffs = controller('crm/Customer','lib')->getShopAllStaff( ['shop_code'=>$add_shop_code,'department_id'=>$djDepartmentId] );
            }else{
                $tempStaffs = controller('crm/Customer','lib')->getShopAllStaff( ['shop_code'=>$add_shop_code] );
            }
            $djStaffs = [];
            foreach ($tempStaffs as $k => $v) {
                if($djDepartments)
                $temp['staff_id']  = $v['id'];
                $temp['staff_name']= $v['staffname'];
                if (cookie('dj_staff_id') && cookie('dj_staff_id')==$v['id']) {
                    $temp['selected']  = 1;
                }else if (!cookie('dj_staff_id') && session('staff_id')==$v['id']) {
                    $temp['selected']  = 1;
                }else{
                    $temp['selected']  = 0;
                }
                $djStaffs[] = $temp;
                $temp = [];
            }
            $data['djStaffs'] = $djStaffs;

            //计算归属店
            $shop_code = getBelongShopList($add_shop_code,$param['customer_type']);
            if(!$shop_code){
                $shop_code = [
                    [
                        'shop_code'=>$add_shop_code,
                        'shop_name'=>$add_shop_name,
                    ]
                ];
            }
        }
        unset($tempShops,$tempDepartment,$tempStaffs,$temp);
        
        $salesDepartment = [];
        $salesStaffs = [];

        /*

        if(session('belong_shop_code')){
            // mc设置了归属店面 追踪店面
            $shop_code[0]['shop_code'] = session('belong_shop_code');
            $shop_code[0]['shop_name'] = session('belong_shop_name');
            $shop_code[0]['selected'] = 1;
            // 追踪部门
            // $tempDepartment = $this->getDList(['shop_code'=>session('belong_shop_code')]);
        } else {
            // crm设定的归属店
            $checked_shop = db_config('dj_shops_'.session('shop_code'));
            if (!empty($checked_shop)) {
                foreach ($checked_shop as $key => $value) {
                    $shop_code[$key] = $value;
                }
            }else{
                $shop_code[0]['shop_code'] = session('shop_code');
                $shop_code[0]['shop_name'] = session('shop_name');
                $shop_code[0]['selected'] = 1;
                /*
                // 追踪部门
                $tempDepartment = $this->getDList(['shop_code'=>session('shop_code')]);
                // 追踪人
                $salesParam['shop_code'] = session('shop_code');
                $salesParam['work_type'] = RECEIVE_WORK_TYPE;
                $salesParam['all'] = 2;
                $tempStaffs = getShopStaffs($salesParam);
                
            }
        }
        */
        //如果有归属店，同时还有选中的店，则会取部门和人员。
        if($shop_code){
            foreach ($shop_code as $key => $value) {
                if($value['selected']){
                    $tempDepartment = $this->getDList(['shop_code'=>$value['shop_code']]);
                    // 追踪人
                    $salesParam['shop_code'] = $value['shop_code'];
                    $salesParam['work_type'] = RECEIVE_WORK_TYPE;
                    $salesParam['all'] = 2;
                    $tempStaffs = getShopStaffs($salesParam);
                    break;
                }
            }
        }
        // 格式化返回的部门数据
        if ($tempDepartment) {
            foreach ($tempDepartment as $k => $v) {
                $temp['department_id'] = $v['id'];
                $temp['department_name'] = $v['department_name'];
                $salesDepartment[] = $temp;
                $temp = [];
            }
            // 如果只有一个部门 默认选中 
            if (count($salesDepartment)==1) {
                $salesDepartment[0]['selected'] = 1;
                $tempStaffs = $this->getDepartmentStaffs($tempDepartment[0]['id']);
            }
        }
        if ($tempStaffs) {
            foreach ($tempStaffs as $k => $v) {
                $temp['staff_id'] = $v['id'];
                $temp['staff_name'] = $v['staffname'];
                $salesStaffs[] = $temp;
                $temp = [];
            }
        }
        //上海优尼克定制
        if(customize('shynk')){
            //意向套系
            $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);        
            $orderInfo = $erpInterface->getCreateOrderInfo(['shop_code'=>session('shop_code')]);
            $orderInfo['dt_s_packageset'] = my_sort($orderInfo['dt_s_packageset'],'package_price','SORT_ASC');
            $data['package'] = $orderInfo['dt_s_packageset'];
        }
        $data['shopCode'] = $shop_code;
        $data['salesDepartment'] = $salesDepartment;
        $data['salesStaffs'] = $salesStaffs;

        return json(['code'=>200,'msg'=>'','data'=>$data]);
    }
    // 获取各个下拉框的值
    public function getSelectData($param=[]){
        $param = $param ? $param : input();
        $type = $param['selectType'];
        $typeArr = explode(',', $type);
        foreach ($typeArr as $k => $v) {
            switch ($v) {
                // 二级渠道 来源渠道 
                case 'channel_info_id':
                    $erChannel = controller("crm/Customer","lib")->getErChannel($add_shop_code);
                    $return['erChannel'] = $erChannel;
                    break;
                // 三级渠道 渠道名称
                case 'customer_channel_id':
                    $channel = controller("crm/Customer","lib")->getChannel($add_shop_code);
                    $return['channel'] = $channel;
                    break;
                // 获取方式 是否隐藏
                case 'access_model':
                    $accessModel=controller("crm/Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
                    $return['accessModel'] = $accessModel;
                    break;
                // 消费类型 是否隐藏  不从mc里取了，取erp的设定
                case 'consultation_type':
                    $consumptionType = controller("crm/Customer","lib")->consumptionType();
                    $return['consumptionType'] = $consumptionType;
                    break;
                // 客户意向 是否隐藏
                case 'customer_intention':
                    $intention=controller("crm/Customer","lib")->intention(array('shop_code'=>session('shop_code')));
                    $return['intention'] = $intention;
                    break;
                // 客户来源 是否隐藏
                case 'customer_cource':
                    $source = controller("crm/Customer","lib")->source(array('shop_code'=>session('shop_code')));
                    $return['source'] = $source;
                    break;
                // 客资标记 是否隐藏
                case 'tracksign':
                    $tracksign=controller("crm/Setting","lib")->gettrackingKmarkerList();
                    $return['tracksign'] = $tracksign;
                    break;
                // 推广人 是否隐藏
                case 'recommend_staff':
                    $tgParam['shop_code'] = session('shop_code');
                    $tgParam['work_type'] = KZTB_WORK_TYPE;
                    $tgParam['all'] = 2;
                    $recommendStaff = getShopStaffs($tgParam);
                    $return['recommendStaff'] = $recommendStaff;
                    break;
                // 意向店面 是否隐藏
                case 'consulation_shop':
                    $shops = controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass'),'is_marketing'=>2));
                    $return['shops'] = $shops;
                    break;
                // 出生医院 是否隐藏
                case 'baby_address':
                    $hospital = controller('crm/Customer','lib')->getHospital();
                    $return['hospital'] = $hospital;
                    break;
                // 入住会所 ，是否隐藏
                case 'club_name':
                    $clubData = db("crm_s_club")->where("brandclass_id",session("brandclass_id"))->select();
                    $return['clubData'] = $clubData;
                    break;
                // 医拍摄影师 ，是否隐藏
                case 'photo_cameraman':
                    $ypParam['shop_code'] = session('shop_code');
                    $ypParam['work_type'] = PZ_WORK_TYPE;
                    $photo_cameraman = getShopStaffs($ypParam);
                    $return['photo_cameraman'] = $photo_cameraman;
                    break;
                // 医拍摄影助理 ，是否隐藏
                case 'photo_assistant':
                    $zlParam['shop_code'] = session('shop_code');
                    $zlParam['work_type'] = SYZL_WORK_TYPE;
                    $photo_assistant = getShopStaffs($zlParam);
                    $return['photo_assistant'] = $photo_assistant;
                    break;
            }
        }
        return json(['code'=>200,'msg'=>'','data'=>$return]);
    }
    // 追踪记录 html
    public function traceRecordHtml(){
        $param = input();
        if ((int)$param['id']) {
            $repeat_way = db_config('customer_repeat_method');
            $repeat_way = $repeat_way?$repeat_way:config('repeat_way');
            // $repeat_way = config('repeat_way');
            // 追踪记录
            $trackInfos = controller("crm/Customer","lib")->getCustomerTrackInfos((int)$param['id']);
            // var_dump($trackInfos);die;
            $str = '';
            if ($trackInfos) {
                foreach ($trackInfos as $k => $v) {
                    $str .= '<div class="z_con" style="backgroud-color:#ddd;border: 1px solid #01b88a;">';
                    if ($repeat_way == 'xaf') {
                        $str .= '<div class="z_cc" style="order:1px solid red;">';
                    }else{
                        $str .= '<div class="z_cc" style="height:145px;order:1px solid red;">';
                    }
                    $str .= '<div class="z_left">';
                    // 宝宝姓名div
                    $str .= '<div class="layui-inline zzd">';
                    $str .= '<label class="layui-form-label z_name">宝宝姓名：</label>';
                    $str .= '<div class="layui-input-block z_in">';
                    $str .= '<input type="text" class="cus-input" value="'.$v['baby_name'].'" readonly />';
                    $str .= '</div>';
                    $str .= '</div>';
                    // 宝宝性别 div
                    $str .= '<div class="layui-inline zzd">';
                    $str .= '<label class="layui-form-label z_name">宝宝性别：</label>';
                    $str .= '<div class="layui-input-block z_in">';
                    $str .= '<input type="text" class="cus-input" value="'.$v['baby_sex'].'" readonly />';
                    $str .= '</div>';
                    $str .= '</div>';
                    // 宝宝生日 div
                    $str .= '<div class="layui-inline zzd">';
                    $str .= '<label class="layui-form-label z_name">宝宝生日：</label>';
                    $str .= '<div class="layui-input-block z_in">';
                    if ($v['baby_birthday']) {
                        $str .= '<input type="text" class="cus-input" value="'.date("Y-m-d",strtotime($v['baby_birthday'])).'" readonly />';
                    }else{
                        $str .= '<input type="text" class="cus-input" value="" readonly />';
                    }
                    $str .= '</div>';
                    $str .= '</div>';
                    // 预产期 div
                    $str .= '<div class="layui-inline zzd">';
                    $str .= '<label class="layui-form-label z_name">预产期：</label>';
                    $str .= '<div class="layui-input-block z_in">';
                    if ($v['ready_baby_day']) {
                        $str .= '<input type="text" class="cus-input" value="'.date("Y-m-d",strtotime($v['ready_baby_day'])).'" readonly />';
                    }else{
                        $str .= '<input type="text" class="cus-input" value="" readonly />';
                    }
                    $str .= '</div>';
                    $str .= '</div>';
                    // 客资渠道： div
                    $str .= '<div class="layui-inline zzd">';
                    $str .= '<label class="layui-form-label z_name">客资渠道：</label>';
                    $str .= '<div class="layui-input-block z_in">';
                    $str .= '<input type="text" class="cus-input" value="'.$v['customer_channel'].'" readonly />';
                    $str .= '</div>';
                    $str .= '</div>';
                    // 妈妈姓名 div
                    $str .= '<div class="layui-inline zzd">';
                    $str .= '<label class="layui-form-label z_name">妈妈姓名：</label>';
                    $str .= '<div class="layui-input-block z_in">';
                    $str .= '<input type="text" class="cus-input" value="'.$v['customer_name'].'" readonly />';
                    $str .= '</div>';
                    $str .= '</div>';
                    // 妈妈手机 div
                    $str .= '<div class="layui-inline zzd">';
                    $str .= '<label class="layui-form-label z_name">妈妈手机：</label>';
                    $str .= '<div class="layui-input-block z_in">';
                    $str .= '<input type="text" class="cus-input" value="'.$v['customer_tel'].'" readonly />';
                    $str .= '</div>';
                    $str .= '</div>';
                    if ($repeat_way == 'xaf') {
                        // 获取次数 div
                        $str .= '<div class="layui-inline zzd">';
                        $str .= '<label class="layui-form-label z_name">获取次数：</label>';
                        $str .= '<div class="layui-input-block z_in">';
                        $str .= '<input type="text" class="cus-input" value="'.$v['baby_time'].'" readonly />';
                        $str .= '</div>';
                        $str .= '</div>';
                    }else{
                        // 客资标记 div
                        $str .= '<div class="layui-inline zzd">';
                        $str .= '<label class="layui-form-label z_name">客资标记：</label>';
                        $str .= '<div class="layui-input-block z_in">';
                        $str .= '<input type="text" class="cus-input" value="'.$v['sign_name'].'" readonly />';
                        $str .= '</div>';
                        $str .= '</div>';
                    }
                    $str .= '</div>';
                    // 追踪记录
                    $str .= '<div class="z_right zzd"  style="overflow:auto;margin-left: -45px;">';
                    $str .= '<ul class="layui-timeline">';
                    if ($v['track']) {
                        foreach ($v['track'] as $key => $val) {
                            $str .= '<li class="layui-timeline-item">';
                            $str .= '<div class="layui-timeline-date">&nbsp;</div>';
                            $str .= '<i class="layui-icon layui-timeline-axis"></i>';
                            $str .= '<div class="layui-timeline-content">';
                            $str .= '<div>时间：'.$val['sales_day'].'</div>';
                            $str .= '<div>沟通人员：'.$val['sales_staff'].'</div>';
                            $str .= '<div><div class="layer-photos-demo">备注信息：'.$val['sales_remark'].'</div></div>';
                            if ($val['audio_path']) {
                                $htps = "http://";
                                if (strstr($val['audio_path'], 'https://')) {
                                    $htps='';
                                }
                                $str .= '<audio id="web-sound" controls="controls" src="'.$htps.$val['audio_path'].'">NO<audio>';
                            }
                            $str .= '</div>';
                            $str .= '</li>';
                        }
                    }
                    $str .= '</ul>';
                    $str .= '</div>';
                    $str .= '</div>';
                    $str .= '</div>';
                }
            }
            $return['code'] = 200;
            $return['msg']  = '';
            $return['data'] = $str;
        }else{
            $return['code'] = 100;
            $return['msg']  = '没有客资ID，获取客资信息失败';
            $return['data'] = $param;
        }
        return json($return);
    }
    // 录入客资异步请求下拉框
    public function getcustomeraddselect(){
        // 隐藏项
        $hidden = db_config('lr_hidden_'.session('brandclass_id'));
        $hidden = trim($hidden,',');
        $hidden = explode(',',$hidden);
        // 宝宝性别
        $baby_sex = config('baby_sex');
        if(empty($baby_sex)){
            $baby_sex = [
                ['sex'=>'男',],['sex'=>'女',],
            ];
        }
        $return['baby_sex'] = $baby_sex;
        // 获取方式 是否隐藏
        if ( !in_array('access_model',$hidden) ) {
            $accessModel=controller("crm/Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
            $return['accessModel'] = $accessModel;
        }
        // 消费类型 是否隐藏  不从mc里取了，取erp的设定
        if ( !in_array('consultation_type',$hidden) ) {
            $consumptionType = controller("crm/Customer","lib")->consumptionType();
            $return['consumptionType'] = $consumptionType;
        }
        // 客户意向 是否隐藏
        if ( !in_array('customer_intention',$hidden) ) {
            $intention=controller("crm/Customer","lib")->intention(array('shop_code'=>session('shop_code')));
            $return['intention'] = $intention;
        }
        // 客户来源 是否隐藏
        if ( !in_array('customer_cource',$hidden) ) {
            $source = controller("crm/Customer","lib")->source(array('shop_code'=>session('shop_code')));
            $return['source'] = $source;
        }
        // 客资标记 是否隐藏
        if ( !in_array('sign_name',$hidden) ) {
            $tracksign=controller("crm/Setting","lib")->gettrackingKmarkerList();
            $return['tracksign'] = $tracksign;
        }
        // 推广人 是否隐藏
        if ( !in_array('recommend_staff',$hidden) ) {
            $tgParam['shop_code'] = session('shop_code');
            $tgParam['work_type'] = KZTB_WORK_TYPE;
            $tgParam['all'] = 2;
            $recommendStaff = getShopStaffs($tgParam);
            $return['recommendStaff'] = $recommendStaff;
            // var_dump($recommendStaff);die;
        }
        // 意向店面 是否隐藏
        if ( !in_array('consulation_shop',$hidden) ) {
            $shops = controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass'),'is_marketing'=>2));
            $return['shops'] = $shops;
        }
        // 客资状态 是否隐藏 应该根据当前 员工的权限
        if ( !in_array('is_valid',$hidden) ) {
            //标记有效
            $validArr = [];
            if(check_right('menu1546854995')){
                $temp['id']  = 1;
                $temp['name']= '有效';
                $temp['sele']= 0;
                $validArr[] = $temp;
            }
            // 标记待定
            $temp['id']  = 2;
            $temp['name']= '待定';
            $temp['sele']= 0;
            $validArr[] = $temp;
            // 标记无效
            if(check_right('menu1517129331')){
                $temp['id']  = 3;
                $temp['name']= '无效';
                $temp['sele']= 0;
                $validArr[] = $temp;
            }
            $return['validArr'] = $validArr;
        }
        // 出生医院 是否隐藏
        if ( !in_array('baby_address',$hidden) ) {
            $hospital = controller('crm/Customer','lib')->getHospital();
            $return['hospital'] = $hospital;
        }
        // 入住会所 ，是否隐藏
        if ( !in_array('club_name',$hidden) ) {
            $clubData = db("crm_s_club")->where("brandclass_id",session("brandclass_id"))->select();
            $return['clubData'] = $clubData;
        }
        // 医拍摄影师 ，是否隐藏
        if ( !in_array('photo_cameraman',$hidden) ) {
            $ypParam['shop_code'] = session('shop_code');
            $ypParam['work_type'] = PZ_WORK_TYPE;
            $photo_cameraman = getShopStaffs($ypParam);
            $return['photo_cameraman'] = $photo_cameraman;
        }
        // 医拍摄影助理 ，是否隐藏
        if ( !in_array('photo_assistant',$hidden) ) {
            $zlParam['shop_code'] = session('shop_code');
            $zlParam['work_type'] = SYZL_WORK_TYPE;
            $photo_assistant = getShopStaffs($zlParam);
            $return['photo_assistant'] = $photo_assistant;
        }
        // 渠道在儿童版里默认必选
        //二级渠道
        $erChannel = controller("crm/Customer","lib")->getErChannel($add_shop_code);
        $return['erChannel'] = $erChannel;
        // 来源渠道 --三级从二级下拉框获取
        $channel = controller("crm/Customer","lib")->getChannel($add_shop_code);
        $return['channel'] = $channel;
        // 南宁定制 品牌
        if (customize('nnqqbaby')) {
            $brand = db('crm_s_brandset')->order('sort asc')->select();
            $return['brand'] = $brand;
        }



        $addrParam['type']=1;
        $addrParam['shop_code']=session('shop_code');
        $return['province']=controller("crm/Customer","lib")->address($addrParam);
        if (count($return['province']) > 0) {
            $return['province'][0]['selected']=1;
            //城市
            $addrParam['type']=2;
            $addrParam['pid'] =$return['province'][0]['id'];
            $return['city']=controller("crm/Customer","lib")->address($addrParam);
            unset($addrParam);
        }

        return json(['code'=>200,'msg'=>'','data'=>$return]);
    }
    //标记提醒
    public function isNextTimeRemind(){
        return controller('crm/Customer','lib')->isNextTimeRemind();
    }
    //根据所选省查询以下市、根据市查询以下县
    public function searchCity(){
        $data = input('post.');
        $res = controller('crm/Customer','lib')->address($data);
        return $res;
    }
    //删除客资
    public function delCustomer(){
        $data=input('post.');
        $ids=$data['id'];
        return controller("Customer","lib")->delCustomer($ids);
    }
    //移动端客资录入
    public function appAddCustomer(){
        $param = input('post.');
        $data['shop_code'] = $param['shop_code'];
        if(empty($data['shop_code'])){
            $returnData = array('code' => 100, 'msg' => '未获取到店面，不能提报');
            return json($returnData);
        }
        
        $data['shop_name'] = $param['shop_name'];
        $data['brandclass_id'] = $param['brandclass_id'];
        $data['brandclass'] = $param['brandclass'];
        $data['dj_department_id']=session('department_id');
        $data['dj_staff_id'] = trim($param['dj_staff_id']);
        $data['dj_staff'] = trim($param['dj_staff']);
        $data['dj_staff_number'] = trim($param['dj_staff_number']);
        $data['consulation_shop_code'] = trim($param['consulation_shop_code']);
        $data['consulation_shop'] = trim($param['consulation_shop']);
        $data['customer_channel_id'] = intval($param['customer_channel_id']);
        $data['customer_channel'] = trim($param['customer_channel']);
        $data['customer_cource_id'] = intval($param['customer_cource_id']);
        $data['customer_cource'] = trim($param['customer_cource']);
        $data['customer_intention_id'] = intval($param['customer_intention_id']);
        $data['customer_intention'] = trim($param['customer_intention']);
        $data['consultation_type_id'] = intval($param['consultation_type_id']);
        $data['consultation_type'] = trim($param['consultation_type']);
        $data['access_model_id'] = intval($param['access_model_id']);
        $data['access_model'] = trim($param['access_model']);
        $data['introducer_name'] = $param['introducer_name'] ? trim($param['introducer_name']) : '';
        $data['introducer_tel'] = $param['introducer_tel'] ? trim($param['introducer_tel']): '';
        $data['introducer_ordernum'] = $param['introducer_ordernum'] ? trim($param['introducer_ordernum']) : '';
       
        /* $data['province_id'] = trim($param['province_id']);
        $data['city_id'] = trim($param['city_id']);
        $data['county_id'] = trim($param['county_id']);
        $data['province'] = trim($param['province']);
        $data['city'] = trim($param['city']);
        $data['county'] = trim($param['county']);
        $data['customer_address'] = trim($param['customer_address']); */

        $data['customer_type'] = trim($param['customer_type']);
        $count = count($param['customer_name']);//提报客资数量
        if(!$count){
            return array('code'=>121,'msg'=>'请填写客资姓名');
        }
        $param['customer_sex'] = array_values($param['customer_sex']);
        $param['baby_sex'] = array_values($param['baby_sex']);
        if($param['customer_type'] == 2){
            //转介绍类型 :   1:老顾客转介绍;2:员工亲友转介绍
            $data['zjs_from'] = $param['zjs_from'];
            unset($param['customer_cource_id']);
        }
        //来源渠道要默认给一个  eric 20190306
        if(empty($data['customer_cource_id'])){
            $cusTypeId = $data['customer_type'] == 2?2:3;
            $source=controller("Customer","lib")->source();
            if(in_array('转介绍',array_column($source,'cus_name'))){
                foreach($source as $k=>$v){
                    if($v['cus_name'] == '转介绍'){
                        $data['customer_cource_id'] = $v['id'];
                        $data['customer_cource'] = '转介绍';
                    }
                }
            }else{
                foreach ($source as $k => $v) {
                    if($v['type_id'] == $cusTypeId || $v['type_id'] == 0){
                        $data['customer_cource_id'] = $v['id'];
                        $data['customer_cource'] = $v['cus_name'];
                        break;
                    }
                }
            }
        }

        for($i=0;$i<$count;$i++){
            $data['baby_name'] = trim($param['baby_name'][$i]);
            $data['baby_sex'] = trim($param['baby_sex'][$i]);
            $data['baby_weight'] = trim($param['baby_weight'][$i]);
            $data['baby_stature'] = trim($param['baby_stature'][$i]);
            $data['baby_birthday'] = date('Y-m-d',strtotime(trim($param['baby_birthday'][$i])));
            $data['customer_name'] = trim($param['customer_name'][$i]);
            if(empty($data['customer_name'])){
                $returnData = array('code' => 800, 'msg' => '客资姓名不能为空');
                return json($returnData);
            }
            $data['customer_tel'] = trim($param['customer_tel'][$i]);
            $data['customer_wechat'] = trim($param['customer_wechat'][$i]);
            if(empty($data['customer_tel']) && empty($data['customer_wechat'])){
                $returnData = array('code' => 900, 'msg' => '客资手机号微信号至少填定一个');
                return json($returnData);
            }
            if($data['customer_tel'] && !preg_match("/^1[3|4|5|6|7|8|9][0-9]{9}$/", $data['customer_tel'])){
                $returnData = array('code' => 500, 'msg' => '【'.$data['customer_tel'].'】手机号格式错误');
                return json($returnData);
            }
            $data['customer_remark'] = $param['customer_remark'][$i];
            $data['customer_sex'] = $param['customer_sex'][$i];
            session('sub_validate',null);
            $str = md5(trim($data['customer_tel']));
            if(session('sub_validate') == $str){
                $returnData = array('code' => 700, 'msg' => '客资录入正在处理中，请稍后...');
                return json($returnData);
            }else {
                session('sub_validate', $str);
                if (empty($param['shop_code']) || $param['shop_code'] == '0') {
                    session('sub_validate',null);
                    $returnData = array('code' => 301, 'msg' => '无法获取门店信息，不可录入客资');
                    return json($returnData);
                }
                if (!empty($param['province'])) {
                    $region = controller("Customer", "lib")->getRegionByProvinceId(['name' => $param['province']]);
                    $data['customer_region_id'] = $region['id'];
                    $data['customer_region'] = $region['region_name'];
                }
                $data['add_shop_code'] = session('shop_code');
                $data['add_shop_name'] = session('shop_name');
                //查询归属地是否筛客
                $b_is_sk = controller("Customer", "lib")->is_sk(session('belong_shop_code'));
                if ($data['customer_type'] == 1) {
                    if ($b_is_sk == 1 || session('is_sk') == 1) {
                        $data['is_sk'] = 1;
                        //未选择筛客人则随机
                        if (!$param['sk_staff_id']) {
                            $sklist = controller("Customer", "lib")->sklist('', 24);
                            $rand = rand(0, count($sklist) - 1);
                            $arr = $sklist[$rand];
                            if (!empty($arr)) {
                                $data['sk_staff_id'] = $arr['id'];
                                $data['sk_staff'] = $arr['staffname'];
                            }
                        }
                    }
                } else {
                    //手机转介绍提报不筛客
                    /*if ($b_is_sk == 1) {
                        $data['is_sk'] = 1;
                        //未选择筛客人则随机
                        if (!$data['sk_staff_id']) {
                            $sklist = controller("Customer", "lib")->sklist(session('belong_shop_code'), 24);
                            $rand = rand(0, count($sklist) - 1);
                            $arr = $sklist[$rand];
                            if (!empty($arr)) {
                                $data['sk_staff_id'] = $arr['id'];
                                $data['sk_staff'] = $arr['staffname'];
                            }
                        }
                    }*/
                }

                $res = controller("Customer", "lib")->addCustomer_child($data);
                if($res['code'] == 201){
                    session('sub_validate',null);
                    $returnData = array('code' => 300, 'msg' => $res['msg']);
                    return json($returnData);
                }
                if(is_array($res) && $res['code'] != 200){
                    return $returnData = array('code' => 500,'msg' => $res['msg'],'data'=>$res['data']);
                }else if ($res['code'] == 200) {
                    //更新转介绍最后一次录入的介绍人信息
                    if ($data['customer_type'] == 2) {
                        $arr = array(
                            'introducer_name' => $data['introducer_name'],
                            'introducer_tel' => $data['introducer_tel'],
                            'introducer_ordernum' => $data['introducer_ordernum'],
                            'introducer_type' => $data['introducer_type'],
                            'introducer_number' => $data['introducer_number'],
                        );
                        session('introducerInfo', $arr);
                    }
                    $customerInfo = db('crm_c_customerinfo')->where('id', $res['customer_id'])->field('id,c_unique,customer_name,customer_number,dj_staff_id,dj_staff,dj_staff_number,shop_name,shop_code')->find();
                    $record['gtType'] = 4;
                    $record['customer_id'] = $res['customer_id'];
                    $record['c_unique'] = $customerInfo['c_unique'];
                    $record['customer_name'] = $customerInfo['customer_name'];
                    $record['customer_number'] = $customerInfo['customer_number'];
                    $record['sales_staff_id'] = $customerInfo['dj_staff_id'];
                    $record['sales_staff'] = $customerInfo['dj_staff'];
                    $record['sales_staff_number'] = $customerInfo['dj_staff_number'];
                    $record['shop_name'] = $customerInfo['shop_name'];
                    $record['shop_code'] = $customerInfo['shop_code'];

                    $record['sales_remark'] = '手机录入 ' . trim($param['customer_remark']);

                    $record['sales_day'] = date('Y-m-d H:i:s', time());
                    db()->startTrans();
                    try {
                        db('crm_c_salestrackinginfo')->insert($record);
                        cache('getCustomerTrackInfos' . $res['customer_id'], null);
                        getSalesTracking($res['customer_id']);
                        db()->commit();
                    } catch (Exception $e) {
                        db()->rollback();
                    }
                    session('sub_validate',null);
                } else {
                    session('sub_validate',null);
                    return json(array('msg' =>'客资 '.trim($data['customer_name']). ' 提报失败', 'code' => 100,'res'=>$res));
                }
            }
        }
        return json(array('msg' => '提报成功', 'code' => 200));
    }
    public function getHospital(){
        // 出生医院
        $hos = controller('crm/Customer','lib')->getHospital();
        // var_dump($hos);die;
        return $hos;
    }
    // 客资录入页面
    public function customerAdd(){
        if(!session('shop_code')){
            echo '未获取到店面配置，添加客资必须为店下人员';
            die;
        }
        // 为了防止页面报错
        $custom = $this->getCustomColumn();//获取自定义列
        $this->assign('colModel',$custom['custom_model'] ? json_decode($custom['custom_model'],true) : json_encode([]));
        $this->assign('colNames',$custom['custom_name'] ? json_decode($custom['custom_name'],true) : json_encode([]));

        $this->assign('today', date('Y-m-d'));
        // 转介绍客资与新客资页面切换用
        $target = input('get.target');
       
        
        $this->assign('lrMust',getLrMust(session('brandclass_id'),session('shop_code')));
        // 录入必选项定制 录入时显示 20200106
        if (ini('lr_must.shop_code')==session('shop_code')) {
            // 判断字段是否存在
            $column = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>ini('lr_must.field')));
            if ($column) {
                $select = explode(',', ini('lr_must.select'));
                $this->assign("xaf_field1",ini('lr_must.field'));
                $this->assign("xaf_fieldname1",ini('lr_must.fieldname'));
                $this->assign("xaf_select1",$select);
            }
        }
        // 录入字段隐藏配置
        $hidden = db_config('lr_hidden_'.session('brandclass_id'));
        $hidden = trim($hidden,',');
        $hidden = explode(',',$hidden);
        $this->assign('lrHidden',$hidden);
        $baby_sex = config('baby_sex');
        if(empty($baby_sex)){
            $baby_sex = [
                ['sex'=>'男',],
                ['sex'=>'女',],
            ];
        }
        $this->assign('baby_sex',$baby_sex);
        // 排重方式
        // $repeat_way = config('repeat_way');
        $repeat_way = db_config('customer_repeat_method');
        $repeat_way = $repeat_way?$repeat_way:config('repeat_way');

        $this->assign("repeat_way",$repeat_way);
        // 登记店面 取 当前账号的可操作店
        $p = [
            'staff_id'=> session('staff_id'),
            'brandclass_id'=> session('brandclass_id'),
            'shop_type' => session('shop_type')
        ];
        $djshops = getShops($p);
        if (cookie('add_shop_code')) {
            foreach ($djshops as $key => $value) {
                if (cookie('add_shop_code')==$value['shop_code']) {
                    $add_shop_code = $value['shop_code'];
                }
            }
            if (!$add_shop_code) {
                $add_shop_code = session('shop_code');
            }
        }else{
            foreach ($djshops as $key => $value) {
                if (session('shop_code')==$value['shop_code']) {
                    $add_shop_code = $value['shop_code'];
                }
            }
        }
        $this->assign('djshops',$djshops);
        // 登记部门及登记人
        if(!in_array('dj_staff',$hidden)){
            $shopCode = cookie('add_shop_code') ? cookie('add_shop_code') : session('shop_code');
            //当前店下部门
            $department = $this->getDList(array('shop_code'=>$shopCode));
            $this->assign('department',$department);
            //当前店下所有人
            $allStaff = controller('crm/Customer','lib')->getShopAllStaff(array('shop_code'=>$shopCode ? $shopCode : session('shop_code')));
            $this->assign('allStaff',$allStaff);
        }

        // 归属店面 部门 追踪人
        // mc没有设置归属店面，crm设置的归属店
        $checked_shop = db_config('dj_shops_'.session('shop_code'));
        // 有归属店
        if(session('belong_shop_code')){
            $p['shop_code'] = session('belong_shop_code');
            $p['work_type'] = 21;
            $p['all'] = 2;
            $shopAllStaff = getShopStaffs($p);
            // mc设置了归属店面
            $shop_code[0]['shop_code'] = session('belong_shop_code');
            $shop_code[0]['shop_name'] = session('belong_shop_name');
            $shop_code[0]['selected'] = 1;
            $this->assign('shop_code', $shop_code);
        }elseif(empty(session('belong_shop_code')) && !empty($checked_shop)){
            $shopAllStaff = [];
            foreach($checked_shop as $k=>$v){
                $p['shop_code'] = $v['shop_code'];
                $p['work_type'] = 21;
                $p['all'] = 2;
                $staff = getShopStaffs($p);
                foreach($staff as $key=>$val){
                    $shopAllStaff[] = $val;
                }
            }
            // $this->assign("shopAllStaff",$shopAllStaff);
            $shop_code = [];
            foreach ($checked_shop as $key => $value) {
                $shop_code[$key] = $value;
                if ($key==0) {
                    $shop_code[$key]['selected'] = 1;
                }else{
                    $shop_code[$key]['selected'] = 2;
                }
            }
            $this->assign('shop_code', $shop_code);
        }else{
            $p['shop_code'] = session('shop_code');
            $p['work_type'] = 21;
            $p['all'] = 2;
            $shopAllStaff = getShopStaffs($p);
            // mc没有设置归属店面，crm也没有设置归属店
            $shop_code[0]['shop_code'] = session('shop_code');
            $shop_code[0]['shop_name'] = session('shop_name');
            $shop_code[0]['selected'] = 1;
            $this->assign('shop_code', $shop_code);
        }
        $this->assign("shopAllStaff",$shopAllStaff);
        // 短信账号
        $sms = db_config('sms_'.session('shop_code'));
        $this->assign('sms',$sms);
        // 录入时是否发送短信
        $is_send_sms = db_config('is_send_sms_'.session('shop_code'));
        $this->assign('is_send_sms',$is_send_sms);
        // 短信模板
        $res = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('status',1)->field('id,mtemplate_name')->select();
        $this->assign('smsModel',$res);
        //客户地址
        unset($data);
        $data['type']=1;
        $address=controller("crm/Customer","lib")->address($data);
        $this->assign("address",$address);

        //南宁qqbaby定制内容是否显示
        $this->assign('is_nnqqbaby',customize('nnqqbaby')?1:2);

        // babypastel 录转介绍客资的时候 可以录入渠道
        $babypastel = customize('babypastel');
        // var_dump($babypastel);die;
        if ($babypastel) {
            $this->assign('babypastel','1');
        }else{
            $this->assign('babypastel','2');
        }
        
        /*--------------------------------------- 下拉框 ---------------------------------------*/
        /*
        //二级渠道
        $erChannel = controller("crm/Customer","lib")->getErChannel($add_shop_code);
        $this->assign("erchannel",$erChannel);
        // 来源渠道
        $channel = controller("crm/Customer","lib")->getChannel($add_shop_code);
        $this->assign("channel",$channel);
        // 获取方式
        $accessModel=controller("crm/Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
        $this->assign("accessModel",$accessModel);
        // 消费类型  不从mc里取了，取erp的设定
        $consumptionType = controller("crm/Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        // 客户意向
        $intention=controller("crm/Customer","lib")->intention(array('shop_code'=>session('shop_code')));
        $this->assign("intention",$intention);
        // $this->assign("intention1",$intention);
        // 客户来源
        $source = controller("crm/Customer","lib")->source(array('shop_code'=>session('shop_code')));
        $this->assign("source",$source);
        // 客资标记
        $tracksign=controller("crm/Setting","lib")->gettrackingKmarkerList();
        $this->assign("tracksign",$tracksign);
        //推广人
        $r['shop_code'] = session('shop_code');
        $r['work_type'] = KZTB_WORK_TYPE;
        $r['all'] = 2;
        $recommendStaff = getShopStaffs($r);
        $this->assign('recommendStaff',$recommendStaff);
        //意向店面
        $shops = controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass'),
            'is_marketing'=>2));
        $this->assign('shops',$shops);
        // 客资状态，应该根据当前 员工的权限
        // $this->assign('customer_valid',$customer_valid);
        //出生医院
        $hos = controller('crm/Customer','lib')->getHospital();
        $this->assign("hospital",$hos);
        // 入住会所
        $clubData = db("crm_s_club")->where("brandclass_id",session("brandclass_id"))->select();
        $this->assign('clubData',$clubData);
        // 医拍摄影师
        unset($data);
        $data['shop_code'] = session('shop_code');
        $data['work_type'] = PZ_WORK_TYPE;
        $photo_cameraman = getShopStaffs($data);
        $this->assign('photo_cameraman',$photo_cameraman);
        // 医拍摄影助理
        unset($data);
        $data['shop_code'] = session('shop_code');
        $data['work_type'] = SYZL_WORK_TYPE;
        $doctor_photo_assistant = getShopStaffs($data);
        $this->assign('doctor_photo_assistant',$doctor_photo_assistant);

        $cookie['customer_channel_id']=cookie('customer_channel_id');//来源渠道
        $cookie['channel_plan_number']=cookie('channel_plan_number');//来源计划编号
        $cookie['access_model_id']=cookie('access_model_id');//获取方式
        $cookie['customer_intention_id']=cookie('customer_intention_id');//客户意向
        $cookie['consultation_type_id']=cookie('consultation_type_id');//消费类型
        $cookie['customer_intention_id']=cookie('customer_intention_id');//客户意向
        $cookie['customer_cource_id']=cookie('customer_cource_id');//客户来源
        $cookie['customer_area_id']=cookie('customer_area_id');//客户分区
        $cookie['customer_region_id']=cookie('customer_region_id');//客户地域
        $cookie['is_urgent']=cookie('is_urgent');//是否加急
        $cookie['sign_id']=cookie('sign_id');//是否加急
        $cookie['yp_cameraman_id']=cookie('yp_cameraman_id');//医拍摄影师
        $cookie['yp_assistant_id']=cookie('yp_assistant_id');//医拍摄影助理
        $this->assign('cookie',$cookie);
        */

        /*
        // 不知道干嘛 用的
        $param = [
            '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($param);
        $this->assign('check_shop',$belong);
        // 客资状态
        $valid = db_config('valid_'.session('brandclass_id'));
        $this->assign('valid',$valid);
        //判断是不是集团店
        if(session('is_group') == 1){
            //集团下事业部
            // $url = '5a38840b15ba9';
            // $info = sx_call($url,[]);
            $mc = new \app\common\lib\mcInterface();
            $info = $mc->getBrand();
            
            if($info !== false){
                $this->assign('brand',$info);
            }
        }
        //客户标记
        $mark=controller("crm/Customer","lib")->markSet();
        $this->assign("market",$mark);
        $this->assign("mark1",$mark);
        //消费能力
        $capacity=controller("crm/Customer","lib")->capacity(array('shop_code'=>session('shop_code')));
        $this->assign("capacity",$capacity);
        //查询归属地是否筛客
        $b_is_sk = controller("crm/Customer","lib")->is_sk(session('belong_shop_code'));

        if($b_is_sk ==1 || session('is_sk') == 1){
            $this->assign('is_sk',1);
            if ( session('is_marketing') == 2 ) {
                $this->assign('sklist',controller("crm/Customer", "lib")->sklist(session('shop_code'),24));
            }else{
                $this->assign('sklist',controller("crm/Customer", "lib")->sklist('',24));
            }
        }
        $this->assign('shoptype',session('shop_type'));
        */

        /*
        if(session('is_marketing') == 4 || $target== 'zjs' || $only == 'zjs'){
            //转介绍
            //录入店面
            // foreach ($source as $k=>$v) {
            //     if($v['type_id'] != 0 && $v['type_id'] != 2){
            //         unset($source[$k]);
            //     }
            // }
            // 为了判断 是否在录入转介绍客资的时候 选择渠道  默认转介绍客资的渠道是录入人所在的部门
            $babypastel = customize('babypastel');
            if ($babypastel) {
                $this->assign('babypastel','1');
            }
            
            // //如果有上次记录，去上次的
            // $shopCode = cookie('add_shop_code') ? cookie('add_shop_code') : session('shop_code');
            // $this->assign('only_shop', $shopCode);
            // //当前店下部门
            // $department = $this->getDList(array('shop_code'=>$shopCode));
            // $this->assign('department',$department);
            // //当前店下所有人
            // $allStaff = controller('crm/Customer','lib')->getShopAllStaff(array('shop_code'=>$shopCode ? $shopCode : session('shop_code')));
            // $this->assign('allStaff',$allStaff);
            
            //介绍人是否可输入
            $mobile_input = db_config('mobile_input_'.session('shop_code'));
            $this->assign("mobile_input",$mobile_input);
            return $this->fetch('customeradd_child_jieshao');
        }else{
            return $this->fetch('customeradd_child');
        }*/
    }
    public function getRecommendStaff(){
        $params = input("");
        $shop_code = $params['shop_code'];
        $r['shop_code'] = $shop_code;
        $r['work_type'] = KZTB_WORK_TYPE;
        $r['all'] = 2;
        $recommendStaff = getShopStaffs($r);

        return ['data'=>$recommendStaff];
    }
    /**
     * 根据二级渠道id 获取渠道名称
     * @return [type] [description]
     */
    public function getChannelDataJson(){
        $params = input();
        // if(!$params['channel_info_id']){
        //     return json(['code'=>202,'msg'=>'二级渠道id不能为空']);
        // }

        $p = [
            'staff_id'=> session('staff_id'),
            'brandclass_id'=> session('brandclass_id'),
            'shop_type' => session('shop_type')
        ];
        $djshops = getShops($p);//可操作店
        if($params['shop_code']){
            $add_shop_code = $params['shop_code'];
        }elseif (cookie('add_shop_code')) {
            foreach ($djshops as $key => $value) {
                if (cookie('add_shop_code')==$value['shop_code']) {
                    $add_shop_code = $value['shop_code'];
                }
            }
            if (!$add_shop_code) {
                $add_shop_code = session('shop_code');
            }
        }else{
            foreach ($djshops as $key => $value) {
                if (session('shop_code')==$value['shop_code']) {
                    $add_shop_code = $value['shop_code'];
                }
            }
        }
        $channel = controller("crm/Customer","lib")->getChannel($add_shop_code,'',$params['channel_info_id']);

        if($channel){
            return json(['code'=>200,'msg'=>'获取成功','data'=>$channel]);
        }else{
            return json(['code'=>200,'msg'=>'获取失败']);
        }
    }
    /*
     *   客资录入
     *
     *   验证手机号正则，等后续可能添加的其他正则
     *   验证必选项是否填写
     *   登记人的组织架构（店、部、组）及事业部信息
     *   是否筛客
     *   区分客资类型（新客资、转介绍）
     *   保存一些基本信息到cookie里
     */
    public function addCustomer(){
        if(!session('shop_code')){
            return array('code'=> 100, 'msg'=>'未获取到店面配置，添加客资必须为店下人员');
        }
        $data = input('post.');
        // var_dump($data);die;
        //删除二级渠道
        unset($data['channel_info_id']);
        if (!$data['customer_tel'] && !$data['customer_wechat']) {
            return array('code'=> 100, 'msg'=>'母亲联系方式不存在，请确认');
        }
        // 正则验证联系方式 母亲手机号、微信号二选一，必选 返回参与排重的联系方式
        $rescon = checkContact($data);
        if ($rescon['code'] != 200) {
            return $rescon;
        }else{
            $contact = $rescon['data'];
            unset($rescon);
        }
        // 预产期、宝宝生日 二选一，必选
        if (!$data['ready_baby_day'] && !$data['baby_birthday'] && !$data['record_day']) {
            return array('code'=>101, 'msg'=>'宝宝生日、预产期、填写日期必须填写一项', 'data'=>[]);
        }
        // 渠道名称为必选项 
        if (!$data['customer_channel'] && $data['customer_type'] == 1) {
            return array('code'=>102, 'msg'=>'请填写渠道名称', 'data'=>[]);
        }
        //$detail=controller("AddCustomer","lib")->add($data);
        //$res = controller('AddCustomer','lib')->addCustomer($detail);
        unset($data['file']);//不知道哪来的file参数；毛客资统计时添加失败，必须删除此参数
        // 关于地址方面后面也要考虑 eric6+1
        if(!empty($data['province_id'])){
            $region = controller("Customer","lib")->getRegionByProvinceId(['id'=>$data['province_id']]);
            $data['customer_region_id'] = $region['id'];
            $data['customer_region'] = $region['region_name'];
        }
        $cData['budget'] = DeleteHtml($data['budget']);//去除预算的table标签
        // 登记人  这里缺少小组信息
        if($data['dj_staff_id'] && $data['dj_staff_id'] != session('staff_id')){
            //录入人非本人
            $djStaffInfo = getStaffInfoById($data['dj_staff_id']);
            if(!$djStaffInfo){
                return array('code'=>103, 'msg'=>'登记人员信息错误，请重试', 'data'=>[]);
            }
            $data['dj_staff']          = $djStaffInfo['staffname'];
            $data['dj_group_id']       = $djStaffInfo['group_id'];
            $data['dj_group_name']     = $djStaffInfo['group_name'];
            // $data['dj_department_id']  = $djStaffInfo['department_id'];
            // $data['dj_department_name']= $djStaffInfo['department_name'];
            $data['dj_department_id']  = $data['dj_department_id'] ? $data['dj_department_id'] : '';
            $data['dj_department_name']= $data['dj_department_name'] ? $data['dj_department_name'] : '';
            if(!$data['add_shop_code']){
                $data['add_shop_name']= $djStaffInfo['shop_name'];
                $data['add_shop_code']= $djStaffInfo['shop_code'];
            }
        }else{
            $data['dj_staff_id']       = $data['dj_staff_id'] ? $data['dj_staff_id'] : session('staff_id');
            $data['dj_staff']          = $data['dj_staff'] ? $data['dj_staff'] : session('staff_name');
            $data['dj_group_id']       = $data['dj_group_id'] ? $data['dj_group_id'] : session('group_id');
            $data['dj_group_name']     = $data['dj_group_name'] ? $data['dj_group_name'] : session('group_name');
            $data['dj_department_id']  = $data['dj_department_id'] ? $data['dj_department_id'] : '';
            $data['dj_department_name']= $data['dj_department_name'] ? $data['dj_department_name'] : '';
            $data['add_shop_name']     = $data['add_shop_name'] ? $data['add_shop_name'] : session('shop_name');
            $data['add_shop_code']     = $data['add_shop_code'] ? $data['add_shop_code'] : session('shop_code');
        }
        // $staff = getStaffInfoById($data['dj_staff_id']);
        // $data['dj_staff_number']=$staff['staffnumber'];

        if(!$data['add_shop_code'] || $data['add_shop_code']=='0'){
            return array('code' => 301,'msg' =>'无法获取门店信息，不可录入客资');
        }
        // var_dump($data);
        // die;
        if ($data['sales_staff_id']) {
            $sales_staff = getStaffInfoById($data['sales_staff_id']);
        }
        if($data['recommend_staff_id']){
            $recommend_staff = getStaffInfoById($data['recommend_staff_id']);
        }
        //推广人
        $data['recommend_staff_id'] = $data['recommend_staff_id']?$data['recommend_staff_id']:'';
        $data['recommend_staff'] = $recommend_staff['staffname']?$recommend_staff['staffname']:'';

        if($data['club_id']){
            $clubData = db("crm_s_club")->where("id",$data['club_id'])->find();
        }
        $data['club_id'] = $data['club_id']?$data['club_id']:'';
        $data['club_name'] = $clubData['club_name']?$clubData['club_name']:'';
        
        if(!$data['shop_code']){
            $shopList = getBelongShopList($data['add_shop_code'],$data['customer_type']);
            if(count($shopList) == 1){
                $data['shop_name'] = $shopList[0]['shop_name'];
                $data['shop_code'] = $shopList[0]['shop_code'];
            }elseif (count($shopList) > 1) {
                return array('code' => 301,'msg' =>'无法分配客资归属店，请检查配置');
            }else{
                $data['shop_name'] = session('shop_name');
                $data['shop_code'] = session('shop_code');
            }
        }else{
            // 追踪人 
            $data['sales_staff']          = $data['sales_staff'] ? $data['sales_staff'] : '';
            $data['sales_staff_id']       = $data['sales_staff_id'] ? $data['sales_staff_id'] : '';
            $data['sales_group_id']       = $sales_staff['group_id'] ? $sales_staff['group_id'] : '';
            $data['sales_group_name']     = $sales_staff['group_name'] ? $sales_staff['group_name'] : '';
            $data['sales_department_id']  = $sales_staff['department_id'] ? $sales_staff['department_id'] : '';
            $data['sales_department_name']= $sales_staff['department_name'] ? $sales_staff['department_name'] : '';
            $data['shop_name']            = $data['shop_name'] ? $data['shop_name'] : session('shop_name');
            $data['shop_code']            = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        }
        
        //医拍信息
        $data['hospital_photo_time'] = $data['hospital_photo_time'] ? $data['hospital_photo_time'] : null;
        //医拍摄影师
        $data['hospital_photo_cameraman_id'] = $data['hospital_photo_cameraman_id'] ? intval($data['hospital_photo_cameraman_id']) : null;
        $data['hospital_photo_cameraman'] = $data['hospital_photo_cameraman'] ? trim($data['hospital_photo_cameraman']) : null;
        //医拍摄影助理
        $data['hospital_photo_assistant_id'] = $data['hospital_photo_assistant_id'] ? intval($data['hospital_photo_assistant_id']) : null;
        $data['hospital_photo_assistant'] = $data['hospital_photo_assistant'] ? trim($data['hospital_photo_assistant']) : null;
        $data['baby_address'] = $data['baby_address'] ? trim($data['baby_address']) : null;

        // 如果是渠道/深挖,属于 转介绍 提报类型  这块后面要测试一下 
        // 先去掉，深挖店也有可能要提报新客资，不要控制这么死
        // if(session('is_marketing') == 4){
        //     $data['customer_type'] = 2;
        // }
        // 如果录转介绍客资    这块后面要测试一下 eric6+1
        if($data['customer_type'] == 2){
            // babypastel 定制 录入转介绍客资时 不使用 部门，使用设定的渠道
            $babypastel = customize('babypastel');
            if (!$babypastel) {
                $data['customer_channel_id']= $data['dj_department_id'] ? $data['dj_department_id'] : session('department_id');
                $dep = controller('crm/Customer','lib')->getDepartment();
                $data['customer_channel']   = $dep[$data['customer_channel_id']]['department_name'];
            }            
        }else{
            $data['customer_type'] = 1;
        }
        //渠道绑定关键字信息
        if($data['rid']){
            $keyword = db('crm_s_wx_rchannel')->where('rid',$data['rid'])->order('id desc')->value('keywords');
            $data['customer_key'] = $keyword ? $keyword : null;
            unset($data['rid']);
        }
        // 事业部信息
        $data['brandclass']   = trim($data['brandclass']) ? trim($data['brandclass']) : session('brandclass');
        $data['brandclass_id']= $data['brandclass_id'] ? $data['brandclass_id'] : session('brandclass_id');
        // 默认客资状态 待定
        if(!$data['is_valid']){
            $data['is_valid'] = 2;
        }
        // 存cookie
        cookie('customer_channel_id', $data['customer_channel_id']);//来源渠道
        cookie('channel_plan_number',$data['channel_plan_number']);//渠道计划编号
        cookie('access_model_id', $data['access_model_id']);//获取方式
        cookie('customer_intention_id', $data['customer_intention_id']);//客户意向
        cookie('consultation_type_id', $data['consultation_type_id']);//消费类型
        cookie('customer_cource_id',$data['customer_cource_id']);//客户来源
        cookie('sign_id',$data['sign_id']);//客资标记
        cookie('customer_area_id',$data['customer_area_id']);//客户分区
        cookie('customer_region_id',$data['customer_region_id']);//客户地域
        cookie('is_urgent',$data['is_urgent']);//是否加急

        cookie('yp_cameraman_id',$data['hospital_photo_cameraman_id']);//医拍摄影师
        cookie('yp_assistant_id',$data['hospital_photo_assistant_id']);//医拍摄影助理
        // 筛客部分 停用
        /*
        $work_type=explode(',',trim(session('main_work_type').','.session('work_type'),','));
        if(!in_array(RECEIVE_WORK_TYPE,$work_type)) {//工作类型不是话务
            //查询归属店是否筛客
            $b_is_sk = controller("Customer", "lib")->is_sk(session('belong_shop_code'));
            if($b_is_sk ==1 || session('is_sk') == 1){
                $data['is_sk'] = 1;
                //未选择筛客人则随机
                if(!$data['sk_staff_id']){
                    $sklist = controller("Customer", "lib")->sklist('',24);
                    $rand = rand(0,count($sklist)-1);
                    $arr = $sklist[$rand];
                    if(!empty($arr)){
                        $data['sk_staff_id'] = $arr['id'];
                        $data['sk_staff'] = $arr['staffname'];
                    }
                }
            }
        }
        if($data['is_sk']!=1)  $data['is_already_sk']=1;
        */

        // //来源渠道要默认给一个
        // if(!isset($data['customer_cource_id'])){
        //     $source=controller("Customer","lib")->source();
        //     $cusTypeId = $data['customer_type'] == 2?2:3;
        //     foreach ($source as $k => $v) {
        //         if($v['type_id'] == $cusTypeId || $v['type_id'] == 0){
        //             $data['customer_cource_id'] = $v['id'];
        //             $data['customer_cource'] = $v['cus_name'];
        //             break;
        //         }
        //     }
        // }
        // 录入必选项定制 录入时验证 20200106
        if (ini('lr_must.shop_code')==session('shop_code')) {
            // 判断字段是否存在
            $column = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>ini('lr_must.field')));
            if ($column) {
                if (!$data[ini('lr_must.field')]) {
                    return array('code' => 90,'msg' =>'请选择品类','data'=>'');
                }
            }
        }
        if(customize('shynk')){
            $data['package_name'] = $data['package_name']?$data['package_name']:'';
        }
        // 儿童版录入客资
        $res = controller("Customer", "lib")->addCustomer_child($data);
        // if(session('shop_type')== 2){
        //     $res = controller("Customer", "lib")->addCustomer_child($data);
        // }else{
        //     $res = controller("Customer", "lib")->addCustomer($data);
        // }

        if(empty($res)){
            return $returnData = array('code' => 500,'msg' =>'客资录入失败','data'=>$res['data']);
        }
        if($res['code'] == 201){
            return json($res);
        }
        if (is_array($res) && $res['code'] != 200) {
            if(is_weixin()){
                return $this->wx_index();
            }else{
                $returnData = array('code' => $res['code'],'msg' =>'客资录入失败','data'=>$res['data']);
                return json($returnData);
            }
        } else {
            // $num=controller("Customer","lib")->searchNum();
            if(is_weixin()){
                return $this->wx_index();
            }else{
                //$this->success('客资录入成功', '/',$num);
                $def = array(
                    'customer_channel_id'=>$data['customer_channel_id'],
                    'access_model_id'=>$data['access_model_id'],
                    'consultation_type_id'=>$data['consultation_type_id'],
                    'customer_sex' => $data['customer_sex'],
                    'zjs_from' => $data['zjs_from'],
                    'add_shop_code'=>$data['add_shop_code'],
                );
                if($data['zjs_from'] == 1){
                    cookie('introducer_name',$data['introducer_name']);
                    cookie('introducer_ordernum',$data['introducer_ordernum']);
                    cookie('introducer_tel',$data['introducer_tel']);
                }
                cookie('zjs_from',$data['zjs_from']);
                cookie('dj_staff_id',$data['dj_staff_id']);
                cookie('dj_department_id',$data['dj_department_id']);
                cookie('add_shop_code',$data['add_shop_code']);
                $returnData = array('code' => 1,'msg' =>'客资录入成功','data'=>'','def'=>$def,'customer_id'=>$res['customer_id'],'is_repeat'=>$res['is_repeat'],'save'=>$res['save'],'res'=>$res);
                return json($returnData);
            }
        }
    }

    //录入客资接口
    public function apiAddCustomer($data){
        $staffInfo=controller('Customer','lib')->get_staff_list(array('staffnumber'=>$data['staffnumber']));
        $data['dj_staff_id']=$staffInfo['id'];
        $data['dj_staff']=$staffInfo['staffname'];
        $data['dj_staff_number']=$data['staffnumber'];
        $data['add_shop_name']=$staffInfo['shop_name'];
        $data['add_shop_code']=$staffInfo['shop_code'];
        $data['shop_name']=$staffInfo['belong_shop_name'];
        $data['shop_code']=$staffInfo['belong_shop_code'];
        $data['brandclass']=$staffInfo['brandclass'];
        $data['brandclass_id']=$staffInfo['brandclass_id'];
        if(empty($data['add_shop_code'])||$data['add_shop_code']=='0'){
            $returnData = array('code' => 301,'msg' =>'无法获取门店信息，不可录入客资');
            return json($returnData);
        }
        if(!$data['customer_tel']&&!$data['customer_wechat']&&!$data['customer_qq']){
            $returnData = array('code' => 302,'msg' =>'请填写手机号、微信、QQ任一项联系方式');
            return json($returnData);
        }
        if(!$data['customer_channel']){
            $returnData = array('code' => 303,'msg' =>'缺少参数:渠道名称');
            return json($returnData);
        }
        if(!$data['consultation_type']){
            $returnData = array('code' => 304,'msg' =>'缺少参数:消费类型');
            return json($returnData);
        }
        if(!$data['access_model']){
            $returnData = array('code' => 305,'msg' =>'缺少参数:获取方式');
            return json($returnData);
        }
       /* $arr=controller('Customer','lib')->isRepeat($data['brandclass'],$data['customer_tel'],$data['customer_wechat'],$data['customer_qq'],$data['mate_tel']);
        if($arr['code'] == 201){
            $returnData = array('code' => 306,'msg' =>'手机号，配偶手机号，微信，qq中有一项已存在客资中');
            return json($returnData);
        }*/

        $res = controller("Customer", "lib")->addCustomer($data);
        if($res['code'] == 201){
            return json($res);
        }
        if($res===false){
            $returnData = array('code' => 500,'msg' =>'客资录入失败');
        }else{
            $returnData = array('code' => 1,'msg' =>'客资录入成功');
        }
        return json($returnData);
    }

    //客资导入页面
    public function import(){
        //查询归属店是否筛客
        // $b_is_sk = controller("Customer", "lib")->is_sk(session('belong_shop_code'));
        // if($b_is_sk ==1 || session('is_sk') == 1){
        //     $sklist=controller("Customer", "lib")->sklist('',24);
        //     if(!empty($sklist)){
        //         $this->assign('is_sk',1);
        //     }else{
        //         $this->assign('is_sk',2);
        //     }
        // }
        //已设置的归属店
        $param = [
            '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($param);
        // 如果只有一个，默认选中
        if (count($belong)==1) {
            foreach ($belong as $key => $value) {
                $belong[$key]['select'] = 1;
            }
        }
        $this->assign('check_shop',$belong);
        $size=getMaxUploadSize();
        $this->assign('size', $size);
        return view('import');
    }
    //导入详情
    public function importDetail(){
        $id = input('param.id');
        $total['count'] = db('crm_c_excel_import_data')->where('eid',$id)->order('import_status desc')->count();

        $total['success'] = db('crm_c_excel_import_data')->where('eid',$id)->where('import_status',1)->count();
        $total['error'] = db('crm_c_excel_import_data')->where('eid',$id)->where('import_status',2)->count();
        $total['new'] = db('crm_c_excel_import_data')->where('eid',$id)->where('valid_new',1)->count();
        $this->assign('id',$id);
        $this->assign('total',$total);
        return $this->fetch();
    }
    public function importDetailJSON(){
        $data = input();
        $limit = $data['limit'] ? $data['limit'] : 100;
        $page = $data['page'] ? $data['page'] : 1;
        $result['code'] = 0;
        $result['msg'] = '';
        $temp = db('crm_c_excel_import_data')
            ->where('eid',$data['id'])
            ->order('import_status desc')
            ->page($page)
            ->limit($limit)
            ->select();
        foreach ($temp as $key => $value) {
            $temp[$key]['ready_baby_day'] = $value['ready_baby_day'] ? date('Y-m-d',strtotime($value['ready_baby_day'])) : '';
            $temp[$key]['baby_birthday'] = $value['baby_birthday'] ? date('Y-m-d',strtotime($value['baby_birthday'])) : '';
            if ($value['import_status']==1) {
                $temp[$key]['import_status'] = '成功';
            }else{
                $temp[$key]['import_status'] = '失败';
            }
        }
        $result['data'] = $temp;
        $result['count'] = db('crm_c_excel_import_data')->where('eid',$data['id'])->count();
        $result['success'] = db('crm_c_excel_import_data')->where('eid',$data['id'])->where('import_status',1)->count();
        $result['error'] = db('crm_c_excel_import_data')->where('eid',$data['id'])->where('import_status',2)->count();
        $result['new'] = db('crm_c_excel_import_data')->where('eid',$data['id'])->where('valid_new',1)->count();
        return $result;
    }
    //修改导入信息
    public function editImport(){
        $data = input();
        $id = intval($data['id']);
        if(!$id){
            return array('code'=>100,'msg'=>'未获取到导入ID');
        }
        $field = trim($data['field']);
        $val = trim($data['val']);
        db()->startTrans();
        try{
            db('crm_c_excel_import_data')->where('id',$id)->update([$field=>$val,'update_time'=>date('Y-m-d H:i:s')]);
            db()->commit();
            return array('code'=>200,'msg'=>'修改成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>105,'msg'=>'修改导入信息失败','data'=>$e->getMessage());
        }
    }
    // 导入重试
    public function excelDoAgainExcel() {
        $data = input();
        $message['body']['eid'] = $data['eid'];
        push_list("excelImportRedisList", $message);
    }
    //获取最新导入excel文件历史记录
    public function new_list(){
        $data = input();
        $res=controller("crm/Customer","lib")->new_list($data);
        return $res;
    }

    //删除导入文件历史
    public function delFile(){
        $id=input('post.id');
        $res=controller("Customer","lib")->delFile($id);
        return $res;
    }

    //文件上传 客资导入
    public function uploadExcel(){
        //获取表单上传文件
        $get_file = $_FILES;
        session('upload_eid',null);
        $before_name = $get_file['file']['name'];
        $file  = request()->file('file');
        $data  = input();
        if (!$data['shop_code'] || !$data['shop_name']) {
            $data['shop_code'] = session('belong_shop_code') ? session('belong_shop_code') : session('shop_code');
            $data['shop_name'] = session('belong_shop_name') ? session('belong_shop_name') : session('shop_name');
        }
        $param = [];
        $param['shop_code'] = $data['shop_code'];
        $param['shop_name'] = $data['shop_name'];
        $res = controller("crm/Customer", "lib")->uploadExcel($file, $before_name, $param);
        // print_r($res);exit;
        if (!$res['code']==200) {
            Response::create(['code'=>$res['code'],'msg'=>$res['msg'],'error'=>$res['error']],'json',$res['code'])->send();
            die;
        }
    }
    // 查看上传的文件的处理进度
    public function getUploadFilePercent(){
        $data = input();
        if ((int)$data['eid']) {
            $eid = (int)$data['eid'];
        }else{
            $eid = session('upload_eid');
        }
        $num = cache('upload_percent_'.$eid);
        return json($num);
    }

    //下载源文件
    public function before_file(){
        $id=input('get.');
        $res=controller("crm/Customer","lib")->before_file($id['id']);
    }

    //下载失败文件
    public function fail_file(){
        $id=input('get.');
        $res=controller("crm/Customer","lib")->fail_file($id['id']);
    }

    //查询excel文件上传失败次数
    public function get_excel_fail(){
        $id=input('post.id');
        if(!$id){
            $returnData = array('code' => 301,'msg' =>'无法获取文件信息');
            return json($returnData);
        }else{
            $fail_num=db('crm_c_excel_import')->where('id',$id)->value('import_fail');
            if($fail_num<5){
                $returnData = array('code' => 1,'msg' =>'此文件可修复');
            }else{
                $returnData = array('code' => 302,'msg' =>'此文件修复次数过多，请联系管理员查看失败原因');
            }
            return json($returnData);
        }
    }

    //修复文件
    public function repair(){
        //$id=input('get.');
        $id=input('post.id');
        if($id){
            db('crm_c_excel_import')->where('id',$id)->setInc('import_fail',1);
            $message['body']['eid']=$id;
            // $message['body']['staff']=array('staff_id'=>session('staff_id'),'staff_name'=>session('staff_name'),'staff_number'=>session('staff_number'),'shop_name'=>session('belong_shop_name'),'shop_code'=>session('belong_shop_code'),'brandclass'=>session('brandclass'),'add_shop_code'=>session('shop_code'),'add_shop_name'=>session('shop_name'));
            $resutl=push_list("excelImportRedisList", $message);
            if($resutl){
                $returnData = array('code' => 1,'msg' =>'正在修复，请耐心等待');
            }else{
                $returnData = array('code' => 302,'msg' =>'修复无响应，请重试');
            }
            return json($returnData);
        }
    }

    //客资导出
    public function export(){
        $data=input();

        if($data['cus_id']){
            $sql= " c.id in (".$data['cus_id'].") ";
        }else{
            $end_time=$data['end_time'];
            $data['end_time']=date("Y-m-d",strtotime("$end_time +1 day"));
            if ($data['tab']&&$data['tab']==17) {
                // 今日需追踪
                $data['all_time'] = 'dj_day';
            }
            $sqlArr=controller('Customer','lib')->customerSearch($data);
            $sql = $sqlArr[0];
            $oSql = $sqlArr[1];
            $sql .= controller('crm/Customer','lib')->getSearchRightSql($data);
        }
        // $field = 'c.id,c.customer_number,c.is_valid,c.customer_channel,c.sign_name,c.op_signinfo,c.baby_name,c.baby_sex,c.baby_birthday,c.ready_baby_day,c.customer_name,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.city,c.customer_address,c.baby_address,c.hospital_photo_cameraman,c.hospital_photo_assistant,c.hospital_photo_time,c.recommend_staff,c.customer_key,c.marry_day,c.budget,c.consultation_type,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,c.channel_plan_number,c.ad_page,c.consulation_shop,c.yjd_action_day,c.yjd_day,c.is_intostore,c.syjd_day,c.is_success,c.order_number,c.order_start_time,c.order_day,c.order_type,c.totalpay_money,c.fact_money,o.order_fact,o.order_amount,c.is_loss,c.loss_cause,c.customer_type,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.tel_visit_num,c.track_record,c.last_trackday,c.customer_remark,c.add_friend_time,c.dj_day,c.dj_staff,c.dj_group_name,c.dj_department_name,c.add_shop_name,c.is_fp,c.sales_staff,c.sales_group_name,c.sales_department_name,c.shop_name,c.brandclass';
        $field = 'c.id,c.customer_number,c.is_valid,c.customer_channel,c.sign_name,c.op_signinfo,c.baby_name,c.baby_sex,c.baby_birthday,c.ready_baby_day,c.customer_name,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.province,c.city,c.customer_address,c.baby_address,c.hospital_photo_cameraman,c.hospital_photo_assistant,c.hospital_photo_time,c.recommend_staff,c.customer_key,c.marry_day,c.budget,c.consultation_type,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,c.channel_plan_number,c.ad_page,c.consulation_shop,c.is_success,0 as orderId,MIN(o.targetdate) as targetdate,MAX(o.orderyouxiaodate) as order_day,o.crm_order_type,0 as yxtx,0 as yxss,0 as extx,0 as exss,c.loss_cause,c.customer_type,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.tel_visit_num,c.track_record,c.last_trackday,c.customer_remark,c.add_friend_time,c.dj_day,c.dj_staff,c.dj_group_name,c.dj_department_name,c.add_shop_name,c.is_fp,c.sales_staff,c.sales_group_name,c.sales_department_name,c.shop_name,c.brandclass,c.customer_channel_id,"" as channel_info_name';

        $title=export_header_child();
        
        $count = db('crm_c_customerinfo')->alias('c')->where($sql)
            ->join('crm_l_pc_log sm', 'c.id=sm.cid AND is_delete=2 AND sm.`status`<4', 'left')
            ->join('c_customerorder o','c.id=o.crm_customer_id AND o.blankoutannal<>1','left')
            // ->join('c_customerorder o','c.customer_number=o.crm_customer_number AND o.blankoutannal<>1','left')
            ->group('c.id')
            ->count();
        if ($count>0) {
            set_time_limit(0);
            $file = 'customer.csv';
            //ini_set('memory_limit', '256M');
            //不限制内存了，按PHP.INI给多大，这里就能导多大。
            foreach ($title as $key => $value) {
                $title[$key] = iconv("UTF-8", "GBK", $value);
            }
            $fp = fopen('php://output', 'a');
            fputcsv($fp, $title);

            header('Content-Type: application/vnd.ms-execl');
            header("Content-type:text/csv;charset=utf-8");
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header('Content-disposition: attachment; filename='.$file);
            // echo '占用内存大小：' . memory_get_usage() . "\n";
            // var_dump($pdo);die;
            /*
            $fieldArr = explode(',', $field);
            $field = implode('c.', $fieldArr);
            $field = 'c.'.$field;
            */
            

            // $field .= ',dj_group_name,sales_group_name';

            // $customerSql=db('crm_c_customerinfo c')->join('crm_c_customer_order o','o.order_sn=c.order_number and o.customer_id=c.id','left')->field($field)->where($sql)->fetchSql()->select();

            // 先把客资手机号相关的订单信息查出来
            $allTels = db('crm_c_customerinfo')->alias('c')
                ->join('crm_l_pc_log sm', 'c.id=sm.cid AND is_delete=2 AND sm.`status`<4', 'left')
                ->join('c_customerorder o','c.id=o.crm_customer_id AND o.blankoutannal<>1','left')
                ->where($sql)
                ->field('c.customer_tel')
                ->group('c.id')
                ->select();
            $tels = '';
            foreach ($allTels as $key => $value) {
                if ($value['customer_tel']) {
                    $tels .= $value['customer_tel'].',';
                }
            }
            $tels = trim($tels,',');
            // echo $customerSql;die;
            $inSql = db('c_customerinfo')->alias('c')
                ->join('c_customerorder o','c.customerid=o.customerid','left')
                ->join('c_customerphoto p', 'o.orderId=p.orderId', 'left')
                ->where('c.wphone', 'in', $tels)->where('o.blankoutannal', 0)
                ->where('c.wphone','not null')->where('c.wphone', '<>', '')
                ->where($oSql)
                ->field('c.id as cid, MAX(p.id) AS pid')->buildSql();
            $otherInfo = db('c_customerinfo')->alias('c')
                ->join($inSql.' temp', 'temp.cid = c.id', 'left')
                ->join('c_customerorder o','c.customerid=o.customerid','left')
                ->join('c_customerphoto p', 'o.orderId=p.orderId and temp.pid=p.id', 'left')
                ->where('c.wphone', 'in', $tels)->where('o.blankoutannal', 0)
                ->where('c.wphone','not null')->where('c.wphone', '<>', '')
                ->where($oSql)
                ->group('c.wphone')
                // 一销套系bargain_money，一销实收yixiaoshishou，二销套系supplementary_money，二销实收erxiaoshishou
                ->column('c.wphone,GROUP_CONCAT(o.orderId) as orderIds,GROUP_CONCAT(o.allfinishfate) as allfinishfate,GROUP_CONCAT(p.photodate) as photodate,SUM(bargain_money) as yxtx,SUM(yixiaoshishou) as yxss,SUM(supplementary_money) as extx,SUM(erxiaoshishou) as exss','c.wphone');
            // var_dump($otherInfo);die;
            
            $allChannel = getChannels();

            $pdo = db('crm_c_customerinfo')->getConnection()->getPdo();
            $pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
            // 生成客资的查询语句
            $customerSql = db('crm_c_customerinfo')->alias('c')
                ->join('crm_l_pc_log sm', 'c.id=sm.cid AND is_delete=2 AND sm.`status`<4', 'left')
                ->join('c_customerorder o','c.id=o.crm_customer_id AND o.blankoutannal<>1','left')
                // ->join('crm_s_channel csc','c.customer_channel_id=csc.id AND o.blankoutannal<>1','left')
                ->where($sql)
                ->field($field)
                ->group('c.id')
                ->fetchSql()->select();
            // var_dump($customerSql);die;
            /*          
            //根据单号查询金额
            $orderSN = array_column($customerSql,'order_number');
            $ids = array_column($customerSql,'id');
            $order = db('crm_c_customer_order')->where('order_sn','in',$orderSN)->where('customer_id','in',$ids)->column('earnest_money,order_fact,order_amount,two_pin_fact,two_pin_amount','order_sn');
            */
            $sth = $pdo->prepare($customerSql);
            
            
            $sth->execute();
            $count = 0;

            while ($value = $sth->fetch(\PDO::FETCH_ASSOC)) {
                //print_r($result);
                /*//成交状态
                if ($value['orderyouxiao'] == 1) {
                    $value['orderyouxiao'] = '已成交';
                }elseif ($value['orderyouxiao'] == 0) {
                    $value['orderyouxiao'] = '已订单';
                }elseif(empty($value['orderyouxiao'])){
                    $value['orderyouxiao'] = '未成交';
                } 2021-07-22 这是订单成交状态 导出的是客资的成交状态*/

                if ($value['customer_type']) {
                    $value['customer_type'] = $value['customer_type']==1?'新客资':'转介绍';
                }
                if ($value['is_valid']) {
                    $value['is_valid'] = getIsValidAttr($value['is_valid']);
                }
                if ($value['is_intostore']) {
                    $value['is_intostore']=getIsIntostore($value['is_intostore']);
                }
                if ($value['is_fp']) {
                    $value['is_fp']=getIsFP($value['is_fp']);
                }
                if ($value['is_success']) {
                    $value['is_success']=getIsSuccess($value['is_success']);
                }
                if ($value['is_loss']) {
                    $value['is_loss']=getIsLoss($value['is_loss']);
                }
                
                if ($value['c_from'] == 1) {
                    $value['c_from']='CRM';
                }elseif($value['c_from'] == 2){
                    $value['c_from']='ERP';
                }
                if ($value['introducer_type']) {
                    $value['introducer_type']=getIntroducerType($value['introducer_type']);
                }
                //追踪记录
                if($value['track_record']){
                    $value['track_record'] = strip_tags($value['track_record']);
                }
                // $value['track_record'] = '0503121资驳回';
                // 根据手机号查订单
                if ($value['customer_tel']) {
                    $value['orderId'] = $otherInfo[$value['customer_tel']]['orderIds'];
                    $value['yxtx'] = $otherInfo[$value['customer_tel']]['yxtx'];
                    $value['yxss'] = $otherInfo[$value['customer_tel']]['yxss'];
                    $value['extx'] = $otherInfo[$value['customer_tel']]['extx'];
                    $value['exss'] = $otherInfo[$value['customer_tel']]['exss'];
                }

                if ($value['customer_wechat']) {
                    $value['customer_wechat'] = ",".$value['customer_wechat'];
                }
                if ($value['customer_weibo']) {
                    $value['customer_weibo'] = ",".$value['customer_weibo'];
                }

                if ($value['customer_channel_id']) {
                    $value['channel_info_name'] = $allChannel[$value['customer_channel_id']]['channel_info_name'];
                }
                
                if ($value['customer_channel_id']) {
                    $value['customer_channel_id'] = $allChannel[$value['customer_channel_id']]['channel_class_name'];
                }


                // if ($value['orderId']) {
                //     if ($value['crm_order_type'] == 1) {
                //         $value['crm_order_type']='线上';
                //     }elseif($value['crm_order_type'] == 2){
                //         $value['crm_order_type']='线下';
                //     }
                // }else{
                    $value['crm_order_type']='';
                // }

                /*
                $v['totalpay_money'] = $order[$value['order_number']]['order_amount']+$order[$value['order_number']]['two_pin_amount'] ? number_format($order[$value['order_number']]['order_amount']+$order[$value['order_number']]['two_pin_amount'],2) : '';
                $v['fact_money'] = $order[$value['order_number']]['order_fact']+$order[$value['order_number']]['earnest_money']+$order[$value['order_number']]['two_pin_fact'] ? number_format($order[$value['order_number']]['order_fact']+$order[$value['order_number']]['earnest_money']+$order[$value['order_number']]['two_pin_fact'],2) : '';
                */
                foreach ($value as $k => $v) {
                    $value[$k] = iconv("UTF-8", "GBK//IGNORE", $v);
                }
                ++$count;
                fputcsv($fp, $value);
                unset($value);
                ob_flush();
                flush();
            }

            $log = '由【'.session('staff_name').'】于【'.date('Y-m-d H:i:s').'】导出【'.session('shop_name').'】客资【'.$count.'】条，所在IP【'.get_client_ip().'】';
            //释放stmt内存
            db('crm_c_customerinfo')->getConnection()->free();
            // echo '占用内存大小：' . memory_get_usage() . "\n";
            //fputcsv($fp, ['运行内存：',memory_get_usage()]);
            
            /*
            fclose($fp);
            @readfile('upload'.DS.$file);
            unlink('upload'.DS.$file);
            */
            action_log($log,$customerSql,0,session('staff_id'),session('staff_name'));
            exit;
        }
    }
    // 导入记录中 导出错误数据
    public function exportErr(){
        // 导入id
        $importId = (int)input('id');
        $countAll = db('crm_c_excel_import')->alias('a')
            ->join('crm_c_excel_import_data b','a.id=b.eid','left')
            ->where('a.id',$importId)->where('b.import_status',2)
            ->count();
        if ($countAll>0) {
            set_time_limit(0);
            // ini_set("memory_limit","1024M");
            $file = 'importerr.csv';
            $title=template_header_child();
            array_unshift($title,'失败原因');
            foreach ($title as $key => $value) {
                $title[$key] = iconv("UTF-8", "GBK", $value);
            }

            $fp = fopen('php://output', 'a');
            fputcsv($fp, $title);
            header('Content-Type: application/vnd.ms-execl');
            header("Content-type:text/csv;charset=utf-8");
            header("Cache-Control: public");
            header("Content-Description: File Transfer");
            header('Content-disposition: attachment; filename='.$file);

            if (config('repeat_way')=='xaf') {
                $field = 'b.msg,b.baby_name,b.baby_sex,b.baby_weight,b.baby_stature,b.baby_time,b.baby_birthday,b.ready_baby_day,b.record_day,b.dj_day,b.customer_name,b.customer_tel,b.customer_wechat,b.customer_qq,b.customer_weibo,b.baby_address,b.hospital_photo_cameraman,b.hospital_photo_assistant,b.hospital_photo_time,b.mate_name,b.mate_tel,b.province,b.city,b.county,b.customer_address,b.customer_type,b.introducer_name,b.recommend_staff,b.sign_name,b.customer_channel,b.access_model,b.consultation_type,b.customer_cource,b.channel_plan_number,b.ad_page,b.customer_area,b.customer_intention,b.consulation_shop,b.customer_orderaddress,b.sales_staff,b.customer_remark,b.introduce_staff_name,b.customer_key';
            }else{
                $field = 'b.msg,b.baby_name,b.baby_sex,b.baby_weight,b.baby_stature,b.baby_birthday,b.ready_baby_day,b.record_day,b.dj_day,b.customer_name,b.customer_tel,b.customer_wechat,b.customer_qq,b.customer_weibo,b.baby_address,b.hospital_photo_cameraman,b.hospital_photo_assistant,b.hospital_photo_time,b.mate_name,b.mate_tel,b.province,b.city,b.county,b.customer_address,b.customer_type,b.introducer_name,b.recommend_staff,b.sign_name,b.customer_channel,b.access_model,b.consultation_type,b.customer_cource,b.channel_plan_number,b.ad_page,b.customer_area,b.customer_intention,b.consulation_shop,b.customer_orderaddress,b.sales_staff,b.customer_remark,b.introduce_staff_name,b.customer_key';
            }
            $pdo = db('crm_c_excel_import')->getConnection()->getPdo();
            $pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
            // 生成客资的查询语句
            $importSql = db('crm_c_excel_import')->alias('a')
                ->join('crm_c_excel_import_data b','a.id=b.eid','left')
                ->where('a.id',$importId)->where('b.import_status',2)
                ->field($field)
                ->fetchSql()->select();
            $sth = $pdo->prepare($importSql);
            $sth->execute();
            $count = 0;
            while ($value = $sth->fetch(\PDO::FETCH_ASSOC)) {
                foreach ($value as $k => $v) {
                    $value[$k] = iconv("UTF-8", "GBK", $v);
                }
                ++$count;
                fputcsv($fp, $value);
                unset($value);
                ob_flush();
                flush();
            }
            $log = '由【'.session('staff_name').'】于【'.date('Y-m-d H:i:s').'】导出ID为：'.$importId.'的错误数据【'.$count.'】条，所在IP【'.get_client_ip().'】';
            action_log($log,$importSql,0,session('staff_id'),session('staff_name'));
            //释放stmt内存
            db('crm_c_excel_import')->getConnection()->free();
            exit;
        }
    }
    //模板下载
    public function excel_download(){
        //controller("Customer","lib")->excel_template();
        // if(session('shop_type')  == 2){
            $title=template_header_child();
        // }else{
        //     $title=template_header();
        // }
        //$title=array('客户姓名','性别','手机号','微信','微博','QQ','省','市','区','详细地址','客户类型','消费类型','意向店面','客户渠道','客户来源','客户意向','接单点','获取方式','客户分区','客户地域');
        $file="客资模板.xlsx";
        return controller("crm/Customer","lib")->export($title,'',$file);
    }

    //选择条件下的类型
    public function searchTwo(){
        $data = input('post.');
        $detail=controller("Customer","lib")->searchTwo($data);
        return $detail;
    }

    //类型查询
    public function searchTypt(){
        $data = input('post.');
        $detail=controller("Customer","lib")->searchTypt($data);
        return $detail;
    }

    // 处理未分配或者分配失败 Eric 只处理已分配，未接受的客资，其他未分配的客资，由员工手动分配
    public function disposeCustomerFp(){
        $customers = db('crm_c_customerinfo')
            ->where('is_fp', 3)
            ->where('jr_day', 'null')
            ->column('id, is_fp, fp_day, shop_code', 'id');
        // cache('test','hello world',3600);
        // $key = 'test';
        // $a=cache($key);
        // echo $a;die;
        foreach ($customers as $key => $value) {
            $key = 'fp_timeout_'.$value['shop_code'];
            $timeOut = cache($key);
            if (!$timeOut) {
                $timeOut = db('crm_c_sysconfig')->where('ckey', $key)->find;
                cache($key, $timeOut, 2592000);
            }
            // 如果存在分配时间，并且分配时间+过期时间小于当前时间，则不进入分配队列
            if ($value['fp_day']) {
                $fp_day = strtotime($value['fp_day'])+$timeOut;
                if ($fp_day <= time()) {
                    continue;
                }
            }
            // var_dump($value);
            $this->customerAllot($value['id']);
        }
        exit;
    }
    //追踪记录,历史订单
    public function call_log(){
        // 追踪记录
        $res['track'] = controller("Customer","lib")->getCustomerTrackInfos(input('post.id'));
        // 历史订单
        $res['order'] = controller("Customer","lib")->getCustomerHistoryOrders(input('post.id'));
        $is_erp = is_install('sx_erp');
        foreach ($res as $key => $value) {
            if ($is_erp === false) {
                $erp_status = 0;
                $res[$key]['erp_link'] = '';
            }else{
                $erp_status = 1;
                $res[$key]['erp_link'] = '/crm/Customer/getAllServiceInfo/order_sn/'.$value['order_sn'];
            }
        }
        $this->assign('erp_status', $erp_status);
        $this->assign('historyOrders', $res);
        return json($res);
    }

    public function trackLog(){
        // 追踪记录
        $track = controller("Customer","lib")->getCustomerTrackInfos(input('param.id'));

        $order = controller("Customer","lib")->getCustomerHistoryOrders(input('param.id'));
        $this->assign('trackInfoss',$track);
        $this->assign('order',$order);
        return $this->fetch();
    }
    // 重新分配筛客人 页面
    public function customerAllotSk(){
    	$auth = check_right('menu1512970623');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有分配客资的权限，请先设置权限');
            return json($return);
            exit;
        }

        // 店
        $param['staff_id']        = session('staff_id');
        $param['brandclass_id']   = session('brandclass_id');
        $param['shop_type']       = session('shop_type');
        $param['shop_code']       = session('shop_code');
        $param['belong_shop_code']= session('belong_shop_code');
        $param['belong_shop_name']= session('belong_shop_name');

        $shopList = getBelongShop($param);
        $this->assign('shopList',$shopList);
        $this->assign('isSk',true);
        $time_area = getdateArea('this_week');
        $this->assign('start',$time_area[0]);
        $this->assign('end',date('Y-m-d'));
        return $this->fetch();
    }
    // 获取筛客人
    public function getSkStaff(){
    	$data     = input('post.');
    	$skShop = $data['shop'] ? $data['shop'] : '';
        $skList = controller("crm/Customer", "lib")->sklist($skShop,24);
        return $skList;
    }
    // 获取指定筛客人带筛客客资
    public function getSkCustomer(){
    	$data = input('post.');
    	if (!$data['shop_code']) {
    		return array('error'=>1, 'code'=>100, 'msg'=>'缺少参数，店面信息');
    	}
    	// if (!(int)$data['staff_id']) {
    	// 	return array('error'=>1, 'code'=>101, 'msg'=>'缺少参数，筛客人信息');
    	// }

    	$where['c_from']       = 1;
        $where['is_status']    = 1;
        $where['is_examine']   = 1;
        $where['is_already_sk']= 2;

    	// 筛客人条件 eric 20190107
    	$sk_staff_id = $data['staff_id'] ? (int)$data['staff_id'] : null;
        if ($sk_staff_id) {
            $sql_sk = ' (sk_staff_id='.$sk_staff_id.' or sk_staff_id is null)';
        }else{
            $sql_sk = '';
        }
        // 时间条件
        $sqlT = '';
        if ($data['start'] && $data['end']) {
            $sqlT .= 'dj_day between "'.date('Y-m-d 00:00:00', strtotime($data['start'])).'" and "'.date('Y-m-d 23:59:59', strtotime($data['end'])).'"';
        }else{
            return array('error'=>1, 'code'=>101, 'msg'=>'缺少时间');
        }
        // 店面条件
    	$sql = ' (add_shop_code="'.$data['shop_code'].'" or shop_code="'.$data['shop_code'].'") ';
    	$skCustomer = db('crm_c_customerinfo')
    	    ->where($where)
    	    ->where($sql)
            ->where($sql_sk)
            ->where($sqlT)
            // ->where('dj_day','between',$time)
    	    ->field('id,dj_staff,sk_staff,dj_day,customer_name,customer_tel,customer_wechat')
    	    ->select();
    	return $skCustomer;
    }

    // 重新指定筛客人
    public function customerAllotSkAction() {
    	$data = input('post.');
    	$ip = \think\Request::instance()->ip();
    	$date = date('Y-m-d H:i:s');

    	$cids = '';
    	$temp_cid = explode('&', $data['cid']);
    	foreach ($temp_cid as $key => $value) {
            $cid = substr($value, 4);
            $sk = db('crm_c_customerinfo')->where('id',$cid)->field('sk_staff,sk_staff_id')->find();
    		// action log用数据
    		$lData[$key]['module']     = 'crm';
            $lData[$key]['controller'] = 'Customer';
            $lData[$key]['action']     = 'customerAllotSkAction';
            $lData[$key]['old_data']   = '原筛客人id：'.$sk['sk_staff_id'].'；<br />原筛客人：'.$sk['sk_staff'];
            $lData[$key]['data']       = '目标筛客人id：'.trim($data['staff_id']).'；<br />目标筛客人：'.trim($data['staff']);
            $lData[$key]['customer_id']= $cid;
            $lData[$key]['staff_name'] = session('staff_name');
            $lData[$key]['staff_id']   = session('staff_id');
            $lData[$key]['ip']         = $ip;
            $lData[$key]['create_time']= $date;

    		$cids .= $cid.',';
    	}
        
    	$cids = trim($cids, ',');
    	$upData['sk_staff'] = trim($data['staff']);
    	$upData['sk_staff_id'] = trim($data['staff_id']);

    	db()->startTrans();
    	try {
    		// 更新客资表
	    	db('crm_c_customerinfo')->where('id','in',$cids)->update($upData);
	    	// 新增操作记录
	    	db('crm_action_log','db_logs')->insertAll($lData);
	    	// 删除pool表中的筛客数据
	    	db('crm_c_fp_pool')->where('cid', 'in', $cids)->where('pool_type', 7)->delete();

    		db()->commit();
    		$returnData['code'] = 200;
    		$returnData['msg']  = '重新指定筛客人成功';
    	} catch (\Exception $e) {
    		db()->rollback();
    		$returnData['code'] = 100;
    		$returnData['msg']  = '重新指定筛客人失败';
    		$returnData['error']= $e->getMessage();
    	}

    	return $returnData;
    }


    // 手动分配条件 页面
    public function customerAllot(){
        $data = input();
        $brandlist = db('crm_c_customerinfo')->where('id', 'in',$data['id'])->field('brandclass_id')->group('brandclass_id')->select();

        if (count($brandlist) > 1) {
            unset($brandlist);
            unset($data);
            return array('code' => 100, 'msg'=>'选中客资包含多个事业部，请重新选择。');
        }

        $auth = check_right('menu1512970623');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有分配客资的权限，请先设置权限');
            return json($return);
        }

        $res = '';
        $tracksign = db('crm_c_customerinfo')
                       ->alias('cc')
                       ->where('cc.id', 'in',$data['id'])
                       ->join("crm_s_tracksign ct","ct.id = cc.sign_id","left")
                       ->field('cc.id,cc.customer_name,cc.customer_tel,sign_id,sign_name,sign_time,ct.protect_day')
                       ->select();
        if (count($tracksign) > 0) {
            foreach ($tracksign as $key => $value) {
                if ($value['protect_day'] > 0 && (strtotime($value['sign_time'])+60*60*24*$value['protect_day']) > time() ) {
                    $res .= "ID：".$value['id'];
                    if ($value['customer_name']) {
                        $res .= "-客户姓名：".$value['customer_name'];
                    }
                    if ($value['customer_tel']) {
                        $res .= "-客户手机：".$value['customer_tel'];
                    }
                    if ($value['customer_wechat']) {
                        $res .= "-客户微信：".$value['customer_wechat'];
                    }
                    $res .= ";";
                }
            }
            if (!empty($res)) {
                $return = array('error'=>'1','msg'=>'选择的客资有在保护期内，不能分配。保护期客资是=>'.$res);
                return json($return);
            }
        }

        $this->assign('isSk',false);
        // 业绩列表
        // $targets = controller("crm/Target","lib")->getAllTarget();
        // $i = 0;
        // foreach ($targets as $key => $value) {
        //     $targetList[$i]['name']= controller("crm/Target","lib")->get_target_name_by_id($value['id']);
        //     $targetList[$i]['method']= controller("crm/Target","lib")->get_target_method_by_id($value['id']);
        //     $i++;
        // }
        // // $this->assign('department',$department['data']);
        // unset($targets);
        // $this->assign('targetList',$targetList);

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


        $shopList = [];
        $param['staff_id']        = session('staff_id');
        $param['brandclass_id']   = session('brandclass_id');
        $param['shop_type']       = session('shop_type');
        $param['shop_code']       = session('shop_code');
        $param['belong_shop_code']= session('belong_shop_code');
        $param['belong_shop_name']= session('belong_shop_name');
        $shopList = getBelongShop($param);
        unset($param);
        // var_dump($shopList);
        // exit;

        // 工作类型(话务)
        $workTypes = RECEIVE_WORK_TYPE;
        $type = explode(',', session('work_type'));
        array_push($type, session('main_work_type'));
        //
        if (is_array($type)) {
            $is_hw = in_array($workTypes, $type);
        }else{
            if ($workTypes == $type) {
                $is_hw = true;
            }else{
                $is_hw = false;
            }
        }
        
        // 如果是话务，分配时，店，部门，自动选中
        if ($is_hw) {
            foreach ($shopList as $key => $value) {
                // 选中店
                if ($value['shop_code'] == session('shop_code')) {
                    $shopList[$key]['select'] = '1';// 选中
                    // 获取部门
                    $paramD['shop_code'] = $value['shop_code'];
                    $dList = getDepartments($paramD);
                    // var_dump($dList);die;
                    foreach ($dList as $kD => $vD) {
                        if ($vD['id'] == session('department_id')) {
                            $departmentList[$kD]['id'] = $vD['id'];
                            $departmentList[$kD]['department_name']= $vD['department_name'];
                            $departmentList[$kD]['select'] = '1';// 选中
                            //获取小组
                            $paramG['department_id'] = $vD['id'];
                            $mc = new \app\common\lib\mcInterface();
                            $gList = $mc->getGroupInfo(array('shop_code' => session('shop_code')));
                            foreach ($gList as $kG => $vG) {
                                // if ($vG['id'] == session('group_id')) {
                                    $groupList[$kG]['id'] = $vG['id'];
                                    $groupList[$kG]['group_name']= $vG['group_name'];
                                    // $groupList[$kG]['select'] = '1';// 选中
                                // }else{
                                    // $groupList[$kG]['id']  = $vG['id'];
                                    // $groupList[$kG]['group_name']= $vG['group_name'];
                                    // $groupList[$kG]['select'] = '2';// 不选中
                                // }
                            }
                            unset($gList);
                        }else{
                            $departmentList[$kD]['id'] = $vD['id'];
                            $departmentList[$kD]['department_name']= $vD['department_name'];
                            $departmentList[$kD]['select'] = '2';// 不选中
                        }
                    }
                    unset($dList);
                }else{
                    $shopList[$key]['select'] = '2';// 不选中
                }
            }
        }else{
            $departmentList = [];
            $groupList = [];
        }
        /*
        if(cookie('fp_select_shop_code')){
            foreach ($shopList as  $k => $v) {
                if($v['select'] != '1' && $v['shop_code'] == cookie('fp_select_shop_code')){
                    $shopList[$k]['select'] = '1';
                }else{
                    $shopList[$k]['select'] = '2';
                }
            }
        }*/
        
        // var_dump($shopList);
        // var_dump($departmentList);
        // var_dump($groupList);
        // exit;
        if(empty(session('brandclass_id'))){ //
            $brand = controller('crm/Customer','lib')->getBrandClass();
            $this->assign('brand',$brand);
        }else{
            $this->assign('shopList',$shopList);
            $this->assign('department',$departmentList);
            $this->assign('group',$groupList);
        }
        
        $babypastel = customize('babypastel');
        if ($babypastel) {
            $this->assign('babypastel','1');
        }
        // var_dump($groupList);
        // exit;
        return $this->fetch();
    }

    // 手动分配，根据部门，业绩，时间区间，查询员工，并且根据业绩排序
    public function getTargetStaffs(){
        $data     = input('post.');
        $type     = $data['type'] ? (int)$data['type']: 1;
        $time_area= $data['time_area'] ? $data['time_area'] : 'today';
        $day      = getdateArea($time_area);
        $mc = new \app\common\lib\mcInterface();
        // 筛客
        if ($type==2) {
            $skShop = $data['shop'] ? $data['shop'] : '';
            $skList = controller("crm/Customer", "lib")->sklist($skShop,24);

            $arrIds = array_column($skList,'id');
            $ids = implode(',',$arrIds);
            $condition = [
                'staff_id'  => $ids,
                'start_day' => $day[0],
                'end_day'   => $day[1],
            ];
            $skInfo = controller("crm/Customer", "lib")->skCustomers($condition);
            // var_dump($skInfo);exit;
            $online = [];
            $noline = [];
            foreach ($skList as $key => $value) {
                // 查看员工是否在线
                $status = controller('crm/Customer','lib')->getStaffOnlineStatus($value['id']);
                if ($status) {
                    $res1['status']= '<span style="color: #01b88a;font-size: larger">在线</span>';
                    $res1['name']  = $value['staffname'];
                    $res1['id']    = $value['id'];
                    $res1['cNum']  = $skInfo[$value['id']] ? $skInfo[$value['id']] : 0;
                    $res1['rate']  = 0;
                    array_push($online,$res1);
                }else{
                    $res2['status']= '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>';
                    $res2['name']  = $value['staffname'];
                    $res2['id']    = $value['id'];
                    $res2['cNum']  = $skInfo[$value['id']] ? $skInfo[$value['id']] : 0;
                    $res2['rate']  = 0;
                    array_push($noline,$res2);
                }
            }
            $returnData = array_merge($online, $noline);
            return json($returnData);
        }

        $department_id = $data['department_id'] ? $data['department_id'] : '';
        $group_id      = $data['group_id'] ? $data['group_id'] : '';
        $shop_code     = $data['shop'] ? $data['shop'] : session('shop_code');
        $method        = $data['method'] ? $data['method'] : '';

        if($department_id) $pram['department_id'] = $department_id;
        if($group_id) $pram['group_id'] = $group_id;
        if($shop_code) $pram['shop_code'] = $shop_code;
        $pram['work_type'] = 21;
        if($data['jianzhi'] && $department_id){
            $pram['get_main'] = 2;
        }
        $staffs = $mc->getStaffByDepartment($pram);


        $a = [];
        $b = [];
        $arrIds = array_column($staffs,'id');
        $ids = implode(',',$arrIds);
        $condition = [
            'staff_id'  => $ids,
            'shop_code' => $shop_code,
            'start_day' => $day[0],
            'end_day'   => $day[1],
        ];
        // 查询所有员工 接收的客资
        $info = controller("crm/Customer","lib")->jrCustomers($condition);
        // 查询所有员工 接收的客资  里面  除了自己录的以外的客资数
        $info_not = controller("crm/Customer","lib")->jrCustomers_not($condition);
        // $info = controller("crm/Customer","lib")->noStaffId($condition);
        // 计算每一个员工的业绩
        if($method){
            $targets = controller("crm/Target","lib")->getAllTarget();
            // $i = 0;
            // foreach ($targets as $key => $value) {
            //     $methodList[$i]= controller("crm/Target","lib")->get_target_method_by_id($value['id']);
            //     $i++;
            // }
            $all_method = array_column($targets,'method');
            if (!in_array($method, $all_method)){
                return $staffs;
            }
            $targInfo = controller("crm/Customer","lib")->$method($condition);
        }
        foreach ($staffs as $key => $value) {
            /*if($group_id){
                // if(in_array($value['id'],$groupStaffs)){
                    // 查看员工是否在线
                    $status = controller('Customer','lib')->getStaffOnlineStatus($value['id']);
                    // if ($status) {
                    $condition = [
                        'staff_id'  => $value['id'],
                        'start_day' => $day[0],
                        'end_day'   => $day[1],
                    ];
                    if($status){
                        $res1['status'] = '<span style="color: #01b88a;font-size: larger">在线</span>';
                        // if($method){
                            // $res1['rate'] =  controller("crm/Target","lib")->$method($condition);
                            $res1['rate'] =  $targInfo[$value['id']] ? $targInfo[$value['id']] : 0;
                        // }else{
                        //     $res1['rate'] = 0;
                        // }
                        $res1['name'] = $value['staffname'];
                        $res1['id'] = $value['id'];
                        $res1['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;
                        // $res1['cNum'] = controller("crm/Customer","lib")->noStaffId($condition);
                        array_push($a,$res1);
                    }else{
                        $res['status'] = '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>';
                        // if($method){
                            // $res['rate'] =  controller("crm/Target","lib")->$method($condition);
                            $res['rate'] =  $targInfo[$value['id']] ? $targInfo[$value['id']] : 0;
                        // }else{
                        //     $res['rate'] = 0;
                        // }
                        $res['name'] = $value['staffname'];
                        $res['id']   = $value['id'];
                        $res['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;
                        // $res['cNum'] = controller("crm/Customer","lib")->noStaffId($condition);
                        array_push($b,$res);
                    }
                    // $return[$key]['status'] = $status ? '<span style="color: #01b88a;font-size: larger">在线</span>' : '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>';
                    // $return[$key]['rate'] = controller("crm/Target","lib")->$method($condition);
                    // $return[$key]['name'] = $value['staffname'];
                    // $return[$key]['id']   = $value['id'];
                    // $return[$key]['cNum'] = controller("crm/Customer","lib")->noStaffId($value['id']);
                // }
            }else{
                // 查看员工是否在线
                $status = controller('Customer','lib')->getStaffOnlineStatus($value['id']);
                // if ($status) {
                $condition = [
                    'staff_id'  => $value['id'],
                    'start_day' => $day[0],
                    'end_day'   => $day[1],
                ];
                if($status){
                    $res1['status'] = '<span style="color: #01b88a;font-size: larger">在线</span>';
                    // if($method){
                        // $res1['rate'] =  controller("crm/Target","lib")->$method($condition);
                        $res1['rate'] =  $targInfo[$value['id']] ? $targInfo[$value['id']] : 0;
                    // }else{
                        // $res1['rate'] = 0;
                    // }
                    $res1['name'] = $value['staffname'];
                    $res1['id'] = $value['id'];
                    $res1['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;
                    // $res1['cNum'] = controller("crm/Customer","lib")->noStaffId($condition);
                    array_push($a,$res1);
                }else{
                    $res['status'] = '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>';
                    // if($method){
                        // $res['rate'] =  controller("crm/Target","lib")->$method($condition);
                        $res['rate'] =  $targInfo[$value['id']] ? $targInfo[$value['id']] : 0;
                    // }else{
                        // $res['rate'] = 0;
                    // }
                    $res['name'] = $value['staffname'];
                    $res['id'] = $value['id'];
                    $res['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;
                    // $res['cNum'] = controller("crm/Customer","lib")->noStaffId($condition);
                    array_push($b,$res);
                }
                // $return[$key]['status'] = $status ? '<span style="color: #01b88a;font-size: larger">在线</span>' : '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>';
                // $return[$key]['rate'] = controller("crm/Target","lib")->$method($condition);
                // $return[$key]['name'] = $value['staffname'];
                // $return[$key]['id']   = $value['id'];
                // $return[$key]['cNum'] = controller("crm/Customer","lib")->noStaffId($value['id']);
            // }
            }*/

            $res_info_not = $info_not[$value['id']] ? $info_not[$value['id']] : 0;

            // 查看员工是否在线
            $status = controller('Customer','lib')->getStaffOnlineStatus($value['id']);
            if($status){
                $res['status'] = '<span style="color: #01b88a;font-size: larger">在线</span>';
            }else{
                $res['status'] = '<span style="color:#cccccc;font-size: larger">'.'不在线'.'</span>';
            }

            $res['rate'] = $targInfo[$value['id']] ? $targInfo[$value['id']] : 0;
            $res['name'] = $value['staffname'];
            $res['id']   = $value['id'];
            $res['cNum'] = $info[$value['id']] ? $info[$value['id']]."($res_info_not)" : 0;

            array_push($b,$res);
        }

        $return = array_merge($a,$b);
        // print_r($return);die;
        // $return = my_sort($return, 'rate', 'SORT_DESC');
        return json($return);
    }

    // 手动分配 接收
    public function allotReceive(){
        $data = input('post.');
        $type = (int)$data['type'];
        if (!$data['shop_code']) {
            $returnData = ['code'=>99,'msg'=>'请选择客资归属店'];
            return $returnData;
        }

        /*if (!(int)$data['sid']) {
            $returnData = ['code'=>98,'msg'=>'请选择客资接收人'];
            return $returnData;
        }*/

        if (empty($data['sid']) || !$data['sid']) {
            $returnData = ['code'=>98,'msg'=>'请选择客资接收人'];
            return $returnData;
        }
        $sid  = (array)$data['sid'];
        $rigth = check_right('menu1512970623');
        $date = date('Y-m-d H:i:s',time());
        if ($rigth) {
            // var_dump($type);exit;
            // 分配追踪人
            if ($type == 1) {
                $cid = '';
                //如果追踪人已经是要分配的人，去掉 不去掉了
                // $sales = db('crm_c_customerinfo')->where('id','in',$data['cid'])->field('id,sales_staff_id')->select();
                // foreach($sales as $kk=>$vv){
                //     if($vv['sales_staff_id'] != $sid){
                //         $cid  .= $vv['id'].',';
                //     }
                // }
                /*foreach ($data['cid'] as $key => $value) {
                    $cid  .= $value.',';
                }
                $cid = trim($cid,',');*/
                //$arr['cid'] = $cid;
                //$arr['sid'] = (int)$sid;
                $arr['sal'] = $data['shop_code'];
                if ($data['group_id']) {
                    $arr['group_id']  = $data['group_id'];
                    $arr['group_name']= $data['group_name'];
                }
                if ($data['department_id']) {
                    $arr['department_id'] = $data['department_id'];
                    $arr['department_name']= $data['department_name'];
                }
                $arr['shop_code'] = $data['shop_code'];
                $arr['shop_name'] = $data['shop_name'];
                // 配置是否清空客资标记
                if(ini('allot_clean_customersign')){
                    $arr['sign_name'] = '';
                    $arr['sign_id'] = '';
                }
                // 配置是否清空追踪标记
                if (ini('allot_clean_customer_opsign')) {
                    $arr['op_signinfo'] = '';
                    $arr['op_signinfo_id'] = '';
                }
                // 配置是否清空 开始追踪时间
                if (ini('allot_clean_c_star_day')) {
                    $arr['c_star_day'] = '';
                }
                $cid = $data['cid'];
                // $sid = $data['sid'];
                $sid  = (array)$data['sid'];
                $count = ceil(count($cid)/count($sid));
                $a = 0;
                $idArr = [];
                for ($i=0; $i < $count; $i++) {
                    foreach($sid as $key=>$value){
                        if(!empty($cid[$a])){
                            $idArr[$a]['cid'] = $cid[$a];
                            $idArr[$a]['sid'] = $value;
                            $a++;
                        }
                    }
                }
                //查出原客资的相关信息。
                $customerList = db('crm_c_customerinfo')->field('dj_staff_id,sales_staff_id,customer_tel')->where('id','in',$cid)->column('dj_staff_id,sales_staff_id,customer_tel','id');
                // var_dump($arr);
                // exit;
                db()->startTrans();
                try{
                    foreach($idArr as $key=>$value){
                        $arr['sid'] = $value['sid'];
                        $arr['cid'] = $value['cid'];
                        $res = controller("crm/Customer","lib")->allotSale($arr);
                        if ($res['code']!=200) {
                            db()->rollback();
                            return $res;
                        }
                    }
                    db()->commit();
                }catch(Exception $e){
                    db()->rollback();
                    return ['code'=>101,'msg'=>'分配失败'.$e->getMessage()];
                }

                $sidArr = [];//提醒 以提醒人分组---新追踪人
                foreach ($idArr as $key => $value) {
                    $sidArr[$value['sid']]['cid'][] = $value['cid'];
                }
                //提醒设定
                $remindInfo = getRemind(session("brandclass_id"));
                foreach($sidArr as $key=>$value){
                    if(in_array('tan',$remindInfo['sd']['send_method']) && in_array('sales',$remindInfo['sd']['send_receive'])){
                        if($key != session('staff_id')){
                            $mc = new \app\common\lib\mcInterface();
                            $staff = $mc->getOneStaff(['staff_id'=>$key]);//消息接收者

                            $fp_Remind['staff_id'] = $staff['id'];
                            $fp_Remind['title'] = "分配提醒";
                            $fp_Remind['content'] = '您分配到'.count($value['cid']).'笔客资，请查收。';
                            $fp_Remind['staffname'] = $staff['staffname'];
                            $fp_Remind['shop_code'] = $staff['shop_code'];
                            $md5_k = substr(md5($cid.session('staff_id').config('SX_AUTH_KEY')),8,16);
                            $fp_Remind['operation'] = '[{"button":"查看详情","url":"/crm/Customer/customerList?k='.$md5_k.'&id='.$cid.'"}]';
                            $fp_Remind['operation_type'] = 1;
                            $this->tanRemind($fp_Remind);
                        }
                    }
                }

                //登记人客资被分配提醒
                //即：提醒客资登记人---sdm标记
                if(
                    (in_array('tan',$remindInfo['c_allocation']['send_method']) && in_array('dj', $remindInfo['c_allocation']['send_receive']))
                    // or
                    // (in_array('tan',$remindInfo['sd']['send_method']) && in_array('dj', $remindInfo['sd']['send_receive']))
                ){
                    foreach ($idArr as $key => $value) {
                        $customerInfo = $customerList[$value['cid']];
                        if($customerInfo && $customerInfo['dj_staff_id']){
                            if($customerInfo['dj_staff_id'] != session('staff_id')){
                                $mc = new \app\common\lib\mcInterface();
                                $staff = $mc->getOneStaff(['staff_id'=>$customerInfo['dj_staff_id']]);//消息接收者
                                $s_staff = $mc->getOneStaff(['staff_id'=>$value['sid']]);
                                $dj_Remind['staff_id'] = $staff['id'];
                                $dj_Remind['title'] = "客资被分配";
                                $dj_Remind['content'] = "您登记的客资,手机号：".$customerInfo['customer_tel'].",在".date("Y-m-d H:i:s")."被 ".session("staff_name")."分配给了：".$s_staff['staffname'];
                                $dj_Remind['staffname'] = $staff['staffname'];
                                $dj_Remind['shop_code'] = $staff['shop_code'];
                                $md5_k = substr(md5($value['cid'].session('staff_id').config('SX_AUTH_KEY')),8,16);
                                $dj_Remind['operation'] = '[{"button":"查看详情","url":"/crm/Customer/customerList?k='.$md5_k.'&id='.$value['cid'].'"}]';
                                $dj_Remind['operation_type'] = 1;
                                $this->tanRemind($dj_Remind);
                            }
                        }
                    }
                }
                //追踪人客资被转走提醒
                //即：提醒客资原追踪人-----sdm标记
                if(
                    (in_array('tan',$remindInfo['c_transfer']['send_method']) && in_array('sales', $remindInfo['c_transfer']['send_receive']))
                    // or
                    // (in_array('tan',$remindInfo['sd']['send_method']) && in_array('osales', $remindInfo['sd']['send_receive']))
                ){
                    foreach ($idArr as $key => $value) {
                        $customerInfo = $customerList[$value['cid']];
                        if($customerInfo && $customerInfo['sales_staff_id']){
                            if($customerInfo['sales_staff_id'] != session('staff_id')){ //如果客资的原追踪人就是本人，不提醒。
                                $mc = new \app\common\lib\mcInterface();
                                $staff = $mc->getOneStaff(['staff_id'=>$customerInfo['sales_staff_id']]);//消息接收者
                                $s_staff = $mc->getOneStaff(['staff_id'=>$value['sid']]);
                                $zz_Remind['staff_id'] = $staff['id'];
                                $zz_Remind['title'] = "客资被转移";
                                $zz_Remind['content'] = "您追踪的客资，手机号：".$customerInfo['customer_tel'].",在".date("Y-m-d H:i:s")."被 ".session("staff_name")." 转移给了：".$s_staff['staffname'];
                                $zz_Remind['staffname'] = $staff['staffname'];
                                $zz_Remind['shop_code'] = $staff['shop_code'];
                                $md5_k = substr(md5($value['cid'].session('staff_id').config('SX_AUTH_KEY')),8,16);
                                $zz_Remind['operation'] = '[{"button":"查看详情","url":"/crm/Customer/customerList?k='.$md5_k.'&id='.$value['cid'].'"}]';
                                $zz_Remind['operation_type'] = 1;
                                $this->tanRemind($zz_Remind);
                            }
                        }
                    }
                }
                // 发送微信模板消息
                if(in_array('tui',$remindInfo['sd']['send_method']) && in_array('sales',$remindInfo['sd']['send_receive'])){
                    foreach($sidArr as $key=>$value){
                        if($key != session('staff_id')){
                            $content = [
                                'touser'       => $key,
                                'template_id'  => OPENTM_MFP,
                                'data'         => [
                                    'first'=>[
                                        'value'=> '系统消息',
                                        'color'=> '#173177'
                                    ],
                                    'keyword1'=>[
                                        'value'=> '您分配到'.count($value['cid']).'笔客资，请查收。',
                                        'color'=> '#173177'
                                    ],
                                    'keyword2'=>[
                                        'value'=> date("Y-m-d H:i:s",time()),
                                        'color'=> '#173177'
                                    ],
                                    'remark'=>[
                                        'value'=> '请尽快追踪，谢谢',
                                        'color'=> '#173177'
                                    ],
                                ],
                            ];
                            $send_data['content'] = json_encode($content);
                            $res = sendMsg($send_data);
                        }
                    }
                }
                $returnData = ['code'=>1,'msg'=>'分配完成','res'=>$res];
                return $returnData;
            }
            
            // 分配筛客人
            /*
            if ($type == 2) {
                $arr['cid'] = $cid;
                $arr['sid'] = (int)$sid;
                $res = controller("crm/Customer","lib")->allotSk($arr);
                return $res;
            }
            */
        }else{
            $returnData = ['code'=>100,'msg'=>'抱歉，您没有分配权限'];
        }
        return json($returnData);
    }
    /**
     * 弹窗提醒
     * @return [staff_id] [接收消息人员id]
     * @return [staffname] [接收消息人员姓名]
     * @return [title] [消息标题]
     * @return [content] [消息内容]
     * @return [shop_code] [店]
     */
    public function tanRemind($params){
            $date = date('Y-m-d H:i:s',time());

            $messageD['send_type']      = 1;
            $messageD['send_time']      = $date;
            $messageD['send_title']     = $params['title'];
            $messageD['send_msg']       = $params['content'];
            $messageD['receive_id']     = $params['staff_id'];
            $messageD['receive_name']   = $params['staffname'];
            $messageD['receive_status'] = 1;
            $messageD['receive_time']   = $date;
            $messageD['operation_type'] = $params['operation_type']?:2;
            $messageD['operation']      = $params['operation'] ?: '';
            $timeOut = db_config('fp_timeout_'.$params['shop_code']);
            $messageD['time_out']       = $timeOut ? $timeOut : 60;
            $resM = sendSystemMessage($messageD);
    }
    // 手动分配 接收
    public function anotherAllotReceive(){
        $data = input('post.');
        $type = (int)$data['type'];
        $shop_code  = $data['shop_code'];
        $shop_name  = $data['shop_name'];
        $cid  = $data['cid'];
        $sid  = $data['sid'] ? $data['sid'] : session('staff_id');
        $rigth = check_right('menu1541663886');
        $date = date('Y-m-d H:i:s',time());
        if ($rigth) {
            // 分配追踪人
            if ($type == 1) {
                $arr['cid'] = $cid;
                $arr['sid'] = (int)$sid;
                $arr['shop_code'] = $shop_code;
                $arr['shop_name'] = $shop_name;
                $res = controller("crm/Customer","lib")->anotherAllotSale($arr);

                if ($res['code']!=200) {
                    return $res;
                }
                $cids = explode(',', $cid);
                // $url = '59f933a395abe';
                $arr = array('staff_id'=>$sid);
                // $staff = sx_call($url, $arr);
                // $res = $staff['data'];
                
                $mc = new \app\common\lib\mcInterface();
                $staff = $mc->getOneStaff($arr);
                $cNum = count($cids);
                // 发送消息用数据
                $messageD['send_type']      = 1;
                $messageD['send_time']      = $date;
                $messageD['send_title']     = '分配提醒';
                $messageD['send_msg']       = '您分配到'.$cNum.'笔客资，请查收。';
                $messageD['receive_id']     = $sid;
                $messageD['receive_name']   = $staff['staffname'];
                $messageD['receive_status'] = 1;
                $messageD['receive_time']   = $date;
                $messageD['operation_type'] = 1;
                $md5_k = substr(md5($cid.session('staff_id').config('SX_AUTH_KEY')),8,16);
                $messageD['operation']      = '[{"button":"查看详情","url":"/crm/Customer/customerList?k='.$md5_k.'&id='.$cid.'"}]';
                $timeOut = db_config('fp_timeout_'.$staff['shop_code']);
                $messageD['time_out']       = $timeOut ? $timeOut : 60;

                $resM = sendSystemMessage($messageD);

                // 发送微信模板消息
                $content = [
                    'touser'       => $sid,
                    'template_id'  => OPENTM_MFP,
                    'data'         => [
                        'first'=>[
                            'value'=> '系统消息',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> '您分配到'.$cNum.'笔客资，请查收。',
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $date,
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> '请尽快追踪，谢谢',
                            'color'=> '#173177'
                        ],
                    ],
                ];
                $send_data['content'] = json_encode($content);
                $res = sendMsg($send_data);
                $returnData = ['code'=>1,'msg'=>'分配完成'];
                return $returnData;
            }
            // 分配筛客人
            if ($type == 2) {
                $arr['cid'] = $cid;
                $arr['sid'] = (int)$sid;
                $res = controller("crm/Customer","lib")->allotSk($arr);
                return $res;
            }
        }else{
            $returnData = ['code'=>100,'msg'=>'抱歉，您没有分配权限'];
        }
        return json($returnData);
    }
    // 分配动作
    public function customerAllotOne($cid, $sid,$shop_code,$shop_name){
        // 是否存在相应客资
        $has = controller("Customer","lib")->getCustomerInfo($cid);
        if ($has) {
            // if ($has && $has['is_fp']!=1) {
            // 分配人
            $newDate['fp_staff_id'] = session('staff_id');
            $newDate['fp_staff'] = session('staff_name');
            $newDate['fp_staff_number'] = session('staff_number');
            // 接收状态 1：已接收
            $newDate['is_fp'] = FP_STATUS_SUCESS;
            // 接收人
            // 根据员工id获取员工信息
            $arr = array('staff_id'=>$sid);
            $staff = controller("crm/Customer","lib")->get_staff_info($arr);
            $res = $staff['data'];

            $sales = getStaffInfoById($sid);
            $newDate['sales_department_id'] = $sales['department_id'];
            $date = date('Y-m-d H:i:s');
            $newDate['sales_staff_id'] = $sid;
            $newDate['sales_staff'] = $res['staffname'];
            $newDate['sales_staff_number'] = $res['staffnumber'];
            if($has['shop_code'] != $shop_code){
                 $newDate['shop_code'] = $shop_code;
                 $newDate['shop_name'] = $shop_name;
            }

            $newDate['fp_day'] = $date;
            $newDate['jr_day'] = $date;

            // // 发送消息用数据
            // $messageD['send_type']      = 1;
            // $messageD['send_time']      = $date;
            // $messageD['send_title']     = '系统消息';
            // $messageD['send_msg']       = '您收到一笔新客资，姓名：'.$has['customer_name'].'，请查收。';
            // $messageD['receive_id']     = $sid;
            // $messageD['receive_name']   = $res['staffname'];
            // $messageD['receive_status'] = 1;
            // $messageD['receive_time']   = $date;
            // $messageD['operation_type'] = 2;
            // $messageD['operation']      = '';
            // $timeOut = db_config('fp_timeout_'.$res['shop_code']);
            // $messageD['time_out']       = $timeOut;

            // 数据统计  数据
            // 进入数据统计队列
            $cinfo = [
                'id'     => $has['id'],
                'dj_id'  => $has['dj_staff_id'],
                'dj_day' => $has['dj_day'],
                'sel_id' => $has['sel_staff_id'],
                'sel_day'=> $has['sel_day'],
                'jr_id'  => $sid,
                'jr_day' => $date,
            ];
            // 分配日志
            $fpLogData = [
                'cid'              => $has['id'],
                'fp_model'         => 2,
                'fp_status'        => 1,
                'fp_time'          => $date,
                'jr_time'          => $date,
                'fp_staff_id'      => session('staff_id'),
                'fp_staff_name'    => session('staff_name'),
                'fp_shop_code'     => $has['add_shop_code'],
                'fp_shop_name'     => $has['add_shop_name'],
                'fp_brandclass_id' => $has['brandclass_id'],
                'jr_staff_id'      => $sid,
                'jr_staff_name'    => $res['staffname'],
                'jr_shop_code'     => $has['shop_code'],
                'jr_shop_name'     => $has['shop_name'],
            ];
            // var_dump($fpLogData);
            // exit;
            db()->startTrans();
            try {
                $newDate['update_time'] = $date;
                db('crm_c_customerinfo')->where('id', $cid)->update($newDate);
                // $resM = sendSystemMessage($messageD);

                history_log($newDate,$has,$cid,session('staff_id'),session('staff_name'));

                // 分配日志
                $resLog = fpLogs($fpLogData);

                db()->commit();
                $returnData = ['code'=>1,'msg'=>'分配成功'];
                return json($returnData);
            } catch (Exception $e) {
                db()->rollback();
                $returnData = ['code'=>100,'msg'=>'手动分配失败'];
                return json($returnData);
            }
        }

        // $returnData = array('code'=>0,'msg'=>'分配客资成功');
        // return $returnData;
    }

    // 失败在分配
    public function customerReAllot(){
        // 权限
        $rigth = check_right('menu1517042801');

        // 所有分配失败超过10次的客资
        $falseCustomer = db('crm_c_fp_pool')
            ->where('pool_type', 1)
            ->where('count', '>=', 10)->field('cid,msg')->select();

        // 基础查询条件
        $where = [
            'shop_code'=>session('shop_code'),
            'is_status'=>1,
            'c_from'   =>1,
            'is_fp'    =>FP_STATUS_FALSE,
        ];
        // 循环，找出当前员工所在店的客资，push到分配队列，重新分配
        $listName = 'fpCustomerList';
        foreach ($falseCustomer as $key => $value) {
            $fpCustomer = db('crm_c_customerinfo')
                ->where('id', $value['cid'])
                ->where($where)
                ->count();
            // 如果该客资属于当前员工所在店，重新分配
            if ($fpCustomer) {
                $msg = json_decode($value['msg']);
                push_list($listName, $msg);
            }
        }
    }
    // 员工接收客资 Eric
    public function customerReceive($cid, $mid){
        // $returnData = array('code' => 1,'msg' =>'成功接收客资。cid:'.$cid.';mid:'.$mid);
        // return json($returnData);
        $arrcid = explode(',',$cid);
        $arrmid = explode('_',$mid);
        if(count($arrcid) > 1){
            foreach($arrcid as $k=>$v){
                // 查询 客资表
                $where = array(
                    'id'             => $arrcid[$k],
                    'is_fp'          => FP_STATUS_DJS,
                    // 'jr_day'         => null,
                    'sales_staff_id' => session('staff_id')
                );
                $cInfo = db('crm_c_customerinfo')->where($where)->find();

                // $where = [
                //     'id' => $cid,
                // ];
                // $cInfo = controller("Customer","lib")->getCustomerInfo($cid);

                // 该客资不存在  或者该客资已经被接收
                if (!$cInfo) {
                    // $returnData = array('code' => 111,'msg' =>'该客资已经被接收');
                    // return json($returnData);
                    continue;
                }

                // 查询  消息表
                $whereM = array(
                    'id'            => $arrmid[$k],
                    'receive_id'    => session('staff_id'),
                    'receive_status'=> 0,
                    'is_delete'     => 0
                );
                $message = db('crm_c_message')->where($whereM)->find();

                unset($whereM);
                if (!$message) {
                    // $returnData = array('code' => 222,'msg' =>'该客资不存在或已经被接收');
                    // return json($returnData);
                    continue;
                }
                // 查看店面设定时间
                $timeOut = db_config('fp_timeout_'.session('shop_code'));

                // 计算过期时间
                $endTime = $message['time_out'];
                $time = time();
                // 如果当期时间小于过期时间，超时
                if ($time >= $endTime) {
                    // $returnData = array('code' => 333,'msg' =>'已超时，获取客资失败');
                    // return json($returnData);
                    continue;
                }

                // 提交 客资表  和  消息表  (事务)
                $dataC = [];
                $dataC['is_fp']  = 1;
                $dataC['jr_day'] = date('Y-m-d H:i:s', $time);
                $whereC = $where;

                $date = date('Y-m-d H:i:s', $time);
                $dataM['read_time'] = $date;
                $dataM['read_status'] = 1;
                $dataM['receive_time'] = $date;
                $dataM['receive_status'] = 1;
                $whereM['id'] = $arrmid[$k];

                $libCustomer = controller("Customer","lib");
                $res= $libCustomer->updateCM($dataC, $whereC, $dataM, $whereM);

                if ($res === false) {
                    // $error = $libCustomer->getError();
                    // $returnData = array('code' => 444,'msg' =>'更新失败，请联系管理员'.$error);
                    // return json($returnData);
                    continue;
                }
                $from = db('crm_c_customerinfo')->where('id',$arrcid[$k])->find();
                if($from['cid']){
                    if(empty($from['sales_group_id'])){
                        //更新追踪人小组信息
                        $group = array(
                            'sales_group_id'  => session('group_id'),
                            'sales_group_name'  => session('group_name'),
                        );
                        db('crm_c_customerinfo')->where('id','in',$arrcid[$k])->update($group);
                    }
                    if(empty($from['dj_group_id'])){
                        //登记人小组信息
                         $Info = getStaffInfoById($cInfo['dj_staff_id']);
                        //更新追踪人小组信息
                        db('crm_c_customerinfo')->where('id','in',$arrcid[$k])->update(['dj_group_id'=>$Info['group_id'],'dj_group_name'=>$Info['group_name']]);
                    }
                }else{
                    //登记人追踪人小组信息
                    $Info = getStaffInfoById($cInfo['dj_staff_id']);
                    $group = array(
                        'dj_group_id'=>$Info['group_id'],
                        'dj_group_name'=>$Info['group_name'],
                        'sales_group_id'  => session('group_id'),
                        'sales_group_name'  => session('group_name'),
                    );
                    db('crm_c_customerinfo')->where('id',$arrcid[$k])->update($group);
                }
                // 接收成功之后，删除c_fp_pool
                db('crm_c_fp_pool')->where('cid', $arrcid[$k])->delete();

                // 数据统计队列
                $old_data['is_fp'] = 3;
                $old_data['jr_date'] = null;
                $old_data['customer_tel'] = $cInfo['customer_tel'];
                $dataC['customer_tel'] = $cInfo['customer_tel'];

                $cinfo = [
                    'id'     => $cInfo['id'],
                    'dj_id'  => $cInfo['dj_staff_id'],
                    'dj_day' => $cInfo['dj_day'],
                    'sel_id' => $cInfo['sel_staff_id'],
                    'sel_day'=> $cInfo['sel_day'],
                    'jr_id'  => $cInfo['sales_staff_id'],
                    'jr_day' => $dataC['jr_day'],
                ];

                // 更新分配日志中的状态
                $fpLogData = [
                    'fp_status' => 1,
                    'jr_time'   => $date,
                ];

                db('crm_l_fp_logs')
                    ->where('cid', $cid)
                    ->where('fp_status', 3)
                    ->where('fp_staff_id', 0)
                    ->where('jr_staff_id', session('staff_id'))
                    ->where('fp_time', $cinfo['fp_day'])
                    ->update($fpLogData);
            }
        }else{
            // 查询 客资表
            $where = array(
                'id'             => $cid,
                'is_fp'          => FP_STATUS_DJS,
                // 'jr_day'         => null,
                'sales_staff_id' => session('staff_id')
            );
            $cInfo = db('crm_c_customerinfo')->where($where)->find();

            // $where = [
            //     'id' => $cid,
            // ];
            // $cInfo = controller("Customer","lib")->getCustomerInfo($cid);

            // 该客资不存在  或者该客资已经被接收
            if (!$cInfo) {
                $returnData = array('code' => 111,'msg' =>'该客资已经被接收');
                return json($returnData);
            }

            // 查询  消息表
            $whereM = array(
                'id'            => $mid,
                'receive_id'    => session('staff_id'),
                'receive_status'=> 0,
                'is_delete'     => 0
            );
            $message = db('crm_c_message')->where($whereM)->find();

            unset($whereM);
            if (!$message) {
                $returnData = array('code' => 222,'msg' =>'该客资不存在或已经被接收');
                return json($returnData);
            }
            // 查看店面设定时间
            $timeOut = db_config('fp_timeout_'.session('shop_code'));

            // 计算过期时间
            $endTime = $message['time_out'];
            $time = time();
            // 如果当期时间小于过期时间，超时
            if ($time >= $endTime) {
                $returnData = array('code' => 333,'msg' =>'已超时，获取客资失败');
                return json($returnData);
            }

            // 提交 客资表  和  消息表  (事务)
            $dataC['is_fp']  = 1;
            $dataC['jr_day'] = date('Y-m-d H:i:s', $time);
            $whereC = $where;

            $date = date('Y-m-d H:i:s', $time);
            $dataM['read_time'] = $date;
            $dataM['read_status'] = 1;
            $dataM['receive_time'] = $date;
            $dataM['receive_status'] = 1;
            $whereM['id'] = $mid;

            $libCustomer = controller("Customer","lib");
            $res= $libCustomer->updateCM($dataC, $whereC, $dataM, $whereM);

            if ($res === false) {
                $error = $libCustomer->getError();
                $returnData = array('code' => 444,'msg' =>'更新失败，请联系管理员'.$error);
                return json($returnData);
            }
            $from = db('crm_c_customerinfo')->where('id',$cid)->find();
            if($from['cid']){
                if(empty($from['sales_group_id'])){
                    //更新追踪人小组信息
                    $group = array(
                        'sales_group_id'  => session('group_id'),
                        'sales_group_name'  => session('group_name'),
                    );
                    db('crm_c_customerinfo')->where('id','in',$cid)->update($group);
                }
                if(empty($from['dj_group_id'])){
                    //登记人小组信息
                     $Info = getStaffInfoById($cInfo['dj_staff_id']);
                    //更新追踪人小组信息
                    db('crm_c_customerinfo')->where('id','in',$cid)->update(['dj_group_id'=>$Info['group_id'],'dj_group_name'=>$Info['group_name']]);
                }
            }else{
                //登记人追踪人小组信息
                $Info = getStaffInfoById($cInfo['dj_staff_id']);
                $group = array(
                    'dj_group_id'=>$Info['group_id'],
                    'dj_group_name'=>$Info['dj_group_name'],
                    'sales_group_id'  => session('group_id'),
                    'sales_group_name'  => session('group_name'),
                );
                db('crm_c_customerinfo')->where('id',$cid)->insert($group);
            }
            // 接收成功之后，删除c_fp_pool
            db('crm_c_fp_pool')->where('cid', $cid)->delete();

            // 数据统计队列
            $old_data['is_fp'] = 3;
            $old_data['jr_date'] = null;
            $old_data['customer_tel'] = $cInfo['customer_tel'];
            $dataC['customer_tel'] = $cInfo['customer_tel'];

            $fpLogData = [
                'fp_status' => 1,
                'jr_time'   => $date,
            ];
            db('crm_l_fp_logs')
                ->where('cid', $cid)
                ->where('fp_status', 3)
                ->where('fp_staff_id', 0)
                ->where('jr_staff_id',$cInfo['sel_staff_id'])
                ->where('fp_time', $date)
                ->update($fpLogData);
        }

        $returnData = array('code' => 1,'msg' =>'成功接收客资');
        return json($returnData);
    }

    // 员工放弃客资 或者倒计时结束 Eric
    public function customerDrop($cid, $mid){
        $arrcid = explode(',',$cid);
        $arrmid = explode('_',$mid);
        if(count($arrcid) > 1){
            foreach($arrcid as $k=>$v){
                $where = array(
                    'id'             => $arrcid[$k],
                    'is_fp'          => 3,
                    'sales_staff_id' => session('staff_id')
                );
                $cInfo = db('crm_c_customerinfo')->where($where)->field('shop_code,dj_staff_id')->find();
                // 该客资不存在或者，该客资已经被接收
                if (!$cInfo) {
                    // $returnData = array('code' => 111,'msg' =>'该客资不存在');
                    // return json($returnData);
                    continue;
                }

                $whereM = array(
                    'id'            => $arrmid[$k],
                    'receive_id'    => session('staff_id'),
                    'receive_status'=> 0,
                    'is_delete'     => 0
                );
                $mCount = db('crm_c_message')->where($whereM)->count();

                if (!$mCount) {
                    // $returnData = array('code' => 222,'msg' =>'该客资不存在或已经被接收');
                    // return json($returnData);
                    continue;
                }
                $date = date('Y-m-d H:i:s');

                $dataM['read_time'] = $date;
                $dataM['read_status'] = 1;
                $dataM['receive_time'] = $date;
                $dataM['receive_status'] = 2;

                $res = db('crm_c_message')->where('id', $arrmid[$k])->update($dataM);

                // 重新放入分配队列
                $listName = 'fpCustomerList';
                $msg['receive']  = '-1';
                // 客资id
                $msg['body']     = $arrcid[$k];
                // 录入人的id
                $msg['staff_id'] = $cInfo['dj_staff_id'];
                // 客资的归属店的shop_code
                $msg['shop_code']= $cInfo['shop_code'];
                // redisQueue::init()->rPush($listName, $msg);
                push_list($listName, $msg);
                unset($msg);
                // customer放弃，修改状态
                $cData = [
                    'is_fp'             => FP_STATUS_STA,
                    'sales_staff'       => null,
                    'sales_staff_id'    => null,
                    'sales_staff_number'=> null,
                    'fp_day'            => null,
                    'update_time'       => date('Y-m-d H:i:s')
                ];
                db('crm_c_customerinfo')->where('id', $arrcid[$k])->update($cData);

                // 更新分配日志中的状态
                $fpLogData = [
                    'jr_time'   => $date,
                    'fp_status' => 5
                ];
                db('crm_l_fp_logs')
                    ->where('cid', $cInfo['id'])
                    ->where('fp_status', 3)
                    ->where('fp_staff_id', 0)
                    ->where('jr_staff_id', session('staff_id'))
                    ->where('fp_time', $cInfo['fp_day'])
                    ->update($fpLogData);
            }
        }else {
            $where = array(
                'id' => $cid,
                'is_fp' => 3,
                'sales_staff_id' => session('staff_id')
            );
            $cInfo = db('crm_c_customerinfo')->where($where)->field('shop_code,dj_staff_id')->find();
            // 该客资不存在或者，该客资已经被接收
            if (!$cInfo) {
                $returnData = array('code' => 111, 'msg' => '该客资不存在');
                return json($returnData);
            }

            $whereM = array(
                'id' => $mid,
                'receive_id' => session('staff_id'),
                'receive_status' => 0,
                'is_delete' => 0
            );
            $mCount = db('crm_c_message')->where($whereM)->count();

            if (!$mCount) {
                $returnData = array('code' => 222, 'msg' => '该客资不存在或已经被接收');
                return json($returnData);
            }
            $date = date('Y-m-d H:i:s');

            $dataM['read_time'] = $date;
            $dataM['read_status'] = 1;
            $dataM['receive_time'] = $date;
            $dataM['receive_status'] = 2;

            $res = db('crm_c_message')->where('id', $mid)->update($dataM);

            // 重新放入分配队列
            $listName = 'fpCustomerList';
            $msg['receive'] = '-1';
            // 客资id
            $msg['body'] = $cid;
            // 录入人的id
            $msg['staff_id'] = $cInfo['dj_staff_id'];
            // 客资的归属店的shop_code
            $msg['shop_code'] = $cInfo['shop_code'];
            // redisQueue::init()->rPush($listName, $msg);
            push_list($listName, $msg);
            unset($msg);
            // customer放弃，修改状态
            $cData = [
                'is_fp' => FP_STATUS_STA,
                'sales_staff' => null,
                'sales_staff_id' => null,
                'sales_staff_number' => null,
                'fp_day' => null,
                'update_time' => date('Y-m-d H:i:s')
            ];
            db('crm_c_customerinfo')->where('id', $cid)->update($cData);
            // 更新分配日志中的状态
            $fpLogData = [
                'jr_time'   => $date,
                'fp_status' => 5
            ];
            db('crm_l_fp_logs')
                ->where('cid', $cInfo['id'])
                ->where('fp_status', 3)
                ->where('fp_staff_id', 0)
                ->where('jr_staff_id', session('staff_id'))
                ->where('fp_time', $cInfo['fp_day'])
                ->update($fpLogData);
            // echo db()->getLastSql();
        }
        $returnData = array('code' => 0,'msg' =>'已放弃');
        return json($returnData);
    }

    // 倒计时结束  或者  点右上角的 ×  标记已读
    // 同时获取最新的列表
    public function readMessage(){
        $id = (int)input('post.msg_id');
        $maxId = (int)input('post.max_msg_id');
        // var_dump($id);
        // exit;
        // $msgInfo = db()->
        $res= controller('crm/Customer','lib')->update_message($id);
        if($maxId){
            $messageList = controller("Customer","lib")->getMessageList(0);
            $noRead = controller("Customer","lib")->getNewMessageNum($maxId);
            $return['mid'] = $id;
            $return['noRead'] = $noRead?$noRead:0;
            $return['messageList'] = $messageList;
            $return['popList'] = [];
            return json($return);
        }
        // $date = date('Y-m-d H:i:s');
        // $data['read_status'] = 1;
        // $data['read_time'] = $date;
        // $res = db('CMessage')->where('id',$id)->update($data);

        // $whereCount=[
        //     'receive_id' => session('staff_id'),
        //     'read_status'=> 0,
        //     'is_delete'  => 0
        // ];
        // $noRead = db('crm_c_message')->where($whereCount)->count();
        return $res;
    }

    // 员工请求  ajax递归，订阅发布频道
    public function staffSubscribe($msg_id){
        // 第一次请求，$msg_id == 0
        // list1：最近10条消息，不区分已读未读；messageList
        // list2：最近五条未读弹框消息 popList
        // noRead：未读消息数目
        // mid：最近一条消息的id
        // 之后的请求  $msg_id != 0
        // 数据库对比最后一条消息的id
        //   一样 则 订阅频道
        // 不一样 则 取出后面的消息，两个list弹框和铃铛，noRead，mid
        $info = cache('staffInfo_'.session('staff_id'));
        $info['active'] = time();
        cache('staffInfo_'.session('staff_id'),json_encode($info));
        if(date('i')%10 == 0){
            $res = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>session('staff_id')));
            if($res['code'] == 200){
                $leave_date = $res['data']['leave_date'];
                if($leave_date && ($leave_date<=date('Y-m-d'))){
                    controller('crm/Customer','lib')->logOut(session('staff_id'));
                }
            }
        }
        // 第一次请求
        if ($msg_id == 0 || !$msg_id) {
            // 获取最近10条消息
            $messageList = controller("Customer","lib")->getMessageList($msg_id);
            // 需要弹窗的最近五条消息
            $popList = controller("Customer","lib")->getPopList($msg_id);
            // 没有获取到数据   开启监听
            if (!$messageList) {
                $channel = array('notice');
                $callback= 'noticeCallBack';
                $message = controller("Customer","lib")->webSubscribe($channel, $callback);
                // 监听频道超时
                if ($message === false) {
                    $return['mid']        = $msg_id;
                    $return['noRead']     = controller("Customer","lib")->getNewMessageNum();
                    $return['popList']    = array();
                    $return['messageList']= array();
                    return json($return);
                }

                $messageList = array($message);
                $popList = array($message);

                $return['mid']        = $message['id'];
                $return['noRead']     = controller("Customer","lib")->getNewMessageNum();
                $return['popList']    = array($message);
                $return['messageList']= array($message);
                return json($return);
            }
        }else{
            // 最新的消息id
            $mid = controller("Customer","lib")->getNewMessageId();
            // 新消息id大于传值id
            if ($mid > $msg_id) {
                // 获取新的消息，即大于传值id的消息
                $messageList = controller("Customer","lib")->getMessageList($msg_id);
                // 获取新的弹框消息，即大于传值id的消息
                $popList = controller("Customer","lib")->getPopList($msg_id);
            }else{
                // 开启监听
                $channel = array('notice');
                $callback= 'noticeCallBack';
                $message = controller("Customer","lib")->webSubscribe($channel, $callback);

                // 监听频道超时
                if ($message === false) {
                    $return['mid']        = $msg_id;
                    $return['noRead']     = controller("Customer","lib")->getNewMessageNum();
                    $return['popList']    = array();
                    $return['messageList']= array();
                    return json($return);
                }

                $messageList = array($message);
                $popList = array($message);

                $return['mid']        = $message['id'];
                $return['noRead']     = controller("Customer","lib")->getNewMessageNum();
                $return['popList']    = array($message);
                $return['messageList']= array($message);
                return json($return);
            }
        }
        // 获取最近一条消息id
        $mid = controller("Customer","lib")->getNewMessageId();
        // 获取未读 消息数目
        $noRead = controller("Customer","lib")->getNewMessageNum();

        $return['mid'] = $mid;
        $return['noRead'] = $noRead;
        $return['messageList'] = $messageList;
        $return['popList'] = $popList;

        //循环请求mc查询微信新消息
        controller("weixin/Weixin","controller")->getWxsendSystemMessage();

        return json($return);
    }

    // 判断分配权限
    public function checkRight($code){
        if (!check_right($code)) {
            $returnData = ['code'=>100, 'msg'=>'您现在没有分配权限'];
        }else{
            $returnData = ['code'=>0, 'msg'=>''];

        }
        return json($returnData);
    }

    // 获取部门信息 Eric
    public function getDepartment(){
        $param = input();
        $shop_code = trim($param['shop_code']) ? trim($param['shop_code']) : session('shop_code');
        // $url = '5a0aef152b750';
        $arr = array('shop_code'=>$shop_code);
        // $staffs = sx_call($url, $arr);
        // return $staffs['data'];
        $mc = new \app\common\lib\mcInterface();
        $departmentList = $mc->getDepartment($arr);
        if ($departmentList === false) {
            $departmentList = [];
        }
        return $departmentList;
    }
    // 获取店下的员工 Eric 20200115
    public function getShopStaff(){
        $param = input();
        $arr['shop_code'] = trim($param['shop_code']) ? trim($param['shop_code']) : session('shop_code');
        $mc = new \app\common\lib\mcInterface();
        $shopStaff = $mc->getStaffInfo($arr);
        return $shopStaff;
    }
    // 获取部门信息 wzy
    public function getDepartments($data=[]){
        $param = input() ? input() : $data;
        // $url = '5a0aef152b750';
        // $staffs = sx_call($url, $data);
        // return $staffs['data'];
        $mc = new \app\common\lib\mcInterface();
        $departmentList = $mc->getDepartment($param);
        if ($departmentList === false) {
            $departmentList = [];
        }
        return $departmentList;
    }

    // 根据部门id获取部门下的员工
    // 获取在职的，且含兼职的人员
    public function getDepartmentStaffs($department_id){
        // $url = '5a0e6f272bb38';
        $arr = array('department_id'=>$department_id,'get_leave'=>2,'get_main'=>2);
        // $staffs = sx_call($url, $arr);
        // return $staffs['data'];
        $mc = new \app\common\lib\mcInterface();
        $staffs = $mc->getStaffByDepartment($arr);
        if ($staffs === false) {
            $staffs = [];
        }
        return $staffs;
    }

    // 显示驳回页面
    public function customerValid(){
        // 权限
        $auth = check_right('menu1517278817');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有驳回权限，请先设置权限');
            return json($return);
            exit;
        }
        $cid = input('get.cid');
        $this->assign('cid',$cid);
        return $this->fetch();
    }
    // 显示反驳回页面
    public function customerUnValid(){
        // 权限
        $auth = check_right('menu1517278844');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有反驳回权限，请先设置权限');
            return json($return);
            exit;
        }
        $cid = input('get.cid');
        $this->assign('cid',$cid);
        return $this->fetch();
    }
    // 标记无效时，追踪人上传的文件（图片或者音频）
    public function uploadIsValid(){
        $cid = input('get.cid');
        $file = request()->file('file');

        if (empty($file)) {
            $result["code"] = "1";
            $result["msg"] = "请选择图片";
            $result['data']["src"] = '';
        }else{
            // 移动到 目录下
            $info = $file->move(ROOT_PATH.'public'.DS.'upload'.DS.'img');
            if($info){
                $name_path =str_replace('\\',"/",$info->getSaveName());
                //print_r(strrchr($name_path,'.'));die;
                //成功上传后 获取上传信息
                $result["code"] = '0';
                $result["msg"] = "上传成功";
                $result['data']["src"] = DS.'upload'.DS.'img'.DS.$name_path;
                // $url = urlencode($result['data']["src"]);
                // var_dump($url);
                $key = 'validFileUrl_'.$cid;
                $str = cache($key);
                // var_dump($str);
                if ($str) {
                    $arr = unserialize($str);
                    array_push($arr, $result['data']["src"]);
                    $arr = serialize($arr);
                    // $str .= '<br /><img src="'.$result['data']["src"].'" class="valid" alt="">';
                }else{
                    $arr = array('0'=>$result['data']["src"]);
                    $arr = serialize($arr);
                    // $str = '<img src="'.$result['data']["src"].'" class="valid" alt="">';
                }
                // var_dump($arr);
                cache($key, $arr);
                // exit;
            }else{
                // 上传失败获取错误信息
                $result["code"] = "2";
                $result["msg"] = "上传出错";
                $result['data']["src"] ='';
            }
        }
        return json($result);
    }
    // 反驳回时，上传的文件（图片或者音频）
    public function uploadIsUnValid(){
        $cid = input('get.cid');
        $file = request()->file('file');

        if (empty($file)) {
            $result["code"] = "1";
            $result["msg"] = "请选择图片";
            $result['data']["src"] = '';
        }else{
            // 移动到 目录下
            $info = $file->move(ROOT_PATH.'public'.DS.'upload'.DS.'img');
            if($info){
                $name_path =str_replace('\\',"/",$info->getSaveName());
                //print_r(strrchr($name_path,'.'));die;
                //成功上传后 获取上传信息
                $result["code"] = '0';
                $result["msg"] = "上传成功";
                $result['data']["src"] = DS.'upload'.DS.'img'.DS.$name_path;
                // $url = urlencode($result['data']["src"]);
                // var_dump($url);
                $key = 'unvalidFileUrl_'.$cid;
                $str = cache($key);
                // var_dump($str);
                if ($str) {
                    $arr = unserialize($str);
                    array_push($arr, $result['data']["src"]);
                    $arr = serialize($arr);
                    // $str .= '<br /><img src="'.$result['data']["src"].'" class="valid" alt="">';
                }else{
                    $arr = array('0'=>$result['data']["src"]);
                    $arr = serialize($arr);
                    // $str = '<img src="'.$result['data']["src"].'" class="valid" alt="">';
                }
                // var_dump($arr);
                cache($key, $arr);
                // exit;
            }else{
                // 上传失败获取错误信息
                $result["code"] = "2";
                $result["msg"] = "上传出错";
                $result['data']["src"] ='';
            }
        }
        return json($result);
    }
    // 确定客资驳回动作 ****
    public function customerValidUpdate(){
        // 权限
        $auth = check_right('menu1517278817');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有驳回权限，请确认。');
            return json($return);
            exit;
        }

        // 取post值
        $cid = (int)input('post.cid');
        $send_msg = input('post.send_msg').'<br />';


        // 根据cid取客资名称和编号
        $cInfo = db('crm_c_customerinfo')->where('id', $cid)->field('is_valid,customer_name, customer_number, dj_staff_id,dj_staff, sk_staff_id, sk_staff,sales_staff_id,c_unique')->find();
        if($cInfo['is_valid'] == 4){
            return array('code'=>500,'msg'=>'已是驳回客资,不用再次驳回！');
        }
        if(check_right('menu1517278817') || session('staff_id') == $cInfo['sales_staff_id']){
            db()->startTrans();
            // 更新 客资表，插入  追踪记录表
            try {
                // 更新客资表
                $data = ['is_valid'=>'4','yx_day'=>date('Y-m-d H:i:s',time())];
                db('crm_c_customerinfo')->where('id', $cid)->update($data);
                // 取cache值
                $key = 'validFileUrl_'.$cid;
                // var_dump($key);
                $str = cache($key);
                // var_dump($str);
                if ($str) {
                    // 删除cache
                    cache($key, NUll);
                    $arr = unserialize($str);
                    // 循环cache中取出来的图片，拼接img标签
                    foreach ($arr as $key => $value) {
                        $send_msg .= '<img src="'.$value.'" class="images" layer-src="'.$value.'" alt="">';
                    }
                }
                // var_dump($send_msg);
                // 写入追踪表
                $dataValid = [
                    'gtType'            => '4',
                    'c_unique'       => $cInfo['c_unique'],
                    'customer_id'       => $cid,
                    'customer_name'     => $cInfo['customer_name'],
                    'customer_number'   => $cInfo['customer_number'],
                    'sales_day'         => date('Y-m-d H:i:s'),
                    'sales_staff'       => session('staff_name'),
                    'sales_staff_id'    => session('staff_id'),
                    'sales_staff_number'=> session('staff_number'),
                    'shop_name'         => session('shop_name'),
                    'shop_code'         => session('shop_code'),
                    'sales_remark'      => '客资驳回:'.$send_msg,
                ];
                db('crm_c_salestrackinginfo')->insert($dataValid);
                getSalesTracking($cid);//获取最近三次追踪记录同步更新到客资表
                // echo db()->getLastSql();

                // 向上一级发信息  PC消息
                if ($cInfo['sk_staff_id']) {
                    $receive_id  = $cInfo['sk_staff_id'];
                    $receive_name= $cInfo['sk_staff'];
                }else{
                    $receive_id  = $cInfo['dj_staff_id'];
                    $receive_name= $cInfo['dj_staff'];
                }
                $msg = input('post.send_msg');
                $remind = getRemind(session('brandclass_id'));
                // 181212 Eric
                if($receive_id  != session('staff_id') && in_array('tan',$remind['bh']['send_method']) && in_array('dj',$remind['bh']['send_receive'])){
                    $message['send_type']      = 1;
                    $message['send_title']     = '驳回提醒';
                    $message['send_msg']       = '您有一笔客资被驳回，姓名：'.$cInfo['customer_name'].'，驳回理由：'.$msg.'，请确认。';
                    $message['customer_id']    = $cid;
                    $message['receive_id']     = $receive_id;
                    $message['receive_name']   = $receive_name;
                    $message['receive_status'] = 0;
                    $message['operation_type'] = 1;
                    $md5_k = substr(md5($cid.session('staff_id').config('SX_AUTH_KEY')),8,16);
                    $message['operation'] = '[{"button":"查看详情","url":"/crm/Customer/customerList?k='.$md5_k.'&id='.$cid.'"}]';

                    $message['time_out'] = 120;
                    $sendStatus = sendSystemMessage($message);
                }


                // 向上一级发信息  微信
                if($receive_id  != session('staff_id') && in_array('tui',$remind['bh']['send_method']) && in_array('dj',$remind['bh']['send_receive'])){
                    $content = [
                        'touser'       => $receive_id,
                        'template_id'  => OPENTM_BH,
                        'data'         => [
                            'first'=>[
                                'value'=> '您好，您有一笔客资被驳回',
                                'color'=> '#173177'
                            ],
                            'keyword1'=>[
                                'value'=> $cInfo['customer_name'].'('.$cInfo['customer_sex'].')',
                                'color'=> '#173177'
                            ],
                            'keyword2'=>[
                                'value'=> $cInfo['customer_tel'],
                                'color'=> '#173177'
                            ],
                            'keyword3'=>[
                                'value'=> session('staff_name'),
                                'color'=> '#173177'
                            ],
                            'keyword4'=>[
                                'value'=> $msg,
                                'color'=> '#173177'
                            ],
                            'keyword5'=>[
                                'value'=> date('Y-m-d'),
                                'color'=> '#173177'
                            ],
                            'remark'=>[
                                'value'=>'请您尽快处理驳回信息，谢谢',
                                'color'=>'#173177'
                            ]
                        ]
                    ];
                    $send_data['content'] = json_encode($content);
                    $res = sendMsg($send_data);
                }


                if ($sendStatus) {
                    action_log(input('post.'), '', $cid, session('staff_id'), session('staff_name'));
                    db()->commit();
                    $return = ['msg'=>'已驳回','code'=>200];
                }else{
                    db()->rollback();
                    $return = ['msg'=>'操作失败，请联系管理员','code'=>100];
                }
            } catch (Exception $e) {
                $return = ['msg'=>'操作失败，请联系管理员','code'=>300,'data'=>$e->getMessage()];
                db()->rollback();
            };
        }else{
            $return = ['msg'=>'您不是当前客资的追踪人或筛客人或没有驳回权限','code'=>400];
        }
        return $return;
    }
    // 确定客资反驳回动作 ****
    public function customerUnValidUpdate(){
        // 权限
        $auth = check_right('menu1517278844');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有反驳回权限，请先设置权限');
            exit;
        }
        $return = controller('crm/Customer','lib')->customerUnValidUpdate(input());
        return json($return);
    }
    // 客资驳回时，取消或者×，关闭窗口
    public function delValid(){
        // 清除缓存
        $cid = input('post.cid');
        $key = 'validFileUrl_'.$cid;
        $str = cache($key);
        cache($key, NUll);
        // 删除 上传 文件
        $arr = unserialize($str);
        foreach ($arr as $key => $value) {
            $imgurl = ROOT_PATH.$value;
            $res = unlink($imgurl);
        }
        return true;
    }
    // 获取订单所有服务信息 0613
    public function getAllServiceInfo(){
        $data = input();
        // $order_sn = $data['order_sn'];
        // $order_sn = 'SY18020600018';

        $res = getAllServiceInfo($data);
        $this->assign('res', $res);

        $this->assign('data', $data);
        return $this->fetch();

        /*// 是否安装erp
        $is_erp = is_install('sx_erp');
        if ($is_erp) {
            $erp = config('ext.app_config')['sx_erp'];
            $shop_type = session('shop_type');
            $tel = 1;
            if ($shop_type == 2) {
                $shop_type = 1;
                $addr= $erp['addr_child'];
                $url = trim($addr,'/').'/SX_ChildCrmApi/Sel_AllCustomerOrderInfo?Token=^******^&Phone='.$tel.'&OrderId='.$order_sn;
            }else{
                $shop_type = 0;
                $addr= $erp['addr'];
                $url = trim($addr,'/').'/SX_CrmApi/Sel_AllCustomerOrderInfo?Token=^******^&Phone='.$tel.'&OrderId='.$order_sn;
            }
            $dataErp = '[]';
            ec
            $response = requestERP($url, $dataErp);
            if ($response['Code'] == 200) {
                // 基础信息  订单表
                $baseInfo = $response['Data']['ds'];
                // var_dump($baseInfo);
                $this->assign('baseInfo', $baseInfo);
                // 产品信息  消费项目
                $cpInfo = $response['Data']['ds1'];
                $this->assign('cpInfo', $cpInfo);
                // 摄影信息
                $syInfo = $response['Data']['ds2'];
                $this->assign('syInfo', $syInfo);
                print_r($syInfo);
                // 选片信息
                $xpInfo = $response['Data']['ds3'];
                $this->assign('xpInfo', $xpInfo);
                // 收款信息
                $skInfo = $response['Data']['ds4'];
                $this->assign('skInfo', $skInfo);
                // // 化妆信息
                // $hzInfo = $response['Data']['C_makeup'];
                // $this->assign('hzInfo', $hzInfo);
                // // 礼服信息
                // $lfInfo = $response['Data']['C_dress'];
                // $this->assign('lfInfo', $lfInfo);
                //  var_dump($lfInfo);
            }
        }
        // exit;
        $this->assign('order_sn', $order_sn);
        return $this->fetch();*/
    }
    //客资详情
    public function customerInfo(){
        // 提交客资详情资料
        if (request()->isPost()) {
            $data = input('post.');

            // 如果，手机号，微信，微博，都不存在，返回报错
            if (!$data['customer_tel'] && !$data['customer_wechat']) {
                $returnData = array('code' => 300,'msg' =>'请填写手机号、微信任一项联系方式');
                return json($returnData);
            }
            if (!$data['baby_birthday'] && !$data['ready_baby_day'] && !$data['record_day']) {
                $returnData = array('code' => 301,'msg' =>'请填写宝宝生日、预产期、填写日期任一项');
                return json($returnData);
            }
            // 渠道不存在，返回报错
            if (!$data['customer_channel_id'] && !$data['customer_channel']) {
                $returnData = array('code' => 400,'msg' =>'请填写该获取的渠道名称');
                return json($returnData);
            }
            if (!$data['id']) {
                $returnData = array('code' => 100,'msg' =>'用户ID数据为空，请重试');
                return json($returnData);
            }
            //$has = controller("crm/Customer","lib")->getCustomerInfo($data['id']);
            $has = db('crm_c_customerinfo')->find($data['id']);
            if (!$has) {
                $returnData = array('code' => 900,'msg' =>'用户数据不存在，请检查！');
                return json($returnData);
            }
            // 验证手机号正则 (父母)
            $contact = checkContact($data);
            if ($contact['code'] != 200) {
                return $contact;
            }

            // 如果是转介绍客资
            if ($has['customer_type'] == 2) {
                $customer_channel = '';
            }else{
                $customer_channel = $has['customer_channel'];
            }
            // 组织结构
            $orz = [
                'add_shop_code'=> $has['add_shop_code'],
                'shop_code'    => $has['shop_code'],
                'brandclass'   => $has['brandclass'],
            ];
            // 联系方式
            $exclusion_field = config('exclusion_field');
            $con = [];
            $customer_tel = $data['customer_tel'];
            if ($customer_tel && $has['customer_tel'] != $customer_tel  && in_array('customer_tel',$exclusion_field)) {
                $con['customer_tel'] = $customer_tel;
            }
            $customer_wechat = $data['customer_wechat'];
            if ($customer_wechat && $has['customer_wechat'] != $customer_wechat  && in_array('customer_wechat',$exclusion_field)) {
                $con['customer_wechat'] = $customer_wechat;
            }
            $mate_tel = $data['mate_tel'];
            if ($mate_tel && $has['mate_tel'] != $mate_tel  && in_array('mate_tel',$exclusion_field)) {
                $con['mate_tel'] = $mate_tel;
            }
            $mate_wechat = $data['mate_wechat'];
            if ($mate_wechat && $has['mate_wechat'] != $mate_wechat  && in_array('mate_wechat',$exclusion_field)) {
                $con['mate_wechat'] = $mate_wechat;
            }

            // 其他排重条件
            $other['channel'] = $customer_channel;
            $baby_time = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>'baby_time'));
            if ($baby_time) {
                $other['baby_time'] = $data['baby_time'] ? $data['baby_time'] : $has['baby_time'];
            }
            // var_dump($other);die;

            if(!empty($data['province_id'])){
                $region = controller("Customer","lib")->getRegionByProvinceId(['id'=>$data['province_id']]);
                $data['customer_region_id'] = $region['id'];
                $data['customer_region'] = $region['region_name'];
            }
            //如果是筛客操作，增加筛客时间
            if($data['is_already_sk'] == 1){
                $data['sk_time'] = date('Y-m-d H:i:s',time());
            }
            /*if($data['is_valid']==1){
                $data['yx_day']=date('Y-m-d H:i:s',time());
            }*/
            //如果追踪人员修改，输入实际收款时判定订单是否有效 
            if($data['fact_money']){
                //查询品牌的有效订单标准
                // $info = sx_call('5a3bbb5d0988d',['id'=>session('brandclass_id')]);
                $mc = new \app\common\lib\mcInterface();
                $info = $mc->getBrand(['id'=>session('brandclass_id')]);

                if($info[0]['order_rule'] == 1){//实际收款达到多少
                    if($data['fact_money'] >= $info[0]['proportion']){
                        //修改订单为有效
                        $data['is_success'] = 1;
                    }else{
                        $data['is_success'] = 3;
                    }
                }elseif($info[0]['order_rule'] == 2){//实际收款占套系金额的百分比
                    if($data['fact_money']/$data['totalpay_money'] >= $info[0]['proportion']/100){
                        //修改订单为有效
                        $data['is_success'] = 1;
                    }else{
                        $data['is_success'] = 3;
                    }
                }
            }

            // 判断手机号，同一个事业部（品牌）相同手机号(且没有过期)，不能提交
            // $arr=controller('Customer','lib')->isContactRepeat($has['brandclass'],$data['customer_tel'],$data['customer_wechat'],$data['customer_qq'],$data['mate_tel']);
            // if($arr){
            //     if($arr['id']!=$data['id']){
            //         $returnData = array('code' => 301,'msg' =>'手机号，配偶手机号，微信，qq中有一项已存在客资中');
            //         return json($returnData);
            //    }
            // }

            //修改者是否有修改手机号权限 是否是录入者
            $customerInfo = $has;
            // $customerInfo = controller("Customer","lib")->getCustomerInfo($data['id']);
            //if(!check_right('menu1512998373')&&$customerInfo['tel_staff_id']&&session('staff_id')!=$customerInfo['tel_staff_id']){
            if(strpos($data['customer_tel'],'*')){
                unset($data['customer_tel']);
            }
            if(strpos($data['mate_tel'],'*')){
                unset($data['mate_tel']);
            }
            //}
            if(empty($customerInfo['customer_tel'])&&!empty($data['customer_tel'])){
                $data['tel_staff_id']=session('staff_id');
                $data['tel_staff']=session('staff_name');
                $data['tel_time']=date('Y-m-d H:i:s',time());
            }
            if(empty($customerInfo['customer_wechat'])&&!empty($data['customer_wechat'])){
                $data['wechat_staff_id']=session('staff_id');
                $data['wechat_staff']=session('staff_name');
                $data['wechat_time']=date('Y-m-d H:i:s',time());
            }
            // var_dump($has);die;
            // 对比提交数据和原始数据
            foreach ($data as $key => $value) {
                $dateArr = [
                    'baby_birthday','record_day','ready_baby_day','customer_birthday','hospital_photo_time','op_signday','mate_birthday','marry_day'
                ];
                if($has[$key] && in_array($key, $dateArr)){
                    $has[$key] = date('Y-m-d',strtotime($has[$key]));
                }
                if ($value != $has[$key]) {
                    // $kStr = translate('c_customerinfo',$key);
                    // if ($kStr) {
                    //     $oldDate[$kStr]  = $has[$key];
                    //     $newDate[$kStr]  = $value;
                    // }

                    $newDateIn[$key] = $value;
                    $oldDateIn[$key] = $has[$key];
                }
            }
            if($newDateIn['customer_tel']||$newDateIn['customer_wechat']||$newDateIn['customer_qq']||$newDateIn['mate_tel']){
                /*// 判断手机号，同一个事业部（品牌）相同手机号(且没有过期)，不能提交
                $rep=controller('Customer','lib')->isRepeat($has['brandclass'],$newDateIn['customer_tel'],$newDateIn['customer_wechat'],$newDateIn['customer_qq'],$newDateIn['mate_tel'],$data['id'],$data['consultation_type_id']);
                if($rep['code'] == 201&&$rep['data']!=$data['id']){
                    $arr = $rep['data'];//controller('Customer','lib')->getCustomerInfo($rep['data']);
                    if($arr['sales_staff']){
                        $returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].' ]的[ '.$arr['dj_staff'].' ]录入过，并且分配给了[ '.$arr['sales_staff'].' ]');
                    }else{
                        $returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].']的[ '.$arr['dj_staff'].' ]录入过，未进行分配');
                    }
                    return json($returnData);
                }*/
               /* if($arr&&$arr['id']!=$data['id']){
                    // $returnData = array('code' => 301,'msg' =>'手机号，配偶手机号，微信，qq中有一项已存在客资中');
                    if($arr['sales_staff']){
                        $returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].' ]的[ '.$arr['dj_staff'].' ]录入过，并且分配给了[ '.$arr['sales_staff'].' ]');
                    }else{
                        $returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].']的[ '.$arr['dj_staff'].' ]录入过，未进行分配');
                    }

                    return json($returnData);
                }*/
                if(!empty($con)){
                    // 20191112  排重要改，另外，要写入排重表 20200416
                    $repRes = controller("crm/Customer", "lib")->isRepeat($orz, $con, $other, $data['id']);
                    if ($repRes['code']!=200) {
                        // dealMain($repRes['c_unique'], $data);
                        return $repRes;
                    }
                }
            }
            if($newDateIn['is_intostore']  == 2 || $newDateIn['is_intostore']  == 3){
                if($newDateIn['is_intostore']  == 2 && $customerInfo['is_valid'] != 1){
                    $newDateIn['is_valid'] = 1;
                    $newDateIn['yx_day'] = date('Y-m-d H:i:s',time());
                }
                if(!$newDateIn['syjd_day']){
                    $newDateIn['syjd_day'] = date('Y-m-d H:i:s',time());
                }else{
                    if(date('Y-m-d',strtotime($newDateIn['syjd_day'])) > date('Y-m-d')){
                        $returnData = array('code' => 10,'msg' =>'进店时间不能大于今天');
                        return json($returnData);
                    }
                }
            }
            if($newDateIn['sign_id']){
                $newDateIn['sign_time'] = date('Y-m-d H:i:s',time());
            }
            if($newDateIn['next_time']){
                $newDateIn['is_next'] = 1;
                //如果标记再约，存入pool表
                //查询再约提前时间  天
                $adv = db('crm_s_reminditemset')->where('id','remind2')->where('brandclass',session('brandclass'))->where('isopen',1)->field('advancehour')->find();
                if($adv['advancehour'] || $adv['advancehour'] == 0){
                    $adv = $adv['advancehour'] == 0 ? '今天' : $adv['advancehour'].'天后';
                    $hour = date('H',strtotime($data['next_time']));
                    if($hour == 0){
                        $time = date('Y-m-d 10:00:00',strtotime($data['next_time'])-86400*$adv['advancehour']);
                    }else{
                        $time = date('Y-m-d H:i:s',strtotime($data['next_time'])-86400*$adv['advancehour']);
                    }
                    $message = array(
                        'customer_id' => $data['id'],
                        'send_type'   => 1,
                        'send_title'   => '再约提醒',
                        'send_msg'    => '当前名为：'.$data['customer_name'].'的客资，'.$adv.' 再约电访',
                        'receive_id'  => session('staff_id'),
                        'receive_name'=> session('staff_name'),
                        'operation_type'=> 2,
                        'time_out'=> 120,
                        'next_time'=>$newDateIn['next_time']
                    );
                    $arr = array(
                        'cid' => $data['id'],
                        'msg' => json_encode($message),
                        'fp_time_out' => strtotime($time),
                        'count'=>0,
                        'pool_type' => 6,
                        'create_time' => date('Y-m-d H:i:s',time()),
                    );
                    db()->startTrans();
                    $inc1 = db('crm_c_fp_pool')->insertGetId($arr);
                    if(!$inc1){
                        db()->rollback();
                        $returnData = array('code' => 0,'msg' =>'再约进店失败');
                        return json($returnData);
                    }else{
                        db()->commit();
                    }
                }
                //查询再约提前时间  分钟
                $adv = db('crm_s_reminditemset')->where('id','next_before_minute')->where('shop_code',session('shop_code'))->where('isopen',1)->field('advancehour')->find();
                if($adv['advancehour']){
                    $time = date('Y-m-d H:i:s',strtotime($data['next_time'])-60*$adv['advancehour']);
                    $message = array(
                        'customer_id' => $data['id'],
                        'send_type'   => 1,
                        'send_title'   => '再约提醒',
                        'send_msg'    => '当前名为：'.$data['customer_name'].'的客资，'.$adv['advancehour'].'分钟后再约电访',
                        'receive_id'  => session('staff_id'),
                        'receive_name'=> session('staff_name'),
                        'operation_type'=> 2,
                        'time_out'=> 120,
                        'next_time'=>$newDateIn['next_time']
                    );
                    $arr = array(
                        'cid' => $data['id'],
                        'msg' => json_encode($message),
                        'fp_time_out' => strtotime($time),
                        'count'=>0,
                        'pool_type' => 6,
                        'create_time' => date('Y-m-d H:i:s',time()),
                    );
                    db()->startTrans();
                    $inc1 = db('crm_c_fp_pool')->insertGetId($arr);
                    if(!$inc1){
                        db()->rollback();
                        $returnData = array('code' => 0,'msg' =>'再约进店失败');
                        return json($returnData);
                    }else{
                        db()->commit();
                    }
                }
            }
            if($newDateIn['budget']){
                $newDateIn['budget'] = DeleteHtml($newDateIn['budget']);//去除预算的table标签
            }
            // 没有任何修改
            if (!$newDateIn) {
                // $returnData = array('code' => 900,'msg' =>'没有修改');
                $returnData = array('code' => 1,'msg' =>'编辑客资信息成功');
                return json($returnData);
            }
            if($newDateIn['hospital_photo_time']){
                $newDateIn['hospital_photo_time'] = date('Y-m-d H:i:s',strtotime($newDateIn['hospital_photo_time']));
            }
            // 手机号修改日志
            if ($newDateIn['customer_tel']) {
                $data['tel_staff_id']= session('staff_id');
                $data['tel_staff']   = session('staff_name');
                $data['tel_time']=date('Y-m-d H:i:s',time());
                $needDealMain = true;
            	//history_log(['customer_tel'=>$newDateIn['customer_tel']],['customer_tel'=>$oldDateIn['customer_tel']],$has['id'],session('staff_id'),session('staff_name'),'crm','Customer','editCustomerTel');
            }
            // 开启事务
            db()->startTrans();
            try {
                // 更新时间
                $newDateIn['update_time'] = date('Y-m-d H:i:s');
                $res = db('crm_c_customerinfo')->where('id', $data['id'])->update($newDateIn);
                // 当需要 更新 main表时
                if ($needDealMain) {
                    $cInfo = db('crm_c_customerinfo')->where('id',$data['id'])->find();
                    $dealRes = dealMain($cInfo['c_unique'],$cInfo);
                    if ($dealRes['code'] == 200) {
                        if ($dealRes['c_unique'] != $cInfo['c_unique']) {
                            db('crm_c_customerinfo')->where('id',$data['id'])->update(['c_unique' =>$dealRes['c_unique']] );
                            db('crm_c_salestrackinginfo')->where('customer_id',$data['id'])->update(['c_unique' =>$dealRes['c_unique']] );
                        }
                    }
                }
                if($newDateIn['is_intostore']){
                    //如果是爆破活动，修改对应的爆破表数据
                    if($customerInfo['is_act'] == 2){
                        db('crm_c_swap_customer')->where('customer_number',$customerInfo['customer_number'])->update(['is_intostore'=>$newDateIn['is_intostore']]);
                    }
                }
                // 是否安装erp
                // $is_erp = is_install('sx_erp');

                // if ($is_erp) {
                    // 如果已经邀约时间，并且没有订单，没有订单开始时间，则同步信息到erp
                    // if ($customerInfo['yjd_action_day'] && $customerInfo['is_success'] ==2 && !$customerInfo['order_start_time']) {
                    //     $erpData = $newDateIn;
                    //     $erpData['brandclass_id']  = $customerInfo['brandclass_id'];
                    //     $erpData['customer_number']= $customerInfo['customer_number'];
                    //     $res = controller("crm/Customer","lib")->updateToErp($erpData);
                    //     unset($erpData);
                    // }
                // }
                history_log($newDateIn,$oldDateIn,$data['id'], session('staff_id'), session('staff_name'));
                //进店操作变动记录追踪日志
                if($newDateIn['is_intostore']){
                    $str = getIsIntostore($newDateIn['is_intostore']);
                    //追踪记录
                    $params['customer_id'] = $data['id'];
                    $params['c_unique'] = $customerInfo['c_unique'];
                    $params['customer_name'] = $customerInfo['name'];
                    $params['customer_number'] = $customerInfo['number'];
                    $params['sales_remark'] = $str;
                    $params['sales_day'] = date('Y-m-d H:i:s',time());
                    $params['sales_staff'] = session('staff_name');
                    $params['sales_staff_id'] = session('staff_id');
                    $params['sales_staff_number'] = session('staff_number');
                    $params['shop_name'] = session('shop_name');
                    $params['shop_code'] = session('shop_code');
                    db('crm_c_salestrackinginfo')->insert($params);
                    cache('getCustomerTrackInfos'.$data['id'],null);
                    //修改追踪时间
                    $info = controller("crm/Customer","lib")->getCustomerInfo($data['id']);//客资信息
                    $time = date('Y-m-d H:i:s',time());
                    if(empty($info['c_start_day'])){
                        $arr = array(
                            'c_star_day' => $time,
                            'c_end_day' => $time,
                            'last_trackday' => $time,
                        );
                    }else{
                        $arr = array(
                            'c_end_day' => $time,
                            'last_trackday' => $time,
                        );
                    }
                    db('crm_c_customerinfo')->where('id',$data['id'])->update($arr);
                    //修改客资表近三次追踪记录
                    getSalesTracking($data['id']);
                    //进店日志
                    history_log('是否进店：'. getIsIntostore($newDateIn['is_intostore']), '是否进店：'.getIsIntostore($oldDateIn['is_intostore']),$data['id'], session('staff_id'), session('staff_name'));
                }

                //2021-04-15 上海优尼可 shynk 已订单的客资信息修改 ，同步到ERP里面的订单信息（只同步追踪人，就是网销门市，宝宝姓名、生日）
                if (customize('shynk')) {
                    $erp_order = db('c_customerorder')
                                ->where('crm_customer_id',$data['id'])
                                ->field('customerid')
                                ->find();
                    if($erp_order){
                        $erp_order_w = '';
                        if (!empty($data['baby_name'])) {
                            $erp_order_w['bbname'] = $data['baby_name'];
                        }
                        if (!empty($data['baby_birthday'])) {
                            $erp_order_w['bbithdate'] = date("Ymd",strtotime($data['baby_birthday']));
                        }
                        if (!empty($erp_order_w)) {
                            db('c_customerinfo')->where('customerid',$erp_order['customerid'])->update($erp_order_w);
                        }
                    }
                }

                // //客资标为无效删除其联系方式
                // if($newDateIn['is_valid']==3){
                //     $oldContact=array();
                //     if($has['customer_tel'])       array_push($oldContact,$has['customer_tel']);
                //     if($has['customer_wechat'])    array_push($oldContact,$has['customer_wechat']);
                //     if($has['customer_qq'])        array_push($oldContact,$has['customer_qq']);
                //     db('crm_c_customer_contact')->where('c_id',$has['id'])->where('contact','in',implode(',',$oldContact))->delete();
                // }else{
                //     // var_dump(session('valid_date'));
                //     $valid_date = session('valid_date')*86400;
                //     $end_day = strtotime($has['dj_day']) + $valid_date;
                //     // 如果当前时间小于 过期时间 说明排重表里有这个联系方式  更新联系方式  如果大于，说明已经过期了，排重表里应该没有，不更新
                //     if (time() < $end_day || !$valid_date) {
                //         // 查看排重表
                //         $contact = db('crm_c_customer_contact')
                //             ->where('brandclass',$has['brandclass'])
                //             ->where('c_id', $has['id'])
                //             ->column('contact');
                //         // 接收到的联系方式
                //         $customer_contact = [];
                //         if ($data['customer_tel']) {
                //             array_push($customer_contact,$data['customer_tel']);
                //         }
                //         if ($data['customer_wechat']) {
                //             array_push($customer_contact,$data['customer_wechat']);
                //         }
                //         if ($data['customer_qq']) {
                //             array_push($customer_contact,$data['customer_qq']);
                //         }
                //         if ($data['mate_tel']) {
                //             array_push($customer_contact,$data['mate_tel']);
                //         }
                //         if ($data['mate_wechat']) {
                //             array_push($customer_contact,$data['mate_wechat']);
                //         }
                //         if ($data['mate_qq']) {
                //             array_push($customer_contact,$data['mate_qq']);
                //         }
                //         $ins = array_diff($customer_contact, $contact);
                //         $contactList = [];
                //         foreach($ins as $k => $v){
                //             $contactList[$k]['c_id']       = $has['id'];
                //             $contactList[$k]['contact']    = $v;
                //             $contactList[$k]['brandclass'] = $has['brandclass'];
                //         }
                //         db('crm_c_customer_contact')->insertAll($contactList);

                //         $del = array_diff($contact, $customer_contact);
                //         foreach ($del as $k => $v) {
                //             db('crm_c_customer_contact')->where('c_id', $has['id'])->where('contact',$v)->delete();
                //         }
                //     }
                // }
                // 更新排重表
                if(!empty($con)){
                    updateContact($data['id'],$con);
                }
                db()->commit();
                $returnData = array('code' => 1,'msg' => '编辑客资信息成功');
                return json($returnData);
            } catch (Exception $e) {
                db()->rollback();
                $returnData = array('code' => 10002,'msg' =>'操作失败','data'=>$e->getMessage());
                return json($returnData);
            }
        }
        // 显示客资详情
        else{
            // 获取id
            $cid = input('id/d');

            if($cid){
                // 客资基本资料
                $customerInfo=controller("crm/Customer","lib")->getCustomerInfo($cid);
                // var_dump($customerInfo);die;
                $customerInfo['baby_birthday'] = $customerInfo['baby_birthday'] ? date('Y-m-d', strtotime($customerInfo['baby_birthday'])) : '';
                $customerInfo['customer_birthday']=$customerInfo['customer_birthday'] ? date('Y-m-d',strtotime($customerInfo['customer_birthday'])) : '';
                $customerInfo['mate_birthday'] = $customerInfo['mate_birthday'] ? date('Y-m-d', strtotime($customerInfo['mate_birthday'])) : '';
                $customerInfo['ready_baby_day'] = $customerInfo['ready_baby_day'] ? date('Y-m-d', strtotime($customerInfo['ready_baby_day'])) : '';
                $customerInfo['record_day'] = $customerInfo['record_day'] ? date('Y-m-d', strtotime($customerInfo['record_day'])) : '';
                $customerInfo['marry_day'] = $customerInfo['marry_day'] ? date('Y-m-d', strtotime($customerInfo['marry_day'])) : '';
                $customerInfo['hospital_photo_time'] = $customerInfo['hospital_photo_time'] ? date('Y-m-d', strtotime($customerInfo['hospital_photo_time'])) : '';
                $param['shop_code'] = $customerInfo['add_shop_code'];
                //摄影师
                $param['work_type'] = PZ_WORK_TYPE;
                $photo_cameraman = getShopStaffs($param);
                $this->assign('photo_cameraman',$photo_cameraman);
                //推广人
                $r['shop_code'] = session('shop_code');
                $r['work_type'] = KZTB_WORK_TYPE;
                $r['all'] = 2;
                $recommendStaff = getShopStaffs($r);
                $this->assign('recommendStaff',$recommendStaff);

                //摄影助理
                $param['work_type'] = SYZL_WORK_TYPE;
                $photo_assistant = getShopStaffs($param);
                $this->assign('photo_assistant',$photo_assistant);
                unset($param);
                // exit;
                if(is_install('sx_erp'))  $customerInfo['is_erp']=1;
                if($customerInfo['customer_wechat']){
                    if(!check_right('menu1513409629') || $customerInfo['auth_wechat'] == 'no'){
                        $customerInfo['auth_wechat'] = 'no';
                    }else{
                        if ($customerInfo['is_success'] != 1) {
                            $customerInfo['auth_wechat'] = 'yes';
                        }else{
                            $customerInfo['auth_wechat'] = 'no';
                        }
                    }
                }else{
                    $customerInfo['auth_wechat'] = 'yes';
                }
                if($customerInfo){
                    //归属地信息
                    if($customerInfo['customer_tel']){
                        $telInfo = controller("Customer","lib")->getTelInfo($customerInfo['customer_tel']);
                        $this->assign('telInfo',$telInfo);
                    }
                    if($customerInfo['mate_tel']){

                        $mtelInfo = controller("Customer","lib")->getTelInfo($customerInfo['mate_tel']);
                        $this->assign('mtelInfo',$mtelInfo);
                        //erp应用是否安装

                        //$this->assign('is_install',is_install('sx_erp'));
                    }

                    // --------这里存在权限问题 shop_code 不能作为权限的判断条件
                    $customer_shop_code = $customerInfo['shop_code'];
                    $staff_shop_code = session('shop_code');
                    // 客资店和员工不同店
                    // if ($customer_shop_code != $staff_shop_code) {
                    //     $this->error('该客资不属于本店');
                    //     exit;
                    // }

                    $customerInfo['shoptype']=session('shop_type');
                    $this->assign('customerInfo', $customerInfo);
                    $allSet = controller("crm/Customer","lib")->getCustomerAllSet($customer_shop_code);
                    if($customerInfo['shop_code'] != $customerInfo['add_shop_code']){//如果提报店和归属店不一样，把提报店的渠道追加到归属店的渠道里面
                        $arr = [
                          'id' => $customerInfo['sign_id'],
                          'sign_name' => $customerInfo['sign_name'],
                        ];
                        array_push($allSet['sign'],$arr);
                        $temp = [];
                        foreach($allSet['sign'] as $k=>$v){
                            $temp[$v['id']] = $v;
                        }
                        $allSet['sign'] = $temp;
                        $arr1 = [
                          'id' => $customerInfo['op_signinfo_id'],
                          'mark_name' => $customerInfo['op_signinfo'],
                        ];
                        array_push($allSet['signSet'],$arr1);
                        $temp = [];
                        foreach($allSet['signSet'] as $k=>$v){
                            $temp[$v['id']] = $v;
                        }
                        $allSet['signSet'] = $temp;
                        $allSet['channelInfo'] = array_merge($allSet['channelInfo'],array(array('id'=>$customerInfo['customer_channel_id'],'channel_name'=>$customerInfo['customer_channel'])));
                    }
                    $allSet['sign'] = $allSet['sign'] ? $allSet['sign'] : [];
                    $arr = [
                        'id' => $customerInfo['sign_id'],
                        'tracksign' => $customerInfo['sign_name'],
                    ];
                    array_push($allSet['sign'],$arr);
                    $temp = [];
                    foreach($allSet['sign'] as $k=>$v){
                        $temp[$v['id']] = $v;
                    }
                    $allSet['sign'] = $temp;
                    $arr1 = [
                        'id' => $customerInfo['op_signinfo_id'],
                        'mark_name' => $customerInfo['op_signinfo'],
                    ];
                    $allSet['signSet'] = $allSet['signSet'] ? $allSet['signSet'] : [];
                    array_push($allSet['signSet'],$arr1);
                    $temp = [];
                    foreach($allSet['signSet'] as $k=>$v){
                        $temp[$v['id']] = $v;
                    }
                    $allSet['signSet'] = $temp;
                    $this->assign('allSet', $allSet);
                }else{
                    $this->error('资料不存在，无效的客户编号');
                    exit;
                }
                // $allSet = json_decode($allSet, true);
                // var_dump($allSet);
                // exit;
                // 地址三级联动第一级
                $data['type']=1;
                $address=controller("Customer","lib")->address($data);
                $this->assign("address",$address);
                // 追踪记录
                $trackInfos = controller("crm/Customer","lib")->getCustomerTrackInfos($customerInfo['id']);
                // var_dump($trackInfos);
                // exit;
                 
                $this->assign('trackInfoss', $trackInfos);

                $clubData = db("crm_s_club")->where("brandclass_id",session("brandclass_id"))->select();
                $this->assign('clubData',$clubData);

                // 修改日志
                $changeLogs = controller("crm/Customer","lib")->getCustomerChangeLogs($cid);
                // var_dump($changeLogs);
                // exit;
                $info = [];
                foreach($changeLogs as $k=>$v){
                    if(is_json($v['old_data'])){
                        $oldDate = json_decode($v['old_data'], true);
                        // var_dump($oldDate);
                        $oldDateStr = '';
                        foreach ($oldDate as $kk => $vv) {
                            $key = translate('c_customerinfo',$kk);
                            if($kk == 'is_valid'){
                                $vv = getIsValid($vv);
                            }
                            if($kk == 'is_intostore'){
                                $vv = getIsIntostore($vv);
                            }
                            if($kk == 'is_loss'){
                                $vv = getIsLoss($vv);
                            }
                            if($kk == 'is_status'){
                                $vv = getIsStatusAttr($vv);
                            }
                            if($key){
                                $oldDateStr .= $key.'：'.$vv.'；<br>';
                            }
                        }
                        $info[$k]['oldDateStr'] = $oldDateStr;
                    }else if (is_json($v['data'])) {
                        $newDate = json_decode($v['data'], true);
                        $newDateStr = '';
                        foreach ($newDate as $kkk => $vvv) {
                            if($kkk == 'is_valid'){
                                $vvv = getIsValid($vvv);
                            }
                            if($kkk == 'is_intostore'){
                                $vvv = getIsIntostore($vvv);
                            }
                            if($kkk == 'is_loss'){
                                $vvv = getIsLoss($vvv);
                            }
                            $key1 = translate('c_customerinfo',$kkk);
                            if($key1){
                                $newDateStr .= $key1.'：'.$vvv.'；<br>';
                            }
                        }
                        $info[$k]['newDateStr'] = $newDateStr;
                    }else{
                        
                        $oldDateStr = $v['old_data'];
                        $newDateStr = $v['data'];
                        $info[$k]['oldDateStr'] = $oldDateStr;
                        $info[$k]['newDateStr'] = $newDateStr;
                    }
                    $info[$k]['create_time'] = $v['create_time'];
                    $info[$k]['staff_name'] = $v['staff_name'];
                }
                // var_dump($info);
                $this->assign('changeLogs', $info);
                // 历史订单，现在没有表，调其他接口
                $historyOrders = controller("crm/Customer","lib")->getCustomerHistoryOrders($cid);
                // var_dump($historyOrders);
                // exit;
                $is_erp = is_install('sx_erp');
                foreach ($historyOrders as $key => $value) {
                    if ($is_erp === false) {
                        $erp_status = 0;
                        $historyOrders[$key]['erp_link'] = '';
                    }else{
                        $erp_status = 1;
                        $historyOrders[$key]['erp_link'] = '/crm/Customer/getAllServiceInfo/order_sn/'.$value['order_sn'];
                    }
                }

                //发送短信记录
                $msg = controller("crm/Customer","lib")->getMsgList($customerInfo);
                $this->assign('msg',$msg);
                // print_r($historyOrders);
                // exit;
                $this->assign('erp_status', $erp_status);
                // var_dump($historyOrders);
                // exit;
                $this->assign('historyOrders', $historyOrders);
                //意向店面
                $shops = controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass'),
                    'is_marketing'=>2));
                $this->assign('shops',$shops);
            }else{
                $this->error('客户id为空');
                exit;
            }
            //录入必选项配置
            $lrMust = db_config('lr_must_'.session('brandclass_id'));
            $lrMust = trim($lrMust,',');
            $lrMust = explode(',',$lrMust);
            //成都网销中心录入客资 ‘获取方式’为必填项
            if(session('shop_code') == 'TSYX13' && !in_array('access_model',$lrMust)){
                $lrMust[] = 'access_model';
            }
            $this->assign('jslrMust',$lrMust);

            //客资姓名修改权限
            if(check_right('menu1533803338')){
                $this->assign('editCusNameAuth',true);
            }else{
                $this->assign('editCusNameAuth',false);
            }
            //已成单客资修改权限
            if(check_right('menu1547637604')){
                $this->assign('orderEditAuth',true);
            }else{
                $this->assign('orderEditAuth',false);
            }
            //是否成单
            if($customerInfo['is_success'] == 1 || $customerInfo['is_success'] == 3){
                $this->assign('is_success',true);
            }else{
                $this->assign('is_success',false);
            }
            //关键字修改权限
            if(check_right('menu1539573890')){
                $this->assign('keywordsAuth',true);
            }else{
                $this->assign('keywordsAuth',false);
            }
            $baby_sex = config('baby_sex');
            if(empty($baby_sex)){
                $baby_sex = [
                    ['sex'=>'男',],
                    ['sex'=>'女',],
                ];
            }
            $this->assign('baby_sex',$baby_sex);

            //修改客资渠道的权限
            if(check_right('menu1513409657')){
                $this->assign('editCustomerChannel',true);
            }else{
                $this->assign('editCustomerChannel',false);
            }
            //修改获取方式的权限
            if(check_right('menu1513409684')){
                $this->assign('editAccess',true);
            }else{
                $this->assign('editAccess',false);
            }

            //修改客户来源的权限
            if(check_right('menu1513409882')){
                $this->assign('editCustomerSource',true);
            }else{
                $this->assign('editCustomerSource',false);
            }

            //订单后操作配置
            $ddMust = db_config('dd_must_'.session('brandclass_id'));
            $ddMust = trim($ddMust,',');
            $ddMust = explode(',', $ddMust);
            $this->assign('ddMust',$ddMust);
            if (customize('nnqqbaby')) {
                $brand = db('crm_s_brandset')->order('sort asc')->select();
                $this->assign('brand',$brand);
            }
            return $this->fetch('customerinfo_child');
        }
    }
    // 删除消息
    public function getAllMsgDel(){
        $data = array_column(json_decode(input('param.data'),TRUE),'id');
        $sum = count($data);
        $data = implode($data, ",");
        if (!$data) {
            return  json(array('code'=>'100','msg'=>'请选择消息'));
        }
        if (controller("Customer","lib")->delSendTitle($data,$sum)) {
            return  json(array('code'=>'200','msg'=>'删除成功'));
        }else{
            return  json(array('code'=>'300','msg'=>'删除失败'));
        }
    }
    // 获取员工所有消息 Eric
    public function getAllMsg(){
        $send_title = controller("Customer","lib")->getSendTitle();
        $this->assign('send_title',$send_title);
        $this->assign('title','消息列表');
        $this->assign('time',date("Y-m-d",time()));
        return $this->fetch();
    }
    // table表格需要的json
    public function getAllMsg_json() {
        // table需要的参数()
        $data = input();

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

        $staff_id = session('staff_id');
        $where = [
            'receive_id'=> $staff_id,
            'is_delete' => 0,
        ];
        if ($data['send_title']) {
            $where['send_title'] = $data['send_title'];
        }
        $start = $data['start'] ? date('Y-m-d 00:00:00',strtotime($data['start'])) :  '1999-01-01';
        $end = $data['end'] ? date('Y-m-d 23:59:59',strtotime($data['end'])) :  date('Y-m-d 23:59:59');
        $messageList = db('crm_c_message')
            ->where($where)
            ->where('send_time','between',[$start,$end])
            ->limit($limit)
            ->page($page)
            ->order('id desc')
            ->select();//return json(db('crm_c_message')->getLastSql());exit;
        $time = time();
        foreach ($messageList as $key => $value) {
            // var_dump($value); // 发送的消息类型:1:短消息(弹窗)；2：通知',
            // exit;
            switch ($value['send_type']) {
                case '1':
                    $messageList[$key]['send_type'] = '短消息';
                    break;
                case '2':
                    $messageList[$key]['send_type'] = '通知';
                    break;
            }
            switch ($value['receive_status']) {
                case '0':
                    if ($time>$value['time_out']) {
                        $messageList[$key]['receive_status'] = '已超时，未接收';
                        $messageList[$key]['operation'] = '';
                    }else{
                        $messageList[$key]['receive_status'] = '未接收';
                        $operation = json_decode($value['operation'],true);
                        $temp = '';
                        foreach ($operation as $k => $v) {
                            $temp .= '<button onclick="messageAction(this) data-id="'.$value['id'].'" dataurl="'.$v['url'].'" class="layui-btn layui-btn-xs layui-btn-normal">'.$v['button'].'</button>';
                        }
                        $messageList[$key]['operation'] = $temp;
                    }
                    break;
                case '1':
                    $messageList[$key]['receive_status'] = '已接收';
                    $messageList[$key]['operation'] = '';
                    break;
                case '2':
                    $messageList[$key]['receive_status'] = '已放弃';
                    $messageList[$key]['operation'] = '';
                    break;
                default:
                    $messageList[$key]['receive_status'] = '';
                    $messageList[$key]['operation'] = '';
                    break;
            }
            switch ($value['read_status']) {
                case '0':
                    $messageList[$key]['read_status'] = '未读';
                    break;
                case '1':
                    $messageList[$key]['read_status'] = '已读';
                    break;
            }
        }
        $count = db('crm_c_message')->where($where)->where('send_time','between',[$start,$end])->count();
        $return['code'] = 0;
        $return['msg']  = '';
        $return['count']= $count;
        $return['data'] = $messageList;
        return json($return);
    }

    public function getDList($param){
        //部门 
        $shop_code = $param['shop_code'];
        $shop_code = $shop_code ? $shop_code : session('shop_code');
        // $url = '5a62dcd5c7e40';
        // $res = sx_call($url,['shop_code'=>$shop_code]);
        // if($res['code'] == 200){
        //     return $res['data'];
        // }else{
        //     return false;
        // }
        $mc = new \app\common\lib\mcInterface();
        $departmentList = $mc->getDepartment(['shop_code'=>$shop_code]);
        return $departmentList;
    }

    //通过归属地查询省市
    public function getAddressInfo(){
        $info = input('post.name');
        $arr = explode(' ',$info);
        if(count($arr) == 1){
            $ret['pid'] = controller("Customer","lib")->getAddressByLike(['name'=>$arr[0]]);
        }else{
            $ret['pid'] = controller("Customer","lib")->getAddressByLike(['name'=>$arr[0]]);
            $ret['cid'] = controller("Customer","lib")->getAddressByLike(['name'=>$arr[1]]);
        }
        return $ret;
    }
    public function upload_img(){
        //$content = input('content');
        $file = Request::instance()->file('file');
        if(empty($file)){
            $result["code"] = "1";
            $result["msg"] = "请选择图片";
            $result['data']["src"] = '';
        }else{
            // 移动到 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload/img' );
            if($info){
                $name_path =str_replace('\\',"/",$info->getSaveName());
                //成功上传后 获取上传信息
                $result["code"] = '0';
                $result["msg"] = "上传成功";
                $result['data']["src"] = "/upload/img/".$name_path;
            }else{
                // 上传失败获取错误信息
                $result["code"] = "2";
                $result["msg"] = "上传出错";
                $result['data']["src"] ='';
            }
        }
        //$a='http://crm.sx.com/public/uploads/img/20171221/2af12f7d271e633836abb03f48f559db.jpg';
        //print_r($result);die;
        return json_encode($result);
    }
    // 获取客资详情 20201029
    public function getCustomerInfo(){
        $return['code'] = 200;
        $return['msg']  = '';
        $return['data'] = '';
        $id = (int)input('post.id');
        if (!$id) {
            $return['code'] = 100;
            $return['msg']  = '客资ID为空，无法获取客资信息';
            $return['data'] = input('post.id');
            return json($return);
        }
        // 客资基本资料
        $customerInfo = controller("crm/Customer","lib")->getCustomerInfo($id);
        $customerInfo['baby_birthday'] = $customerInfo['baby_birthday'] ? date('Y-m-d',strtotime($customerInfo['baby_birthday'])) : '';
        $customerInfo['ready_baby_day'] = $customerInfo['ready_baby_day'] ? date('Y-m-d',strtotime($customerInfo['ready_baby_day'])) : '';
        $customerInfo['mate_birthday'] = $customerInfo['mate_birthday'] ? date('Y-m-d',strtotime($customerInfo['mate_birthday'])) : '';
        $customerInfo['customer_birthday'] = $customerInfo['customer_birthday'] ? date('Y-m-d',strtotime($customerInfo['customer_birthday'])) : '';
        $customerInfo['marry_day'] = $customerInfo['marry_day'] ? date('Y-m-d',strtotime($customerInfo['marry_day'])) : '';
        // 标签
        $customerInfo['customer_label'] = $customerInfo['customer_label'] ? explode(',',trim($customerInfo['customer_label'],',')) : '';
        if ($customerInfo) {
            $return['data'] = $customerInfo;
        }else{
            $return['msg']  = '获取客资信息失败';
            $return['data'] = db()->getLastSql();
        }
        return json($return);
    }
    /*
    //获取客资详情
    public function getCustomerInfo(){
        // 客资基本资料
        $customerInfo = controller("crm/Customer","lib")->getCustomerInfo(input('post.id'));
        $customerInfo['baby_birthday'] = $customerInfo['baby_birthday'] ? date('Y-m-d',strtotime($customerInfo['baby_birthday'])) : '';
        $customerInfo['ready_baby_day'] = $customerInfo['ready_baby_day'] ? date('Y-m-d',strtotime($customerInfo['ready_baby_day'])) : '';
        $customerInfo['mate_birthday'] = $customerInfo['mate_birthday'] ? date('Y-m-d',strtotime($customerInfo['mate_birthday'])) : '';
        $customerInfo['customer_birthday'] = $customerInfo['customer_birthday'] ? date('Y-m-d',strtotime($customerInfo['customer_birthday'])) : '';
        $customerInfo['marry_day'] = $customerInfo['marry_day'] ? date('Y-m-d',strtotime($customerInfo['marry_day'])) : '';
        return json($customerInfo);
    }
    */
    //电访
    public function dianfang(){
        // 权限
        // 客资追踪权限
        $auth = check_right('menu1512971662');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有追踪的权限，请先设置权限');
            return json($return);
            exit;
        }
        // 参数
        $param = input('param.');
        // 启用预约进店排控
        $yjd_ctrl_set = db_config('yjd_ctrl_set_'.session('shop_code'));
        $this->assign('yjd_ctrl_set',$yjd_ctrl_set);
        // 客资姓名修改权限
        if(check_right('menu1533803338')){
            $this->assign('editCusNameAuth',true);
        }else{
            $this->assign('editCusNameAuth',false);
        }

        // 客资标记权限
        if (check_right('menu1512971681')) {
            $this->assign('auth_sign',true);
        }else{
            $this->assign('auth_sign',false);
        }
        // 预约进店
        if (check_right('menu1519633870')) {
            $this->assign('yyjd',true);
        }else{
            $this->assign('yyjd',false);
        }
        // 修改消费类型权限
        if (check_right('menu1513409704')) {
            $this->assign('auth_consumptionType',true);
        }else{
            $this->assign('auth_consumptionType',false);
        }

        // 修改微信/qq/微博权限
        if (check_right('menu1513409629')) {
            $this->assign('auth_wechat','yes');
        }else{
            $this->assign('auth_wechat','no');
        }
        //呼叫前缀
        $prefix = controller('crm/Customer','lib')->getCallPrefix();
        $this->assign("prefix",$prefix);
        // 呼叫中心
        $call_id =  db_config('call_id');
        // var_dump($call_id);
        if($call_id){
            $call = db('crm_s_call_center')->where('id',$call_id)->value('call_name');
            $this->assign('callCenter',$call);
        }
        // var_dump($call);
        // exit;
        $customerinfo = controller("crm/Customer","lib")->getCustomerInfoIntostore($param['id']);
        // 修改加好友时间
        if (check_right('menu1513409630')) {
            if ($customerinfo['is_success'] != 1) {
                $this->assign('add_friend_time',true);
            }else{
                $this->assign('add_friend_time',false);
            }
        }else{
            $this->assign('add_friend_time',false);
        }

        //标记有效
        $validArr = [];
        if(check_right('menu1546854995')){
            $temp['id']  = 1;
            $temp['name']= '有效';
            $temp['sele']= 0;
            $validArr[1] = $temp;
        }
        // 标记无效
        if(check_right('menu1517129331')){
            $temp['id']  = 3;
            $temp['name']= '无效';
            $temp['sele']= 0;
            $validArr[3] = $temp;
        }
        // 标记待定
        // if(check_right('menu1517129331')){
            $temp['id']  = 2;
            $temp['name']= '待定';
            $temp['sele']= 0;
            $validArr[2] = $temp;
        // }
        switch ($customerinfo['is_valid']) {
            case '1':
                $temp['id']  = 1;
                $temp['name']= '有效';
                $temp['sele']= 1;
                $validArr[1] = $temp;
                break;
            case '2':
                $temp['id']  = 2;
                $temp['name']= '待定';
                $temp['sele']= 1;
                $validArr[2] = $temp;
                break;
            case '3':
                $temp['id']  = 3;
                $temp['name']= '无效';
                $temp['sele']= 1;
                $validArr[3] = $temp;
                break;
            case '4':
                $temp['id']  = 4;
                $temp['name']= '驳回';
                $temp['sele']= 1;
                $validArr[4] = $temp;
                break;
            case '5':
                $temp['id']  = 5;
                $temp['name']= '反驳回';
                $temp['sele']= 1;
                $validArr[5] = $temp;
                break;
        }
        $this->assign("validArr",$validArr);
        // 修改手机号权限
        if(check_right('menu1555556591')){
            $customerinfo['auth_tel'] = 'yes';
            $customerinfo['auth_mate_tel'] = 'yes';
        }else{
            if($customerinfo['customer_tel']){
                if($customerinfo['auth_tel']!='no' && $customerinfo['is_success']!=1){
                    $customerinfo['auth_tel'] = 'yes';
                }else{
                    $customerinfo['auth_tel'] = 'no';
                }
            }else{
                $customerinfo['auth_tel'] = 'yes';
            }
            if($customerinfo['mate_tel']){
                if(check_right('menu1513409629') && $customerinfo['is_success'] != 1){
                    $customerinfo['auth_mate_tel'] = 'yes';
                }else{
                    $customerinfo['auth_mate_tel'] = 'no';
                }
            }else{
                $customerinfo['auth_mate_tel'] = 'yes';
            }
        }

        if($customerinfo['customer_wechat']){
            if(!check_right('menu1513409629') || $customerinfo['auth_wechat'] == 'no'){
                $customerinfo['auth_wechat'] = 'no';
            }else{
                if ($customerinfo['is_success'] != 1) {
                    $customerinfo['auth_wechat'] = 'yes';
                }else{
                    $customerinfo['auth_wechat'] = 'no';
                }
            }
        }else{
            $customerinfo['auth_wechat'] = 'yes';
        }
        
        if($customerinfo['mate_wechat']){
            if(!check_right('menu1513409629')){
                $customerinfo['auth_mate_wechat'] = 'no';
            }else{
                if ($customerinfo['is_success'] != 1) {
                    $customerinfo['auth_mate_wechat'] = 'yes';
                }else{
                    $customerinfo['auth_mate_wechat'] = 'no';
                }
            }
        }else{
            $customerinfo['auth_mate_wechat'] = 'yes';
        }
        // echo '<pre>';
        // var_dump($customerinfo);
        // exit;
        // 预约进店取消条件
        // if ($customerinfo['yjd_day'] && $customerinfo['is_intostore']==1 && $customerinfo['is_success']==2) {
        //     $yjdstatus = true;
        //     $this->assign('yjdstatus',$yjdstatus);
        // }
        if ($customerinfo['yjd_day']) {
            // 预约进店时间 大于时间进店时间  或者  预约进店时间 大于  开单时间
            if ($customerinfo['yjd_day']>$customerinfo['syjd_day'] || $customerinfo['yjd_day']>$customerinfo['order_start_time']) {
                $yjdstatus = true;
                $this->assign('yjdstatus',$yjdstatus);
            }
        }
        // var_dump($yjdstatus);
        // exit;
        $customerinfo['marry_day'] = $customerinfo['marry_day'] ? date('Y-m-d',strtotime($customerinfo['marry_day'])) : '';
        $customerinfo['customer_remark'] = str_replace('&nbsp;','',strip_tags($customerinfo['customer_remark']));//剥离标签
        if ($customerinfo['baby_birthday']) {
            $customerinfo['baby_birthday'] = date('Y-m-d',strtotime($customerinfo['baby_birthday']));
        }
        if ($customerinfo['ready_baby_day']) {        
            $customerinfo['ready_baby_day'] = date('Y-m-d',strtotime($customerinfo['ready_baby_day']));
        }
        // 标签
        $customerinfo['customer_label'] = $customerinfo['customer_label'] ? explode(',',trim($customerinfo['customer_label'],',')) : [];
        // var_dump($customerinfo['customer_label']);
        // exit;
        $telList = [];
        if($customerinfo['customer_tel']){
            $telList[] = $customerinfo['customer_tel'];
        }
        if($customerinfo['mate_tel']){
            $telList[] = $customerinfo['mate_tel'];
        }
        $this->assign('telList',$telList);
        $this->assign('info',$customerinfo);
        // 客资标签
        $cat = cache('label_'.session('brandclass_id'));
        if(empty($cat)){
            $cat = db('crm_s_label_cat')->where('brandclass_id',session('brandclass_id'))->where('status',2)->select();
            foreach($cat as $k=>$v){
                $cat[$k]['cat_name'] = $v['cat_name'];
                $cat[$k]['label'] = db('crm_s_label')->where('brandclass_id',session('brandclass_id'))->where('label_cat_id',$v['id'])->where('is_delete',2)->select();
                if(empty($cat[$k]['label'])){
                    unset($cat[$k]);
                }
            }
            cache('label_'.session('brandclass_id'),$cat);
        }
        // var_dump($cat);
        // exit;
        $this->assign('cat',$cat);
        // 追踪标记
        $mark=controller("Customer","lib")->markSet(array('shop_code'=>session('shop_code')));
        $this->assign("mark",$mark);
        // 意向店面
        $intentionShop=controller('crm/Customer','lib')->get_shop(array('brandclass'=>$customerinfo['brandclass'],'is_marketing'=>2,'is_op2'=>1));
        $this->assign('intentionShop',$intentionShop);
        // 客资标记
        $sign = controller('crm/Setting','lib')->gettrackingKmarkerList();
        $sign = is_array($sign) ? $sign : [];

        if ($customerinfo['sign_id'] && $customerinfo['sign_name']) {
            $arr = [
                'id'=>$customerinfo['sign_id'],
                'tracksign'=>$customerinfo['sign_name'],
            ];
            array_push($sign,$arr);
        }
        
        $temp = [];
        foreach($sign as $k=>$v){
            $temp[$v['id']] = $v;
        }
        $sign = $temp;

        $this->assign('sign',$sign);
        //客户意向
        $authInten = check_right('menu1513410030');
        if ($authInten) {
            $this->assign('authInten', true);
        }else{
            $this->assign('authInten', false);
        }
        $intention=controller("Customer","lib")->intention(array('shop_code'=>session('shop_code')));
        $this->assign('intention',$intention);
        //消费类型
        $consumptionType=controller("Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        //追踪阶段
        $seles = controller('crm/Customer','lib')->get_seles_step();
        $this->assign("seles",$seles);
        $auth = check_right('menu1512998373');
        $this->assign("auth",$auth);
        //不再追踪原因
        $reason = db('crm_s_file_reason')->where('shop_code',session('shop_code'))->select();
        $this->assign("reason",$reason);
        //驳回原因
        $reject = db('crm_s_reject_reason')->where('shop_code',session('shop_code'))->select();
        $this->assign("reject",$reject);
        //省
        $province = controller('crm/Customer','lib')->address(['type'=>1,'shop_code'=>session('shop_code')]);
        $this->assign("province",$province);
        //追踪必选项配置
        $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);
        //预约短信模板
        $yyModel  = db_config('yy_sms_model_'.session('shop_code'));
        $this->assign('model_id',$yyModel);
        //所有短信模板
        $smsmodel = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('status',1)->field('id,mtemplate_name')->select();
        $this->assign('model',$smsmodel);

        $this->assign('now_time', date('Y-m-d H:i:s'));
        $this->assign('today', date('Y-m-d'));
        // 追踪记录
        $trackInfos = controller("crm/Customer","lib")->getCustomerTrackInfos($param['id']);
        $this->assign('trackInfoss', $trackInfos);
        // 追踪是否使用预约进店
        $this->assign('is_track_yjd',config('is_track_yjd'));

        // 录入必选项定制 电访时显示 20200106
        if (ini('lr_must.shop_code')==session('shop_code')) {
            // 判断字段是否存在
            $column = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>ini('lr_must.field')));
            if ($column) {
                $this->assign("xaf_field1",ini('lr_must.field'));
                $this->assign("xaf_fieldname1",ini('lr_must.fieldname'));
                $select = explode(',', ini('lr_must.select'));
                $this->assign("xaf_select1",$select);
            }
        }
        // 儿童追踪页面
        return $this->fetch('dianfang_child');
        // if(session('shop_type') == 2){
        // }else{
        //     return $this->fetch('dianfang');
        // }
        // return $this->fetch();
    }
    // 新版电访页面 20201022
    public function dianfang_new(){

        return $this->fetch();
    }
    //追踪记录
    public function traceRecord(){
        // 追踪记录
        $trackInfos = controller("Customer","lib")->getCustomerTrackInfos(input('param.id'));
        return $trackInfos;
    }

    //修改日志
    public function changeLog(){
        $changeLogs = controller("Customer","lib")->getCustomerChangeLogs(input('param.id'));
        $info = [];
        $children = array(0=>"customer_name","customer_tel","customer_wechat","mate_name","mate_tel","mate_wechat");
        foreach($changeLogs as $k=>$v){
            if(is_json($v['old_data']) || is_json($v['data'])){
                $oldDate = json_decode($v['old_data'], true);
                $oldDateStr = '';
                foreach ($oldDate as $kk => $vv) {
                    if (session('shop_type')==2) {
                        if (in_array($kk, $children)) {
                            $kk = $kk."s";
                        }
                    }
                    $key = translate('crm_c_customerinfo',$kk);
                    if($kk == 'is_valid'){
                        $vv = getIsValid($vv);
                    }
                    if($kk == 'is_intostore'){
                        $vv = getIsIntostore($vv);
                    }
                    if($kk == 'is_loss'){
                        $vv = getIsLoss($vv);
                    }
                    if($kk == 'is_status'){
                        $vv = getIsStatusAttr($vv);
                    }
                    if($key){
                        $oldDateStr .= $key.'：'.$vv.'；<br>';
                    }
                }
                $newDate = json_decode($v['data'], true);

                $newDateStr = '';
                foreach ($newDate as $kkk => $vvv) {
                    if (session('shop_type')==2) {
                        if (in_array($kkk, $children)) {
                            $kkk = $kkk."s";
                        }
                    }
                    if($kkk == 'is_valid'){
                        $vvv = getIsValid($vvv);
                    }
                    if($kkk == 'is_intostore'){
                        $vvv = getIsIntostore($vvv);
                    }
                    if($kkk == 'is_loss'){
                        $vvv = getIsLoss($vvv);
                    }
                    $key1 = translate('crm_c_customerinfo',$kkk);
                    if($key1){
                        $newDateStr .= $key1.'：'.$vvv.'；<br>';
                    }
                }
                $info[$k]['action'] = getLogsName($v['action']) ? getLogsName($v['action']) : '';
                $info[$k]['oldDateStr'] = $oldDateStr;
                $info[$k]['newDateStr'] = $newDateStr;
                $info[$k]['create_time'] = $v['create_time'];
                $info[$k]['staff_name'] = $v['staff_name'];
            }else{
                // $oldDate = json_decode($v['old_data'], true);
                $oldDateStr = $v['old_data'];
                $newDateStr = $v['data'];
                /* foreach ($oldDate as $kk => $vv) {
                     $oldDateStr .= $kk.'：'.$vv.'；';
                 }
                 $newDate = json_decode($v['data'], true);
                 $newDateStr = '';
                 foreach ($newDate as $kk => $vv) {
                     $newDateStr .= $kk.'：'.$vv.'；';
                 }*/
                $info[$k]['action'] = getLogsName($v['action']) ? getLogsName($v['action']) : '';
                $info[$k]['oldDateStr'] = $oldDateStr;
                $info[$k]['newDateStr'] = $newDateStr;
                $info[$k]['create_time'] = $v['create_time'];
                $info[$k]['staff_name'] = $v['staff_name'];
            }
        }
        return $info;
    }

    //历史订单 历史订单，现在没有表，调其他接口
    public function orderHistory(){
        $param = input();
        $mid = (int)$param['mid'];
        $id = (int)$param['id'];
        $historyOrders = controller("crm/Customer","lib")->getCustomerHistoryOrders($id,$mid);
        $is_erp = is_install('sx_erp');
        foreach ($historyOrders as $key => $value) {
            if ($is_erp === false) {
                $historyOrders[$key]['erp_status'] = 0;
                $historyOrders[$key]['erp_link'] = '';
            }else{
                $historyOrders[$key]['erp_status'] = 1;
                $historyOrders[$key]['erp_link'] = '/crm/Customer/getAllServiceInfo/order_sn/'.$value['order_sn'];
            }
        }
        return $historyOrders;
    }
    //短信日志
    public function customerMsg(){
        //发送短信记录
        $msg = controller("Customer","lib")->getMsgList(input());
        return $msg;
    }

    //编辑状态
    public function editStatus(){

    }

    //刷新
    public function refresh(){

    }

    //拨打电话
    public function dial(){

    }

    //发送短信
    public function sendShortMessage(){

    }

    //快速标记
    public function customerSign(){
        return controller('Customer','lib')->customerSign(input('post.'));
    }
    //发送短信
    public function send_message(){
        if(!check_right('menu1512971646')){
            return array('msg'=>'无此操作权限','code'=>100);
        }else{
            return controller('crm/Customer','lib')->send_message(input('post.'));
        }
    }
    //追踪添加
    public function addSalesTracking(){
        return controller('Customer','lib')->addSalesTracking(input('post.'));
    }
    //追踪修改  20180910
    public function editSalesTracking(){
        $data = input('post.');

        // 录入必选项定制 电访编辑验证 录入时验证 20200106
        if (ini('lr_must.shop_code')==session('shop_code')) {
            // 判断字段是否存在
            $column = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>ini('lr_must.field')));
            if ($column) {
                if (!$data[ini('lr_must.field')]) {
                    return array('code' => 90,'msg' =>'请选择品类','data'=>'');
                }
            }
        }
        // var_dump($data);
        // exit;
        //电访必选项配置
        $dfMust = db_config('df_must_'.session('brandclass_id'));
        $dfMust = trim($dfMust, ',');
        if ($data['noTrack'] == 1) {
            if ($dfMust) {
                $dfMust = explode(',',$dfMust);
                foreach ($dfMust as $key => $value) {
                    if ($value == 'next_time') {
                        if (!$data[$value] || $data[$value] <= date('Y-m-d H:i:s')) {
                            return json(array('code'=>'99','msg'=>'再约时间小于当前时间，请重试'));
                        }
                    }
                }
            }
        }
        elseif($data['noTrack'] ==  3){
            $onlinecash_invite = db_config('onlinecash_invite_'.session('brandclass_id'));
            $info = controller('crm/Customer','lib')->getCustomerInfo($data['customer_id']);
            if(!$onlinecash_invite && $info['order_type'] == 1 && $info['order_number']){
                return json(array('code'=>'90','msg'=>'线上订单不允许预约！'));
            }
            if($info['syjd_day'] && $info['is_intostore'] > 1){
                return json(array('code'=>'95','msg'=>'已经进店，不能再预约！'));
            }
        }
        // 0511
        // 如果，手机号，微信，微博，都不存在，返回报错
        if (!$data['customer_tel'] && !$data['customer_wechat']) {
            $returnData = array('code' => 300,'msg' =>'请填写手机号、微信任一项联系方式');
            return json($returnData);
        }
        $dfMust = explode(',',$dfMust);
        if ($data['noTrack'] == 1 && (in_array('baby_birthday',$dfMust)||in_array('ready_baby_day',$dfMust)) && !$data['baby_birthday'] && !$data['ready_baby_day']) {
            $returnData = array('code' => 301,'msg' =>'请填写宝宝生日、预产期任一项');
            return json($returnData);
        }
        if (!$data['customer_id']) {
            $returnData = array('code' => 100,'msg' =>'用户ID数据为空，请重试');
            return json($returnData);
        }
        $has = controller("Customer","lib")->getCustomerInfo($data['customer_id']);
        if (!$has) {
            $returnData = array('code' => 900,'msg' =>'用户数据不存在，请检查！');
            return json($returnData);
        }
        // 验证手机号正则 (父母)
        $contact = checkContact($data);
        if ($contact['code'] != 200) {
            return $contact;
        }
        // 判断是否排重
        $exclusion_field = config('exclusion_field') ? config('exclusion_field') : ['customer_tel'];
        foreach ($exclusion_field as $key => $value) {
            if ($data[$value] && $has[$value] != $data[$value]) {
                $repeat[$value] = $data[$value];
            }
        }
        if ($repeat) {
            // 如果是转介绍客资
            if ($has['customer_type'] == 2) {
                $customer_channel = '';
            }else{
                $customer_channel = $has['customer_channel'];
            }
            // 组织结构
            $orz = [
                'add_shop_code'=> $has['add_shop_code'],
                'shop_code'    => $has['shop_code'],
                'brandclass'   => $has['brandclass'],
            ];
            // 联系方式
            // $con = [
            //     'customer_tel'   => $data['customer_tel'],
            //     'customer_wechat'=> $data['customer_wechat'],
            //     'mate_tel'       => $data['mate_tel'],
            //     'mate_wechat'    => $data['mate_wechat'],
            // ];
            // 其他排重条件
            $other = [
                'channel' => $customer_channel,
            ];

            $baby_time = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>'baby_time'));
            if (!$baby_time) {
                unset($data['baby_time']);
            }else{
                $other['baby_time'] = $data['baby_time'] ? $data['baby_time'] : $has['baby_time'];
            }

            /**  2021-03-15 南宁版CRM 过保护期客资，与保护期客资流程，移到61版CRM  **/
            if (!$repeat['customer_wechat']) {
                $repeat['customer_wechat'] = $data['customer_wechat'];
            }
            if (!$repeat['customer_qq']) {
                $repeat['customer_qq'] = $data['customer_qq'];
            }
            if (!$repeat['mate_tel']) {
                $repeat['mate_tel'] = $data['mate_tel'];
            }
            if (!$repeat['consultation_type_id']) {
                $repeat['consultation_type_id'] = $data['consultation_type_id'];
            }
            /**  2021-03-15 end  **/

            $repRes = controller("crm/Customer", "lib")->isRepeat($orz, $repeat, $other, $has['id']);
            if ($repRes['code']!=200) {
                return $repRes;
            }
        }
        // var_dump($repRes);die;
        // 清除追踪记录的缓存
        $unique = db('crm_c_customerinfo')->where('id',$data['customer_id'])->value('c_unique');
        cache('track_log_'.$unique,null);
        return controller('Customer','lib')->editSalesTracking(input('post.'));
    }

    //新客资来电添加
    public function addNewCusCall(){
        $data = input();
        if($data['customer_id']){
            return controller('Customer','lib')->addOldCusCall($data);
        }else{
            return controller('Customer','lib')->addNewCusCall($data);
        }
    }
    //老客资来电添加
    public function addOldCusCall(){
        return controller('Customer','lib')->addOldCusCall(input('post.'));
    }
    //不再追踪
    public function notTraking(){
        if(!check_right('menu1519633436')){
            return array('msg'=>'无此操作权限','code'=>100);
        }else{
            return controller('Customer','lib')->notTraking(input('post.'));
        }
    }
    /**
     *      把秒数转换为时分秒的格式
     *      @param Int $times 时间，单位 秒
     *      @return String
     */
    static function secToTime($times){
        // $result = '00:00:00';
        $result = '00:00';
        if ($times>0) {
            $hour = 1;
            $minute = floor(($times-3600 * $hour)/60);
            $second = floor((($times-3600 * $hour) - 60 * $minute) % 60);
            $result = $minute.':'.$second;
            // $result = $hour.':'.$minute.':'.$second;
        }
        return $result;
    }
    public function setJQGrid(){
        $param = input('post.');
        $arr = $param['arrColumn'];
        $column = implode(',',$arr);
        db()->startTrans();
        try{
            $data['custom_name']  = $param['name'] ? json_encode($param['name']) : null;
            $data['custom_model'] = $param['model'] ? json_encode($param['model']) : null;
            $data['custom_column']= $column;
            $data['staff_id']     = session('staff_id');
            $data['staff_name']   = session('staff_name');
            $data['shop_type']   = session('shop_type');
            //查询有无数据
            $info = db('crm_s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->find();
            if($info['id']){
                db('crm_s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->update($data);
            }else{
                db('crm_s_custom_column')->insert($data);
            }

            cache('colColumn_'.session('staff_id').'_'.session('shop_type'),$column);
            cache('colNames_'.session('staff_id').'_'.session('shop_type'),$param['name'] ? json_encode($param['name']): null);
            cache('colModel_'.session('staff_id').'_'.session('shop_type'),$param['model'] ? json_encode($param['model']) : null);
            // action_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return true;
        }catch (\Exception $e){
            db()->rollback();
            return false;
        }
    }
    //查询自定义列
    public function getCustomColumn(){
        $column= cache('colColumn_'.session('staff_id').'_'.session('shop_type'));
        $names = cache('colNames_'.session('staff_id').'_'.session('shop_type'));
        $model = cache('colModel_'.session('staff_id').'_'.session('shop_type'));

        if(strlen($column)>0 && !$names && !$model){
            $info = array(
                'custom_name'=>json_encode($names),
                'custom_model'=>json_encode($model),
            );
        }else{
            $info = db('crm_s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->find();
            if(!empty($info)){
                cache('colColumn_'.session('staff_id').'_'.session('shop_type'),$info['custom_column']);
                cache('colNames_'.session('staff_id').'_'.session('shop_type'),$info['custom_name']);
                cache('colModel_'.session('staff_id').'_'.session('shop_type'),$info['custom_model']);
                $info = array(
                    'custom_name'=>($info['custom_name']),
                    'custom_model'=>($info['custom_model']),
                );
            }
        }
        return $info;
    }
    // 同步其他人的自定义列给自己
    public function syncColumn(){
        $staff_name = input('post.staffname');
        $columnInfo = db('crm_s_custom_column')->where('staff_name', $staff_name)->where('shop_type',session('shop_type'))->find();
        if (!$columnInfo || !$columnInfo['custom_column']) {
            $returnData = [
                'code' => '100',
                'msg'  => '目标人没有设定自定义列，请确定。',
            ];
            return $returnData;
        }

        $data['custom_name']  = $columnInfo['custom_name'];
        $data['custom_model'] = $columnInfo['custom_model'];
        $data['custom_column']= $columnInfo['custom_column'];
        $data['staff_id']     = session('staff_id');
        $data['staff_name']   = session('staff_name');
        $data['shop_type']   = session('shop_type');

        // 查询当前员工是否存在自定义列
        $info = db('crm_s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->find();

        db()->startTrans();
        try {
            if($info['id']){
                db('crm_s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->update($data);
            }else{
                db('crm_s_custom_column')->insert($data);
            }

            cache('colColumn_'.session('staff_id').'_'.session('shop_type'), $data['custom_column']);
            cache('colNames_'.session('staff_id').'_'.session('shop_type'), $data['custom_name']);
            cache('colModel_'.session('staff_id').'_'.session('shop_type'), $data['custom_model']);

            db()->commit();
            $returnData = [
                'code' => '200',
                'msg'  => 'success',
            ];
        } catch (\Exception $e) {
            db()->rollback();
            $returnData = [
                'code' => '101',
                'msg'  => '同步失败，请联系管理员',
                'error'=> $e->getMessage(),
            ];
        }
        return $returnData;
    }
    //筛客
    public function skCustomer(){
        if(!check_right('menu1519635403')){
            return array('code'=>130,'msg'=>'你无此操作权限');
        }else{
            return controller('crm/Customer','lib')->skCustomer(input('post.'));
        }
    }
    //根据来电获取是新客户还是老客户
    public function getCustomerByTel(){
        return controller('crm/Customer','lib')->getCustomerByTel(input('post.'));
    }
    //预约进店页面
    public function yyjd(){
        // 权限
        $auth = check_right('menu1519633870');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有操作预约进店的权限，请先设置权限');
            return json($return);
            exit;
        }


        $param = input('param.');


        $table = isTableExist('crm_c_customer_intostore');
        if ($table) {
            $where['status']= 1;
            $where['cid']  = (int)$param['id'];
            $info =  controller("Customer","lib")->getCustomerInfoIntostore($param['id']);
        }else{
            $info = controller("Customer","lib")->getCustomerInfo($param['id']);
            $info['intostore_remark'] = $info['intostore_note'];
        }
        //意向店面
        $intentionShop=controller('crm/Customer','lib')->get_shop(['brandclass'=>$info['brandclass'],'is_marketing'=>2]);
        $this->assign('info',$info);
        $this->assign('intentionShop',$intentionShop);
        //预约短信模板
        $yyModel  = db_config('yy_sms_model_'.session('shop_code'));
        $this->assign('model_id',$yyModel);
        //所有短信模板
        $smsmodel = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('status',1)->field('id,mtemplate_name')->select();
        $this->assign('model',$smsmodel);
        return $this->fetch();
    }
    //预约进店
    public function customerYJD(){
        if(!check_right('menu1519633870')){
            return array('code'=>130,'msg'=>'你无此操作权限');
        }else{
            $data = input('post.');
            $onlinecash_invite = db_config('onlinecash_invite_'.session('brandclass_id'));
            // $info = controller('crm/Customer','lib')->getCustomerInfo($data['id']);
            $info = db('crm_c_customerinfo')
                ->where('id',$data['id'])
                ->field('yjd_day,is_intostore,syjd_day,order_type,order_number')
                ->find();
            if(!$onlinecash_invite && $info['order_type'] == 1 && $info['order_number'] && $info['syjd_day']){
                return json(array('code'=>'90','msg'=>'线上订单不允许预约！'));
            }
            if($info['syjd_day'] && $info['is_intostore'] > 1){
                return json(array('code'=>'95','msg'=>'已经进店，不能再预约！'));
            }
            return controller("crm/Customer","lib")->customerYJD_child($data);
            // if(session('shop_type') == 2){
            // }else{
            //     return controller("Customer","lib")->customerYJD($data);
            // }
        }
    }

    public function getStaffForWorktype(){
        $data = input();
        $p['shop_code'] = $data['shop_code'];
        $p['work_type'] = $data['work_type'];
        $p['all']       = '1';
        $staff = getShopStaffs($p);
        return $staff;
        // return controller("crm/Customer","lib")->sklist($data['shop_code'],$data['work_type']);
    }
    //转客资
    public function zhuanCustomer(){
        return $this->fetch();
    }
    public function zhuanCustomerJSON(){
        $call = controller("Customer","lib")->zhuanCustomer(input());
        return $call;
    }
    public function zhuanKeZi(){
        return controller("Customer","lib")->zhuanKeZi(input('post.'));
    }
    public function delNewCall(){
        return controller("Customer","lib")->delNewCall(input('post.id'));
    }
    //转客资
    public function zhuanCustomerInfo(){
        $call = controller("Customer","lib")->getCallInfo(input('param.id'));
        $this->assign('info',$call);
        //客户意向
        $intention=controller("Customer","lib")->intention(array('shop_code'=>session('shop_code')));
        $this->assign('intention',$intention);
        //客户来源
        $source=controller("Customer","lib")->source(array('shop_code'=>session('shop_code')));
        $this->assign("source",$source);
        //获取方式
        $accessModel=controller("Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
        $this->assign("accessModel",$accessModel);
        //来源渠道
        $channel=controller("Customer","lib")->getChannel();
        $this->assign("channel",$channel);
        //消费类型
        $consumptionType=controller("Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        //分区
//        $area=controller("Customer","lib")->areaSet(array('shop_code'=>session('shop_code')));
//        $this->assign("area",$area);
        //客户标记
        $sign=controller('crm/Setting','lib')->gettrackingKmarkerList();
        $this->assign("sign",$sign);
        $baby_sex = config('baby_sex');
        if(empty($baby_sex)){
            $baby_sex = [
                ['sex'=>'男',],
                ['sex'=>'女',],
            ];
        }
        $this->assign('baby_sex',$baby_sex);
        return $this->fetch();
    }
    //获取短信模板内容
    public function getModelContent(){
        $id = input('post.id');
        $res = db('crm_s_message_templateinfo')->where('id',$id)->find();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    //批量标记待定
    public function customerMoreDd(){
        $id = input();
        $info = db('crm_c_customerinfo')->where('id','in',$id['id'])->field('id,c_unique,is_valid,yx_day,customer_number,c_star_day')->select();

        db()->startTrans();
        try{
            $ids = [];
            $time = date('Y-m-d H:i:s',time());
            $data['update_time'] = $time;
            $data['is_valid'] = 2;
            $data['yx_day'] = $time;
            $log = [];
            foreach($info as $k=>$v){
                if($v['is_valid'] != 2){
                    $ids[$k] = $v['id'];
                    //追踪记录
                    $params['customer_id'] = $v['id'];
                    $params['c_unique'] = $v['c_unique'];
                    $params['customer_name'] = $v['customer_name'];
                    $params['customer_number'] = $v['customer_number'];
                    $params['sales_remark'] = '批量待定';
                    $params['sales_day'] = $time;
                    $params['sales_staff'] = session('staff_name');
                    $params['sales_staff_id'] = session('staff_id');
                    $params['sales_staff_number'] = session('staff_number');
                    $params['shop_name'] = session('shop_name');
                    $params['shop_code'] = session('shop_code');
                    db('crm_c_salestrackinginfo')->insert($params);
                    cache('getCustomerTrackInfos'.$v['id'],null);
                    //修改追踪时间
                    if(empty($v['c_star_day'])){
                        $arr = array(
                            'c_star_day' => $time,
                            'c_end_day' => $time,
                            'last_trackday' => $time,
                        );
                    }else{
                        $arr = array(
                            'c_end_day' => $time,
                            'last_trackday' => $time,
                        );
                    }
                    db('crm_c_customerinfo')->where('id',$v['id'])->update($arr);
                    //修改客资表近三次追踪记录
                    getSalesTracking($v['id']);
                    //如果是爆破活动，修改对应的爆破表数据
//                    if($info['is_act'] == 2){
//                        db('c_swap_customer')->where('customer_number',$v['customer_number'])->update(['is_valid'=>2]);
//                    }
                    $old['is_valid'] = $v['is_valid'];
                    $old['yx_day'] = $v['yx_day'];
                    $log[$k]['module']='crm';
                    $log[$k]['controller']='Customer';
                    $log[$k]['action']='customermoredd';
                    $log[$k]['ip']=get_client_ip();
                    $log[$k]['data']=json_encode($data);
                    $log[$k]['old_data']=json_encode($old);
                    $log[$k]['customer_id']=$v['id'];
                    $log[$k]['staff_id']=session('staff_id');
                    $log[$k]['staff_name']=session('staff_name');
                    $log[$k]['create_time']=$time;

                    // eric 181212  发消息
                }
            }

            $res = db('crm_c_customerinfo')->where('id','in',$ids)->update($data);
            //日志
            db('action_log','db_logs')->insertAll($log);
            db()->commit();
            return array('code'=>200,'msg'=>'批量标记待定成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>300,'msg'=>'批量标记待定失败','data'=>$e->getMessage());
        }
    }
    //批量标记有效
    public function customerMoreValid(){
        $id = input();
        $info = db('crm_c_customerinfo')->where('id','in',$id['id'])->field('id,is_valid,yx_day,unvalid_id,unvalid_reason,customer_number,c_star_day')->select();

        db()->startTrans();
        try{
            $ids = [];
            $time = date('Y-m-d H:i:s',time());
            $data['update_time'] = $time;
            $data['is_valid'] = 1;
            $data['unvalid_reason'] = null;
            $data['yx_day'] = $time;
            $log = [];
            foreach($info as $k=>$v){
                if($v['is_valid'] != 1){
                    $ids[$k] = $v['id'];
                    //追踪记录
                    $params['customer_id'] = $v['id'];
                    $params['customer_name'] = $v['customer_name'];
                    $params['customer_number'] = $v['customer_number'];
                    $params['sales_remark'] = '标记有效';
                    $params['sales_day'] = $time;
                    $params['sales_staff'] = session('staff_name');
                    $params['sales_staff_id'] = session('staff_id');
                    $params['sales_staff_number'] = session('staff_number');
                    $params['shop_name'] = session('shop_name');
                    $params['shop_code'] = session('shop_code');
                    db('crm_c_salestrackinginfo')->insert($params);
                    cache('getCustomerTrackInfos'.$v['id'],null);
                    //修改追踪时间
                    if(empty($v['c_star_day'])){
                        $arr = array(
                            'c_star_day' => $time,
                            'c_end_day' => $time,
                            'last_trackday' => $time,
                        );
                    }else{
                        $arr = array(
                            'c_end_day' => $time,
                            'last_trackday' => $time,
                        );
                    }
                    db('crm_c_customerinfo')->where('id',$v['id'])->update($arr);
                    //修改客资表近三次追踪记录
                    getSalesTracking($v['id']);
                    //如果是爆破活动，修改对应的爆破表数据
                    if($info['is_act'] == 2){
                        db('crm_c_swap_customer')->where('customer_number',$v['customer_number'])->update(['is_valid'=>1]);
                    }
                    $old['is_valid'] = $v['is_valid'];
                    $old['unvalid_id'] = $v['unvalid_id'];
                    $old['unvalid_reason'] = $v['unvalid_reason'];
                    $old['yx_day'] = $v['yx_day'];
                    $log[$k]['module']='crm';
                    $log[$k]['controller']='Customer';
                    $log[$k]['action']='customermorevalid';
                    $log[$k]['ip']=get_client_ip();
                    $log[$k]['data']=json_encode($data);
                    $log[$k]['old_data']=json_encode($old);
                    $log[$k]['customer_id']=$v['id'];
                    $log[$k]['staff_id']=session('staff_id');
                    $log[$k]['staff_name']=session('staff_name');
                    $log[$k]['create_time']=$time;

                    // eric 181212  发消息
                }
            }

            $res = db('crm_c_customerinfo')->where('id','in',$ids)->update($data);
            //日志
            db('crm_action_log','db_logs')->insertAll($log);
            db()->commit();
            return array('code'=>200,'msg'=>'批量标记有效成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>300,'msg'=>'批量标记有效失败','data'=>$e->getMessage());
        }
    }
    //批量标记无效
    public function customerMoreUnValid(){
        $param = input();
        $info = db('crm_c_customerinfo')->where('id','in',$param['id'])->field('id,c_unique,is_valid,yx_day,unvalid_id,unvalid_reason,customer_number,c_star_day')->select();

        db()->startTrans();
        try{
            $ids = [];
            $time = date('Y-m-d H:i:s',time());
            $data['update_time'] = $time;
            $data['is_valid'] = 3;
            $data['unvalid_id'] = $param['unvalid_id'];
            $data['unvalid_reason'] = $param['unvalid_reason'];
            $data['yx_day'] = $time;
            $log = [];
            foreach($info as $k=>$v){
                if($v['is_valid'] != 3){
                    $ids[$k] = $v['id'];
                    //追踪记录
                    $params['customer_id'] = $v['id'];
                    $params['c_unique'] = $v['c_unique'];
                    $params['customer_name'] = $v['customer_name'];
                    $params['customer_number'] = $v['customer_number'];
                    $params['sales_remark'] = '标记无效-'.$param['unvalid_reason'];
                    $params['sales_day'] = $time;
                    $params['sales_staff'] = session('staff_name');
                    $params['sales_staff_id'] = session('staff_id');
                    $params['sales_staff_number'] = session('staff_number');
                    $params['shop_name'] = session('shop_name');
                    $params['shop_code'] = session('shop_code');
                    db('crm_c_salestrackinginfo')->insert($params);
                    cache('getCustomerTrackInfos'.$v['id'],null);
                    //修改追踪时间
                    if(empty($v['c_star_day'])){
                        $arr = array(
                            'c_star_day' => $time,
                            'c_end_day' => $time,
                            'last_trackday' => $time,
                        );
                    }else{
                        $arr = array(
                            'c_end_day' => $time,
                            'last_trackday' => $time,
                        );
                    }
                    db('crm_c_customerinfo')->where('id',$v['id'])->update($arr);
                    //修改客资表近三次追踪记录
                    getSalesTracking($v['id']);
                    //如果是爆破活动，修改对应的爆破表数据
                    if($info['is_act'] == 2){
                        db('crm_c_swap_customer')->where('customer_number',$v['customer_number'])->update(['is_valid'=>3]);
                    }
                    $old['is_valid'] = $v['is_valid'];
                    $old['unvalid_id'] = $v['unvalid_id'];
                    $old['unvalid_reason'] = $v['unvalid_reason'];
                    $old['yx_day'] = $v['yx_day'];
                    $log[$k]['module']='crm';
                    $log[$k]['controller']='Customer';
                    $log[$k]['action']='customermoreunvalid';
                    $log[$k]['ip']=get_client_ip();
                    $log[$k]['data']=json_encode($data);
                    $log[$k]['old_data']=json_encode($old);
                    $log[$k]['customer_id']=$v['id'];
                    $log[$k]['staff_id']=session('staff_id');
                    $log[$k]['staff_name']=session('staff_name');
                    $log[$k]['create_time']=$time;
                }
            }

            $res = db('crm_c_customerinfo')->where('id','in',$ids)->update($data);

            //日志
            db('crm_action_log','db_logs')->insertAll($log);
            db()->commit();
            return array('code'=>200,'msg'=>'批量标记无效成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>300,'msg'=>'批量标记无效失败','data'=>$e->getMessage());
        }
    }
    //一键标记有效
    public function signValid(){
        if(check_right('menu1546854995')){
            $id = input('post.id');
            return controller('crm/Customer','lib')->signValid($id);
        }else{
            return array('code'=>100,'msg'=>'您没有标记有效权限');
        }

    }
    //一键标记无效
    public function signUnvalid(){
        if(check_right('menu1517129331')){
            $param = input();
            return controller('crm/Customer','lib')->signUnValid($param);
        }else{
            return array('code'=>100,'msg'=>'您没有标记无效权限');
        }
    }
    //撤销
    public function customerRevoke(){
        if(check_right('menu1520675106')){
            $id = input('post.id');
            $info = controller("Customer","lib")->getCustomerInfo($id);
            if($info['is_loss'] == 2){
                return array('code'=>500,'msg'=>'当前客资不用撤销！');
            }else{
                $data['is_loss']    = 2;
                $data['loss_day']   = date('Y-m-d H:i:s',time());
                $data['loss_cause'] = null;
                $data['update_time']= date('Y-m-d H:i:s',time());
            }

            db()->startTrans();
            try{
                db('crm_c_customerinfo')->where('id',$id)->update($data);
                //追踪记录
                $params['customer_id'] = $id;
                $params['c_unique'] = $info['c_unique'];
                $params['customer_name'] = $info['customer_name'];
                $params['customer_number'] = $info['customer_number'];
                $params['sales_remark'] = '撤销：不在追踪-->可追踪';
                $params['sales_day'] = date('Y-m-d H:i:s',time());
                $params['sales_staff'] = session('staff_name');
                $params['sales_staff_id'] = session('staff_id');
                $params['sales_staff_number'] = session('staff_number');
                $params['shop_name'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('crm_c_salestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$id,null);
                //修改追踪时间
                $time = date('Y-m-d H:i:s',time());
                if(empty($info['c_start_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }
                db('crm_c_customerinfo')->where('id',$id)->update($arr);
                getSalesTracking($id);
                action_log($data,$info,$id,session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>200,'msg'=>'撤销成功');
            }catch (Exception $e){
                db()->rollback();
                return array('code'=>300,'msg'=>'撤销失败');
            }
        }else{
            return array('code'=>100,'msg'=>'您无撤销权限');
        }

    }
    //替换移动端三级联动插件，取MC地址表，已替换，无人调用，暂做保留
    public function getProvinceApp(){
        $address = cache('crm_address_app_'.session('shop_code'));
        if(empty($address)){
            $data['type']=1;
            $data['shop_code']=session('shop_code');
            $address=controller("Customer","lib")->address($data);
            foreach($address as $k=>$v){
                $address[$k]['value']=$v['id'];
                $address[$k]['text']=$v['name'];
                $address[$k]['children'] = controller("Customer","lib")->address(['pid'=>$v['id'],'type'=>2,'shop_code'=>session('shop_code')]);
                foreach($address[$k]['children'] as $key=>$val){
                    $address[$k]['children'][$key]['value']=$val['id'];
                    $address[$k]['children'][$key]['text']=$val['name'];
                    $address[$k]['children'][$key]['children'] = controller("Customer","lib")->address(['pid'=>$val['id'],'type'=>3,'shop_code'=>session('shop_code')]);
                    foreach($address[$k]['children'][$key]['children'] as $kk=>$vv){
                        $address[$k]['children'][$key]['children'][$kk]['value'] = $vv['id'];
                        $address[$k]['children'][$key]['children'][$kk]['text'] = $vv['name'];
                    }
                }
            }
            if(empty($address)){
                $data['shop_code']=session('shop_code');
                $url="59fd885ed3628";

                $data['type']=1;
                $info=sx_call($url,$data);
                if($info['code'] == 200){
                    $address = $info['data'];
                    foreach($address as $k=>$v){
                        $address[$k]['value']=$v['id'];
                        $address[$k]['text']=$v['name'];
                        $info1 = sx_call($url,['pid'=>$v['id'],'type'=>2]);
                        if($info1['code'] == 200){
                            $address[$k]['children'] = $info1['data'];
                            foreach($address[$k]['children'] as $key=>$val){
                                $address[$k]['children'][$key]['value']=$val['id'];
                                $address[$k]['children'][$key]['text']=$val['name'];
                                $info2 = sx_call($url,['pid'=>$val['id'],'type'=>3]);
                                if($info2['code'] == 200){
                                    $address[$k]['children'][$key]['children'] = $info2['data'];
                                    foreach($address[$k]['children'][$key]['children'] as $kk=>$vv){
                                        $address[$k]['children'][$key]['children'][$kk]['value'] = $vv['id'];
                                        $address[$k]['children'][$key]['children'][$kk]['text'] = $vv['name'];
                                    }
                                }
                            }
                        }
                    }
                }
                cache('crm_address_app_'.session('shop_code'),$address);
            }
        }
        return json_encode($address);
    }
    //订单详情
    public function getOrderDetail(){
        $order_sn = input('post.order_sn');
        $res = db('crm_c_order_detail')->where('order_sn',$order_sn)->select();
        if($res){
            $arr = array('code'=>200,'data'=>$res);
        }else{
            $arr = array('code'=>100,'data'=>'','msg'=>'暂无详情');
        }
        return $arr;
    }
    //事业部下的店
    public function searchShop(){
        $brandclass_id = session('brandclass_id');
        if(!$brandclass_id){
            return false;
        }
        // $url = '5a37a1503264d';
        $data['brandclass_id']= $brandclass_id;
        // $res = sx_call($url, $data);
        // if ($res['code'] == 200) {
        //     $shopList = $res['data'];
        // }else{
        //     $shopList = '';
        // }
        $mc = new \app\common\lib\mcInterface();
        $shopList = $mc->getShopInfo($data);
        if ($shopList===false) {
            $shopList = [];
        }
        return $shopList;
    }
    public function getDepartmentList($param=[]){
        //部门 
        $shop_code = input('param.shop_code');
        if(!$shop_code) $shop_code = $param['shop_code'];
        if(!$shop_code) return [];
        // $url = '5a62dcd5c7e40';
        // $res = sx_call($url,['shop_code'=>$shop_code]);
        // if($res['code'] == 200){
        //     return $res['data'];
        // }else{
        //     return false;
        // }
        $mc = new \app\common\lib\mcInterface();
        $departmentList = $mc->getDepartments(['shop_code'=>$shop_code]);
        return $departmentList;
    }

    public function getDepartmentListReport(){
        //部门
        $data = input('param.');
        // $url = '5a62dcd5c7e40';
        // $res = sx_call($url,$data);
        // if($res['code'] == 200){
        //     return $res['data'];
        // }else{
        //     return false;
        // }
        $mc = new \app\common\lib\mcInterface();
        $departmentList = $mc->getDepartments($data);
        return $departmentList;
    }
    //部门下的人员
    public function getDepartmentStaff(){
        $id = (int)input('param.id');
        if(!$id) return [];
        /*
        $url = '5a01766b4a3dd';
        $res = sx_call($url,['department_id'=>$id]);
        if($res['code'] == 200){
            return $res['data'];
        }else{
            return false;
        }
        */
        $mc = new \app\common\lib\mcInterface();
        $departmentStaffs = $mc->getStaffInfo(['department_id'=>$id]);
        return $departmentStaffs;
    }
    public function moreSearch(){
        // 权限
        $auth = check_right('menu1521267312');
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        return $this->fetch();
    }
    public function moreSearchCus(){
        $data = input();
        $tel = $data['tel'];
        $tel = trim($tel);
        $data['tel'] = str_replace(array("\r\n","\r","\n",""," ",PHP_EOL),',',$tel);
        $data['tel'] = explode(",",$data['tel']);
        $info = controller('crm/Customer','lib')->moreSearchCus($data);
        return json($info);
    }
    public function searchOrders(){
        // 权限
        $is_erp = is_install('sx_erp');
        if (!$is_erp) {
            echo "当前系统未对接素玄店务系统，请联系销售人员。";
            exit();
        }

        $auth = check_right('menu1521267312');
        if(request()->isPost()){
            if(!$auth){
                $ret = array(
                    'code'=>500,
                    'msg'=>'无此操作权限',
                    'data'=>[],
                );
                return json($ret);
            }
            $shopType = session('shop_type');
            if ($shopType == 2) {
                $shopType = 1;
            }else{
                $shopType = 0;
            }
            $condition['shop_type'] = $shopType;
            
            $keyword = trim(input('keyword/s'));
            $condition['keyword'] = $keyword;

            $startDate = input('start_date');
            $endDate = input('end_date');

            if($startDate){
                $start = strtotime($startDate);
                $startDate = date('Ymd',$start);
            }else{
                $start = date('Ymd',strtotime('2010-01-01'));
                $startDate = date('Ymd',$start);
            }
            if($endDate){
                $end = strtotime($endDate);
                $endDate = date('Ymd',$end);
            }else{
                $end = time();
                $endDate = date('Ymd',$end);
            }
            if($end < $start){
                $ret = array(
                    'code'=>500,
                    'msg'=>'查询日期错误。',
                    'data'=>[],
                );
                return json($ret);
            }
            // if(($end - $start) > 61 * 86400){
            //     $ret = array(
            //         'code'=>500,
            //         'msg'=>'最多可查询两个月的订单',
            //         'data'=>[],
            //     );
            //     return json($ret);
            // }
            $brandId = session('brandclass_id');
            $condition['brand_id'] = $brandId;
            $condition['start_date'] = $startDate;
            $condition['end_date'] = $endDate;
            $list = controller('crm/Customer','lib')->searchErpOrder($condition);
            if($list === false){
                $ret = [
                    'code'=>500,
                    'msg'=>'查询失败，请重试。',
                    'data'=>[],
                ];
            }else if(isset($list['code'])){
                $ret = [
                    'code'=>$list['code'],
                    'msg'=>$list['msg'],
                    'data'=>[],
                ];
            }else{
                $ret = [
                    'code'=>200,
                    'msg'=>'',
                    'data'=>$list,
                ];
            }
            return json($ret);
        }
        $this->assign('today',date('Y-m-d'));
        if (!$auth) {
            controller('crm/Index','controller')->index();
            exit;
        }
        return $this->fetch();
    }
    public function versionUpdateLog(){
        $up = new \app\index\lib\Update();
        if(request()->isAjax()){
            $res = $up->runUpdate();
            if($res['code'] == 200){
                return json(['code'=>200]);
            }else{
                return $res;
            }
        }
        $update = include_once(ROOT_PATH . 'application/index/lib/update_log.php');
        krsort($update);
        $this->assign('update',$update);

        
        $dbVersion = $up->getDbVersion();
        $thisVersion = get_version('APP');
        if(version_compare($thisVersion, $dbVersion, '>')){
            //需要升级
            $sqlList = $up->getUpdateSqlList();
            $this->assign('updateSqlList',$sqlList);
            $this->assign('need_update',1);
            $this->assign('dbVersion',$dbVersion);
            $this->assign('thisVersion',$thisVersion);
        }
        // 2020-08-05 去掉列表页选中颜色2020-08-05 列表页鼠标跟随颜色
        // $on_select_color = db_config('on_select_color');
        // $this->assign('on_select_color',$on_select_color ? $on_select_color : 'ffd7dc');
        // $hover_color = db_config('hover_color');
        // $this->assign('hover_color',$hover_color ? $hover_color : 'ffe1c9');
        $service_end = db_config('service_end');
        $this->assign('service_end',$service_end);
        $service_start = db_config('service_start');
        $this->assign('service_start',$service_start);
        $service_no = db_config('service_no');
        $this->assign('service_no',$service_no);
        // 2020-08-05 去掉隔行变色
        // $alt_row_color = db_config('alt_row_color');
        // $this->assign('alt_row_color',$alt_row_color);
        $success_color = db_config('success_color');
        $this->assign('success_color',$success_color);
        $into_color = db_config('into_color');
        $this->assign('into_color',$into_color);
        $loss_color = db_config('loss_color');
        $this->assign('loss_color',$loss_color);
        $erp_loss_color = db_config('erp_loss_color');
        $this->assign('erp_loss_color',$erp_loss_color);
        $int_no_suc_color = db_config('int_no_suc_color');
        $this->assign('int_no_suc_color',$int_no_suc_color);
        $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);
        $unvalid_color = db_config('unvalid_color');
        $this->assign('unvalid_color',$unvalid_color);
        $urgent_color = db_config('urgent_color');
        $this->assign('urgent_color',$urgent_color);
        return $this->fetch();
    }
    public function getChannel(){
        return controller("Customer","lib")->getChannel(input('post.shop_code'));
    }
    public function getErChannel(){
        $shopCode = input('shop_code');
        $shopCode = $shopCode?$shopCode:session('shop_code');
        $erChannel = controller("crm/Customer","lib")->getErChannel($shopCode);
        return ['code'=>200,'data'=>$erChannel];
    }
    //获取事业部下的店
    public function searchShops(){
        $brandclass_id = input('param.brandclass_id');
        $shops = cache('shops_'.session('staff_id'));
        $arr = [];
        $i = 0;
        foreach($shops as $k=>$v){
            if($brandclass_id == $v['brandclass_id']){
                $arr[$i]['shop_code'] = $v['shop_code'];
                $arr[$i]['shop_name'] = $v['shop_name'];
                $i++;
            }
        }
        return $arr;
    }
    // 切换店面
    public function change_shop(){
        $data = input();
        
        $res = changeMyPosition($data['position_code']);
        if($res){
            cookie('current_position_code',$data['position_code']);
        }else{
            return false;
        }
        // 发送消息用数据
        $date = date('Y-m-d H:i:s');
        $messageD['send_type']   = 4;
        $messageD['save_msg']    = 2;//是否记录message表
        $messageD['receive_id']  = session('staff_id');
        $messageD['receive_name']= session('staff_name');
        $messageD['p_new_code']  = $data['position_code'];
        
        $res = sendSystemMessage($messageD);
        
        return true;
        $url = '5a0b96b65c111';
        $info = sx_call($url,['position_code'=>$data['position_code']]);


        session('accessModel',null);
        session('source',null);
        session('intention',null);
        session('areaSet',null);
        session('capacity',null);
        session('channel',null);
        cache('shopAllStaffs_'.session('belong_shop_code'),null);
        $b_id = session('brandclass_id');
        
        if($info['code'] == 200){
            $position = $info['data'][0];
            // print_r($position);die;
            $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$position['shop_code']]);
            if(!empty($shopInfo)){
                $shopInfo = $shopInfo[0];

                session('position_code',session('main_position_code').','.session('position_code'));
                session('main_position_code',$position['position_code']);
                session('main_position_name',$position['position_name']);
                session('department_id',$position['department_id']);
                session('department_name',$position['department_name']);

                session('shop_code',$shopInfo['shop_code']);
                session('shop_name',$shopInfo['shop_name']);
                session('belong_shop_code',$shopInfo['belong_shop_code']);
                session('belong_shop_name',$shopInfo['belong_shop_name']);
                session('brandclass_id',$position['brandclass_id']);
                session('brandclass',$position['brandclass']);
                session('shop_type',$shopInfo['shop_type']);
                session('main_work_type',$position['work_type']);

                session('is_belong',$position['grade_type']);
                session('is_sk',$shopInfo['is_sk']);
                session('is_marketing',$shopInfo['is_marketing']);//是否是营销店
                session('open_id', $shopInfo['open_id']);
                session('is_group', $shopInfo['is_group']);//是不是集团店:1:是,2:否
                //替换cache信息
                $cacheInfo = cache('staffInfo_'.session('staff_id'));
                $cacheInfo['brandclass_id'] = $position['brandclass_id'];
                $cacheInfo['brandclass'] = $position['brandclass'];
                $cacheInfo['shop_type'] = $shopInfo['shop_type'];
                $cacheInfo['department_name'] = $position['department_name'];
                $cacheInfo['department_id'] = $position['department_id'];
                $cacheInfo['main_position_name'] = $position['position_name'];
                $cacheInfo['main_position_code'] = $position['position_code'];
                $cacheInfo['position_code'] = $position['position_code'];
                $cacheInfo['main_work_type'] = $position['work_type'];

                $cacheInfo['shop_code'] = $shopInfo['shop_code'];
                $cacheInfo['shop_name'] = $shopInfo['shop_name'];
                $cacheInfo['belong_shop_code'] = $shopInfo['belong_shop_code'];
                $cacheInfo['belong_shop_name'] = $shopInfo['belong_shop_name'];
                $cacheInfo['is_marketing'] = $shopInfo['is_marketing'];
                $cacheInfo['is_sk'] = $shopInfo['is_sk'];
                $cacheInfo['is_group'] = $shopInfo['is_group'];
                $cacheInfo['active'] = time();
                cache('staffInfo_'.session('staff_id'),$cacheInfo);

                //替换为要切换的事业部的客资有效期
                if($b_id != $position['brandclass_id']){
                    $url = '5a4216fe6b2b5';
                    $info = sx_call($url,['id'=>$position['brandclass_id']]);
                    if($info['code'] == 200){
                        $brand = $info['data'][0];
                        session('valid_date', $brand['valid_date']);
                    }
                }
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    // 检查岗位是否切换
    public function checkPosition(){
        $data = input('post.');
        $p_old_code = $data['p_old_code'];
        $p_new_code = session('main_position_code');
        if (!$p_old_code || !$p_new_code) {
            $returnData['code'] = '100';
            $returnData['msg']  = 'error';
            $returnData['data'] = array('p_old_code' => $p_old_code, 'p_new_code'=>$p_new_code);
            return $returnData;
        }

        if ($p_old_code != $p_new_code) {
            $returnData['code'] = '200';
            $returnData['msg']  = 'success';
            $returnData['data'] = array('p_old_code' => $p_old_code, 'p_new_code'=>$p_new_code);
        }else{
            $returnData['code'] = '100';
            $returnData['msg']  = 'error';
            $returnData['data'] = array('p_old_code' => $p_old_code, 'p_new_code'=>$p_new_code);
        }
        return $returnData;
    }
    //转介绍：介绍人信息修改
    public function editIntroducer(){
        // 权限
        $auth = check_right('menu1522653972');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有操作修改介绍人信息的权限，请先设置权限');
            return json($return);
            exit;
        }
        $id = input('param.id');
        $info = controller('crm/Customer','lib')->getCustomerInfo($id);
        $this->assign('info',$info);
        return $this->fetch();
    }
    public function updateIntroducer(){
        // 权限
        $auth = check_right('menu1522653972');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有操作修改介绍人信息的权限，请先设置权限');
            return json($return);
            exit;
        }
        $data = input();
        return controller('crm/Customer','lib')->editIntroducer($data);
    }
    public function searchIntroducer(){
        $search = input('param.search');
        if(empty($search)){
            return array('Msg'=>'搜索内容不能为空！','Code'=>100,'Data'=>'');
        }
        $info = controller('crm/Customer','lib')->customerNameSearch($search);
        return $info;
    }
    //部门下的小组成员
    public function getGroup(){
        $id = input('param.department_id');
        // 调mc接口获取部门下的小组
        $mc = new \app\common\lib\mcInterface();
        $groups = $mc->getGroupInfoByDid(array('department_id' => $id));
        unset($mc);
        return $groups;
        //部门下的小组
        // $groups = db('c_staff_group')->where('department_id',$id)->field('id,group_name')->select();
    }

    //店下的小组
    public function getShopGroup(){

        $shop_code = input('param.shop_code');
        $department_id = input('param.department_id');

        $mcInterface = new \app\common\lib\mcInterface();
        $groups = $mcInterface->getGroupInfo(['shop_code'=>$shop_code,'department_id'=>$department_id]);
        unset($mcInterface);
        return $groups;

    }

    //店下的 小组人员二级
    public function getShopGroupStaff(){

        $shop_code = input('param.shop_code');

        $groupStaff = getGroupStaff(['shop_code'=>$shop_code]);

        return json($groupStaff);

    }

    //小组下 某个工作类型的员工
    public function getGroupWorkTypeStaff(){
        $data = input();
        if($data['group_id']){
            $mcParams['group_id'] = $data['group_id'];
        }

        if($data['work_type']){
            $mcParams['work_type'] = $data['work_type'];
        }

        $staff = getShopStaffs($mcParams);

        return $staff;
    }

    //小组下 
    public function getGroupStaff(){
        $data = input();
        if(!$data['group_id']){
            return array('Msg'=>'没有参数小组id！','Code'=>100,'Data'=>'');
        }

        $staff = getGroupStaffs($data);

        if ($staff['code'] == 200) {
            return $staff['data'];
        }else{
            return $staff;
        }
    }

    //店下二三级渠道
    public function getShopChannel(){

        $shop_code = input('param.shop_code');

        $channel = getChannelArray23($shop_code);

        return json($channel);
    }

    //店下省市
    public function getShopAddress(){
        $data = input();

        $shop_code = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        $where['shop_code'] = $shop_code;

        if($data['type']){
            $where['type'] = $data['type'];
        }
        if($data['pid']){
            $where['pid'] = $data['pid'];
        }

        $province = controller('crm/Customer','lib')->address($where);

        return $province;
    }


    //订单转移
    public function customerMerge(){
        $isTable = isTableExist('crm_c_customer_intostore');
        $this->assign('isTable',$isTable);
        return $this->fetch();
    }
    // 订单转移
    public function customerMergeSub(){
        $data = input();
        $logNewInfo = $logOldInfo = '';
        if ( !trim($data['orderSn']) )  {
            return array('code'=>100,'msg'=>'请输入订单编号');
        }
        $isTable = isTableExist('crm_c_customer_intostore');

        if ( !(int)$data['customerId'] ) {
            return array('code'=>101,'msg'=>'请选择客资ID');
        }
        //查询订单表看有无数据
        if($data['orderId']){
            $order = db('crm_c_customer_order')->where('id',$data['orderId'])->find();
        }else{
            $order = db('crm_c_customer_order')->where('order_sn',$data['orderSn'])->find();
        }

        if(!$order){
            return array('code'=>104,'msg'=>'未找到订单信息.');
        }


        // 原信息
        $cInfoY = db('crm_c_customerinfo')
            ->find($order['customer_id']);
        /*
		$cInfoY = db('crm_c_customerinfo')
            ->where('order_number', trim($data['orderSn']))
            ->where('brandclass_id',session('brandclass_id'))
            ->order('id desc')
            ->find();
        //*/
        // if($order['customer_id'] != $cInfoY['id']){
        // 	return array('code'=>105,'msg'=>'当前订单与客资的数据不匹配，请核实后操作.');
        // }
        if(!$cInfoY || !$order['customer_id']){
            return array('code'=>104,'msg'=>'未找到客资信息.');
        }
        if($order['into_id'] && $isTable){
            $orderIntostore = db('crm_c_customer_intostore')->where('id',$order['into_id'])->find();
        }
        $yData['is_success']       = 2;
        $yData['is_intostore']     = 1;
        $yData['syjd_day']         = null;
        $yData['order_type']       = 0;
        $yData['order_number']     = null;
        $yData['order_start_time'] = null;
        $yData['order_day']        = null;
        $yData['fact_money']       = null;
        $yData['totalpay_money']   = null;
        $yData['order_newclass']   = null;
        $yData['reception_id']   = null;
        $yData['reception_name']   = null;
        $logOldInfo .= '成交状态：未成交;进店状态：未进店；实际进店时间：空；订单类型：空；订单开始时间：空；订单有效时间：空；订单收实：空；订单套系金额：空；客资接待人员：空；';
        // 目标信息
        $cInfoM = db('crm_c_customerinfo')->where('id', $data['customerId'])->find();
        if($cInfoM['order_number']){
            return array('code'=>102,'msg'=>'目标客资不能是成单客资');
        }
        if(!$cInfoM){
            return array('code'=>106,'msg'=>'未找到目标客资信息，请核实。');
        }


        // 转移 更新部分客资数据，开单时填的数据
        $mData['erp_wphone']            = $cInfoY['erp_wphone'];
        $mData['erp_mphone']            = $cInfoY['erp_mphone'];
        $mData['consulation_shop_code'] = $cInfoY['consulation_shop_code'];
        $mData['consulation_shop']      = $cInfoY['consulation_shop'];
        $mData['reception_id']      = $cInfoY['reception_id'];
        $mData['reception_name']         = $cInfoY['reception_name'];
        $mData['customer_address']      = $cInfoY['customer_address'];
        $mData['customer_birthday']     = $cInfoY['customer_birthday'];
        $mData['mate_birthday']         = $cInfoY['mate_birthday'];
        $logNewInfo .= "ERP女士手机号：{$mData['erp_wphone']}；ERP男士手机号：{$mData['erp_mphone']}；意向店面：{$mData['consulation_shop']}；接待人员：{$mData['reception_name']}；客户地址：{$mData['customer_address']}；客户生日：{$mData['customer_birthday']}；配偶生日：{$mData['customer_birthday']}；";

        /*
        $mData['customer_area_id']      = $cInfoY['customer_area_id'];
        $mData['customer_area']         = $cInfoY['customer_area'];
        $mData['photo_address']         = $cInfoY['photo_address'];
        $mData['customer_orderaddress_id']= $cInfoY['customer_orderaddress_id'];
        $mData['customer_orderaddress'] = $cInfoY['customer_orderaddress'];
        //-----------------------------------?????????????------*/
        if($cInfoM['is_valid'] != 1){
            $mData['is_valid'] = 1;
            $mData['yx_day'] = $cInfoY['yx_day']?$cInfoY['yx_day']:$order['target_time'];
            $logNewInfo .='客资有效状态：有效；有效时间：'.$mData['yx_day'].'；';
        }
        if($cInfoM['is_loss'] == 1){
            $mData['is_loss'] = 2;
            $mData['loss_cause'] = null;
            $mData['loss_remark'] = null;
            // $mData['loss_day'] = $cInfoY['loss_day'];
            $mData['loss_day'] = null;
            $logNewInfo .='流失状态：空；';
        }
        if($cInfoM['erp_loss'] == 2){
            $mData['erp_loss'] = 1;
            $mData['erp_loss_reason'] = null;
            $mData['erp_loss_time'] = null;
            $logNewInfo .='流失状态：空；';
        }

        //进店判断
        if($cInfoM['is_intostore'] == 1 || $cInfoM['is_intostore'] == 4){
            //新客资未进店，
            if($cInfoY['is_intostore'] != 1 && $cInfoY['is_intostore'] != 4){
                //老客资进过店的，以老客资为准
                $mData['is_intostore'] = $cInfoY['is_intostore']?$cInfoY['is_intostore']:2;
                $mData['syjd_day'] = $cInfoY['syjd_day']?$cInfoY['syjd_day']:$order['target_time'];
                $logNewInfo .='进店状态：'.getIsIntostore($mData['is_intostore']).'；进店时间：'.$mData['syjd_day'].'；';
            }
        }else{
            //新客资有过进店
            if($cInfoY['is_intostore'] != 1 && $cInfoY['is_intostore'] != 4){
                //老客资也进过店的，要看新客资的实际进店，是否比订单还晚，要是晚的话，就更新成订单时间
                //但这种情况有可能是新的客资的实际进店时间与进客里不相符
                if(strtotime($cInfoM['syjd_day']) > strtotime($order['target_time'])){
                    if($orderIntostore['syjd_day']){
                        $mData['syjd_day'] = $orderIntostore['syjd_day'];
                    }else{
                        $mData['syjd_day'] = $order['target_time'];
                    }
                }
                $mData['is_intostore'] = 2;
                $logNewInfo .='进店状态：'.getIsIntostore($mData['is_intostore']).'；进店时间：'.$mData['syjd_day'].'；';
            }
        }


        /*
        if(empty($cInfoM['syjd_day'])){
            $mData['syjd_day']              = $cInfoY['syjd_day'];
            // $iData['syjd_day']              = $cInfoY['syjd_day'];
        }elseif($cInfoM['syjd_day']>$cInfoY['syjd_day']){
            $mData['syjd_day']              = $cInfoY['syjd_day'];
            // $iData['syjd_day']              = $cInfoY['syjd_day'];
        }
        if(empty($cInfoM['yjd_day'])){
            $mData['yjd_day']              = $cInfoY['yjd_day'];
            // $iData['yjd_day']              = $cInfoY['yjd_day'];
        }
        if($cInfoY['order_type'] == 1){
            $intostore = getPercent($cInfoY['fact_money'],$cInfoY['totalpay_money'],session('brandclass_id'),'into');
            if($intostore){
                $mData['is_intostore'] = 2;
                $iData['is_intostore'] = 2;
                if(empty($cInfoM['syjd_day'])){
                    $mData['syjd_day']              = $cInfoY['order_day'];
                    $iData['syjd_day']              = $cInfoY['order_day'];
                }
                $mData['is_intostore']   = 1;
                $iData['is_intostore']   = 1;
            }
        }else{
            $mData['is_intostore'] = 2;
            $iData['is_intostore'] = 2;
        }
        //*/
        //成单判断

        if($order['order_valid'] == 2){
            //有效单
            $mData['is_success']            = 1;
            $mData['order_day']      = $order['valid_time'];
            $logNewInfo .='客资成单状态：'.getIsSuccess($mData['is_success']).'；成交时间：'.$mData['order_day'].'；';
        }else{
            $mData['is_success']            = 3;
            $logNewInfo .='客资成单状态：'.getIsSuccess($mData['is_success']).'；';
        }

        /*
        $success = getPercent($cInfoY['fact_money'],$cInfoY['totalpay_money'],session('brandclass_id'),'order');

        if($success){
            $mData['is_success']            = 1;
            $iData['is_success']            = 1;
            $mData['order_day']      = $cInfoY['order_day'];
        }else{
            $mData['is_success']            = 3;
            $iData['is_success']            = 3;
        }
        */

        $mData['order_start_time']      = $order['target_time'];
        $mData['order_type']            = $order['order_type'];//1线上，2线下
        $mData['order_number']          = $order['order_sn'];
        $mData['fact_money']            = $cInfoY['fact_money'];
        $mData['totalpay_money']        = $cInfoY['totalpay_money'];
        $logNewInfo .= "订单开始时间：{$mData['order_start_time']}；订单类型：".getOrderTypeText($mData['order_type'])."；订单号：{$mData['order_number']}；订单实收：{$mData['fact_money']}；订单套系：{$mData['totalpay_money']}；";
        if($cInfoY['order_newclass'] != $cInfoM['order_newclass']){
            $mData['order_newclass']        = $cInfoY['order_newclass'];//消费子类型
            $logNewInfo .= "消费子类型：{$mData['order_newclass']}；";
        }
        /*
        $mData['order_start_time']      = $cInfoY['order_start_time'];
        $mData['order_day']             = $cInfoY['order_day'];
        $mData['order_type']            = $cInfoY['order_type'];
        $mData['order_number']          = $cInfoY['order_number'];
        $mData['fact_money']            = $cInfoY['fact_money'];
        $mData['totalpay_money']        = $cInfoY['totalpay_money'];
        $mData['order_newclass']        = $cInfoY['order_newclass'];
        //*/

        // 目标客资订单数据
        $mOData['customer_id']           = $cInfoM['id'];
        $mOData['customer_name']         = $cInfoM['customer_name'];
        $mOData['customer_channel']      = $cInfoM['customer_channel'];
        $mOData['customer_channel_id']   = $cInfoM['customer_channel_id'];

        //$mOData['order_type']            = $cInfoM['order_type'];

        $mOData['customer_orderaddress'] = $cInfoM['customer_orderaddress'];
        if($cInfoY['shop_code'] != $cInfoM['shop_code']){
            //* 订单对应的网销店
            $mOData['shop_code']             = $cInfoM['shop_code'];
            $mOData['shop_name']             = $cInfoM['shop_name'];
            $logNewInfo .= '订单网销店：'.$mOData['shop_name'];
        }

        //*/
        db()->startTrans();
        try {
            // 清除目标数据中的当天进客信息
            if($isTable && $data['customerId'] && $order['into_id']){
                $yjdDay = date('Y-m-d',strtotime($orderIntostore['yjd_day']));
                $mInto = db('crm_c_customer_intostore')
                    ->where('status',1)
                    ->where('cid',$data['customerId'])
                    ->where('yjd_day','like','%'.$yjdDay.'%')
                    ->find();
                if($mInto){
                    db('crm_c_customer_intostore')->where('id',$mInto['id'])->update(['status'=>99]);
                }
                if($order['into_id']){
                    $iData['cid'] = $cInfoM['id'];
                    db('crm_c_customer_intostore')->where('id',$order['into_id'])->update($iData);
                }
                //目标客资    原订单客资预约日期之后的所有进客改为回门
                db('crm_c_customer_intostore')
                    ->where('cid',$cInfoM['id'])
                    ->where('yjd_day','>',$orderIntostore['yjd_day'])
                    ->where('is_intostore','in',[2,3,5])
                    ->where(' status <> 99 ')
                    ->update(['reback'=>2]);
            }

            // 清除原数据中的订单信息
            db('crm_c_customerinfo')->where('id',$cInfoY['id'])->update($yData);
            // 更新目标客资数据
            db('crm_c_customerinfo')->where('id',$cInfoM['id'])->update($mData);

            // 更新或新添目标客资订单数据
            db('crm_c_customer_order')->where('customer_id',$cInfoY['id'])->where('order_sn', trim($data['orderSn']))->update($mOData);

            $logNewInfo = '订单转移：原客资信息：'.$cInfoY['id'].'；'.$logNewInfo;
            action_log($logNewInfo,$mData,$data['customerId'],session('staff_id'),session('staff_name'));
            $logOldInfo = '订单转移 ：'.$order['order_sn'].'==>'.'客资ID：'.$data['customerId'];
            if($order['into_id']){
                $logOldInfo .= ';进客ID：'.$order['into_id'] ;
            }
            action_log($logOldInfo,'',$cInfoY['id'],session('staff_id'),session('staff_name'));
            unset($logNewInfo,$logOldInfo);
            // 调erp接口跟新ERP订单信息
            $is_erp = is_install('sx_erp');
            if ($is_erp) {
                $erp = config('ext.app_config');
                $addr = $erp['sx_erp']['addr'];
                $url =  $addr.'SX_CrmApi/Set_Order_Cssname?Token=^******^&orderId='.trim($data['orderSn']);
                // 调erp接口，修改信息
                $erpData['Cssname'] = $cInfoM['customer_cource'];
                $erpData['Customer_channel'] = $cInfoM['customer_channel'];
                $erpData['Storeconsuitant2'] = $cInfoM['sales_staff'];
                $erpData['Customer_from_index'] = $cInfoM['customer_number'];
                $erpData = json_encode($erpData);
                $response = requestERP($url, $erpData);
                if ($response['Code'] != 200) {
                    db()->rollback();
                    return array('code'=>102,'msg'=>'erp接口(Set_Order_Cssname)调用失败，请重试。','error'=>json_encode($response));
                }
            }
            db()->commit();
            return array('code'=>200,'msg'=>'订单转移成功');
        } catch (\Exception $e) {
            db()->rollback();
            return array('code'=>103,'msg'=>'订单转移，操作失败','error'=>$e->getMessage());
        }
    }
    // 订单转移 查询订单
    public function mergeSearchOrder(){
        $result['code'] = 0;
        $result['msg']  = '';
        $data = input();
        $order_sn = trim($data['orderSn']);
        $info = [];
        if (!$order_sn) {
            $result['count'] = 0;
            $result['data']  = array();
            return $result;
        }
        $is_erp = is_install('sx_erp');
        $brandId =session('brandclass_id');

        //先从客资的订单表里查订单，如果查不到订单，且对接了ERP的，则从ERP表里查数据，
        $info = db('crm_c_customer_order o')
            ->join('crm_c_customerinfo c','c.id = o.customer_id','left')
            ->where('o.order_sn', $order_sn)
            ->where('o.is_delete',2)
            ->field('o.id,o.customer_id,o.order_status,o.order_valid,o.order_sn,(ifnull(o.earnest_money,0)+ifnull(o.order_fact,0)) as order_fact,o.order_amount,o.create_time,o.shop_name,o.shop_code,o.order_type,o.target_time,o.brandclass,o.brandclass_id,o.valid_time,c.customer_number,c.customer_name,c.customer_tel,c.mate_tel,c.dj_day,c.dj_staff,c.jr_day,c.sales_staff,c.customer_cource,o.customer_channel,c.is_valid,c.is_fp,c.add_shop_name,c.is_success')
            ->order('o.id desc')
            ->select();
        /*
        if(!$info && $is_erp){

            $shopType = session('shop_type');
            $startDate = '2010-01-01';
            $endDate = date('Y-m-d');

            $erp = config('ext.app_config')['sx_erp'];
            if(session('shop_type') == 2){
                $addr= $erp['addr_child'];
                $url = $addr?trim($addr,'/').'/SX_ChildCrmApi/Sel_CustomerOrderList?Token=^******^&CustomerType='.$shopType:'';
            }else{
                $addr= $erp['addr'];
                $url = $addr?trim($addr,'/').'/SX_CrmApi/Sel_CustomerOrderList?Token=^******^&CustomerType='.$shopType:'';
            }
            if($url){
                $url = $url.'&orderinfo='.$order_sn.'&brandid='.$brandId.'&startdate='.$startDate.'&enddate='.$endDate;
                $dataErp = '[]';
                $response = requestERP($url, $dataErp);
                if($response['Code'] == 200) {
                    $numbers = [];
                    foreach ($response['Data'] as $k => $v) {//取出客资编号组成数组
                        array_push($numbers, $v['customer_from_index']);
                    }
                    //查询符合的所有客资
                    $info = $response['Data'];
                }
            }
        }
        //*/
        //如果客资的订单表查到了，但没关联到客资表，则页面上要显示客资未关联，则订单有效性需要重算。

        foreach($info as $k=>$v){
            $info[$k]['order_fact'] = sprintf('%.2f',$v['order_fact']);
            $info[$k]['order_amount'] = sprintf('%.2f',$v['order_amount']);
            $info[$k]['is_valid'] = getIsValidAttr($v['is_valid']);
            $info[$k]['is_fp'] = getIsFP($v['is_fp']);
            $info[$k]['is_success'] = getIsSuccess($v['is_success']);
            if(!$v['customer_number']){
                $info[$k]['is_fp'] = '-';
                $info[$k]['is_valid'] = '-';
                $info[$k]['is_success'] = '-';
                $info[$k]['customer_number'] = '-';
                $info[$k]['customer_name'] = '-';
                $info[$k]['customer_tel'] = '-';
                $info[$k]['mate_tel'] = '-';
                $info[$k]['dj_staff'] = '-';
                $info[$k]['sales_staff'] = '-';
                $info[$k]['customer_cource'] = '-';
                $info[$k]['add_shop_name'] = '-';
            }
            // $info[$k]['customer_cource'] = $v['customer_cource'];
        }

        if(count($info)>0){
            $result['data'] = $info;
            $result['count'] = count($info);
        }else{
            $result['data'] = array();
        }

        return json($result);
    }
    // 订单转移 查询客资
    public function mergeSearchCustomer(){
        $data = input();
        $result['code'] = 0;
        $result['msg']  = '';
        if (!$data['customerTel']) {
            $result['count'] = 0;
            $result['data']  = array();
            return $result;
        }

        $sql = ' customer_tel="'.trim($data['customerTel']).'" OR mate_tel="'.trim($data['customerTel']).'" ';
        $info = db('crm_c_customerinfo')
            ->where($sql)
            ->where('is_status',1)
            ->where('brandclass_id',session('brandclass_id'))
            ->field('id,customer_number,customer_name,customer_tel,mate_tel,dj_day,dj_staff,jr_day,sales_staff,customer_cource,customer_channel,order_start_time,order_day,order_number,fact_money,totalpay_money,sales_staff,is_valid,is_fp,yjd_action_day,yjd_day,syjd_day,is_success,add_shop_name,shop_name')
            ->select();


        foreach($info as $k=>$v){
            $info[$k]['fact_money'] = sprintf('%.2f',$v['fact_money']);
            $info[$k]['totalpay_money'] = sprintf('%.2f',$v['totalpay_money']);
            $info[$k]['is_valid'] = getIsValidAttr($v['is_valid']);
            $info[$k]['is_fp'] = getIsFP($v['is_fp']);
            $info[$k]['is_success'] = getIsSuccess($v['is_success']);
            $info[$k]['customer_cource'] = $v['customer_cource'];
        }

        if(count($info)>0){
            $result['data'] = $info;
            $result['count'] = count($info);
        }else{
            $result['data'] = array();
        }

        return json($result);
    }
    public function customerMergeShow(){
        $data = input();
        $where = [];
        if($data['tel']){
            $where['customer_tel'] = trim($data['tel']);
        }
        if($data['qq']){
            $where['customer_qq'] = trim($data['qq']);
        }
        if($data['wx']){
            $where['customer_wechat'] = trim($data['wx']);
        }
        if($data['order_sn']){
            $where['order_number'] = trim($data['order_sn']);
        }
        $info = db('crm_c_customerinfo')
            ->where($where)
            ->where('brandclass_id',session('brandclass_id'))
            ->where('is_status',1)
            ->field('id,customer_name,customer_tel,mate_tel,customer_wechat,customer_qq,dj_staff_id,dj_staff,sales_staff_id,sales_staff,is_valid,is_intostore,is_success,customer_type')
            ->select();
        // print_r(db()->getLastSql());die;
        if(count($info)>1){
            $this->assign('info',$info);
        }
        return $this->fetch();
    }
    public function customerMergeSearch(){
        $data = input();
        $result['code'] = 0;
        $result['msg'] = '';
        $where = [];
        if($data['tel']){
            $where['customer_tel'] = trim($data['tel']);
        }
        if($data['qq']){
            $where['customer_qq'] = trim($data['qq']);
        }
        if($data['wx']){
            $where['customer_wechat'] = trim($data['wx']);
        }
        if($data['order_sn']){
            $where['order_number'] = trim($data['order_sn']);
        }
        $info = db('crm_c_customerinfo')
            ->where($where)
            ->where('brandclass_id',session('brandclass_id'))
            ->where('is_status',1)
            ->select();
        foreach($info as $k=>$v){
            $info[$k]['customer_type'] = $v['customer_type'] == 1 ? '新客资' : '转介绍';
            $info[$k]['is_valid'] = getIsValidAttr($v['is_valid']);
            $info[$k]['is_intostore'] = getIsIntostore($v['is_intostore']);
            $info[$k]['is_fp'] = getIsFP($v['is_fp']);
            $info[$k]['is_success'] = getIsSuccess($v['is_success']);
            $info[$k]['introducer_type'] = getIntroducerType($v['introducer_type']);
        }
        if(count($info)>1){
            $result['data'] = $info;
            $result['count'] = count($info);
        }else{
            $result['data'] = array();
        }
        return json($result);
    }
    public function check_customer(){
        $data = input();
        $id = $data['id'] ? (int)$data['id'] : 0;
        $channel = $data['customer_channel'] ? trim($data['customer_channel']) : '';
        $orz = [
            'add_shop_code'=> $data['add_shop_code'] ? $data['add_shop_code'] : session('shop_code'),
            'shop_code'    => $data['shop_code'] ? $data['shop_code'] : session('shop_code'),
            'brandclass'   => $data['brandclass'] ? $data['brandclass'] : session('brandclass'),
        ];
        // 联系方式
        $con = [
            'customer_tel'   => $data['customer_tel'] ? $data['customer_tel'] : '',
            'customer_wechat'=> $data['customer_wechat'] ? $data['customer_wechat'] : '',
            'customer_qq'   => $data['customer_qq'] ? $data['customer_qq'] : '',
            'mate_tel'   => $data['mate_tel'] ? $data['mate_tel'] : '',
            'consultation_type_id'=> $data['consultation_type_id'] ? $data['consultation_type_id'] : '',
        ];
        $repeat_way = db_config('customer_repeat_method');
        $repeat_way = $repeat_way?$repeat_way:config('repeat_way');
        // $repeat_way = config('repeat_way');
        if ($repeat_way == 'xaf') {
            $baby_time = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>'baby_time'));
            if ($baby_time) {
                $other['baby_time'] = $data['baby_time'] ? $data['baby_time'] : '';
            }
        }else if ($repeat_way == '6j1') {
            $other['channel'] = $channel;
        }else{
            $other['channel'] = $channel;
        }
        // var_dump($other);die;
        $res = controller('crm/Customer','lib')->isRepeat($orz,$con,$other,0);
        // var_dump($res);die;
        if($res['code'] == 200) {
            $tact = db('crm_c_customer_contact')->where('contact', $contact)->where('brandclass', '<>', session('brandclass'))->order('c_id desc')->find();
            //客资过期录入是否提示设定
            $cus_repeat_notice = db_config('cus_repeat_notice');
            if ($tact) {
                if ($cus_repeat_notice) {
                    return array('code' => 201, 'msg' => '该联系方式与ID为【' . $tact['c_id'] . '】,【' . $tact['brandclass'] . '】的客资重复!');
                }
            }
            return array('code'=>200,'msg'=>$res['msg'],'sql'=>$res['sql']);
        }
        if($res['code'] != 201) {
            return array('code'=>200,'msg'=>$res['msg'],'sql'=>$res['sql']);
        }
        $repeatEdit = config('repeat_edit_shop');
        if($rep['code'] == 201 && in_array($data['add_shop_code'], $repeatEdit)){
                return ['code'=>200,'msg'=>'在repeat_edit_shop配置内的店，不提示重复，直接更新旧客资。'];
        }

        // 20191217
        $arr = $res['data'];
        $msg  = "您 录入的客资信息重复，已存在的客资信息如下：<br/>";
        $msg .= '客资提报人：' . $arr['dj_staff'] . '<br/>';
        $msg .= '客资提报人所属店面：' . $arr['add_shop_name'] . '<br/>';
        $msg .= '客资ID：'.$arr['id'].'<br/>';
        $msg .= '客资姓名：'.$arr['customer_name'].'<br/>';
        if($arr['customer_tel']){
            $msg .= '手机号：'.$arr['customer_tel'].'<br/>';
        }
        if($arr['customer_wechat']){
            $msg .= '微信：'.$arr['customer_wechat'].'<br/>';
        }
        if($arr['customer_qq']){
            $msg .= 'QQ：'.$arr['customer_qq'].'<br/>';
        }
        $msg .= '渠道名称 ：'.$arr['customer_channel'].'<br/>';
        $msg .= '客资录入时间：' . $arr['dj_day'] . '<br/>';
        if ($arr['sales_staff']) {
            $msg .= '追踪状态：' . $sal . '<br/>';
            $msg .= '追踪人：' . ($arr['sales_staff']) . '<br/>';
            $msg .= '请核对信息后再录入';
            $returnData = array('code' => 201, 'msg' => $msg,'repeat'=>$res);
        } else {
            $msg .= '是否分配：' . getIsFP($arr['is_fp']) . '<br/>';
            $msg .= '请核对信息后再录入';
            $returnData = array('code' => 201, 'msg' => $msg,'repeat'=>$res);
        }
        return $returnData;
    }
    //丧失焦点客资重复验证
    public function check_customer_rename(){
        $data = input();
        $contact = trim($data['contact']);
        //判断 mc客资有效期配置 为空的话 不限制
        if (session('valid_date') === null) {
            return array('code'=>200,'msg'=>'mc客资有效期配置 为空 不限制');
        }
        $sql = '1=1';
        if($data['id']){
            $sql .= ' and id <> '.intval($data['id']);
        }
        $ktact = db('crm_c_customer_contact')->where('contact',$contact)->order('c_id desc')->find();
     
        if(empty($ktact)){
            return array('code'=>200,'msg'=>'客资未重复，可以录入');
        }else{
            if($data['id']){
                $customerinfo_res = db('crm_c_customerinfo')->field('consultation_type_id')->where('id',$data['id'])->where('customer_tel|customer_wechat|customer_qq|mate_tel','in',$contact)->find();
                if ($customerinfo_res) {
                    return array('code'=>200,'msg'=>'客资本身，可以录入','data'=>'');
                }
            }
            //判断 不同资讯类型的客资，是否可以重复 
            if (db_config('cus_validdate_'.session('shop_code')) == 1 && $data['consultation_type'] > 0 && $customerinfo_res['consultation_type_id'] != $data['consultation_type']) {
                $ros = db('crm_c_customerinfo')->field('id,customer_tel,consultation_type')->where('customer_tel|customer_wechat|customer_qq|mate_tel',$contact)->where('consultation_type_id',$data['consultation_type'])->where($sql)->find();
                if ($ros) {
                    return array('code'=>201,'msg'=>"客资有重复",'data'=>$ros);
                }else{
                    return array('code'=>200,'msg'=>"设置了 不同资讯类型的客资，可以重复",'data'=>[]);
                }
            }   
            //取排重范围状态
            $unrepeatStatus = db_config('unrepeat_status');
            if($unrepeatStatus){
                $unrepeatStatus = explode(',', $unrepeatStatus);
            }else{
                $unrepeatStatus = [];
            }
            $whereRepeat = [];
            if(in_array('unvalid', $unrepeatStatus)){
                $whereRepeat['is_valid'] = ['<>',3];
            }
            if(in_array('lossed', $unrepeatStatus)){
                $whereRepeat['is_loss'] = 2;
            }
            
            //如果有重复,查看是不是事业部内重复
            $tact = db('crm_c_customer_contact')->where('contact',$contact)->where($sql)->where('brandclass',session('brandclass'))->order('c_id desc')->find();
            //客资过期录入是否提示设定
            $cus_repeat_notice = db_config('cus_repeat_notice');
            if(empty($tact)){
                if($cus_repeat_notice){
                    return array('code'=>201,'msg'=>'该联系方式与ID为【'.$ktact['c_id'].'】,【'.$ktact['brandclass'].'】的客资重复!');
                }
            }else{
                if(empty($tact['c_id'])&&$cus_repeat_notice){
                    return array('code'=>201,'msg'=>'客资有重复，但未找到客资编号','data'=>[]);
                }
                if($data['id'] != $tact['c_id']){
                    //查看是否已订单或过期
                    $info = db('crm_c_customerinfo')->where('id',$tact['c_id'])->find();
                    $valid = $info['is_valid'];
                    $loss = $info['is_loss'];
                    if($info['is_success'] == 1 && $cus_repeat_notice){
                        return array('code'=>201,'msg'=>'该联系方式与ID为【'.$ktact['c_id'].'】的客资重复,该客资已订单!');
                    }else{
                        //客资过期时间
                        $key = 'brand_valid_date_'.md5(session('brandclass'));
                        $valid_date = cache('?'.$key);
                        if(!$valid_date){
                            // $info = sx_call('5a3bbb5d0988d',['brandclass'=>session('brandclass')]);
                            $mc = new \app\common\lib\mcInterface();
                            $info = $mc->getBrand(['brandclass'=>session('brandclass')]);
                            if($info !== false){
                                $valid_date = $info[0]['valid_date'];
                                cache($key,$valid_date,1800);
                            }else{
                                $valid_date = 60;
                            }
                        }else{
                            $valid_date = cache($key);
                        }
                        if($valid_date == 0){//为0,则永不过期
                            if(in_array('unvalid', $unrepeatStatus) && $valid == 3){
                                return array('code'=>200,'msg'=>'已设置无效客资可录入');
                            }
                            if(in_array('lossed', $unrepeatStatus) && $loss == 1){
                                return array('code'=>200,'msg'=>'已设置不再追踪可录入');
                            }
                            return array('code'=>201,'msg'=>'已设置为永不过期,不可录入');
                        }
                        //客资过期判定规则
                        $rule = db_config('valid_date_rule');
                        $rule = $rule ? $rule : 'dj_day';
                        $lastDate = date('Y-m-d H:i:s',time() - ($valid_date * 86400));
                        $where = ' '.$rule.' is null or '.$rule.' > \''.$lastDate.'\'';
                        $arr= db("c_customerinfo")
                            ->field('id,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_name,customer_number,mate_tel,dj_day,add_shop_name,dj_staff,sales_staff,shop_name,is_success,is_fp,is_valid,is_intostore,c_star_day')->where('id','in',$tact['c_id'])->where('is_status',1)->where($where)->where('is_success','<>',1)->where($whereRepeat)->master()->order('id desc')->find();
                        if($arr){
                            return array('code'=>201,'msg'=>'与该联系方式重复的客资未过期,不能录入','data'=>$arr);
                        }else{
                            $valid_date_notice = db_config('valid_date_notice');
                                if($valid_date_notice && $cus_repeat_notice){ //客资过期是否提示
                                    return array('code'=>201,'msg'=>'与该联系方式重复的客资已过期,可以录入');
                                }else{
                                    return array('code'=>200,'msg'=>'与该联系方式重复的客资已过期,可以录入');
                                }
                        }
                    }
                }else{
                    return array('code'=>200,'msg'=>'修改客资时联系方式未重复');
                }
            }
        }
    }
    //联系方式验证  20191111
    public function isRepeat(){
        $data = input();
        $id = $data['id'] ? intval($data['id']) : 0;
        $tel = $data['tel'] ? trim($data['tel']) : null;
        $qq = $data['qq'] ? trim($data['qq']) : null;
        $wechat= $data['wx'] ? trim($data['wx']) : null;

        $mate_tel   = $data['mate_tel'] ? trim($data['mate_tel']) : null;
        $mate_wechat= $data['mate_wechat'] ? trim($data['mate_wechat']) : null;

        // $mate_tel = $data['mate_tel'] ? trim($data['mate_tel']) : null;
        $baby_time = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>'baby_time'));
        $column = 'id,customer_tel,customer_wechat,mate_tel,mate_wechat,customer_type,customer_channel,add_shop_code,add_shop_name,shop_code,shop_name,brandclass';
        $baby_time = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>'baby_time'));
        if ($baby_time) {
            $column .= ',baby_time';
        }
        $cInfo = db('crm_c_customerinfo')->where('id',$id)->field($column)->find();

        // 如果是转介绍客资
        if ($cInfo['customer_type'] == 2) {
            $customer_channel = '';
        }else{
            $customer_channel = $cInfo['customer_channel'];
        }
        // 组织结构
        $orz = [
            'add_shop_code'=> $cInfo['add_shop_code'],
            'shop_code'    => $cInfo['shop_code'],
            'brandclass'   => $cInfo['brandclass'],
        ];
        // 联系方式
        $con = [
            'customer_tel'   => $tel,
            'customer_wechat'=> $wechat,
            'mate_tel'       => $cInfo['mate_tel'],
            'mate_wechat'    => $cInfo['mate_wechat'],
            'qq'=> $qq,
            'consultation_type_id' => $data['consultation_type'],
        ];
        // 其他排重条件
        $other['channel'] = $customer_channel;
        
        if ($baby_time) {
            $other['baby_time'] = $cInfo['baby_time'];
        }

        $repRes = controller("crm/Customer", "lib")->isRepeat($orz, $con, $other, $id);
        if ($repRes['code']==201) {
            $arr = $repRes['data'];
            if ($arr['sales_staff']) {
                $msg .= '客资提报人：' . $arr['dj_staff'] . '<br/>';
                $msg .= '客资提报人所属店面：' . $arr['add_shop_name'] . '<br/>';
                $msg .= '客资ID：'.$arr['id'].'<br/>';
                $msg .= '客资姓名：'.$arr['customer_name'].'<br/>';
                if($arr['customer_tel']){
                    $msg .= '手机号：'.$arr['customer_tel'].'<br/>';
                }
                if($arr['customer_wechat']){
                    $msg .= '微信：'.$arr['customer_wechat'].'<br/>';
                }
                if($arr['customer_qq']){
                    $msg .= 'QQ：'.$arr['customer_qq'].'<br/>';
                }

                //$msg .= '客资当前状态：'.getIsValidAttr($arr['is_valid']).'<br/>';
                $sal = $arr['is_loss']==1 ? '不再追踪' : ($arr['c_star_day'] ? '追踪中' : '待追踪');
                //$msg .= '是否分配：'.getIsFP($arr['is_fp']).'<br/>';
                $msg .= '追踪状态：' . $sal . '<br/>';
                $msg .= '追踪人：' . ($arr['sales_staff']) . '<br/>';
                $msg .= '是否进店：' . getIsIntostore($arr['is_fp']) . '<br/>';
                $msg .= '是否成交：' . getIsSuccess($arr['is_success']) . '<br/>';
                $msg .= '客资录入时间：' . $arr['dj_day'] . '<br/>';
                $msg .= '请核对信息后再录入';
            }else{
                $msg .= '客资提报人：' . $arr['dj_staff'] . '<br/>';
                $msg .= '客资提报人所属店面：' . $arr['add_shop_name'] . '<br/>';
                $msg .= '客资ID：'.$arr['id'].'<br/>';
                $msg .= '客资姓名：'.$arr['customer_name'].'<br/>';
                if($arr['customer_tel']){
                    $msg .= '手机号：'.$arr['customer_tel'].'<br/>';
                }
                if($arr['customer_wechat']){
                    $msg .= '微信：'.$arr['customer_wechat'].'<br/>';
                }
                if($arr['customer_qq']){
                    $msg .= 'QQ：'.$arr['customer_qq'].'<br/>';
                }
                $msg .= '渠道名称 ：'.$arr['customer_channel'].'<br/>';
                $msg .= '是否分配：' . getIsFP($arr['is_fp']) . '<br/>';
                $msg .= '是否进店：' . getIsIntostore($arr['is_fp']) . '<br/>';
                $msg .= '是否成交：' . getIsSuccess($arr['is_success']) . '<br/>';
                $msg .= '客资录入时间：' . $arr['dj_day'] . '<br/>';
                $msg .= '请核对信息后再录入';
            }
            return array('code' => 201, 'msg' => $msg);
        }
        return $repRes;
    }
    //追踪打开时检测客资重复 标准版用了，儿童版没用上
    public function dianfang_check_customer(){
        $id = input('id');
        if(empty($id)){
            return array('code'=>101,'msg'=>'未获取到客资ID');
        }
        $info = db('crm_c_customerinfo')->where('id',$id)->field('customer_tel,customer_wechat,mate_tel,mate_wechat')->select();
        $arr = [];
        foreach($info as $kk=>$vv){
            if($vv['customer_tel']){
                $arr[] = $vv['customer_tel'];
            }
            if($vv['customer_wechat']){
                $arr[] = $vv['customer_wechat'];
            }
            if($vv['mate_tel']){
                $arr[] = $vv['mate_tel'];
            }
            if($vv['mate_wechat']){
                $arr[] = $vv['mate_wechat'];
            }
        }
        //判断 mc客资有效期配置 为空的话 不限制
        if (session('valid_date') === null) {
            return array('code'=>200,'msg'=>'mc客资有效期配置 为空 不限制');
        }
        //取排重范围状态
        $unrepeatStatus = db_config('unrepeat_status'); 

        if($unrepeatStatus){
            $unrepeatStatus = explode(',', $unrepeatStatus);
        }else{
            $unrepeatStatus = [];
        }
        $whereRepeat = [];
        if(in_array('unvalid', $unrepeatStatus)){
            $whereRepeat['is_valid'] = ['<>',3];
        }
        if(in_array('lossed', $unrepeatStatus)){
            $whereRepeat['is_loss'] = 2;
        }


        $sql = ' 1=1 ';
        //客资过期时间
        $key = 'brand_valid_date_'.md5(session('brandclass_id'));
        $valid_date = cache('?'.$key);
        if(!$valid_date){
            // $info = sx_call('5a3bbb5d0988d',['brandclass'=>session('brandclass_id')]);
            $mc = new \app\common\lib\mcInterface();
            $info = $mc->getBrand(['brandclass'=>session('brandclass')]);
            if($info !== false){
                $valid_date = $info[0]['valid_date'];
                cache($key,$valid_date,1800);
            }else{
                $valid_date = 60;
            }
        }else{
            $valid_date = cache($key);
        }
        $lastDate = date('Y-m-d H:i:s',time() - ($valid_date * 86400));
        //客资过期判定规则
        $rule = db_config('valid_date_rule');
        $rule = $rule ? $rule : 'dj_day';
        $where = ' '.$rule.' is null or '.$rule.' > \''.$lastDate.'\'';
        $res = db('crm_c_customer_contact')->where('c_id','<>',$id)->where('contact','in',$arr)->select();
        if($res){
            $info1 = db('crm_c_customerinfo')->where('id','in',array_column($res,'c_id'))->where($where)->where('is_success','<>',1)->where($whereRepeat)->field('id,is_status,is_valid,is_loss,sales_staff,dj_staff')->select();
            $msg = '';
            foreach($info1 as $k=>$v){
                if($v['is_status'] == 2){
                    unset($info1[$k]);
                }else{
                    $msg .= '与ID为'.$v['id'];
                    if($v['dj_staff']){
                        $msg .= ' 登记人：'.$v['sales_staff'] .' ';
                    }
                    if($v['sales_staff']){
                        $msg .= ' 追踪人：'.$v['sales_staff'] .' ';
                    }
                }
            }
            if($info1){
                return array('code'=>102,'msg'=>$msg.' 的客资重复');
            }else{
                return array('code'=>200,'msg'=>'');
            }
        }else{
            return array('code'=>200,'msg'=>'');
        }
    }
    //捞客资
    public function customerBySalf(){
        return $this->fetch();
    }
    public function customerBySalfJSON(){
        $param = input();
        $result = [];
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 15;
        $where['is_status'] = 1;
        $where['is_examine'] = 1;
        if(session('is_sk')){
            $where['is_already_sk'] = 1;
        }
        $info = db('crm_c_customerinfo')->where('shop_code',session('shop_code'))->where('is_fp','in',[2,4])->where($where)->field('id,customer_name,customer_tel,customer_qq,customer_wechat,mate_tel,customer_channel,access_model,consultation_type,dj_day,dj_staff,is_fp')->order('id desc')->page($page)->limit($limit)->select();
        $count = db('crm_c_customerinfo')->where('shop_code',session('shop_code'))->where('is_fp','in',[2,4])->where($where)->count('id');

        if(!empty($info)){
            $result['data'] = $info;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return json($result);
    }
    //手机端设置个人离线是否分配  和系统配置的离线是否分配一块使用
    /*
     *     全局开关    个人开关  ---状态---
     *        开          关       分配
     *        开          开       分配
     *        关          开       分配
     *        关          关      不分配
     * */
    public function setNotOnlineIsFP(){
        $data = input();
        $res3 = db_config('not_online_is_fp_'.session('staff_id'),$data['not_online_is_fp']);
        if($res3 === false){
            return false;
        }else{
            action_log($data,[],0,session('staff_id'),session('staff_name'));
            return true;
        }
    }
    //获取可用短信模板
    public function getSmsModel(){
        $res = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('status',1)->field('id,mtemplate_name')->select();
        if(empty($res)){
            return array('code'=>100,'msg'=>'暂未设置短信模板','data'=>'');
        }
        return array('code'=>200,'msg'=>'','data'=>$res);
    }
    //客资录入时的所属店;没有归属店则查crm设置的归属店,还没有归属店则是自己
    public function getBelongShop(){
        $data = input();
        if(!$data['shop_code']){
            $data['shop_code'] = session('shop_code');
        }
        $shopList = getBelongShopList($data['shop_code'],$data['customer_type']);
        if(empty($shopList)){
            $shopList = array(['shop_code'=>$data['shop_code'],'shop_name'=>$data['shop_name']]);
        }
        return $shopList;

        /*
        if($data['customer_type'] == 2){
            //转介绍，取所有是专介绍接收店的店面。
            $mc = new mcInterface();
            $shop = $mc->getShopInfo(['is_dig'=>1]);
            //这里暂时不加事业部
            if(empty($shop)){
                $shop = array(['shop_code'=>$shop_code,'shop_name'=>$data['shop_name']]);
            }
        }else{
            //取指定店的客资提报归属店，看有没有，
            //如果没有，则取CRM设置内的提报归属店配置内进行配置
            //如果当前店已经在MC内设置了提报客资归属店了，则CRM内配置不可见
            $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$shop_code]);
            if(empty($shop[0]['belong_shop_code'])){
                $shop = db_config('dj_shops_'.$shop_code);
                if(empty($shop)){
                    $shop = array(['shop_code'=>$shop_code,'shop_name'=>$data['shop_name']]);
                }
            }else{
                $shop[0]['shop_code'] = $shop[0]['belong_shop_code'];
                $shop[0]['shop_name'] = $shop[0]['belong_shop_name'];
            }
        }

            
        return $shop;
        */
    }
    //客资审核
    public function customerExamine(){;
        $channel = controller('crm/Customer','lib')->getChannel();
        $this->assign('channel',$channel);
        $staff = controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>session('shop_code')]);
        $this->assign('staff',$staff);
        return $this->fetch();
    }
    public function customerExamineJSON(){
        $param = input();
        $result = [];
        $result['code'] = 0;
        $result['msg'] = '';
        $is_examine = [2,3];
        if($param['dj_staff_id']) $where['dj_staff_id'] = intval($param['dj_staff_id']);
        if($param['customer_channel_id']) $where['customer_channel_id'] = intval($param['customer_channel_id']);
        if($param['is_examine']) $is_examine = [intval($param['is_examine'])];
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 15;

        $info = db('crm_c_customerinfo')->where('shop_code|add_shop_code',session('shop_code'))->where('is_status',1)->field('id,customer_name,customer_tel,customer_qq,customer_wechat,mate_tel,customer_channel,access_model,consultation_type,dj_day,dj_staff,is_examine')->where('is_examine','in',$is_examine)->where($where)->order('dj_day desc')->page($page)->limit($limit)->select();
        $count = db('crm_c_customerinfo')->where($where)->where('is_examine','in',$is_examine)->where('shop_code|add_shop_code',session('shop_code'))->where('is_status',1)->count('id');

        if(!empty($info)){
            $result['data'] = $info;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return json($result);
    }
    //客资由待审核改为已通过
    public function customerIsExamine(){
        $cid = input('param.cid');
        db()->startTrans();
        try{
            db('crm_c_customerinfo')->where('id',$cid)->update(['is_examine'=>1]);
            db()->commit();
            action_log(['cid'=>$cid,'is_examine'=>1],[],$cid,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 customerNoExamine(){
        $data = input('param.');
        db()->startTrans();
        try{
            db('crm_c_customerinfo')->where('id',$data['cid'])->update(['is_examine'=>3,'examine_reason'=>$data['examine_reason']]);
            db()->commit();
            action_log(['cid'=>$data['cid'],'is_examine'=>3],[],$data['cid'],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 examine(){
        $id = input('param.cid');
        $info = db('crm_c_customerinfo')->where('id',$id)->find();
        $this->assign('info',$info);
        return $this->fetch();
    }

    //客资回收站
    public function customerBack(){
        //登记人
        $staff = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('shop_code')]);
        $this->assign('staff',$staff);
        //追踪人
        if(session('is_marketing') == 1){
            $sales = controller('crm/Customer','lib')->getShopAllStaff(['shop_code'=>session('belong_shop_code')]);
            $this->assign('sales',$sales);
        }else{
            $this->assign('sales',$staff);
        }
        return $this->fetch();
    }
    public function customerBackJSON(){

        $param = input();
        $result = [];
        $result['code'] = 0;
        $result['msg'] = '';
        $page = $param['page'] ? $param['page'] : 1;
        $limit = $param['limit'] ? $param['limit'] : 50;
        $sql = ' 1=1 ';
        if($param['customer_name']){
            $sql .= ' and customer_name like "%'.trim($param['customer_name']).'%" ';
        }
        if($param['dj_staff_id']){
            $sql .= ' and dj_staff_id='.intval($param['dj_staff_id']);
        }
        if($param['sales_staff_id']){
            $sql .= ' and sales_staff_id='.intval($param['sales_staff_id']);
        }
        if($param['id']){
            $sql .= ' and id ='.$param['id'];
        }
        if($param['customer_tel']){
            $sql .= ' and (customer_tel like "%'.trim($param['customer_tel']).'%" or customer_qq like "%'.trim($param['customer_tel']).'%" or customer_wechat like "%'.trim($param['customer_tel']).'%" or mate_tel like "%'.trim($param['customer_tel']).'%") ';
        }
        $start = $param['start'] ? $param['start'].' 00:00:00' : NULL;
        $end = $param['start'] ? $param['end'].' 23:59:59' : NULL;
        if($start && $end){
            $info = db('crm_c_customerinfo')
                ->where('shop_code|add_shop_code',session('shop_code'))
                ->where($sql)
                ->where('is_status',2)
                ->where('del_time','between',[$start,$end])
                ->field('id,customer_name,customer_tel,customer_qq,customer_wechat,mate_tel,customer_channel,access_model,consultation_type,dj_day,dj_staff,sales_staff,is_fp')
                ->order('del_time desc')
                ->page($page)->limit($limit)
                ->select();
            $where['del_time'] = ['between',[$start,$end]];
        }else{
            $info = db('crm_c_customerinfo')
                ->where('shop_code|add_shop_code',session('shop_code'))
                ->where($sql)
                ->where('is_status',2)
                ->field('id,customer_name,customer_tel,customer_qq,customer_wechat,mate_tel,customer_channel,access_model,consultation_type,dj_day,dj_staff,sales_staff,is_fp')
                ->order('del_time desc')
                ->page($page)->limit($limit)
                ->select();
        }

        $ids = array_column($info,'id');
        $log = db('crm_action_log','db_logs')->where('action','delcustomer')->where('customer_id','in',$ids)->column('staff_id,customer_id,staff_name','customer_id');
        foreach($info as $k=>$v){
            $info[$k]['staff_name'] = $log[$v['id']]['staff_name'];
        }
        $count = db('crm_c_customerinfo')
            ->where('shop_code|add_shop_code',session('shop_code'))
            ->where($sql)
            ->where('is_status',2)
            ->where($where)
            ->count('id');

        if(!empty($info)){
            $result['data'] = $info;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return json($result);
    }
    //客资由回收站恢复为正常客资 20181105
    public function customerRecove(){
        $cid = input('param.cid');
        //查询其联系方式
        $contact = db('crm_c_customerinfo')->where('id',$cid)->field('customer_tel,customer_qq,customer_wechat,mate_tel,mate_wechat,mate_qq')->find();

        $brandclass = db('crm_c_customerinfo')->where('id',$cid)->value('brandclass');
        $c_unique = db('crm_c_customerinfo')->where('id',$cid)->value('c_unique');
        $repeat_way = db_config('customer_repeat_method');
        $repeat_way = $repeat_way?$repeat_way:config('repeat_way');
        // $repeat_way = config('repeat_way');
        if ($repeat_way == 'xaf') {
            $customer_channel = db('crm_c_customerinfo')->where('id',$cid)->value('baby_time');
        }else if ($repeat_way == '6j1') {
            $customer_channel = db('crm_c_customerinfo')->where('id',$cid)->value('customer_channel');
        }else{
            //$customer_channel = db('crm_c_customerinfo')->where('id',$cid)->value('customer_channel');
            $customer_channel = '';
        }
        
        $contact = array_filter($contact);//去除空元素
        //查询排重表有无此联系方式
        $info = db('crm_c_customer_contact')->where('contact','in',$contact)->where('brandclass',$brandclass)->select();
        if(!empty($info)){
            return array('code'=>300,'msg'=>'已有此联系方式的客资,不能恢复','data'=>'');
        }
        db()->startTrans();
        try{
            $contactList = [];
            foreach($contact as $k => $v){
                $con['c_id']=$cid;
                $con['contact']=$v;
                $con['c_unique']=$c_unique;
                $con['brandclass']=$brandclass;
                $con['customer_channel']=$customer_channel;
                array_push($contactList,$con);
            }

            db('crm_c_customerinfo')->where('id',$cid)->update(['is_status'=>1]);
            db('crm_c_customer_contact')->insertAll($contactList);
            db()->commit();
            action_log(['is_status'=>1],['is_status'=>2],$cid,session('staff_id'),session('staff_name'));
            return array('code'=>200,'msg'=>'客资恢复成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'客资恢复失败','data'=>$e->getMessage());
        }
    }

    /*
     * 客资转移
     * 变更录入人  0609
     * */
    public function customerChange(){
        // 20200115
        $p = [
            'staff_id'=> session('staff_id'),
            'brandclass_id'=> session('brandclass_id'),
            'shop_type' => session('shop_type')
        ];
        $djshops = getShops($p);//可操作店
        $this->assign('djshops',$djshops);
        $dep = $this->getDepartmentList(array('shop_code'=>session('shop_code')));
        // $group = db('c_staff_group')->where('shop_code',session('shop_code'))->select();
        // $mc = new \app\common\lib\mcInterface();
        // $group = $mc->getGroupInfoByDid();
        $staff = controller('crm/Customer','lib')->get_staff_lists(array('shop_code'=>session('shop_code')));
        $this->assign('department',$dep);
        $this->assign('staff',$staff);
        return $this->fetch();
    }
    public function customerChangeSub(){
        $data = input();
        $sinfo = getStaffInfoById($data['dj_staff_id']);
        $param['dj_staff_id'] = intval($data['dj_staff_id']);
        $param['dj_staff'] = trim($data['dj_staff']) ? trim($data['dj_staff']) : $sinfo['staffname'];
        $param['dj_staff_number'] = $sinfo['staffnumber'];
        $param['dj_group_id'] = intval($data['dj_group_id']);
        $param['dj_group_name'] = trim($data['dj_group_name']);
        $param['dj_department_id'] = (int)$data['dj_department_id'];
        $param['dj_department_name'] = trim($data['dj_department_name']);
        $param['add_shop_code'] = trim($data['add_shop_code']);
        $param['add_shop_name'] = trim($data['add_shop_name']);
        if (!$param['add_shop_name'] || !$param['add_shop_code']) {
            return array('code'=>100,'msg'=>'请选择登记店面','data'=>$param['add_shop_code'].':'.$param['add_shop_name']);
        }
        if (!$param['dj_staff_id'] || !$param['dj_staff']) {
            return array('code'=>100,'msg'=>'请选择目标人员','data'=>$param['dj_staff_id'].':'.$param['dj_staff']);
        }
        $info = db('crm_c_customerinfo')->where('id','in',$data['id'])->field('id,c_unique,customer_name,customer_number,dj_staff_id,dj_staff,dj_staff_number,dj_department_id,dj_department_name,add_shop_code,add_shop_name,customer_type')->select();
        $ip = get_client_ip();
        $time = date('Y-m-d H:i:s');
        $lData  = [];
        $params = [];
        $type = [];
        foreach($info as $key=>$val){
            //转介绍客资需要修改渠道
            if($val['customer_type'] == 2){
                $type[] = $val['id'];
            }
            //日志
            $lData[$key]['module']     = 'crm';
            $lData[$key]['controller'] = 'Customer';
            $lData[$key]['action']     = 'customerchangesub';
            $lData[$key]['old_data']   = json_encode($val);
            $lData[$key]['data']       = json_encode($param);
            $lData[$key]['customer_id']= $val['id'];
            $lData[$key]['staff_name'] = session('staff_name');
            $lData[$key]['staff_id']   = session('staff_id');
            $lData[$key]['ip']         = $ip;
            $lData[$key]['create_time']= $time;
            //追踪记录
            $params[$key]['customer_id'] = $val['id'];
            $params[$key]['c_unique'] = $val['c_unique'];
            $params[$key]['customer_name'] = $val['customer_name'];
            $params[$key]['customer_number'] = $val['customer_number'];
            $params[$key]['sales_remark'] = '客资转移--录入人由【'.$val['dj_staff'].'】转移给【'.$param['dj_staff'].'】';
            $params[$key]['sales_day'] = $time;
            $params[$key]['sales_staff'] = session('staff_name');
            $params[$key]['sales_staff_id'] = session('staff_id');
            $params[$key]['sales_staff_number'] = session('staff_number');
            $params[$key]['shop_name'] = session('shop_name');
            $params[$key]['shop_code'] = session('shop_code');
            cache('getCustomerTrackInfos'.$val['id'],null);
        }

        db()->startTrans();
        try{
            db('crm_c_customerinfo')->where('id','in',$data['id'])->update($param);
            if(!empty($type)){
                $channel['customer_channel_id'] = $sinfo['department_id'] ? $sinfo['department_id'] : -1;
                $channel['customer_channel'] = $sinfo['department_name'] ? $sinfo['department_name'] : '空渠道';
                db('crm_c_customerinfo')->where('id','in',$type)->update($channel);
            }
            db('crm_action_log','db_logs')->insertAll($lData);
            db('crm_c_salestrackinginfo')->insertAll($params);
            db()->commit();
            unset($data,$lData,$params,$info);
            return array('code'=>200,'msg'=>'客资转移成功','data'=>''.db()->getLastSql());
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'客资转移失败','data'=>$e->getMessage());
        }
    }
    //客资交接  离职人员交接
    public function customerMove(){
        $data = input();
        $info = getStaffInfoById($data['staff_id']);
        $cInfo = db('crm_c_customerinfo')->where('id','in',$data['id'])->field('id,dj_staff_id,dj_staff,dj_staff_number,sales_staff_id,dj_staff,dj_staff_number,dj_department_id,sales_department_id')->select();
        $log = [];
        $time = date('Y-m-d H:i:s');
        if($data['move'] == 'dj'){
            $arr = array(
                'dj_staff_id'=>$data['staff_id'],
                'dj_staff'=>$data['staff_name'],
                'dj_staff_number'=>$info['staffnumber'],
                'dj_department_id'=>$info['department_id']
            );
            foreach($cInfo as $k=>$v){
                $old = array(
                    'dj_staff_id'=>$v['dj_staff_id'],
                    'dj_staff'=>$v['dj_staff'],
                    'dj_staff_number'=>$v['dj_staff_number'],
                    'dj_department_id'=>$v['dj_department_id']
                );
                $log[$k]['module']='crm';
                $log[$k]['controller']='Customer';
                $log[$k]['action']='customermove';
                $log[$k]['ip']=get_client_ip();
                $log[$k]['data']=json_encode($arr);
                $log[$k]['old_data']=json_encode($old);
                $log[$k]['customer_id']=$v['id'];
                $log[$k]['staff_id']=session('staff_id');
                $log[$k]['staff_name']=session('staff_name');
                $log[$k]['create_time']=$time;
            }
        }else{
            $arr = array(
                'sales_staff_id'=>$data['staff_id'],
                'sales_staff'=>$data['staff_name'],
                'sales_staff_number'=>$info['staffnumber'],
                'sales_department_id'=>$info['department_id']
            );
            foreach($cInfo as $k=>$v){
                $old = array(
                    'sales_staff_id'=>$v['sales_staff_id'],
                    'sales_staff'=>$v['sales_staff'],
                    'sales_staff_number'=>$v['sales_staff_number'],
                    'sales_department_id'=>$v['sales_department_id']
                );
                $log[$k]['module']='crm';
                $log[$k]['controller']='Customer';
                $log[$k]['action']='customermove';
                $log[$k]['ip']=get_client_ip();
                $log[$k]['data']=json_encode($arr);
                $log[$k]['old_data']=json_encode($old);
                $log[$k]['customer_id']=$v['id'];
                $log[$k]['staff_id']=session('staff_id');
                $log[$k]['staff_name']=session('staff_name');
                $log[$k]['create_time']=$time;
            }
        }
        if(empty($data['id'])){
            return array('code'=>100,'msg'=>'请选择要交接的客资');
        }
        if(empty($data['staff_id'])){
            return array('code'=>101,'msg'=>'请选择要交接给谁');
        }
        db()->startTrans();
        try{
            db('crm_c_customerinfo')->where('id','in',$data['id'])->update($arr);
            db('crm_action_log','db_logs')->insertAll($log);
            db()->commit();
            return array('code'=>200,'msg'=>'客资交接成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>103,'msg'=>'客资交接失败','data'=>$e->getMessage());
        }
    }
    // // 离职交接 选择是否 包含兼职员工
    // public function customerHandoverEmployee(){
    //     $param['shop_code'] = session('shop_code');
    //     if (input('post.type')==1) {
    //         $staffs = getShopStaffs($param); 
    //     }elseif (input('post.type')==0) {
    //         $staffs = controller('crm/Customer','lib')->get_staff_list($param);
    //     }
    //     $res = "<option value='0'>选择员工</option>";
    //     foreach ($staffs as $key => $value) {
    //         $res .= "<option value='".$value['id']."'>".$value['staffname']."</option>";
    //     }
    //     return $res;
    // }
    // 离职交接 （ 页面 ）
    public function customerHandover(){

        //$staffs = getShopStaffs($param);

        //店
        $shop_url = '5a37a1503264d';
        $shop_data['brandclass_id'] = session('brandclass_id');
        $shop_res = sx_call($shop_url, $shop_data);
        if ($shop_res['code'] == 200) {
            $shopList = $shop_res['data'];
        } else {
            $shopList = '';
        }
        $this->assign('shopList',$shopList);

        //部门
        $mcInter = new \app\common\lib\mcInterface();
        $departmentList = $mcInter->getDepartment(['shop_code'=>session('shop_code')]);
        $this->assign('departmentList',$departmentList);

        //小组
        $groupList = $mcInter->getGroupInfo(['department_id'=>session('department_id')]);

        $this->assign('grouplist',$groupList);

        //人员
        $param['shop_code'] = session('shop_code');
        // $param['department_id'] = session('department_id');
        // $param['group_id'] = session('group_id');
        $staffs = controller('crm/Customer','lib')->get_staff_list($param);
        $this->assign('staffs', $staffs);

        return $this->fetch();
    }
    // 客资转移 查询客资
    public function moveSearchCustomer(){
        $temp = input();
        $data = $temp['getData'];
        $page = $temp['page'] ? $temp['page'] : 1;
        $limit = $temp['limit'] ? $temp['limit'] : 50;
        $result['code'] = 0;
        $result['msg']  = '';
        if (!$data['staff']) {
            $result['count'] = 0;
            $result['data']  = array();
            return $result;
        }

        //dj_staff_id 登记员工录入人，sales_staff_id 销售员追踪人， sk_staff_id 筛客人， tel_staff_id
        $sql = ' (dj_staff_id="'.(int)$data['staff'].'" or sales_staff_id="'.(int)$data['staff'].'" or tel_staff_id="'.(int)$data['staff'].'") ';
        // $sql = ' (dj_staff_id="'.(int)$data['staff'].'" or sales_staff_id="'.(int)$data['staff'].'" or sk_staff_id="'.(int)$data['staff'].'" or tel_staff_id="'.(int)$data['staff'].'") ';

        if ($data['start'] && $data['end']) {
            $sql .= ' and dj_day between "'.date('Y-m-d 00:00:00', strtotime($data['start'])).'" and "'.date('Y-m-d 23:59:59', strtotime($data['end'])).'" ';
        }else if ($data['start'] && !$data['end']) {
            $sql .= ' and dj_day > "'.date('Y-m-d 23:59:59', strtotime($data['start'])).'" ';
        }else if (!$data['start'] && $data['end']) {
            $sql .= ' and dj_day < "'.date('Y-m-d 23:59:59', strtotime($data['end'])).'" ';
        }else{
            $sql .= ' and dj_day < "'.date('Y-m-d H:i:s').'" ';
        }

        if ($data['get_contact']) {
            switch ($data['get_contact']) {
                case 'tel':
                    $sql .= ' and (customer_tel is not null or customer_tel <> "" or customer_tel <> 0) ';
                    break;
                case 'wechat':
                    $sql .= ' and (customer_wechat is not null or customer_wechat <> "" or customer_wechat <> 0) ';
                    break;
                case 'qq':
                    $sql .= ' and (customer_qq is not null or customer_qq <> "" or customer_qq <> 0) ';
                    break;
            }
        }
        if ($data['is_loss']) {
            $sql .= ' and is_loss='.(int)$data['is_loss'];
        }
        if ($data['is_valid']) {
            $sql .= ' and is_valid in ('.$data['is_valid'].')';
        }
        if ($data['is_intostore']) {
            $sql .= ' and is_intostore in ('.$data['is_intostore'].')';
        }
        if ($data['is_success']) {
            $sql .= ' and is_success in ('.$data['is_success'].')';
        }
        if ($temp['type']==1) {
            $shop_code = 'shop_code = "'.session('shop_code').'" or add_shop_code ="'.session('shop_code').'"';
        }else{
            $shop_code = '1 = 1';
        }
        $info = db('crm_c_customerinfo')
            ->where($sql)
            ->where('is_status',1)
            ->where('brandclass_id',session('brandclass_id'))
            ->where($shop_code)
            ->field('id,customer_number,customer_name,customer_tel,mate_tel,dj_day,dj_staff,jr_day,sales_staff,customer_cource,customer_channel,add_shop_name,shop_name')
            ->limit($limit)
            ->page($page)
            ->select();
        // echo db()->getLastSql();die;
        $count = db('crm_c_customerinfo')
            ->where($sql)
            ->where('is_status',1)
            ->where('brandclass_id',session('brandclass_id'))
            ->where($shop_code)
            ->count();
        // echo db()->getLastSql();die;
        if(count($info)>0){
            $result['data'] = $info;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }

        return json($result);
    }
    //客资转移
    public function customerMoveAction(){
        $data = input();
        $result['code'] = 0;
        $result['msg']  = '';
        if (!$data['staff'] || !$data['target_staff']) {
            $result['count'] = 0;
            $result['data']  = array();
            return $result;
        }

        //dj_staff_id 登记员工录入人，sales_staff_id 销售员追踪人， sk_staff_id 筛客人， tel_staff_id
        $sql = ' (dj_staff_id="'.(int)$data['staff'].'" or sales_staff_id="'.(int)$data['staff'].'" or tel_staff_id="'.(int)$data['staff'].'") ';
        // $sql = ' (dj_staff_id="'.(int)$data['staff'].'" or sales_staff_id="'.(int)$data['staff'].'" or sk_staff_id="'.(int)$data['staff'].'" or tel_staff_id="'.(int)$data['staff'].'") ';

        if ($data['start'] && $data['end']) {
            $sql .= ' and dj_day between "'.date('Y-m-d H:i:s', strtotime($data['start'])).'" and "'.date('Y-m-d H:i:s', strtotime($data['end'])).'" ';
        }else if ($data['start'] && !$data['end']) {
            $sql .= ' and dj_day > "'.date('Y-m-d H:i:s', strtotime($data['start'])).'" ';
        }else if (!$data['start'] && $data['end']) {
            $sql .= ' and dj_day < "'.date('Y-m-d H:i:s', strtotime($data['end'])).'" ';
        }else{
            $sql .= ' and dj_day < "'.date('Y-m-d H:i:s').'" ';
        }

        if ($data['get_contact']) {
            switch ($data['get_contact']) {
                case 'tel':
                    $sql .= ' and (customer_tel is not null or customer_tel <> "" or customer_tel <> 0) ';
                    break;
                case 'wechat':
                    $sql .= ' and (customer_wechat is not null or customer_wechat <> "" or customer_wechat <> 0) ';
                    break;
                case 'qq':
                    $sql .= ' and (customer_qq is not null or customer_qq <> "" or customer_qq <> 0) ';
                    break;
            }
        }
        if ($data['is_loss']) {
            $sql .= ' and is_loss='.(int)$data['is_loss'];
        }
        if ($data['is_valid']) {
            $sql .= ' and is_valid in ('.$data['is_valid'].')';
        }
        if ($data['is_intostore']) {
            $sql .= ' and is_intostore in ('.$data['is_intostore'].')';
        }
        if ($data['is_success']) {
            $sql .= ' and is_success in ('.$data['is_success'].')';
        }
        if ($data['type']==1) {
            $shop_code = 'shop_code = "'.session('shop_code').'" or add_shop_code ="'.session('shop_code').'"';
        }else{
            $shop_code = '1 = 1';
        }
        // 需要转移的客资信息
        $info = db('crm_c_customerinfo')
            ->where($sql)
            ->where('is_status',1)
            ->where('brandclass_id',session('brandclass_id'))
            ->where($shop_code)
            ->field('id,sales_staff,sales_staff_id,sales_staff_number,dj_staff_id,tel_staff_id')
            ->select();
        // 目标员工信息
        $staffInfo = getStaffInfoById($data['target_staff']);

        $sales_staff = $staffInfo['staffname'] ? $staffInfo['staffname'] : $staffInfo['staff_name'];
        $sales_staff_id = $staffInfo['id'] ? $staffInfo['id'] : $staffInfo['staff_id'];
        $sales_staff_number = $staffInfo['staffnumber'] ? $staffInfo['staffnumber'] : $staffInfo['staff_number'];

        //改成客资信息里的录入人、筛客人、追踪人、tel_staff对应的交接 2019.04.11
        $cids_dj_staff_id = '';
        $cids_sales_staff_id = '';
        $cids_sk_staff_id = '';
        $cids_tel_staff_id = '';
        foreach ($info as $key => $value) {
            if ($data['staff']==$value['dj_staff_id']) {
                $cids_dj_staff_id .= $value['id'].',';
                $target_dj['dj_staff'] = $sales_staff;
                $target_dj['dj_staff_id'] = $sales_staff_id;
                $target_dj['dj_staff_number'] = $sales_staff_number;
            }
            if ($data['staff']==$value['sales_staff_id']) {
                $cids_sales_staff_id .= $value['id'].',';
                $target_sales['sales_staff'] = $sales_staff;
                $target_sales['sales_staff_id'] = $sales_staff_id;
                $target_sales['sales_staff_number'] = $sales_staff_number;
            }
            // if ($data['staff']==$value['sk_staff_id']) {
            //     $cids_sel_staff_id .= $value['id'].',';
            //     $target_sel['sk_staff'] = $sales_staff;
            //     $target_sel['sk_staff_id'] = $sales_staff_id;
            //     $target_sel['sk_staff_number'] = $sales_staff_number;
            // }
            if ($data['staff']==$value['tel_staff_id']) {
                $cids_tel_staff_id .= $value['id'].',';
                $target_tel['tel_staff'] = $sales_staff;
                $target_tel['tel_staff_id'] = $sales_staff_id;
                // $target_tel['tel_time'] = date("Y-m-d H:i:s");
            }
        }
        $cids_dj_staff_id = $cids_dj_staff_id ? trim($cids_dj_staff_id, ',') : '';
        $cids_sales_staff_id = $cids_sales_staff_id ? trim($cids_sales_staff_id, ',') : '';
        // $cids_sk_staff_id = $cids_sk_staff_id ? trim($cids_sk_staff_id, ',') : '';
        $cids_tel_staff_id = $cids_tel_staff_id ? trim($cids_tel_staff_id, ',') : '';

        db()->startTrans();
        try{
            $mysql_log = '';
            if ($cids_dj_staff_id) {
                $target_dj['update_time'] = date("Y-m-d H:i:s");
                db('crm_c_customerinfo')->where('id', 'in', $cids_dj_staff_id)->update($target_dj);
                $mysql_log .= db('crm_c_customerinfo')->getLastSql().";";
            }
            if ($cids_sales_staff_id) {
                $target_sales['update_time'] = date("Y-m-d H:i:s");
                db('crm_c_customerinfo')->where('id', 'in', $cids_sales_staff_id)->update($target_sales);
                $mysql_log .= db('crm_c_customerinfo')->getLastSql().";";
            }
            // if ($cids_sk_staff_id) {
            //     $target_sel['update_time'] = date("Y-m-d H:i:s");
            //     db('crm_c_customerinfo')->where('id', 'in', $cids_sk_staff_id)->update($target_sel);
            //     $mysql_log .= db('crm_c_customerinfo')->getLastSql().";";
            // }
            if ($cids_tel_staff_id) {
                $target_tel['update_time'] = date("Y-m-d H:i:s");
                db('crm_c_customerinfo')->where('id', 'in', $cids_tel_staff_id)->update($target_tel);
                $mysql_log .= db('crm_c_customerinfo')->getLastSql().";";
            }
            $log = date("Y-m-d H:i:s").session('staff_name')." 操作离职交接，将".$data['staff_name'].count($info)."个客资转移给".$sales_staff;
            action_log($log,$mysql_log,0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'客资转移成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>103,'msg'=>'客资转移失败','data'=>$e->getMessage());
        }
    }
    public function check_auth(){
        $auth = input('param.auth');
        return check_right($auth);
    }
    public function jdm(){
        $url = strpos($_SERVER['HTTP_HOST'],'http://') ? $_SERVER['HTTP_HOST']:'http://'.$_SERVER['HTTP_HOST'];
        $url .= "/crm/index/jindianma?";
        $url .= 'shop_code='.session('shop_code').'&shop_name='.session('shop_name');
        $this->assign('url',($url));
        return $this->fetch();
    }
    //进店码生成
    public function makeJDM(){
        $url = strpos($_SERVER['HTTP_HOST'],'http://') ? $_SERVER['HTTP_HOST']:'http://'.$_SERVER['HTTP_HOST'];
        $url .= "/crm/index/jindianma?";
        $url .= 'shop_code='.session('shop_code').'&shop_name='.session('shop_name');
        $qrcode = new \Endroid\QrCode\QrCode();
        $qrcode->setText($url);
        echo $qrcode->writeString();
        exit();
    }
    //店面下人员
    public function getShopStaffs(){
        $data = input();
        return controller('crm/Customer','lib')->get_staff_lists($data);
    }
    //多地登陆
    public function more_login(){
        $data = input();
        $info = cache('staffInfo_'.session('staff_id'));
        if($data['more_login'] == 1){
            $info['more_login'] = 1;
            db_config('more_login_'.session('staff_id'),1);
        }else{
            $info['more_login'] = 0;
            db_config('more_login_'.session('staff_id'),0);
        }
        cache('staffInfo_'.session('staff_id'),$info);
        return array('code'=>200,'msg'=>'设置成功');
    }
    //--------------------------------- 开单调erp接口 新版页面，代替唤起erp直接开单 开始   这一整块都不要了 ---------------------------------//
    // 根据工作店面和工作类型查询员工
    public function getStaffByWorkType(){
        $param = input();

        // $url = '5b75341456d18';
        $data['shop_code'] = $param['shop_code'] ? $param['shop_code'] : session('shop_code');
        $data['work_type'] = $param['work_type'];
        // $temp_staffs = sx_call($url,$data);

        $mc = new \app\common\lib\mcInterface();
        $temp_staff = $mc->getAllStaffListByShopcode($data);
        return $temp_staff;
    }
    /**
     * 支付类型
     * 
     * @return [type] [description]
     */
    public function getShopPayType(){
        $shopType = input('param.shop_type');
        $erpInterface = new erpInterface(['shop_type'=>$shopType]);
        $res =  $erpInterface->getPayTypeDict();
        if($res === false){
            $res = ['error'=>1,'msg'=>$erpInterface->error,'code'=>501];
        }
        return json($res);
    }
    /**
     * 收款方式
     */
    public function getShopFeeCategory(){
        $shopType = input('shop_type');
        $erpInterface = new erpInterface(['shop_type'=>$shopType]);
        $res =  $erpInterface->getFeeCategoryDict();
        if($res === false){
            $res = ['error'=>1,'msg'=>$erpInterface->error,'code'=>501];
        }
        return json($res);
    }
    // 没有erp转订单
    public function orderManager(){
        // 权限
        $auth = check_right('menu1519633923');
        if (!$auth) {
            $return=array('error'=>'1','msg'=>'您没有操作转订单的权限，请先设置权限');
            return json($return);
        }
        $id = (int)input('param.id');
        // $id = (int)input('param.id') ? (int)input('param.id') :110;
        $cusInfo = controller('crm/Customer', 'lib')->getCustomerInfo($id);

        $baby_sex = config('baby_sex');
        if(empty($baby_sex)){
            $baby_sex = [
                ['sex'=>'男',],
                ['sex'=>'女',],
            ];
        }
        $this->assign('baby_sex',$baby_sex);
        // 判断配置，是否允许无网销开单
        $sys_sales = db_config('is_zhuanorder_not_wx');
        if(!$cusInfo['sales_staff_id'] && ($sys_sales != 1)){
            $return=array('error'=>'1','msg'=>'没有网销，不能转单');
            return json($return);
        }
        // $cusInfo['shop_code'] = session('shop_code');
        // $cusInfo['shop_name'] = session('shop_name');
        // $cusInfo['sales_staff_id']= session('staff_id');
        // $cusInfo['sales_staff']  = session('staff_name');
        // 格式化时间
        $cusInfo['baby_birthday']= $cusInfo['baby_birthday'] ? date('Y-m-d', strtotime($cusInfo['baby_birthday'])) : '';
        $cusInfo['ready_baby_day']= $cusInfo['ready_baby_day'] ? date('Y-m-d', strtotime($cusInfo['ready_baby_day'])) : '';
        $cusInfo['marry_day']= $cusInfo['marry_day'] ? date('Y-m-d', strtotime($cusInfo['marry_day'])) : '';
        $cusInfo['mate_birthday']= $cusInfo['mate_birthday'] ? date('Y-m-d', strtotime($cusInfo['mate_birthday'])) : '';
        $cusInfo['customer_birthday']= $cusInfo['customer_birthday'] ? date('Y-m-d', strtotime($cusInfo['customer_birthday'])) : '';

        $cusInfo['customer_channel'] = $cusInfo['customer_channel'] ? strip_tags($cusInfo['customer_channel']) : '';
        $cusInfo['consultation_type'] = $cusInfo['consultation_type'] ? strip_tags($cusInfo['consultation_type']) : '';
        if (!$cusInfo['sales_staff_id']) {
            $cusInfo['sales_staff_id'] = session('staff_id');
            $cusInfo['sales_staff'] = session('staff_name');
        }
        // 上海优尼克定制  客资备注 =  订单备注
        if (customize('shynk')) {
            $cusInfo['order_note'] = $cusInfo['customer_remark'];
        }
        $this->assign('info',$cusInfo);
        // $sInfo = getStaffInfoById($cusInfo['sales_staff_id']);
        $sInfo = getStaffInfoById(session('staff_id'));
        $this->assign('sInfo',$sInfo);
        $this->assign('today',date('Ymd'));
        //省
        $province = controller('crm/Customer','lib')->address(['type'=>1]);
        $this->assign('province',$province);
        //拍照店
        $shop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id'),'is_photo'=>1]);
        $this->assign('shop',$shop);
        $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);
        //渠道
        $channel = controller('crm/Customer','lib')->getChannel();
        if(session('shop_code') != $cusInfo['add_shop_code']){
            $channel = array_merge($channel,array(array('id'=>$cusInfo['customer_channel_id'],'channel_name'=>$cusInfo['customer_channel'])));
        }
        $this->assign('channel',$channel);
        $param['ShopSn'] = session('ShopSn');
        if (!$param['ShopSn']) {
        	$shopInfo = getShopInfo();
        	$param['ShopSn'] = $shopInfo[session('shop_code')]['sn'];
        }
        if (session('staff_sn')) {
            $param['StaffSN'] =  session('staff_sn');
        }else{
            $param['StaffSN'] =  $sInfo['staff_sn'];
        }
        $param['channelCode'] = $cusInfo['channel_code'];
        $order_sn = $erpInterface->getOrderSn($param);

        // var_dump($order_sn);die;
        
        $this->assign('order_sn',$order_sn);
        $this->assign('shop_sn',$param['ShopSn']);
        $this->assign('staff_sn',$param['StaffSN']);        
 
        //门市
        $rec = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>1]);
        $this->assign('rec',$rec);
        //摄影师
        $cameraman = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>3]);
        $this->assign('cameraman',$cameraman);
        //化妆师
        $dresser = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>7]);
        $this->assign('dresser',$dresser);
        //引导师
        $mentor = getShopStaffs(['shop_code'=>$cusInfo['consulation_shop_code'],'work_type'=>25]);
        $this->assign('mentor',$mentor);
        //是否可输入套系金额
        $this->assign('set_order_money',db_config('set_order_money_'.session('brandclass_id')));
        $babypastel = customize('babypastel');
        if ($babypastel) {
            $this->assign('babypastel_wangfutype','1');
        }
        $this->assign('package_name',$cusInfo['package_name']);
        // 20191225
        if(ini('order.orderpage')){
            // 小阿福订单规则，同一客资，如果有收款的 消费类型订单 则该消费类型不可用
            // if (ini('order.orderpage') == 'ordermanagerxaf') {
            //     // 开单是否必须收款
            //     $isSkArr = db('c_customerorder')->alias('o')
            //         ->join('c_customerphoto p','p.orderid = o.orderid and p.photodate=2','left')
            //         ->where('o.crm_customer_number',$cusInfo['customer_number'])
            //         ->field('o.id as oid,p.id as pid')->select();
            //     // 循环结果，如果有oid，没有pid，那么下个订单必须收费
            //     $isSk = 2;
            //     foreach ($isSkArr as $key => $value) {
            //         if ($value['oid'] && !$value['pid']) {
            //             $isSk = 1;
            //         }
            //     }
            //     $this->assign('isSk',$isSk);
                
            //     // 已订单的消费类型
            //     $consultation_types = db('c_customerorder')->alias('o')
            //         ->join('c_paymentcontent p','p.orderid = o.orderid and o.blankoutannal<>1','left')
            //         ->where('o.crm_customer_number',$cusInfo['customer_number'])
            //         ->where('p.id','not null')
            //         ->field('o.consumption_type')
            //         ->select();
            //     $typeArr = [];
            //     // 收款订单的消费类型
            //     if ($consultation_types) {
            //         foreach ($consultation_types as $key => $value) {
            //             array_push($typeArr,$value['consumption_type']);
            //         }
            //     }
            //     $typeArr = array_unique($typeArr);
                    //开单相关信息
                $orderInfo = $erpInterface->getCreateOrderInfo(['shop_code'=>session('shop_code')]);
                // print_r($orderInfo);
                // exit;
                $orderInfo['dt_s_packageset'] = my_sort($orderInfo['dt_s_packageset'],'package_price','SORT_ASC');
                foreach($orderInfo['dt_s_consumptiontype'] as $k=>$v){
                    $tihuan = ['摄影师;','化妆师;','引导师;','MV摄影师;','MV'];
                    $tihuans = ['','','','',''];
                    $orderInfo['dt_s_consumptiontype'][$k]['mustfill'] = trim(str_replace($tihuan,$tihuans,$v['mustfill']),';');
                }
                $this->assign('orderInfo',$orderInfo);
                $allConsultation = [];
                foreach ($orderInfo['dt_s_consumptiontype'] as $key => $value) {
                    $allConsultation[$key] = $value;
            //         if (in_array($value['consumption_name'],$typeArr)) {
            //             // 已有收费订单
            //             $allConsultation[$key]['dis'] = 1;
            //         }else{
            //             // 无收费订单
            //             $allConsultation[$key]['dis'] = 2;
            //         }
            //     }
            //     // var_dump($allConsultation);die;
                $this->assign('allConsultation',$allConsultation);
            }
            return $this->fetch(ini('order.orderpage'));
        }else{
            $orderInfo = $erpInterface->getCreateOrderInfo(['shop_code'=>session('shop_code')]);
            $orderInfo['dt_s_packageset'] = my_sort($orderInfo['dt_s_packageset'],'package_price','SORT_ASC');
            foreach($orderInfo['dt_s_consumptiontype'] as $k=>$v){
                    $tihuan = ['摄影师;','化妆师;','引导师;','MV摄影师;','MV'];
                    $tihuans = ['','','','',''];
                    $orderInfo['dt_s_consumptiontype'][$k]['mustfill'] = trim(str_replace($tihuan,$tihuans,$v['mustfill']),';');
            }
            // 上海优尼克定制  录入、追踪时选择的意向套系 自动选中 并写入erp意向套系
            if (customize('shynk')) {
                foreach ($orderInfo['dt_s_packageset'] as $k => $v) {
                    if ($v['package_name']==$cusInfo['package_name']) {
                        $orderInfo['dt_s_packageset'][$k]['selected'] = 1;
                    }
                }
            }
            $this->assign('orderInfo',$orderInfo);
            return $this->fetch();
        }
    }
    //切换消费类型获取套系 
    public function getPackage(){
        $data = input();
        if($data['consultation_type'] == '三宝'){
            $where['txtype'] = ['in','三宝'];
        }else{
            $where['txtype'] = ['not in','三宝'];
        }
        // $packageset = db('s_packageset')->where("find_in_set('".$data['shop_code']."',shop_code)")->where($where)->field('package_name,package_price')->select();
        // 20200115
        $tx = db('s_packageset')->where("find_in_set('".$data['shop_code']."',shop_code)")->field('package_name,package_price,"tx" as type')->select();
        $cz = db('s_czpackageset')->where("find_in_set('".$data['shop_code']."',shop_code)")->field('czpackage_name as package_name,czpackage_price as package_price,"cz" as type')->select();
        $packageset = array_merge($tx,$cz);
        $packageset = my_sort($packageset,'package_price','SORT_ASC');
        return $packageset;
    }
    //切换消费类型获取套系 ---getPackage新方法---SDM
    public function changeConsultation(){
        $data = input();
        if($data['consultation_type'] == '三宝'){
            $where['txtype'] = ['in','三宝'];
        }else{
            $where['txtype'] = ['not in','三宝'];
        }
        // $packageset = db('s_packageset')->where("find_in_set('".$data['shop_code']."',shop_code)")->where($where)->field('package_name,package_price')->select();
        // 20200115
        $tx = db('s_packageset')->where("find_in_set('".$data['shop_code']."',shop_code)")->field('package_name,package_price,"tx" as type')->select();
        $cz = db('s_czpackageset')->where("find_in_set('".$data['shop_code']."',shop_code)")->field('czpackage_name as package_name,czpackage_price as package_price,"cz" as type')->select();
        $packageset = array_merge($tx,$cz);
        $packageset = my_sort($packageset,'package_price','SORT_ASC');
        $ret = ['code'=>200,'msg'=>'','data'=>['packageset'=>$packageset]];
        if(customize('bjggt')){
            $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);
            $param['Consumption_type'] = $data['consultation_type'];
            $sInfo = getStaffInfoById(session('staff_id'));
            $param['ShopSn'] = session('ShopSn');
            if (!$param['ShopSn']) {
                $shopInfo = getShopInfo();
                $param['ShopSn'] = $shopInfo[session('shop_code')]['sn'];
            }
            if (session('staff_sn')) {
                $param['StaffSN'] =  session('staff_sn');
            }else{
                $param['StaffSN'] =  $sInfo['staff_sn'];
            }
            $ret['data']['order_sn'] = $erpInterface->getOrderSn($param);
        }
        return $ret;
    }
    public function changeChannel(){
        $data = input();
        $ret = ['code'=>200,'msg'=>'','data'=>[]];
        if(!$data['customer_channel_id']) return $ret;
        if(customize('shynk')){
            $channelData = db('crm_s_channel')->where('id',$data['customer_channel_id'])->find();
            $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);
            $param['ShopSn'] = session('ShopSn');
            if (!$param['ShopSn']) {
                $shopInfo = getShopInfo();
                $param['ShopSn'] = $shopInfo[session('shop_code')]['sn'];
            }
            $param['channelCode'] = $channelData['channel_code'];
            $ret['data']['order_sn'] = $erpInterface->getOrderSn($param);
        }
        return $ret;
    }
    //编辑订单
    public function orderEdit(){
        // 权限
        $auth = check_right('menu1519633959');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有操作转订单的权限，请先设置权限');
            return json($return);
            exit;
        }
        $id = input('param.id');
        $info = db('crm_c_customerinfo')->where('id',$id)->field('order_number')->find();
        if(empty($info['order_number'])){
            $return = array('error'=>'1','msg'=>'此客资还未成单，请先去转订单');
            return json($return);
            exit;
        }
        $orderInfo = db('crm_c_customer_order')->where('order_sn',$info['order_number'])->find();
        $this->assign('orderInfo',$orderInfo);
        return $this->fetch();
    }
    //提交订单编辑
    public function editOrder(){
        if(!check_right('menu1519633959')){
            return array('code'=>130,'msg'=>'你无此操作权限');
        }else{
            $param = input('post.');
            return controller("Customer","lib")->editOrder($param);
        }
    }
    public function zhuanOrder(){
        if(!check_right('menu1519633923')){
            return array('code'=>130,'msg'=>'你无此操作权限');
        }else{
            $param = input('post.');
            return controller("Customer","lib")->zhuanOrder($param);
        }
    }
    // 检查客资是否转过订单
    public function checkCustomerOrder(){
        // 权限
        $auth = check_right('menu1519633923');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有操作转订单的权限，请先设置权限');
            return json($return);
            exit;
        }
        $erp = is_install('sx_erp');

        $return = [];
        if ($erp) {
            $return['erp'] = 1;  // 安装erp
        }else{
            $return['erp'] = 2;  // 未安装erp
        }
        $id = (int)input('post.id');
        $where['c.id'] = $id;
        $where['c.is_status'] = 1;
        $info = db('crm_c_customerinfo')->alias('c')
            ->join('c_customerorder o','c.id=o.crm_customer_id AND o.blankoutannal<>1 AND o.crm_order_type<>2','left')
            ->where($where)
            ->field('c.id,c.customer_number,c.c_unique,c.customer_tel,o.orderId')
            ->find();

        if (!$info) {
            $return['error']= 1;
            $return['code'] = 100;
            $return['msg']  = '客资信息查询失败，请联系管理员';
            $return['data'] = db()->getLastSql();
            return $return;
        }
        // 查看是否有未完成的上门 
        $lWhere['cid'] = $id;
        $lWhere['is_delete'] = 2; // 未删除
        $lWhere['status'] = 1; // 未上门
        $smpNum = db('crm_l_pc_log')->where($lWhere)->where('pc_time','>=', date('Y-m-d'))->count();
        if ($smpNum>0) {
            $return['error']= 1;
            $return['code'] = 101;
            $return['msg']  = '有尚未完成的上门，无法开单，请确认！';
            $return['data'] = db()->getLastSql();
            return $return;
        }
        $one_order = db_config('one_customer_more_order');//同一客资允许多次订单,有过成交，就一直成交

        if ($info['orderId']) {
            if($one_order == 2){
                $return['error'] = 1;
                $return['code'] = 104;
                $return['msg']  = '已设置为不允许同一客资多次订单，请打开设置或重新创建客资转订单';
            }else{
                $return['code'] = 100;
                $return['msg']  = '已订单';
            }
        }else{
            $return['code'] = 200;
            $return['msg']  = '未订单';
        }

        return json($return);
    }
    /**
     * 方法描述：开单
     * @return Ambigous <\think\mixed, string>
     * @author Zhaojiepeng<zhaojiepeng@suxuantech.cn> 2018年5月3日 19:58:38
     */
    public function order(){
        $data = input();

        //查询品牌信息
        if(empty(cache("brandInfo"))){
            $brandList = sx_call('5a38840b15ba9',array(),'sx_mc');
            if($brandList['code'] == 200){
                $brandlist = $brandList['data'];
                cache("brandInfo",$brandList['data'], 3600);
            }
        }else{
            $brandlist = cache("brandInfo");
        }
        $this->assign([
            'brandlist'=>$brandlist,//事业部
        ]);
        $id = (int)$data['id'];
        $cInfo = db('crm_c_customerinfo')->where('id',$id)
            ->field('id,customer_name,customer_sex,customer_tel,customer_wechat,mate_name,mate_sex,mate_tel,mate_wechat,customer_cource,customer_cource_id,consultation_type,sales_staff')
            ->find();

        if ($cInfo['customer_sex'] == '男') {
            $cInfo['mname'] = $cInfo['customer_name'];
            $cInfo['mphone']= $cInfo['customer_tel'];
            $cInfo['mwechat']= $cInfo['customer_wechat'];

            $cInfo['wname'] = $cInfo['mate_name'];
            $cInfo['wphone']= $cInfo['mate_tel'];
            $cInfo['wwechat']= $cInfo['mate_wechat'];
        } else {
            $cInfo['wname'] = $cInfo['customer_name'];
            $cInfo['wphone']= $cInfo['customer_tel'];
            $cInfo['wwechat']= $cInfo['customer_wechat'];

            $cInfo['mname'] = $cInfo['mate_name'];
            $cInfo['mphone'] = $cInfo['mate_tel'];
            $cInfo['mwechat'] = $cInfo['mate_wechat'];
        }

        $this->assign('cInfo', $cInfo);
        return $this->fetch();
    }
    public function getAddOrderNeedInfo(){
        if(request()->isAjax()){   //ajax调取数据
            $shop_code = input("shop_code"); //店面code
            
            if(empty($shop_code)){
                $shop_code = session("shop_code");
            }
            $erp = config('ext.app_config');  //读取erp配置文件
            $addr = $erp['sx_erp']['addr'];   //调用url
            //订单类型
            if(empty(cache("orderType_".$shop_code))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_ConsumptionKindSet?Token=^******^&Code='.$shop_code; //定义拼接url
                $dataN = "";
                $orderList = requestERP($url,$dataN);
                if($orderList['Code'] == 200){
                    $orderlist = $orderList['Data'];
                    cache("orderType_".$shop_code,$orderList['Data']);
                }else{
                    $orderlist = "";
                }
            }else{
                $orderlist = cache("orderType_".$shop_code);
            }
            //客户分区
            if(empty(cache("areaInfo_".$shop_code))){
                $url =trim($addr,'/').'/SXWebErpAppStaff/SX_A0AreaSet?Token=^******^&Code='.$shop_code; //定义拼接url
                //$url = $addr.'/SXWebErpAppStaff/SX_BrandPhotoShopNameSet?Token=^******^&BrandName=演示事业部';
                $dataN = "";
                $areaList = requestERP($url,$dataN);
                if($areaList['Code'] == 200){
                    $arealist = $areaList['Data'];
                    cache("areaInfo_".$shop_code,$areaList['Data']);
                }else{
                    $arealist = "";
                }
            }else{
                $arealist = cache("areaInfo_".$shop_code);
            }
            //销售门市
            if(empty(cache("marketInfo_".$shop_code))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_MenShiSet?Token=^******^&Code='.$shop_code; //定义拼接url
                $dataN = "";
                $marketList = requestERP($url,$dataN);
                if($marketList['Code'] == 200){
                    $marketlist = $marketList['Data'];
                    cache("marketInfo_".$shop_code,$marketList['Data']);
                }else{
                    $marketlist = "";
                }
            }else{
                $marketlist = cache("marketInfo_".$shop_code);
                if(empty($marketlist)){
                    $marketlist = "";
                }
            }
            //网销门市
            if(empty(cache("networkInfo_".$shop_code))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_WangXiaoMenShiSet?Token=^******^&Code='.$shop_code; //定义拼接url
                $dataN = "";
                $networdList = requestERP($url,$dataN);
                if($networdList['Code'] == 200){
                    $networdlist = $networdList['Data'];
                    cache("networkInfo_".$shop_code,$networdList['Data']);
                }else{
                    $networdlist = "";
                }
            }else{
                $networdlist = cache("networkInfo_".$shop_code);
            }
            //套系
            if(empty(cache("priceInfo_".$shop_code))){
                $shop_code = 'ZX002';
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_PackageSet?Token=^******^&Code='.$shop_code; //定义拼接url
                $dataN = "";
                $shootList = requestERP($url,$dataN);
                if($shootList['Code'] == 200){
                    $pricelist = $shootList['Data'];
                    cache("priceInfo_".$shop_code,$shootList['Data']);
                }else{
                    $pricelist = "";
                }
            }else{
               $pricelist = cache("priceInfo_".$shop_code);
            }
            //拍摄主题
            if(empty(cache("shootInfo_".$shop_code))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_TopicSet?Token=^******^&Code='.$shop_code; //定义拼接url
                $dataN = "";
                $shootList = requestERP($url,$dataN);
                if($shootList['Code'] == 200){
                    $shootlist = $shootList['Data'];
                    cache("shootInfo_".$shop_code,$shootList['Data']);
                }else{
                    $shootlist = "";
                }
            }else{
                $shootlist = cache("shootInfo_".$shop_code);
            }
            //礼服主题
            if(empty(cache("fullInfo_".$shop_code))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_DressThemesetSet?Token=^******^&Code='.$shop_code; //定义拼接url
                $dataN = "";
                $fullList = requestERP($url,$dataN);
                if($fullList['Code'] == 200){
                    $fulllist = $fullList['Data'];
                    cache("fullInfo_".$shop_code,$fullList['Data']);
                }else{
                    $fulllist = "";
                }
            }else{
                $fulllist = cache("fullInfo_".$shop_code);
            }
            //客户来源
            if(empty(cache("sourceInfo_".$shop_code))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_CusNameSet?Token=^******^&Code='.$shop_code; //定义拼接url
                $dataN = "";
                $sourceList = requestERP($url,$dataN);
                if($sourceList['Code'] == 200){
                    $sourcelist = $sourceList['Data'];
                    cache("sourceInfo_".$shop_code,$sourceList['Data']);
                }else{
                    $sourcelist = "";
                }
            }else{
                $sourcelist = cache("sourceInfo_".$shop_code);
            }
            
            //单号查询
            if(empty(cache("shopInfo"))){            //根据shop_code查询SN
                $shopList = sx_call("5a005e0038270",array(),'sx_mc');
                if($shopList['code'] == 200){
                    $shoplist = $shopList['data'];
                    cache("shopInfo",$shopList['data']);
                }else{
                    $shoplist = "";
                }
            }else{
                $shoplist = cache("shopInfo");
            }
            foreach($shoplist as $k=>$v){
                if($v['shop_code'] == $shop_code){
                    $SN = $shoplist[$k]['sn'];
                }
            }
            // if(empty(cache("ordercode_".$shop_code))){ //调取查询单号的接口
            $url = trim($addr,'/').'/SXWebErpAppStaff/SX_GetOrderNum?Token=^******^&Code='.$shop_code.'&SN='.$SN; //定义拼接url
            $dataN = "";
            $ordercodeList = requestERP($url,$dataN);
            if($ordercodeList['Code'] == 200){
                $ordercode = $ordercodeList['Data'];
               // cache("ordercode_".$shop_code,$ordercodeList['Data']);
            }else{
                $ordercode = "";
            }
            //}else{
                //$ordercode = cache("ordercode_".$shop_code);
            //}
            $returnData = array(
                "code"=>200,
                "msg" =>"查询成功",
                "data"=>array(
                    'arealist'   => $arealist, 
                    'orderlist'  => $orderlist,
                    'marketlist' => $marketlist,  
                    'networdlist'=> $networdlist, 
                    'zhuguanlist'=> $networdlist, 
                    'shootlist'  => $shootlist, 
                    'sourcelist' => $sourcelist,
                    'fulllist'   => $fulllist,
                    'ordercode'  => $ordercode,
                    'pricelist'  => $pricelist,
                )
            );
            return json($returnData);
        }
    }
    /**
     * 方法描述：婚纱开单
     * @return Ambigous <\think\response\Json, \think\Response, \think\response\View, \think\response\Xml, \think\response\Redirect, \think\response\Jsonp, unknown, \think\Response>
     * @author Zhaojiepeng<zhaojiepeng@suxuantech.cn>       2018年5月4日   9:17:38
     */
    public function setorder(){
        if(IS_POST && request()->isAjax()){
            // $data = input('post.');
            // var_dump($data);exit;
            // return json(array('code'=>200,'msg'=>'开单成功'));
            $acdata = request()->post();
            // crm开单
            $cInfo = controller('crm/Customer', 'lib')->createOrder($acdata);
            // $acdata['Package_name'] = '浪漫樱花套系';
            $a = [
                'PZCode'=>$acdata['PZCode'],
                'PZCode1'=>$acdata['PZCode1'],
            ];
            if(!empty($acdata['Targetdate'])){  //订单日期
                $acdata['Targetdate'] = str_replace('-','',$acdata['Targetdate']);
            }
            if(!empty($acdata['mbirthdate'])){  //男士生日
                $acdata['mbirthdate'] = str_replace('-','',$acdata['mbirthdate']);
            }
            if(!empty($acdata['wbirthdate'])){  //女士生日
                $acdata['wbirthdate'] = str_replace('-','',$acdata['wbirthdate']);
            }
            if(!empty($acdata['weddingdate'])){ //结婚日期
                $acdata['weddingdate'] = str_replace('-','',$acdata['weddingdate']);
            }
            if(!empty($acdata['Ordertopic'])){
                $acdata['Ordertopic'] = implode('|',$acdata['Ordertopic']);
            }
            if(!empty($acdata['Dresstheme'])){
                $acdata['Dresstheme'] = implode('|',$acdata['Dresstheme']);
            }
            $erp = config('ext.app_config');  //读取erp配置文件
            $addr = $erp['sx_erp']['addr'];   //调用url
            if(!empty($acdata['shop_code']) && !empty($acdata['Area_id'])){
                //客户分区
                if(empty(cache("areaInfo_".$acdata['shop_code']))){
                    $url = trim($addr,'/').'/SXWebErpAppStaff/SX_A0AreaSet?Token=^******^&Code='.$acdata['shop_code']; //定义拼接url
                    $dataN = "";
                    $areaList = requestERP($url,$dataN);
                    if($areaList['Code'] == 200){
                        foreach($areaList['Data'] as $k=>$v){
                            if($acdata['Area_id'] == $v['id']){
                                $acdata['area'] = $v['area_name'];
                            }
                        }
                    }else{
                        $acdata['area'] = "";
                    }
                }else{
                    foreach(cache("areaInfo_".$acdata['shop_code']) as $k=>$v){
                        if($acdata['Area_id'] == $v['id']){
                            $acdata['area'] = $v['area_name'];
                        }
                    }
                }
            }
            if(!empty($acdata['shop_code']) && !empty($acdata['Brandid'])){
                //店面shop_code \ shop_name
                if(empty(cache("shopInfo_".$acdata['Brandid']))){
                    $data['brandclass_id'] = $acdata['Brandid'];
                    $shopList = sx_call("5a005e0038270",$data,'sx_mc');
                    if($shopList['code'] == 200){
                        foreach($shopList['Data'] as $k=>$v){
                            if($acdata['shop_code'] == $v['shop_code']){
                                $acdata['shop_name'] = $v['shop_name'];
                            }
                        }
                    }else{
                        $acdata['shop_name'] = "";
                    }
                }else{
                    foreach(cache("shopInfo_".$acdata['Brandid']) as $k=>$v){
                        if($acdata['shop_code'] == $v['shop_code']){
                            $acdata['shop_name'] = $v['shop_name'];
                        }
                    }
                }
            }
            if(!empty($acdata['PZCode']) || !empty($acdata['PZCode1'])){
                if(empty(cache("photo_".$acdata['Brandid']))){
                    $brandlist = cache("brandInfo");
                    foreach($brandlist as $k=>$v){  //查询brandname
                        if($v[id] == $acdata['Brandid']){
                            $brandname = $brandlist[$k]["brandclass"];
                        }
                    }
                    $url = trim($addr,'/').'/SXWebErpAppStaff/SX_BrandPhotoShopNameSet?Token=^******^&BrandName='.$brandname;
                    $dataN = "";
                    $photoList = requestERP($url,$dataN);
                    if($photoList['Code'] == 200){
                        foreach($photoList['Data'] as $k=>$v){
                            if($acdata['PZCode'] == $v['shop_code']){
                                $acdata['PZshopname'] = $v['shop_name'];
                            }
                            if($acdata['PZCode1'] == $v['shop_code']){
                                $acdata['PZshopname1'] = $v['shop_name'];
                            }
                        }
                    }else{
                        $acdata['PZshopname'] = $v['shop_name'];
                        $acdata['PZshopname1'] = $v['shop_name'];
                    }
                }else{
                    foreach(cache("photo_".$acdata['Brandid']) as $k=>$v){
                        if($acdata['PZCode'] == $v['shop_code']){
                            $acdata['PZshopname'] = $v['shop_name'];
                        }
                        if($acdata['PZCode1'] == $v['shop_code']){
                            $acdata['PZshopname1'] = $v['shop_name'];
                        }
                    }
                    $photolist = cache("photo_".$acdata['Brandid']);
                }
            }
            $data = [
                'Brandid'            =>$acdata['Brandid'],
                'Opershop'           =>'',
                'OrderId'            =>$acdata['OrderId'],
                'Targetdate'         =>$acdata['Targetdate'],
                'Consumption_type'   =>$acdata['Consumption_type'],
                'Oeder_newclass'     =>$acdata['Oeder_newclass'],
                'mname'              =>$acdata['mname'],
                'mphone'             =>$acdata['mphone'],
                'mwechat'            =>$acdata['mwechat'],
                'mbirthdate'         =>$acdata['mbirthdate'],
                'wname'              =>$acdata['wname'],
                'wphone'             =>$acdata['wphone'],
                'wwechat'            =>$acdata['wwechat'],
                'wbirthdate'         =>$acdata['wbirthdate'],
                'Storeconsuitant1'   =>$acdata['Storeconsuitant1'] ? $acdata['Storeconsuitant1'] : '',
                'Storeconsuitant2'   =>$acdata['Storeconsuitant2'],
                'Storeconsuitant3'   =>$acdata['Storeconsuitant3'],
                'weddingdate'        =>$acdata['weddingdate'],
                'Area_id'            =>$acdata['Area_id'],
                'area'               =>$acdata['area'],
                'Cssname_id'         =>$acdata['Cssname_id'],
                'cssname'            =>'',
                'Indoordresscount'   =>$acdata['Indoordresscount'],
                'Outerdresscount'    =>$acdata['Outerdresscount'],
                'Seadresscount'      =>$acdata['Seadresscount'],
                'Travelresscount'    =>$acdata['Travelresscount'],
                'email'              =>$acdata['email'],
                'address'            =>$acdata['address'],
                'customernote'       =>$acdata['customernote'],
                'Ordertopic'         =>$acdata['Ordertopic'],
                'Dresstheme'         =>$acdata['Dresstheme'],
                'mqq'=>'',
                'wqq'=>'',
                'midtype'=>'',
                'mid'=>'',
                'introducerid'=>'',
                'introducer_name'=>'',
                'wIdtype'=>'',
                'wid'=>'',
                'bbname'=>'',
                'bnickname'=>'',
                'bbithdate'=>'',
                'liunardate'=>'',
                'bbsex'=>'',
                'bzodiac'=>'',
                'shop_code'          =>$acdata['shop_code'],
                'shop_name'          =>$acdata['shop_name'],
                'Package_name'       =>$acdata['Package_name'],
                'Acceptor_address'=>'',
                'Yc_day'=>'',
                'Bb_hospital'=>'',
                'Customer_from'=>'',
                'Shareshoplist'=>'',
                'Ordernote'=>'',
                'Paizhaocount'=>'',
                'Rucecount'=>'',
                'Jingxiucount'=>'',
                'Customer_from_index'=>'',
                'Jinkeid'=>'',
                'Consumption_type_id'=>'',
            ];
            $erp = config('ext.app_config');  //读取erp配置文件
            $addr = $erp['sx_erp']['addr'];   //调用url
            $url = trim($addr,'/')."/SX_CrmApi/SX_Open_WeddingOrder?Token=^******^&package_name=".$acdata['Package_name']."&cid=&Code=".session("shop_code")."&shopname=".session("shop_name")."&PZCode=".$a['PZCode']."&PZshopname=".$acdata['PZshopname']."&PZCode1=".$a['PZCode1']."&PZshopname1=".$acdata['PZshopname1']."&zktype=0&staffid=".session("staff_id")."&crmid=".$cInfo['customer_number'];
            $dataN = json_encode($data);
            $order = requestERP($url,$dataN);
            // var_dump($order);exit;
            if($order['Code'] == 200){
                return (array('code'=>200,'msg'=>'开单成功'));
            }else{
                return (array('code'=>700,'msg'=>$order['Msg']));
            }
        }
    }
    /**
     * 方法描述：获取订单erp接口信息
     * @author Zhaojiepeng<zhaojiepeng@suxuantech.cn> 2018年5月4日 10:36:38
     */
    public function getorderinfo(){
        $action = input("action");
        $erp = config('ext.app_config');  //读取erp配置文件
        $addr = $erp['sx_erp']['addr'];   //调用url
        if($action == "photo"){ //获取拍照门店
            $brandid = input("brandid");
            $brandlist = cache("brandInfo");
            foreach($brandlist as $k=>$v){
                if($v[id] == $brandid){
                    $brandname = $brandlist[$k]["brandclass"];
                }
            }/* 
            cache("photo_".$brandid,null);
            cache("shopInfo",null); */
            //拍照店
            if(empty(cache("photo_".$brandid))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_BrandPhotoShopNameSet?Token=^******^&BrandName='.$brandname;
                $dataN = "";
                $photoList = requestERP($url,$dataN);
                if($photoList['Code'] == 200){
                    cache("photo_".$brandid,$photoList['Data']);
                    $photolist = $photoList['Data'];
                }else{
                    $photolist = "";
                }   
            }else{
                $photolist = cache("photo_".$brandid);
            }
            //店面详情查询
            if(empty(cache("shopInfo_".$brandid))){
                $data['brandclass_id'] = $brandid;
                $shopList = sx_call("5a005e0038270",$data,'sx_mc');
                if($shopList['code'] == 200){
                    $shoplist = $shopList['data'];
                    cache("shopInfo_".$brandid,$shopList['data']);
                }else{
                    $shoplist = "";
                }
            }else{
                $shoplist = cache("shopInfo_".$brandid);
            }
            return json(array("code"=>200,"msg"=>"获取成功","data"=>array("photolist"=>$photolist,"shoplist"=>$shoplist)));
        }elseif($action == "ordertype"){//消费子类型
            $ordertypename = input("ordertypename");
            $ordertypeid = input("ordertypeid");
            $orderlist = cache("orderType");
            foreach($orderlist as $k=>$v){
                if($v['consumption_name'] == $ordertypename){
                    $ordertypeid = $orderlist[$k]["consumption_name"];
                }
            } 
            if(empty(cache("ordertype_".$ordertypeid))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_OrderTypeSet?Token=^******^&Code='.session("shop_code").'&consumptiontype='.$ordertypename;
                $dataN = "";
                $orderList = requestERP($url,$dataN);
                if($orderList['Code'] == 200){
                   cache("ordertype_".$ordertypeid,$orderList['Data']);
                    $orderlist = $orderList['Data'];
                }else{
                    $orderlist = "";
                }
            }else{
                $orderlist = cache("ordertype_".$ordertypeid);
            }
            return json(array("code"=>200,"msg"=>"获取成功","data"=>$orderlist));
        }
    }
    //--------------------------------- 开单调erp接口 新版页面，代替唤起erp直接开单 结束 ---------------------------------//

    public function getBelongShopInfo(){
        $data = input();
        $param = [
            'brandclass_id' => $data['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($param);
        return $belong;
    }
    public function getBelongShops(){
        $data = input();
        $param = [
            'brandclass_id' => $data['brandclass_id'],
            'staff_id' => session('staff_id'),
            'shop_type' => session('shop_type'),
            'shop_code' => $data['shop_code'] ? $data['shop_code'] : session('shop_code'),
            'belong_shop_code' => $data['belong_shop_code'] ? $data['belong_shop_code'] : session('belong_shop_code'),
            'belong_shop_name' => $data['belong_shop_name'] ? $data['belong_shop_name'] : session('belong_shop_name'),
        ];
        $belong = getBelongShop($param);
        return array_values($belong);
    }
    public function getShop(){
        $data = input();
        $info = controller('crm/Customer','lib')->get_shop($data);
        return $info;
    }
    public function table(){
        return $this->fetch();
    }
    //用于存储电话的guid
    public function setGuid(){
        $data = input();
        if($data['tel'] && $data['guid']){
            cache('guid_'.$data['tel'],$data['guid'],7200);
            cache('tel_'.session('staff_id'),$data['tel'],7200);
        }
    }
    //客资来电
    public function customer_call(){
        $data = input();
        $info = db('crm_c_customerinfo')->where('customer_tel|mate_tel',$data['tel'])->where('is_status',1)->order('id desc')->find();
        $this->assign('tel',$data['tel']);
        if(!empty($info)){
            $this->assign('info',$info);
            return $this->fetch('oldcustomercall');
        }else{
            //来源渠道
            $channel=controller("Customer","lib")->getChannel();
            $this->assign("channel",$channel);
            //客户来源
            $source=controller("Customer","lib")->source(array('shop_code'=>session('shop_code')));
            $this->assign("source",$source);
            //获取方式
            $accessModel=controller("Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
            $this->assign("accessModel",$accessModel);
            //消费类型
            $consumptionType=controller("Customer","lib")->consumptionType();
            $this->assign("consumptionType",$consumptionType);
            //客资地域
            $region=controller("Customer","lib")->region(array('shop_code'=>session('shop_code')));
            $this->assign("region",$region);
            $baby_sex = config('baby_sex');
            if(empty($baby_sex)){
                $baby_sex = [
                    ['sex'=>'男',],
                    ['sex'=>'女',],
                ];
            }
            $this->assign('baby_sex',$baby_sex);
            //客户标记
            $sign=controller('crm/Setting','lib')->gettrackingKmarkerList();
            $this->assign("sign",$sign);
            return $this->fetch('newcustomercall');
        }
    }
    //设置坐席在线状态
    public function callManStatus(){
        $data = input();
        $inData['status'] = $data['status'];
        $info = db('crm_s_call_man')->where('staff_id',session('staff_id'))->find();
        db()->startTrans();
        try{
            db('crm_s_call_man')->where('staff_id',session('staff_id'))->update($inData);
            db()->commit();
            session('ip',$info['ip']);
            session('port',$info['port']);
            session('user',$info['user']);
            session('pwd',$info['pwd']);
            return true;
        }catch (\Exception $e){
            db()->rollback();
            echo $e->getMessage();
            return false;
        }
    }
    //设置坐席忙闲状态
    public function callManBusySet(){
        $data = input();
        $inData['is_busy'] = $data['is_busy'];
        if ($data['is_busy']==1) {
            $inData['right_now_tel'] = $data['right_now_tel'];
        }else{
            $inData['right_now_tel'] = NULL;
        }
        db()->startTrans();
        try{
            db('crm_s_call_man')->where('staff_id',session('staff_id'))->update($inData);
            db()->commit();
            return true;
        }catch (\Exception $e){
            db()->rollback();
            echo $e->getMessage();
            return false;
        }
    }
    public function paicheng(){
        $param = input();
        $cus = db('crm_c_customerinfo')->where('id',$param['id'])->field('id,customer_name,customer_tel,customer_address,consulation_shop_code')->find();
        $this->assign('cus',$cus);
        if($cus['consulation_shop_code']){
            $data['shop_code'] = $cus['consulation_shop_code'];
            $data['work_type'] = 3;
            $info = getShopStaffs($data);
            $this->assign('info',$info);//摄影师
            $data['work_type'] = 1;
            $sales = getShopStaffs($data);
            $this->assign('sales',$sales);//销售
            $data['work_type'] = 25;
            $tech = getShopStaffs($data);
            $this->assign('tech',$tech);//导师
            $this->assign('title','排程');
        }
        // 消费类型
        $consumptionType=controller("crm/Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        //分区
        $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);
        //所有短信模板
        $smsmodel = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('status',1)->field('id,mtemplate_name')->select();
        $this->assign('model',$smsmodel);
        //当前日期
        $this->assign('pc_time',date('Y-m-d'));
        return $this->fetch();
    }
    //用于排程时查询摄影师,销售,导师
    public function getStaffs(){
        $tech = getShopStaffs(input());
        return $tech;
    }
    //排程提交
    public function paichengSub(){
        $data = input();
        $where = [];
        $sales_staff_id = db('crm_c_customerinfo')->where('id',$data['id'])->value('sales_staff_id');

        if(!$sales_staff_id) {
            return array('code' => 80, 'msg' => '没有网销，不能排程');
        }
        if($data['pc_time'] < date('Y-m-d')){
            return array('code' => 106, 'msg' => '已是过去时间,不能排程');
        }
        if($data['pc_shop_code']){
            $where['pc_shop_code'] = trim($data['pc_shop_code']);
            $whereS['shop_code'] = trim($data['pc_shop_code']);
        }
        if($data['area_id']){
            $where['area_id'] = intval($data['area_id']);
            $whereS['area_id'] = intval($data['area_id']);
        }
        else{
            $where['area_id'] = NULL;
            $whereS['area_id'] = NULL;
        }
        if($data['time']){
            $where['time'] = trim($data['time']);
            $whereS['time'] = trim($data['time']);
        }
        else{
            $where['time'] = NULL;
            $whereS['time'] = NULL;
        }
        $res = db('crm_l_pc_log')->where('cid',$data['id'])->where('pc_type',1)->where('pc_time',$data['pc_time'])->where($where)->find();
        if($res) {
            return array('code' => 101, 'msg' => '本客资此时间已排程,不能多次操作');
        }
        $todaySetting = db('crm_l_pc_setting_log')->where('pc_type',1)->where('shop_code',$data['pc_shop_code'])->where('setting_date',$data['pc_time'])->count();
        if(!$todaySetting){
            $queryDate = db('crm_l_pc_setting_log')->where('pc_type',1)->where('shop_code',$data['pc_shop_code'])->where('setting_date','<',$data['pc_time'])->order('setting_date desc')->value('setting_date');

        }else{
            $queryDate = $data['pc_time'];
        }
        $settingRow =db('crm_l_pc_setting_log')->where('pc_type',1)->where('setting_date',$queryDate)->where($whereS)->find();
        if(!$settingRow){
            if($data['time'] && $data['area_id']){
                $whereS['time'] = NULL;
                $settingRow =db('crm_l_pc_setting_log')->where('pc_type',1)->where('setting_date',$queryDate)->where($whereS)->find();
                if(!$settingRow){
                    $whereS['area_id'] = NULL;
                    $whereS['time'] = $data['time'];
                    $settingRow =db('crm_l_pc_setting_log')->where('pc_type',1)->where('setting_date',$queryDate)->where($whereS)->find();
                    if(!$settingRow){
                        $whereS['area_id'] = NULL;
                        $whereS['time'] = NULL;
                        $settingRow =db('crm_l_pc_setting_log')->where('pc_type',1)->where('setting_date',$queryDate)->where($whereS)->find();
                    }
                }
            }elseif($data['time'] && empty($data['area_id'])){
                $whereS['time'] = NULL;
                $settingRow =db('crm_l_pc_setting_log')->where('pc_type',1)->where('setting_date',$queryDate)->where($whereS)->find();
            }elseif(empty($data['time']) && $data['area_id']){
                $whereS['area_id'] = NULL;
                $settingRow =db('crm_l_pc_setting_log')->where('pc_type',1)->where('setting_date',$queryDate)->where($whereS)->find();
            }
        }

        if($settingRow){
            $num = $settingRow['num'];
            $todayTotal = db('crm_l_pc_setting_log')->where('pc_type',1)->where($whereS)->where('setting_date',$queryDate)->sum('num');
        }else{
            $num = 0;
        }
        $todayPcTotal = db('crm_l_pc_log')->where('pc_type',1)->where($where)->where('pc_time',$data['pc_time'])->count();
        if($todayPcTotal >= intval($todayTotal)){
            return array('code' => 102, 'msg' => '排程总量已达最大值或没有此排程,请核对后再操作');
        }

        if($num == 0){
            return array('code' => 103, 'msg' => '当前分区时间点无档期不能排程，请设定档期');
        }
        $whereNew['pc_shop_code'] = $settingRow['shop_code'];
        if($settingRow['area_id']) $whereNew['area_id'] = $settingRow['area_id'];
        if($settingRow['time']) $whereNew['time'] = $settingRow['time'];
        $total = db('crm_l_pc_log')->where('pc_type',1)->where('pc_time',$data['pc_time'])->where($whereNew)->count();
        if( $total >= $num){
            return array('code' => 104, 'msg' => '已达排程最大次数,不能排程');
        }
        $c_unique = db('crm_c_customerinfo')->where('id',$data['id'])->value('c_unique');

        $status = db('crm_l_pc_log')->where('c_unique',$c_unique)->where('pc_type',1)->where($whereNew)->where('consulation_type',$data['consulation_type'])->value('status');
        if($status == 2 || $status == 1){
            return array('code' => 105, 'msg' => '已有此消费类型的体验,不能排程','sql'=>db()->getLastSql());
        }
        //体验拍可重复时间设定
        $repeat_experience_day = db_config('repeat_experience_day');
        if($repeat_experience_day){
            $res = db('crm_l_pc_log')->where('c_unique',$c_unique)->where('pc_type',1)->where('status',2)->where('consulation_type',$data['consulation_type'])->order('hx_time desc')->value('hx_time');
            if(strtotime($res) >= strtotime(date('Y-m-d',strtotime("- $repeat_experience_day days")))){
                return array('code' => 104, 'msg' => '上次体验未过期,不能排程');
            }
        }
        db()->startTrans();
        try{
            $code = date('is').get_rand_string(4,1);
            $arr = [
                'cid' => $data['id'],
                'c_unique' => $c_unique,
                'shop_code' => session('shop_code'),
                'shop_name' => session('shop_name'),
                'pc_shop_code' => trim($data['pc_shop_code']),
                'pc_shop_name' => $data['pc_shop_name'] ? trim($data['pc_shop_name']) : '',
                'cameraman_id' => intval($data['cameraman_id']),
                'cameraman_name' => $data['cameraman_name'] ? trim($data['cameraman_name']) : '',
                'sale_id' => intval($data['sale_id']),
                'sale_name' => $data['sale_name'] ? trim($data['sale_name']) : '',
                'tutor_id' => intval($data['tutor_id']),
                'tutor_name' => $data['tutor_name'] ? trim($data['tutor_name']) : '',
                'remark'     => trim($data['remark']),
                'pc_time'    => trim($data['pc_time']),
                'area_id'    => $data['area_id'] ? $data['area_id'] : NULL,
                'area_name'    => $data['area_name'] ? trim($data['area_name']) : NULL,
                'time'    => $data['time'] ? trim($data['time']) : NULL,
                'code' => $code,
                'consulation_type' => $data['consulation_type'],
                'create_time' => date('Y-m-d H:i:s')
            ];
            db('crm_l_pc_log')->insert($arr);
            //crm标记预约进店
            $cData['yjd_action_day']=date('Y-m-d H:i:s');
            $cData['yjd_day']=date('Y-m-d H:i:s',strtotime($data['pc_time'].' '.date('H:i',strtotime($arr['time']))));
            $cData['consulation_shop_code'] = $data['pc_shop_code'];
            $cData['consulation_shop'] = $data['pc_shop_name'];
            db('crm_c_customerinfo')->where('id',$data['id'])->update($cData);
            //追踪记录
            $customerInfo =  db('crm_c_customerinfo')->where('id', $data['id'])->find();
            $params['customer_id'] = $data['id'];
            $params['c_unique'] = $customerInfo['c_unique'];
            $params['customer_name'] = $customerInfo['customer_name'];
            $params['c_unique'] = $customerInfo['c_unique'];
            $params['customer_number'] = $customerInfo['customer_number'];
            $params['sales_remark'] = '到店拍预约进店-'.trim($data['remark']);
            $params['sales_day'] = date('Y-m-d H:i:s',time());
            $params['sales_staff'] = session('staff_name');
            $params['sales_staff_id'] = session('staff_id');
            $params['sales_staff_number'] = session('staff_number');
            $params['shop_name'] = session('shop_name');
            $params['shop_code'] = session('shop_code');
            db('crm_c_salestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$data['id'],null);
            //短信
            if($data['model_id']){
                $send_msg = db('crm_s_message_templateinfo')->where('id',$data['model_id'])->value('mtemplate_content');
                $send_msg .= ',店面：'.$data['pc_shop_name'];
                if($arr['area_name']){
                    $send_msg .= ',分区：'.$arr['area_name'];
                }else{
                    $send_msg .= ',分区：任意分区；';
                }
                if($arr['time']){
                    $a = substr($arr['time'],0,2);
                    $b = substr($arr['time'],2,4);
                    $send_msg .= ',时间点：'.$a.':'.$b;
                }else{
                    $send_msg .= ',时间点：任意时间点；';
                }
                $sms = db_config('sms_'.session('shop_code'));//短信账号
                $param = [
                    'ids' =>$data['id'],//客资id
                    'model_id' => $data['model_id'],//模板id
                    'send_msg' => $send_msg,//发送的模板内容
                    'send_config' => $sms,//短信账号
                ];
                controller('Customer','lib')->send_message($param);
            }
            action_log($arr,[],$data['id'],session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'排程成功','data'=>'','time'=>date('Y-n-j',strtotime($data['pc_time'])));
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'排程失败','data'=>$e->getMessage());
        }
    }
    //删除排程
    public function delPaicheng(){
        $id = input('param.id');
        $info = db('crm_l_pc_log')->where('id',$id)->where('pc_type',1)->find();
        if($info['status'] != 1){
            return array('code'=>101,'msg'=>'只有未上门的排程可以删除。');
        }
        if($info['cameraman_name'] || $info['tutor_name']){
            $return['code'] = 102;
            $return['msg']  = '已安排上门人员，不允许删除，请改期。';
            return $return;
        }
        db()->startTrans();
        try{
            db('crm_l_pc_log')->where('id',$id)->update(['is_delete'=>1]);
            action_log($id,$info,$info['cid'],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 pcLogJSON(){
        $data = input();
        $limit = $data['limit'] ? $data['limit'] : 10;
        $page = $data['page'] ? $data['page'] : 1;
        $pc_time = $data['pc_time'] ? $data['pc_time'] : date('Y-m-d');
        $where = [];
        if($data['area_id']){
            $where['f.area_id'] = intval($data['area_id']);
            $whereL['area_id'] = intval($data['area_id']);
        }
        // else{
        //     $where['f.area_id'] = NULL;
        //     $whereL['area_id'] = NULL;
        // }
        if($data['time']){
            $where['f.time'] = intval($data['time']);
            $whereL['time'] = intval($data['time']);
        }
        if($data['customer_name']){
            $where['c.customer_name'] = trim($data['customer_name']);
        }
        if($data['customer_tel']){
            $where['c.customer_tel'] = trim($data['customer_tel']);
        }
        // else{
        //     $where['f.time'] = NULL;
        //     $whereL['time'] = NULL;
        // }
        $result['code'] = 0;
        $result['msg'] = '';
        $result['data'] = db('crm_l_pc_log')->alias('f')->join('crm_c_customerinfo c','f.cid=c.id')->where('f.pc_time',$pc_time)->where('f.pc_shop_code',$data['pc_shop_code'])->where('f.pc_type',1)->where('f.is_delete',2)->field('f.id,c.customer_name,c.customer_tel,f.remark,c.customer_address,f.cameraman_name,f.sale_name,f.tutor_name,f.pc_shop_name,f.area_name,f.time,f.code,f.result,c.is_success,f.status')->where($where)->limit($limit)->page($page)->select();
        $result['count'] = db('crm_l_pc_log')->alias('f')->join('crm_c_customerinfo c','f.cid=c.id')->where('f.pc_time',$pc_time)->where('f.pc_shop_code',$data['pc_shop_code'])->where('f.pc_type',1)->where('f.is_delete',2)->where($where)->count();
        return json($result);
    }
    //日历中的排程次数
    public function paichengNum(){
        $data = input();
        $month = $data['month'] ? date('Y-m',strtotime($data['month'])) : date('Y-m');
        $shop_code = $data['shop_code'] ? trim($data['shop_code']) : session('shop_code');
        if($data['area_id']){
            $where['area_id']  = intval($data['area_id']);
        }
        // else{
        //     $where['area_id']  = NULL;
        // }
        if($data['time']){
            $where['time']  = intval($data['time']);
        }
        // else{
        //     $where['time']  = NULL;
        // }
        //已排 次数
        $pcInfo = db('crm_l_pc_log')->where('pc_time','like',$month.'-%')->where('pc_type',1)->where('is_delete',2)->where('pc_shop_code',$shop_code)->where($where)->group('pc_time')->order('pc_time')->column('count(id)','pc_time');
        //排程设定
        $info = db('crm_l_pc_setting_log')->where('setting_date','like',$month.'-%')->where('pc_type',1)->where('shop_code',$shop_code)->where($where)->group('setting_date')->order('setting_date')->column('sum(num)','setting_date');

        if($info){
            $thisFirstKey = key($info);
            $thisFirst = $info[$thisFirstKey];
        }

        if(empty($thisFirst)){
            $temp = db('crm_l_pc_setting_log')->where('setting_date','<',$thisFirstKey)->where('pc_type',1)->where($where)->where('shop_code',$shop_code)->group('setting_date')->order('setting_date desc')->column('sum(num)','setting_date');
        }else{
            $temp = db('crm_l_pc_setting_log')->where('setting_date','<',$month.'-01')->where('pc_type',1)->where($where)->where('shop_code',$shop_code)->group('setting_date')->order('setting_date desc')->column('sum(num)','setting_date');
        }
        $temp = end($temp);

        $prev = 0;
        if($thisFirstKey != $month.'-01' && $temp){
            $prev = $temp;
        }
        $days = date("t",strtotime($month));
        $return = [];
        $ret = [];
        for($i=0;$i<$days;$i++){
            $date = date('Y-m-d',strtotime($month)+$i*86400);
            if($info[$date]){
                $ret['num'] = $info[$date];
                $prev = $info[$date];
            }else{
                $ret['num'] = $prev;
            }

            $ret['date'] = date('Y-n-j',strtotime($month)+$i*86400);

            $ret['pc'] = $pcInfo[$date] ? $pcInfo[$date] : 0;
            $return[] = $ret;

        }
        return $return;
    }
    //获取剩余排程数量
    public function getOverNum(){
        $data = input();
        $where = [];
        $whereL = ' 1=1 ';//[];
        if($data['shop_code']){
            $where['shop_code'] = $data['shop_code'];
            //$whereL['pc_shop_code'] = $data['shop_code'];
            $whereL .= ' and pc_shop_code = \''.$data['shop_code'].'\' ';
        }else{
            return  '请选择店面。';
        }
        if($data['month']){
            $where['setting_date'] = $data['month'];
            //$whereL['pc_time'] = [$data['month']];
            $whereL .= ' and (pc_time is null or pc_time = \''.$data['month'].'\')';
        }
        
        if($data['area_id']){
            $where['area_id'] = $data['area_id'];
            //$whereL['area_id'] = $data['area_id'];
            $whereL .= ' and (area_id is null or area_id = \''.$data['area_id'].'\')';
        }
        // else{
        //     $where['area_id'] = NULL;
        //     $whereL['area_id'] = NULL;
        // }
        if($data['time']){
            $where['time'] = $data['time'];
           // $whereL['time'] = $data['time'];
            $whereL .= ' and (time is null or time = \''.$data['time'].'\')';
        }
        $sett = db('crm_l_pc_setting_log')->where($where)->where('pc_type',1)->select();

        if(empty($sett)){
            unset($where['setting_date']);
            $sett = db('crm_l_pc_setting_log')->where($where)->where('pc_type',1)->where('setting_date','<',$data['month'])->order('setting_date desc')->select();
        }
        $log = db('crm_l_pc_log')->where($whereL)->where('pc_type',1)->where('is_delete',2)->select();
        //echo db()->getLastSql();die;
        // print_r($log);die;
        foreach ($log as $k=> $v) {
            foreach($sett as $kk=>$vv){
                if(!empty($v['area_name']) 
                    && $v['area_name'] == $vv['area_name'] 
                    && $v['time'] == $vv['time']
                    && !empty($v['time']) 
                ){
                    //两个都符合且不为空
                    if($vv['num'] <= $vv['dec']){
                        continue;
                    }
                    $sett[$kk]['dec'] = $vv['dec']>0?$sett[$kk]['dec'] + 1 : 1;
                    break;
                }elseif(empty($v['area_name'])
                    &&($v['time'] == $vv['time']|| empty($vv['time'])) && empty($vv['area_name'])
                ){
                    if($vv['num'] <= $vv['dec']){
                        continue;
                    }
                    $sett[$kk]['dec'] = $vv['dec']>0?$sett[$kk]['dec'] + 1 : 1;
                    break;
                }elseif(empty($v['time'])
                    &&($v['area_name'] == $vv['area_name'] || empty($vv['area_name'])) && empty($vv['time'])
                ){
                    if($vv['num'] <= $vv['dec']){
                        continue;
                    }
                    $sett[$kk]['dec'] = $vv['dec']>0?$sett[$kk]['dec'] + 1 : 1;
                    break;
                }elseif(
                    empty($vv['area_name']) &&  empty($vv['time'])
                ){
                    if($vv['num'] <= $vv['dec']){
                        continue;
                    }
                    $sett[$kk]['dec'] = $vv['dec']>0?$sett[$kk]['dec'] + 1 : 1;
                    break;
                }elseif(
                empty($vv['area_name'])
                ){
                    if($v['time'] != $vv['time']){
                        continue;
                    }
                    $sett[$kk]['dec'] = $vv['dec']>0?$sett[$kk]['dec'] + 1 : 1;
                    break;
                }elseif(
                empty($vv['time'])
                ){
                    if($v['area_name'] != $vv['area_name']){
                        continue;
                    }
                    $sett[$kk]['dec'] = $vv['dec']>0?$sett[$kk]['dec'] + 1 : 1;
                    break;
                }
            }
        }
        $str = '';
        $day = '';
        foreach($sett as $k=>$v){
            if($day != '' && $v['setting_date'] != $day){
                continue;
            }
            $day = $v['setting_date'];
            if($v['area_id']){
                $str .= '分区：'.$v['area_name'].',';
                if($v['time']){
                    $str .= '时间点：'.$v['time'].',';
                }else{
                    $str .= '任意时间，';
                }
                $shenyu = $v['num']>$v['dec']?$v['num']-$v['dec']:0;
                $str .= ' 余 '.$shenyu.' 个   █   ';
            }else{
                $str .= '无分区 '.',';
                if($v['time']){
                    $str .= '时间点：'.$v['time'].',';
                }else{
                    $str .= '任意时间，';
                }
                $shenyu = $v['num']>$v['dec']?$v['num']-$v['dec']:0;
                $str .= ' 余 '.$shenyu.' 个   █   ';
            }
        }
        return $str;
    }

    // 预约进店排程数量查询  当前月 每日总量及排程量  +  当前日期的明细数据 eric 190126
    public function yjdCtrlMonth(){
        $data = input();
        $day = $data['day'] ? date('Y-m-d',strtotime($data['day'])) : date('Y-m-d');
        $month = $data['day'] ? date('Y-m',strtotime($data['day'])) : date('Y-m');
        $shop_code = $data['shop_code'] ? trim($data['shop_code']) : session('shop_code');

        // 设定数量
        $month_data_set = db('crm_l_yjd_ctrl')
            ->where('is_del', 1)->where('shop_code', $shop_code)
            ->where('use_day','like',$month.'%')
            ->order('use_day')->group('use_day')
            ->column('sum(num) as set_num','use_day');
            // ->select();
        // 实际数量
        $temp = db('crm_c_customer_intostore')
            ->where('consulation_shop_code', $shop_code)->where('status',1)->where('yjd_day','like',$month.'%')
            ->group('day')
            ->field('count(*) as real_num,DATE_FORMAT(yjd_day,"%Y-%m-%d") as `day`')
            ->select();
        // echo db()->getLastSql();
        // exit;
        $month_data_real = [];
        foreach ($temp as $key => $value) {
            $month_data_real[$value['day']] = $value['real_num'];
        }
        unset($temp);
        // 当月时间
        $m_start= date('Y-m-01',strtotime($month));
        $m_end  = date('Y-m-d',strtotime("$m_start +1 month -1 day"));
        $m_area = getDateFromRange($m_start,$m_end);

        $month_data = [];
        foreach ($m_area as $key => $value) {
            // 月日 去掉0
            $month_data[$key]['day'] = date('Y-n-j',strtotime($value));
            $month_data[$key]['set_num'] = $month_data_set[$value] ? $month_data_set[$value] : 0;
            $month_data[$key]['real_num']= $month_data_real[$value] ? $month_data_real[$value] : 0;
        }
        // var_dump($month_data);
        // exit;
        $return['month']= $month_data;
        unset($month_data_set,$month_data_real,$month_data);
        return $return;
    }
    public function yjdCtrlDay(){
        $data = input();
        $day = $data['day'] ? date('Y-m-d',strtotime($data['day'])) : date('Y-m-d');
        $month = $data['day'] ? date('Y-m',strtotime($data['day'])) : date('Y-m');
        $shop_code = $data['shop_code'] ? trim($data['shop_code']) : session('shop_code');
        // 当前日期 设定
        $day_data_set = db('crm_l_yjd_ctrl')
            ->where('is_del', 1)->where('shop_code', $shop_code)->where('use_day',$day)
            ->order('time_area')
            ->column('time_area,num,start,end','time_area');
            // ->select();
        // echo db()->getLastSql();die;
        // var_dump($day_data_set);
        // exit;
        // 当前日期 实际数量
        $day_data_real = db('crm_l_yjd_ctrl')->alias('c')
            ->join('crm_c_customer_intostore i', 'DATE_FORMAT(i.yjd_day, "%H:%i:%S") >= c.`start` AND DATE_FORMAT(i.yjd_day, "%H:%i:%S") < c.`end` AND c.use_day= DATE_FORMAT(i.yjd_day, "%Y-%m-%d")', 'left')
            ->where('c.is_del', 1)->where('c.shop_code', $shop_code)->where('c.use_day',$day)
            ->order('c.time_area')
            ->group('c.time_area')
            ->column('count(i.yjd_day) AS real_num','c.time_area');
            // ->select();
        // echo db()->getLastSql();
        // var_dump($day_data_real);
        // exit;
        $day_data = [];
        foreach ($day_data_set as $key => $value) {
            $temp['time_area'] = $key;
            $temp['set']  = $value['num'];
            $temp['real'] = $day_data_real[$key];
            array_push($day_data,$temp);
        }
        $return['day']= $day_data;
        unset($day_data_set,$day_data_real,$day_data);
        return $return;
    }
    public function jieshao_search(){
        $search = input('param.search');
        $intro=controller("Customer","lib")->customerNameSearch($search);
        return $intro;
    }
    // 删除自定义列
    public function delSalfColumn(){
        db()->startTrans();
        try{
            db('crm_s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->delete();
            cache('colColumn_'.session('staff_id').'_'.session('shop_type'),null);
            cache('colNames_'.session('staff_id').'_'.session('shop_type'),null);
            cache('colModel_'.session('staff_id').'_'.session('shop_type'),null);
            db()->commit();
            return array('code'=>200,'msg'=>'删除成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'删除失败','data'=>$e->getMessage());
        }
    }
    //查询小组下员工
    public function getStaffByGroupId(){
        $data = input();
        // 0606
        $mc = new \app\common\lib\mcInterface();
        $info = $mc->getStaffInfoByGid(array('group_id' => $data['group_id']));
        unset($mc);
        // $info = db('c_staff_group_relation')->where('group_id',$data['group_id'])->select();
        return $info;
    }
    //通过活动名称查询介绍人
    public function searchIntroducerName(){
        $data = input('post.');
        $where = [];
        if($data['channel_plan_number']){
            $where['channel_plan_number'] = trim($data['channel_plan_number']);
        }
        if($data['dj_staff']){
            $where['dj_staff'] = trim($data['dj_staff']);
        }
        $info = db('crm_c_customerinfo')->where($where)->where('introducer_name is not null or introducer_name<>""')->group('introducer_name')->field('introducer_name')->select();
        if(!empty($info)){
            return $info;
        }else{
            return false;
        }
    }
    //通过活动名称查询录入人
    public function searchDjName(){
        $data = input('post.');
        $where = [];
        if($data['channel_plan_number']){
            $where['channel_plan_number'] = trim($data['channel_plan_number']);
        }
        if($data['dj_staff_id']){
            $where['dj_staff_id'] = intval($data['dj_staff_id']);
        }
        $info = db('crm_c_customerinfo')->where($where)->group('dj_staff')->select();
        if(!empty($info)){
            return $info;
        }else{
            return false;
        }
    }
    //活动客资明细
    public function hd_customerList(){
        $data = input();
        $start = $data['start'] ? date('Y-m-d 00:00:00',strtotime($data['start'])) : '';
        $end = $data['end'] ? date('Y-m-d 23:59:59',strtotime($data['end'])) : '';
        $limit = $data['limit'] ? intval($data['limit']) : 10;
        $page = $data['page'] ? intval($data['page']) : 1;
        if(empty($start) || empty($end)){
            return array('code'=>100,'msg'=>'请选择时间');
        }
        $where = [];
        if($data['dj_staff']) $where['c.dj_staff'] = trim($data['dj_staff']);
        if($data['hd_name']) $where['c.channel_plan_number'] = trim($data['hd_name']);
        if($data['introducer_name']){
            $where['c.introducer_name'] = trim($data['introducer_name']);
        }else{
            $sql = " c.introducer_name = :introducer_name or c.introducer_name = '' or c.introducer_name is null";
            $arr['introducer_name']    = trim($data['dj_staff']);
        }
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_c_customerinfo')->alias('c')
            ->where($where)
            ->where('c.dj_day','between',[$start,$end])
            ->where($sql,$arr)
            ->order('c.dj_staff,c.introducer_name')
            ->field('c.id,c.customer_name,c.customer_tel,is_fp,c.sales_staff,is_valid,is_intostore,is_success')
            ->page($page)->limit($limit)
            ->select();
        foreach($res as $k=>$v){
            $res[$k]['is_valid'] = getIsValidAttr($v['is_valid']);
            $res[$k]['is_fp'] = getIsFP($v['is_fp']);
            $res[$k]['is_success'] = getIsSuccess($v['is_success']);
            $res[$k]['is_intostore'] = getIsIntostore($v['is_intostore']);
        }
        $count = db('crm_c_customerinfo')->alias('c')
            ->where($where)
            ->where('c.dj_day','between',[$start,$end])
            ->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //修改排程备注
    public function editPcRemark(){
        $data = input();
        $old = db('crm_l_pc_log')->where('id',intval($data['id']))->find();
        try{
            db('crm_l_pc_log')->where('id',intval($data['id']))->update($data);
            action_log($data,$old,$old['cid'],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 customerPersonalDetail(){
        $data = input();
        $start = $data['start'] ? date('Y-m-d 00:00:00',strtotime($data['start'])) : '';
        $end = $data['end'] ? date('Y-m-d 23:59:59',strtotime($data['end'])) : '';
        $limit = $data['limit'] ? intval($data['limit']) : 10;
        $page = $data['page'] ? intval($data['page']) : 1;
        if(empty($start) || empty($end)){
            return array('code'=>100,'msg'=>'请选择时间');
        }
        $where = [];
        if($data['sales_staff_id']) $where['sales_staff_id'] = trim($data['sales_staff_id']);
        $where['shop_code'] = $data['shop_code'];
        $result['code'] = 0;
        $result['msg'] = '';
        $res = db('crm_c_customerinfo')
            ->where($where)
            ->where('jr_day','between',[$start,$end])
            ->order('jr_day desc')
            ->field('id,customer_name,customer_tel,sales_staff,is_valid,is_intostore,is_success')
            ->select();
        foreach($res as $k=>$v){
            $res[$k]['is_valid'] = getIsValidAttr($v['is_valid']);
            $res[$k]['is_fp'] = getIsFP($v['is_fp']);
            $res[$k]['is_success'] = getIsSuccess($v['is_success']);
            $res[$k]['is_intostore'] = getIsIntostore($v['is_intostore']);
        }
        $count = db('crm_c_customerinfo')
            ->where($where)
            ->where('jr_day','between',[$start,$end])
            ->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($result);
    }
    //获取某一工作类型下的人员

    
    /**
     * 查询预约进店的客资 页面，参考erp进客
     * @return  view
     * @author  lilong<lilong@suxuantech.cn>
     */
    public function yjdSearch(){
        //意向店面
        $intentionShop=controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id'),'is_marketing'=>2]);
        $this->assign('intentionShop',$intentionShop);
        // 消费类型
        $consumptionType=controller("crm/Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        // 客户意向
        $intention=controller("crm/Customer","lib")->intention(array('shop_code'=>session('shop_code')));
        $this->assign("intention",$intention);
        // 客户来源
        $source=controller("crm/Customer","lib")->source(array('shop_code'=>session('shop_code')));
        $this->assign('cource', $source);
        // 渠道名称
        $channel=controller("crm/Customer","lib")->getChannel();
        $this->assign("channel",$channel);
        // var_dump($channel);exit;
        return $this->fetch();
    }

    /**
     * 查询预约进店的客资 数据，参考erp进客
     * @param   yjd_start              预约进店开始时间
     * @param   yjd_end                预约进店结束时间
     * @param   consulation_shop       意向店面
     * @param   reception_name         门市
     * @param   consultation_type      消费类型
     * @param   customer_intention     客户意向
     * @param   customer_cource        客户来源
     * @param   customer_channel       渠道名称
     * @param   keyword                姓名/手机号
     *
     * @return  json
     * @author  lilong<lilong@suxuantech.cn>
     */
    public function yjdSearchJson(){
        $data = input();

        $page = $data['page'] ? (int)$data['page'] : 1;
        $limit= $data['limit'] ? (int)$data['limit'] : 50;
        $keyword = trim($data['keyword']);

        // 意向店面
        if ($data['intentionShop']) {
            $shop_codes = $data['intentionShop'];
        }else{
            //意向店面
            $intentionShop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id'),'is_marketing'=>2]);
            $shop_codes = '';
            foreach ($intentionShop as $key => $value) {
                $shop_codes .= $value['shop_code'].',';
            }
            $shop_codes = trim($shop_codes, ',');
        }

        $table = isTableExist('crm_c_customer_intostore');
        // 如果进店表不存在 直接查客资
        if (!$table) {
            $where['is_status'] = 1;
            if ((int)$data['consumptionType']) {
                $where['consultation_type_id'] = (int)$data['consumptionType'];
            }
            // 客户意向
            if ((int)$data['intention']) {
                $where['customer_intention_id'] = (int)$data['intention'];
            }
            // 客户来源
            if ((int)$data['cource']) {
                $where['customer_cource_id'] = (int)$data['cource'];
            }
            // 渠道名称
            if ((int)$data['channel']) {
                $where['customer_channel_id'] = (int)$data['channel'];
            }

            // 预计进店时间
            if ($data['start_time']) {
                $yjds = ' yjd_day>="'.date('Y-m-d 00:00:00',strtotime($data['start_time'])).'"';
            }else{
                $yjds = ' yjd_day>="'.date('Y-m-d 00:00:00').'"';
            }
            if ($data['end_time']) {
                $yjde = ' yjd_day<="'.date('Y-m-d 23:59:59',strtotime($data['end_time'])).'"';
            }else{
                $yjde = ' yjd_day<="'.date('Y-m-d 23:59:59').'"';
            }

            if ($keyword) {
                unset($data,$yjds,$yjde);
                $sql = 'customer_name LIKE "%'.$keyword.'%" OR customer_tel LIKE "%'.$keyword.'%"';
            }
            $info = db('crm_c_customerinfo i')
                ->where('consulation_shop_code', 'in', $shop_codes)
                ->where($where)
                ->where($yjds)
                ->where($yjde)
                ->where($sql)
                ->field('id,id as cid,yjd_day,syjd_day,consulation_shop,reception_name,is_intostore,op_signinfo,op_signday,intostore_note as intostore_remark,customer_name,customer_sex,customer_tel,customer_wechat,customer_qq,mate_name,mate_sex,mate_tel,mate_wechat,mate_qq,customer_address,consultation_type,customer_intention,customer_cource,customer_channel,dj_staff,sales_staff,fact_money,totalpay_money')
                ->order('yjd_day desc,id asc')
                ->page($page)
                ->limit($limit)
                ->select();
            $count = db('crm_c_customerinfo i')
                ->where('consulation_shop_code', 'in', $shop_codes)
                ->where($where)
                ->where($yjds)
                ->where($yjde)
                ->where($sql)
                ->count();
            // echo db()->getLastSql();die;

            $returnData['code'] = 0;
            $returnData['msg']  = '';
            $returnData['count']= $count;
            $returnData['data'] = $info;
            unset($info,$where,$sql,$yjds,$yjde,$data);
            return json($returnData);
        }

        // 预计进店时间
        if ($data['start_time']) {
            $yjds = ' i.yjd_day>="'.date('Y-m-d 00:00:00',strtotime($data['start_time'])).'"';
        }else{
            $yjds = ' i.yjd_day>="'.date('Y-m-d 00:00:00').'"';
        }
        if ($data['end_time']) {
            $yjde = ' i.yjd_day<="'.date('Y-m-d 23:59:59',strtotime($data['end_time'])).'"';
        }else{
            $yjde = ' i.yjd_day<="'.date('Y-m-d 23:59:59').'"';
        }

        if ($keyword) {
            unset($data,$yjds,$yjde);
            $sql = 'c.customer_name LIKE "%'.$keyword.'%" OR c.customer_tel LIKE "%'.$keyword.'%"';
        }
        $where['c.is_status'] = 1;
        $where['i.status'] = 1;

        // 门市
        // if ((int)$data['reception']) {
        //     $where['c.reception_id'] = (int)$data['reception'];
        // }
        // 消费类型
        if ((int)$data['consumptionType']) {
            $where['c.consultation_type_id'] = (int)$data['consumptionType'];
        }
        // 客户意向
        if ((int)$data['intention']) {
            $where['c.customer_intention_id'] = (int)$data['intention'];
        }
        // 客户来源
        if ((int)$data['cource']) {
            $where['c.customer_cource_id'] = (int)$data['cource'];
        }
        // 渠道名称
        if ((int)$data['channel']) {
            $where['c.customer_channel_id'] = (int)$data['channel'];
        }

        $info = db('crm_c_customer_intostore i')
            ->join('crm_c_customerinfo c','c.id=i.cid','LEFT')
            ->where('i.consulation_shop_code', 'in', $shop_codes)
            ->where($where)
            ->where($yjds)
            ->where($yjde)
            ->where($sql)
            ->field('i.id,i.cid,i.yjd_day,i.syjd_day,i.consulation_shop_name,i.reception_name,i.is_intostore,i.intostore_remark,c.customer_name,c.customer_sex,c.customer_tel,c.customer_wechat,c.customer_qq,c.mate_name,c.mate_sex,c.mate_tel,c.mate_wechat,c.mate_qq,c.customer_address,c.consultation_type,c.customer_intention,c.customer_cource,c.customer_channel,c.op_signinfo,c.op_signday,c.dj_staff,c.sales_staff,c.fact_money,c.totalpay_money')
            ->order('i.yjd_day desc,i.cid asc')
            ->page($page)
            ->limit($limit)
            ->select();
        $count = db('crm_c_customer_intostore i')
            ->join('crm_c_customerinfo c','c.id=i.cid','LEFT')
            ->where('i.consulation_shop_code', 'in', $shop_codes)
            ->where($where)
            ->where($yjds)
            ->where($yjde)
            ->where($sql)
            ->count();
        $weekArray = array("日","一","二","三","四","五","六");
        $intoArray = array("","未进店","进店进客","进店非进客","邀约未进店","进店未成交");
        foreach ($info as $key => $value) {
            // 进店状态 1未进店； 2进店进客；3进店非进客；4：邀约未进店（爽约）；5：进店未成交（流失）',
            $info[$key]['is_intostore'] = $intoArray[$value['is_intostore']];
            //日期和时间分开
            $info[$key]['s_yjd_day'] = date('Y-m-d', strtotime($value['yjd_day']));
            $info[$key]['s_yjd_time']= date('H:i', strtotime($value['yjd_day']));
            // 星期
            $info[$key]['week'] = '星期'.$weekArray[date('w',strtotime($value['yjd_day']))];
        }
        // echo db()->getLastSql();die;
        $returnData['code'] = 0;
        $returnData['msg']  = '';
        $returnData['count']= $count;
        $returnData['data'] = $info;
        unset($info,$where,$sql,$yjds,$yjde,$data);
        return json($returnData);
    }
    //奖金标记
    public function customerBonus(){
        $param = input();
        if(empty($param['id'])){
            return array('code'=>100,'msg'=>'未选择要标记的客资');
        }
        if(empty($param['bonus'])){
            return array('code'=>101,'msg'=>'未选择要标记的奖金状态');
        }
        $id = explode(',',$param['id']);
        $log = [];
        for($i=0;$i<=count($id);$i++){
            $log[$i]['module']     = 'crm';
            $log[$i]['controller'] = 'Customer';
            $log[$i]['action']     = 'customerBonus';
            $log[$i]['old_data']   = [];
            $log[$i]['data']       = $param['bonus'] == 1 ? 'A客奖金：已发' : 'A客奖金：未发';
            $log[$i]['customer_id']=$id[$i];
            $log[$i]['staff_name'] = session('staff_name');
            $log[$i]['staff_id']   = session('staff_id');
            $log[$i]['ip']         = get_client_ip();
            $log[$i]['create_time']= date('Y-m-d');
        }
        db()->startTrans();
        try{
            db('crm_c_customerinfo')->where('id','in',$param['id'])->update(['bonus'=>$param['bonus']]);

            //操作日志
            db('crm_action_log','db_logs')->insertAll($log);
            db()->commit();
            return array('code'=>200,'msg'=>'标记奖金状态成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>103,'msg'=>'标记奖金状态失败','data'=>$e->getMessage());
        }
    }
     //成交奖金
    public function customerBonusDeal(){
        $param = input();
        if(empty($param['id'])){
            return array('code'=>100,'msg'=>'未选择要标记的客资');
        }
        if(empty($param['bonus_deal'])){
            return array('code'=>101,'msg'=>'未选择要标记的奖金状态');
        }
        $id = explode(',',$param['id']);
        $log = [];
        for($i=0;$i<=count($id);$i++){
            $log[$i]['module']     = 'crm';
            $log[$i]['controller'] = 'Customer';
            $log[$i]['action']     = 'customerBonusDeal';
            $log[$i]['old_data']   = [];
            $log[$i]['data']       = $param['bonus_deal'] == 1 ? '成交奖金：已发' : '成交奖金：未发';
            $log[$i]['customer_id']=$id[$i];
            $log[$i]['staff_name'] = session('staff_name');
            $log[$i]['staff_id']   = session('staff_id');
            $log[$i]['ip']         = get_client_ip();
            $log[$i]['create_time']= date('Y-m-d');
        }
        db()->startTrans();
        try{
            db('crm_c_customerinfo')->where('id','in',$param['id'])->update(['bonus_deal'=>$param['bonus_deal']]);

            //操作日志
            db('crm_action_log','db_logs')->insertAll($log);
            db()->commit();
            return array('code'=>200,'msg'=>'成交奖金状态成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>103,'msg'=>'成交奖金状态失败','data'=>$e->getMessage());
        }
    }
    //获取员工事业部下可操作店
    public function getBrandActionShop(){
        $data = input();
        $p = [
            'staff_id'=> session('staff_id'),
            'brandclass_id'=> $data['brandclass_id'],
            'shop_type' => session('shop_type')
        ];
        $djshops = getShops($p);//可操作店
        return array_values($djshops);
    }
    /*---------上门拍----------start--------------*/
    public function Smpaicheng(){
        $param = input();
        $cid = (int)$param['id'];
        $cus = db('crm_c_customerinfo')->where('id',$cid)->field('id,customer_name,customer_tel,customer_address,consulation_shop_code,consultation_type,sales_staff_id,province_id,province,city_id,city,county_id,county,baby_address,ready_baby_day,baby_birthday')->find();
        $this->assign('cus',$cus);
        $sys_sales = db_config('is_sm_not_wx');
        if(($sys_sales != 1) && !$cus['sales_staff_id']) {
            $return=array('error'=>'1','msg'=>'没有网销，不能预约上门');
            return json($return);
        }
        // 上门订单
        $smOrder = db('c_customerorder')->alias('o')
            ->join('c_customerphoto p','o.orderId=p.photodate','left')
            ->where('o.crm_customer_id',$cid)->where("p.photodate='' OR p.photodate IS NULL")->group('o.orderId')
            ->field('o.orderId,o.payment_money,o.total_money')->select();
        $this->assign("smOrder",$smOrder);
        //出生医院
        $hos = controller('crm/Customer','lib')->getHospital();
        $this->assign("hospital",$hos);

        $data['shop_code'] = session('shop_code');
        $data['work_type'] = 3;
        $info = getShopStaffs($data);
        $this->assign('info',$info);//摄影师
        $data['work_type'] = 1;
        $sales = getShopStaffs($data);
        $this->assign('sales',$sales);//销售
        $data['work_type'] = 25;
        $tech = getShopStaffs($data);
        $this->assign('tech',$tech);//导师
        $this->assign('title','排程');
        //拍照店
        $shop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id'),'is_door'=>1]);
        $default_pc_shop_code = $cus['consulation_shop_code'] ? $cus['consulation_shop_code'] : session('shop_code');
        foreach ($shop as $key => $value) {
            if ($value['shop_code'] == $default_pc_shop_code) {
                $shop[$key]['selected'] = 1;
            }
        }
        $this->assign('shop',$shop);
        //消费类型
        $consumptionType=controller("Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        //所有短信模板
        $mc = new \app\common\lib\mcInterface();
        $smsmodel =  $mc->getSMSModel();
        $this->assign('model',$smsmodel);
        //当前日期
        $this->assign('pc_time',date('Y-m-d'));
        //上门类型
        $type = db('crm_s_pc_type_set')->where('status',2)->select();
        if(empty($type)){
            $type = [
                0=>['sm_type'=>'拍摄'],
                1=>['sm_type'=>'理发'],
                2=>['sm_type'=>'售后'],
                3=>['sm_type'=>'其它']
            ];
        }
       
        $this->assign('type',$type);
        //省市县
        $addr['type'] = 1;
        $province = controller('crm/Customer','lib')->address($addr);
        $this->assign('province',$province);
        if($cus['province_id']){
            $addr['type'] = 2;
            $addr['pid'] = $cus['province_id'];
            $city = controller('crm/Customer','lib')->address($addr);
            $this->assign('city',$city);
            if($cus['city_id']){
                $addr['type'] = 3;
                $addr['pid'] = $cus['city_id'];
                $county = controller('crm/Customer','lib')->address($addr);
                $this->assign('county',$county);
            }
        }
        if(customize('nnqqbaby')){
            $this->assign('smcloth',(array)config('smcloth'));
        }
        return $this->fetch();
    }
    //排程提交
    public function SmpaichengSub(){
        $data = input();
        /*if(empty($data['street_id'])){
            return array('code' => 101, 'msg' => '没有地址,不能排程');
        }*/
        $shop_code = trim($data['pc_shop_code']);
        $sales_staff_id = db('crm_c_customerinfo')->where('id',$data['id'])->value('sales_staff_id');
        $sm_type = $data['sm_type'];
        // if(!$sales_staff_id) {
        //     return array('code' => 80, 'msg' => '没有网销，不能排程');
        // }
        $sys_sales = db_config('is_sm_not_wx');
        if(($sys_sales != 1) && !$sales_staff_id) {
            return array('code' => 80, 'msg' => '没有网销，不能排程');
        }
        if(!$data['pc_shop_code']) {
            return array('code' => 90, 'msg' => '没有服务店面，不能排程');
        }
        if($data['pc_time'] < date('Y-m-d')){
            return array('code' => 106, 'msg' => '已是过去时间,不能排程');
        }

        $num = db('crm_l_pc_setting_log')->where('pc_type',2)->where('sm_type',$sm_type)->where('setting_date',$data['pc_time'])->where('shop_code',$shop_code)->find();
        if(empty($num) || $num['num'] === 0){
            return array('code' => 103, 'msg' => '无档期不能排程，请设定档期');
        }
        $num = $num['num'];
        // 预约上门的服务订单(网销开的)
        $sm_order = trim($data['sm_order']);
        if ($sm_order) {
            $smOrderCount = db('c_customerorder')->where('orderId',$sm_order)->where('crm_customer_id',(int)$data['id'])->count();
            if (!$smOrderCount) {
                return array('code'=>100, 'msg'=>'未找到上门订单：'.$sm_order.'，请确认。', 'sql'=>db()->getLastSql());
            }
        }

        $hisWhere['status']   = 1;
        $hisWhere['pc_type']  = 2;
        $hisWhere['is_delete']= 2;
        $hisWhere['pc_shop_code']= $shop_code;
        $hisWhere['cid']      = $data['id'];
        $hisWhere['sm_type']  = $data['sm_type'];
        $history = db('crm_l_pc_log')->where($hisWhere)->order('id desc')->find();
        // var_dump($history);die;
        if($history){
            return array('code' => 101, 'msg' => $history['pc_time'].',类型为：'.$history['sm_type'].'的排程未结束,不能排程','sql'=>db()->getLastSql());
        }
        $todayPcTotal = db('crm_l_pc_log')->where('pc_type',2)->where('sm_type',$sm_type)->where('pc_time',$data['pc_time'])->where('is_delete',2)->where('pc_shop_code',$shop_code)->count();

        if(($num > 0) && ($todayPcTotal >= $num)){
            return array('code' => 102, 'msg' => '排程总量已达最大值,不能排程','sql'=>db()->getLastSql());
        }
        $c_unique = db('crm_c_customerinfo')->where('id',$data['id'])->value('c_unique');
        $pc = db('crm_l_pc_log')
            ->where('cid',$data['id'])
            // ->where('c_unique',$c_unique)
            ->where('is_delete',2)
            ->where('sm_type',$sm_type)
            ->select();
        if(in_array(1,array_column($pc,'status'))){
            // $key = array_search(1, array_column($pc,'status'));
            return array('code' => 106, 'msg' => '已预约到'.$pc[0]['pc_time'].'上门');
        }
        if(in_array(2,array_column($pc,'status')) && in_array($data['consulation_type'],array_column($pc,'consulation_type'))){
            return array('code' => 105, 'msg' => '已有此消费类型的预约上门,不能重复预约');
        }
        //体验拍可重复时间设定
        $repeat_experience_day = db_config('repeat_experience_day');
        if($repeat_experience_day){
            $res = db('crm_l_pc_log')->where('c_unique',$c_unique)->where('pc_type',2)->where('status',2)->where('consulation_type',$data['consulation_type'])->where('sm_type',$sm_type)->order('hx_time desc')->value('hx_time');
            if(strtotime($res) >= strtotime(date('Y-m-d',strtotime("- $repeat_experience_day days")))){
                return array('code' => 104, 'msg' => '上次预约上门未过期,不能排程');
            }
        }
        //如果没有选择摄影师，这里自动分配
        /* if(empty($data['cameraman_id'])){
            $camera = $this->fpCamera($data['pc_shop_code']);
            $data['cameraman_id'] = $camera['id'];
            $data['cameraman_name'] = $camera['staffname'];
            $auto = true;
        }else{
            $auto = false;
        }*/
        db()->startTrans();
        try{
            $code = get_rand_string(2,2).date('s');
            $arr = [
                'cid' => $data['id'],
                'c_unique' => $c_unique,
                'shop_code' => session('shop_code'),
                'shop_name' => session('shop_name'),
                'pc_shop_code' => $data['pc_shop_code'],
                'pc_shop_name' => $data['pc_shop_name'],
                // 'sale_id' => intval($data['sale_id']),
                // 'sale_name' => $data['sale_name'] ? trim($data['sale_name']) : '',
                'sale_id' => session('staff_id'),
                'sale_name' => session('staff_name'),
                'cameraman_id' => intval($data['cameraman_id']),
                'cameraman_name' => $data['cameraman_name'] ? trim($data['cameraman_name']) : '',
                'tutor_id' => intval($data['tutor_id']),
                'tutor_name' => $data['tutor_name'] ? trim($data['tutor_name']) : '',
                'remark'     => trim($data['remark']),
                'pc_time'    => trim($data['pc_time']),
                // 'street_id' => intval($data['street_id']),
                // 'street' => trim($data['street']),
                'address'   => trim($data['customer_address']),
                'code' => $code,
                'consulation_type' => $data['consulation_type'],
                'create_time' => date('Y-m-d H:i:s'),
                'pc_type'  => 2,
                'is_chaoju'  => $data['is_chaoju'] ? $data['is_chaoju'] : 2,
                'sm_type'  => $data['sm_type'] ? $data['sm_type'] : null,
                'visit_order'=>$sm_order ? $sm_order : NULL,
                'cloth' =>$data['cloth'],
                'time'=>$data['time'],
            ];
            
            $visit_id = db('crm_l_pc_log')->insertGetId($arr);
            if ($sm_order) {
                $upCOrder['visit_id'] = $visit_id;
                $upCOrder['visit_order_type'] = 1;
                db('crm_c_customer_order')->where('customer_id',(int)$data['id'])->where('order_sn',$sm_order)->update($upCOrder);
            }
            
            $cData['consulation_shop_code'] = $data['pc_shop_code'];
            $cData['consulation_shop'] = $data['pc_shop_name'];
            $customerInfo =  db('crm_c_customerinfo')->where('id', $data['id'])->field('id,c_unique,customer_name,customer_number,consultation_type_id,consultation_type,next_time,province_id,city_id,county_id,province,city,county,customer_address,baby_address,is_valid,yx_day')->find();
            // 如果预约进店 直接标记有效
            if ($customerInfo['is_valid']!=1) {
                $cData['is_valid'] = 1;
                $cData['yx_day'] = date('Y-m-d H:i:s');
                $oldArr['is_valid']=$customerInfo['is_valid'];
                $arr['is_valid'] = 1;
            }
            if($data['consulation_type_id']!=$customerInfo['consultation_type_id']){
                $cData['consultation_type_id'] = $data['consulation_type_id'];
                $cData['consultation_type'] = $data['consulation_type'];
                $oldArr['consultation_type']=$customerInfo['consultation_type'];
                $arr['consultation_type'] = $data['consulation_type'];
            }
            if ($customerInfo['next_time']) {
                $cData['next_time'] = NULL;
            }
            if ($data['province_id']!=$customerInfo['province_id']) {
                $cData['province_id'] = $data['province_id'];
                $cData['province'] = $data['province'];
                $oldArr['province']=$customerInfo['province'];
                $arr['province'] = $data['province'];
            }
            if ($data['city_id']!=$customerInfo['city_id']) {
                $cData['city_id'] = $data['city_id'];
                $cData['city'] = $data['city'];
                $oldArr['city']=$customerInfo['city'];
                $arr['city'] = $data['city'];
            }
            if ($data['county_id']!=$customerInfo['county_id']) {
                $cData['county_id'] = $data['county_id'];
                $cData['county'] = $data['county'];
                $oldArr['county']=$customerInfo['county'];
                $arr['county'] = $data['county'];
            }
            if ($data['customer_address']!=$customerInfo['customer_address']) {
                $cData['customer_address'] = trim($data['customer_address']);
                $oldArr['customer_address']=$customerInfo['customer_address'];
                $arr['customer_address'] = $data['customer_address'];
            }
            if ($data['baby_address']!=$customerInfo['baby_address']) {
                $cData['baby_address'] = trim($data['baby_address']);
                $oldArr['baby_address']=$customerInfo['baby_address'];
                $arr['baby_address'] = trim($data['baby_address']);
            }
            db('crm_c_customerinfo')->where('id',$data['id'])->update($cData);
            //追踪记录
            $params['c_unique'] = $customerInfo['c_unique'];
            $params['customer_id'] = $data['id'];
            $params['customer_name'] = $customerInfo['customer_name'];
            $params['customer_number'] = $customerInfo['customer_number'];
            $params['sales_remark'] = '预约'.trim($data['pc_time']).'上门-'.trim($data['remark']);
            if ($sm_order) {
                $params['sales_remark'] .= '；并关联订单：'.$sm_order;
            }
            if ($customerInfo['next_time']) {
                $params['sales_remark'] .= '；并清除再约时间：'.$customerInfo['next_time'];
            }
            // $params['sales_remark'] = '预约上门-'.trim($data['remark']).'；清除再约时间：'.$customerInfo['next_time'];
            $params['sales_day'] = date('Y-m-d H:i:s',time());
            $params['sales_staff'] = session('staff_name');
            $params['sales_staff_id'] = session('staff_id');
            $params['sales_staff_number'] = session('staff_number');
            $params['shop_name'] = session('shop_name');
            $params['shop_code'] = session('shop_code');
            db('crm_c_salestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$data['id'],null);
            //短信
            $smpModel  =  db_config('smp_sms_model_'.$shop_code);
            if($smpModel){
                $param = [
                    'ids' => $data['id'],//客资id
                    '_template_id' => $smpModel,//模板id
                    'flag'=>'smp',
                    'hx_code' => $code,
                    'pc_time'=>$data['pc_time'],
                    'receiver_flag'=>''
                ];
                $smsConfig = db_config('sms_'.session('shop_code'));//短信账号
                if($sms){
                    $param['_send_config'] = $smsConfig;
                }else{
                    $param['_shop_code'] = $shop_code;
                }
                // var_dump($param);die;
                controller('crm/Customer','lib')->send_message_notice($param);
            }
            action_log($arr,$oldArr,$data['id'],session('staff_id'),session('staff_name'));
            //摄影师分配日志
            // if($auto){
            //     //分配方式(1：自动分配；2：手动分配）
            //     $fLog['fp_model']         = 1;
            //     $fLog['fp_staff_id']      = session('staff_id');
            //     $fLog['fp_staff_name']    = session('staff_name');
            // }else{
                $fLog['fp_model']         = 2;
                $fLog['fp_staff_id']      = session('staff_id');
                $fLog['fp_staff_name']    = session('staff_name');
            // }
            $fLog['cid']              = $data['id'];
            // 分配状态（1：已分配；2：未分配；3：待接收；4：分配失败；5：放弃）
            // $fLog['fp_status']        = 1;
            // $fLog['fp_time']          = date('Y-m-d H:i:s');
            // $fLog['jr_time']          = date('Y-m-d H:i');
            // $fLog['fp_shop_code']     = session('shop_code');
            // $fLog['fp_shop_name']     = session('shop_name');
            // $fLog['fp_brandclass_id'] = session('brandclass_id');
            // $fLog['jr_staff_id']      = $data['cameraman_id'];
            // $fLog['jr_staff_name']    = $data['cameraman_name'];;
            // $fLog['jr_shop_code']     = $data['pc_shop_code'];
            // $fLog['jr_shop_name']     = $data['pc_shop_name'];
            // db('crm_l_camera_log')->insert($fLog);
            db()->commit();
            return array('code'=>200,'msg'=>'排程成功','data'=>'','time'=>date('Y-n-j',strtotime($data['pc_time'])));
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'排程失败','data'=>$e->getMessage());
        }
    }
    //自动分配摄影师
    public function fpCamera($shop_code){
        $p['shop_code'] = $shop_code;
        $p['work_type'] = 3;
        $info = getShopStaffs($p);
        //历史摄影师数量
        $camera_count = cache('camera_count_'.$shop_code);
        if((count($info)-1) != $camera_count){
            cache('camera_count_'.$shop_code,count($info));
        }
        //下一个摄影师的key
        $fp = cache('next_camera_'.$shop_code);
        if(!$fp || $fp > count($info)-1){
            cache('next_camera_'.$shop_code,1);
            return $info[0];
        }else{
            cache('next_camera_'.$shop_code,$fp+1);
            return $info[$fp];
        }
    }
    //删除排程
    public function delSmPaicheng(){
        $data = input('param.');
        $info = db('crm_l_pc_log')->where('id',$data['id'])->find();
        $customerInfo = db('crm_c_customerinfo')->where('id',$info['cid'])->field('customer_name,customer_number')->find();
        if($info['status'] != 1){
            return array('code'=>101,'msg'=>'不是未开始的排程，不能删除！');
        }
        db()->startTrans();
        try{
            db('crm_l_pc_log')->where('id',$data['id'])->update(['is_delete'=>1,'status'=>99,'remark'=>trim($data['remark'])]);
            //追踪记录
            $params['customer_id'] = $info['cid'];
            $params['c_unique'] = $customerInfo['c_unique'];
            $params['customer_name'] = $customerInfo['customer_name'];
            $params['customer_number'] = $customerInfo['customer_number'];
            $params['sales_remark'] = '删除排程:'.$info['pc_time'].';类型：'.$info['sm_type'].';原因：'.trim($data['remark']);
            $params['sales_day'] = date('Y-m-d H:i:s',time());
            $params['sales_staff'] = session('staff_name');
            $params['sales_staff_id'] = session('staff_id');
            $params['sales_staff_number'] = session('staff_number');
            $params['shop_name'] = session('shop_name');
            $params['shop_code'] = session('shop_code');
            db('CrmCSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$info['cid'],null);
            action_log('删除排程',[],$info['cid'],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 SmpcLogJSON(){
        $data = input();
        $limit = $data['limit'] ? $data['limit'] : 10;
        $page = $data['page'] ? $data['page'] : 1;
        $where = [];
        $where['f.pc_time'] = $data['pc_time'] ? $data['pc_time'] : date('Y-m-d');
        $where['f.pc_shop_code'] = $data['pc_shop_code'];
        if($data['sm_type']){
            $where['f.sm_type'] = $data['sm_type'];
        }
        if($data['customer_name']){
            $whereFull['c.customer_name'] = ['like',"%".trim($data['customer_name'])."%"];
        }
        if($data['customer_tel']){
            $whereFull['c.customer_tel'] = ['like',"%".trim($data['customer_tel'])."%"];
        }
        if (!empty($whereFull)) {
            unset($where);
            $where = $whereFull;
        }
        $result['code'] = 0;
        $result['msg'] = '';
        $result['data'] = db('crm_l_pc_log')->alias('f')
            ->join('crm_c_customerinfo c','f.cid=c.id','left')
            ->join('c_customerorder o','o.orderId=f.visit_order','left')
            ->where($where)->where('f.pc_type',2)->where('f.is_delete',2)
            ->field('\''.session('shop_code').'\' as staff_shop_code,f.id,c.customer_name,c.customer_tel,f.remark,f.consulation_type,f.sm_type,c.customer_address,f.cameraman_name,f.sale_name,f.tutor_name,f.shop_name,f.code,c.is_success,f.status,f.shop_code,f.pc_shop_code,f.pc_shop_name,f.pc_time,f.visit_order,o.package_name')
            ->order('sm_type')->limit($limit)->page($page)->select();
        // echo db()->getLastSql();die;
        $result['count'] = db('crm_l_pc_log')->alias('f')->join('crm_c_customerinfo c','f.cid=c.id')->where('f.pc_type',2)->where('f.is_delete',2)->where($where)->count();
        return json($result);
    }
    //日历中的排程次数
    public function SmpaichengNum(){
        $data = input();
        $month = $data['month'] ? date('Y-m',strtotime($data['month'])) : date('Y-m');
        $shop_code = trim($data['shop_code']);
        $sm_type = $data['sm_type'] ? $data['sm_type'] : '拍摄';

        //已排 次数
        $pcInfo = db('crm_l_pc_log')->where('pc_time','like',$month.'-%')->where('is_delete',2)->where('sm_type',$sm_type)->where('pc_shop_code',$shop_code)->where('pc_type',2)->group('pc_time')->order('pc_time')->column('count(id)','pc_time');
        //排程设定
        $info = db('crm_l_pc_setting_log')->where('setting_date','like',$month.'-%')->where('sm_type',$sm_type)->where('pc_type',2)->where('shop_code',$shop_code)->group('setting_date')->order('setting_date')->column('sum(num)','setting_date');

        $days = date("t",strtotime($month));
        $return = [];
        $ret = [];
        for($i=0;$i<$days;$i++){
            $date = date('Y-m-d',strtotime($month)+$i*86400);
            if(in_array($date,array_keys($info))){
                if($info[$date] === null){
                    $ret['num'] = '∞';
                }elseif($info[$date] === 0){
                    $ret['num'] = 0;
                }else{
                    $ret['num'] = $info[$date];
                }
            }else{
                $ret['num'] = 0;
            }


            $ret['date'] = date('Y-n-j',strtotime($month)+$i*86400);

            $ret['pc'] = $pcInfo[$date] ? $pcInfo[$date] : 0;
            $return[] = $ret;

        }
        return $return;
    }
    //获取剩余排程数量
    public function getOverSmNum(){
        $data = input();
        $where = [];
        $whereL = ' 1=1 ';//[];
        $sm_type = $data['sm_type'] ? $data['sm_type'] : '拍摄';
        $where['sm_type'] = $data['sm_type'];
        $whereL .= ' and sm_type="'.$data['sm_type'].'" ';
        $where['shop_code'] = $data['shop_code'];
        $whereL .= ' and pc_shop_code = \''.$data['shop_code'].'\' ';

        if($data['month']){
            $where['setting_date'] = $data['month'];
            //$whereL['pc_time'] = [$data['month']];
            $whereL .= ' and (pc_time is null or pc_time = \''.$data['month'].'\')';
        }

        $sett = db('crm_l_pc_setting_log')->where('pc_type',2)->where($where)->select();
        // echo db()->getLastSql();die;
        $log = db('crm_l_pc_log')->where($whereL)->where('is_delete',2)->where('pc_type',2)->select();
        // print_r($log);die;
        foreach ($log as $k=> $v) {
            foreach($sett as $kk=>$vv){
                if($v['pc_time'] == $vv['setting_date']){
                    $sett[$kk]['dec'] = $vv['dec']>0?$sett[$kk]['dec'] + 1 : 1;
                    break;
                }
            }
        }
        $str = '未设置档期，不能排程';
        foreach($sett as $k=>$v){
            $num = $v['dec'] ? $v['dec'] : 0;
            $str = '已排 '.$num.'个；';
            if($v['num'] === null){
                $str .=  "余 ∞ 个   █   ";
            }elseif($v['num'] === 0){
                $str .=  "余 0 个   █   ";
            }else{
                $str .=  "余 ".($v['num']-$num)." 个   █   ";
            }

        }
        return $str;
    }
    //修改上门拍排程备注
    public function editSmPcRemark(){
        $data = input();
        $old = db('crm_l_pc_log')->where('id',intval($data['id']))->where('pc_type',2)->find();
        try{
            db('crm_l_pc_log')->where('id',intval($data['id']))->where('pc_type',2)->update(['remark'=>$data['remark']]);
            action_log($data,$old,$old['cid'],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());
        }
    }
    /*---------上门拍----------end--------------*/
    
    /*---------根据渠道获取绑定的客资标记----------start--------------*/
    public function getSign(){
        $channel_id = input('channel_id');
        $sign_id = db('crm_s_channel')->where('id',$channel_id)->value('sign_id');
        if($sign_id){
            return array('code'=>200,'sign_id'=>$sign_id);
        }else{
            return array('code'=>100,'sign_id'=>'');
        }
    }
    /*---------根据渠道获取绑定的客资标记----------end--------------*/
    /*
     * 获取店面人员
     * */
    public function getStaffsByWorkType(){
        $staff = getStaffsByWorkType(input());
        return $staff;
    }
    //人员追踪数据
    public function staffTrackLog(){
        $county = controller('crm/Customer','lib')->address(['type'=>2,'shop_code'=>session('shop_code')]);
        $this->assign('county',$county);
        $channel = controller('crm/Customer','lib')->getChannel();
        $this->assign('channel',$channel);
        $consumption = controller('crm/Customer','lib')->consumptionType();
        $this->assign('consumption',$consumption);
        //归属店
        if(session('belong_shop_code')){
            $shop[0]['shop_code'] = session('belong_shop_code');
            $shop[0]['shop_name'] = session('belong_shop_name');
        }else{ //取当前店的归属店
            $param = [
                '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'),
            ];
            $shop = getBelongShop($param);
        }
        $this->assign('shop',$shop);
        return $this->fetch();
    }
    public function staffTrackLogJSON(){
        $data = input();
        $limit = $data['limit'] ? $data['limit'] : 20;
        $page = $data['page'] ? $data['page'] : 1;
        $start = $data['start'] ? $data['start'] : date('Y-m-d');
        $end = $data['end'] ? date('Y-m-d 23:59:59',strtotime($data['end'])) : date('Y-m-d 23:59:59');

        $result['code'] = 0;
        $result['msg'] = '';

        $where['c.c_from'] = 1;
        $where['c.is_status'] = 1;
        $where['t.gtType'] = 1;
        $where['t.tel_type'] = 1;
        $where['c.sales_staff'] = ['not null'];
        $where['t.tel_alltime'] = ['not null'];
        $where['t.audio_path'] = ['not null'];
        //判断有无查看本店通话记录的权限
        if(!check_right('menu1573096502')){
            $where['c.sales_staff'] = session('staff_name');
        }
        if($data['shop_code']){
            $where['c.shop_code'] = $data['shop_code'];
            $staff = getStaffsByWorkType(['shop_code'=>$data['shop_code'],'work_type'=>21]);
        }else{
            $where['c.shop_code'] = session('shop_code');
            $staff = getStaffsByWorkType(['shop_code'=>session('shop_code'),'work_type'=>21]);
        }
        if($data['county_id']){
            $where['c.county_id'] = intval($data['county_id']);;
        }
        if($data['customer_channel_id']){
            $where['c.customer_channel_id'] = intval($data['customer_channel_id']);;
        }
        if($data['consultation_type_id']){
            $where['c.consultation_type_id'] = intval($data['consultation_type_id']);;
        }
        if($data['search']){
            $where['c.customer_contact'] = ['like','%'.trim($data['search']).'%'];
        }else{
            $where['t.sales_day'] = ['between',[$start,$end]];
        }
        $result['data'] = db('crm_c_customerinfo')->alias('c')
            ->join('crm_c_salestrackinginfo t','c.id=t.customer_id','left')
            ->where('c.sales_staff','in',array_column($staff,'staffname'))
            ->where($where)
            ->limit($limit)->page($page)
            ->order('t.sales_day desc')
            ->field('c.id,c.sales_staff,t.sales_day,t.sales_remark,c.tel_visit_num,c.customer_name,c.customer_tel,c.mate_name,c.mate_tel,t.tel_starttime,t.tel_endtime,t.tel_alltime,c.baby_name,c.baby_birthday,c.ready_baby_day,c.customer_channel,c.consultation_type,c.county,c.customer_address,c.baby_address')
            ->select();
        foreach($result['data'] as $k=>$v){
            $result['data'][$k]['baby_birthday'] = $v['baby_birthday']&&$v['baby_birthday']!= '1970-01-01 00:00:00' ? date('Y-m-d',strtotime($v['baby_birthday'])) : '';
            $result['data'][$k]['ready_baby_day'] = $v['ready_baby_day']&&$v['ready_baby_day']!= '1970-01-01 00:00:00' ? date('Y-m-d',strtotime($v['ready_baby_day'])) : '';
        }

        $group = db('crm_c_customerinfo')->alias('c')
            ->join('crm_c_salestrackinginfo t','c.id=t.customer_id','left')
            ->where('c.sales_staff','in',array_column($staff,'staffname'))
            ->where($where)
            ->group('c.sales_staff')
            ->column('count(t.id)','c.sales_staff');

        $result['group'] = key($group) ? $group : [];
        $result['count'] = db('crm_c_customerinfo')->alias('c')
            ->join('crm_c_salestrackinginfo t','c.id=t.customer_id','left')
            ->where('c.sales_staff','in',array_column($staff,'staffname'))
            ->where($where)
            ->count();
        return $result;
    }
    public function prompt(){
        $msg = input('param.msg');

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

        $this->assign('title','提示页');
        return view('prompt');
    }

    /**
     * 获取组下的人
    */
    public function getStaffInfoByGid(){
        $group_id = input('param.group_id');
        $mc = new \app\common\lib\mcInterface();
        $groupStaff = $mc->getStaffInfoByGid(['group_id'=>$group_id]);
        unset($mc);
        return $groupStaff;
    }
    //获取erp套系详细
    public function getPackageDetail(){
        $param = input('');
        $package_name = $param['package_name'];
        $package_type = $param['package_type'];
        //意向套系
        if($package_type == 'tx'){
            $data = db('s_package_portfolio')->where('package_name',$package_name)->select();
        }elseif($package_type == 'cz'){
            $wherePackage = db('s_czpackagedetailset')->where('czpackage_name',$package_name)->select();
            $wherePackageName = array_column($wherePackage, 'package_name');
            $data = db('s_package_portfolio')->where('package_name','in',$wherePackageName)->select();
        }
        return $data?$data:'';
    }
    // 微信 加上 未加上 状态修改
    public function wxStatus(){
        $param = input();
        $wxstatus = (int)$param['wxstatus'] ? (int)$param['wxstatus'] : 0;
        $cid = (int)$param['cid'];
        if (!$cid) {
            $return['code']= 100;
            $return['msg'] = '获取客资ID失败';
            $return['data']= json_encode($param);
        }else{
            $staffInfo = [
                'staff_id'=>session('staff_id'),
                'staff_name'=>session('staff_name'),
                'staff_number'=>session('staff_number'),
                'shop_code'=>session('shop_code'),
                'shop_name'=>session('shop_name'),
            ];
            $return = controller("crm/Customer","lib")->setWxStatus(['wxstatus'=>$wxstatus,'cid'=>$cid,'staffInfo'=>$staffInfo]);
        }
        return json($return);
    }
    // 返回 微信扫码 复制 二维码 
    public function getWxCopyPageEwm(){
        $param = input();
        $cid = (int)$param['cid'];
        if ($cid) {
            $url = request()->domain().'/crm/index/getWxCopyPage?cid='.$cid.'&staff_id='.session('staff_id').'&staff_name='.urlencode(session('staff_name')).'&staff_number='.session('staff_number').'&shop_code='.session('shop_code').'&shop_name='.urlencode(session('shop_name'));
            // $url = url('index/getWxCopyPage',$data,'',true);
            $qrcode = new \Endroid\QrCode\QrCode();
            $qrcode->setText($url);
            echo $qrcode->writeString();
        }
    }
    

    /*
    * erp 某个月内排程数
    */
    public function erpPcNum(){
        $data = input();
        $month = $data['month'] ? date('Ym',strtotime($data['month'])).'01' : date('Ym01');
        $shop_code = trim($data['shop_code']) ? trim($data['shop_code']) : session('shop_code');

        $start = date('Ym01',strtotime($month));
        $end = date('Ym31',strtotime($month));

        //已排程
        $pcInfo = db('c_customerphoto')
            ->alias('p')
            ->where('isphoto_zd',0)
            ->where('p.shop_code',$shop_code)
            ->where('photodate',['BETWEEN',[$start,$end]])
            ->group('photodate')
            ->order('photodate')
            ->column('count(p.orderId) as num','photodate');

        $pcSql = db()->getLastSql();


        //占位
        $zdInfo = db('c_customerphotozd')
            ->where('zddel=""')
            ->where('shop_code',$shop_code)
            ->where('photodate',['BETWEEN',[$start,$end]])
            ->group('photodate')
            ->column('count(id) num','photodate');
        $zdSql = db()->getLastSql();


        //排程设定
        $setInfo = db('s_pcdefault_monthset')
            ->where('shop_code',$shop_code)
            ->where('pctype',0)
            ->where('pcday',['BETWEEN',[$start,$end]])
            ->group('pcday')
            ->column('sum(timecount) num','pcday');

        $setSql = db()->getLastSql();

        $days = date("t",strtotime($month));
        $list = [];

        for($i=0;$i<$days;$i++){
            $ret = [];

            $date = date('Ymd',strtotime($month)+$i*86400);


            $ret['num'] = (int)$setInfo[$date] > 0 ? (int)$setInfo[$date] : 0;

            $pc = (int)$pcInfo[$date] > 0 ? (int)$pcInfo[$date] : 0;
            $zd = (int)$zdInfo[$date] > 0 ? (int)$zdInfo[$date] : 0;
            $ret['pc'] = (int)($pc + $zd);

            $ret['date'] = date('Y-n-j',strtotime($date));

            $list[] = $ret;
        }

        $setAll = array_sum(array_map(function($val){return $val['num'];}, $list));
        $pcAll = array_sum(array_map(function($val){return $val['pc'];}, $list));
        return $return = [
            'list' => $list,
            'today' => date('Y-m-j'),
            'setAll' => $setAll,
            'pcAll' => $pcAll,
//            'pcSql' => $pcSql,
//            'zdSql' => $zdSql,
//            'setSql' => $setSql,
        ];
    }

    /*
     * 获取某天排程信息列表
     */
    public function erpPcList(){

        $day = input('pc_time') ? date('Ymd',strtotime(input('pc_time'))) : date('Ymd');
        $shop_code = input('shop_code') ? input('shop_code') : session('shop_code');
        //$shop_code = 'XBB403';
        $res = controller('customer','lib')->getErpPcListByDay($day,$shop_code);
        return json(array('code'=>0, 'msg'=>'', 'count'=>count($res), 'data'=>$res));
    }

    /*
    * 获取某天改期信息列表
    */
    public function erpPcUpdateList(){

        $day = input('pc_time') ? date('Ymd',strtotime(input('pc_time'))) : date('Ymd');
        $shop_code = input('shop_code') ? input('shop_code') : session('shop_code');
        //$shop_code = 'XBB403';
        $res = controller('customer','lib')->getErpPcUpdateListByDay($day,$shop_code);
        return json(array('code'=>0, 'msg'=>'', 'count'=>count($res), 'data'=>$res));
    }

    /*
     * 2021.03.11 南宁qqbaby 
     * 客资解除订单功能
     */
    public function relieveOrder()
    {
        // 南宁qqbaby  2021-04-19
        if (!customize('nnqqbaby')) {
            return $this->redirect('/');
        }

        $param = input();
        $id = (int)$param['id'];
        if(!$id){
            return array('code'=>100,'msg'=>'没有订单id参数');exit;
        }
        return controller('customer','lib')->relieveOrder($id);
    }

    /*
     * 2021.06.16 南宁qqbaby 
     * 客资绑定订单功能
     */
    public function bindingOrder()
    {
        // 南宁qqbaby  2021-04-19
        if (!customize('nnqqbaby')) {
            return $this->redirect('/');
        }

        $param = input();
        $id = (int)$param['id'];
        if(!$id){
            return array('code'=>100,'msg'=>'没有订单id参数');exit;
        }
        $crm_customer_id = (int)$param['crm_customer_id'];
        if(!$crm_customer_id){
            return array('code'=>100,'msg'=>'没有客资id参数');exit;
        }
        return controller('customer','lib')->bindingOrder($param);
    }

    //批量录入客资
    public function customerAddMore(){
        // 判断南宁定制
        if (customize('nnqqbaby')) {
            $this->assign('nnqqbaby','1');
        }else{
            $this->assign('nnqqbaby','2');
        }
        $channel=controller("crm/Customer","lib")->getChannel();
        $this->assign("channel",$channel);
        $this->assign('default_ashop', array('shop_code'=>session('shop_code'), 'shop_name'=> session('shop_name')));
        $this->assign('default_shop', array('belong_shop_code'=>session('belong_shop_code'), 'belong_shop_name'=> session('belong_shop_name')));
        $this->assign('open_time', date('Y-m-d H:i:s'));
        //获取方式
        $accessModel=controller("crm/Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
        $this->assign("accessModel",$accessModel);
        //客户意向
        $intention=controller("crm/Customer","lib")->intention(array('shop_code'=>session('shop_code')));
        $this->assign("intention",$intention);
        $this->assign("intention1",$intention);
        //消费类型
        $consumptionType=controller("crm/Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        //客户来源
        $source=controller("crm/Customer","lib")->source(array('shop_code'=>session('shop_code')));
        $this->assign("source",$source);
        //客户标记
        $mark=controller("crm/Customer","lib")->markSet();
        $this->assign("market",$mark);
        $this->assign("mark1",$mark);
        //客户地址
        $data['type']=1;
        $address=controller("crm/Customer","lib")->address($data);
        $this->assign("address",$address);
        // 品牌
        $brand = db('crm_s_brandset')->order('sort asc')->select();
        $this->assign('brand',$brand);

        //已设置的归属店  20191008
        $checked_shop = db_config('dj_shops_'.session('shop_code'));
        // 如果当前店面类型是实体店 取该店下所有人
        if(session('belong_shop_code')){
            $paramG['shop_code'] = session('belong_shop_code');
            $paramG['work_type'] = 21;
            $shopAllStaff = getShopStaffs($paramG);
        }elseif(empty(session('belong_shop_code')) && !empty($checked_shop)){
            $shopAllStaff = [];
            foreach($checked_shop as $k=>$v){
                $paramG['shop_code'] = $v['shop_code'];
                $paramG['work_type'] = 21;
                $staff = getShopStaffs($paramG);
                foreach($staff as $key=>$val){
                    $shopAllStaff[] = $val;
                }
            }
        }else{
            $paramG['shop_code'] = session('shop_code');
            $paramG['work_type'] = 21;
            $shopAllStaff = getShopStaffs($paramG);
        }

        $this->assign("shopAllStaff",$shopAllStaff);

        //查询归属地是否筛客
        $b_is_sk = controller("crm/Customer","lib")->is_sk(session('belong_shop_code'));

        if($b_is_sk ==1 || session('is_sk') == 1){
            $this->assign('is_sk',1);
            if ( session('is_marketing') == 2 ) {
                // 可操作店为当前店面 ，且 工作类型包含 筛客的员工
                $this->assign('sklist',controller("crm/Customer", "lib")->sklist(session('shop_code'),24));
            }else{
                $this->assign('sklist',controller("crm/Customer", "lib")->sklist('',24));
            }
        }
        $this->assign('shoptype',session('shop_type'));
        $sms = db_config('sms_'.session('shop_code'));
        $this->assign('sms',$sms);//短信账号
        $is_send_sms = db_config('is_send_sms_'.session('shop_code'));
        $this->assign('is_send_sms',$is_send_sms);//录入时是否发送短信
        //短信模板
        $res = db('crm_s_message_templateinfo')->where('shop_code',session('shop_code'))->where('status',1)->field('id,mtemplate_name')->select();
        $this->assign('smsModel',$res);
        //意向店面
        $shops = controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass'),
            'is_marketing'=>2));
        $this->assign('shops',$shops);

        $custom = $this->getCustomColumn();//获取自定义列
        $this->assign('colModel',$custom['custom_model'] ? json_decode($custom['custom_model'],true) : json_encode([]));
        $this->assign('colNames',$custom['custom_name'] ? json_decode($custom['custom_name'],true) : json_encode([]));
        //录入必选项配置
        $lrMust = db_config('lr_must_'.session('brandclass_id'));
        $lrMust = trim($lrMust,',');
        $lrMust = explode(',',$lrMust);
        $this->assign('lrMust',$lrMust);
        //录入字段隐藏配置
        $hidden = db_config('lr_hidden_'.session('brandclass_id'));
        $hidden = trim($hidden,',');
        $hidden = explode(',',$hidden);
        $this->assign('lrHidden',$hidden);
        //客资状态
        $valid = db_config('valid_'.session('brandclass_id'));
        $this->assign('valid',$valid);
        //判断是不是集团店
        if(session('is_group') == 1){
            //集团下事业部
            $url = '5a38840b15ba9';
            $info = sx_call($url,[]);
            if($info['code'] == 200){
                $this->assign('brand',$info['data']);
            }
        }
        $p = [
            'staff_id'=> session('staff_id'),
            'brandclass_id'=> session('brandclass_id'),
            'shop_type' => session('shop_type')
        ];
        $djshops = getShops($p);//可操作店

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

        $param = [
            '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($param);

        $this->assign('check_shop',$belong);
        //客资标记
        $tracksign=controller("crm/Setting","lib")->gettrackingKmarkerList();
        $this->assign("tracksign",$tracksign);
        return $this->fetch();
    }
    public function addCustomerMore(){
        $param = input('post.');

        if(empty($data['customer_channel_id'])){
            return $returnData = array('code' => 101,'msg' =>'渠道名称不能为空');
        }

        $content = trim($param['content']);
        $split = str_replace(array("\r\n","\r","\n","","|",PHP_EOL),',',$content);
        $one_arr = explode(",",$split);
        $baby_name = [];
        $baby_sex = [];
        $baby_birthday = [];
        $ready_baby_day = [];
        $customer_name = [];
        $customer_sex = [];
        $customer_tel = [];
        $customer_wechat = [];
        $mate_name = [];
        $mate_sex = [];
        $mate_tel = [];
        $mate_wechat = [];
        $customer_remark = [];
        foreach($one_arr as $k=>$v){
            $arr = explode('|',$v);
            foreach($arr as $kk=>$vv){
                $search = array(" ","　","\n","\r","\t");
                $replace = array(",",",",",",",",",");
                $arrinfo = str_replace($search, $replace, $vv);
                $arr1 = explode(',',$arrinfo);
                if(session('shop_type') == 1){
                    array_push($customer_name,$arr1[0]);
                    array_push($customer_tel,$arr1[1]);
                    array_push($customer_wechat,$arr1[2]);
                    array_push($mate_name,$arr1[3]);
                    array_push($mate_tel,$arr1[4]);
                    array_push($mate_wechat,$arr1[5]);
                    array_push($customer_remark,$arr1[6]);

                    // array_push($customer_name,$arr1[0]);
                    // array_push($customer_sex,$arr1[1]);
                    // array_push($customer_tel,$arr1[2]);
                    // array_push($customer_wechat,$arr1[3]);
                    // array_push($mate_name,$arr1[4]);
                    // array_push($mate_sex,$arr1[5]);
                    // array_push($mate_tel,$arr1[6]);
                    // array_push($mate_wechat,$arr1[7]);
                    // array_push($customer_remark,$arr1[8]);
                }else{
                    array_push($customer_name,$arr1[0]);
                    array_push($customer_tel,$arr1[1]);
                    array_push($customer_wechat,$arr1[2]);
                    array_push($customer_remark,$arr1[3]);
                    // array_push($baby_name,$arr1[0]);
                    // array_push($baby_sex,$arr1[1]);
                    // array_push($baby_birthday,$arr1[2]);
                    // array_push($ready_baby_day,$arr1[3]);
                    // array_push($customer_name,$arr1[4]);
                    // array_push($customer_tel,$arr1[5]);
                    // array_push($customer_wechat,$arr1[6]);
                    // array_push($mate_name,$arr1[7]);
                    // array_push($mate_tel,$arr1[8]);
                    // array_push($mate_wechat,$arr1[9]);
                    // array_push($customer_remark,$arr1[10]);
                }
            }
        }
        $data = [];
        $data['add_shop_code'] = $param['add_shop_code'] ? $param['add_shop_code'] : session('shop_code');
        $data['add_shop_name'] = $param['add_shop_name'] ? $param['add_shop_name'] : session('shop_name');
        $data['shop_code'] = $param['shop_code'] ? $param['shop_code'] : session('belong_shop_code');
        $data['shop_name'] = $param['shop_name'] ? $param['shop_name'] : session('belong_shop_name');
        $data['brandclass_id'] = $param['brandclass_id'] ? $param['brandclass_id'] :session('brandclass_id');
        $data['brandclass'] = $param['brandclass'] ? $param['brandclass'] :session('brandclass');
        $data['customer_type'] = $param['customer_type'];
        $data['customer_channel_id'] = $param['customer_channel_id'] ? $param['customer_channel_id'] : null;
        $data['customer_channel'] = $param['customer_channel'] ? $param['customer_channel'] : null;
        $data['access_model_id'] = $param['access_model_id'] ? $param['access_model_id'] : null;
        $data['access_model'] = $param['access_model'] ? $param['access_model'] : null;
        $data['consultation_type_id'] = $param['consultation_type_id'] ? $param['consultation_type_id'] : null;
        $data['consultation_type'] = $param['consultation_type'] ? $param['consultation_type'] : null;
        $data['customer_intention_id'] = $param['customer_intention_id'] ? $param['customer_intention_id'] : null;
        $data['customer_intention'] = $param['customer_intention'] ? $param['customer_intention'] : null;
        $data['customer_cource_id'] = $param['customer_cource_id'] ? $param['customer_cource_id'] : null;
        $data['customer_cource'] = $param['customer_cource'] ? $param['customer_cource'] : null;
        $data['channel_plan_number'] = $param['channel_plan_number'] ? $param['channel_plan_number'] : null;
        $data['sign_id'] = $param['sign_id'] ? $param['sign_id'] : null;
        $data['sign_name'] = $param['sign_name'] ? $param['sign_name'] : null;
        $data['sales_staff_id'] = $param['sales_staff_id'] ? $param['sales_staff_id'] : null;
        $data['sales_staff'] = $param['sales_staff'] ? $param['sales_staff'] : null;
        $data['consulation_shop_code'] = $param['consulation_shop_code'] ? $param['consulation_shop_code'] : null;
        $data['consulation_shop'] = $param['consulation_shop'] ? $param['consulation_shop'] : null;
        $data['is_valid'] = $param['is_valid'] ? $param['is_valid'] : 2;
        $data['customer_key'] = $param['customer_key'] ? $param['customer_key'] : null;
        $data['budget'] = $param['budget'] ? $param['budget'] : null;
        $data['dj_staff_id'] = session('staff_id');
        $data['dj_staff'] = session('staff_name');
        $data['dj_staff_number'] = session('staff_number');
        $data['dj_department_id'] = session('department_id');
        $data['dj_department_name'] = session('department_name');

        $data['province_id'] = $param['province_id'] ? $param['province_id'] : null;
        $data['province'] = $param['province'] ? $param['province'] : null;
        $data['city_id'] = $param['city_id'] ? $param['city_id'] : null;
        $data['city'] = $param['city'] ? $param['city'] : null;

        $data['b_id'] = $param['b_id'] ? $param['b_id'] : null;
        $data['b_name'] = $param['b_name'] ? $param['b_name'] : null;

        $i= 1;
        $patrn = check_tel_arr();
        $patrn = explode(',',$patrn);
        foreach($one_arr as $k=>$v){
            if(session('shop_type') == 2){
                $data['baby_name'] = $baby_name[$k] ? $baby_name[$k] : null;
                $data['baby_sex'] = $baby_sex[$k] ? $baby_sex[$k] : null;
                $data['baby_birthday'] = $baby_birthday[$k] ? date('Y-m-d',strtotime($baby_birthday[$k])) : null;
                $data['ready_baby_day'] = $ready_baby_day[$k] ? date('Y-m-d',strtotime($ready_baby_day[$k])) : null;
            }
            $data['customer_name'] = $customer_name[$k] ? $customer_name[$k] : null;
            $data['customer_sex'] = $customer_sex[$k] ? $customer_sex[$k] : null;
            $data['customer_tel'] = $customer_tel[$k] ? $customer_tel[$k] : null;
            $data['customer_wechat'] = $customer_wechat[$k] ? $customer_wechat[$k] : null;
            if(empty($data['customer_tel']) && empty($data['customer_wechat'])){
                return $returnData = array('code' => 500,'msg' =>'第 【'.$i .'】 条客资，联系方式不能为空','data'=>$data);
            }
            if($data['customer_tel']){
                $tel = false;
                //循环匹配手机正则
                foreach($patrn as $kk=>$vv){
                    $check = check_tel($data['customer_tel'],$vv);
                    if($check){
                        $tel = true;
                    }
                }
                if(!$tel){
                    return $returnData = array('code' => 500,'msg' =>'第 【'.$i .'】 条客资，手机格式错误','tel'=>$data['customer_tel']);
                }
            }
            $data['mate_name'] = $mate_name[$k] ? $mate_name[$k] : null;
            $data['mate_sex'] = $mate_sex[$k] ? $mate_sex[$k] : null;
            $data['mate_tel'] = $mate_tel[$k] ? $mate_tel[$k] : null;
            $data['mate_wechat'] = $mate_wechat[$k] ? $mate_wechat[$k] : null;
            $data['customer_remark'] = $customer_remark[$k] ? $customer_remark[$k] : null;
            $res = controller("crm/Customer", "lib")->addCustomer_child($data);
            
            if(empty($res)){
                return $returnData = array('code' => 500,'msg' =>'第 【'.$i .'】 条客资，【'.$data['customer_name'].'】 录入失败','data'=>$res['data']);
            }
            if($res['code'] == 201){
                return json($res);
            }
            if (is_array($res) && $res['code'] != 200) {
                if(is_weixin()){
                    return $this->wx_index();
                }else{
                    $returnData = array('code' => $res['code'],'msg' =>$data['customer_name'].' 录入失败','data'=>$res['data']);
                    return json($returnData);
                }
            }
            $i++;
        }
        $returnData = array('code' => 1,'msg' =>'客资录入成功','data'=>'');
        return json($returnData);
    }
    
    public function getStaffInfos(){
        $params = input();
        if(!$params['shop_code'] && !$params['department_id']){
            return json(['code'=>202,'msg'=>'店和部门必须选择一个']);
        }
        if($params['shop_code']){
            $data['shop_code'] = $params['shop_code'];
        }
        if($params['department_id']){
            $data['department_id'] = $params['department_id'];
        }
        $mcInter = new \app\common\lib\mcInterface(['shop_type'=>session('shop_type')]);
        $staffArr = $mcInter->getStaffInfo($data);
        return json($staffArr);
    }

    //呼叫中心(七陌) 呼叫
    public function huJiaoZX_qimo_hujiao()
    {
        $params = input('post.');
        if (!$params['tel']) {
            return array('code'=>100,'msg'=>'没有呼叫电话。');exit;
        }
        if (!$params['cid']) {
            return array('code'=>100,'msg'=>'没有客资id。');exit;
        }
        if (!$params['callCenterType']) {
            return array('code'=>100,'msg'=>'没有通话类型。');exit;
        }
        if (!$params['callMan']) {
            return array('code'=>100,'msg'=>'没有设置坐席。');exit;
        }
        $time = time();

        $data['FromExten'] = $params['callMan'];//坐席工号
        $data['Exten'] = $params['tel'];//被叫号码
        $data['ExtenType'] = $params['callCenterType'];//外呼时强制坐席使用该接听方式进行外呼。Local为“手机”,”gateway为“语音网关”
        $data['DialoutStrVar'] = json_encode(array('cid'=>$params['cid'],'sales_staff_id'=>session('staff_id'),'time'=>$time));

        $where['url'] = '/v20180426/call/dialout/';
        $where['data'] = $data;
        $res = huJiaoZXQiMo($where);

        if ($res['Succeed'] === false) {
            $Message = substr($res['Message'], 0,3);

            $msg=[
                400=>'请求有误，请检查传递的参数是否合法',
                401=>'账户配置问题',
                403=>'用户账户或验证码无效或过期，请技术支持修改账户属性，允许这个账户使用外呼接口',
                403=>'鉴权失败',
                404=>'坐席未找到，请检查FromExten字段中的坐席分机号是否传递正确',
                407=>'坐席无法接听电话（坐席没有登录），可通过传ExtenType解决该问题',
                408=>'坐席忙碌，无法接听（坐席已经有一通电话在进行中）。如果是话机方式（gateway）,可能是话机掉注册了，请检查一下话机状态',
                409=>'：调用者指定的接听方式，不可用。可能原因：软电话未登陆，网关未绑定或未注册，未绑定手机号',
                500=>'服务器错误',
            ];

            return array('code'=>$Message,'msg'=>$msg[$Message]);
        }else{
            
            return array('code'=>200,'data'=>json_decode($res),'time'=>$time);
        }
    }

    //呼叫中心(七陌) 挂断
    public function huJiaoZX_qimo_guaduan()
    {
        $zuoxi = input('callMan');
        if (!$zuoxi) {
            return array('code'=>100,'msg'=>'没有监听到正在通讯的电话！');exit;
        }

        // $data['CallID'] = $ActionID;//通话ID
        $data['Agent'] = $zuoxi;//坐席工号  CallID和Agent必填一项，优先使用CallID

        $where['url'] = '/v20160818/call/hangup/';
        $where['data'] = $data;
        $res = huJiaoZXQiMo($where);
        if ($res['Succeed'] === false) {
            $Message = substr($res['Message'], 0,3);

            $msg=[
                400=>'请求有误，请检查传递的参数是否合法',
                401=>'账户配置问题',
                404=>'账户未找到，请检查Account参数',
                500=>'服务器异常',
            ];

            return array('code'=>$Message,'msg'=>$msg[$Message]);
        }else{
            return array('code'=>200,'data'=>json_decode($res));
        }
    }
    //呼叫中心(七陌) 被呼振铃Ringing
    public function callCenterSevenStranger_ringing(){
        $instance[] = 'callCenterSeven'.session('staff_id');
        $res = redisQueue::init()->subscribe($instance, 'callCenterSevenStrangerRinging');
        // 监听频道超时
        if ($res === false) {
            return false;
        }
    }
    //呼叫中心 通话记录
    public function callLog(){
        //发送短信记录
        $msg = controller("Customer","lib")->getCallList(input());
        return $msg;
    }



}
