<?php
/**
 * CRM 基本模块
 * 默认接口方法，此方法内定议基础框架所需要的方法，用于验证模块合法性，模块版本，对接基础架构中需要的方法
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\crm\controller;
use app\crm\lib\Target;
use think\Cache;
use app\index\controller\Base;
use think\Exception;
use think\Log;
use think\Request;
use think\Session;
use PHPExcel_IOFactory;
use PHPExcel;
use Excel5;
use think\Controller;
use app\common\lib\redisQueue;
class Testcustomer extends Base{
    public function check(){
        return $this->fetch();
    }
    public  function test(){
        $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();
    }
    /**
     * 清除模版缓存 不删除 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);
        session('source',null);
        session('channel',null);
        session('accessModel',null);
        session('intention',null);
        session('region',null);
        session('areaSet',null);
        session('capacity',null);
        session('consumptionType',null);
        session('orderAddress',null);
        session('positions_'.session('staff_id'),null);

        cache('companyInfo',null);//清除组织架构缓存

        cache('staffs_*',null);

        //清除菜单缓存
        cache('CRM_menuAll',null);
        cache('CRM_menuAllS',null);
        cache('CRM_menu_p15156347814477',null);
        cache('CRM_menu_position1512878846',null);
        cache('fpRuleStaffs_*',null);
        cache('work_type_'.session('staff_id'));//工作类型缓存
        //linux下没有缓存文件会报错，清除前必须判断文件存不存在
        // array_map( 'unlink', glob(TEMP_PATH.'*.php' ) );
    }
    public function index(){
        // $ip = '220.181.108.102';
//         dump($_SESSION);die;
//         $res = controller('crm/Customer','lib')->companyInfo();
//        $arr = [];
//        foreach($res[1]['shop'] as $key=>$val){
//            array_push($arr,$key);
//        }
//        print_r(getShopCode(1));
//        die;
        // $res = array(
        //     'sql'=>array(
        //         'is_fp'=>'2,4',
        //         'is_already_sk'=>1,
        //     ),
        //     'order_by'=> ' is_valid asc,dj_day desc '
        // );
        //  print_r(json_encode($res));die;
        // 获取个人信息
        // echo 'start';die;
        //echo microtime(true)."==";
        $staffId = input('param.id');
        if(!empty($staffId)){
            $staffId = $staffId;
        }else{
            $staffId = session('staff_id');
        }
        if($staffId == session('staff_id')){
            //当前人
            $info = session('');
            $info['staffname'] = session('staff_name');
        }else{
            $info = cache("staffInfo_".$staffId);
        }
        if(!$info){
            $info = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>$staffId));//个人信息
            if(empty($info['data'])){
                alert('查看有误，无信息','/');
                exit();
            }
            $this->assign('info',$info['data']);
        }else{
            $info['data'] = [
                'id' => $info['staff_id'],
                'staffname' => $info['staffname'],
                'shop_code' => $info['shop_code'],
                'main_position_code' => $info['main_position_code'],
            ];
            $this->assign('info',['id'=>$info['staff_id'],'staffname'=>$info['staffname']]);
        }

        //根据主岗位获取显示内容
        $res = db('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'],
        );

        // $auth = controller('crm/Customer','lib')->get_sales_auth($info['data']);//获取该用户的查询条件
        // $cost = controller('crm/Customer','lib')->cost($info['data'],$where);
        
        //新增客资
        // $newCRM = controller('crm/Customer','lib')->new_crm($info,$where);
        // $this->assign('newCRM',$newCRM);


        /* //已订单
        $orderCRM = controller('crm/Customer','lib')->order_crm($info['data'],input('param.times'));
        $this->assign('orderCRM',$orderCRM);
        $suc = sprintf('%.2f',($orderCRM/$allCRM)*100);
        $this->assign('suc',$suc);
        //进店
        $jd_crm = controller('crm/Customer','lib')->jd_crm($info['data'],$where);
        $this->assign('jd_crm',$jd_crm);*/




        /*//待分配
        $no_fp_crm = controller('crm/Customer','lib')->no_staff_id_crm($staffId,$where);
        $this->assign('no_fp_crm',$no_fp_crm);
        //已预约
        $yuyue_crm = controller('crm/Customer','lib')->yuyue_crm($staffId,input('param.times'));
        $this->assign('yuyue_crm',$yuyue_crm);*/
        //进店未定
        // $jdwd_crm = controller('crm/Customer','lib')->jdwd_crm($staffId,input('param.times'));
        // $this->assign('jdwd_crm',$jdwd_crm);
        //订单消费总额
        /* $xiaofei_amount = controller('crm/Customer','lib')->xiaofei_amount($info['data']['shop_code'],input('param.times'));
        $this->assign('xiaofei_amount',$xiaofei_amount ? $xiaofei_amount : 0);
        $this->assign('avg',sprintf('%.2f',($xiaofei_amount/$orderCRM)));*/
        //实收总额
        // $shishou_amount = controller('crm/Customer','lib')->shishou_amount($info['data']['shop_code'],input('param.times'));
        // $this->assign('shishou_amount',$shishou_amount ? $shishou_amount : 0);


        //目标
        $aim = controller('crm/Customer','lib')->get_aim(array('info'=>$info['data'],'where'=>$where,'staff_id'=>$staffId,'position_code'=>$info['data']['main_position_code']));
//        echo db()->getLastSql();die;
        $this->assign('aim',$aim);
        // //目标完成
        // $mubiao = sprintf('%.2f',($allCRM/$aim['zhi'])*100);
        // $this->assign('mubiao',$mubiao);
        // 实际收款
        // $amount = controller('crm/Customer','lib')->get_amount($staffId,$where);
        // $this->assign('amount',$amount ? $amount : 0);
        // //进店率
        // $jd_crm = controller('crm/Customer','lib')->jd_crm($staffId,$where);
        // $this->assign('jin',sprintf('%.2f',($jd_crm/$allCRM)*100));
        // //转化率
        // $this->assign('zh',sprintf('%.2f',($orderCRM/$allCRM)*100));
        //业绩
        $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));
        //追踪中
        // $zhuizong = controller('crm/Customer','lib')->staff_id_crm($staffId,$where);
        // $this->assign('zhuizong',$zhuizong);
        //总条数
        //
        /* 移到异步
        $total =  controller('crm/Customer','lib')->get_total_count($info['data'],$where);
        $this->assign('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);
            $this->assign('seles',$seles);
        }
        */
        /* //短消息
         $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();
        $this->assign('title',session('group_company_name'));
        return view('home');
    }
    public function getIndexData(){
        $data = ['code'=>200,'msg'=>'','data'=>[]];
        $staffId = input('param.id');
        if(!empty($staffId)){
            $staffId = $staffId;
        }else{
            $staffId = session('staff_id');
        }
        if($staffId == session('staff_id')){
            //当前人
            $info = session('');
            $info['staffname'] = session('staff_name');
        }else{
            $info = cache("staffInfo_".$staffId);
        }
        
        if(!$info){
            $info = controller('crm/Customer','lib')->get_staff_info(array('staff_id'=>$staffId));//个人信息
            if(empty($info['data'])){
                $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'],
            ];
        }
        //根据主岗位获取显示内容
        $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']);
        $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';
        $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'],
        );

        if(in_array('花费',$content)){
            $cost = $tar->cost($arr);
            $data['data'][] = ['id'=>'cost','value'=>sprintf('%.2f',$cost)];
        }

        // $allCRM = controller('crm/Customer','lib')->all_crm($info['data'],$where);
        if(in_array('毛客资',$content)){
            $allCRM = $tar->newCustomerNum($arr);
            $data['data'][] = ['id'=>'allCRM','value'=>$allCRM];
        }
        // $validCRM = controller('crm/Customer','lib')->valid_crm($info['data'],$where);
        if(in_array('有效客资',$content)){
            $validCRM = $tar->validCustomerNumber($arr);
            $data['data'][] = ['id'=>'validCRM','value'=>$validCRM];
        }

        // $validOrder = controller('crm/Customer','lib')->order_crm($info['data'],$where);
        // && strpos($params['staff_id'],',')
        if(in_array('有效新单',$content)){
            $validOrder = $tar->orderNumber($arr);
            $data['data'][] = ['id'=>'validOrder','value'=>$validOrder];
        }
        if(in_array('毛客资成本',$content)){
            $all_cost = $tar->ObtainCost($arr);
            $data['data'][] = ['id'=>'all_cost','value'=>sprintf('%.2f',$all_cost)];
        }
        if(in_array('新单成本',$content)){
            $order_cost = $tar->newOrderCost($arr);
            $data['data'][] = ['id'=>'order_cost','value'=>sprintf('%.2f',$order_cost)];
        }

        if(in_array('获取电话',$content)){
            $tel = controller('crm/Customer','lib')->getTelCount($info['data'],$where);
            $data['data'][] = ['id'=>'tel','value'=>$tel];
        }
        if(in_array('QQ/微信',$content)){
            $qq = controller('crm/Customer','lib')->getQQCount($info['data'],$where);
            $data['data'][] = ['id'=>'qq','value'=>$qq];
        }

        // $validJD = controller('crm/Customer','lib')->validJD($info['data'],$where);
        if(in_array('有效进店',$content)){
            $validJD = $tar->actualIntoCustomerNumber($arr);
            $data['data'][] = ['id'=>'validJD','value'=>$validJD];
        }
        if(in_array('无效新单',$content)){
            // $invalidOrder = controller('crm/Customer','lib')->invalidOrder($info['data'],$where);
            $invalidOrder = $tar->unvalidOrder($arr);
            $data['data'][] = ['id'=>'invalidOrder','value'=>$invalidOrder];
        }
        if(in_array('营收',$content)){
            // $fact = controller('crm/Customer','lib')->fact($info['data'],$where);
            $fact = $tar->dealAmount($arr);
            $data['data'][] = ['id'=>'fact','value'=>$fact];
        }

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

        if(in_array('转化率',$content)){
            //进店转化率 有效订单/进店
            $zhuanhua = $tar->intoValueRate($arr);
            // $this->assign('zhuanhua',sprintf('%.2f',($validOrder/$jd_crm)*100));
            $data['data'][] = ['id'=>'zhuanhua','value'=>sprintf('%.2f',$zhuanhua*100)."%"];
        }
        if(in_array('进店率',$content)){
            //进店率  进店 进客/标记有效
            $jindian = $tar->valueCustomerIntoRate($arr);
            // $this->assign('jindian',sprintf('%.2f',($jd_crm/$validCRM)*100));
            $data['data'][] = ['id'=>'jindian','value'=>sprintf('%.2f',$jindian*100)."%"];
        }
        if(in_array('成交率',$content)){
            //成交率  DT/YT  YT：标记有效；DT：有效成单数
            // $sucOrder = controller('crm/Customer','lib')->sucOrder($info['data'],$where);
            $chengjiao = $tar->orderValueRate($arr);
            $data['data'][] = ['id'=>'chengjiao','value'=>sprintf('%.2f',$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'][] = ['id'=>'yyzh','value'=>sprintf('%.2f',($factIn/$makeIn)*100)."%"];
        }
        if(in_array('A客转化率',$content)){
            //  A客/有效
            $ake = $tar->ACustomerRate($arr);
            // $this->assign('ake',sprintf('%.2f',($cus_a/$validCRM)*100));
            $data['data'][] = ['id'=>'ake','value'=>sprintf('%.2f',$ake*100)."%"];
        }

        $total =  controller('crm/Customer','lib')->get_total_count($info['data'],$where);
        $data['total'] = $total;
        //$this->assign('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);
    }

    //修改信息，通知
    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 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);
        //事业部大屏
        $b_auth = check_right('menu1526378178');
        $this->assign('b_auth',$b_auth);
        //离线开关
        $this->assign('switch',db_config('not_online_is_fp_'.session('staff_id')));
        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 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');
    }
    //移动端提报页面
    public function keziTB(){
        //客户意向
        $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);

        $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));
        }*/
        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);
        //接入店面信息
        $shop = controller('Customer','lib')->getShopInfo(array('brandclass'=>session('brandclass'),'is_dig'=>1));
        $this->assign('shop',$shop['data']);
        //客户来源
        $source=controller("Customer","lib")->source(array('shop_code'=>session('shop_code')));
        $this->assign("source",$source);
        //获取方式
        $accessModel=controller("Customer","lib")->accessModel(array('shop_code'=>session('shop_code')));
        $this->assign("accessModel",$accessModel);
        //来源渠道
        // $info = controller("Customer","lib")->get_staff_info(array('staff_id'=>session('staff_id')));
        // $this->assign("info",$info['data']);
        // $channel=controller("Customer","lib")->channel(array('shop_code'=>session('shop_code')));jies
        // $this->assign("channel",$channel);
        //消费类型
        $consumptionType=controller("Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        //客资地域
        $region=controller("Customer","lib")->region(array('shop_code'=>session('shop_code')));
        $this->assign("region",$region);
        //分区
        // $area=controller("Customer","lib")->areaSet(array('shop_code'=>session('shop_code')));
        // $this->assign("area",$area);
        //查询归属地是否筛客
        // $b_is_sk = controller("Customer", "lib")->is_sk(session('belong_shop_code'));
        // if($b_is_sk == 1 || session('is_sk') == 1){
            // $this->assign('is_sk',1);
            // $this->assign('sklist',controller("Customer", "lib")->sklist('',24));
        // }
        $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'));
        $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 refreshNumber(){
        $data = input('post.');
        $num=controller("Customer","lib")->searchNum($data);
        $this->success('刷新成功', '/',$num);
    }

    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 customerList(){
        if(Request::instance()->isAjax()){
            $data = input();
            if($data['tab'] == 100){
                $detail=controller("Testcustomer","lib")->customerListData_bp($data);
            }else{
                $detail=controller("Testcustomer","lib")->customerListData($data);
            }

            echo  json_encode($detail);
        }else{
            // $data = input();
            // if($data['id']){
            //     $this->assign("cid",$data['id']);
            // }
            //来源渠道
            // $channel=controller("Customer","lib")->channel(array('shop_code'=>session('shop_code')));
            $channel=controller("Testcustomer","lib")->getChannel();
            $this->assign("channel",$channel);
            //客户来源
            $source=controller("Testcustomer","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("Testcustomer","lib")->intention(array('shop_code'=>session('shop_code')));
            $this->assign("intention",$intention);
            $this->assign("intention1",$intention);
            //消费类型
            $consumptionType=controller("Testcustomer","lib")->consumptionType();
            $this->assign("consumptionType",$consumptionType);
            //客资地域
            $region=controller("Testcustomer","lib")->region(array('shop_code'=>session('shop_code')));
            $this->assign("region",$region);
            //分区
            $area=controller("Testcustomer","lib")->areaSet(array('shop_code'=>session('shop_code')));
            $this->assign("area",$area);
            //追踪标记
            $mark=controller("Testcustomer","lib")->markSet(array('shop_code'=>session('shop_code')));
            $this->assign("mark",$mark);
            $this->assign("mark1",$mark);

            //客户标记
            $sign=controller('crm/Setting','lib')->gettrackingKmarkerList();
            $this->assign("sign",$sign);
            //意向店面
            $intentionShop=controller('crm/Testcustomer','lib')->get_shop(array('brandclass'=>session('brandclass'),'is_marketing'=>2));
            $this->assign('intentionShop',$intentionShop);
            //消费能力
            $capacity=controller("Testcustomer","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("Testcustomer","lib")->address($data);
            $this->assign("address",$address);
            //登录人搜索下拉框 根据权限显示
            if(check_right('menu1512637269')){
                if(session('is_belong')==1){
                    $staff_list=controller("Testcustomer","lib")->get_staff_lists();
                }elseif(session('is_belong')==2){
                    $staff_list=controller("Testcustomer","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/Testcustomer','lib')->get_seles_step();
            $this->assign("seles",$seles);
            $this->assign("seless",$seles);
            //追踪失败原因
            $reason = controller('crm/Testcustomer','lib')->get_reason();
            $this->assign("reason",$reason);
            //呼叫前缀
            $prefix = controller('crm/Testcustomer','lib')->getCallPrefix();
            $this->assign("prefix",$prefix);
            //应用是否安装
            $this->assign('is_install',is_install('sx_erp'));
            $this->assign('title','客资');
            //品牌下的店面
            $shops = controller('crm/Testcustomer','lib')->getShopInfo(['brandclass_id'=>session('brandclass_id')]);
            $this->assign('shops',$shops['data']);
            // $menu=getAuth($type='auth');
            $menu = session('mc_auth');
            $this->assign('menu',$menu);

            $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([]));
            //检查当前店是否开启爆破活动，并且活动已开始，在有效时间内
            $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');
            $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);
            $hover_color = db_config('hover_color');
            $this->assign('hover_color',$hover_color);
            $alt_row_color = db_config('alt_row_color');
            $this->assign('alt_row_color',$alt_row_color);
            $success_color = db_config('success_color');
            $this->assign('success_color',$success_color);
            $loss_color = db_config('loss_color');
            $this->assign('loss_color',$loss_color);
            $int_no_suc_color = db_config('int_no_suc_color');
            $this->assign('int_no_suc_color',$int_no_suc_color);
            $unvalid_color = db_config('unvalid_color');
            $this->assign('unvalid_color',$unvalid_color);
            $urgent_color = db_config('urgent_color');
            $this->assign('urgent_color',$urgent_color);
            return view('customer/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.');
        $str = md5(trim($param['customer_tel']).trim($param['customer_qq']).trim($param['customer_wechat']));
        if(session('sub_validate') == $str){
            $returnData = array('code' => 700, 'msg' => '客资录入正在处理中，请稍后...');
            return json($returnData);
        }else {
            session('sub_validate', $str);
            /*$arr = controller('Customer', 'lib')->isRepeat($param['brandclass'], $param['customer_tel'], $param['customer_wechat'], $param['customer_qq'], $param['mate_tel']);
            if ($arr) {
                session('sub_validate',null);
                $returnData = array('code' => 300, 'msg' => '手机号，微信，qq中有一项已存在客资中');
                return json($returnData);
            }*/
            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']]);
                $param['customer_region_id'] = $region['id'];
                $param['customer_region'] = $region['region_name'];
            }
            if (!$param['yp_day']) {
                unset($param['yp_day']);
            }
            $param['add_shop_code'] = session('shop_code');
            $param['add_shop_name'] = session('shop_name');
            // $param['add_shop_code'] = session('belong_shop_code');
            // $param['add_shop_name'] = session('belong_shop_name');
            //查询归属地是否筛客
            $b_is_sk = controller("Customer", "lib")->is_sk(session('belong_shop_code'));
            if ($param['customer_type'] == 1) {
                if ($b_is_sk == 1 || session('is_sk') == 1) {
                    $param['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)) {
                            $param['sk_staff_id'] = $arr['id'];
                            $param['sk_staff'] = $arr['staffname'];
                        }
                    }
                }
            } else {
                if ($b_is_sk == 1) {
                    $param['is_sk'] = 1;
                    //未选择筛客人则随机
                    if (!$param['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)) {
                            $param['sk_staff_id'] = $arr['id'];
                            $param['sk_staff'] = $arr['staffname'];
                        }
                    }
                }
            }

            $res = controller("Customer", "lib")->addCustomer($param);
            if($res['code'] == 201){
                session('sub_validate',null);
                $returnData = array('code' => 300, 'msg' => '手机号，微信，qq中有一项已存在客资中');
                return json($returnData);
            }
            if ($res) {
                //更新转介绍最后一次录入的介绍人信息
                if (input('post.customer_type') == 2) {
                    $arr = array(
                        'introducer_name' => input('post.introducer_name'),
                        'introducer_tel' => input('post.introducer_tel'),
                        'introducer_ordernum' => input('post.introducer_ordernum'),
                    );
                    cookie('introducerInfo', $arr);
                }
                if ($param['customer_remark']) {
                    $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'];
                    if($param['shop_code'] == $param['add_shop_code']) {
                        $record['sales_remark'] = '手机录入-前端-' . trim($param['customer_remark']);
                    }else{
                        $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);
                        //日志
                        action_log($param, '', $res, session('staff_id'), session('staff_name'));
                        db()->commit();
                    } catch (Exception $e) {
                        db()->rollback();
                    }
                }
                session('sub_validate',null);
                return json(array('msg' => '提报成功', 'code' => 200));
            } else {
                session('sub_validate',null);
                return json(array('msg' => '提报失败', 'code' => 100));
            }
        }
    }
    //客资录入
    public function addCustomer(){
        $data = input('post.');
        //$detail=controller("AddCustomer","lib")->add($data);
        //$res = controller('AddCustomer','lib')->addCustomer($detail);
        unset($data['file']);//不知道哪来的file参数；毛客资统计时添加失败，必须删除此参数
        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标签
        $data['dj_staff_id']=session('staff_id');
        $data['dj_staff']=session('staff_name');
        $data['dj_staff_number']=session('staff_number');
        $data['add_shop_name']=session('shop_name');
        $data['add_shop_code']=session('shop_code');
        $data['shop_name']= session('belong_shop_name');
        $data['shop_code']= session('belong_shop_code');
        $data['brandclass']= session('brandclass');
        $data['brandclass_id']= session('brandclass_id');
        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_intention_id', $data['customer_intention_id']);//客户意向
        cookie('customer_cource_id',$data['customer_cource_id']);//客户来源
        cookie('customer_area_id',$data['customer_area_id']);//客户分区
        cookie('customer_region_id',$data['customer_region_id']);//客户地域
        cookie('is_urgent',$data['is_urgent']);//是否加急

        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;
        $res = controller("Customer", "lib")->addCustomer($data);
        if($res['code'] == 201){
            return json($res);
        }
        if ($res === false) {
            if(is_weixin()){
                return $this->wx_index();
            }else{
                $returnData = array('code' => 500,'msg' =>'客资录入失败');
                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']
                );

                $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);
        //     }
        // }
        $size=getMaxUploadSize();
        $this->assign('size', $size);
        return view('import');
    }

    //获取最新导入excel文件历史记录
    public function new_list(){

        $res=controller("Customer","lib")->new_list();
        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');
        controller("Customer","lib")->uploadExcel($file,$before_name);
    }

    //下载源文件
    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('get.');
        if($data['cus_id']){
            $sql= " id in (".$data['cus_id'].") ";
        }else{
            $end_time=$data['end_time'];
            $data['end_time']=date("Y-m-d",strtotime("$end_time +1 day"));
            $sql=controller('Customer','lib')->customerSearch($data);
            // var_dump($data);
            // exit;
            if(check_right('menu1512637269')){
                switch (session('is_belong')){
                    case '2':
                        $sql .= " and brandclass = '".session('brandclass')."' ";
                        break;
                    case '3':
                        $sql .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                        break;
                    case '4':
                        $sql .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                        break;
                }
            }else{
                if(strpos($data['type_info'],'sales_staff_id')===false){
                    if(!$data['tab']||$data['tab']==1){//所有
                        $sql .= " and (dj_staff_id = '".session('staff_id')."' or (sales_staff_id = '".session('staff_id')."' and is_fp=1 ) or (sk_staff_id = '".session('staff_id')."')) ";
                    }elseif($data['tab']&&$data['tab']==2){//待追踪
                        $sql .= " and sales_staff_id = '".session('staff_id')."' ";
                    }elseif($data['tab']&&$data['tab']==3){//待分配
                        $sql .= " and shop_code = '".session('shop_code')."' ";
                    }elseif($data['tab']&&$data['tab']==4){//追踪中
                        $sql .= " and (dj_staff_id = '".session('staff_id')."' or sales_staff_id = '".session('staff_id')."') ";
                    }elseif($data['tab']&&$data['tab']==5){//已订单
                        $sql .= " and (dj_staff_id = '".session('staff_id')."' or sales_staff_id = '".session('staff_id')."') ";
                    }elseif($data['tab']&&$data['tab']==6){//进店未成交
                        $sql .= " and (dj_staff_id = '".session('staff_id')."' or sales_staff_id = '".session('staff_id')."') ";
                    }elseif($data['tab']&&$data['tab']==7){//流失
                        $sql .= " and (dj_staff_id = '".session('staff_id')."' or sales_staff_id = '".session('staff_id')."') ";
                    }elseif($data['tab']&&($data['tab']==8)){//待筛客
                        $sql .= " and sk_staff_id = '".session('staff_id')."'  ";
                    }elseif($data['tab']&&($data['tab']==9)){//、已筛客
                        $sql .= " and sk_staff_id = '".session('staff_id')."'  ";
                    }elseif($data['tab']&&($data['tab']==10)){//、当日接收
                        $sql .= " and (dj_staff_id = '".session('staff_id')."' or (sales_staff_id = '".session('staff_id')."' and is_fp=1 ) or (sk_staff_id = '".session('staff_id')."')) ";
                    }elseif($data['tab']&&($data['tab']==11)){//、三日内追踪
                        $sql .= " and (dj_staff_id = '".session('staff_id')."' or (sales_staff_id = '".session('staff_id')."' and is_fp=1 ) or (sk_staff_id = '".session('staff_id')."')) ";
                    }elseif($data['tab']&&($data['tab']==12)){ //、当日预进店
                        $sql .= " and (dj_staff_id = '".session('staff_id')."' or (sales_staff_id = '".session('staff_id')."' and is_fp=1 ) or (sk_staff_id = '".session('staff_id')."')) ";
                    }
                }
            }
        }

        $customer=db('c_customerinfo')->field('customer_channel,sign_name,is_valid,op_signinfo,customer_number,customer_name,customer_sex,customer_tel,customer_wechat,customer_weibo,customer_qq,city,marry_day,budget,consulation_shop,yjd_action_day,yjd_day,track_record,is_intostore,syjd_day,is_success,order_day,totalpay_money,loss_cause,customer_type,dj_day,create_time,is_fp,is_loss,dj_staff,sales_staff,sk_staff,introducer_name,introducer_tel,introducer_ordernum,introducer_type,tel_visit_num,last_trackday,consultation_type,customer_cource,customer_intention,access_model,customer_orderaddress,customer_area,brandclass,shop_name,add_shop_name')->where($sql)->select();

        //$title=array('客户姓名','客户编号','性别','手机号','微信','微博','QQ','省','市','区','详细地址','客户类型','消费类型','客户渠道','客户来源','客户意向','接单点','获取方式','客户分区','客户地域','消费能力','是否有效','是否进店','是否分配','登记日期','介绍人');
        $title=export_header();
        $file="customer.xlsx";
        controller("Customer","lib")->export($title,$customer,$file);
    }

    //模板下载
    public function excel_download(){
        //controller("Customer","lib")->excel_template();
        $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 customerAllot(){
        // // 当前店下的部门列表
        // $shop_code = session('shop_code');
        // $url = '5a0aef152b750';
        // $arr = array('shop_code'=>$shop_code);
        // $department = sx_call($url, $arr);
        // 权限
        $auth = check_right('menu1512970623');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有分配客资的权限，请先设置权限');
            return json($return);
            exit;
        }
        // 当前店及当前店的客资提报归属店
        $shopList = [];
        // 当前店和客资提报归属店 是同一个店
        if (session('shop_code') == session('belong_shop_code')) {
            $shopList[0] = [
                'shop_code'=>session('shop_code'),
                'shop_name'=>session('shop_name'),
            ];
        }else{
            $shopList[0] = [
                'shop_code'=>session('shop_code'),
                'shop_name'=>session('shop_name'),
            ];
            $shopList[1] = [
                'shop_code'=>session('belong_shop_code'),
                'shop_name'=>session('belong_shop_name'),
            ];
        }
        $this->assign('shopList',$shopList);

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

        // $this->assign('department',$department['data']);
        $this->assign('targetList',$targetList);
        return $this->fetch();
    }

    // 手动分配，根据部门，业绩，时间区间，查询员工，并且根据业绩排序
    public function getTargetStaffs(){
        $data = input('post.');
        
        $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');
        $time_area     = $data['time_area'] ? $data['time_area'] : 'today';
        $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;
               $staffs = cache('staffs_'.$shop_code);
               if(empty($staffs)){
                   $staffs = controller('Customer','lib')->get_staff_lists($pram);
                   cache('staffs_'.$shop_code,$staffs);
               }
           }
        // }
        // var_dump($staffs);
        // exit;

        $day = getdateArea($time_area);
        //获取小组下的员工
        if($group_id){
            $groupStaffs = db('c_staff_group_relation')->where('group_id',$group_id)->column('staff_id');
        }

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

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

    // 手动分配 接收
    public function allotReceive(){
        $data = input('post.');
        $cid  = $data['cid'];
        $sid  = $data['sid'] ? $data['sid'] : session('staff_id');
        $rigth = check_right('menu1512970623');
        $date = date('Y-m-d H:i:s',time());
        if ($rigth) {
            $cids = explode(',', $cid);
            foreach ($cids as $key => $value) {
                // var_dump($value);
                $this->customerAllotOne($value, $sid);
                // 将对应的客资从c_fp_pool中删除
                db('c_fp_pool')->where('cid', $value)->delete();
            }
            // 接收人
            // 根据员工id获取员工信息
            $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'=>'分配完成'];
        }else{
            $returnData = ['code'=>100,'msg'=>'抱歉，您没有分配权限'];
        }
        return json($returnData);
    }
    // 分配动作
    public function customerAllotOne($cid, $sid){
        // 是否存在相应客资
        $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'];

            $date = date('Y-m-d H:i:s');
            $newDate['sales_staff_id'] = $sid;
            $newDate['sales_staff'] = $res['staffname'];
            $newDate['sales_staff_number'] = $res['staffnumber'];
            // $newDate['shop_code'] = $res['shop_code'];
            // $newDate['shop_name'] = $res['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 {
                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;
                }
                // 接收成功之后，删除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 = [
                    'jr_time'   => $date,
                    'fp_status' => 1
                ];
                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'          => 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);
            }
            // 接收成功之后，删除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 = [
                'jr_time'   => $date,
                'fp_status' => 1
            ];
            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);
        }

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

        // 第一次请求
        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'];
    }

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

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

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

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


        // 根据cid取客资名称和编号
        $cInfo = db('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');

                $message['send_type']      = 1;
                $message['send_title']     = '系统消息';
                $message['send_msg']       = '您有一笔客资被驳回，姓名：'.$cInfo['customer_name'].'，驳回理由：'.$msg.'，请确认。';
                $message['customer_id']    = $cid;
                $message['receive_id']     = $receive_id;
                $message['receive_name']   = $receive_name;
                $message['receive_status'] = 0;
                $message['operation_type'] = 2;
                $message['operation']      = '';
                $message['time_out'] = 120;
                $sendStatus = sendSystemMessage($message);

                // 向上一级发信息  微信
                $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];
                db()->rollback();
            };
        }else{
            $return = ['msg'=>'您不是当前客资的追踪人或筛客人或没有驳回权限','code'=>400];
        }
        return $return;
    }
    // 确定客资反驳回动作 ****
    public function customerUnValidUpdate(){
        // 权限
        $auth = check_right('menu1517278844');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有反驳回给网销的权限，请先设置权限');
            exit;
        }
        // 取post值
        $data = input('post.');

        $cid = (int)input('post.cid');
        $isValid = (int)input('post.is_valid_fbh');
        $send_msg = input('post.fbhReason').'<br />';
        // 根据cid取客资名称和编号
        $cInfo = db('c_customerinfo')->where('id', $cid)->field('customer_name, customer_number, dj_staff_id,dj_staff, sk_staff_id, sk_staff,sales_staff_id,sales_staff')->find();
        if(check_right('menu1517278844') || session('staff_id') == $cInfo['dj_staff_id'] || session('staff_id') == $cInfo['sk_staff_id']){
        // if(check_right('menu1517278844') && session('staff_id') == $cInfo['dj_staff_id'] || session('staff_id') == $cInfo['sk_staff_id']){
            db()->startTrans();
            // 更新 客资表，插入  追踪记录表
            try {
                // 更新客资表
                $data = ['is_valid'=>$isValid];
                $data['yx_day'] = date('Y-m-d H:i:s',time());
                if($isValid == 1){
                    $data['yx_day'] = date('Y-m-d H:i:s',time());
                }else{
                    $data['yx_day'] = date('Y-m-d H:i:s',time());
                }
                db('c_customerinfo')->where('id', $cid)->update($data);
                // // 取cache值
                // $key = 'unvalidFileUrl_'.$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);

                // 向下一级发信息  PC消息
                if ($cInfo['sales_staff_id']) {
                    $receive_id  = $cInfo['sales_staff_id'];
                    $receive_name= $cInfo['sales_staff'];
                }else{
                    $receive_id  = $cInfo['sk_staff_id'];
                    $receive_name= $cInfo['sk_staff'];
                }

                $message['send_type']      = 1;
                $message['send_title']     = '系统消息';
                $message['send_msg']       = '您有一笔客资被反驳回，姓名：'.$cInfo['customer_name'].'，请确认。';
                $message['customer_id']    = $cid;
                $message['receive_id']     = $receive_id;
                $message['receive_name']   = $receive_name;
                $message['receive_status'] = 0;
                $message['operation_type'] = 2;
                $message['operation']      = '';
                $message['time_out'] = 120;
                $sendStatus = sendSystemMessage($message);

                // 向上一级发信息  微信
                $msg = input('post.send_msg');
                $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'=> $receive_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'=>'已反驳回给网销'];
                }else{
                    db()->rollback();
                    $return = ['msg'=>'操作失败，请联系管理员'];
                }
            } catch (Exception $e) {
                $return = ['msg'=>'操作失败，请联系管理员'];
                db()->rollback();
            };
        }else{
            $return = ['msg'=>'您不是当前客资的录入人或筛客人或没有反驳回权限'];
        }

        // exit;
        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) {
            $shop_type = session('shop_type');
            if ($shop_type == 2) {
                $shop_type = 1;
            }else{
                $shop_type = 0;
            }
            $erp = config('ext.app_config')['sx_erp'];
            $addr= $erp['addr'];
            $tel = 1;
            $url = $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(){
        // 提交客资详情资料
        if (request()->isPost()) {
            $data = input('post.');
            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 != $has[$key]) {
                    // $kStr = translate('c_customerinfo',$key);
                    // if ($kStr) {
                    //     $oldDate[$kStr]  = $has[$key];
                    //     $newDate[$kStr]  = $value;
                    // }

                    $newDateIn[$key] = $value;
                    $oldDateIn[$key] = $has[$key];
                }
            }
            if($newDateIn['customer_tel']||$newDateIn['customer_wechat']||$newDateIn['customer_qq']||$newDateIn['mate_tel']){
                // 判断手机号，同一个事业部（品牌）相同手机号(且没有过期)，不能提交
                $rep=controller('Customer','lib')->isRepeat($has['brandclass'],$newDateIn['customer_tel'],$newDateIn['customer_wechat'],$newDateIn['customer_qq'],$newDateIn['mate_tel'],$data['id']);
                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'].'天后';
                    $time = date('Y-m-d H:i:s',strtotime($newDateIn['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();
                    }
                }
            }else{
                $newDateIn['next_time'] = null;
            }
            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']) {
                // $telInfo = getData($newDateIn['customer_tel']);
                // $arr = explode(' ',$telInfo);
                // $newDateIn['tel_belong'] = $arr[1].' '.$arr[2];
                // $newDateIn['tel_operator'] = $arr[3];
                // $newDateIn['tel_area_code'] = $arr[5];
                action_log($newDateIn['customer_tel'],$oldDateIn['customer_tel'],$has['id'],session('staff_id'),session('staffname'),$module,$controller,'editCustomerTel');
            }

            // 开启事务
            db()->startTrans();
            try {
                $res = db('c_customerinfo')->where('id', $data['id'])->update($newDateIn);
                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']]);
                    }
                }
                //进店操作变动记录追踪日志
                if($newDateIn['is_intostore']){
                    $str = getIsIntostore($newDateIn['is_intostore']);
                    //追踪记录
                    $params['customer_id'] = $data['id'];
                    $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('staffnumber');
                    $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_start_day'])){
                        $arr = array(
                            'c_star_day' => $time,
                            'c_end_day' => $time,
                            'last_trackday' => $time,
                        );
                    }else{
                        $arr = array(
                            'c_end_day' => $time,
                            'last_trackday' => $time,
                        );
                    }
                    db('CCustomerinfo')->where('id',$data['id'])->update($arr);
                    //修改客资表近三次追踪记录
                    getSalesTracking($data['id']);
                    //进店日志
                    action_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('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) {
                        // 查看排重表
                        $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_tel']);
                        }
                        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();
                        }
                    }
                }

                $listName = 'historyDataList';
                $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'  => $has['sales_staff_id'],
                    'jr_day' => $has['jr_day'],
                ];
                $message = array(
                    'type'      => 1,
                    'staff_id'  => session('staff_id'),
                    'identity'  => 'sale',
                    'cinfo'     => $cinfo,
                    'old_data'  => $oldDateIn,
                    'new_data'  => $newDateIn,
                    'controller'=> 'Customer',
                    'action'    => 'customerInfo'
                );
                $pushStatus = push_list($listName, $message);
                if ($pushStatus) {
                    db()->commit();
                    $returnData = array('code' => 1,'msg' => '编辑客资信息成功');
                }else{
                    db()->rollback();
                    $returnData = array('code' => 10001,'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);
                if(is_install('sx_erp'))  $customerInfo['is_erp']=1;

                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']){//如果提报店和归属店不一样，把提报店的渠道追加到归属店的渠道里面
                        $allSet['channelInfo'] = array_merge($allSet['channelInfo'],array(array('id'=>$customerInfo['customer_channel_id'],'channel_name'=>$customerInfo['customer_channel'])));
                    }
                    // var_dump($customerInfo['is_valid']);
                    // var_dump($allSet['channelInfo']);
                    // exit;
                    $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("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);

                foreach ($changeLogs as $key => $value) {
                    $oldDate = json_decode($value['old_data'], true);
                    $oldDateStr = $value['old_data'];
                    foreach ($oldDate as $k => $v) {
                        $oldDateStr .= $k.'：'.$v.'；';
                    }
                    $newDate = json_decode($value['data'], true);
                    $newDateStr = '';
                    foreach ($newDate as $k => $v) {
                        $newDateStr .= $k.'：'.$v.'；';
                    }
                    $oldDateStr = $value['old_data'];
                    $newDateStr = $value['data'];
                    $changeLogs[$key]['oldDateStr'] = $oldDateStr;
                    $changeLogs[$key]['newDateStr'] = $newDateStr;
                }
                // var_dump($changeLogs);
                // exit;
                $this->assign('changeLogs', $changeLogs);
                // 历史订单，现在没有表，调其他接口
                $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'];
                    }
                }
                // 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);
            return $this->fetch('customerinfo');
        }
    }

    // 获取员工所有消息 Eric
    public function getAllMsg(){
        $this->assign('title','消息列表');
        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,
        ];
        $messageList = db('c_message')
            ->where($where)
            ->limit($limit)
            ->page($page)
            ->order('id desc')
            ->select();
        $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)->count();
        $return['code'] = 0;
        $return['msg']  = '';
        $return['count']= $count;
        $return['data'] = $messageList;
        return json($return);
    }

    public function customerAdd(){
        //来源渠道
//        $channel=controller("Customer","lib")->channel();
        $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);
        //客户意向
        $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();
        $this->assign("mark",$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("Customer","lib")->address($data);
        $this->assign("address",$address);
        $shopAllStaff=controller('Customer','lib')->getShopAllStaff(array('shop_code'=>session('belong_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');//是否加急
        //查询归属地是否筛客
        $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);
            // var_dump(session('is_sk'));
            $this->assign('sklist',controller("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([]));
        return $this->fetch();
    }
    //通过归属地查询省市
    public function getAddressInfo(){
        $info = input('post.name');
        $arr = explode(' ',$info);
        if(count($arr) == 1){
            $ret['pid'] = controller("Customer","lib")->getAddressByLike(['name'=>$arr[0]]);
        }else{
            $ret['pid'] = controller("Customer","lib")->getAddressByLike(['name'=>$arr[0]]);
            $ret['cid'] = controller("Customer","lib")->getAddressByLike(['name'=>$arr[1]]);
        }
        return $ret;
    }
    public function upload_img(){
        //$content = input('content');
        $file = Request::instance()->file('file');
        if(empty($file)){
            $result["code"] = "1";
            $result["msg"] = "请选择图片";
            $result['data']["src"] = '';
        }else{
            // 移动到 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'upload/img' );
            if($info){
                $name_path =str_replace('\\',"/",$info->getSaveName());
                //成功上传后 获取上传信息
                $result["code"] = '0';
                $result["msg"] = "上传成功";
                $result['data']["src"] = "/upload/img/".$name_path;
            }else{
                // 上传失败获取错误信息
                $result["code"] = "2";
                $result["msg"] = "上传出错";
                $result['data']["src"] ='';
            }
        }
        //$a='http://crm.sx.com/public/uploads/img/20171221/2af12f7d271e633836abb03f48f559db.jpg';
        //print_r($result);die;
        return json_encode($result);
    }

    //获取客资详情
    public function getCustomerInfo(){
        // 客资基本资料
        $customerInfo = controller("Customer","lib")->getCustomerInfo(input('post.id'));
        return json($customerInfo);
    }
    //电访
    public function dianfang(){
        // 权限
        $auth = check_right('menu1512971662');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有追踪的权限，请先设置权限');
            return json($return);
            exit;
        }
        //标记有效
        if(check_right('menu1517129299')){
            $this->assign('valid',true);
        }else{
            $this->assign('valid',false);
        }
        $auth1 = check_right('menu1519633870');
        if ($auth1) {
            $this->assign('yyjd',true);
        }else{
            $this->assign('yyjd',false);
        }
        $param = input('param.');
        //呼叫前缀
        $prefix = controller('crm/Customer','lib')->getCallPrefix();
        $this->assign("prefix",$prefix);
        $info = controller("Customer","lib")->getCustomerInfo(input('param.id'));
        $this->assign('info',$info);
        //意向店面
        $intentionShop=controller('crm/Customer','lib')->get_shop(array('brandclass'=>$info['brandclass'],'is_marketing'=>2));
        $this->assign('intentionShop',$intentionShop);
        //客资标记
        $sign = controller('crm/Setting','lib')->gettrackingKmarkerList();
        $this->assign('sign',$sign);
        //客户意向
        $intention=controller("Customer","lib")->intention(array('shop_code'=>session('shop_code')));
        $this->assign('intention',$intention);
        //消费类型
        $consumptionType=controller("Customer","lib")->consumptionType();
        $this->assign("consumptionType",$consumptionType);
        //追踪阶段
        $seles = controller('crm/Customer','lib')->get_seles_step();
        $this->assign("seles",$seles);
        $auth = check_right('menu1512998373');
        $this->assign("auth",$auth);
        //不再追踪原因
        $reason = db('s_file_reason')->where('shop_code',session('shop_code'))->select();
        $this->assign("reason",$reason);
        //驳回原因
        $reject = db('s_reject_reason')->where('shop_code',session('shop_code'))->select();
        $this->assign("reject",$reject);
        //省
        $province = controller('crm/Customer','lib')->address(['type'=>1,'shop_code'=>session('shop_code')]);
        $this->assign("province",$province);
        return $this->fetch();
    }
    //追踪记录
    public function traceRecord(){

    }

    //修改日志
    public function changeLog(){

    }

    //历史订单
    public function orderHistory(){

    }

    //编辑状态
    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.'));
    }
    //追踪修改
    public function editSalesTracking(){
        return controller('Customer','lib')->editSalesTracking(input('post.'));
    }
    //新客资来电添加
    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');
            //查询有无数据
            $info = db('s_custom_column')->where('staff_id',session('staff_id'))->find();
            if($info['id']){
                db('s_custom_column')->where('staff_id',session('staff_id'))->update($data);
            }else{
                db('s_custom_column')->insert($data);
            }

            cache('colColumn_'.session('staff_id'),$column);
            cache('colNames_'.session('staff_id'),$param['name'] ? json_encode($param['name']): null);
            cache('colModel_'.session('staff_id'),$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'));
        $names = cache('colNames_'.session('staff_id'));
        $model = cache('colModel_'.session('staff_id'));

        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'))->find();
            if(!empty($info)){
                cache('colColumn_'.session('staff_id'),$info['custom_column']);
                cache('colNames_'.session('staff_id'),$info['custom_name']);
                cache('colModel_'.session('staff_id'),$info['custom_model']);
                $info = array(
                    'custom_name'=>($info['custom_name']),
                    'custom_model'=>($info['custom_model']),
                );
            }
        }
        return $info;
    }
    //筛客
    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.');
        $info = controller("Customer","lib")->getCustomerInfo($param['id']);
        //意向店面
        $intentionShop=controller('crm/Customer','lib')->get_shop(array('brandclass'=>$info['brandclass'],'is_marketing'=>2));
        $this->assign('info',$info);
        $this->assign('intentionShop',$intentionShop);
        return $this->fetch();
    }
    //预约进店
    public function customerYJD(){
        if(!check_right('menu1519633870')){
            return array('code'=>130,'msg'=>'你无此操作权限');
        }else{
            return controller("Customer","lib")->customerYJD(input('post.'));
        }
    }
    public function getStaffForWorktype(){
        $shop_code = input('post.shop_code');
        return controller("Customer","lib")->sklist($shop_code,1);
    }
    //转订单
    public function orderManager(){
        // 权限
        $auth = check_right('menu1519633923');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有操作转订单的权限，请先设置权限');
            return json($return);
            exit;
        }
        $id = (int)input('param.id');
         $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,reception_id,reception_name,consulation_shop_code,shop_code,add_shop_code,customer_channel_id,customer_channel,consultation_type,brandclass')
            ->find();
        //来源渠道
        // $channel=controller("Customer","lib")->channel(array('shop_code'=>session('shop_code')));
        $channel=controller("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);
        //意向店面
        $intentionShop=controller('crm/Customer','lib')->get_shop(array('brandclass'=>$cusInfo['brandclass'],'is_marketing'=>2));

        $this->assign('intentionShop',$intentionShop);
        $this->assign('cusInfo',$cusInfo);
        // $this->assign('id',$id);
        
        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("Customer","lib")->editOrder($param);
        }
    }
    public function zhuanOrder(){
        if(!check_right('menu1519633923')){
            return array('code'=>130,'msg'=>'你无此操作权限');
        }else{
            $param = input('post.');
            return controller("Customer","lib")->zhuanOrder($param);
        }
    }
    //转客资
    public function 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 signValid(){
        if(check_right('menu1517129299')){
            $id = input('post.id');
            $info = controller("Customer","lib")->getCustomerInfo($id);
            if($info['is_valid'] == 1){
                return array('code'=>500,'msg'=>'已是有效客资,不用再次标记！');
            }else{
                $data['yx_day'] = date('Y-m-d H:i:s',time());
                $data['is_valid'] = 1;
                $data['unvalid_id'] = 0;
                $data['unvalid_reason'] = null;
            }

            db()->startTrans();
            try{
                $res = db('c_customerinfo')->where('id',$id)->update($data);
                //追踪记录
                $params['customer_id'] = $id;
                $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('staffnumber');
                $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_start_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }
                db('CCustomerinfo')->where('id',$id)->update($arr);
                //修改客资表近三次追踪记录
                getSalesTracking($id);
                action_log($data,'',$id,session('staff_id'),session('staff_name'));
                //如果是爆破活动，修改对应的爆破表数据
                if($info['is_act'] == 2){
                    db('c_swap_customer')->where('customer_number',$info['customer_number'])->update(['is_valid'=>1]);
                }
                db()->commit();
                return array('code'=>200,'msg'=>'标记有效成功');
            }catch (Exception $e){
                db()->rollback();
                return array('code'=>300,'msg'=>'标记有效失败');
            }
        }else{
            return array('code'=>100,'msg'=>'您没有标记有效权限');
        }

    }
    //一键标记无效
    public function signUnvalid(){
        if(check_right('menu1517129331')){
            $param = input();
            $info = controller("Customer","lib")->getCustomerInfo($param['id']);
            if($info['is_valid'] == 3){
                return array('code'=>500,'msg'=>'已是无效客资,不用再次标记！');
            }else{
                $data['yx_day'] = date('Y-m-d H:i:s',time());
                $data['is_valid'] = 3;
                $data['unvalid_id'] = $param['unvalid_id'];
                $data['unvalid_reason'] = $param['unvalid_reason'];
            }

            db()->startTrans();
            try{
                db('c_customerinfo')->where('id',$param['id'])->update($data);
                //追踪记录
                $params['customer_id'] = $param['id'];
//                $params['sales_remark'] = '标记无效';
                $params['sales_remark'] = '标记无效--'.$data['unvalid'];
                $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('staffnumber');
                $params['shop_name'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('CSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$param['id'],null);
                //修改追踪时间
                $time = date('Y-m-d H:i:s',time());
                if(empty($info['c_start_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }
                db('CCustomerinfo')->where('id',$param['id'])->update($arr);
                getSalesTracking($param['id']);
                action_log($data,'',$param['id'],session('staff_id'),session('staff_name'));
                //如果是爆破活动，修改对应的爆破表数据
                if($info['is_act'] == 2){
                    db('c_swap_customer')->where('customer_number',$info['customer_number'])->update(['is_valid'=>3]);
                }

                db()->commit();
                return array('code'=>200,'msg'=>'标记无效成功');
            }catch (Exception $e){
                db()->rollback();
                return array('code'=>300,'msg'=>'标记无效失败');
            }
        }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;
            }

            db()->startTrans();
            try{
                db('c_customerinfo')->where('id',$id)->update($data);
                //追踪记录
                $params['customer_id'] = $id;
                $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('staffnumber');
                $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_start_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }
                db('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');
        $url = '5a62dcd5c7e40';
        $res = sx_call($url,['shop_code'=>$shop_code]);
        if($res['code'] == 200){
            return $res['data'];
        }else{
            return false;
        }
    }
    //部门下的人员
    public function getDepartmentStaff(){
        $id = input('param.id');
        $url = '5a01766b4a3dd';
        $res = sx_call($url,['department_id'=>$id]);
        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(ltrim($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(){
        $update = include_once(ROOT_PATH . 'application/index/lib/update_log.php');
        krsort($update);
        $this->assign('update',$update);
        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(){
        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');
        $data = input();
        $url = '5a0b96b65c111';
        $info = sx_call($url,['position_code'=>$data['position_code']]);
        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('is_belong',$position['grade_type']);
                session('is_sk',$shopInfo['is_sk']);
                session('is_marketing',$shopInfo['is_marketing']);//是否是营销店
                session('open_id', $shopInfo['open_id']);
                //替换cache信息
                $cacheInfo = cache('staffInfo_'.session('staff_id'));
                $cacheInfo['brandclass_id'] = $position['brandclass_id'];
                $cacheInfo['brandclass'] = $position['brandclass'];
                $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['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['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 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(){

        return $this->fetch();
    }
    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 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);
        return $info;
    }
    //捞客资
    public function customerBySalf(){
        $switch = db_config('fp_switch_'.session('shop_code'));
        $this->assign('switch',$switch);
        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;

        $info = db('c_customerinfo')->where('shop_code',session('shop_code'))->where('is_fp','in',[2,4])->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])->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);
    }
}