<?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\exception\PDOException;
use think\Log;
use think\Request;
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(){
        cache('fpCustomerP*',null);die;
        $erp = config('ext.app_config');
        $addr = $erp['sx_erp']['addr'];
        $url =  $addr.'SX_CrmApi/Set_Order_Cssname?Token=^******^&orderId=SX190417003';
        // 调erp接口，修改信息
        $erpData['Cssname'] = '网络';
        $erpData['Customer_channel'] = '15	搜狗';
        $erpData['Storeconsuitant2'] = '';
        $erpData['Customer_from_index'] = '63455701555155';
        $erpData = json_encode($erpData);
        $response = requestERP($url, $erpData);
        print_r($response);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'));

        $isTable = isTableExist('c_customer_intostore');
        print_r($isTable);die;
        return $this->fetch();
    }
    public  function test(){
        echo date_default_timezone_get();
        echo '<br />';
        echo date('Y-m-d 00:00:00', strtotime('last week monday'));
        echo '<br />';
        echo date('Y-m-d 23:59:59', strtotime('last week sunday'));
        echo '<hr />';
        echo date('Y-m-d 00:00:00', strtotime('this week monday'));
        echo '<br />';
        echo date('Y-m-d 23:59:59', strtotime('this week sunday'));
        die;
        $week = getdateArea('last_week');
        var_dump($week);
        die;
        $res = controller('crm/ListenRedis','lib')->checkCustomerOrder();

        var_dump($res);
        die;

        $a = [1=>'a',2=>'b',3=>'c'];
        $b = [2=>'b',3=>'c',4=>'d'];
        $c = array_unique(array_merge($a,$b));
        dump($c);die;
        $a = '{
            "baby_birthday": "2018-11-27",
            "consulation_shop": "聚焦baby",
            "consulation_shop_code": "XB0140",
            "customer_cource": "会员活动",
            "customer_cource_id": "38",
            "custolkmer_name": "杜鹃",
            "customer_tel": "18601134664",
            "default_staff_id": "701",
            "hd_name": "您有一份价值1288元免费彩色face拍摄",
            "introducer_name": "北京银行 丰台",
            "shop_code": "XLM466",
            "shop_name": "聚焦baby-丰台店",
            "staff_id": "-1",
            "staff_name": "北京银行 丰台",
        }';
        $b = json_decode($a,true);
        ksort($b);
        $tokenStr = arrayToParams($b).'g1d53dsf3sd1f3as5df54asd5fsd';
        if('10df93952c55ffef9f66a057c17b6091' != md5($tokenStr)){
            echo md5($tokenStr);die;
        }
        echo 111;die;
        return true;
        $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('accessModel',null);
        cache('intention',null);
        cache('areaSet',null);
        cache('capacity',null);
        session('consumptionType_*',null);
        session('orderAddress',null);
        session('positions_'.session('staff_id'),null);
        //标签缓存
        cache('label_'.session('brandclass_id'),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('staffs_21*',null);
        cache('shop_staffs_*',null);
        //颜色
        cache('sign_color_*',null);
        cache('sales_sign_color_*',null);

        cache('companyInfo',null);//清除组织架构缓存
        cache('shopAllStaffs_*',null);
        cache('staffs_*',null);
        // cache('staffInfo_*',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('guishu_shop_*',null);
        cache('caozuo_shop_*',null);
        cache('brandclassInfo_*',null);
        // 大屏里记录的缓存
        cache('bg_*',null);
        // c_sysconfig 缓存
        cache('db_config_*',null);
        // 渠道
        cache('all_channel_*',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 = getStaffInfoById($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('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);
        //查询同组小伙伴
        $group_info = controller('crm/Customer','lib')->get_group_info($staffId);
        //$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') || !in_array($staffId,$gId)){
                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('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('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 = getStaffInfoById($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')) {//查看小组客资权限
            $staff_id = getGroupStaffByStaffId($staffId);
            $staff_id = array_column($staff_id,'staff_id');
            $staffId = implode(',',$staff_id);
        }
        //根据主岗位获取显示内容
        $res = db('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_start'] = ['id'=>'order_start','value'=>$order];
            }
            if(in_array('总订单(登记时间)',$content)){
                $order_dj = $tar->orderNumberByDJday($arr);
                $data['data'][$v]['order_dj'] = ['id'=>'order_dj','value'=>$order_dj];
            }
            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('c_salestrackinginfo')->where('id',$id)->update(['audio_path'=>$path.'/'.$name]);
                    }else{
                        db('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('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 update_staff_status(){
        $data = input('post.');
        $param['status'] = $data['status'];
        $info = cache('staffInfo_'.$data['staff_id']);
        db()->startTrans();
        try{
            db('SSession')->where(array('staff_id' => $data['staff_id']))->update($param);
            db()->commit();
            // 赋值状态
            $info['status'] = $data['status'];
            if($info['keep_login'] == 1){
                cache('staffInfo_'.$data['staff_id'], json_encode($info),432000);
            }else{
                cache('staffInfo_'.$data['staff_id'], json_encode($info));
            }
            return true;
        }catch (\Exception $e){
            db()->rollback();
            return false;
        }
    }
    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');
        $str_id = config('bigScreen_id');
        $bigScreen_id = explode(',', $str_id);
        $is_in = in_array($staff_id, $bigScreen_id);
        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);
        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');
        if(IS_POST === true){
            $password = input('post.password');
            $res = sx_call('5a221c9548d47', ['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]);
        $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');
        $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');
    }
    //客资提报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');
    }
    //移动端提报页面   20200825
    public function keziTB(){
        // 登记人 当前操作人所在的店 部门 下的人 20210105
        $mc = new \app\common\lib\mcInterface();
        $mcParam['brandclass_id'] = session('brandclass_id') ? session('brandclass_id') : 'zero';
        $mcParam['shop_code'] = session('shop_code') ? session('shop_code') : 'zero';
        $mcParam['department_id'] = session('department_id') ? session('department_id') : 'zero';
        $djStaff = $mc->getStaffInfo($mcParam);
        if ($djStaff) {
            foreach ($djStaff as $key => $value) {
                if ($value['id']== session('staff_id')) {
                    $djStaff[$key]['selected'] = 1;
                }
            }
        }else{
            $djStaff[0]['id'] = session('staff_id');
            $djStaff[0]['staffname'] = session('staff_name');
            $djStaff[0]['selected'] = 1;
        }
        $this->assign('djStaff',$djStaff);
        //客户意向
        $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")->channel(array('shop_code'=>session('shop_code')));
        $channel=controller("Customer","lib")->getChannel();
        $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);
        //意向店面
        $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);
        // 追踪人
        //已设置的归属店 
        $checked_shop = db_config('dj_shops_'.session('shop_code'));
        // 如果当前店面类型是实体店 取该店下所有人
        if(session('belong_shop_code')){
            $shop[0]['shop_code'] = session('belong_shop_code');
            $shop[0]['shop_name'] = session('belong_shop_name');

            $paramG['shop_code'] = session('belong_shop_code');
            $paramG['work_type'] = RECEIVE_WORK_TYPE;
            $shopAllStaff = getShopStaffs($paramG);
        }elseif(empty(session('belong_shop_code')) && !empty($checked_shop)){
            $shop = $checked_shop;
            $shopAllStaff = [];
            foreach($checked_shop as $k=>$v){
                // $staff = controller('Customer','lib')->getShopAllStaff(array('shop_code'=>$v['shop_code']));
                $paramG['shop_code'] = $v['shop_code'];
                $paramG['work_type'] = RECEIVE_WORK_TYPE;
                $staff = getShopStaffs($paramG);
                foreach($staff as $key=>$val){
                    $shopAllStaff[] = $val;
                }
            }
        }else{
            $shop[0]['shop_code'] = session('shop_code');
            $shop[0]['shop_name'] = session('shop_name');

            $paramG['shop_code'] = session('shop_code');
            $paramG['work_type'] = RECEIVE_WORK_TYPE;
            $shopAllStaff = getShopStaffs($paramG);
        }
        $this->assign('shop',$shop);
        $this->assign('shopAllStaff',$shopAllStaff);
        // var_dump($shopAllStaff);die;
        ///录入必选项配置
        $lrMust = db_config('lr_must_'.session('brandclass_id'));
        $lrMust = trim($lrMust,',');
        $lrMust = explode(',',$lrMust);
        $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.');
        $channel = sx_call('59fd5e729e5a8',array('id'=>$param['channel_id']));//渠道名称
        $shop = sx_call('5a005e0038270',array('shop_code'=>$param['shop_code']));//提交店面信息
        $this->assign('channel',$channel['data'][0]);
        $this->assign('shop',$shop['data'][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);
        //接入店面信息 20200523
        $shop = controller('Customer','lib')->getShopInfo(array('brandclass'=>session('brandclass'),'is_dig'=>1));
        if(empty($shop['data'])){
            $belong_code = session('belong_shop_code');
            $belong_name = session('belong_shop_name');
            if (!$belong_code && !$belong_name) {
                $shop['data'] = [
                    0=>[
                        'shop_code'=>session('shop_code'),'shop_name'=>session('shop_name'),
                    ],
                ];
            }else{
                $shop['data'] = [
                    0=>[
                        'shop_code'=>session('belong_shop_code'),'shop_name'=>session('belong_shop_name'),
                    ],
                ];
            }
        }
        $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());
        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'));
        $info['customer_label'] = $info['customer_label'] ? explode(',',trim($info['customer_label'],',')) : [];
        $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 refreshNumber(){
        $data = input('post.');
        $num=controller("Customer","lib")->searchNum($data);
        $this->success('刷新成功', '/',$num);
    }

    //客资列表、查询
    public function customerList(){
        if(Request::instance()->isAjax()){
            $data = input();
            // 客资状态
            $is_valid = $data['is_valid'] ? $data['is_valid'] : '1,2,3,4,5';
            cookie('valid', $is_valid);
            
            if ($data['tab'] == 7) {
                $data['is_loss'] = 1;
            }
            // var_dump($arr);
            // exit;
            // 客资爆破
            if($data['tab'] == 100){
                $detail=controller("Customer","lib")->customerListData_bp($data);
            }
            else{
                $detail=controller("Customer","lib")->customerListData($data);
            }
            echo json_encode($detail);
        }else{
            // 查看某条客资信息
            $client_customer_id = input('client_customer_id');
            $this->assign('client_customer_id',$client_customer_id?$client_customer_id:0);

            // $auth=getAuth($type='auth');
            $auth = session('crm_auth');
            $menuCode= array_column($auth,'menu_code');
            $allRightMenu = [//要控制的所有右键菜单
                'menu1512971662',//客资追踪
                // 'menu1519631971',//右键-客资标记
                'menu1519635403',//右键-筛客
                'menu1519632099',//右键-追踪标记
                'menu1519633870',//右键-预约进店
                'menu1519633923',//右键-转订单
                'menu1519633959',//右键-编辑订单
                'menu1520675106',//右键-撤销
                'menu1522653972',//右键-介绍人修改
                'menu1519633436',//右键-不再追踪
                // 'menu1517129299',//标有效
                'menu1546854995',//标有效
                'menu1517129331',//标无效
                'menu1517278817',//客资驳回
                'menu1517278844',//客资反驳回
                'menu1512971646',//发送短信
                'menu1584353494',//发送站内信
                'menu1512970623',//客资分配
                'menu1512970667',//修改客资
                'menu1512970570',//删除客资
                'menu1572077805',//退单
            ];
            //查看一年内客资
            if(check_right('menu1546854888') && session('main_work_type') != SYSTEM_AUTH_ADMIN){
                $this->assign('yearCus',1);
            }else{
                $this->assign('yearCus',0);
            }
            //查询有无查看小组权限
            $admin = db('c_staff_group')->where('shop_code',session('shop_code')) ->where('find_in_set(:id,admin)',['id'=>session('staff_id')])->select();
            if(!empty($admin) && check_right('menu1529653231')){
                $this->assign('group',1);
            }else{
                $this->assign('group',0);
            }
            $rightMenuList = array_intersect($allRightMenu,$menuCode);
            $this->assign('right_menu_list', $rightMenuList);
            $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'),session('brandclass_id'));
            $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);
            $listMark = ':全部;';
            foreach ($mark as $k => $v) {
                $listMark .= $v['mark_name'].':'.$v['mark_name'].';';
            }
            $listMark = trim($listMark,';');
            $this->assign("listMark",$listMark);
            //客户标记
            $sign=controller('crm/Setting','lib')->gettrackingKmarkerList();
            $this->assign("sign",$sign);
            $listSign = ':全部;';
            foreach ($sign as $k => $v) {
                $listSign .= $v['tracksign'].':'.$v['tracksign'].';';
            }
            $listSign = trim($listSign,';');
            $this->assign("listSign",$listSign);
            //意向店面
            $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('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',$auth);

            $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('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);
            //呼叫中心
            // $this->assign('callCenter',config('call_center'));//要在登录时放点session或cookie里
            // $this->assign('callCenter','shenou');//要在登录时放点session或cookie里

            // 是否开启爆破活动选项卡
            // $where = [
            //     'status' => 2,
            //     'is_del' => 1,
            //     'shop_code'=>session('shop_code'),
            // ];
            // $today = date('Y-m-d');

            // $res = db('s_swapset')
            //     ->where($where)
            //     ->where('start_date', '<=', $today)
            //     ->where('end_date', '>=', $today)
            //     ->count();
            // if ($res) {
            //     $is_swap = 1;
            // }else{
            //     $is_swap = 2;
            // }

            // $this->assign('is_swap', $is_swap);
            //颜色
            $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');
            $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);
            $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);

            $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 H:i');
                $end=date('Y-m-d');
            }
            */
            if($list_date == 'week'){
                $start = date('Y-m-d 00:00',strtotime('-1 week'));
                $end=date('Y-m-d 23:59');
            }elseif($list_date == 'day'){
                $start=date('Y-m-d 00:00');
                $end=date('Y-m-d 23:59');
            }else{
                $start=date('Y-m-01 00:00');
                $end=date('Y-m-d 23:59');
            }
            
            $this->assign('start',$start);
            $this->assign('end',$end);
            if(session('shop_type') == 2){
                return view('customer_child');
            }else{
                return view('customer');
            }
        }
    }
    //标记提醒
    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']);
        // 20200825
        $data['sales_staff_id'] = trim($param['sales_staff_id']);
        $data['sales_staff'] = trim($param['sales_staff']);

        $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['introducer_number'] = $param['introducer_number'] ? trim($param['introducer_number']) : '';
        /* $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'] = intval($param['customer_type']);
        if($data['customer_type'] == 2){
            if(empty($data['customer_channel_id'])){
                $data['customer_channel_id'] = session('department_id');
                $data['customer_channel'] = session('department_name');
            }
        }
        $count = count($param['customer_name']);//提报客资数量
        if(!$count){
            return array('code'=>121,'msg'=>'请填写客资姓名');
        }
        $param['customer_sex'] = array_values($param['customer_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['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($data);
                if($res['code'] == 201){
                    session('sub_validate',null);
                    $returnData = array('code' => 300, 'msg' => $res['msg']);
                    return json($returnData);
                }
                if(is_array($res)){
                    return $returnData = array('code' => 500,'msg' => $res['msg'],'data'=>$res['data']);
                }else if ($res) {
                    //更新转介绍最后一次录入的介绍人信息
                    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('CCustomerinfo')->where('id', $res)->find();
                    $record['gtType'] = 4;
                    $record['customer_id'] = $res;
                    $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('c_salestrackinginfo')->insert($record);
                        cache('getCustomerTrackInfos' . $res, null);
                        getSalesTracking($res);
                        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 addCustomer(){
        $param = input('post.');
        // var_dump($param);die;
        $data = explode('&',$param['all']);
        foreach ($data as $key => $value) {
            $temp = explode('=', $value);
            unset($data[$key]);
            $data[$temp[0]] = urldecode($temp[1]);
        }
        // var_dump($data);die;
        if ($data['ad_page']) {
            if (substr($data['ad_page'], 0, 4) !== 'http') {
                $data['ad_page'] = 'http://'.$data['ad_page'];
            }
        }
        // $data['img_record'] = $param['img_record'];
        // $data['img_record'] = urldecode($param['img_record']);
        
        // $data = input('post.');
        $filename='addcus.txt';
        $str = 'tel--'.$data['customer_tel'].';channel--'.$data['customer_channel'].';ashop--'.$data['add_shop_code'].'-'.$data['add_shop_name'].';shop--'.$data['shop_code'].'-'.$data['shop_name'].';bid--'.$data['brandclass_id'].';bname--'.$data['brandclass'];
        textlog($str,$filename);
        $str = 'default--a'.$data['default_ashop_code'].'-'.$data['default_ashop_name'].';s'.$data['default_shop_code'].''.$data['default_shop_name'];
        $str.= ';--time'.$data['open_time'].';--now'.date('Y-m-d H:i:s');
        textlog($str,$filename);
        //$detail=controller("AddCustomer","lib")->add($data);
        //$res = controller('AddCustomer','lib')->addCustomer($detail);
        unset($data['file'],$data['default_ashop_code'],$data['default_ashop_name'],$data['default_shop_code'],$data['default_shop_name'],$data['open_time']);//不知道哪来的file参数；毛客资统计时添加失败，必须删除此参数
        // var_dump($data);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'];
        }
        $data['budget'] = DeleteHtml($data['budget']);//去除预算的table标签
        // if(session('is_marketing') == 4){
            $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');
            $staff = getStaffInfoById($data['dj_staff_id']);
            $data['dj_staff_number']=$staff['staffnumber'];

            $data['dj_department_id']= $data['dj_department_id'] ? $data['dj_department_id'] : session('department_id');
            // $data['customer_channel_id'] = $data['dj_department_id'];
            // $dep = controller('crm/Customer','lib')->getDepartment();
            // $data['customer_channel'] = $dep[$data['dj_department_id']]['department_name'];
            
        // }
        // else{
        //     $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');
        // }

        // 如果录转介绍客资
        if($data['customer_type'] == 2){
            $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'];
        }
        $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');

        // $data['shop_name'] = $data['shop_name'] ? $data['shop_name'] : session('belong_shop_name');
        // $data['shop_code'] = $data['shop_code'] ? $data['shop_code'] : session('belong_shop_code') ;
        // 如果是实体店

        if(session('shop_type') == 2){
            $data['customer_sex'] = '女';
        }
        $shopInfo = controller('crm/Customer','lib')->get_shop(['shop_code'=>$data['add_shop_code']]);
        if($data['company_shop_code']){
            $data['shop_name'] = $data['company_shop_name'];
            $data['shop_code'] = $data['company_shop_code'];
        }else{
            if(!$data['shop_code']){
                $data['shop_name']= session('belong_shop_name') ? session('belong_shop_name') : session('shop_name');
                $data['shop_code']= session('belong_shop_code') ? session('belong_shop_code') : session('shop_code');
            }
        }
        $str = 'session_shop--'.session('shop_code').'-'.session('shop_name').';session_bshop--'.session('belong_shop_code').'-'.session('belong_shop_name').';session_bid--'.session('brandclass_id').';session_bname---'.session('brandclass');
        textlog($str,$filename);
        $data['brandclass']= $data['brandclass'] ? $data['brandclass'] : session('brandclass');
        $data['brandclass_id']= $data['brandclass_id'] ? $data['brandclass_id'] : session('brandclass_id');
        $str = 'shop_type--'.session('shop_type').';ashop--'.$data['add_shop_code'].'-'.$data['add_shop_name'].';shop--'.$data['shop_code'].'-'.$data['shop_name'].';bid--'.$data['brandclass_id'].';bname--'.$data['brandclass'];
        textlog($str,$filename);
        unset($data['company_shop_name']);
        unset($data['company_shop_code']);

        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('is_valid',$data['is_valid']);//是否有效

        if(empty($data['add_shop_code'])||$data['add_shop_code']=='0'){
            // echo $data['add_shop_code'];
            $returnData = array('code' => 301,'msg' =>'无法获取门店信息，不可录入客资');
            return json($returnData);
        }
        $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(session('is_marketing') == 4){
            $data['customer_type'] = 2;
        }
        if(!$data['is_valid']){
            $data['is_valid'] = 2;
        }
        //来源渠道要默认给一个
        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;
                }
            }
        }
        
        if(empty($data['customer_type'])){
            $data['customer_type'] = 1;
        }
        if(!empty($data['customer_label'])){
            $data['customer_label'] = trim($data['customer_label'],',');
        }
        // var_dump($data['img_record']);
        // die;
        if(session('shop_type')== 2){
            $res = controller("Customer", "lib")->addCustomer_child($data);
        }else{
            $res = controller("Customer", "lib")->addCustomer($data);
        }
        // var_dump($res);
        // exit;

        if(empty($res)){
            return $returnData = array('code' => 500,'msg' =>'客资录入失败......','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' =>'客资录入失败('.$res['data'].')','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']
                );
                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);
                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);
        $this->assign('check_shop',$belong);
        $size=getMaxUploadSize();
        $this->assign('size', $size);
        return view('import');
    }

    //获取最新导入excel文件历史记录
    public function new_list(){
        $data = input();
        $res=controller("Customer","lib")->new_list($data);
        return $res;
    }

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


    //客资导入
    public function cus_import($data){
        $res=controller("Customer","lib")->cus_import($data);
        return $res;
    }

    //文件上传
    public function uploadExcel(){
        //获取表单上传文件
        $get_file=$_FILES;

        //  $param = input('param.');
        //   查询归属地是否筛客
        //  $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)){
        //          $param['is_sk'] == 1;
        //      }
        //       未选择筛客人则随机
        //      if(!$param['sk_staff_id']){
        //          unset($param['sk_staff_id']);
        //          unset($param['sk_staff']);
        //          $sklist = controller("Customer", "lib")->sklist('',24);
        //          $rand = rand(0,count($sklist)-1);
        //          $arr = $sklist[$rand];
        //          if(!empty($arr)){
        //              $param['sk_staff_id'] = $arr['id'];
        //              $param['sk_staff'] = $arr['staffname'];
        //          }
        //      }
        // }

        $before_name=$get_file['file']['name'];
        $file = request()->file('file');
        $data = input();
        $param = [];
        $param['shop_code'] = $data['shop_code'] ? trim($data['shop_code']) : '';
        $param['shop_name'] = $data['shop_name'] ? trim($data['shop_name']) : '';
        controller("Customer","lib")->uploadExcel($file,$before_name,$param);
    }

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

    //下载失败文件
    public function fail_file(){
        $id=input('get.');
        $res=controller("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('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('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';
            }
            $sql=controller('Customer','lib')->customerSearch($data);

            // var_dump($sql);
            // exit;
            if(check_right('menu1512637269')){
                switch (session('is_belong')){
                    case '2':
                        $sql .= " and c.brandclass = '".session('brandclass')."' ";
                        break;
                    case '3':
                        $sql .= " and (c.shop_code = '".session('shop_code')."' or c.add_shop_code = '".session('shop_code')."') ";
                        break;
                    case '4':
                        // $sql .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                        if(session('is_marketing') == 1){
                            $sql .= " and c.add_shop_code='".session('shop_code')."'";
                        }elseif(session('is_marketing') == 3 || session('is_marketing') == 4){
                            $sql .= " and c.shop_code='".session('shop_code')."'";
                        }else{
                            $sql .= " and (c.shop_code = '".session('shop_code')."' or c.add_shop_code = '".session('shop_code')."') ";
                        }
                        break;
                }
            }else{
                //如果没有查看所有客资权限,但有查看小组权限
                if(!$data['group']){
                    if(strpos($data['type_info'],'sales_staff_id')===false) {
                        if ($data['tab'] && $data['tab'] == 3) {//待分配
                            $sql .= " and (c.dj_staff_id='" . session('staff_id') . "' or (c.sales_staff_id='" . session('staff_id') . "' and c.is_fp=2 ) or c.sk_staff_id='" . session('staff_id') . "' )";
                        } elseif ($data['tab'] && ($data['tab'] == 8)) {//待筛客
                            $sql .= " and c.sk_staff_id = '" . session('staff_id') . "'  ";
                        } elseif ($data['tab'] && ($data['tab'] == 9)) {//、已筛客
                            $sql .= " and c.sk_staff_id = '" . session('staff_id') . "'  ";
                        } else {
                            if (!$data['dep']) {
                                if (session('is_marketing') == 1) {
                                    $sql .= " and (c.dj_staff_id='" . session('staff_id') . "' or c.sk_staff_id='" . session('staff_id') . "')";
                                } elseif (session('is_marketing') == 3 || session('is_marketing') == 4) {
                                    $sql .= " and c.is_fp=1 and (c.sales_staff_id='" . session('staff_id') . "' or c.sk_staff_id='" . session('staff_id') . "')";
                                } else {
                                    $sql .= " and (c.dj_staff_id='" . session('staff_id') . "' or (c.sales_staff_id='" . session('staff_id') . "' and c.is_fp=1 ) or c.sk_staff_id='" . session('staff_id') . "' )";
                                }
                            }
                        }
                    }
                }
            }
        }
        $columnInfo = db('s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->find();
        // 未设定 或 无自定义列
        if (!$columnInfo || !$columnInfo['custom_column']) {
            if(session('shop_type') ==2){
                $field = 'c.id,c.customer_channel,c.sign_name,c.is_valid,c.op_signinfo,c.customer_number,c.baby_name,c.baby_sex,c.baby_birthday,c.ready_baby_day,c.customer_name,c.customer_sex,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.mate_name,c.mate_tel,c.mate_wechat,c.city,c.customer_key,c.marry_day,c.budget,c.consulation_shop,c.yjd_action_day,c.yjd_day,c.channel_plan_number,c.ad_page,c.track_record,c.customer_label,c.is_intostore,c.syjd_day,c.is_success,c.order_start_time,c.order_day,c.order_type,c.totalpay_money,c.fact_money,o.order_fact,o.order_amount,c.loss_cause,c.customer_type,c.dj_day,c.create_time,c.is_fp,c.is_loss,c.dj_staff,c.sales_staff,c.sk_staff,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.introducer_type,c.tel_visit_num,c.c_star_day,c.last_trackday,c.consultation_type,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,c.brandclass,c.shop_name,c.add_shop_name,c.order_number,c.customer_remark,c.add_friend_time';
            }else{
                $field = 'c.id,c.customer_channel,c.sign_name,c.is_valid,c.op_signinfo,c.customer_number,c.customer_name,c.customer_sex,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.mate_name,c.mate_tel,c.mate_wechat,c.city,c.customer_key,c.marry_day,c.budget,c.consulation_shop,c.yjd_action_day,c.yjd_day,c.channel_plan_number,c.ad_page,c.track_record,c.customer_label,c.is_intostore,c.syjd_day,c.is_success,c.order_start_time,c.order_day,c.order_type,c.totalpay_money,c.fact_money,o.order_fact,o.order_amount,c.loss_cause,c.customer_type,c.dj_day,c.create_time,c.is_fp,c.is_loss,c.dj_staff,c.sales_staff,c.sk_staff,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.introducer_type,c.tel_visit_num,c.c_star_day,c.last_trackday,c.consultation_type,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,c.brandclass,c.shop_name,c.add_shop_name,c.order_number,c.customer_remark,c.add_friend_time';
            }
            if(session('shop_type') ==2){
                $title=export_header_child();
            }else{
                $title=export_header();
            }
        }else{
            $fieldArr = explode(',', $columnInfo['custom_column']);
            $field = 'c.id,';
            // var_dump($fieldArr);
            foreach ($fieldArr as $key => $value) {
                // 20191015  这里要判断字段
                if ($value=='dj_group_name') {
                    $field .= 'f.'.$value.',';
                }else if ($value=='sales_group_name') {
                    $field .= 'f.'.$value.',';
                }else if ($value=='order_fact') {
                    $field .= 'o.'.$value.',';
                }else if ($value=='order_amount') {
                    $field .= 'o.'.$value.',';
                }else if ($value=='bonus') {
                    $field .= 'f.'.$value.',';
                }else if ($value=='bonus_deal') {
                    $field .= 'f.'.$value.',';
                }
                else{
                    $field .= 'c.'.$value.',';
                }
            }
            $field = trim($field, ',');
            $custom_name = json_decode($columnInfo['custom_name'], true);
            // $title = substr($title, 0,2);
            $custom_name = trim($custom_name,'"[');
            $custom_name = trim($custom_name,']"');
            $custom_name = explode(',', $custom_name);
            $title = [0=>'客资ID'];
            foreach ($custom_name as $key => $value) {
                array_push($title,trim($value,'"'));
            }
        }
        $count = db('c_customerinfo c')->join('c_customer_from f','c.id=f.cid','left')->where($sql)->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;
            */
            $pdo = db('c_customerinfo')->getConnection()->getPdo();
            $pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

            $customerSql=db('c_customerinfo c')->join('c_customer_from f','c.id=f.cid','left')->join('c_customer_order o','o.order_sn=c.order_number and o.customer_id=c.id','left')->field($field)->where($sql)->fetchSql()->select();
            $sql = db()->getLastSql();
            //根据单号查询金额
            $orderSN = array_column($customerSql,'order_number');
            $ids = array_column($customerSql,'id');
            $order = db('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['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']);
                }
                $value['customer_number'] = '="'.$value['customer_number'].'"';
                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['erp_loss']) {
                    $value['erp_loss']=getErpLoss($value['erp_loss']);
                }
                if ($value['ready_baby_day']) {
                    $value['ready_baby_day']=date('Y-m-d',strtotime($value['ready_baby_day']));
                }
                if ($value['baby_birthday']) {
                    $value['baby_birthday']=date('Y-m-d',strtotime($value['baby_birthday']));
                }
                if ($value['marry_day']) {
                    $value['marry_day']=date('Y-m-d',strtotime($value['marry_day']));
                }
                if ($value['order_type'] == 1 && $value['is_success'] != 2) {
                    $value['order_type']='线上';
                }elseif($value['order_type'] == 2 && $value['is_success'] != 2){
                    $value['order_type']='线下';
                }
                if ($value['c_from'] == 1) {
                    $value['c_from']='CRM';
                }elseif($value['c_from'] == 2){
                    $value['c_from']='ERP';
                }
                $value['channel_plan_number'] = $value['channel_plan_number']+"\t";
                if ($value['introducer_type']) {
                    $value['introducer_type']=getIntroducerType($value['introducer_type']);
                }
                if($value['track_record']){
                    $temp = explode('<br/>', $value['track_record']);
                    $str = '';
                    foreach ($temp as $k => $v) {
                        if ($v) {
                            $str .= str_replace('&nbsp;',' ',strip_tags($v))."\r\n";
                        }
                    }
                    $value['track_record'] = $str;
                }
                if ($value['customer_remark']) {
                    $value['customer_remark'] = str_replace( '&nbsp;',' ',strip_tags($value['customer_remark']) );
                }
                $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", $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('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,$sql,0,session('staff_id'),session('staff_name'));
            exit;
        }else{
            set_time_limit(0);
            $field .= ',dj_group_name,sales_group_name';
            $customer=db('c_customerinfo c')->join('c_customer_from f','c.id=f.cid','left')->join('c_customer_order o','o.order_sn=c.order_number and o.customer_id=c.id','left')->field($field)->where($sql)->select();


            $sql = db()->getLastSql();
            //根据单号查询金额
            $orderSN = array_column($customer,'order_number');
            $ids = array_column($customer,'id');
            $order = db('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');
            foreach ($customer as $key => $value) {
                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['order_type'] == 1 && $value['is_success'] != 2) {
                    $value['order_type']='线上';
                }elseif($value['order_type'] == 2 && $value['is_success'] != 2){
                    $value['order_type']='线下';
                }else{
                    $value['order_type']='';
                }
                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['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) : '';
                $value['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) : '';
            }
            $log = '由【'.session('staff_name').'】于【'.date('Y-m-d H:i:s').'】导出【'.session('shop_name').'】客资【'.count($customer).'】条，所在IP【'.get_client_ip().'】';
            action_log($log,$sql,0,session('staff_id'),session('staff_name'));
            $file="customer.xlsx";
            controller("Customer","lib")->export($title,$customer,$file);
        }
    }

    //模板下载
    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("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('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('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('track',$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('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('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('c_customerinfo')->where('id','in',$cids)->update($upData);
	    	// 新增操作记录
	    	db('action_log','db_logs')->insertAll($lData);
	    	// 删除pool表中的筛客数据
	    	db('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(){
        $auth = check_right('menu1512970623');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有分配客资的权限，请先设置权限');
            return json($return);
        }

        $data = input();
        $brandlist = db('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'=>'选中客资包含多个事业部，请重新选择。');
        }
        $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++;
        }
        unset($targets);
        $this->assign('targetList',$targetList);
        */

        $shopList = [];
        $departmentList = [];
        // 如果没有事业部 20200318
        if(empty(session('brandclass_id')) || !session('shop_code')){ //
            $brand = controller('crm/Customer','lib')->getBrandClass();
            $this->assign('brand',$brand);
            // 如果只有一个事业部，默认选中
            if (count($brand) == 1) {
                $brand[0]['select'] = 1;
                // 获取该员工事业部下可操作店
                $p = [
                    'staff_id'=> session('staff_id'),
                    'brandclass_id'=> $brand[0]['id'],
                    'shop_type' => session('shop_type')
                ];
                $shopList = getShops($p);
                // 如果只有一个店， 默认选中
                if (count($shopList) == 1) {
                    $shopList[0]['select'] = 1;
                    // 获取店下的部门
                    $departmentList = getDepartments(array('shop_code'=>$shopList[0]['shop_code']));
                }
            }
        }else{
            $param['staff_id']        = session('staff_id');
            $param['shop_type']       = session('shop_type');
            $param['shop_code']       = session('shop_code');
            $param['brandclass_id']   = session('brandclass_id');
            $param['belong_shop_code']= session('belong_shop_code');
            $param['belong_shop_name']= session('belong_shop_name');
            $shopList = getBelongShop($param);
            unset($param);
            foreach ($shopList as $key => $value) {
                if ($value['shop_code'] == session('belong_shop_code')) {
                    $shopList[$key]['select'] = 1;
                    $paramD['shop_code'] = $value['shop_code'];
                    $departmentList = getDepartments($paramD);
                }else{
                    $shopList[$key]['select'] = 0;
                }
            }
        }
        // 如果只有一个部门 并获取该部门下小组
        if (count($departmentList) == 1) {
            $departmentList[0]['select'] = 1;

            $paramG['department_id'] = $departmentList[0]['id'];
            $groupList = getGroups($paramG);
        }
        // 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);
        //             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'];
        //                     $gList = getGroups($paramG);
        //                     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';
        //         }
        //     }
        // }
        
        $this->assign('brand',$brand);
        $this->assign('shopList',$shopList);
        $this->assign('department',$departmentList);
        $this->assign('group',$groupList);
        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);

        // 筛客
        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'] : '';

        // 根据部门id查员工  getGroupStaffs
        // if ($department_id) {
        //     $staffs = controller('Statistics','lib')->getDepartmentStaffs($department_id);
        // }
        // // 没有部门id，根据shop_code查员工
        // else{
            if($department_id) $pram['department_id'] = $department_id;
            if($shop_code){
                $pram['shop_code'] = $shop_code;
                $pram['work_type'] = RECEIVE_WORK_TYPE;
                $pram['department_id'] = $department_id;
                $staffs = cache('staffs_21'.$shop_code.$department_id.$method);
                if(empty($staffs)){
                    // $staffs = controller('Customer','lib')->get_staff_lists($pram);
                    $staffs = getShopStaffs($pram);
                    cache('staffs_21'.$shop_code.$department_id.$method,$staffs);
                }
            }
        // }
        // var_dump($staffs);
        // exit;
        $day = getdateArea($time_area);
        // var_dump($day);die;
        //获取小组下的员工
        if($group_id){
            $groupStaffs = db('c_staff_group_relation')->where('group_id',$group_id)->select();
            $staffs = [];
            foreach($groupStaffs as $k=>$v){
                $staffs[$k]['id'] = $v['staff_id'];
                $staffs[$k]['staffname'] = $v['staff_name'];
            }
        }

        $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 = controller("crm/Customer","lib")->noStaffId($condition);
        // 计算每一个员工的业绩
        // var_dump($method);die;
        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)){
                $targInfo = controller("crm/Target","lib")->$method($condition);
                // var_dump($targInfo);
            }else{
                return $staffs;
            }
        }
        // die;
        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['name'] = $value['staffname'];
                        $res1['id'] = $value['id'];
                        $res1['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;

                        $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']]['num'] ? $targInfo[$value['id']]['num'] : 0;
                        // }else{
                        //     $res1['rate'] = 0;
                        // }
                        if ($res1['rate'] && $res1['cNum']) {
                            $res1['rate'] .= '('.number_format(($res1['rate']/$res1['cNum'])*100,2).'%'.')';
                        }
                        // $res1['cNum'] = controller("crm/Customer","lib")->noStaffId($condition);
                        array_push($a,$res1);
                    }else{
                        $res['name'] = $value['staffname'];
                        $res['id']   = $value['id'];
                        $res['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;

                        $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']]['num'] ? $targInfo[$value['id']]['num'] : 0;
                        // }else{
                        //     $res['rate'] = 0;
                        // }
                        if ($res['rate'] && $res['cNum']) {
                            $res['rate'] .= '('.number_format(($res['rate']/$res['cNum'])*100,2).'%'.')';
                        }
                        // $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['name'] = $value['staffname'];
                    $res1['id'] = $value['id'];
                    $res1['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;

                    $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']]['num'] ? $targInfo[$value['id']]['num'] : 0;
                    // }else{
                        // $res1['rate'] = 0;
                    // }
                    if ($res1['rate'] && $res1['cNum']) {
                        $res1['rate'] .= '('.number_format(($res1['rate']/$res1['cNum'])*100,2).'%'.')';
                    }
                    // $res1['cNum'] = controller("crm/Customer","lib")->noStaffId($condition);
                    array_push($a,$res1);
                }else{
                    $res['name'] = $value['staffname'];
                    $res['id'] = $value['id'];
                    $res['cNum'] = $info[$value['id']] ? $info[$value['id']] : 0;

                    $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']]['num'] ? $targInfo[$value['id']]['num'] : 0;
                    // }else{
                        // $res['rate'] = 0;
                    // }
                    if ($res['rate'] && $res['cNum']) {
                        $res['rate'] .= '('.number_format(($res['rate']/$res['cNum'])*100,2).'%'.')';
                    }
                    // $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']);
            }
            // }
        }

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

    // 手动分配 接收
    public function allotReceive(){
        $data = input('post.');
        $type = (int)$data['type'] ? (int)$data['type'] : 1;
        $shop_code  = $data['shop_code'];
        $shop_name  = $data['shop_name'];

        $sid  = $data['sid'] ? $data['sid'] : session('staff_id');
        $rigth = check_right('menu1512970623');
        $date = date('Y-m-d H:i:s',time());
        if ($rigth) {
            // var_dump($type);exit;
            // 分配追踪人
            if ($type == 1) {
                //如果追踪人已经是要分配的人，去掉
                /*$sales = db('c_customerinfo')->alias('c')->join('c_customer_from f','c.id=f.cid','left')
                    ->where('c.id','in',$data['cid'])->field('c.id,c.sales_staff_id,c.shop_code,c.sales_department_id,f.sales_group_id')->select();
                $cid = '';
                foreach($sales as $kk=>$vv){
                    if($vv['sales_staff_id'] != $sid || $vv['shop_code'] != $shop_code){
                        $cid  .= $vv['id'].',';
                    }
                }*/
                $cid = trim($data['cid'],',');
                $arr['cid'] = $cid;
                $arr['sid'] = (int)$sid;
                $arr['shop_code'] = $shop_code;
                $arr['shop_name'] = $shop_name;
                $arr['department_id'] = $data['department_id'];
                $arr['department_name'] = $data['department_name'];
                $result = controller("crm/Customer","lib")->allotSale($arr);
                return $result;
                /*
                if ($result['code']!=200) {
                    return $result;
                }
                $cids = explode(',', $cid);
                $url = '59f933a395abe';
                $arr = array('staff_id'=>$sid);
                $staff = sx_call($url, $arr);
                $res = $staff['data'];
                $cNum = count($cids);
                // 发送消息用数据
                $remind = getRemind(session('brandclass_id'));
                // 181212 Eric
                if($sid  != session('staff_id') && in_array('tan',$remind['sd']['send_method']) && in_array('sales',$remind['sd']['send_receive'])){
                    $messageD['send_type']      = 1;
                    $messageD['send_time']      = $date;
                    $messageD['send_title']     = '分配提醒';
                    $messageD['send_msg']       = '您分配到'.$cNum.'笔客资，请查收。';
                    $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 ? $timeOut : 60;

                    $resM = sendSystemMessage($messageD);
                }
                // 发送微信模板消息
                if($sid != session('staff_id') && in_array('tui',$remind['sd']['send_method']) && in_array('sales',$remind['sd']['send_receive'])){
                    $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'=>'分配完成','sql'=>$result['sql'],'wx'=>json_encode($res)];
                return $returnData;
                */
            }
            // 分配筛客人
            if ($type == 2) {
                $arr['cid'] = $data['cid'];
                $arr['sid'] = (int)$sid;
                $res = controller("crm/Customer","lib")->allotSk($arr);
                return $res;
            }
        }else{
            $returnData = ['code'=>100,'msg'=>'抱歉，您没有分配权限'];
        }
        return json($returnData);
    }
    // 手动分配 接收
    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'];
                $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']   = $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 ? $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'] = $res['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,
            ];
            $messageH = array(
                'type'      => 1,
                'staff_id'  => $sid,
                'identity'  => 'sale',
                'cinfo'     => $cinfo,
                'old_data'  => $has,
                'new_data'  => $newDate,
                'controller'=> 'Customer',
                'action'    => 'customerAllotOne',
            );
            // 分配日志
            $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('c_customerinfo')->where('id', $cid)->update($newDate);
                // $resM = sendSystemMessage($messageD);
                $listName = 'historyDataList';
                $resH = push_list($listName, $messageH);
                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('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('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('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('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('c_customer_from')->where('cid',$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('c_customer_from')->where('cid','in',$arrcid[$k])->update($group);
                    }
                    if(empty($from['dj_group_id'])){
                        //登记人小组信息
                        $groupInfo = getGroupInfo($cInfo['dj_staff_id']);
                        //更新追踪人小组信息
                        db('c_customer_from')->where('cid','in',$arrcid[$k])->update(['dj_group_id'=>$groupInfo['id'],'dj_group_name'=>$groupInfo['group_name']]);
                    }
                }else{
                    //登记人追踪人小组信息
                    $groupInfo = getGroupInfo($cInfo['dj_staff_id']);
                    $group = array(
                        'cid' => $arrcid[$k],
                        'dj_group_id'=>$groupInfo['id'],
                        'dj_group_name'=>$groupInfo['dj_group_name'],
                        'sales_group_id'  => session('group_id'),
                        'sales_group_name'  => session('group_name'),
                    );
                    db('c_customer_from')->insert($group);
                }
                // 接收成功之后，删除c_fp_pool
                db('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'];

                $listName = 'historyDataList';
                $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'],
                ];
                $message = array(
                    // 数据统计类型（1：单条；2：批量导入）
                    'type'      => 1,
                    'staff_id'  => session('staff_id'),
                    'identity'  => 'sale',
                    'cinfo'     => $cinfo,
                    'old_data'  => $old_data,
                    'new_data'  => $dataC,
                    'controller'=> 'Customer',
                    'action'    => 'customerReceive',
                );
                push_list($listName,$message);

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

                db('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('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('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('c_customer_from')->where('cid',$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('c_customer_from')->where('cid','in',$cid)->update($group);
                }
                if(empty($from['dj_group_id'])){
                    //登记人小组信息
                    $groupInfo = getGroupInfo($cInfo['dj_staff_id']);
                    //更新追踪人小组信息
                    db('c_customer_from')->where('cid','in',$cid)->update(['dj_group_id'=>$groupInfo['id'],'dj_group_name'=>$groupInfo['group_name']]);
                }
            }else{
                //登记人追踪人小组信息
                $groupInfo = getGroupInfo($cInfo['dj_staff_id']);
                $group = array(
                    'cid' => $cid,
                    'dj_group_id'=>$groupInfo['id'],
                    'dj_group_name'=>$groupInfo['dj_group_name'],
                    'sales_group_id'  => session('group_id'),
                    'sales_group_name'  => session('group_name'),
                );
                db('c_customer_from')->insert($group);
            }
            // 接收成功之后，删除c_fp_pool
            db('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'];

            $listName = 'historyDataList';
            $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'],
            ];
            $message = array(
                // 数据统计类型（1：单条；2：批量导入）
                'type'      => 1,
                'staff_id'  => session('staff_id'),
                'identity'  => 'sale',
                'cinfo'     => $cinfo,
                'old_data'  => $old_data,
                'new_data'  => $dataC,
                'controller'=> 'Customer',
                'action'    => 'customerReceive',
            );
            push_list($listName,$message);

            $fpLogData = [
                'fp_status' => 1,
                'jr_time'   => $date,
            ];
            db('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', $cinfo['fp_day'])
                ->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('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('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('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('c_customerinfo')->where('id', $arrcid[$k])->update($cData);

                // 更新分配日志中的状态
                $fpLogData = [
                    'jr_time'   => $date,
                    'fp_status' => 5
                ];
                db('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('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('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('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('c_customerinfo')->where('id', $cid)->update($cData);
            // 更新分配日志中的状态
            $fpLogData = [
                'jr_time'   => $date,
                'fp_status' => 5
            ];
            db('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('c_message')->where($whereCount)->count();
        return $res;
    }

    // 员工请求  ajax递归，订阅发布频道
    public function staffSubscribe($msg_id){
        $staffinfo = cache('staffInfo_'.session('staff_id'));
        $staffinfo['active'] = time();
        cache('staffInfo_'.session('staff_id'),$staffinfo);

        $lWhere['session_id']= session('session_id');
        $lWhere['staff_id']  = session('staff_id');
        $ltime = date('Y-m-d');
        $lid = db('l_login_log')->where($lWhere)->where('last_login_time', 'like', $ltime.'%')->order('id desc')->value('id');

        $active = isColumnExist(array('table'=>'l_login_log','column'=>'active'));
        if ($active&&$lid) {
            $lup['active'] = $staffinfo['active'];
            db('l_login_log')->where('id',$lid)->update($lup);
        }
        // update(array('active'=>$staffinfo['active']));
        // exit;
        // 第一次请求，$msg_id == 0
        // list1：最近10条消息，不区分已读未读；messageList
        // list2：最近五条未读弹框消息 popList
        // noRead：未读消息数目
        // mid：最近一条消息的id
        // 之后的请求  $msg_id != 0
        // 数据库对比最后一条消息的id
        //   一样 则 订阅频道
        // 不一样 则 取出后面的消息，两个list弹框和铃铛，noRead，mid
        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;

        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(){
        $shop_code = session('shop_code');
        $url = '5a0aef152b750';
        $arr = array('shop_code'=>$shop_code);
        $staffs = sx_call($url, $arr);
        return $staffs['data'];
    }
    // 获取部门信息 wzy
    public function getDepartments($data){
        $url = '5a0aef152b750';
        $staffs = sx_call($url, $data);
        return $staffs['data'];
    }

    // 根据部门id获取部门下的员工 Eric
    public function getDepartmentStaffs($department_id){
        $url = '5a0e6f272bb38';
        $arr = array('department_id'=>$department_id,'get_leave'=>2);
        $staffs = sx_call($url, $arr);
        return $staffs['data'];
    }
    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();
        $staffArr = $mcInter->getStaffInfo($data);
        return json($staffArr);
    }
    // 显示驳回页面
    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);
    }
    // 确定客资驳回动作 ****  这个控制器不用了  在lib 下有 customerReject
    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('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')->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('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',
                    '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('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;
                    // 20200612
                    $message['operation_type'] = 1;
                    $message['operation']      = [
                        [
                            'button'=>'查看',
                            'url'=>'/crm/Customer/customerList?client_customer_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;
        }
        $param = input();
        $data['fbhReason'] = $param['fbhReason'];
        $data['cid'] = $param['cid'];
        if (!trim($data['fbhReason'])) {
            $return = array('error'=>'1','code'=>100,'msg'=>'请输入驳回原因');
            exit;
        }
        $return = controller('crm/Customer','lib')->customerUnValidUpdate($data);
        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;
    }
    // 获取订单所有服务信息
    public function getAllServiceInfo(){
        $data = input();
        $order_sn = $data['order_sn'];
        // $order_sn = 'SY18020600018';
        // 是否安装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/All_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Tel='.$tel.'&orderId='.$order_sn;
            }else{
                $shop_type = 0;
                $addr= $erp['addr'];
                $url = trim($addr,'/').'/SX_CrmApi/All_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Tel='.$tel.'&orderId='.$order_sn;
            }
            $dataErp = '[]';

            $response = requestERP($url, $dataErp);
            if ($response['Code'] == 200) {
                // 基础信息  订单表
                $baseInfo = $response['Data']['C_order'];
                // var_dump($baseInfo);
                $this->assign('baseInfo', $baseInfo);
                // 产品信息  消费项目
                $cpInfo = $response['Data']['C_page'];
                $this->assign('cpInfo', $cpInfo);
                // 摄影信息
                $syInfo = $response['Data']['C_photo'];
                $this->assign('syInfo', $syInfo);
                // print_r($syInfo);
                // 选片信息
                $xpInfo = $response['Data']['C_sp'];
                $this->assign('xpInfo', $xpInfo);
                // 收款信息
                $skInfo = $response['Data']['C_payment'];
                $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(){
        //手机配置地址
        // $this->assign("patrn",check_tel_arr());
        // 提交客资详情资料
        if (request()->isPost()) {
            $data = input('post.');
            // var_dump($data);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['id']) {
                $returnData = array('code' => 100,'msg' =>'用户ID数据为空，请重试');
                return json($returnData);
            }

            $has = controller("Customer","lib")->getCustomerInfo($data['id']);
            if (!$has) {
                $returnData = array('code' => 900,'msg' =>'用户数据不存在，请检查！');
                return json($returnData);

            }
            //如果是筛客操作，增加筛客时间
            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')]);
                if($info['data'][0]['order_rule'] == 1){//实际收款达到多少
                    if($data['fact_money'] >= $info['data']['proportion']){
                        //修改订单为有效
                        $data['is_success'] = 1;
                    }else{
                        $data['is_success'] = 3;
                    }
                }elseif($info['data'][0]['order_rule'] == 2){//实际收款占套系金额的百分比
                    if($data['fact_money']/$data['totalpay_money'] >= $info['data']['proportion']/100){
                        //修改订单为有效
                        $data['is_success'] = 1;
                    }else{
                        $data['is_success'] = 3;
                    }
                }
            }
            // customer_tel customer_weibo customer_wechat  customer_qq
            // 如果，手机号，微信，微博，qq，都不存在，返回报错
            if (!$data['customer_tel'] && !$data['customer_wechat'] && !$data['customer_qq']) {
                $returnData = array('code' => 300,'msg' =>'请填写手机号、微信、QQ任一项联系方式');
                return json($returnData);
            }
            // 渠道不存在，返回报错
            // if (!$data['customer_channel_id']) {
            //     $returnData = array('code' => 400,'msg' =>'请填写客资来源渠道');
            //     return json($returnData);
            // }

            // 判断手机号，同一个事业部（品牌）相同手机号(且没有过期)，不能提交
            // $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 = 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());
            }
            if(empty($customerInfo['customer_qq'])&&!empty($data['customer_qq'])){
                $data['qq_staff_id']=session('staff_id');
                $data['qq_staff']=session('staff_name');
                $data['qq_time']=date('Y-m-d H:i:s',time());
            }
            // 对比提交数据和原始数据
            foreach ($data as $key => $value) {
                if ($value != strip_tags($has[$key])) {
                    // $kStr = translate('c_customerinfo',$key);
                    // if ($kStr) {
                    //     $oldDate[$kStr]  = $has[$key];
                    //     $newDate[$kStr]  = $value;
                    // }
                    $newDateIn[$key] = $value;
                    $oldDateIn[$key] = strip_tags($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($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('s_reminditemset')->where('id','remind2')->where('shop_code',session('shop_code'))->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('c_fp_pool')->insertGetId($arr);
                    if(!$inc1){
                        db()->rollback();
                        $returnData = array('code' => 0,'msg' =>'再约进店失败');
                        return json($returnData);
                    }else{
                        db()->commit();
                    }
                }
                //查询再约提前时间  分钟
                $adv = db('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('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['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());
            //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('c_customerinfo')->where('id', $data['id'])->update($newDateIn);
                // 如果修改客资备注 
                foreach ($newDateIn as $key => $value) {
                    if ($key=='customer_remark') {
                        $record['gtType']=4;
                        $record['customer_id']=$customerInfo['id'];
                        $record['customer_name']=$customerInfo['customer_name'];
                        $record['customer_number']=$customerInfo['customer_number'];
                        $record['sales_staff_id']=session('staff_id');
                        $record['sales_staff']=session('staff_name');
                        $record['sales_staff_number']=session('staff_number');
                        $record['shop_name']=session('shop_name');
                        $record['shop_code']=session('shop_code');
                        $record['sales_day']=date('Y-m-d H:i:s',time());
                        $record['sales_remark'] = '修改客资备注：'.$value;
                        db('c_salestrackinginfo')->insert($record);
                        getSalesTracking($customerInfo['id']);
                    }
                }
                history_log($newDateIn, $oldDateIn,$data['id'], session('staff_id'), session('staff_name'));

                if($newDateIn['is_intostore']){
                    //如果是爆破活动，修改对应的爆破表数据
                    if($customerInfo['is_act'] == 2){
                        db('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);
                    // }
                }
                //进店操作变动记录追踪日志
                if($newDateIn['is_intostore']){
                    $str = getIsIntostore($newDateIn['is_intostore']);
                    //追踪记录
                    $params['customer_id'] = $data['id'];
                    $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('CSalestrackinginfo')->insert($params);
                    cache('getCustomerTrackInfos'.$data['id'],null);
                    //修改追踪时间
                    $info = controller("Customer","lib")->getCustomerInfo($data['id']);//客资信息
                    $time = date('Y-m-d H:i:s',time());
                    if(empty($info['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('CCustomerinfo')->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'));
                }
                //客资标为无效删除其联系方式
                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('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('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('c_customer_contact')->insertAll($contactList);

                        $del = array_diff($contact, $customer_contact);
                        foreach ($del as $k => $v) {
                            db('c_customer_contact')->where('c_id', $has['id'])->where('contact',$v)->delete();
                        }
                    }
                }
                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("Customer","lib")->getCustomerInfo($cid);
                $customerInfo['customer_remark'] = db('c_customerinfo')->where('id',$cid)->value('customer_remark');
                // var_dump($customerInfo['customer_remark']);
                // die;
                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("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;
                    // 20200226
                    $allSet['ready_marry_day'] = controller("crm/Customer","lib")->ready_marry_day( array('brandclass_id' => session('brandclass_id')) );
                    $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']);
                foreach ($trackInfos as $key => $value) {
                    $temp = strtotime($value['sales_day']);
                    $trackInfos[$key]['date'] = date('m月d日', $temp);
                    $trackInfos[$key]['time'] = date('H:i:s', $temp);
                    // $trackInfos[$key]['allTime'] = self::secToTime($value['tel_alltime']);
                    $trackInfos[$key]['allTime'] = $value['tel_alltime'];

                }
                // var_dump($trackInfos);
                // exit;
                $this->assign('trackInfos', $trackInfos);

                // 修改日志
                $changeLogs = controller("Customer","lib")->getCustomerChangeLogs($cid);
                $info = [];
                foreach($changeLogs as $k=>$v){
                    if(is_json($v['old_data'])){
                        $oldDate = json_decode($v['old_data'], true);
                        $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>';
                            }
                        }
                    }else{
                        $oldDateStr = $v['old_data'];
                    }
                    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>';
                            }
                        }
                    }else{
                        $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'];
                }
                $this->assign('changeLogs', $info);
                // 历史订单，现在没有表，调其他接口
                $historyOrders = controller("Customer","lib")->getCustomerHistoryOrders($cid);
                $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("Customer","lib")->getMsgList($customerInfo);
                $this->assign('msg',$msg);
                // print_r($historyOrders);
                // exit;
                $this->assign('erp_status', $erp_status);
                $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;
            }
            // var_dump($allSet['consultationType']);
            // var_dump($customerInfo);
            // exit;
            // var_dump($trackInfo);
            // var_dump($changeLogs);
            // var_dump($historyOrder);
            //录入必选项配置
            $lrMust = db_config('lr_must_'.session('brandclass_id'));
            $lrMust = trim($lrMust,',');
            $lrMust = explode(',',$lrMust);
            $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);
            }
            if(session('shop_type') == 2){
                $baby_sex = config('baby_sex');
                if(empty($baby_sex)){
                    $baby_sex = [
                        ['sex'=>'男',],
                        ['sex'=>'女',],
                    ];
                }
                $this->assign('baby_sex',$baby_sex);
                return $this->fetch('customerinfo_child');
            }else{
                return $this->fetch('customerinfo');
            }
        }
    }
    // 删除消息
    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'=>'删除失败'));
        }
    }
    // 清空全部消息
    public function delAllMsg(){
        if (controller("Customer","lib")->delAllMsg()) {
            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('c_message')
            ->where($where)
            ->where('send_time','between',[$start,$end])
            ->limit($limit)
            ->page($page)
            ->order('id desc')
            ->select();//return json(db('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('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 customerAdd(){
        //手机配置地址
        //$this->assign("patrn",check_tel_arr());
        //来源渠道
        // $channel=controller("Customer","lib")->channel();
        $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);

        //客户标记
        $mark=controller("crm/Customer","lib")->markSet();
        $this->assign("market",$mark);
        $this->assign("mark1",$mark);
        //消费能力
        $capacity=controller("Customer","lib")->capacity(array('shop_code'=>session('shop_code')));
        $this->assign("capacity",$capacity);
        //所有客资姓名
        /*$customer_name=db('c_customerinfo')->where(array('is_success'=>1))->select();
        $this->assign("customers",$customer_name);*/
        //客户地址
        $data['type']=1;
        $address=controller("crm/Customer","lib")->address($data);
        $this->assign("address",$address);

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

        $this->assign("shopAllStaff",$shopAllStaff);
        $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');//是否加急
        //查询归属地是否筛客
        $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);
            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));
            }
        }
        // die;
        $this->assign('cookie',$cookie);
        $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('SMessageTemplateinfo')->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);//可操作店
        /*
        if(session('is_belong') == 1){
            $p = [
                'staff_id'=> session('staff_id'),
                'brandclass_id'=> session('brandclass_id'),
                'shop_type' => session('shop_type')
            ];
            $djshops = getShops($p);//可操作店
        }elseif(session('is_belong') == 2){
            $djshops = controller('crm/Customer','lib')->get_shop(array('brandclass_id'=>session('brandclass_id')));
        }else{
            $djshops = [
                'shop_code' => session('shop_code'),
                'shop_name' => session('shop_name'),
            ];
        }
        */
        $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);
        }
        // 
        $checked_shop = db_config('dj_shops_'.session('shop_code'));
        $this->assign('check_shop',$checked_shop);
        // $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);
        //客户来源
        $source=controller("crm/Customer","lib")->source(array('shop_code'=>session('shop_code')));
        //客资标记
        $tracksign=controller("crm/Setting","lib")->gettrackingKmarkerList();
        $this->assign("tracksign",$tracksign);
        // 客资录入类型  eric 190122
        // 
        $customer_type = db_config('customer_type_'.session('shop_code'));
        if (!$customer_type) {
            // 当前店面是否为转介绍客资接入店
            $mc = new \app\common\lib\mcInterface();
            $shopInfo = $mc->getShopInfo(array('shop_code' => session('shop_code')));
            // var_dump($shopInfo);
            // 如果是转介绍客资接入店 提报转介绍客资
            if ($shopInfo[0]['is_dig'] == 1) {
                // 只有转介绍，没有新客资
                $only = 'zjs';
            }else{
                // 只有新客资，没有转介绍
                $only = 'new';
            }
        }else{
            $customer_type = explode(',', $customer_type);
            if (count($customer_type)==2) {
                $only = 'all';
            }else{
                if ($customer_type[0] == 1) {
                    $only = 'new';
                }else{
                    $only = 'zjs';
                }
            }
        }
        $this->assign('only', $only);
        $target = input('get.target');
        // var_dump($target);
        // exit;
        //客资标签
        $cat = cache('label_'.session('brandclass_id'));
        if(empty($cat)){
            $cat = db('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('s_label')->where('brandclass_id',session('brandclass_id'))->where('label_cat_id',$v['id'])->select();
                if(empty($cat[$k]['label'])){
                    unset($cat[$k]);
                }
            }
            cache('label_'.session('brandclass_id'),$cat);
        }

        $this->assign('cat',$cat);
        // 预计婚期
        $ready_marry_day = controller("crm/Customer","lib")->ready_marry_day( array('brandclass_id' => session('brandclass_id')) );
        $this->assign('ready_marry_day', $ready_marry_day);
        // var_dump($ready_marry_day);die;
        // 20190826
        // var_dump(session('productid'));
        // exit;
        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]);
                }
            }
            $this->assign("source",$source);
            //如果有上次记录，去上次的
            $shopCode = cookie('add_shop_code') ? cookie('add_shop_code') : session('shop_code');
            $this->assign('only_shop', $shopCode);
            // 转介绍客资接入店  20200523
            $belong_shop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>session('brandclass_id'),'is_dig'=>1]);
            if(empty($belong_shop)){
                $belong_code = session('belong_shop_code');
                $belong_name = session('belong_shop_name');

                if (!$belong_code && !$belong_name) {
                    $belong_shop = [
                        0=>[
                            'shop_code'=>session('shop_code'),
                            'shop_name'=>session('shop_name'),
                        ],
                    ];
                }else{
                    $belong_shop = [
                        0=>[
                            'shop_code'=>session('belong_shop_code'),
                            'shop_name'=>session('belong_shop_name'),
                        ],
                    ];
                }
            }
            $this->assign('belong_shop',$belong_shop);
            //当前店下部门
            $department = $this->getDList(array('shop_code'=>$shopCode));
            $this->assign('department',$department);
            //当前店下所有人
            $allStaff = controller('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);
            if(session('shop_type')== 2){
                $baby_sex = config('baby_sex');
                if(empty($baby_sex)){
                    $baby_sex = [
                        ['sex'=>'男',],
                        ['sex'=>'女',],
                    ];
                }
                $this->assign('baby_sex',$baby_sex);
                return $this->fetch('customeradd_child_jieshao');
            }else{
                return $this->fetch('customeradd_jieshao');
            }
        }else{
            foreach ($source as $k=>$v) {
                if($v['type_id'] != 0 && $v['type_id'] != 3){
                    unset($source[$k]);
                }
            }
            $this->assign("source",$source);
            if(session('shop_type')== 2){
                $baby_sex = config('baby_sex');
                if(empty($baby_sex)){
                    $baby_sex = [
                        ['sex'=>'男',],
                        ['sex'=>'女',],
                    ];
                }
                $this->assign('baby_sex',$baby_sex);
                return $this->fetch('customeradd_child');
            }else{
                return $this->fetch();
            }
        }
    }

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

    //通过归属地查询省市
    public function getAddressInfo(){
        $info = input('post.name');
        $arr = explode(' ',$info);
        if(count($arr) == 1){
            $pParam['name'] = $arr[0];
            $pParam['type'] = 1;
            $ret['pid'] = controller("crm/Customer","lib")->getAddressByLike($pParam);
        }else{
            $pParam['name'] = $arr[0];
            $pParam['type'] = 1;
            $ret['pid'] = controller("crm/Customer","lib")->getAddressByLike($pParam);
            // 获取城市
            $cParam['name'] = $arr[1];
            $cParam['type'] = 2;
            $cParam['pid'] = $ret['pid'][0]['id'];
            $ret['cid'] = controller("crm/Customer","lib")->getAddressByLike($cParam);
        }
        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);
    }

    //获取客资详情
    public function getCustomerInfo(){
        // 客资基本资料
        $customerInfo = controller("Customer","lib")->getCustomerInfo(input('post.id'));
        return json($customerInfo);
    }
    //电访
    public function dianfang(){
        //手机配置地址
        // $this->assign("patrn",check_tel_arr());
        // 权限
        $auth = check_right('menu1512971662');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有追踪的权限，请先设置权限');
            return json($return);
            exit;
        }
        // 启用预约进店排控
        $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);
        }
        // 预约进店
        $auth1 = check_right('menu1519633870');
        if ($auth1) {
            $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',true);
        }else{
            $this->assign('auth_wechat',false);
        }
        // // 修改联系方式（ xglxfs ）  qq，微信，微博 menu1513409629
        // if (check_right('menu1517129299')) {
        //     $this->assign('xglxfs',true);
        // }else{
        //     $this->assign('xglxfs',true);
        // }

        $param = input('param.');
        //呼叫前缀
        $prefix = controller('crm/Customer','lib')->getCallPrefix();
        $this->assign("prefix",$prefix);

        $table = isTableExist('c_customer_intostore');
        if ($table) {
            $customerinfo = controller("crm/Customer","lib")->getCustomerInfoIntostore($param['id']);
        }else{
            $customerinfo = controller("crm/Customer","lib")->getCustomerInfo($param['id']);
            $customerinfo['intostore_remark'] = $customerinfo['intostore_note'];
        }
        // var_dump($customerinfo);die;
        // 修改加好友时间
        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('menu1517129299')){
            $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;
        }

        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;
        // 预约进店取消条件：今天及以后的时间有一条邀约并且未进店的记录 0506
        if ($customerinfo['yjd_day']) {
            $isTable = isTableExist('c_customer_intostore');
            if ($isTable) {
                $intoWhere['status']= '1';
                $intoWhere['cid']   = $customerinfo['id'];
                $into_info = db('c_customer_intostore')->where($intoWhere)->where('syjd_day','null')->where('yjd_day','>=',date("Y-m-d 00:00:00"))->count();
                // echo db()->getLastSql();
                // exit;
                if ($into_info>=1) {
                    $yjdstatus = true;
                    $this->assign('yjdstatus',$yjdstatus);
                }
            }else if ($customerinfo['yjd_day']>$customerinfo['syjd_day']) {
            // }else 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']));//剥离标签
        $customerinfo['customer_label'] = $customerinfo['customer_label'] ? explode(',',trim($customerinfo['customer_label'],',')) : [];
        // var_dump($customerinfo);die;
        $this->assign('info',$customerinfo);
        // 客资标签
        $cat = cache('label_'.session('brandclass_id'));
        if(empty($cat)){
            $cat = db('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('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);
        }
        $this->assign('cat',$cat);
        //追踪标记
        $mark=controller("Customer","lib")->markSet(array('shop_code'=>session('shop_code')));
        $this->assign("mark",$mark);
        //意向店面 
        $search['brandclass'] = $customerinfo['brandclass'];
        $search['is_marketing'] = 2;
        $intentionShop=controller('crm/Customer','lib')->get_shop($search);
        $this->assign('intentionShop',$intentionShop);
        // 预约进店是否默认发送短信 1 不发送短信
        $yjd_dx = db_config('yjd_dx_'.session('shop_code'));
        if ($yjd_dx==1) {
            $yjd_dx_select = 'no';
        }else{
            if ($customerinfo['customer_tel']) {
                $yjd_dx_select = 'ctel';
            }else if (!$customerinfo['customer_tel'] && $customerinfo['mate_tel']) {
                $yjd_dx_select = 'mtel';
            }
        }
        $this->assign('yjd_dx_select',$yjd_dx_select);
        //客资标记
        $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);
        // 客户来源
        $customerCource=controller("crm/Customer","lib")->source();
        $this->assign("customerCource",$customerCource);
        //追踪阶段
        $seles = controller('crm/Customer','lib')->get_seles_step();
        $this->assign("seles",$seles);
        $auth = check_right('menu1512998373');
        $this->assign("auth",$auth);
        //不再追踪原因
        $reason = db('s_file_reason')->where('shop_code',session('shop_code'))->select();
        $this->assign("reason",$reason);
        // 20200522 驳回接收店面 当前员工的客操作店
        $rejParam['staff_id']        = session('staff_id');
        $rejParam['shop_type']       = session('shop_type');
        $rejParam['shop_code']       = session('shop_code');
        $rejParam['brandclass_id']   = session('brandclass_id');
        $rejParam['belong_shop_code']= session('belong_shop_code');
        $rejParam['belong_shop_name']= session('belong_shop_name');
        $reject_shop = getBelongShop($rejParam);
        foreach ($reject_shop as $key => $value) {
            if ($value['shop_code'] == session('shop_code')) {
                // 当前店选中
                $reject_shop[$key]['select'] = 1;
                $rejStaff = $value['shop_code'];
            }else{
                $reject_shop[$key]['select'] = 2;
            }
        }
        $this->assign("reject_shop",$reject_shop);
        $mc = new \app\common\lib\mcInterface();
        // 驳回接收员工
        if ($rejStaff) {
            $reject_staff = $mc->getStaffsByWorkType(array('shop_code'=>$rejStaff,'work_type'=>SK_WORK_TYPE));
            $this->assign("reject_staff",$reject_staff);
        }
        //驳回原因
        $reject = db('s_reject_reason')->where('shop_code',session('shop_code'))->select();
        $this->assign("reject",$reject);
        //客资无效原因
        $unValidReason = controller('crm/Customer','lib')->getUnValidReason();
        $this->assign('unValidReason',$unValidReason);
        //省
        $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);
        // var_dump($dfMust);die;
        $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('SMessageTemplateinfo')->where('shop_code',session('shop_code'))->where('status',1)->field('id,mtemplate_name')->select();
        $this->assign('model',$smsmodel);
        // 预计婚期
        $ready_marry_day = controller("crm/Customer","lib")->ready_marry_day( array('brandclass_id' => session('brandclass_id')) );
        $this->assign('ready_marry_day',$ready_marry_day);
        //消费能力
        $mc = new \app\common\lib\mcInterface();
        $capacity = $mc->getCapacity();
        $this->assign('capacity',$capacity);
        $this->assign('now_time', date('Y-m-d H:i:s'));
        $this->assign('today', date('Y-m-d'));

        // 预约进店 预约时间是否必选（深圳天长定制） 默认0（必选） 天长1（非必选）
        $isYjdMust = config('isYjdMust');
        if ($isYjdMust===1) {
            $this->assign('isYjdMust', 1);
        }else{
            $this->assign('isYjdMust', 0);
        }
        if(session('shop_type') == 2){
            return $this->fetch('dianfang_child');
        }else{
            return $this->fetch('dianfang');
        }
        return $this->fetch();
    }
    //追踪记录
    public function traceRecord(){
        // 追踪记录
        $trackInfos = controller("crm/Customer","lib")->getCustomerTrackInfos(input('param.id'));
        foreach ($trackInfos as $key => $value) {
            $temp = strtotime($value['sales_day']);
            $trackInfos[$key]['date'] = date('m月d日', $temp);
            $trackInfos[$key]['time'] = date('H:i:s', $temp);
            // $trackInfos[$key]['allTime'] = self::secToTime($value['tel_alltime']);
            $trackInfos[$key]['customer_intention'] = $value['customer_intention'] ? $value['customer_intention'] : '';
            $trackInfos[$key]['allTime'] = $value['tel_alltime'];
            $trackInfos[$key]['sales_staff'] = $value['sales_staff'];
            if(empty($trackInfos[$key]['no_track'])){
                $trackInfos[$key]['no_track'] = '';
            }
            if($value['gtType'] == 1){
                $trackInfos[$key]['getType'] = '电话';
            }elseif($value['gtType'] == 2){
                $trackInfos[$key]['getType'] = 'QQ';
            }elseif($value['gtType'] == 3){
                $trackInfos[$key]['getType'] = '微信';
            }else{
                $trackInfos[$key]['getType'] = '其他';
            }
        }
        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'])){
                $oldDateStr = '';
                $oldDate = json_decode($v['old_data'], true);
                foreach ($oldDate as $kk => $vv) {
                    if (session('shop_type')==2) {
                        if (in_array($kk, $children)) {
                            $kk = $kk."s";
                        }
                    }
                    $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>';
                    }
                }
            }else{
                $oldDateStr = $v['old_data'];
            }
           if(is_json($v['data'])){
               $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('c_customerinfo',$kkk);
                   if($key1){
                       $newDateStr .= $key1.'：'.$vvv.'；<br>';
                   }
               }
           }else{
               $newDateStr = $v['data'];
           }

            $info[$k]['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(){
        $historyOrders = controller("Customer","lib")->getCustomerHistoryOrders(input('param.id'));
        $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('Customer','lib')->send_message(input('post.'));
        }
    }
    //追踪添加
    public function addSalesTracking(){
        return controller('Customer','lib')->addSalesTracking(input('post.'));
    }
    //追踪修改  20180910
    public function editSalesTracking(){
        $data = input('post.');
        if ($data['wechat_status'] == 1) {
            $data['add_friend_time'] = date("Y-m-d H:i:s",time());
        }else{
            if ($data['add_friend_time']) {
                $data['wechat_status'] =2;
            }
        }
        $data['sales_remark'] = strip_tags($data['sales_remark'], '<img>');
        //电访必选项配置
        $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'=>'再约时间小于当前时间，请重试'));
                        }
                    }
                    if ($value == 'sign_id') {
                        if (empty($data[$value])) {
                            return json(array('code'=>'100','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'=>'线上订单不允许预约！'));
            }elseif($info['order_type'] == 2 && ($info['is_success'] == 1 || $info['is_success'] == 3)){
                return json(array('code'=>'95','msg'=>'已经订单，不能再预约！'));
            }
            if ($dfMust) {
                $dfMust = explode(',',$dfMust);
                foreach ($dfMust as $key => $value) {
                    if ($value == 'sign_id') {
                        if (empty($data[$value])) {
                            return json(array('code'=>'110','msg'=>'客资标记不能为空'));
                        }
                    }
                }
            }
        }
        return controller('Customer','lib')->editSalesTracking($data);
    }

    //新客资来电添加
    public function addNewCusCall(){
        return controller('Customer','lib')->addNewCusCall(input('post.'));
    }
    //老客资来电添加
    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('s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->find();
            if($info['id']){
                db('s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->update($data);
            }else{
                db('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('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('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('s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->find();

        db()->startTrans();
        try {
            if($info['id']){
                db('s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->update($data);
            }else{
                db('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('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'];
        }
        $this->assign('info',$info);

        //意向店面
        $search['brandclass']  = $info['brandclass'];
        $search['is_marketing']= 2;
        $intentionShop=controller('crm/Customer','lib')->get_shop($search);
        $this->assign('intentionShop',$intentionShop);
        //预约短信模板
        $yyModel  = db_config('yy_sms_model_'.session('shop_code'));
        $this->assign('model_id',$yyModel);
        //所有短信模板
        $smsmodel = db('SMessageTemplateinfo')->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']);
            if(!$onlinecash_invite && $info['order_type'] == 1 && $info['order_number'] && $info['syjd_day']){
                return json(array('code'=>'90','msg'=>'线上订单不允许预约！'));
            }elseif($info['order_type'] == 2 && ($info['is_success'] == 1 || $info['is_success'] == 3)){
                return json(array('code'=>'95','msg'=>'已经订单，不能再预约！'));
            }
            if(session('shop_type') == 2){
                return controller("Customer","lib")->customerYJD_child($data);
            }else{
                return controller("Customer","lib")->customerYJD($data);
            }
        }
    }

    public function getStaffForWorktype(){
        $data = input();
        return controller("crm/Customer","lib")->sklist($data['shop_code'],$data['work_type']);
    }
    //转客资
    public function zhuanCustomer(){
        $call = controller("Customer","lib")->zhuanCustomer(input());
        $this->assign('call',$call);
        return $this->fetch();
    }
    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")->channel(array('shop_code'=>session('shop_code')));
        $channel=controller("Customer","lib")->getChannel();
        $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);
        return $this->fetch();
    }
    //获取短信模板内容
    public function getModelContent(){
        $id = input('post.id');
        $res = db('s_message_templateinfo')->where('id',$id)->find();
        if($res){
            return $res;
        }else{
            return false;
        }
    }
    //批量标记待定
    public function customerMoreDd(){
        $id = input();
        $info = db('c_customerinfo')->where('id','in',$id['id'])->field('id,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['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('CSalestrackinginfo')->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('CCustomerinfo')->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('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('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('CSalestrackinginfo')->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('CCustomerinfo')->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'=>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('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 customerMoreUnValid(){
        $param = input();
        $info = db('c_customerinfo')->where('id','in',$param['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'] = 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['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('CSalestrackinginfo')->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('CCustomerinfo')->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'=>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('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 signValid(){
        if(check_right('menu1517129299')){
            $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('c_customerinfo')->where('id',$id)->update($data);
                //追踪记录
                $params['customer_id'] = $id;
                $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('CSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$id,null);
                //修改追踪时间
                $time = date('Y-m-d H:i:s',time());
                if(empty($info['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('CCustomerinfo')->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('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 = '';
        }
        return $shopList;
    }
    public function getDepartmentList(){
        //部门 
        $shop_code = input('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;
        }
    }

    public function getDepartmentListReport(){
        //部门
        $data = input('param.');
        $url = '5a62dcd5c7e40';
        $res = sx_call($url,$data);
        if($res['code'] == 200){
            return $res['data'];
        }else{
            return false;
        }
    }
    //部门下的人员
    public function getDepartmentStaff(){
        $param = input();
        $id = $param['id'];
        $shop_code = $param['shop_code'];
        $url = '5a01766b4a3dd';
        $res = sx_call($url,['department_id'=>$id,'shop_code'=>$shop_code]);
        if($res['code'] == 200){
            return $res['data'];
        }else{
            return false;
        }
    }
    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{
                if($res === true){
                    return json(['code'=>100,'data'=>'升级进行中，请待待其他升级进程结束后再操作。']);
                }
                return json(['code'=>100,'data'=>$res['data']]);
            }
        }
        $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);
        }
        $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);
        $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 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');
        //部门下的小组
        $groups = db('c_staff_group')->where('department_id',$id)->field('id,group_name')->select();
        return $groups;
    }
    //订单转移
    public function customerMerge(){
        $isTable = isTableExist('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('c_customer_intostore');

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


        // 原信息
        $cInfoY = db('c_customerinfo')
            ->find($order['customer_id']);
        /*
		$cInfoY = db('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('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('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('c_customer_intostore')
                    ->where('status',1)
                    ->where('cid',$data['customerId'])
                    ->where('yjd_day','like','%'.$yjdDay.'%')
                    ->find();
                if($mInto){
                    if(in_array($mInto['is_intostore'], [2,3,5])){
                        //把目标的进店，挂到原客资上
                        db('c_customer_intostore')->where('id',$mInto['id'])->update(['cid'=>$cInfoY['id']]);
                        $yData['is_intostore']     = $mInto['is_intostore'];
                        $yData['syjd_day']     = $mInto['syjd_day'];
                    }else{
                        db('c_customer_intostore')->where('id',$mInto['id'])->update(['status'=>99]);
                    }
                }
                if($order['into_id']){
                    $iData['cid'] = $cInfoM['id'];
                    db('c_customer_intostore')->where('id',$order['into_id'])->update($iData);
                }
                //目标客资    原订单客资预约日期之后的所有进客改为回门
                db('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('c_customerinfo')->where('id',$cInfoY['id'])->update($yData);
            // 更新目标客资数据
            db('c_customerinfo')->where('id',$cInfoM['id'])->update($mData);

            // 更新或新添目标客资订单数据
            db('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('c_customer_order o')
                ->join('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']).'" OR  customer_wechat="'.trim($data['customerTel']).'" OR mate_wechat="'.trim($data['customerTel']).'" ';
        $info = db('c_customerinfo')
            ->where($sql)
            ->where('is_status',1)
            ->where('brandclass_id',session('brandclass_id'))
            ->field('id,customer_number,customer_name,customer_tel,customer_wechat,mate_tel,mate_wechat,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('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('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();
        $contact = trim($data['contact']);
        $brandclass = trim($data['brandclass']) ? trim($data['brandclass']) : session('brandclass');
        $tel = $mate_tel = $contact;
        $wechat = $contact;
        $qq = $contact;
        $id = $data['id'];
        $consultation_type_id = $data['consultation_type'];
        $res = controller('crm/Customer','lib')->isRepeat($brandclass,$tel,$wechat,$qq,$mate_tel,$id,$consultation_type_id);
        // var_dump($res);die;
        if($res['code'] == 200 || $res['code']== 205) {
            $tact = db('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']);
        }
        // 20200522 匠古紧急升级
        else if ($res['code']==201) {
            $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 .= '客资当前状态：'.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 .= '请核对信息后再录入';
            return array('code'=>201,'msg'=>$msg);
        }
        return $res;
    }
    //丧失焦点客资重复验证
    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('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('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('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('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('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')]);
                            if($info['code'] == 200){
                                $valid_date = $info['data'][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'=>'修改客资时联系方式未重复');
                }
            }
        }
    }
    //联系方式验证
    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;

        $brandclass = 0;
        if(session('brandclass')){
            $brandclass = session('brandclass');
        }
        $info = controller('crm/Customer','lib')->isRepeat($brandclass,$tel,$wechat,$qq,$mate_tel,$id,$data['consultation_type']);
        return $info;
    }
    //追踪打开时检测客资重复
    public function dianfang_check_customer(){
        $id = input('id');
        if(empty($id)){
            return array('code'=>101,'msg'=>'未获取到客资ID');
        }
        $info = db('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')]);
            if($info['code'] == 200){
                $valid_date = $info['data'][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('c_customer_contact')->where('c_id','<>',$id)->where('contact','in',$arr)->select();
        if($res){
            $info1 = db('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('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('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('SMessageTemplateinfo')->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();
        $shop_code = $data['shop_code'];
        $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('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('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('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('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('c_customerinfo')->where('id',$id)->find();
        $this->assign('info',$info);
        return $this->fetch();
    }

    //客资回收站
    public function customerBack(){
        if(!check_login('menu1529995330')){
            return $this->redirect('/');
        }
        //登记人
        $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(session('shop_code')){
            $sql .= ' and (shop_code="'.session('shop_code').'" or add_shop_code="'.session('shop_code').'") ';
        }elseif(session('brandclass_id')){
            $sql .= ' and brandclass_id='.session('brandclass_id');
        }
        if($start && $end){
            $info = db('c_customerinfo')
                ->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('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('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('c_customerinfo')
            ->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('c_customerinfo')->where('id',$cid)->field('customer_tel,customer_qq,customer_wechat,mate_tel,mate_wechat,mate_qq')->find();
        $brandclass = db('c_customerinfo')->where('id',$cid)->value('brandclass');
        $contact = array_filter($contact);//去除空元素
        //查询排重表有无此联系方式
        $info = db('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['brandclass']=$brandclass;
                array_push($contactList,$con);
            }

            db('c_customerinfo')->where('id',$cid)->update(['is_status'=>1]);
            db('c_customer_contact')->insertAll($contactList);
            db()->commit();
            action_log('客资恢复，ID:'.$cid,'已删除',$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 customerChange(){
        $dep = $this->getDepartmentList(array('shop_code'=>session('shop_code')));
        $group = db('c_staff_group')->where('shop_code',session('shop_code'))->select();
        $staff = controller('crm/Customer','lib')->get_staff_lists(array('shop_code'=>session('shop_code')));
        $this->assign('department',$dep);
        $this->assign('group',$group);
        $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'] = $data['dj_staff'] ? trim($data['dj_staff']) : $sinfo['staffname'];
        $param['dj_department_id'] = $data['dj_department_id']? intval($data['dj_department_id']) : $sinfo['department_id'];
        $param['dj_staff_number'] = $sinfo['staffnumber'];
        $group = [];
        $group['dj_group_id'] = intval($data['dj_group_id']);
        $group['dj_group_name'] = trim($data['dj_group_name']);
        $info = db('c_customerinfo')->where('id','in',$data['id'])->field('id,customer_name,customer_number,dj_staff_id,dj_staff,dj_staff_number,dj_department_id,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]['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('c_customerinfo')->where('id','in',$data['id'])->update($param);
            db('c_customer_from')->where('cid','in',$data['id'])->update($group);
            if(!empty($type)){
                $channel['customer_channel_id'] = $sinfo['department_id'] ? $sinfo['department_id'] : -1;
                $channel['customer_channel'] = $sinfo['department_name'] ? $sinfo['department_name'] : '空渠道';
                db('c_customerinfo')->where('id','in',$type)->update($channel);
            }
            db('action_log','db_logs')->insertAll($lData);
            db('CSalestrackinginfo')->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('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('c_customerinfo')->where('id','in',$data['id'])->update($arr);
            db('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(){
        $param['shop_code'] = session('shop_code');

        $staffs = controller('crm/Customer','lib')->get_staff_lists($param);
        //$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);

        $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 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 ($temp['type']==1) {
            $shop_code = 'shop_code = "'.session('shop_code').'" or add_shop_code ="'.session('shop_code').'"';
        }else{
            $shop_code = '1 = 1';
        }
        $info = db('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('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(){
        set_time_limit(0);
        $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 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['type']==1) {
            $shop_code = 'shop_code = "'.session('shop_code').'" or add_shop_code ="'.session('shop_code').'"';
        }else{
            $shop_code = '1 = 1';
        }
        // 需要转移的客资信息
        $info = db('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,sk_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'];

        $department_id = $data['department_id']?$data['department_id']:'';  //部门id信息
        $group_id = $data['group_id']?$data['group_id']:'';
        $group_name = $data['group_name']?$data['group_name']:'';

        //改成客资信息里的录入人、筛客人、追踪人、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;
                $target_dj['dj_department_id'] = $department_id;
                $from_save['dj_group_id'] = $group_id;
                $from_save['dj_group_name'] = $group_name;
            }
            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;
                $target_sales['sales_department_id'] = $department_id;
                $from_save['sales_group_id'] = $group_id;
                $from_save['sales_group_name'] = $group_name;
            }
            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('c_customerinfo')->where('id', 'in', $cids_dj_staff_id)->update($target_dj);
                db('c_customer_from')->where('cid','in',$cids_dj_staff_id)->update($from_save);
                $mysql_log .= db('c_customerinfo')->getLastSql().";";
            }
            if ($cids_sales_staff_id) {
                $target_sales['update_time'] = date("Y-m-d H:i:s");
                db('c_customerinfo')->where('id', 'in', $cids_sales_staff_id)->update($target_sales);
                db('c_customer_from')->where('cid','in',$cids_sales_staff_id)->update($from_save);
                $mysql_log .= db('c_customerinfo')->getLastSql().";";
            }
            if ($cids_sk_staff_id) {
                $target_sel['update_time'] = date("Y-m-d H:i:s");
                db('c_customerinfo')->where('id', 'in', $cids_sk_staff_id)->update($target_sel);
                $mysql_log .= db('c_customerinfo')->getLastSql().";";
            }
            if ($cids_tel_staff_id) {
                $target_tel['update_time'] = date("Y-m-d H:i:s");
                db('c_customerinfo')->where('id', 'in', $cids_tel_staff_id)->update($target_tel);
                $mysql_log .= db('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(){
        $data = [
            'shop_code'=>session('shop_code'),
            'shop_name'=>session('shop_name')
        ];
        $url = url('index/jindianma',$data,true,true);
        /*
        $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(){
        $data = [
            'shop_code'=>session('shop_code'),
            'shop_name'=>session('shop_name')
        ];
        $url = url('index/jindianma',$data,true,true);
        /*
        $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);
        if ($temp_staffs['code'] == 200) {
            $staffs = $temp_staffs['data'];
        }
        return $staffs;
    }
    /**
     * 支付类型
     * 
     * @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');
        // 20200606
        $ddMust = db_config('dd_must_'.session('brandclass_id'));
        $ddMust = trim($ddMust,',');
        $ddMust = explode(',',$ddMust);
        $this->assign("ddMust",$ddMust);
        // 20200611
        // $cusInfo = controller("Customer","lib")->getCustomerInfo($id);
        // if(!empty($cusInfo['order_number'])){
        //     $return = array('error'=>'1','msg'=>'已经转过订单，不能再次操作');
        //     return json($return);
        //     exit;
        //     // $info = db('c_customer_order')->where('order_sn',$cusInfo['order_number'])->find();
        //     // $this->assign('info',$info);
        // }
        $cusInfo = db('c_customerinfo')
            ->where('id', $id)
            ->field('id,customer_name,baby_birthday,reception_id,reception_name,consulation_shop_code,shop_code,add_shop_code,customer_channel_id,customer_channel,customer_cource,consultation_type,brandclass')
            ->find();
        //来源渠道
        // $channel=controller("Customer","lib")->channel(array('shop_code'=>session('shop_code')));
        $channel=controller("crm/Customer","lib")->getChannel();
        if($cusInfo['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);
        //消费类型
        $consumptionType=controller("Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        // 客户来源
        $customerCource=controller("crm/Customer","lib")->source();
        $this->assign("customerCource",$customerCource);
        //意向店面
        $search['brandclass'] = $cusInfo['brandclass'];
        $intention_shop = db_config('intention_shop');
        if($intention_shop == 1){//所有店

        }elseif($intention_shop == 2){//接单店
            $search['is_op2'] = 1;
        }elseif($intention_shop == 3){//本店
            $search['shop_code'] = session('shop_code');
        }else{
            $search['is_marketing'] = 2;
        }
        $intentionShop=controller('crm/Customer','lib')->get_shop($search);
        $this->assign('intentionShop',$intentionShop);
        unset($search);
        // 接单人员列表
        $reception = [];
        //是否安装ERP
        $erp = is_install('sx_erp');
        $this->assign('erp',$erp);
        $erpInterface = new erpInterface();
        // 20180917
        foreach ($intentionShop as $key => $value) {
            // 如果有了意向店面
            if ($cusInfo['consulation_shop_code'] == $value['shop_code']) {
                $url = '5b75341456d18';
                $data['shop_code'] = $value['shop_code'];
                $data['work_type'] = MS_WORK_TYPE;
                $temp_staffs = sx_call($url,$data);
                if ($temp_staffs['code'] == 200) {
                    $reception = $temp_staffs['data'];
                    foreach ($temp_staffs['data'] as $k => $v) {
                        if ($v['id'] == session('staff_id') && $cusInfo['reception_id'] != $v['id']) {
                            $cusInfo['reception_id'] = $v['id'];
                            $cusInfo['reception_name'] = $v['staffname'];
                        }
                    }
                }
                
                if($erp){
                    $erpInterface->setShopType($value['shop_type']);
                    $cusInfo['pay_type_dict'] = $erpInterface->getPayTypeDict();
                    $cusInfo['fee_category_dict'] = $erpInterface->getFeeCategoryDict();
                }
            }
            // 如果没有意向店面，并且当前店 在意向店面列表中
            else if ($value['shop_code'] == session('shop_code')) {
                $url = '5b75341456d18';
                $data['shop_code'] = $value['shop_code'];
                $data['work_type'] = MS_WORK_TYPE;
                $temp_staffs = sx_call($url,$data);
                if ($temp_staffs['code'] == 200) {
                    $reception = $temp_staffs['data'];
                    foreach ($temp_staffs['data'] as $k => $v) {
                        if ($v['id'] == session('staff_id') && $cusInfo['reception_id'] != $v['id']) {
                            $cusInfo['reception_id'] = $v['id'];
                            $cusInfo['reception_name'] = $v['staffname'];
                        }
                    }
                }
                $cusInfo['consulation_shop_code'] = $value['shop_code'];
                if($erp){
                    $erpInterface->setShopType($value['shop_type']);
                    $cusInfo['pay_type_dict'] = $erpInterface->getPayTypeDict();
                    $cusInfo['fee_category_dict'] = $erpInterface->getFeeCategoryDict();
                }
            }
        }
        $this->assign('reception',$reception);
        $this->assign('cusInfo',$cusInfo);
        // $this->assign('id',$id);
        
        // 拍照店面
        $search['brandclass'] = $cusInfo['brandclass'];
        $search['is_photo']   = 1;
        $photoShop=controller('crm/Customer','lib')->get_shop($search);
        foreach ($photoShop as $key => $value) {
            // 如果有意向店面，并且意向店面在拍照店面列表中，默认选中
            if ($cusInfo['consulation_shop_code'] == $value['shop_code']) {
                $photoShop[$key]['select'] = 1;
            }else{
                $photoShop[$key]['select'] = 2;
            }
        }
        $this->assign('photoShop',$photoShop);
        // var_dump($photoShop);
        // exit;

        // 如果安装erp
        // if ($erp) {
            $order_source = db('s_order_source')->where('shop_code',session('shop_code'))->where('is_delete',1)->select();
            if (count($order_source) == 1) {
                $this->assign('snumber',1);
            }else{
                $this->assign('snumber',count($order_source));
            }
            $this->assign('order_source',$order_source);            
        // }
        //客资标记
        $sign = controller('crm/Setting','lib')->gettrackingKmarkerList();
        $this->assign('sign',$sign);
        return $this->fetch();
    }
    //编辑订单
    public function orderEdit(){
        // 权限
        $auth = check_right('menu1519633959');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有操作转订单的权限，请先设置权限');
            return json($return);
            exit;
        }
        $id = input('param.id');
        $info = db('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('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("crm/Customer","lib")->editOrder($param);
        }
    }
    public function zhuanOrder(){
        if(!check_right('menu1519633923')){
            return array('code'=>130,'msg'=>'你无此操作权限');
        }else{
            $param = input('post.');
            $target_time = date('Y', strtotime($param['target_time']));
            if ($target_time<'1975') {
                return array('code'=>120,'msg'=>'开单时间错误：'.$param['target_time']);
            }
            
            if (!$param['consultation_type']) {
                return array('code'=>121,'msg'=>'请选择消费类型');
            }
            return controller("crm/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');
        $info = db('c_customerinfo')->where('id',$id)->field('order_number')->find();
        $one_order = db_config('one_customer_more_order');//同一客资允许多次订单,有过成交，就一直成交

        if ($info['order_number']) {
            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('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,add_shop_code,customer_channel')
            ->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'];
        }
        //渠道
        $channel = controller('crm/Customer','lib')->getchannel($cInfo['add_shop_code']);
        $this->assign('cInfo', $cInfo);
        $this->assign('channel', $channel);
        $this->assign('date', date('Y-m-d'));
        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("jiedandian_".$shop_code))){
                $url = $addr.'/SXWebErpAppStaff/SX_AOAcceptorAddress?Token=^******^&Code='.$shop_code.'&brandid='.session('brandclass_id'); //定义拼接url
                $dataN = "";
                $jiedandianlist = requestERP($url,$dataN);
                if($jiedandianlist['Code'] == 200){
                    $jiedandian = $jiedandianlist['Data'];
                    cache("jiedandian_".$shop_code,$jiedandianlist['Data']);
                }else{
                    $jiedandian = "";
                }
//            }else{
//                $jiedandian = cache("jiedandian_".$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))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_PackageSet?Token=^******^&Code='.$shop_code; //定义拼接url
                $dataN = "";
                $shootList = requestERP($url,$dataN);
//            print_r($shootList);die;
                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);
            //}
            if(empty(cache("photo_".session('brandclass_id')))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_BrandPhotoShopNameSet?Token=^******^&BrandName='.session('brandclass').'&Staffid='.session('staff_id');
                $dataN = "";
                $photoList = requestERP($url,$dataN);
                if($photoList['Code'] == 200){
                    cache("photo_".session('brandclass_id'),$photoList['Data']);
                    $photolist = $photoList['Data'];
                }else{
                    $photolist = "";
                }
            }else{
                $photolist = cache("photo_".session('brandclass_id'));
            }
            $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,
                    'jiedandian'  => $jiedandian,
                    'photolist'  => $photolist,
                )
            );
            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']);
            }

            $data = [
                'mname'              =>$acdata['mname'],
                'mphone'             =>$acdata['mphone'],
                'mwechat'            =>$acdata['mwechat'],
                'mqq'                =>'',
                'wname'              =>$acdata['wname'],
                'wphone'             =>$acdata['wphone'],
                'wwechat'            =>$acdata['wwechat'],
                'wqq'                =>'',
                'address'            =>$acdata['address'],
                'cssname'            =>$acdata['cssname'],
                'area'               =>$acdata['area'],
                'mbirthdate'         =>$acdata['mbirthdate'],
                'wbirthdate'         =>$acdata['wbirthdate'],
                'midtype'=>'',
                'mid'=>'',
                'introducerid'=>'',
                'introducer_name'=>'',
                'weddingdate'        =>$acdata['weddingdate'],
                'wIdtype'=>'',
                'wid'=>'',
                'customernote'       =>$acdata['customernote'],
                'bbname'=>'',
                'bnickname'=>'',
                'bbithdate'=>'',
                'liunardate'=>'',
                'bbsex'=>'',
                'bzodiac'=>'',
                'email'              =>$acdata['email'],
                'shop_code'          =>$acdata['shop_code'],
                'shop_name'          =>$acdata['shop_name'],
                'OrderId'            =>$acdata['OrderId'],
                'Consumption_type'   =>$acdata['Consumption_type'],
                'Package_name'       =>$acdata['Package_name'],
                'Targetdate'         =>$acdata['Targetdate'],
                'Storeconsuitant1'   =>$acdata['Storeconsuitant1'] ? $acdata['Storeconsuitant1'] : '',
                'Storeconsuitant2'   =>$acdata['Storeconsuitant2'],
                'Storeconsuitant3'   =>$acdata['Storeconsuitant3'],
                'Acceptor_address'=>'',
                'Yc_day'=>'',
                'Bb_hospital'=>'',
                'Customer_from'=>'crm',
                'Brandid'            =>session('brandclass_id'),
                'Opershop'           =>session('shop_name'),
                'Oeder_newclass'     =>$acdata['Oeder_newclass'],
                'Shareshoplist'=>'',
                'Ordernote'=>'',
                'Ordertopic'         =>implode('|',$acdata['Ordertopic']),
                'Dresstheme'         =>implode('|',$acdata['Dresstheme']),
                'Indoordresscount'   =>$acdata['shineifz'],
                'Outerdresscount'    =>$acdata['waijingfz'],
                'Seadresscount'      =>$acdata['neijingfz'],
                'Travelresscount'    =>$acdata['lvpaishu'],
                'Paizhaocount'          =>$acdata['paizhaocount'],
                'Rucecount'             =>$acdata['rucecount'],
                'Jingxiucount'          =>$acdata['jingxiucount'],
                'Customer_from_index'=>$cInfo['customer_number'],
                'Jinkeid'=>'',
                'Consumption_type_id'=>'',
                'Cssname_id'         =>$acdata['Cssname_id'],
                'Area_id'            =>$acdata['Area_id'],
                'packagecount'            =>$acdata['taoxifz'],
                'username'              =>session('staff_name'),
                'userid'                =>session('staff_id'),
                'Storeconsuitant1id'            =>'',
                'isnewjkzd'                 =>0,
                'customer_channel'            =>$acdata['customer_channel'],
            ];
            $erp = config('ext.app_config');  //读取erp配置文件
            $addr = $erp['sx_erp']['addr'];   //调用url
            $url = trim($addr,'/')."/SXWebErpAppStaff/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");
            $dataN = json_encode($data);
            $order = requestERP($url,$dataN);
            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 = session('brandclass_id');
            $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"){//消费子类型
            $shop_code = input("shop_code");
            $ordertypename = input("ordertypename");
            $orderlist = cache("orderType");
            foreach($orderlist as $k=>$v){
                if($v['consumption_name'] == $ordertypename){
                    $ordertypeid = $orderlist[$k]["consumption_name"];
                }
            } 
            if(empty(cache("ordertype_".$ordertypename))){
                $url = trim($addr,'/').'/SXWebErpAppStaff/SX_OrderTypeSet?Token=^******^&Code='.$shop_code.'&consumptiontype='.$ordertypename;
                $dataN = "";
                $orderList = requestERP($url,$dataN);
                if($orderList['Code'] == 200){
                   cache("ordertype_".$ordertypename,$orderList['Data']);
                    $orderlist = $orderList['Data'];
                }else{
                    $orderlist = "";
                }
            }else{
                $orderlist = cache("ordertype_".$ordertypename);
            }
            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('c_customerinfo')->where('customer_tel|mate_tel',$data['tel'])->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);

            //客户标记
            $sign=controller('crm/Setting','lib')->gettrackingKmarkerList();
            $this->assign("sign",$sign);
            return $this->fetch('newcustomercall');
        }
    }
    //设置坐席忙闲状态
    public function callManStatus(){
        $data = input();
        db()->startTrans();
        try{
            db('s_call_man')->where('staff_id',session('staff_id'))->update($data);
            db()->commit();
            return true;
        }catch (\Exception $e){
            db()->rollback();
            return false;
        }
    }
    //设置坐席忙闲状态
    public function callManBusySet(){
        $data = input();
        db()->startTrans();
        try{
            db('s_call_man')->where('staff_id',session('staff_id'))->update($data);
            db()->commit();
            return true;
        }catch (\Exception $e){
            db()->rollback();
            return false;
        }
    }
    public function paicheng(){
        $param = input();
        $cus = db('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','排程');
        }
        //分区
        $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('SMessageTemplateinfo')->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 = [];
        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'] = intval($data['time']);
            $whereS['time'] = intval($data['time']);
        }
        else{
            $where['time'] = NULL;
            $whereS['time'] = NULL;
        }
        $res = db('l_pc_log')->where('cid',$data['id'])->where('pc_time',$data['pc_time'])->where($where)->find();
        if($res) {
            return array('code' => 101, 'msg' => '本客资此时间已排程,不能多次操作');
        }
        $todaySetting = db('l_pc_setting_log')->where('shop_code',$data['pc_shop_code'])->where('setting_date',$data['pc_time'])->count();
        if(!$todaySetting){
            $queryDate = db('l_pc_setting_log')->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('l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
        if(!$settingRow){
            if($data['time'] && $data['area_id']){
                $whereS['time'] = NULL;
                $settingRow =db('l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
                if(!$settingRow){
                    $whereS['area_id'] = NULL;
                    $whereS['time'] = $data['time'];
                    $settingRow =db('l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
                    if(!$settingRow){
                        $whereS['area_id'] = NULL;
                        $whereS['time'] = NULL;
                        $settingRow =db('l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
                    }
                }
            }elseif($data['time'] && empty($data['area_id'])){
                $whereS['time'] = NULL;
                $settingRow =db('l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
            }elseif(empty($data['time']) && $data['area_id']){
                $whereS['area_id'] = NULL;
                $settingRow =db('l_pc_setting_log')->where('setting_date',$queryDate)->where($whereS)->find();
            }
        }

        if($settingRow){
            $num = $settingRow['num'];
            $todayTotal = db('l_pc_setting_log')->where('setting_date',$queryDate)->where('shop_code',$data['pc_shop_code'])->sum('num');
        }else{
            $num = 0;
        }
        $todayPcTotal = db('l_pc_log')->where('pc_time',$data['pc_time'])->where('pc_shop_code',$data['pc_shop_code'])->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('l_pc_log')->where('pc_time',$data['pc_time'])->where($whereNew)->count();
        if( $total >= $num){
            return array('code' => 104, 'msg' => '已达排程最大次数,不能排程');
        }

        db()->startTrans();
        try{
            $arr = [
                'cid' => $data['id'],
                '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,
                'create_time' => date('Y-m-d H:i:s')
            ];
            db('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('c_customerinfo')->where('id',$data['id'])->update($cData);
            // 核销码 在vip的 接口有可能生成过
            $code = db('c_customer_from')->where('cid',$data['id'])->value('code');
            if (!$code) {
                $code = date('is').generate_code(4);
                db('c_customer_from')->where('cid',$data['id'])->update(['code'=>$code]);
            }
            //追踪记录
            $customerInfo =  db('c_customerinfo')->where('id', $data['id'])->find();
            $params['customer_id'] = $data['id'];
            $params['customer_name'] = $customerInfo['customer_name'];
            $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('CSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$data['id'],null);
            //短信
            if($data['model_id']){
                $send_msg = db('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('l_pc_log')->where('id',$id)->find();
        db()->startTrans();
        try{
            db('l_pc_log')->where('id',$id)->delete();
            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('l_pc_log')->alias('f')->join('c_customerinfo c','f.cid=c.id')->join('c_customer_from r','r.cid=c.id')->where('f.pc_time',$pc_time)->where('f.pc_shop_code',$data['pc_shop_code'])->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,r.code,f.result,r.hd_name,c.is_success')->where($where)->limit($limit)->page($page)->select();
        $result['count'] = db('l_pc_log')->alias('f')->join('c_customerinfo c','f.cid=c.id')->join('c_customer_from r','r.cid=c.id')->where('f.pc_time',$pc_time)->where('f.pc_shop_code',$data['pc_shop_code'])->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,r.code,f.result,r.hd_name,c.is_success')->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('l_pc_log')->where('pc_time','like',$month.'-%')->where('pc_shop_code',$shop_code)->where($where)->group('pc_time')->order('pc_time')->column('count(id)','pc_time');
        //排程设定
        $info = db('l_pc_setting_log')->where('setting_date','like',$month.'-%')->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('l_pc_setting_log')->where('setting_date','<',$thisFirstKey)->where($where)->where('shop_code',$shop_code)->group('setting_date')->order('setting_date desc')->column('sum(num)','setting_date');
        }else{
            $temp = db('l_pc_setting_log')->where('setting_date','<',$month.'-01')->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('l_pc_setting_log')->where($where)->select();

        if(empty($sett)){
            unset($where['setting_date']);
            $sett = db('l_pc_setting_log')->where($where)->where('setting_date','<',$data['month'])->order('setting_date desc')->select();
        }
        $log = db('l_pc_log')->where($whereL)->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('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('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('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('l_yjd_ctrl')->alias('c')
            ->join('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('i.status',1)->where('i.consulation_shop_code', $shop_code)
            ->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] ? $day_data_real[$key] : 0;
            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('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();
        $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('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('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['f.hd_name'] = 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('c_customerinfo')->alias('c')->join('c_customer_from f','f.cid=c.id','left')
            ->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')
            ->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('c_customerinfo')->alias('c')->join('c_customer_from f','f.cid=c.id','left')
            ->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('l_pc_log')->where('id',intval($data['id']))->find();
        try{
            db('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('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('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);
        $is_ctrl = db_config('yjd_ctrl_set_'.session('shop_code'));
        $this->assign('is_ctrl',$is_ctrl);

        // 是否进店
        $this->assign('is_intostore',getIsIntostore(1,'arr'));
        // 是否成交
        $this->assign('is_success',getIsSuccess(1,'arr'));
        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['start_time']) {
            $data['start_time'] = date('Y-m-d');
            $yjds = ' i.yjd_day>="'.date('Y-m-d 00:00:00').'"';
        }else{
              $yjds = ' i.yjd_day>="'.date('Y-m-d 00:00:00',strtotime($data['start_time'])).'"';
        }
        if (!$data['end_time']) {
            $data['end_time'] = date('Y-m-d 23:59:59');
            $yjde = ' i.yjd_day<="'.date('Y-m-d 23:59:59').'"';
        }else{
            $yjde = ' i.yjd_day<="'.date('Y-m-d 23:59:59',strtotime($data['end_time'])).'"';
        }

        // 意向店面
        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('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('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('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 ($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'];
        }
        // 进店状态
        if ((int)$data['is_intostore']) {
            $where['i.is_intostore'] = (int)$data['is_intostore'];
        }
        // 成交状态
        if ((int)$data['is_success']) {
            $where['i.is_success'] = (int)$data['is_success'];
        }

        $info = db('c_customer_intostore i')
            ->join('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.is_success,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('c_customer_intostore i')
            ->join('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'] = getIsIntostore($value['is_intostore']);
            // 是否成交
            $info[$key]['is_success'] = getIsSuccess($value['is_success']);
            //日期和时间分开
            $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']))];
        }
        $is_ctrl = db_config('yjd_ctrl_set_'.session('shop_code'));
        //是否启用预约排控
        if($is_ctrl){
            $ctrl = db('l_yjd_ctrl')->where('use_day','between',[$data['start_time'],$data['end_time']])->where('shop_code','in',$shop_codes)->where('is_del',1)->order('start asc')->select();
            $return = [];
            foreach($ctrl as $k=>$v){
                for($i=0;$i<$v['num'];$i++){
                    $temp['ctrl_date'] = $v['use_day'];
                    $temp['time_area'] = $v['time_area'];
                    $temp['start'] = $v['start'];
                    $temp['end'] = $v['end'];
                    array_push($return,$temp);
                }
            }
            foreach($return as $k=>$v){
                foreach($info as $kk=>$vv){
                    //var_dump($vv);
                    if($v['ctrl_date'] == $vv['s_yjd_day'] && date('H:i',strtotime($vv['s_yjd_time'])) >= date('H:i',strtotime($v['start'])) && date('H:i',strtotime($vv['s_yjd_time'])) < date('H:i',strtotime($v['end']))){
                        $return[$k] = array_merge($v,$vv);
                        unset($info[$kk]);
                        break;
                    }
                }
                /*
                if($v['ctrl_date'] == $info[$k]['s_yjd_day'] && date('H:i',strtotime($info[$k]['s_yjd_time'])) >= date('H:i',strtotime($v['start'])) && date('H:i',strtotime($info[$k]['s_yjd_time'])) <= date('H:i',strtotime($v['end']))){
                    $return[$k] = array_merge($v,$info[$k]);
                }
                */
            }
        }

        $returnData['code'] = 0;
        $returnData['msg']  = '';
        if($is_ctrl){
            $returnData['count']= count($return);
            $returnData['data'] = $return;
        }else{
            $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('c_customer_from')->where('cid','in',$param['id'])->update(['bonus'=>$param['bonus']]);

            //操作日志
            db('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('c_customer_from')->where('cid','in',$param['id'])->update(['bonus_deal'=>$param['bonus_deal']]);

            //操作日志
            db('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);
    }
    //退单
    public function delOrder(){
        $id = input('id');
        if(!check_right('menu1572077805')){
            return array('code'=>95,'msg'=>'您没有退单权限！');
        }
        if(!$id){
            return array('code'=>96,'msg'=>'未获取到客资ID！');
        }else{
            $info = db('c_customerinfo')->alias('c')
                ->join('c_customer_order o','c.order_number=o.order_sn','left')
                ->join('c_order_detail d','d.order_sn=o.order_sn','left')
                ->where('c.id',$id)
                ->field('c.id,c.order_number,c.fact_money,c.totalpay_money,c.order_start_time,c.order_day,o.order_amount,o.two_pin_amount,o.order_fact,o.two_pin_fact')
                ->find();
            if(empty($info)){
                return array('code'=>97,'msg'=>'未获取到此客资的订单编号！');
            }else{
                db()->startTrans();
                try{
                    db('c_customer_order')->where('order_sn',$info['order_number'])->delete();
                    db('c_order_detail')->where('order_sn',$info['order_number'])->delete();
                    $arr = [
                        'is_success' => 2,
                        'order_number' => null,
                        'order_start_time' => null,
                        'order_day' => null,
                        'order_type' => null,
                        'fact_money' => null,
                        'totalpay_money' => null,
                    ];
                    db('c_customerinfo')->where('id',$id)->update($arr);
                    $log = "单号：".$info['order_number'].";";
                    $log .= "订单创建时间：".$info['order_start_time'].";";
                    $log .= "订单有效时间：".$info['order_day'].";";
                    $log .= "收款：".$info['fact_money'].";";
                    $log .= "套系：".$info['totalpay_money'].";";
                    action_log($log,[],$id);
                    db()->commit();
                    return array('code'=>200,'msg'=>'退单成功！');
                }catch (\Exception $e){
                    db()->rollback();
                    return array('code'=>100,'msg'=>'退单失败！','data'=>$e->getMessage());
                }
            }
        }
    }
    //批量录入客资
    public function customerAddMore(){
        $channel=controller("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("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);
        //客户来源
        $source=controller("Customer","lib")->source(array('shop_code'=>session('shop_code')));
        $this->assign("source",$source);
        //客户标记
        $mark=controller("Customer","lib")->markSet();
        $this->assign("market",$mark);
        $this->assign("mark1",$mark);
        //客户地址
        $data['type']=1;
        $address=controller("Customer","lib")->address($data);
        $this->assign("address",$address);

        //已设置的归属店  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'] = RECEIVE_WORK_TYPE;
            $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'] = RECEIVE_WORK_TYPE;
                $staff = getShopStaffs($paramG);
                foreach($staff as $key=>$val){
                    $shopAllStaff[] = $val;
                }
            }
        }else{
            $paramG['shop_code'] = session('shop_code');
            $paramG['work_type'] = RECEIVE_WORK_TYPE;
            $shopAllStaff = getShopStaffs($paramG);
        }

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

        //查询归属地是否筛客
        $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);
            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('SMessageTemplateinfo')->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("Setting","lib")->gettrackingKmarkerList();
        $this->assign("tracksign",$tracksign);
        return $this->fetch();
    }
    public function addCustomerMore(){
        $param = input('post.');
        $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($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;
        
        $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_phone($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;
            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' =>'第 【'.$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);
    }

    /**
     * 向员工(追踪人)发送消息  
     * 
     * @param  cid          客资ID
     * @param  staff_id     员工ID
     * @param  staff_name   员工名字
     * @param  msg          消息内容
     * 
     * @return array
     * @author lilong<lilong@suxuantech.cn> 20200511
     */
    public function sendMsgToStaff() {
        // 验证权限
        if(!check_right('menu1584353494')){
            $return['code'] = 201;
            $return['msg']  = '没有发送消息的权限，请确认！';
            // return $return;
        }
        // 获取参数
        $param = input();
        // 验证客资ID
        $cid = (int)$param['cid'];
        if (!$cid) {
            $return['code'] = 99;
            $return['msg']  = '没有获取到客资信息，请重试';
            return $return;
        }
        // 判断请求类型，post为提交 否则为打开页面
        if (request()->isPost()) {
            $staff_id = (int)$param['staff_id'];
            $staff_name = trim($param['staff_name']);
            if (!$staff_name || !$staff_id) {
                $return['code'] = 100;
                $return['msg']  = '没有获取到员工信息，请重试';
                return $return;
            }
            $msg = trim($param['msg']);
            if (!$msg) {
                $return['code'] = 101;
                $return['msg']  = '没有获取到信息内容，请重试';
                return $return;
            }

            $message['send_id']        = session('staff_id');
            $message['send_name']      = session('staff_name');
            $message['send_type']      = 1;
            $message['send_title']     = '';
            $message['send_msg']       = $msg;
            $message['customer_id']    = $cid;
            $message['receive_id']     = $staff_id;
            $message['receive_name']   = $staff_name;
            $message['receive_status'] = 0;
            // 20200612
            $message['operation_type'] = 1;
            $message['operation']      = [];
            $message['time_out']       = 240;
            $res = sendSystemMessage($message);
            if ($res === false) {
                $return['code'] = 102;
                $return['msg']  = '发送失败，请重试！';
                return $return;
            }else{
                $return['code'] = 200;
                $return['msg']  = '发送成功';
                return $return;
            }
        }else{
            // 客资基本资料
            $info = controller("crm/Customer","lib")->getCustomerInfo($cid);
            $this->assign("info",$info);
            return $this->fetch();
        }
    }
    /**
     * 在分配客资前，验证，客资是否订单
     * 
     * @param  id          客资ID     
     * @return array
     * @author lilong<lilong@suxuantech.cn>
     */
    public function checkOrderCustomer(){
    	$param = input();
    	$id = $param['id'];
    	if (!$id) {
    		$return['code']= 201;
            $return['msg'] = '参数错误，请重试。';
            $return['data']= $param['id'];
            return $return;
    	}
    	$where['id'] = ['in',$id];
    	$where['is_success'] = ['in','1,3'];
    	$res = db('c_customerinfo')->where($where)->count();
		$return['code']= 200;
        $return['msg'] = '';
        $return['data']= $res;
    	return $return;
    }
    // 获取店下的员工 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;
    }

    //店下的小组
    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);
        if($shop_code){
            $where['shop_code'] = $shop_code;
        }
        if($department_id){
            $where['department_id'] = $department_id;
        }
        $groups = db("c_staff_group")->where($where)->select();
        return $groups;

    }

    /**
     * 获取组下的人
    */
    public function getStaffInfoByGid(){
        $group_id = input('param.group_id');
        $groupStaff = db("c_staff_group_relation")->where("group_id",$group_id)->select();

        return $groupStaff;
    }
    // 微信 加上 未加上 状态修改
    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{
    		$return = controller("crm/Customer","lib")->setWxStatus(['wxstatus'=>$wxstatus,'cid'=>$cid]);
    	}
    	return json($return);
    }
    // 返回 微信扫码 复制 二维码 
    public function getWxCopyPageEwm(){
    	$param = input();
    	$cid = (int)$param['cid'];
    	if ($cid) {
    		$url = Url('customer/getWxCopyPage','','',true);
	        $url = strpos($url,'?')?($url . '&'):($url.'?');
	        $url = $url.'cid='.(int)$param['cid'];
	        $qrcode = new \Endroid\QrCode\QrCode();
	        $qrcode->setText($url);
	        echo $qrcode->writeString();
    	}
    }
    // 微信扫码 复制 页面
    public function getWxCopyPage(){
    	$param = input();
    	$wechat = db('c_customerinfo')->where('id',(int)$param['cid'])->value('customer_wechat');
    	$this->assign('customer_wechat',$wechat);
    	return $this->fetch();
    }
}
