<?php
/**
 * CRM 实现模块
 * CRM的基本功能实现，如客资录入，客资查询等。
 * 所有业务的真正实现全在lib目录下建controller并且访问modle等，供controller层调用
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\crm\lib;
use think\Cache;
use think\Controller;
use PHPExcel_IOFactory;
use Excel5;
use PHPExcel;
use app\common\lib\redisQueue;
use think\Exception;

class Customer extends Controller{
    protected $errid = 0;
    protected $errmsg = '';
    function login($params){
        testTime(__FILE__,__LINE__);
        if(!empty($params['five'])){
            $params['five'] = input('post.five');
            $time =date('Y-m-d H:i:s',time()+432000);
        }else{
            $time = date('Y-m-d H:i:s',time()+86400);
        }
        $params['login_ip'] = get_client_ip();
        $params['app_id'] = config('app_id');
        $url = '59f2e9fb5f863';
        $res = sx_call($url,$params);
        // http://crm.sx.com/crm/Setting/menuSet
        if($res['code'] == 200){
            // var_dump(session('return_url'));
            $loginRes = $this->setLoginEnv($res['data'],'pc','user_name',$params['five']);
            if($loginRes){
                //所有可查看店的岗位
                $info = $this->getPositions();
                if($info){
                    session('positions_'.session('staff_id'),$info);
                }
                $returnUrl = '/crm/Customer/customerList';
                if(session('return_url')){
                    $returnUrl = session('return_url');
                    session('return_url',null);
                }
                //登录日志
                $isTable = isTableExist('l_login_log');
                if($isTable){
                    $logId = db('l_login_log')->insertGetId(['staff_id'=>session('staff_id'),'staff_name'=>session('staff_name'),'is_five'=>$params['five'],'last_login_time'=>date('Y-m-d H:i:s', time()),'last_login_ip'=>get_client_ip(),'session_id'=>session('session_id')]);
                    session('login_log_id',$logId);
                }
                return [
                    'code'=>200,
                    'return_url'=>$returnUrl,
                ];
            }else{
                $res = array('code'=>101,'error'=>101,'msg'=>$res['msg'],'data'=>$res);
            }

        }else{
            if($res['code'] == 500){
                $res = array('code'=>500,'error'=>101,'msg'=>'此员工已离职');
            }elseif($res['code'] == 403){
                $res = array('code'=>100,'error'=>101,'msg'=>$res['msg']);
            }else{
                $res = array('code'=>100,'error'=>101,'msg'=>$res['msg'],'data'=>$res);
            }
        }
        return $res;
    }

    /**
     * 设置登录环境，根据MC返回的登录结果数据
     *
     * @param type $loginRes
     */
    function setLoginEnv($loginRes,$loginType='pc',$loginMethod='user_name',$five = 0){
        if(empty($loginRes['staff_id'])
            || empty($loginRes['staffname'])
            || empty($loginRes['staffnumber'])
            || empty($loginRes['session_id'])
            //|| empty($loginRes['setkey'])
        ){
            return false;
        }
        
        $return_url = session('return_url');

        session();
        session('return_url',$return_url);

        session('staff_id',$loginRes['staff_id']);
        session('staff_name',$loginRes['staffname'] ? $loginRes['staffname'] : $loginRes['staff_name']);
        session('staff_number',$loginRes['staffnumber'] ? $loginRes['staffnumber'] : $loginRes['staff_number']);
        session('session_id',$loginRes['session_id']);
        session('brandclass_id',$loginRes['brandclass_id']);
        session('brandclass',$loginRes['brandclass']);
        session('shop_name',$loginRes['shop_name']);
        session('shop_code',$loginRes['shop_code']);
        session('belong_shop_name',$loginRes['belong_shop_name']);
        session('belong_shop_code',$loginRes['belong_shop_code']);
        session('is_sk',$loginRes['is_sk']);
        session('shop_type',$loginRes['shop_type']);
        session('setkey',$loginRes['setkey']);
        session('main_work_type',$loginRes['main_work_type']);
        session('work_type',$loginRes['work_type']);
        session('department_name',$loginRes['department_name']);
        session('department_id',$loginRes['department_id']);
        session('position_code',$loginRes['position_code']);
        session('main_position_name',$loginRes['main_position_name']);
        session('main_position_code',$loginRes['main_position_code']);
        session('grade_type',$loginRes['grade_type']);
        session('is_marketing',$loginRes['is_marketing']);//1:电商店；2：实体店；3：网销店
        session('is_belong',$loginRes['is_belong']);//判断是属于集团，品牌，店面下
        session('open_id', $loginRes['open_id']);
        session('valid_date', $loginRes['valid_date']);
        session('is_group', $loginRes['is_group']);//是不是集团店:1:是,2:否
        session('login_type', $loginType);//登录类型：PC或WX移动端
        session('telphone', $loginRes['telphone']);//员工手机
        session('productid', $loginRes['productid']);//mc的productid，区分客户

        //如果有小组,放到session
        $group_id = db('c_staff_group_relation')->where('staff_id',$loginRes['staff_id'])->value('group_id');
        if($group_id){
            $ginfo = db('c_staff_group')->where('id',$group_id)->field('id,group_name,create_staff_id,create_staff_name')->find();
            //如果是组长，提醒管理员
            $create_group = db('c_staff_group')->where("create_staff_id",$loginRes['staff_id'])->field('id,group_name,admin')->find();
            if($create_group){ //通知管理员
                $temp_staff = explode(',',$create_group['admin']);
                if($temp_staff){
                    foreach($temp_staff as $k=>$v){
                        if($v != $loginRes['staff_id']){
                            $temp_staff_info = getStaffInfoById($v);
                            $message['send_type']      = 1;
                            $message['send_title']     = '登录提醒';
                            $message['send_msg']       = $ginfo['group_name'].' 组长：'.$ginfo['create_staff_name'].' 于 '.date('Y-m-d H:i:s').' 登录系统';
                            $message['customer_id']    = 0;
                            $message['receive_id']     = $v;
                            $message['receive_name']   = $temp_staff_info['staff_name'];
                            $message['receive_status'] = 0;
                            $message['operation_type'] = 2;
                            $message['operation']      = '';
                            $message['time_out'] = 120;
                            // sendSystemMessage($message);

                            push_list('sendSystemMessage', $message);
                        }
                    }
                }
            }else{ //如果是员工，提醒组长；
                $message['send_type']      = 1;
                $message['send_title']     = '登录提醒';
                $message['send_msg']       = $ginfo['group_name'].' 组员：'.$loginRes['staffname'].' 于 '.date('Y-m-d H:i:s').' 登录系统';
                $message['customer_id']    = 0;
                $message['receive_id']     = $ginfo['create_staff_id'];
                $message['receive_name']   = $ginfo['create_staff_name'];
                $message['receive_status'] = 0;
                $message['operation_type'] = 2;
                $message['operation']      = '';
                $message['time_out'] = 120;
                // sendSystemMessage($message);

                push_list('sendSystemMessage', $message);
            }
            session('group_id',$ginfo['id']);
            session('group_name',$ginfo['group_name']);
            $loginRes['group_id'] = $ginfo['id'];
            $loginRes['group_name'] = $ginfo['group_name'];
        }

        //呼叫中心信息
        $call_id =  db_config('call_id');
        if($call_id){
            //检测用户坐席信息
            $callInfo = db('s_call_man')->where('staff_id',$loginRes['staff_id'])->find();
            $arr = [];
            $flag = false;
            if($loginRes['department_id'] != $callInfo['department_id']){
                $arr['department_id'] = $loginRes['department_id'];
                $arr['department_name'] = $loginRes['department_name'];
                $flag = true;
            }
            if(session('group_id') != $callInfo['group_id']){
                $arr['group_id'] = session('group_id');
                $arr['group_name'] = session('group_name');
                $flag = true;
            }
            if(session('staff_name') != $callInfo['staff_name']){
                $arr['staff_name'] = session('staff_name');
                $flag = true;
            }
            if($flag){
                db('s_call_man')->where('staff_id',$loginRes['staff_id'])->update($arr);
            }
            $call = db('SCallCenter')->where('id',$call_id)->find();
            session('ip',$call['ip']);
            session('port',$call['port']);
            session('user',$callInfo['user']);
            session('pwd',$callInfo['pwd']);
        }
        //判断是否设置多地登陆
        $more_login = db_config('more_login_'.session('staff_id'));
        if($more_login){
            $loginRes['more_login'] = 1;
        }
        //设定的登录状态
        $status = db_config('login_status_'.session('brandclass_id'));
        $status = $status ? $status : $loginRes['status'];
        $loginRes['status'] = $status;
        if($five){
            $loginRes['keep_login'] = 1;
            $info = json_encode($loginRes);
            cookie('session_id',$loginRes['session_id'],432000);
            cookie('staff_id',$loginRes['staff_id'],432000);
            cache('staffInfo_'.$loginRes['staff_id'],$info,432000);
            cookie('status',$status,432000);
        }else{
            $info = json_encode($loginRes);
            cookie('session_id',$loginRes['session_id']);
            cookie('staff_id',$loginRes['staff_id']);
            cache('staffInfo_'.$loginRes['staff_id'],$info);
            cookie('status',$status);
        }
        cookie('current_position_code',null);
        //操作session表
        $db = db('SSession');
        $staffInfo = $db->where(array('staff_id' => $loginRes['staff_id']))->find();
        $sql = "show columns from s_session like 'login_time'";
        $aa = db()->execute($sql);
        if($aa){
            $param['login_time'] = date('Y-m-d H:i:s',time());
        }

        //权限
        // session('crm_auth', getAuth($type='auth'));
        // $menu = include(APP_PATH.'menu.php');
        // $menuCustomize = include(APP_PATH.'menu_customize.php');
        // $auth = getAuthMenu($menu,'auth',$menuCustomize);
        
        // $menu = getAuthMenu($menu,'menu',$menuCustomize);
        // session('crm_menu', $menu);
        // $newAuth = controller('crm/Setting','lib')->arrayDuoZhuanEr($auth['list']);
        // session('crm_auth', $newAuth);

        db()->startTrans();
        try{
            if(!empty($staffInfo['staff_id'])){
                $param['session_id'] = $loginRes['session_id'];
                $param['ip'] = get_client_ip();
                $param['login_type'] = $loginType;
                $param['login_method'] = $loginMethod;
                $param['expiry'] = date('Y-m-d H:i:s',time()+86400);
                $param['status'] = $status;
                db('SSession')->where(array('staff_id' => $staffInfo['staff_id']))->update($param);
                $param['staff_id'] = $loginRes['staff_id'];
            }else {
                $param['staff_id'] = $loginRes['staff_id'];
                $param['session_id'] = $loginRes['session_id'];
                $param['ip'] = get_client_ip();
                $param['login_type'] = $loginType;
                $param['login_method'] = $loginMethod;
                $param['expiry'] = date('Y-m-d H:i:s', time() + 86400);
                $param['status'] = $status;
                db('SSession')->insert($param);
            }
            //天长专用，按登记时间分客资
           /* $rule = db('s_allocation_rule')->where('shop_code',$loginRes['shop_code'])->order('id desc')->find();
            $rule_staff = json_decode($rule['staff_value'],true);
            //判断当前登录人在不在规则里
            if(in_array($loginRes['staff_id'],array_column($rule_staff,'staff_id'))){
                $staff_value1 = $rule['staff_value1'] ? json_decode($rule['staff_value1'],true) : [];

                //如果登录人不在登录人员里，push里面
                if(!in_array($loginRes['staff_id'],array_column($staff_value1,'staff_id'))){
                    array_push($staff_value1,['staff_id'=>$loginRes['staff_id'],'staff_name'=>$loginRes['staffname']]);
                    $staff_value1 = json_encode($staff_value1);
                    db('s_allocation_rule')->where('id',$rule['id'])->update(['staff_value1'=>$staff_value1]);
                }
            }*/
            db()->commit();
            return true;
        }catch (\Exception $e){
            db()->rollBack();
            return false;
        }
    }

    function update_status($status){
        // 取出员工信息
        $info = cache('staffInfo_'.cookie('staff_id'));
        $param['status'] = $status;
        db()->startTrans();
        try{
            db('SSession')->where(array('staff_id' => session('staff_id')))->update($param);
            cookie('status',$status);
            db()->commit();
            // 赋值状态
            $info['status'] = $status;
            if($info['keep_login'] == 1){
                cache('staffInfo_'.cookie('staff_id'), json_encode($info),432000);
            }else{
                cache('staffInfo_'.cookie('staff_id'), json_encode($info));
            }
            cookie('status',$status);
            return true;
        }catch (\Exception $e){
            db()->rollback();
            return false;
        }
    }
    /*
     * 短消息
     * */
    public function message_list($type){
        $res = db('CMessage')->where('send_type',$type)->where('is_delete',0)->where('receive_id',session('staff_id'))->select();
        return $res;
    }
    /*
     * 通知
     * */
    public function notice_list(){
        return db('CMessage')->where('send_type',2)->where('is_delete',0)->where('receive_id',session('staff_id'))->select();
    }
    /*
     * 查看信息，通知
     */
    function update_message($id){
        $info = db('CMessage')->where('is_delete',0)->where('id',$id)->find();
        if($info && $info['read_status'] == 0){
            //修改状态，更新时间
            $data['read_status'] = 1;
            $data['read_time'] = date('Y-m-d H:i:s',time());
            db()->startTrans();
            $res = db('CMessage')->where('id',$id)->update($data);
            if($res === false){
                db()->rollBack();
                return false;
            }else{
                db()->commit();
                $info['read_status'] == 1;
                $info['read_time'] = $data['read_time'];
                return $info;
            }
        }else{
            return $info;
        }
    }
    function logOut($staffId){

        $res = db('s_session')->where('staff_id',$staffId)->find();
        if(!empty($res)){
            db('s_session')->where('staff_id',$staffId)->update(['logout_time'=>date('Y-m-d H:i:s')]);
            //退出日志
            db('l_login_log')->where('id',session('login_log_id'))->update(['login_out_time'=>date('Y-m-d H:i:s')]);
        }
        /*else{
            $param['staff_id'] = $staffId;
            $param['ip'] = get_client_ip();
            $param['login_type'] = 'pc';
            $param['login_method'] = 'user_name';
            $param['logout_time'] = date('Y-m-d H:i:s',time());
            $param['expiry'] = date('Y-m-d H:i:s',time()+86400);
            $param['status'] = 1;
            db('s_session')->insert($param);
        }*/
        cookie('session_id',null);
        cookie('auto_session_id',null);
        cookie('auto_staff_id',null);
        cookie('staff_id',null);
        cookie('status',null);
        cookie(null);
        session('openid',null);
        session('staff_id',null);
        session('auto_staff_id',null);
        session('status',null);
        session(null);
        //如果是多地登陆,只退出当前登录
        $more_login = db_config('more_login_'.session('staff_id'));
        if(!$more_login){
            $staffId = cookie('staff_id');
            cache('staffInfo_'.$staffId,null);
        }
        if(is_weixin()){
            $url = '59f424811d52f';
            sx_call($url,array('staff_id'=>$staffId));
            $this->redirect('crm/Index/wxLogin');
        }
    }

    function getStaffinfoByOpenId(){
        $url = '59fe8bd048e1d';
        return sx_call($url,cookie('openId'));
    }
    function getStaffOnlineStatus($staff_id){
        $info = cache('staffInfo_'.$staff_id);
        // echo 'noStaffId--|'.$staff_id.'|\r\n';
        if( (time() - $info['active'] > 160) || ($info['status'] != 1) ){
            // echo 'noT--|'.time().'|\r\n';
            // echo 'noA--|'.$info['active'].'|\r\n';
            // echo 'noS--|'.$info['status'].'|\r\n';
            return false;
        }else{
            // echo 'nor--|(zhen)|\r\n';
            return true;
        }
    }
    function wx_login($param){
        $url = '5a029ee140dba';
        //$param['open_id'] = cookie('openId');
        $res = sx_call($url,$param);//openid和员工对应，调登录接口
        if($res['code'] == 200){
            //绑定openid成功与否无所谓，大不了再输一次密码
            // sx_call('5a2239cf24883', ['staffname'=>$param['staffname'],'password'=>$param['password'],'open_id'=>$param['open_id']]);
            $this->setLoginEnv($res['data'], 'WX', 'user_name', 0);
            //登录日志
            $isTable = isTableExist('l_login_log');
            if($isTable) {
                $logId = db('l_login_log')->insertGetId(['staff_id' => session('staff_id'), 'staff_name' => session('staff_name'), 'last_login_time' => date('Y-m-d H:i:s', time()), 'last_login_ip' => get_client_ip(),'session_id'=>session('session_id')]);
                session('login_log_id', $logId);
            }
            $param['return_url'] = session('return_url')?session('return_url'):'';
            $arr = array(
                'code' => 200,
                'msg' =>'',
                'data' =>  $param
            );
        }else {
            if($res['code'] == 500){
                $arr = array('code'=>500,'error'=>101,'msg'=>'此员工已离职');
            }elseif($res['code'] == 403){
                $arr = array('code'=>100,'error'=>101,'msg'=>$res['msg']);
            }else{
                $arr = array('code'=>100,'error'=>101,'msg'=>$res['msg'],'data'=>$res);
            }
        }
        return $arr;
    }
    function update_pwd($params){
        $url = '59f44a14c3cae';
        return sx_call($url,$params);
    }

    function get_staff_info($staffId){
        /*$url = '59f933a395abe';
        return sx_call($url,$staffId);*/
        $mc = new \app\common\lib\mcInterface();
        return $mc->getOneStaff($staffId);
    }
    function get_group_info($staff_id){
        $group = db('c_staff_group_relation')->where('staff_id',$staff_id)->field('group_id')->find();
        $staffs = db('c_staff_group_relation a')
                ->join('c_staff_group_relation b','b.group_id = a.group_id','left')
                ->where('a.staff_id',$staff_id)
                ->field('b.staff_id,b.staff_name,b.group_id')
                ->select();
        /*
        $arr = array_column($staffIds,'staff_id');
        $ids = implode(',',$arr);
        $url = '5a18e3fa516a1';
        $res = sx_call($url,array('staff_id'=>$ids));
        if($res['code'] == 200){
            foreach($res['data'] as $k=>$v){
                $res['data'][$k]['status'] = $this->getStaffOnlineStatus($v['id']);
            }
        }*/

        return $staffs;
    }

    function get_sales_auth($info){
        // if(check_right('menu1512637269')){
        //     $res['sql']="add_shop_code = :add_shop_code OR shop_code =:belong_shop_code";
        //     $res['arr']['add_shop_code']=session('shop_code');
        //     $res['arr']['belong_shop_code']=session('belong_shop_code');
        // }else{
        //根据主岗位的工资类型确定查询条件
        if($info['main_work_type'] == 22 || check_right('menu1512637269')){//管理员
            $res['sql']="add_shop_code = :add_shop_code OR shop_code =:belong_shop_code";
            $res['arr']['add_shop_code']=session('shop_code');
            $res['arr']['belong_shop_code']=session('shop_code');
        }else{//默认显示
            $res['sql']="dj_staff_id = :dj_staff_id or sales_staff_id = :sales_staff_id or sk_staff_id = :sk_staff_id";
            $res['arr']['dj_staff_id']=$info['id'];
            $res['arr']['sales_staff_id']=$info['id'];
            $res['arr']['sk_staff_id']=$info['id'];
        }

        // }
        return $res;
    }

    //有效
    function valid_crm($info,$where){
        /*$t = new Target();
        if($where == 'month'){
            $where = 'this_month';
        }elseif($where == 'last_month'){
            $where = 'last_month';
        }elseif($where == 'week'){
            $where = 'this_week';
        }elseif($where == 'last_week'){
            $where = 'last_week';
        }else{
            $where = 'this_month';
        }
        $time = getdateArea($where);*/
        // $res = $t->newCustomerNum(array('start_day'=>$time[0],'end_day'=>$time[1],'staff_id'=>$staffId));
        // $res = db('c_day_number')->where(array('dj_staff_id'=>$staffId))->whereTime('creator_day',$where)->count('id');
        //$res = db('c_customerinfo')->where('is_fp',1)->where('sales_staff_id',$staffId)->where('jr_day','between',"$time[0],$time[1]")->where('is_status',1)->count('id');
        $res=$this->get_sales_auth($info);
        $res = db('c_customerinfo')->where($res['sql'],$res['arr'])->whereTime('yx_day',$where)->where('is_status',1)->where('is_valid',1)->count('id');
        return $res;
    }
    //毛客资
    function all_crm($info,$where){
        /* if($where == 'month'){
             $where = 'month';
         }elseif($where == 'last_month'){
             $where = 'last month';
         }elseif($where == 'week'){
             $where = 'week';
         }elseif($where == 'last_week'){
             $where = 'last week';
         }else{
             $where = 'last month';
         }*/
        // $time = getdateArea($where);

        //$res = db('CCustomerinfo')->where('sales_staff_id',$staffId)->whereTime('fp_day',$where)->where('is_status',1)->count();
        /*       if(check_right('menu1512637269')){
                   $sql="shop_code = :shop_code";
                   $arr['shop_code']=session('shop_code');
               }else{
                   $sql="sales_staff_id = :sales_staff_id or dj_staff_id = :dj_staff_id";
                   $arr['sales_staff_id']=$staffId;
                   $arr['dj_staff_id']=$staffId;
               }
        */
        $arr=$this->get_sales_auth($info);
        $res = db('CCustomerinfo')->where($arr['sql'],$arr['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //有效进店
    public function validJD($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where('is_intostore',1)->where('is_valid',1)->where($res['sql'],$res['arr'])->whereTime('syjd_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //无效新单
    public function invalidOrder($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where('is_success',1)->where('is_valid',3)->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //营收
    public function fact($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->sum('fact_money');
        return $res;
    }
    //流失
    public function loss($arr){
        if(check_right('menu1512637269')) {//查看所有客资权限
            $res = db('CCustomerinfo')-> where('add_shop_code|shop_code',$arr['shop_code'])->where('is_loss',1)->where('loss_day','between',[$arr['start_day'],$arr['end_day']])->where('c_from',1)->where('is_status',1)->count();
        }elseif(check_right('menu1531471639')) {//查看部门客资权限
            $res = db('CCustomerinfo')->where('loss_day','between',[$arr['start_day'],$arr['end_day']])->where('is_loss',1)->where('dj_department_id|sales_department_id', $arr['department_id'])-> where('add_shop_code|shop_code',$arr['shop_code'])->where('is_status',1)->where('c_from',1)->count();
        }else{
            $res = db('CCustomerinfo')->where('sales_staff_id','in',$arr['staff_id'])->whereTime('loss_day','between',[$arr['start_day'],$arr['end_day']])->where('c_from',1)->where('is_status',1)->where('is_loss',1)->count();
        }
        return $res;
    }
    //花费
    function cost($info,$where){
        $res = db('s_channel_cost')->where('shop_code',$info['shop_code'])->whereTime('cost_date',$where)->sum('cost');
        return $res;
    }
    //有效订单
    function order_crm($staffId,$where){
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where(array('is_success'=>1))->where($res['sql'],$res['arr'])->whereTime('order_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //订单
    public function sucOrder($info,$where){
        $res=$this->get_sales_auth($info);
        $res = db('CCustomerinfo')->where(array('is_success'=>1))->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //实际进店
    public function factIn($info,$where){
        $res=$this->get_sales_auth($info);
        $res = db('CCustomerinfo')->whereTime('syjd_day',$where)->where($res['sql'],$res['arr'])->where('is_status',1)->count();
        return $res;
    }
    //预约进店
    public function makeIn($info,$where){
        $res=$this->get_sales_auth($info);
        $res = db('CCustomerinfo')->whereTime('yjd_day',$where)->where($res['sql'],$res['arr'])->where('is_status',1)->count();
        return $res;
    }
    //待追踪
    function jdwd_crm($arr){
        if(check_right('menu1512637269')) {//查看所有客资权限
            $res = db('CCustomerinfo')->where(array('c_star_day'=>null,'is_fp'=>1))->where('is_intostore',1)->where('is_valid','in',[1,2])->where('jr_day','between',[$arr['start_day'],$arr['end_day']])->where('is_status',1)->where('c_from',1)->where('add_shop_code|shop_code',$arr['shop_code'])->where('is_loss',2)->count();
        }elseif(check_right('menu1531471639')) {//查看部门客资权限
            $res = db('CCustomerinfo')->where(array('c_star_day'=>null,'is_fp'=>1))->where('is_intostore',1)->where('is_valid','in',[1,2])->where('jr_day','between',[$arr['start_day'],$arr['end_day']])->where('is_loss',2)->where('dj_department_id|sales_department_id', $arr['department_id'])-> where('add_shop_code|shop_code',$arr['shop_code'])->where('is_status',1)->where('c_from',1)->count();
        }else{
            $res = db('CCustomerinfo')->where(array('c_star_day'=>null,'is_fp'=>1))->where('is_intostore',1)->where('is_valid','in',[1,2])->where('dj_staff_id|sk_staff_id|sales_staff_id','in',$arr['staff_id'])->where('jr_day','between',[$arr['start_day'],$arr['end_day']])->where('is_status',1)->where('c_from',1)->where('add_shop_code|shop_code',$arr['shop_code'])->where('is_loss',2)->count();
        }

        return $res;
    }
    //A客资
    function cus_a($staffId,$where,$shop_code){

        $res = db('CCustomerinfo')->where('sign_name', 'like','A%')->where('dj_staff_id','in',$staffId)->whereTime('sign_time',$where)->where('is_status',1)->where('c_from',1)->where('add_shop_code|shop_code',$shop_code)->where('is_loss',2)->count();
        return $res;
    }
    //待分配
    function fp_crm($staffId,$where){
        //$res = db('CCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_fp'=>2))->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where(array('is_fp'=>2))->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //获取到电话的客资数量
    public function getTelCount($data){
        if(check_right('menu1512637269')) {//查看所有客资权限
            $res = db('CCustomerinfo')->where('customer_tel|mate_tel','<>','')->where('yx_day','between',[$data['start_day'],$data['end_day']])->where('is_valid',1)->where('add_shop_code|shop_code',$data['shop_code'])->where('is_status',1)->where('c_from',1)->count();
        }elseif(check_right('menu1531471639')) {//查看部门客资权限
            $res = db('CCustomerinfo')->where('customer_tel|mate_tel','<>','')->where('yx_day','between',[$data['start_day'],$data['end_day']])->where('is_valid',1)->where('dj_department_id|sales_department_id', $data['department_id'])->where('add_shop_code|shop_code',$data['shop_code'])->where('is_status',1)->where('c_from',1)->count();
        }else{
            $res = db('CCustomerinfo')->where('customer_tel|mate_tel','<>','')->where('tel_staff_id','in',$data['staff_id'])->where('yx_day','between',[$data['start_day'],$data['end_day']])->where('is_valid',1)->where('add_shop_code|shop_code',$data['shop_code'])->where('is_status',1)->where('c_from',1)->count();
        }
        return $res;
    }
    //获取到微信QQ的客资数量
    public function getQQCount($data){
        if(check_right('menu1512637269')) {//查看所有客资权限
            $res = db('CCustomerinfo')->where('customer_qq|customer_wechat','<>','')->where('dj_day','between',[$data['start_day'],$data['end_day']])-> where('add_shop_code|shop_code',$data['shop_code'])->where('is_status',1)->where('c_from',1)->count();
        }elseif(check_right('menu1531471639')) {//查看部门客资权限
            $res = db('CCustomerinfo')->where('customer_qq|customer_wechat','<>','')->where('dj_day','between',[$data['start_day'],$data['end_day']])->where('dj_department_id|sales_department_id', $data['department_id'])-> where('add_shop_code|shop_code',$data['shop_code'])->where('is_status',1)->where('c_from',1)->count();
        }else{
            $res = db('CCustomerinfo')->where('customer_qq|customer_wechat','<>','')->where('qq_staff_id|wechat_staff_id','in',$data['staff_id'])->where('dj_day','between',[$data['start_day'],$data['end_day']])-> where('add_shop_code|shop_code',$data['shop_code'])->where('is_status',1)->where('c_from',1)->count();
        }

        return $res;
    }
    //追踪中
    function staff_id_crm($arr){
        if(check_right('menu1512637269')) {//查看所有客资权限
            $res = db('CCustomerinfo')->where(array('is_valid'=>1,'is_fp'=>1))-> where('add_shop_code|shop_code',$arr['shop_code'])->where('c_star_day','not null')->where('c_star_day','between',[$arr['start_day'],$arr['end_day']])->where('is_status',1)->count();
        }else{
            $res = db('CCustomerinfo')->where(array('is_valid'=>1,'is_fp'=>1))->where('dj_staff_id|sales_staff_id|sk_staff_id','in',$arr['staff_id'])->where('c_star_day','not null')->where('c_star_day','between',[$arr['start_day'],$arr['end_day']])->where('is_status',1)->count();
        }
        return $res;

    }
    //已预约
    function yuyue_crm($staffId,$where){
        //$res = db('CCustomerinfo')->where(array('sales_staff_id'=>$staffId))->where('yjd_day','<>','')->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where($res['sql'],$res['arr'])->where('yjd_day','<>','')->whereTime('creator_day',$where)->where('is_status',1)->count();
        // $res = db('c_day_number')->where(array('staff_id'=>$staffId))->whereTime('addtime',$where)->sum('yjd');
        return $res;
    }
    //进店未定
    function jdwd1_crm($staffId,$where){//进客+非进客-成单数
        // $res1 = db('c_day_number')->where(array('staff_id'=>$staffId))->whereTime('addtime',$where)->sum('syjd_jk');
        // $res2 = db('c_day_number')->where(array('staff_id'=>$staffId))->whereTime('addtime',$where)->sum('syjd_no_jk');
        // $res3 = db('c_day_number')->where(array('staff_id'=>$staffId))->whereTime('addtime',$where)->sum('orders');
        //$res = db('CCustomerinfo')->where(array('sales_staff_id'=>$staffId,'is_intostore'=>1,'is_success'=>2))->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where(array('is_intostore'=>1,'is_success'=>2))->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //进店(邀约)
    function jd_crm($info,$where){
        //$res = db('CCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_intostore'=>1))->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where('is_intostore','in','2,3')->where($res['sql'],$res['arr'])->whereTime('syjd_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //订单消费总额
    function xiaofei_amount($shop_code,$where){
        $res = db('c_customerinfo')->where('shop_code',$shop_code)->whereTime('creator_day',$where)->where('is_status',1)->sum('totalpay_money');
        return $res;
    }
    //实收总额
    function shishou_amount($shop_code,$where){
        /* $t = new Target();
         if($where == 'month'){
             $where = 'this_month';
         }elseif($where == 'last_month'){
             $where = 'last_month';
         }elseif($where == 'week'){
             $where = 'this_week';
         }elseif($where == 'last_week'){
             $where = 'last_week';
         }else{
             $where = 'this_month';
         }
         $time = getdateArea($where);*/
        // $res = $t->dealAmount(array('start_day'=>$time[0],'end_day'=>$time[1],'staff_id'=>$staffId,'staff_type'=>'sales_staff_id'));
        $res = db('c_customer_order')->where('shop_code',$shop_code)->whereTime('create_time',$where)->field('SUM(order_amount)')->find();
        return $res;
    }
    //沟通阶段和条数
    function get_seles_count($staff_id,$where){
        $r=$this->get_sales_auth($staff_id);
        $res = db('s_sales_routines')->where('shop_code',session('shop_code'))->order('id asc')->select();
        foreach($res as $k=>$v){
            $res[$k]['count'] = db('CCustomerinfo')
                ->where($r['sql'],$r['arr'])->whereTime('c_end_day',$where)->where('is_status',1)->where('seles_step',$v['step_stage'])
                ->count('id');
        }
        return $res;
    }
    //沟通总条数
    function get_total_count($staff_id,$times){
        $res=$this->get_sales_auth($staff_id);
        $count = db('CCustomerinfo')
            ->whereTime('c_end_day',$times)
            ->where('is_status',1)
            // ->where('sales_staff_id = :sales_staff_id and is_fp = :is_fp',['sales_staff_id'=>$staff_id,'is_fp'=>1])
            ->where($res['sql'],$res['arr'])
            // ->whereOr('dj_staff_id = :dj_staff_id',['dj_staff_id'=>$staff_id])
            ->count('id');
        return $count;
    }
    //无效
    function null_crm($staffId,$where){
        // $res = db('c_day_number')->where(array('staff_id'=>$staffId))->whereTime('addtime',$where)->sum('no_valid_customer');
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where('is_valid',3)->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count('id');
        return $res;
    }

    //沟通进度
    function get_seles_step(){
        $res = db('s_sales_routines')->where(array('shop_code'=>session('shop_code')))->select();
        return $res;
    }
    //追踪失败原因
    function get_reason(){
        return db('s_file_reason')->where('shop_code',session('shop_code'))->select();
    }

    function getCustomerList($param,$times='',$seles_step = 0){
        $data['page'] = $param['page'] ? $param['page'] : 1;
        if($times == 'month'){
            $times = 'month';
        }elseif($times == 'last_month'){
            $times = 'last month';
        }elseif($times == 'week'){
            $times = 'week';
        }elseif($times == 'last_week'){
            $times = 'last week';
        }elseif($times == 'today'){
            $times = 'today';
        }else{
            $times =  'today';
        }
        $arr=$this->get_sales_auth($param);
        if(!$seles_step){
            // $redis = connectRedis();
            // $data = $redis->get('getCustomerList_'.$param['staff_id']);
            // if(!$data){
            $data['total'] = ceil($data['records']/10) ? ceil($data['records']/10) : 1;
            $res = db('CCustomerinfo')//->fetchSql(true)
            // ->where('is_status',1)
            // ->whereTime('fp_day',$times)
            // ->where('sales_staff_id = :sales_staff_id and is_fp = :is_fp and is_success <>:is_success ',['sales_staff_id'=>$param['staff_id'],'is_fp'=>1,'is_success'=>1])
            // ->whereOr('dj_staff_id = :dj_staff_id and is_status = :is_status',['dj_staff_id'=>$param['staff_id'],'is_status'=>1])
            ->where($arr['sql'],$arr['arr'])->whereTime('c_end_day',$times)->where('is_status',1)
                ->field('customer_number,customer_name,is_intostore,is_success,is_valid,customer_sex,customer_tel,customer_wechat,seles_step,step_name,customer_type,consultation_type,consulation_shop,customer_channel,customer_cource,customer_intention,customer_orderaddress,access_model,customer_area,customer_region')->order('id desc')->select();
            // echo $res;die;
            // echo db()->getLastSql();die;

            $data['records'] = db('CCustomerinfo')
                // ->where('is_status',1)
                // ->whereTime('fp_day',$times)
                // ->where('sales_staff_id = :sales_staff_id and is_fp = :is_fp and is_success <>:is_success ',['sales_staff_id'=>$param['staff_id'],'is_fp'=>1,'is_success'=>1])
                // ->whereOr('dj_staff_id = :dj_staff_id and is_status = :is_status',['dj_staff_id'=>$param['staff_id'],'is_status'=>1])
                ->where($arr['sql'],$arr['arr'])->whereTime('c_end_day',$times)->where('is_status',1)
                ->count();
            foreach($res as $k=>$v){
                //通过common的获取器获取其内容
                $v['is_intostore'] = getIsIntostore($v['is_intostore']);
                $v['is_success'] = getIsSuccess($v['is_success']);
                $v['is_valid'] = getIsValidAttr($v['is_valid']);

                $v['customer_type'] = $v['customer_type'] == 1 ? '新客资' : '转介绍';
                if(!check_right('menu1512998373')){
                    $v['customer_tel'] = !empty($v['customer_tel']) ? substr($v['customer_tel'], 0, 3).'****'.substr($v['customer_tel'], 7) : '';
                }
                $data['rows'][$k]['cell'] = array_values($v);
            }
            //     foreach($res2 as $k=>$v){
            //         $data['rows'][$k]['id'] = array_values($v);
            //     }
            //     $redis->set('getCustomerList_'.$param['staff_id'],json_encode($data));
            // }else{
            //     $data = json_decode($data,true);
            // }
        }else{
            $data['total'] = ceil($data['records']/10) ? ceil($data['records']/10) : 1;
            $res = db('CCustomerinfo')
                // ->where('is_status',1)
                // ->whereTime('fp_day',$times)
                // ->where('seles_step',$seles_step)
                // ->where('sales_staff_id = :sales_staff_id and is_fp = :is_fp and is_success <>:is_success ',['sales_staff_id'=>$param['staff_id'],'is_fp'=>1,'is_success'=>1])
                // ->whereOr('dj_staff_id = :dj_staff_id and seles_step = :seles_step1 and is_status =:is_status',['dj_staff_id'=>$param['staff_id'],'seles_step1'=>$seles_step,'is_status'=>1])
                ->where($arr['sql'],$arr['arr'])->whereTime('c_end_day',$times)->where('is_status',1)->where('seles_step',$seles_step)
                ->field('customer_number,customer_name,is_intostore,is_success,is_valid,customer_sex,customer_tel,customer_wechat,seles_step,step_name,customer_type,consultation_type,consulation_shop,customer_channel,customer_cource,customer_intention,customer_orderaddress,access_model,customer_area,customer_region')->order('id desc')
                ->select();
            $data['records'] = db('CCustomerinfo')
                // ->where('is_status',1)
                // ->whereTime('fp_day',$times)
                // ->where('seles_step',$seles_step)
                // ->where('sales_staff_id = :sales_staff_id and is_fp = :is_fp and is_success <>:is_success ',['sales_staff_id'=>$param['staff_id'],'is_fp'=>1,'is_success'=>1])
                // ->whereOr('dj_staff_id = :dj_staff_id and seles_step = :seles_step1 and is_status =:is_status',['dj_staff_id'=>$param['staff_id'],'seles_step1'=>$seles_step,'is_status'=>1])
                ->where($arr['sql'],$arr['arr'])->whereTime('c_end_day',$times)->where('is_status',1)->where('seles_step',$seles_step)
                ->count();

            foreach($res as $k=>$v){
                //通过common的获取器获取其内容
                $v['is_intostore'] = getIsIntostore($v['is_intostore']);
                $v['is_success'] = getIsSuccess($v['is_success']);
                $v['is_valid'] = getIsValidAttr($v['is_valid']);

                $v['customer_type'] = $v['customer_type'] == 1 ? '新客资' : '转介绍';
                if(!check_right('menu1512998373')){
                    $v['customer_tel'] = !empty($v['customer_tel']) ? substr($v['customer_tel'], 0, 3).'****'.substr($v['customer_tel'], 7) : '';
                }
                $data['rows'][$k]['cell'] = array_values($v);
            }
            // foreach($res2 as $k=>$v){
            //     $data['rows'][$k]['id'] = array_values($v);
            // }
        }
        return $data;
    }
    //五维图
    function getHomeTu($staffId,$times){
        $info = getStaffInfoById($staffId);
        $info['data'] = [
            'id' => $info['staff_id'],
            'staffname' => $info['staffname'],
            'shop_code' => $info['shop_code'],
            'main_position_code' => $info['main_position_code'],
        ];

        if(check_right('menu1512637269')) {//查看所有客资权限
            $staff_id =  controller('crm/Customer','lib')->get_staff_lists(['shop_code'=>$info['data']['shop_code']]);
            $staff_id = array_column($staff_id,'id');
            $staffId = implode(',',$staff_id);
        }elseif(check_right('menu1531471639')){//查看部门客资权限
            $staff_id = controller('crm/Customer')->getDepartmentStaffs(session('department_id'));
            $staff_id = array_column($staff_id,'id');
            $staffId = implode(',',$staff_id);
        }elseif(check_right('menu1529653231')) {//查看小组客资权限
            $staff_id = getGroupStaffByStaffId($staffId);
            $staff_id = array_column($staff_id,'staff_id');
            $staffId = implode(',',$staff_id);
        }
        $day = getdateArea($times);
        $param = array(
            'start_day' => $day[0],
            'end_day' => $day[1],
            'department_id'  => $info['department_id'],
            'shop_code'=> $info['data']['shop_code'],
            'staff_id' => $staffId,
        );

        if($times != 'last_month'){
            $time = 'month';
        }else{
            $time = $times;
        }
        //获取当前主岗位的五维图
        $wwt = db('SStaffAbility')->where('shop_code',$info['shop_code'])->where('position_name',$info['main_position_name'])->where('times',$time)->find();
        $param['staff_id'] = $staffId;
        $arr = explode(',', $wwt['abilityItem']);
        $max = explode(',', $wwt['max']);
        $wwt['abilityItem'] = $arr;
        $arr1 = array();
        $arr2 = array();
        $t = new Target();
        $obj = new Target();
        $methodList = $obj->getAllTarget();
        $res = [];
        foreach ($arr as $ke => $va) {
            $a = $t->get_target_name_by_id($va);
            $arr1[] = "{name: '" . $a . "', max: ".$max[$ke]."}";
            if(key_exists($va, $methodList)){
                $targetMethod = $methodList[$va]['method'];
                $res[$ke] = $obj->$targetMethod($param);
                if(strpos($targetMethod,'Rate') !== false){
                    $res[$ke] = sprintf('%.2f',$res[$ke]*100);
                }elseif(strpos($targetMethod,'Cost') !== false || in_array($targetMethod,['dealAmount','oneFact','oneAVG'])){
                    $res[$ke] = sprintf('%.2f',$res[$ke]);
                }
            }
            $val =  $res[$ke];
            if($val > $max[$ke]){
                $val = $max[$ke];
            }
            $arr2[] = $val;
        }
        if(empty($wwt['id'])){
            // $res = array('a'=> "[{ name: '成交量', max: 50},{ name: '进客量', max: 60},{ name: '有效量', max: 60},{ name: '电访量', max: 80},{ name: '客资量', max: 50},]",'b'=>"[0,0,0,0,0]",'c'=>$wwt['positioni_name']);
        }else{
            $res = array('a'=> "[".implode(',',$arr1)."]",'b'=>"[".implode(',',$arr2)."]",'c'=>$wwt['position_name']);
        }

        // var_dump(empty($res));
        return $res;
    }
    //目标
    function get_aim($shop){
        $month = date('Y-m',time());
        // echo db()->getLastSql();die;
        //人员权限
        if(check_right('menu1512637269')){//查看所有客资权限
            $res = db('SKpiStaffgoal')
                ->where(array('shop_code' => $shop['info']['shop_code'], 'month' => $month))
                ->where('department_id', 0)
                ->where('group_id',0)
                ->where('staff_id',0)
                ->where('position_code','')
                ->field('kpi_id,kpi_name,kpi_value,kpi_unit,channel_id,province_id,city_id,avg_value')
                ->order('order_sort asc')
                ->select();
            $temp = [];
            foreach($res as $key=>$val){
                $temp[$val['kpi_id']] = [
                    'kpi_id'=> $val['kpi_id'],
                    'kpi_name'=> $val['kpi_name'],
                    'kpi_value'=> $val['kpi_value']+$temp[$val['kpi_id']]['kpi_value'],
                    'kpi_unit'=> $val['kpi_unit'],
                    'channel_id'=> $val['channel_id'],
                    'province_id'=> $val['province_id'],
                    'city_id'=> $val['city_id'],
                    'avg_value'=> $val['avg_value'],
                ];
            }
            $res = array_values($temp);
            $staff_id = $this->get_staff_lists(['shop_code'=>$shop['info']['shop_code']]);
            $staff_id = array_column($staff_id,'id');
            $staff_id = implode(',',$staff_id);
        }elseif(check_right('menu1531471639')){//查看部门客资权限
            $res = db('SKpiStaffgoal')
                ->where(array('shop_code' => $shop['info']['shop_code'], 'month' => $month))
                ->where('department_id', session('department_id'))
                ->where('group_id',0)
                ->where('staff_id',0)
                ->field('kpi_id,kpi_name,kpi_value,kpi_unit,channel_id,province_id,city_id,avg_value')
                ->limit(5)
                ->order('order_sort asc')->select();
            $temp = [];
            foreach($res as $key=>$val){
                $temp[$val['kpi_id']] = [
                    'kpi_id'=> $val['kpi_id'],
                    'kpi_name'=> $val['kpi_name'],
                    'kpi_value'=> $val['kpi_value']+$temp[$val['kpi_id']]['kpi_value'],
                    'kpi_unit'=> $val['kpi_unit'],
                    'channel_id'=> $val['channel_id'],
                    'province_id'=> $val['province_id'],
                    'city_id'=> $val['city_id'],
                    'avg_value'=> $val['avg_value'],
                ];
            }
            $res = array_values($temp);
            $staff_id = controller('crm/Customer')->getDepartmentStaffs(session('department_id'));
            $staff_id = array_column($staff_id,'id');
            $staff_id = implode(',',$staff_id);
        }elseif(check_right('menu1529653231')){//查看小组客资权限
            $res = db('SKpiStaffgoal')
                ->where(array('shop_code'=>$shop['info']['shop_code'],'month'=>$month))
                ->where('group_id',session('group_id'))
                ->where('staff_id',0)
                ->where('position_code','')
                ->field('kpi_id,kpi_name,kpi_value,kpi_unit,channel_id,province_id,city_id,avg_value')
                ->limit(5)
                ->order('order_sort asc')
                ->select();
            $temp = [];
            foreach($res as $key=>$val){
                $temp[$val['kpi_id']] = [
                    'kpi_id'=> $val['kpi_id'],
                    'kpi_name'=> $val['kpi_name'],
                    'kpi_value'=> $val['kpi_value']+$temp[$val['kpi_id']]['kpi_value'],
                    'kpi_unit'=> $val['kpi_unit'],
                    'channel_id'=> $val['channel_id'],
                    'province_id'=> $val['province_id'],
                    'city_id'=> $val['city_id'],
                    'avg_value'=> $val['avg_value'],
                ];
            }
            $res = array_values($temp);
            $staff_id = getGroupStaffByStaffId($shop['staff_id']);
            $staff_id = array_column($staff_id,'staff_id');
            $staff_id = implode(',',$staff_id);
        }else{//个人权限
            //根据人员查目标
            $res = db('SKpiStaffgoal')
                ->where(array('shop_code'=>$shop['info']['shop_code'],'month'=>$month))
                ->where('staff_id',$shop['staff_id'])->field('kpi_id,kpi_name,kpi_value,kpi_unit,channel_id,province_id,city_id,avg_value')
                ->limit(5)
                ->order('order_sort asc')
                ->select();
            $temp = [];
            if (empty($res)) {
                $res = db('SKpiStaffgoal')
                    ->where(array('shop_code'=>$shop['info']['shop_code'],'month'=>$month))
                    ->where('staff_id',0)
                    ->where('position_code',$shop['position_code'])
                    ->field('kpi_id,kpi_name,kpi_value,kpi_unit,channel_id,province_id,city_id,avg_value')
                    ->limit(5)
                    ->order('order_sort asc')
                    ->select();
            }
            // echo db()->getLastSql();exit;
            foreach($res as $key=>$val){
                $temp[$val['kpi_id']] = [
                    'kpi_id'=> $val['kpi_id'],
                    'kpi_name'=> $val['kpi_name'],
                    'kpi_value'=> $val['kpi_value']+$temp[$val['kpi_id']]['kpi_value'],
                    'kpi_unit'=> $val['kpi_unit'],
                    'channel_id'=> $val['channel_id'],
                    'province_id'=> $val['province_id'],
                    'city_id'=> $val['city_id'],
                    'avg_value'=> $val['avg_value'],
                ];
            }
            $res = array_values($temp);
            $staff_id = $shop['staff_id'];
        }

        $staff_id = trim($staff_id,',');
        $time = getdateArea($month);

        foreach($res as $ke=>$va){
            $res[$ke]['kpi'] = $va['kpi_value'];
            if($va['kpi_id'] == 'newCustomerNum'){
                //毛客资
                $reach = db('c_customerinfo')
                    ->where('dj_day', 'between time',[$time[0], $time[1]])
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('add_shop_code', $shop['info']['shop_code'])
                    ->where('dj_staff_id','in', $staff_id)
                    ->count();
                $res[$ke]['reach'] = sprintf('%.2f',$reach/$res[$ke]['kpi_value']*100);
            }elseif($va['kpi_id'] == 'validCustomerNumber'){
                //有效客资
                $reach = db('c_customerinfo')
                    ->where('yx_day', 'between time',[$time[0], $time[1]])
                    ->where('is_valid',1)
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('add_shop_code', $shop['info']['shop_code'])
                    ->where('dj_staff_id','in', $staff_id)
                    ->count();
                $res[$ke]['reach'] = sprintf('%.2f',$reach/$res[$ke]['kpi_value']*100);
            }elseif($va['kpi_id'] == 'valueCustomerRate'){
                //客资有效率
                $valid = db('c_customerinfo')
                    ->where('yx_day', 'between time',[$time[0], $time[1]])
                    ->where('is_valid',1)
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('add_shop_code', $shop['info']['shop_code'])
                    ->where('dj_staff_id','in', $staff_id)
                    ->count();
                $all =   $reach = db('c_customerinfo')
                    ->where('dj_day', 'between time',[$time[0], $time[1]])
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('add_shop_code', $shop['info']['shop_code'])
                    ->where('dj_staff_id','in', $staff_id)
                    ->count();
                $res[$ke]['reach'] = sprintf('%.2f',$valid/$all*100);
            }elseif($va['kpi_id'] == 'inviteIntoCustomerNumber'){
                //邀约进店客资量
                $reach = db('c_customerinfo')
                    ->where('yjd_day', 'between time',[$time[0], $time[1]])
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('shop_code', $shop['info']['shop_code'])
                    ->where('sales_staff_id','in', $staff_id)
                    ->count();
                $res[$ke]['reach'] = sprintf('%.2f',$reach/$res[$ke]['kpi_value']*100);
            }elseif($va['kpi_id'] == 'actualIntoCustomerNumber'){
                //实际进店
                $reach = db('c_customerinfo')
                    ->where('syjd_day', 'between time',[$time[0], $time[1]])
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('is_intostore','between',['2', '3'])
                    ->where('shop_code', $shop['info']['shop_code'])
                    ->where('sales_staff_id','in', $staff_id)
                    ->count();
                $res[$ke]['reach'] = sprintf('%.2f',$reach/$res[$ke]['kpi_value']*100);
            }elseif($va['kpi_id'] == 'intoValueRate'){
                //进店转换率
                //实际进店
                $syjd = db('c_customerinfo')
                    ->where('syjd_day', 'between time',[$time[0], $time[1]])
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('is_intostore','between',['2', '3'])
                    ->where('shop_code', $shop['info']['shop_code'])
                    ->where('sales_staff_id','in', $staff_id)
                    ->count();
                //邀约进店客资量
                $yjd = db('c_customerinfo')
                    ->where('yjd_day', 'between time',[$time[0], $time[1]])
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('shop_code', $shop['info']['shop_code'])
                    ->where('sales_staff_id','in', $staff_id)
                    ->count();
                $res[$ke]['reach'] = sprintf('%.2f',$syjd/$yjd*100);
            }elseif($va['kpi_id'] == 'orderNumber'){
                //新单量
                $reach = db('c_customerinfo')
                    ->where('order_start_time', 'between time', [$time[0], $time[1]])
                    ->where('is_status', 1)
                    ->where('is_success', 1)
                    ->where('c_from', 1)
                    ->where('shop_code', $shop['info']['shop_code'])
                    ->where('sales_staff_id','in', $staff_id)
                    ->count();
                $res[$ke]['reach'] = sprintf('%.2f',$reach/$res[$ke]['kpi_value']*100);
            }elseif($va['kpi_id'] == 'aCustomerNum'){
                //A客转换率
                $aCus = db('c_customerinfo')
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('sign_time', 'between time', [$time[0], $time[1]])
                    ->where('sign_name', 'like', '%A%')
                    ->where('sales_staff_id','in', $staff_id)
                    ->where('shop_code', $shop['info']['shop_code'])
                    ->count('id');

                $value = db('c_customerinfo')
                    ->where('yx_day','between time', [$time[0], $time[1]])
                    ->where('is_valid',1)
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('sales_staff_id','in', $staff_id)
                    ->where('shop_code', $shop['info']['shop_code'])
                    ->count('id');
                $res[$ke]['reach'] = sprintf('%.2f',$aCus/$value*100);
            }elseif($va['kpi_id'] == 'bCustomerNum'){
                //b客转换率
                $bCus = db('c_customerinfo')
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('sign_time', 'between time', [$time[0], $time[1]])
                    ->where('sign_name', 'like', '%B%')
                    ->where('sales_staff_id','in', $staff_id)
                    ->where('shop_code', $shop['info']['shop_code'])
                    ->count('id');

                $value = db('c_customerinfo')
                    ->where('yx_day', 'between time', [$time[0], $time[1]])
                    ->where('is_valid',1)
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('sales_staff_id','in', $staff_id)
                    ->where('shop_code',  $shop['info']['shop_code'])
                    ->count('id');
                $res[$ke]['reach'] = sprintf('%.2f',$bCus/$value*100);
            }elseif($va['kpi_id'] == 'cCustomerNum'){
                //c客转换率
                $cCus = db('c_customerinfo')
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('sign_time', 'between time', [$time[0], $time[1]])
                    ->where('sign_name', 'like', '%C%')
                    ->where('sales_staff_id','in', $staff_id)
                    ->where('shop_code', $shop['info']['shop_code'])
                    ->count('id');

                $value = db('c_customerinfo')
                    ->where('yx_day', 'between time',[$time[0], $time[1]])
                    ->where('is_valid',1)
                    ->where('is_status', 1)
                    ->where('c_from', 1)
                    ->where('sales_staff_id','in', $staff_id)
                    ->where('shop_code',  $shop['info']['shop_code'])
                    ->count('id');
                $res[$ke]['reach'] = sprintf('%.2f',$cCus/$value*100);
            }elseif($va['kpi_id'] == 'oneFact'){
                //一销实收
                $reach = db('c_customerinfo')->alias('c')
                    ->join('c_customer_order o','c.id=o.customer_id','left')
                    ->join('c_order_detail d','o.order_sn=d.order_sn','left')
                    ->where('c.sales_staff_id','in',$staff_id)
                    ->where('d.pay_type',1)
                    ->where('c.shop_code',$shop['info']['shop_code'])
                    ->where('d.pay_time','between',[$time[0], $time[1]])
                    ->sum('d.order_fact');
                $res[$ke]['reach'] = round($reach/$res[$ke]['kpi_value'],2)*100;
            }elseif($va['kpi_id'] == 'totalFact'){
                //总实收
                $reach = db('c_customerinfo')
                    ->where('sales_staff_id','in',$staff_id)
                    ->where('shop_code',$shop['info']['shop_code'])
                    ->where('order_start_time','between',[$time[0], $time[1]])
                    ->sum('fact_money');
                $res[$ke]['reach'] = sprintf('%.2f',$reach/$res[$ke]['kpi_value']*100);
            }elseif($va['kpi_id'] == 'oneAVG'){
                //一销均价
                $total = db('c_customerinfo')
                    ->where('sales_staff_id','in',$staff_id)
                    ->where('sales_staff_id','in',$staff_id)
                    ->where('shop_code',$shop['info']['shop_code'])
                    ->where('order_start_time','between',[$time[0], $time[1]])
                    ->sum('totalpay_money');
                $order = db('c_customerinfo')
                    ->where('order_start_time', 'between time', [$time[0], $time[1]])
                    ->where('is_status', 1)
                    ->where('is_success', 1)
                    ->where('c_from', 1)
                    ->where('shop_code', $shop['info']['shop_code'])
                    ->where('sales_staff_id','in', $staff_id)
                    ->count();
                $res[$ke]['reach'] = sprintf('%.2f',$total/$order/$res[$ke]['kpi_value']*100);
            }
        }
        return $res;
    }
    //实际收款
    function get_amount($staffId,$where){
        $res = db('CCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_intostore'=>1,'is_success'=>1,'Is_valid'=>1))->field('SUM(totalpay_money)')->find();
        action_log($staffId,'',$staffId['staff_id']);
        return $res['sum'];
    }

    //客户来源
    function source($data=''){
        $source = cache('source');
        if(empty($source)){
            $url="59fd5ec462c88";
            $res=sx_call($url,$data);
            if($res['code']==200){
                $source=$res['data'];
                cache('source',$source);
            }
        }
        return $source;
    }

    //来源渠道
    public function channel($data){
       // $detail = session('channel');
       // if(empty($detail)){
        $url="59fd5e729e5a8";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $detail=$res['data'];
                // session('channel',$detail);
        }
        // }

        return $detail;
    }

    //获取方式
    function accessModel($data)
    {
        $detail = cache('accessModel');
        if(empty($detail)){


            $mc = new \app\common\lib\mcInterface();


            $data = $mc->cacheData('59fd5f0792e10',$data);
            if($data !== false){
                $detail = $data;
                cache('accessModel', $detail);
            }else{
                $detail = [];
            }

            // $url = "59fd5f0792e10";
            // $res = sx_call($url, $data);
            // if ($res['code'] == 200) {
            //     $detail = $res['data'];
            //     cache('accessModel', $detail);
            // }
        }
        return $detail;
    }

    //客户意向
    function intention($data)
    {
        $detail = cache('intention');
        if(empty($detail)){
            $url = "59fd5f6c1d340";
            $res = sx_call($url, $data);
            if ($res['code'] == 200) {
                $detail = $res['data'];
                cache('intention', $detail);
            }
        }
        return $detail;
    }

    //2021-06-21 优化 搜索 店 下面 部门
    function getDList($param)
    {
        //部门 
        $shop_code = $param['shop_code'] ? $param['shop_code'] : session('shop_code');

        $mc = new \app\common\lib\mcInterface();
        $departmentList = $mc->getDepartment(['shop_code'=>$shop_code]);
        return $departmentList;
    }

    //客资地域
    function region($data)
    {
        // $detail = session('region');
        // if(empty($detail)){
        $url = "59fd5fa926b98";
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $detail = $res['data'];
            // session('region', $detail);
        }
        // }
        return $detail;
    }

    //客户分区
    function areaSet($data)
    {
        $detail = cache('areaSet');
        if(empty($detail)){
        $url = "5a004e9c3e030";
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $detail = $res['data'];
            cache('areaSet', $detail);
        }
    }
        return $detail;
    }
    //客资标记
    function markSet($data){
        /*$url="5a0c42f43e986";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $detail=$res['data'];
        }*/
        // //标记取前端的不是MC的
        // $detail = db('s_markset')->where('shop_code',session('shop_code'))->select();
        $detail = cache('markset_'.session('shop_code'));
        if(empty($detail)){
            $detail = db('s_markset')->where('shop_code',session('shop_code'))->select();
            cache('markset_'.session('shop_code'),$detail,60*60*2);
        }
        return $detail;
    }
    //消费能力
    function capacity($data)
    {
        $detail = cache('capacity');
        if(empty($detail)){
            $url = "5a0c43da3e99a";
            $res = sx_call($url, $data);
            if ($res['code'] == 200) {
                $detail = $res['data'];
                cache('capacity', $detail);
            }
        }
        return $detail;
    }

    //消费类型
    function consumptionType($data)
    {
        $data['brandclass_id'] = $data['brandclass_id'] ? $data['brandclass_id'] : session('brandclass_id');
        $data['id'] = $data['id'] ? $data['id'] : '';
        $return = cache('consumptionType_'.$data['brandclass_id'].$data['id']);
        if(empty($return)){
            $url = "59fd58574204a";
            $request = sx_call($url, $data);
            if ($request['code'] == 200) {
                $return = $request['data'];
                cache('consumptionType_'.$data['brandclass_id'].$data['id'], $return);
            }else{
                $request = sx_call($url, []);
                if ($request['code'] == 200) {
                    $return = $request['data'];
                    cache('consumptionType_'.$data['brandclass_id'].$data['id'], $return);
                }
            }
        }
        return $return;
    }

    //接单点
    function orderAddress($data)
    {
        // $detail = session('orderAddress');
        // if(empty($detail)){
        $url = "5a00506445948";
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $detail = $res['data'];
           // session('orderAddress', $detail);
        }
        // }
        return $detail;
    }
    //员工所有岗位
    public function getPositions(){
        $mc = new \app\common\lib\mcInterface();
        // $position = $this->get_staff_info(['staff_id'=>session('staff_id')]);
        $position = $mc->getOneStaff(['staff_id'=>session('staff_id')]);
        if($position === false){
            return false;
        }
        $position_code = $position['main_position_code'].','.$position['position_code'];
        return $mc->getPosition(['position_code'=>$position_code]);

        /*
        $url = '5a0b96b65c111';
        $position = $this->get_staff_info(['staff_id'=>session('staff_id')]);
        $position_code = $position['data']['main_position_code'].','.$position['data']['position_code'];
        $info = sx_call($url,['position_code'=>$position_code]);
        if($info['code'] == 200) {
            return $info['data'];
        }else{
            return false;
        }*/
    }

    //人员
    function get_staff_list($data){
        $mc = new \app\common\lib\mcInterface();
        return  $mc->cacheData('5a01766b4a3dd',$data);

        // $url="5a01766b4a3dd";
        // $res=sx_call($url,$data);
        // if($res['code']==200){
        //     $info=$res['data'];
        // }
        // return $info;
    }
    //人员
    function get_staff_lists($data){
        if ($data['shop_code']) {
            $hash = '5a7424f13aa54';
        }else{
            $hash = '5a01766b4a3dd';
        }
        $mc = new \app\common\lib\mcInterface();
        $info = $mc->cacheData($hash,$data);

        // if (!$info) {
            
        //     if($info){
        //         cache('shop_staffs_'.$data['shop_code'],$info);
        //     }
            // $url="5a7424f13aa54";
            // $res=sx_call($url,$data);
            // if($res['code']==200){
            //     $info=$res['data'];
            //     cache('shop_staffs_'.$data['shop_code'],$info);
            // }
        // }
        
        return $info;
    }

    //店面
    function get_shop($data){
        $mc = new \app\common\lib\mcInterface();
        return $mc->getShops($data);

            // $url="5a005e0038270";
            // $res=sx_call($url,$data);
            // if($res['code']==200){
            //     $info=$res['data'];
            // }
    

        // return $info;
    }

    //客资查询
    function customerSearch_bp($data){
        $arr = [];
        $condition = [];
        $sql = " 1=1 ";
        if (!empty($data)) {
            if($data['city_id'])       $sql .= " and c.city_id = '".$data['city_id']."' ";//$sql .= " and customer_number = :customer_number ";  $arr['customer_number']=$data['customer_number'];
            if($data['customer_number'])       $sql .= " and c.customer_number = '".$data['customer_number']."' ";//$sql .= " and customer_number = :customer_number ";  $arr['customer_number']=$data['customer_number'];
            if($data['customer_name'])         $sql .= " and c.customer_name like '%".$data['customer_name']."%' ";
            if($data['customer_tel'])          $sql .= " and c.customer_tel = '".$data['customer_tel']."' ";
            if($data['customer_wechat'])       $sql .= " and c.customer_wechat = '".$data['customer_wechat']."' ";
            if($data['customer_weibo'])        $sql .= " and c.customer_weibo = '".$data['customer_weibo']."' ";
            if($data['customer_qq'])           $sql .= " and c.customer_qq = '".$data['customer_qq']."' ";
            if($data['dj_staff_id'])           $sql .= " and c.dj_staff_id = '".$data['dj_staff_id']."' ";
            if($data['dj_staff_name'])         $sql .= " and c.dj_staff_name = '".$data['dj_staff_name']."' ";
            if($data['sk_staff_id'])           $sql .= " and c.sk_staff_id = '".$data['sk_staff_id']."' ";
            if($data['consultation_type_id'])  $sql .= " and c.consultation_type_id = '".$data['consultation_type_id']."' ";
            if($data['customer_intention_id']) $sql .= " and c.customer_intention_id = '".$data['customer_intention_id']."' ";
            if($data['is_success'])            $sql .= " and c.is_success = '".$data['is_success']."' ";
            if($data['customer_cource_id'])    $sql .= " and c.customer_cource_id = '".$data['customer_cource_id']."' ";
            if($data['op_signinfo'])           $sql .= " and op_signinfo = '".$data['op_signinfo']."' ";
            if($data['sales_staff_id'])        $sql .= " and c.sales_staff_id = '".$data['sales_staff_id']."' ";
            if($data['is_fp'])                 $sql .= " and c.is_fp = '".$data['is_fp']."' ";
            if($data['is_valid'])              $sql .= " and c.is_valid = '".$data['is_valid']."' ";
            if($data['is_success'])            $sql .= " and c.is_success = '".$data['is_success']."' ";
            if($data['brandclass'])            $sql .= " and c.brandclass = '".$data['brandclass']."' ";
            //if($data['op_signinfo_id'])      $sql .= " and op_signinfo_id = '".$data['op_signinfo_id']."' ";
            if($data['sign_id'])               $sql .= " and c.sign_id = '".$data['sign_id']."' ";
            if($data['more_like'])             $sql .= " and (c.customer_name like '%".$data['more_like']."%' or c.customer_tel like '%".$data['more_like']."%' or c.customer_qq like '%".$data['more_like']."%' or c.customer_wechat like '%".$data['more_like']."%' or c.customer_weibo like '%".$data['more_like']."%') ";

            if($data['get_contact']){
                switch($data['get_contact']){
                    case 'get_phone': $sql .=" and c.customer_tel is not null and c.customer_tel != 0 ";
                        break;
                    case 'get_wechat': $sql .=" and c.customer_wechat is not null and c.customer_wechat != 0 ";
                        break;
                    case 'get_qq': $sql .=" and c.customer_qq is not null and c.customer_qq != 0 ";
                        break;
                }
            }

            if($data['is_fp']&&strpos($data['is_fp'],',')){
                $sql .= " and c.is_fp in (".$data['is_fp'].") ";
            }else if($data['is_fp']){
                $sql .= " and c.is_fp = '".$data['is_fp']."' ";
            }

            if($data['is_intostore']&&strpos($data['is_intostore'],',')){
                $sql .= " and c.is_intostore in (".$data['is_intostore'].") ";
            }else if($data['is_intostore']){
                $sql .= " and c.is_intostore = '".$data['is_intostore']."' ";
            }

            if($data['all_time']&&!empty($data['all_time'])){
                if($data['start_time'])      $sql .= " and c.".$data['all_time']." >='".$data['start_time']."' ";
                if($data['end_time'])        $sql .= " and c.".$data['all_time']." <'".$data['end_time']."' ";
            }

            if($data['type_info'] && !empty($data['type_info'])){
                $arr = explode(',',$data['type_info']);
            }

            if(count($arr)){
                foreach($arr as $k => $v){
                    $res = explode('=',$v);
                    $condition[$res[0]][] = $res[1];
                }
            }

            if(count($condition)){
                foreach($condition as $k => $v){
                    $arr=implode(',',$v);
                    $sql .= " and c.{$k} in ($arr) ";
                }
            }
        }
        $sql .= ' and c.is_status=1 and c.is_act=2 ';
        return $sql;
    }

    // 获取 爆破 客资数据
    function customerListData_bp($data){
        $end_time=$data['end_time'];
        $data['end_time']=date("Y-m-d",strtotime("$end_time +1 day"));
        $sql=$this->customerSearch_bp($data);

        if(check_right('menu1512637269')){
            switch (session('is_belong')){
                case '2':
                    $sql .= " and c.brandclass = '".session('brandclass')."' ";
                    break;
                case '3':
                    $sql .= " and (c.shop_code = '".session('shop_code')."' or c.add_shop_code = '".session('shop_code')."') ";
                    break;
                case '4':
                    $sql .= " and (c.shop_code = '".session('shop_code')."' or c.add_shop_code = '".session('shop_code')."') ";
                    break;
            }
        }else{
            if(strpos($data['type_info'],'sales_staff_id')===false){
                if($data['tab']&&($data['tab']==100)){ //、当日预进店
                    $sql .= " and s.sales_staff_id = '".session('staff_id')."' ";
                }
            }
        }
        if($data['tab']&&$data['tab']==100)  $order=" c.is_valid asc,c.dj_day desc ";
        $str = cache('colColumn_'.session('staff_id').'_'.session('shop_type'));//个人自定义列
        $check_list = db_config('shop_column_'.session('shop_code'));//店面自定义列
        if(session('shop_type') == 2){
            $default_coluwn = strlen($check_list)>0 ? 'c.id,'.trim($check_list,',') : 'c.id,c.customer_channel,c.sign_name,c.is_valid,c.op_signinfo,c.customer_number,c.baby_name,c.baby_sex,c.baby_birthday,c.customer_name,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.mate_name,c.mate_tel,c.add_friend_time,c.city,c.,c.customer_key,c.marry_day,c.budget,c.consulation_shop,c.reception_name,c.yjd_day,c.track_record,c.is_intostore,c.syjd_day,c.is_success,c.order_start_time,c.order_day,c.totalpay_money,c.fact_money,c.loss_cause,c.erp_loss_reason,c.customer_type,c.dj_day,c.create_time,c.is_fp,c.is_loss,erp_loss,c.dj_staff,s.sales_staff_name,c.sk_staff,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.introducer_type,c.tel_visit_num,c.last_trackday,c.consultation_type,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,f.bonus,c.brandclass,c.shop_name,c.add_shop_name,customer_address,order_type,f.dj_group_name,f.sales_group_name,c.dj_department_name,c.sales_department_name';
        }else{
            $default_coluwn = strlen($check_list)>0 ? 'c.id,'.trim($check_list,',') : 'c.id,c.customer_channel,c.sign_name,c.is_valid,c.op_signinfo,c.customer_number,c.customer_name,c.customer_sex,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.mate_name,c.mate_tel,c.add_friend_time,c.city,c.customer_key,c.marry_day,c.budget,c.consulation_shop,c.reception_name,c.yjd_day,c.track_record,c.is_intostore,c.syjd_day,c.is_success,c.order_start_time,c.order_day,c.totalpay_money,c.fact_money,c.loss_cause,c.erp_loss_reason,c.customer_type,c.dj_day,c.create_time,c.is_fp,c.is_loss,c.erp_loss,c.dj_staff,s.sales_staff_name,c.sk_staff,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.introducer_type,c.tel_visit_num,c.last_trackday,c.consultation_type,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,f.bonus,c.brandclass,c.shop_name,c.add_shop_name,customer_address,order_type,f.dj_group_name,f.sales_group_name,c.dj_department_name,c.sales_department_name';
        }
        $clumn = $str ? 'c.id,c.'.str_replace(',',',c.',$str) : $default_coluwn;

        $join = [
            ['c_swap_customer s','c.customer_number=s.customer_number', 'left'],
        ];
        $customer = db('c_customerinfo c')->join($join)->join('c_customer_from f','f.cid = c.id','left')->where($sql)->field($clumn)->select();

//        $a=db()->getLastSql();print_r($a);die;
        $detail['page']= $data['page'] ? $data['page'] : 1;
        $detail['records']=count($customer);
        $detail['total']=ceil($detail['records']/10) ? ceil($detail['records']/10) : 0;
//        $dep = $this->getDepartment();
        foreach($customer as $k=>$v){
            $v['customer_type'] = $v['customer_type'] == 1 ? '新客资' : '转介绍';
            if ($v['order_type'] == 1 && $v['is_success'] != 2) {
                $v['order_type']='线上';
            }elseif($v['order_type'] == 2 && $v['is_success'] != 2){
                $v['order_type']='线下';
            }else{
                $v['order_type']='';
            }
            $v['is_loss'] = $v['is_loss'] == 1 ? '是':'否';
            if(!check_right('menu1512998373')){
                $v['customer_tel'] = !empty($v['customer_tel']) ? substr($v['customer_tel'], 0, 3).'****'.substr($v['customer_tel'], 7) : '';
            }
            $v['order_start_time'] = $v['order_start_time'] ? date('Y-m-d',strtotime($v['order_start_time'])) : '';
            $v['order_day'] = $v['order_day'] ? date('Y-m-d',strtotime($v['order_day'])) : '';
            $v['yjd_day'] = $v['yjd_day'] ? date('Y-m-d H:i',strtotime($v['yjd_day'])) : '';
            $v['yjd_action_day'] = $v['yjd_action_day'] ? date('Y-m-d',strtotime($v['yjd_action_day'])) : '';
            $v['next_time'] = $v['next_time'] ? date('Y-m-d',strtotime($v['next_time'])) : '';
            $v['syjd_day'] = $v['syjd_day'] ? date('Y-m-d',strtotime($v['syjd_day'])) : '';
            $v['dj_day'] = $v['dj_day'] ? date('Y-m-d H:i',strtotime($v['dj_day'])) : '';
            $v['create_time'] = $v['create_time'] ? date('Y-m-d H:i',strtotime($v['create_time'])) : '';
            $v['marry_day'] = $v['marry_day'] ? date('Y-m-d',strtotime($v['marry_day'])) : '';
            $v['is_intostore'] = getIsIntostore($v['is_intostore']);
            $v['is_urgent'] = $v['is_urgent'] == 1 ? '是' : '否';
            $v['erp_loss'] = $v['erp_loss'] == 1 ? '否' : '是';
            $v['bonus'] = $v['bonus'] == 1 ? '已发' : '未发';
            $v['is_valid'] = getIsValidAttr($v['is_valid']);
            $v['is_fp'] = getIsFP($v['is_fp']);
            $v['is_success'] = getIsSuccess($v['is_success']);
            $v['introducer_type'] = getIntroducerType($v['introducer_type']);
//            $v['dj_department_id'] = $dep[$v['dj_department_id']]['department_name'];
//            $v['sales_department_id'] = $dep[$v['sales_department_id']]['department_name'];
            $v['totalpay_money'] = $v['totalpay_money'] ? number_format($v['totalpay_money'],2) : '';
            $v['fact_money'] = $v['fact_money'] ? number_format($v['fact_money'],2) : '';
            $v['customer_remark'] = strip_tags($v['customer_remark']);
            $cus[$k]['id']=$v['id'];
            $cus[$k]['cell']=array_values($v);
        }
        $detail['rows']=$cus;
        $detail['userdata']['amount']=3320;
        $detail['userdata']['tax']=336;
        $detail['userdata']['total']=3320;
        $detail['userdata']['name']='Totals:';
        return $detail;
    }

    //获取客资数据
    function customerListData($data){
        ini_set('memory_limit','-1');
        testTime(__FILE__,__LINE__);
        $listTime = microtime(true).'==>Line'.__LINE__.';';
        $end_time=$data['end_time'];
        $data['end_time']=date("Y-m-d H:i:s",strtotime($data['end_time']));
        $sql=$this->customerSearch($data);
        // if(session('staff_name') == 'gm'){
        //     print_r($sql);
        //     exit;
        // }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if ($data['tab']&&$data['tab']==17) {
            // 今日需追踪
            $data['all_time'] = 'dj_day';
            unset($data['start_time']);
            $sql = $this->customerSearch($data);
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // 近三日预进店
        if ($data['tab']&&$data['tab']==12) {
            // 今日需追踪
            $data['all_time'] = 'dj_day';
            unset($data['start_time']);
            $sql = $this->customerSearch($data);
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if ($data['tab']&&$data['tab']==18) {
            // 过期客资
            unset($data['all_time']);
            unset($data['start_time']);
            unset($data['end_time']);
            $sql = $this->customerSearch($data);
        }
        // 20200612
        $client_customer_id = trim($data['client_customer_id']);
        if ($client_customer_id) {
            $sql = ' is_status=1 AND c.is_examine=1 AND c.id IN ('.$client_customer_id.')';
        }

        if(check_right('menu1512637269')){
            switch (session('is_belong')){
                case '2':
                    $sql .= " and c.brandclass = '".session('brandclass')."' ";
                    break;
                case '3':
                    // if(session('is_marketing') == 1){
                    //     $sql .= " and add_shop_code='".session('shop_code')."'";
                    // }elseif(session('is_marketing') == 3 || session('is_marketing') == 4){
                    //     $sql .= " and shop_code='".session('shop_code')."'";
                    // }else{
                    //     $sql .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                    // }
                     $sql .= " and (c.shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                    break;
                case '4':
                    if(session('is_marketing') == 1){
                        $sql .= " and add_shop_code='".session('shop_code')."'";
                    }elseif(session('is_marketing') == 3 || session('is_marketing') == 4){
                        $sql .= " and c.shop_code='".session('shop_code')."'";
                    }else{
                        $sql .= " and (c.shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                    }
                    //$sql .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                    break;
            }
        }else{
            //没有查看所有客资权限，则限制只能查当前店--醉唐风
            if(customize('gyztf')){
                $sql .= " and (c.shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
            }
            //如果没有查看所有客资权限,但有查看小组权限
            if(!$data['group']){
                if(strpos($data['type_info'],'sales_staff_id')===false){
                    if($data['tab']&&$data['tab']==3) {//待分配
                        $sql .= " and (dj_staff_id='" . session('staff_id') . "' or (sales_staff_id='" . session('staff_id') . "' and is_fp=2 ) or sk_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')."'  ";
                    }else{
                        if(!$data['dep']){
                            if(session('is_marketing') == 1){
                                $sql .= " and (dj_staff_id='".session('staff_id')."' or sk_staff_id='".session('staff_id')."')";
                            }elseif(session('is_marketing') == 3 || session('is_marketing') == 4){
                                $sql .= " and is_fp=1 and (sales_staff_id='".session('staff_id')."' or sk_staff_id='".session('staff_id')."')";
                            }else{
                                $sql .= " and (dj_staff_id='" . session('staff_id') . "' or (c.sales_staff_id='" . session('staff_id') . "' and is_fp=1 ) or sk_staff_id='" . session('staff_id') . "' )";
                            }
                        }//else{
                          //  $sql .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                        //}

                    }
                    /*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 ) ) ";
                    }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 ) ) ";
                    }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 ) ) ";
                    }elseif($data['tab']&&($data['tab']==17)){ //今日需追踪
                        $sql .= " and (dj_staff_id = '".session('staff_id')."' or (sales_staff_id = '".session('staff_id').") ) ";
                    }*/
                }
            }
        }
        // if($data['tab']&&$data['tab'] != 1){
        //     $res = db('s_customer_tab')->where('id',$data['tab'])->find();
        //     $info = json_decode($res['sql'],true);
        //     $order = $info['order_by'];
        // }else{
        //     if(!$data['tab']||$data['tab']==1)          $order=" is_valid asc,dj_day desc ";
        // }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $order = '';
        if($data['sidx']){
            $order .= ' '.$data['sidx'].' '.$data['sord'].',';
        }

        // if(!$data['tab']||$data['tab']==1)          $order .=" is_valid asc,dj_day desc ";
        if(!$data['tab']||($data['tab']== 1) )        $order .= " c.dj_day desc ";
        if( $data['tab']&&($data['tab']== 2) )        $order .= " c.fp_day desc ";
        if( $data['tab']&&($data['tab']== 3) )        $order .= " c.is_valid asc,c.dj_day desc ";
        if( $data['tab']&&($data['tab']== 4) )        $order .= " c.jr_day desc ";
        if( $data['tab']&&($data['tab']== 5) )        $order .= " c.order_day desc ";
        if( $data['tab']&&($data['tab']== 6) )        $order .= " c.syjd_day desc ";
        if( $data['tab']&&($data['tab']== 7) )        $order .= " c.loss_day desc ";
        if( $data['tab']&&($data['tab']== 8) )        $order .= " c.is_valid asc,c.dj_day desc ";
        if( $data['tab']&&($data['tab']== 9) )        $order .= " c.sk_time desc ";
        if( $data['tab']&&($data['tab']==10) )        $order .= " c.jr_day desc ";
        if( $data['tab']&&($data['tab']==11) )        $order .= " c.jr_day desc ";
        if( $data['tab']&&($data['tab']==12) )        $order .= " c.yjd_day desc ";
        if( $data['tab']&&($data['tab']==13) )        $order .= " c.dj_day desc ";
        if( $data['tab']&&($data['tab']==14) )        $order .= " c.dj_day desc ";
        if( $data['tab']&&($data['tab']==17) )        $order .= " c.next_time desc,c.jr_day desc ";
        if( $data['tab']&&($data['tab']==18) ){
            //客资过期判定规则
            $rule = db_config('valid_date_rule');
            $rule = $rule ? $rule : 'dj_day';
            $order .= " $rule desc ";
        }
        // if($data['tab']&&($data['tab']==10))        $order .=" dj_day desc ";
        // if($data['tab']&&($data['tab']==11))        $order .=" c_star_day desc ";

        $column = cache('colColumn_'.session('staff_id').'_'.session('shop_type'));
        if (!$column) {
            $info = db('s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->find();
            if(!empty($info)){
                cache('colColumn_'.session('staff_id').'_'.session('shop_type'),$info['custom_column']);
                cache('colNames_'.session('staff_id').'_'.session('shop_type'),$info['custom_name']);
                cache('colModel_'.session('staff_id').'_'.session('shop_type'),$info['custom_model']);
            }
        }
        $check_list = db_config('shop_column_'.session('shop_code'));//店面自定义列
        if($check_list){
            $temp1 = explode(',',$check_list);
            $my1 = '';
            foreach($temp1 as $k=>$v){
                if($v == 'order_fact' || $v == 'order_amount'){
                    $my1 .= 'o.'.$v.',';
                }elseif($v == 'dj_group_name' || $v == 'sales_group_name' || $v == 'bonus' || $v == 'bonus_deal' || $v == 'dj_group_id' || $v == 'sales_group_id'){
                    $my1 .= 'f.'.$v.',';
                }elseif($v){
                    $my1 .= 'c.'.$v.',';
                }
            }
            $check_list = trim($my1,',');
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if(session('shop_type') == 2){
            $default_cluwn = strlen($check_list)>0 ? $check_list :  'c.id,c.customer_channel,c.customer_channel_id,c.sign_name,c.is_valid,c.unvalid_reason,c.op_signinfo,c.customer_number,c.baby_name,c.baby_sex,c.baby_birthday,c.ready_baby_day,c.customer_name,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.mate_name,c.mate_tel,c.mate_wechat,c.wechat_status,c.add_friend_time,c.province,c.city,c.county,c.customer_address,c.customer_key,c.channel_plan_number,c.budget,c.consulation_shop,c.reception_name,c.next_time,c.yjd_action_day,c.yjd_day,c.customer_remark,c.ad_page,c.step_name,c.track_record,c.customer_label,c.is_intostore,c.is_urgent,c.syjd_day,c.is_success,c.order_number,c.order_start_time,c.order_day,c.totalpay_money,o.order_type,o.order_fact,o.order_amount,c.fact_money,c.loss_cause,c.erp_loss_reason,c.customer_type,c.dj_day,c.fp_day,c.create_time,c.is_fp,c.is_loss,c.erp_loss,c.dj_staff,c.sales_staff,c.sk_staff,c.fp_staff,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.introducer_type,c.tel_visit_num,c.c_star_day,c.last_trackday,c.consultation_type,c.consultation_type_id,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,f.bonus_deal,f.bonus,c.brandclass,c.shop_name,c.add_shop_name,c.dj_department_name,c.sales_department_name,c.customer_address,f.dj_group_name,f.sales_group_name';
            $def = 'c.id,c.customer_channel,c.customer_channel_id,c.sign_name,c.is_valid,c.unvalid_reason,c.op_signinfo,c.customer_number,c.baby_name,c.baby_sex,c.baby_birthday,c.ready_baby_day,c.customer_name,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.mate_name,c.mate_tel,c.mate_wechat,c.wechat_status,c.add_friend_time,c.province,c.city,c.county,c.customer_address,c.customer_key,c.channel_plan_number,c.budget,c.consulation_shop,c.reception_name,c.next_time,c.yjd_action_day,c.yjd_day,c.customer_remark,c.ad_page,c.step_name,c.track_record,c.customer_label,c.is_intostore,c.is_urgent,c.syjd_day,c.is_success,c.order_number,c.order_start_time,c.order_day,c.totalpay_money,o.order_type,o.order_fact,o.order_amount,c.fact_money,c.loss_cause,c.erp_loss_reason,c.customer_type,c.dj_day,c.fp_day,c.create_time,c.is_fp,c.is_loss,c.erp_loss,c.dj_staff,c.sales_staff,c.sk_staff,c.fp_staff,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.introducer_type,c.tel_visit_num,c.c_star_day,c.last_trackday,c.consultation_type,c.consultation_type_id,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,f.bonus_deal,f.bonus,c.brandclass,c.shop_name,c.add_shop_name,c.dj_department_name,c.sales_department_name,c.customer_address,f.dj_group_name,f.sales_group_name';
        }else{
            $default_cluwn = strlen($check_list)>0 ? $check_list : 'c.id,c.customer_channel,c.customer_channel_id,c.sign_name,c.is_valid,c.unvalid_reason,c.op_signinfo,c.customer_number,c.customer_name,c.customer_sex,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.mate_name,c.mate_tel,c.mate_wechat,c.wechat_status,c.add_friend_time,c.province,c.city,c.county,c.customer_address,c.customer_key,c.channel_plan_number,c.marry_day,c.budget,c.consulation_shop,c.reception_name,c.next_time,c.yjd_action_day,c.yjd_day,c.customer_remark,c.ad_page,c.step_name,c.track_record,c.customer_label,c.is_intostore,c.is_urgent,c.syjd_day,c.is_success,c.order_number,c.order_start_time,c.order_day,c.totalpay_money,o.order_type,o.order_fact,o.order_amount,c.fact_money,c.loss_cause,c.erp_loss_reason,c.customer_type,c.dj_day,c.fp_day,c.create_time,c.is_fp,c.is_loss,c.erp_loss,c.dj_staff,c.sales_staff,c.sk_staff,c.fp_staff,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.introducer_type,c.tel_visit_num,c.c_star_day,c.last_trackday,c.consultation_type,c.consultation_type_id,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,f.bonus_deal,f.bonus,c.brandclass,c.shop_name,c.add_shop_name,c.dj_department_name,c.sales_department_name,f.dj_group_name,f.sales_group_name';
            $def = 'c.id,c.customer_channel,c.customer_channel_id,c.sign_name,c.is_valid,c.unvalid_reason,c.op_signinfo,c.customer_number,c.wechat_status,c.customer_name,c.customer_sex,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.mate_name,c.mate_tel,c.mate_wechat,c.add_friend_time,c.province,c.city,c.county,c.customer_address,c.customer_key,c.channel_plan_number,c.marry_day,c.budget,c.consulation_shop,c.reception_name,c.next_time,c.yjd_action_day,c.yjd_day,c.customer_remark,c.ad_page,c.step_name,c.track_record,c.customer_label,c.is_intostore,c.is_urgent,c.syjd_day,c.is_success,c.order_number,c.order_start_time,c.order_day,c.totalpay_money,o.order_type,o.order_fact,o.order_amount,c.fact_money,c.loss_cause,c.erp_loss_reason,c.customer_type,c.dj_day,c.fp_day,c.create_time,c.is_fp,c.is_loss,c.erp_loss,c.dj_staff,c.sales_staff,c.sk_staff,c.fp_staff,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.introducer_type,c.tel_visit_num,c.c_star_day,c.last_trackday,c.consultation_type,c.consultation_type_id,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,f.bonus_deal,f.bonus,c.brandclass,c.shop_name,c.add_shop_name,c.dj_department_name,c.sales_department_name,f.dj_group_name,f.sales_group_name';
        }

        $myClumn = cache('colColumn_'.session('staff_id').'_'.session('shop_type'));
        if($myClumn){
            $temp = explode(',',$myClumn);
            $my = '';
            foreach($temp as $k=>$v){
                if($v == 'order_fact' || $v == 'order_amount'){
                    $my .= 'o.'.$v.',';
                }elseif($v == 'dj_group_name' || $v == 'sales_group_name' || $v == 'bonus' || $v == 'bonus_deal' || $v == 'dj_group_id' || $v == 'sales_group_id'){
                    $my .= 'f.'.$v.',';
                }elseif($v){
                    $my .= 'c.'.$v.',';
                }
            }
        }
        $my = trim($my,',');
        $clumn = cache('colColumn_'.session('staff_id').'_'.session('shop_type')) ? 'c.id,'.$my : 'c.id,'.trim($default_cluwn,',');
        //组合字段，自定义字段+默认字段（排除自定义）
        $clumn_arr = explode(',',$clumn);
        $def_arr = explode(',',$def);
        foreach($clumn_arr as $k=>$v){
            $s = array_search($v,$def_arr);
            if($s !== false){
                unset($def_arr[$s]);
            }
            // 计算值 数据库中 无字段
            if ($v=='c.noTrackDay') {
                unset($clumn_arr[$k]);
            }
        }
        $mer = array_merge($clumn_arr,$def_arr);
        $clumn = implode(',',$mer);
        unset($clumn_arr,$def_arr);
        $data['rows'] =  (int)$data['rows'] ? (int)$data['rows'] : 100;
        $data['page'] =  (int)$data['page'] ? (int)$data['page'] : 1;
        // if((int)$data['id']){
        //     $sql = ' id='.(int)$data['id'];
        // }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // $customer  =db('c_customerinfo')->alias('c')->join('c_customer_from f','c.id=f.cid','left')->where($sql)->count();

        // 判断有无索引
        $all_time = $data['all_time'];
        $index_sql = 'show index from c_customerinfo where key_name = "'.$all_time.'"';
        $index = db('c_customerorder')->query($index_sql);
        if(!empty($all_time) && !empty($index) && empty($data['more_like'])){
            $customer  =db('c_customerinfo c  force index (`'.$all_time.'`)')->join('c_customer_from f','c.id=f.cid','left')->where($sql)->count();
        }else{
            $customer  =db('c_customerinfo')->alias('c')->join('c_customer_from f','c.id=f.cid','left')->where($sql)->count();
        }
        $detail['csql']=db()->getLastSql();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $customer1=db('c_customerinfo')->alias('c')
                    ->join('c_customer_from f','c.id=f.cid','left')
                    ->join('c_customer_order o','c.order_number=o.order_sn and c.id=o.customer_id','left')
                    ->field($clumn)
                    ->where($sql)
                    ->limit($data['rows'])
                    ->page($data['page'])
                    ->ORDER($order)
                    ->select();
        // $a=db()->getLastSql();print_r($a);die;
        $detail['sql']=db()->getLastSql();
        $detail['page']= $data['page'] ? $data['page'] : 1;
        $detail['records']=($customer);
        $detail['page'] = $data['page'];
        $detail['total']=ceil($detail['records']/$data['rows']) ? ceil($detail['records']/$data['rows']) : 0;
        $data['page'] = $data['page']>$detail['total']?$detail['total']:$data['page'];
        // $dep = $this->getDepartment();
        //根据单号查询金额
        $orderSN = array_column($customer1,'order_number');
        $ids = array_column($customer1,'id');
        $order = db('c_customer_order')->where('order_sn','in',$orderSN)->where('customer_id','in',$ids)->column('earnest_money,order_fact,order_amount,two_pin_fact,two_pin_amount','order_sn');
        $newRow = [];
        $mc = config('ext.app_config');
        $addr = $mc['sx_mc']['addr'];
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $allChannel = getChannels();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $check_right = check_right('menu1512998373');
        foreach($customer1 as $k=>$v){
            $v['customer_type'] = $v['customer_type'] == 1 ? '新客资' : '转介绍';
            if ($v['order_type'] == 1 && $v['is_success'] != 2) {
                $v['order_type']='线上';
            }elseif($v['order_type'] == 2 && $v['is_success'] != 2){
                $v['order_type']='线下';
            }else{
                $v['order_type']='';
            }
            // 微信添加状态 0：未添加；1：已添加未通过；2：已加上；3：未加上
            if ($v['customer_wechat']) {
            	$cWechat = $v['customer_wechat'];
                $wechat_status = $v['wechat_status'];
            	$v['customer_wechat'] = '<div class="pos_con" onclick="popWx('.$v['id'].')">';
                if ($wechat_status==1) {
                    $v['customer_wechat'] .= '<img style="width:18px;padding-right: 5px;padding-left: 5px;" src="/img/wxdtg.png" id="'.$v['id'].'wxicon" /><span class="wx_icon">'.$cWechat.'</span>';
                }else if ($wechat_status==2) {
                    $v['customer_wechat'] .= '<img style="width:18px;padding-right: 5px;padding-left: 5px;" src="/img/wxtj.png" id="'.$v['id'].'wxicon" /><span class="wx_icon">'.$cWechat.'</span>';
                }elseif ($wechat_status==3) {
                    $v['customer_wechat'] .= '<img style="width:18px;padding-right: 5px;padding-left: 5px;" src="/img/wxwtj.png" id="'.$v['id'].'wxicon" /><span class="wx_icon">'.$cWechat.'</span>';
                }else{
                    $v['customer_wechat'] .= '<img style="width:18px;padding-right: 5px;padding-left: 5px;" src="/img/wx.png" id="'.$v['id'].'wxicon" /><span class="wx_icon">'.$cWechat.'</span>';
                }
                $v['customer_wechat'] .= '<div class="weChat_model" id="'.$v['id'].'wxpop" style="display:none;"><img class="ivu_img" src="/crm/customer/getWxCopyPageEwm/cid/'.$v['id'].'"><div onclick="wxStatus(2,'.$v['id'].')" class="ivu_btn"><span><img src="/img/wxtj.png" style="margin-right: 5px;width: 18px;">已通过</span></div><div onclick="wxStatus(3,'.$v['id'].')" class="ivu_btn"><span><img src="/img/wxwtj.png" style="margin-right: 5px;width: 18px;">未通过</span></div></div>';
                unset($cWechat,$wechat_status);
            }
            // if ($v['customer_tel']) {
            //     $v['customer_tel'] = '<img style="width:20px;margin-top:-3px;" src="/img/tel.png" /><span class="wx_icon">'.$v['customer_tel'].'</span>';
            // }
            // 渠道图标
            if ($v['customer_channel_id']) {
                $v['customer_channel'] = '<img onerror="javascript:this.remove()" src="'.$addr.'/public/channelimg/'.$allChannel[$v['customer_channel_id']]['channel_info_id'].'.png" style="width:25px;padding-right:5px;">'.$v['customer_channel'];
            }
            // 消费类型图标
            if ($v['consultation_type_id']) {
                $v['consultation_type'] = '<img onerror="javascript:this.remove()" src="'.$addr.'/public/consumptionimg/'.$v['consultation_type_id'].'.png" style="width:25px;padding-right:5px;">'.$v['consultation_type'];
            }
            // 加好友已通过
            if ($v['wechat_status']!=2) {
                $v['add_friend_time'] = NULL;
            }
            $v['is_loss'] = $v['is_loss'] == 1 ? '是':'否';
            if(!$check_right){
                $v['customer_tel'] = !empty($v['customer_tel']) ? substr($v['customer_tel'], 0, 3).'****'.substr($v['customer_tel'], 7) : '';
            }
            if(session('shop_type') == 2){
                $v['baby_birthday'] = $v['baby_birthday'] ? date('Y-m-d',strtotime($v['baby_birthday'])) : '';
                $v['ready_baby_day'] = $v['ready_baby_day'] ? date('Y-m-d',strtotime($v['ready_baby_day'])) : '';
            }
            $v['order_start_time'] = $v['order_start_time'] ? date('Y-m-d',strtotime($v['order_start_time'])) : '';
            $v['order_day'] = $v['order_day'] ? date('Y-m-d',strtotime($v['order_day'])) : '';
            $v['yjd_day'] = $v['yjd_day'] ? date('Y-m-d H:i',strtotime($v['yjd_day'])) : '';
            $v['yjd_action_day'] = $v['yjd_action_day'] ? date('Y-m-d',strtotime($v['yjd_action_day'])) : '';
            $v['next_time'] = $v['next_time'] ? date('Y-m-d',strtotime($v['next_time'])) : '';
            $v['syjd_day'] = $v['syjd_day'] ? date('Y-m-d',strtotime($v['syjd_day'])) : '';
            $v['dj_day'] = $v['dj_day'] ? date('Y-m-d H:i:s',strtotime($v['dj_day'])) : '';
            $v['fp_day'] = $v['fp_day'] ? date('Y-m-d H:i',strtotime($v['fp_day'])) : '';
            $v['create_time'] = $v['create_time'] ? date('Y-m-d H:i',strtotime($v['create_time'])) : '';
            $v['marry_day'] = $v['marry_day'] ? date('Y-m-d',strtotime($v['marry_day'])) : '';
            // 如果存在实际进店时间 并且小于当前日期 并且 没有订单 那么该客资的进店状态为 进店流失
            if ($v['syjd_day'] && date('Ymd',strtotime($v['syjd_day']))<date('Ymd') && $v['is_success']==2 && $v['is_intostore']!=5) {
                $v['is_intostore'] = 5;
            }
            $v['is_intostore'] = getIsIntostore($v['is_intostore']);
            $v['is_urgent'] = $v['is_urgent'] == 1 ? '是' : '否';
            $v['erp_loss'] = $v['erp_loss'] == 1 ? '否' : '是';
            $v['bonus'] = $v['bonus'] == 1 ? '已发' : '未发';
            $v['bonus_deal'] = $v['bonus_deal'] == 1 ? '已发' : '未发';
            // 客资无效时，才显示无效原因
            if ($v['is_valid']!==3) {
                $v['unvalid_reason'] = '';
            }
            $v['is_valid'] = getIsValidAttr($v['is_valid']);
            $v['is_fp'] = getIsFP($v['is_fp']);
            $v['is_success'] = getIsSuccess($v['is_success']);
            $v['introducer_type'] = getIntroducerType($v['introducer_type']);
            if ($v['ad_page']) {
                // $adUrl = 'http://'.trim($v['ad_page'],'http://');
                // $adUrl = 'https://'.trim($v['ad_page'],'https://');
                $v['ad_page'] = '<a href="'.$v['ad_page'].'" target="_blank">'.$v['ad_page'].'</a>';
            }else{
                $v['ad_page'] = '';
            }

            // $v['dj_department_id'] = $dep[$v['dj_department_id']]['department_name'];
            // $v['sales_department_id'] = $dep[$v['sales_department_id']]['department_name'];
            $v['totalpay_money'] = $order[$v['order_number']]['order_amount']+$order[$v['order_number']]['two_pin_amount'] ? number_format($order[$v['order_number']]['order_amount']+$order[$v['order_number']]['two_pin_amount'],2) : '';
            $v['order_fact'] = $order[$v['order_number']]['order_fact']+$order[$v['order_number']]['earnest_money'];
            $v['fact_money'] = $order[$v['order_number']]['order_fact']+$order[$v['order_number']]['earnest_money']+$order[$v['order_number']]['two_pin_fact'] ? number_format($order[$v['order_number']]['order_fact']+$order[$v['order_number']]['earnest_money']+$order[$v['order_number']]['two_pin_fact'],2) : '';
            $v['customer_remark'] = strip_tags($v['customer_remark']);
            // 未追踪时间 ( 没有追踪过的 当前日期 - 登记日期)
            if (!$v['last_trackday']) {
                $v['noTrackDay'] = date('Ymd',time()) - date('Ymd',strtotime($v['dj_day']));
            }else{
                $v['noTrackDay'] = '';
            }
            $cus[$k]['id']=$v['id'];
            $cus[$k]['cell']=array_values($v);
            $newRow[$k] = $v;
        }testTime(__FILE__,__LINE__);
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // var_dump($newRow);die;
        // $detail['rows']=$cus;
        $detail['listTime'] = $listTime;
        $detail['new_rows'] = $newRow;
        $detail['userdata']['amount']=3320;
        $detail['userdata']['tax']=336;
        $detail['userdata']['total']=3320;
        $detail['userdata']['name']='Totals:';
        $detail['userdata']['total']=3320;
        global $abc;
        $detail['test_time'] = $abc;

        return $detail;
    }

    //客资数量
    function searchNum($data,$tab=0){
        $tab = $data['tab']?(int)$data['tab']:0;
        $end_time=$data['end_time'];
        // $data['end_time']=date("Y-m-d",strtotime("$end_time +1 day"));
        $data['end_time']=date("Y-m-d H:i:s",strtotime($data['end_time']));
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $sql=$this->customerSearch($data);
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // var_dump($sql);
        // exit;
        // 不再追踪 tab == 7
        $data['is_loss'] = 1;
        $data['tab'] = 7;
        $sqlLoss = $this->customerSearch($data);
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // var_dump($sqlLoss);
        // exit;
        // 今日需追踪 近三日预进店
        $data['all_time'] = 'dj_day';
        unset($data['start_time']);
        unset($data['is_loss']);
        unset($data['tab']);
        $sqlT=$this->customerSearch($data);
        $listTime .= microtime(true).'==>Line'.__LINE__.';';

        $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');
        if($is_bp){
            $bp_sql=$this->customerSearch_bp($data);
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';

        if(check_right('menu1512637269')){
            switch (session('is_belong')){

                case '1':
                    $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 =$sql16 = $sql17 = $sql;
                    break;
                case '2':
                    $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 =$sql16 = $sql17 = $sql . " and brandclass = '".session('brandclass')."' ";
                    $sqlT = $sqlT. " and brandclass = '".session('brandclass')."' ";
                    $sqlLoss = $sqlLoss. " and brandclass = '".session('brandclass')."' ";
                    break;
                case '3':
                    /*
                    if(session('is_marketing') == 1){
                        $sql .= " and add_shop_code = '".session('shop_code')."'";
                        $sqlT .= " and add_shop_code = '".session('shop_code')."'";
                        $sqlLoss .= " and add_shop_code = '".session('shop_code')."'";
                    }elseif(session('is_marketing') == 3 || session('is_marketing') == 4){
                        $sql .= " and shop_code = '".session('shop_code')."'";
                        $sqlT .= " and shop_code = '".session('shop_code')."'";
                        $sqlLoss .= " and shop_code = '".session('shop_code')."'";
                    }else{
                        */
                        $sql .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                        $sqlT .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                        $sqlLoss .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                    //}
                    $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 =$sql16 = $sql17 = $sql;
                    $bp_sql .= " and s.shop_code = '".session('shop_code')."'";
                    break;
                case '4':

                    if(session('is_marketing') == 1){
                        $sql .= " and add_shop_code = '".session('shop_code')."'";
                        $sqlT.= " and add_shop_code = '".session('shop_code')."'";
                        $sqlLoss.= " and add_shop_code = '".session('shop_code')."'";
                    }elseif(session('is_marketing') == 3 || session('is_marketing') == 4){
                        $sql .= " and shop_code = '".session('shop_code')."'";
                        $sqlT.= " and shop_code = '".session('shop_code')."'";
                        $sqlLoss.= " and shop_code = '".session('shop_code')."'";
                    }else{
                        $sql .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                        $sqlT.= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                        $sqlLoss.= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                    }
                    $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 =$sql16 = $sql17 = $sql;
                    $bp_sql .= " and s.shop_code = '".session('shop_code')."'";
                    break;
            }
        }else{
            if(!$data['group']) {
                if(strpos($data['type_info'],'sales_staff_id')===false) {
                    if(!$data['dep']){
                        if(session('is_marketing') == 1){
                            $sql1  = $sql4 = $sql5 = $sql6 = $sql7 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 = $sql16 = $sql17 = $sql .= " and (dj_staff_id = '" . session('staff_id') . "' or sk_staff_id ='" . session('staff_id') . "')  ";
                            $sqlT .= " and (dj_staff_id = '" . session('staff_id') . "' or sk_staff_id ='" . session('staff_id') . "')  ";
                            $sqlLoss .= " and (dj_staff_id = '" . session('staff_id') . "' or sk_staff_id ='" . session('staff_id') . "')  ";
                        }elseif(session('is_marketing') == 3 || session('is_marketing') == 4){
                            $sql1 = $sql4 = $sql5 = $sql6 = $sql7 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 = $sql16 = $sql17 = $sql .= " and (sales_staff_id = '" . session('staff_id') . "' or sk_staff_id ='" . session('staff_id') . "')  and is_fp=1  ";
                            $sqlT .= " and (sales_staff_id = '" . session('staff_id') . "' or sk_staff_id ='" . session('staff_id') . "')  and is_fp=1  ";
                            $sqlLoss .= " and (sales_staff_id = '" . session('staff_id') . "' or sk_staff_id ='" . session('staff_id') . "')  and is_fp=1  ";
                        }else{
                            $sql1 = $sql4 = $sql5 = $sql6 = $sql7 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 = $sql16 = $sql17 = $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') . "' )    ";
                            $sqlT .= " 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') . "' )    ";
                            $sqlLoss .= " 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') . "' )    ";
                        }
                    }else{
                        $sql1 = $sql4 = $sql5 = $sql6 = $sql7 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 = $sql16 = $sql17 = $sql;
                    }

                    $sql2 = $sql ." and sales_staff_id = '" . session('staff_id') . "' ";
                    $sql3 = $sql . " and (shop_code = '" . session('shop_code') . "' or add_shop_code= '".session('shop_code')."')";
                    $sql8 = $sql . " and sk_staff_id = '" . session('staff_id') . "' ";
                    $sql9 = $sql . " and sk_staff_id = '" . session('staff_id') . "' ";
                    $bp_sql .= " and s.sales_staff_id = '" . session('staff_id') . "'";
                   /* $sql1 = $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') . "')) ";
                    $sql2 = $sql . " and sales_staff_id = '" . session('staff_id') . "' ";
                    $sql3 = $sql . " and shop_code = '" . session('shop_code') . "' ";
                    $sql4 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $sql5 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $sql6 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $sql7 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $sql8 = $sql . " and sk_staff_id = '" . session('staff_id') . "' ";
                    $sql9 = $sql . " and sk_staff_id = '" . session('staff_id') . "' ";
                    //$sql8= $sql . " and (dj_staff_id = '".session('staff_id')."' or sales_staff_id = '".session('staff_id')."') ";
                    $sql10 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $sql11 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $sql12 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $sql13 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $sql14 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $sql15 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $sql16 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                    $bp_sql .= " and s.sales_staff_id = '" . session('staff_id') . "'";*/
                }else{
                    $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 = $sql16 = $sql;
                }
            }else{
                $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 = $sql16 = $sql17 = $sql;
            }
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        
        $index_sql = 'show index from c_customerinfo where key_name = "all_time"';
        $index = db('c_customerinfo')->query($index_sql);//判断有无索引
        if(!empty($index) && !config('search_use_full_text_index')){
            $table = 'c_customerinfo c force index(all_time)';
        }else{
            $table = 'c_customerinfo c';
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if(!$tab || $tab == 1){
            $detail['all_crm'] = $detail['tab_all']= db($table)->join('c_customer_from f','c.id=f.cid','left')->where($sql1)->count();//所有客资
            $detail['all_sql'] = db()->getLastSql();
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // echo db()->getLastSql();exit;
        // $detail['no_traking']=db('c_customerinfo')->where(array('c_star_day'=>null,'is_fp'=>1,'is_loss'=>2,'is_intostore'=>1))->where($sql2)->count();//待追踪
        // if(!$tab || $tab == 2)
        //     $detail['no_traking'] = $detail['tab_no_tracking'] = db($table)->join('c_customer_from f','c.id=f.cid','left')->where(array('c_star_day'=>null,'is_fp'=>1,'is_intostore'=>1,'is_loss'=>2,))->where('is_valid','in','1,2')->where($sql2)->count();//待追踪
        // $detail['no_traking_sql'] = db()->getLastSql();
        // $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if(!$tab || $tab == 3){
            if(session('is_sk')==1){
                $detail['no_fp'] = $detail['tab_no_fp'] = db($table)->join('c_customer_from f','c.id=f.cid','left')->where('is_fp','in','2,4')->where('is_already_sk',1)->where($sql3)->count();//待分配
            }else{
                $detail['no_fp'] = $detail['tab_no_fp'] = db($table)->join('c_customer_from f','c.id=f.cid','left')->where('is_fp','in','2,4')->where($sql3)->count();//待分配
            }
            $detail['no_fp_sql'] = db()->getLastSql();
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if(!$tab || $tab == 4)
            $detail['traking'] = $detail['tab_tracking'] = db($table)->join('c_customer_from f','c.id=f.cid','left')->where(array('is_loss'=>2,'is_fp'=>1,'is_intostore'=>1,'is_success'=>2))->where('is_valid','in','1,2')->where('c_star_day is not null')->where($sql4)->count();//追踪中
        $detail['traking_sql'] = db()->getLastSql();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if(!$tab || $tab == 5)
            $detail['crm_order'] = $detail['tab_order'] = db($table)->join('c_customer_from f','c.id=f.cid','left')->where('is_success','in','1,3')->where($sql5)->count();//已成单
        $detail['crm_order_sql'] = db()->getLastSql();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if(!$tab || $tab == 6)
            $detail['jdwd'] = $detail['tab_jdwd'] = db($table)->join('c_customer_from f','c.id=f.cid','left')->where(array('is_success'=>2,'is_loss'=>2))->where('is_intostore','in','2,3,5')->where($sql6)->count();//进店未成单
        $detail['jdwd_sql'] = db()->getLastSql();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if(!$tab || $tab == 7)
            $detail['loss'] = $detail['tab_loss'] = db($table)->join('c_customer_from f','c.id=f.cid','left')->where($sqlLoss)->count();//不再追踪
        $detail['loss_sql'] = db()->getLastSql();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // if(!$tab || $tab == 8)
        //     $detail['sk']= $detail['tab_no_sk'] = db($table)->join('c_customer_from f','c.id=f.cid','left')->where(array('is_sk'=>1,'is_already_sk'=>2))->where($sql8)->count();//筛客
        // $detail['sk_sql'] = db()->getLastSql();
        // $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // if(!$tab || $tab == 9)
        // $detail['already_sk']= $detail['tab_already_sk'] = db($table)->join('c_customer_from f','c.id=f.cid','left')->where(array('is_sk'=>1,'is_already_sk'=>1))->where($sql9)->count();//已筛客
        // $detail['already_sk_sql'] = db()->getLastSql();
        // $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // 今天 明天 3天前
        $today = date('Y-m-d 00:00:00');
        $end   = date('Y-m-d 23:59:59');
        $threeDaysAgo = date('Y-m-d', strtotime('-3 day'));
        // 今日接入
        if(!$tab || $tab == 10){
            $detail['today_receive'] = $detail['tab_today_receive'] = db($table)->join('c_customer_from f','c.id=f.cid','left')
                ->where('jr_day', 'between time', [$today, $end])
                ->where($sql10)
                ->count('id');
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $detail['today_receive_sql'] = db()->getLastSql();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // 三天内追踪
        // if(!$tab || $tab == 11)
        // $detail['three_tracking'] = $detail['tab_three_tracking'] = db($table)->join('c_customer_from f','c.id=f.cid','left')
        //     ->where('last_trackday', 'between time', [$threeDaysAgo, $today])
        //     ->where($sql11)
        //     ->count('id');
        // 预计今日进店  近三日  今天 明天 后天
        if(!$tab || $tab == 12){
            $detail['today_yjd']  = $detail['tab_today_yjd'] = db($table)->join('c_customer_from f','c.id=f.cid','left')
                ->where('yjd_day', 'between time', [$today, date('Y-m-d 23:59:59',strtotime('+ 2days'))])
                // ->where($sql12)
                ->where($sqlT)
                ->count('id');
            $detail['sql_today_yjd'] = db()->getLastSql();
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if($is_bp){
            //爆破客资
            $join = [
                ['c_swap_customer s','c.customer_number=s.customer_number'],
            ];
            $detail['bp'] = $detail['tab_bp'] = db('c_customerinfo c')
                ->join($join)
                ->where($bp_sql)
                ->count('c.id');
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // 有效客资
        if(!$tab || $tab == 13) {
            $detail['validCustomer'] = db($table)->join('c_customer_from f','c.id=f.cid','left')
                ->where($sql13)
                ->where('is_valid',1)
                ->count('id');
            $detail['sqlvaild'] = db()->getLastSql();
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if(!$tab || $tab == 14) {
            $detail['unValidCustomer'] = db($table)->join('c_customer_from f','c.id=f.cid','left')
                ->where($sql14)
                ->where('is_valid',3)
                ->count('id');
            $detail['sqlunvalid'] = db()->getLastSql();
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';

        if(session('productid') == '4583370241'){
            $detail['is_validShow'] = 1;
            $detail['tab'] = $tab;
            if($tab == 1){
                $detail['validCustomer'] = db($table)->join('c_customer_from f','c.id=f.cid','left')
                    ->where($sql13)
                    ->where('is_valid',1)
                    ->count('id');
                $detail['sqlvaild'] = db()->getLastSql();

                $detail['unValidCustomer'] = db($table)->join('c_customer_from f','c.id=f.cid','left')
                    ->where($sql14)
                    ->where('is_valid',3)
                    ->count('id');
                $detail['sqlunvalid'] = db()->getLastSql();
            }

            if($tab == 1 || !$tab){
                //待定
                $detail['ddValidCustomer'] = db($table)->join('c_customer_from f','c.id=f.cid','left')
                    ->where($sql14)
                    ->where('is_valid',2)
                    ->count('id');
                $detail['sqlddvalid'] = db()->getLastSql();
            }
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';

        // 今日需追踪
         $tWhere = " is_loss=2 and is_success=2 and (next_time is not null and next_time  <'".$end."' AND DATE_FORMAT(last_trackday, '%Y-%m-%d') < DATE_FORMAT(next_time, '%Y-%m-%d') OR ( c_star_day IS NULL) )  ";
        // 似乎这个才是正确的
        // $tWhere = " is_loss=2 and is_success=2 and ( next_time <= '".$end."' AND last_trackday < '".date('Y-m-d')."' OR ( c_star_day IS NULL) )  ";
        // exit;

        if(!$tab || $tab == 17)
        $detail['today_sales']  = $detail['tab_today_sales'] = db($table)->join('c_customer_from f','c.id=f.cid','left')
            ->where($sqlT)
            ->where($tWhere)
            ->count('id');
        $detail['today_sales_sql'] = db()->getLastSql();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // echo db()->getLastSql();die;
        //客资过期时间
        $key = 'brand_valid_date_'.md5(session('brandclass'));
        $valid_date = cache('?'.$key);
        if(!$valid_date){
            $mc = new \app\common\lib\mcInterface();
            $info = $mc->getBrand(['brandclass'=>session('brandclass')]);
            /*
            $info = sx_call('5a3bbb5d0988d',['brandclass'=>session('brandclass')]);
            if($info['code'] == 200){
                $valid_date = $info['data'][0]['valid_date'];
                cache($key,$valid_date,1800);
            }else{
                $valid_date = 60;
            }
            //*/
            if($info){
                $valid_date = $info['valid_date'];
            }else{
                $valid_date = 60;
            }
            cache($key,$valid_date,1800);
        }else{
            $valid_date = cache($key);
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if($valid_date == 0){
            $valid_date = 60;
        }
        // if(!$tab || $tab == 19)
        // $detail['friend'] = $detail['tab_weixin'] = db($table)->join('c_customer_from f','c.id=f.cid','left')->where($sql)->where(' add_friend_time is not null')->count('id');
        $lastDate = date('Y-m-d H:i:s',time() - ($valid_date * 86400));
        //客资过期判定规则
        $rule = db_config('valid_date_rule');
        $rule = $rule ? $rule : 'dj_day';
        $sqlOver = " $rule < '".$lastDate."'";
        //过期客资
        // if(!$tab || $tab == 18)
        // $detail['over_customer'] = db($table)->join('c_customer_from f','c.id=f.cid','left')
        //     ->where($sql)
        //     ->where($sqlOver)
        //     ->count('id');
        // $detail['over_customer_sql'] = db()->getLastSql();
        // $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $detail['listTime'] = $listTime;
        // $detail['valid_customer']=db('c_customerinfo')->where('is_valid',1)->where($sql13)->count();//有效客资
        // $detail['unvalid_customer']=db('c_customerinfo')->where('is_valid',2)->where($sql14)->count();//无效客资
        // $detail['daiding_customer']=db('c_customerinfo')->where('is_valid',3)->where($sql15)->count();//待定客资
        // $detail['bohui_customer']=db('c_customerinfo')->where('is_valid',4)->where($sql16)->count();//驳回客资
        // echo db()->getLastSql();die;
        //$detail['tel']=db('c_customerinfo')->where('tel_visit_num > 0')->where($sql8)->count();
        return $detail;
    }

    //客资查询
    function customerSearch($data){
        foreach($data as $k=>$v){
            if($v == 'undefined'){
                unset($data[$k]);
            }
        }
        $arr = [];
        $condition = [];
        $sql = " 1=1 ";
        if (!empty($data)) {
            if($data['more_like']){
                unset($data['add_shop_code']);
                unset($data['department_id']);
                unset($data['type_info']);
                unset($data['province_id']);
                unset($data['city_id']);
                unset($data['county_id']);
                unset($data['consultation_type_id']);
                unset($data['customer_intention_id']);
                unset($data['is_success']);
                unset($data['customer_cource_id']);
                unset($data['is_valid']);
                unset($data['is_fp']);
                // unset($data['is_loss']);
                unset($data['sign_id']);
                unset($data['get_contact']);
                unset($data['is_intostore']);
                unset($data['all_time']);
                unset($data['start_time']);
                unset($data['end_time']);
                unset($data['type_info']);
            }

            if(session('is_dig') == 1){
                if($data['department_id'])       $sql .= " and c.customer_channel_id = '".$data['department_id']."'";
            }else {
                if($data['department_id']){
                    $sql .= 'and c.dj_department_id='.$data['department_id'];
                }
            }

            //$sql .= " and customer_number = :customer_number ";  $arr['customer_number']=$data['customer_number'];
            if($data['add_shop_code'])       $sql .= " and c.add_shop_code = '".$data['add_shop_code']."' ";
            if($data['province_id'])       $sql .= " and c.province_id = '".$data['province_id']."' ";
            if($data['city_id'])       $sql .= " and c.city_id = '".$data['city_id']."' ";
            if($data['county_id'])       $sql .= " and c.county_id = '".$data['county_id']."' ";
            if($data['customer_number'])       $sql .= " and c.customer_number like '%".$data['customer_number']."%' ";
            if($data['customer_name'])         $sql .= " and c.customer_name like '%".$data['customer_name']."%' ";
            if($data['customer_tel'])          $sql .= " and c.customer_tel = '".$data['customer_tel']."' ";
            if($data['customer_wechat'])       $sql .= " and c.customer_wechat = '".$data['customer_wechat']."' ";
            if($data['customer_weibo'])        $sql .= " and c.customer_weibo = '".$data['customer_weibo']."' ";
            if($data['customer_qq'])           $sql .= " and c.customer_qq = '".$data['customer_qq']."' ";
            if($data['dj_staff_id'])           $sql .= " and c.dj_staff_id = '".$data['dj_staff_id']."' ";
            if($data['dj_staff_name'])         $sql .= " and c.dj_staff_name = '".$data['dj_staff_name']."' ";
            if($data['sk_staff_id'])           $sql .= " and c.sk_staff_id = '".$data['sk_staff_id']."' ";
            if($data['consultation_type_id'])  $sql .= " and c.consultation_type_id = '".$data['consultation_type_id']."' ";
            if($data['customer_intention_id']) $sql .= " and c.customer_intention_id = '".$data['customer_intention_id']."' ";
            if($data['is_success'])            $sql .= " and c.is_success = '".$data['is_success']."' ";
            if($data['customer_cource_id'])    $sql .= " and c.customer_cource_id = '".$data['customer_cource_id']."' ";
            if($data['op_signinfo'])           $sql .= " and c.op_signinfo = '".$data['op_signinfo']."' ";
            if($data['sales_staff_id'])        $sql .= " and c.sales_staff_id = '".$data['sales_staff_id']."' ";
            // if($data['is_valid'])              $sql .= " and is_valid in (".$data['is_valid'].") ";
            // if($data['is_loss'])               $sql .= " and is_loss = ".$data['is_loss']." ";
            if($data['is_success'])            $sql .= " and c.is_success = '".$data['is_success']."' ";
            if($data['brandclass'])            $sql .= " and c.brandclass = '".$data['brandclass']."' ";
            //if($data['op_signinfo_id'])        $sql .= " and op_signinfo_id = '".$data['op_signinfo_id']."' ";
            if($data['sign_id'])               $sql .= " and c.sign_id = '".$data['sign_id']."' ";

            // if($data['is_valid']) $sql .= " and c.is_valid in (".$data['is_valid'].") ";
            //2021-06-23 优化
            if($data['is_valid']){
                $is_valid = explode(",", trim($data['is_valid'],","));
                sort($is_valid);
                $sql .= " and c.is_valid in (".implode(",", $is_valid).") "; 
            } 

            // var_dump($sql);
            // exit;
            if($data['more_like']){
                $data['more_like'] = trim($data['more_like']);
                //
                if(config('search_use_full_text_index')){
                    $sql .= " and MATCH(c.customer_number,c.customer_name,c.customer_tel,c.customer_wechat,c.customer_qq,c.mate_name,c.mate_tel,c.mate_wechat,c.mate_qq,c.baby_name,c.order_number,c.channel_plan_number) AGAINST ('".$data['more_like']."*' in boolean mode) ";
                }else{
                    // $sql .= " and ( c.id=".intval($data['more_like'])." or c.customer_name like '%".$data['more_like']."%' or c.customer_tel like '%".$data['more_like']."%' or c.customer_qq like '%".$data['more_like']."%' or c.customer_wechat like '%".$data['more_like']."%' or c.mate_wechat like '%".$data['more_like']."%' or c.mate_tel like '%".$data['more_like']."%' or c.baby_name like '%".$data['more_like']."%' or c.customer_number like '%".$data['more_like']."%'  or c.order_number like '%".$data['more_like']."%' or c.customer_label like '%".$data['more_like']."%'or c.mate_name like '%".$data['more_like']."%') ";
                    // 20210223
                    // $sql .= " and c.customer_contact like '%".$data['more_like']."%' ";
                    //$sql .= " and ( c.id=".intval($data['more_like'])." or c.customer_name like '".$data['more_like']."%' or c.customer_tel like '".$data['more_like']."%' or c.customer_qq like '".$data['more_like']."%' or c.customer_wechat like '".$data['more_like']."%' or c.mate_wechat like '".$data['more_like']."%' or c.mate_tel like '".$data['more_like']."%' or c.baby_name like '".$data['more_like']."%' or c.customer_number like '".$data['more_like']."%'  or c.order_number like '".$data['more_like']."%' or c.mate_name like '".$data['more_like']."%') ";

                    //2021-11-09 优化
                    if(getChinese($data['more_like'])){ //全是中文
                        if (customize('gyztf')) {
                            $sql .= " and (c.customer_name = '".$data['more_like']."') ";
                        }else{
                            $sql .= " and (c.customer_name = '".$data['more_like']."' or c.mate_name = '".$data['more_like']."') ";
                        }
                    }else{

                        if (customize('gyztf')) {
                            if(is_numeric($data['more_like'])){ //是数字
                                if(strlen($data['more_like']) > 8){
                                    $sql .= " and ( c.customer_tel = '".$data['more_like']."' or c.customer_wechat = '".$data['more_like']."') ";
                                }else{
                                    $sql .= " and ( c.id=".intval($data['more_like'])." or c.customer_tel = '".$data['more_like']."' or c.customer_wechat = '".$data['more_like']."') ";
                                }
                            }else{ //其他
                                $sql .= " and ( c.customer_wechat = '".$data['more_like']."') ";
                            }
                        }else{
                            if(is_numeric($data['more_like'])){ //是数字
                                if(strlen($data['more_like']) > 8){
                                    $sql .= " and ( c.customer_tel = '".$data['more_like']."' or c.customer_wechat = '".$data['more_like']."' or c.mate_wechat = '".$data['more_like']."' or c.mate_tel = '".$data['more_like']."') ";
                                }else{
                                    $sql .= " and ( c.id=".intval($data['more_like'])." or c.customer_tel = '".$data['more_like']."' or c.customer_wechat = '".$data['more_like']."' or c.mate_wechat = '".$data['more_like']."' or c.mate_tel = '".$data['more_like']."') ";
                                }
                            }else{ //其他
                                $sql .= " and ( c.customer_wechat = '".$data['more_like']."' or c.mate_wechat = '".$data['more_like']."') ";
                            }
                        }
                    }  
                }
            }
            // var_dump($sql);die;
            if($data['customer_channel']){
                $inChannel = explode(',', $data['customer_channel']);
                // var_dump($inChannel);
                //员工绑定渠道后，只能看到绑定渠道的客资 管理员除外  20200428
                $trench = db('c_staff_trench_mate')->where('shop_code',session('shop_code'))->where('staff_id',session('staff_id'))->value('trench');
                if($trench && session('main_work_type') != SYSTEM_AUTH_ADMIN){
                    $channel = $this->getChannel();
                    $def_channel = '';
                    if(!empty($channel)){
                        foreach($channel as $k=>$v){
                            if (in_array($v['channel_name'],$inChannel)) {
                                $def_channel .= "'".$v['channel_name']."',";
                            }
                        }
                    }
                    if(!$def_channel){
                        $def_channel = "'nochannel'";
                    }
                    $sql .= " and c.customer_channel in (".trim($def_channel,',').')';
                }else{
                    $channel = "'".str_replace(',',"','",$data['customer_channel'])."'";
                    $sql .= " and c.customer_channel in (".$channel.") ";
                }
            }else{
                //员工绑定渠道后，只能看到绑定渠道的客资 管理员除外
                $trench = db('c_staff_trench_mate')->where('shop_code',session('shop_code'))->where('staff_id',session('staff_id'))->value('trench');
                if($trench && session('main_work_type') != SYSTEM_AUTH_ADMIN){
                    $channel = $this->getChannel();
                    $def_channel = '';
                    if(!empty($channel)){
                        foreach($channel as $k=>$v){
                           $def_channel .= "'".$v['channel_name']."',";
                        }
                    }
                    $sql .= " and c.customer_channel in (".trim($def_channel,',').')';
                }
            }

            if($data['get_contact']){
                switch($data['get_contact']){
                    case 'get_phone': $sql .=" and c.customer_tel <> '' and c.customer_tel is not null ";
                        break;
                    case 'only_phone': $sql .=" and c.customer_tel <> '' and c.customer_tel is not null and (customer_wechat is null or customer_wechat='') ";
                        break;
                    case 'get_wechat': $sql .=" and c.customer_wechat is not null and c.customer_wechat != '' ";
                        break;
                    case 'only_wechat': $sql .=" and c.customer_wechat is not null and c.customer_wechat != '' and (customer_tel is null or customer_tel='') ";
                        break;
                    case 'get_qq': $sql .=" and c.customer_qq is not null and c.customer_qq != 0 ";
                        break;

                }
            }

            if($data['is_fp']&&strpos($data['is_fp'],',')){
                $sql .= " and c.is_fp in (".$data['is_fp'].") ";
            }else if($data['is_fp']){
                $sql .= " and c.is_fp = '".$data['is_fp']."' ";
            }

            if($data['is_intostore']&&strpos($data['is_intostore'],',')){
                $sql .= " and c.is_intostore in (".$data['is_intostore'].") ";
            }else if($data['is_intostore']){
                $sql .= " and c.is_intostore = '".$data['is_intostore']."' ";
            }

            if($data['all_time']&&!empty($data['all_time'])){
                if($data['start_time'] && $data['end_time']){
                    // $sql .= " and c.".$data['all_time']." BETWEEN '".$data['start_time']." 00:00:00' ";
                    // $sql .= " and '".date('Y-m-d',strtotime($data['end_time'])-86400)." 23:59:59' ";
                    $sql .= " and c.".$data['all_time']." BETWEEN '".date('Y-m-d H:i:00', strtotime($data['start_time']))."' ";
                    $sql .= " and '".date('Y-m-d H:i:59',strtotime($data['end_time']))."' ";
                }elseif($data['start_time'] && !$data['end_time']){
                    $sql .= " and c.".$data['all_time']." > '".date('Y-m-d H:i:00', strtotime($data['start_time']))."' ";
                }elseif(!$data['start_time'] && $data['end_time']){
                    $sql .= " and c.".$data['all_time']." < '".date('Y-m-d H:i:59', strtotime($data['end_time']))."' ";
                }else{
                    //列表页时间
                    $list_date = db_config('list_date');
                    if($list_date == 'week'){
                        //当前日期
                        // $sdefaultDate = date("Y-m-d");
                        //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
                        // $first=1;
                        //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
                        // $w=date('w',strtotime($sdefaultDate));
                        //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
                        // $start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
                        //本周结束日期
                        $start = date('Y-m-d',strtotime('-1 week'));
                        $end=date('Y-m-d 23:59:59');
                    }elseif($list_date == 'month'){
                        $start=date('Y-m-01');
                        $end=date('Y-m-d 23:59:59');
                    }else{
                        $start=date('Y-m-d 00:00:00');
                        $end=date('Y-m-d 23:59:59');
                    }
                    $sql .= ' and  c.dj_day BETWEEN "'.date('Y-m-d H:i:s',strtotime($start)).'"';
                    $sql .= " and  '".date('Y-m-d H:i:s', strtotime($end))."'";
                }
            } else{
                if(!$data['more_like']){
                    //列表页时间
                    $list_date = db_config('list_date');
                    if($list_date == 'week'){
                        //当前日期
                        // $sdefaultDate = date("Y-m-d");
                        //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
                        // $first=1;
                        //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
                        // $w=date('w',strtotime($sdefaultDate));
                        //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
                        // $start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
                        //本周结束日期
                        $start = date('Y-m-d',strtotime('-1 week'));
                        $end=date('Y-m-d 23:59:59');
                    }elseif($list_date == 'month'){
                        $start=date('Y-m-01');
                        $end=date('Y-m-d 23:59:59');
                    }else{
                        $start=date('Y-m-d 00:00:00');
                        $end=date('Y-m-d 23:59:59');
                    }
                    $sql .= ' and  c.dj_day BETWEEN "'.$start.'"';
                    $sql .= " and  '".$end."'";
                    // $sql .= ' and  dj_day BETWEEN "'.date('Y-m',time()).'-01 00:00:00"';
                    // $sql .= " and  '".date('Y-m',time()).'-'.(date('d'))." 23:59:59'";
				}
            }
            // var_dump($sql);die;
            if($data['type_info'] && !empty($data['type_info'])){
                $arr = explode(',',$data['type_info']);
            }
            //小组
            // 详细地址
            if ($data['customer_address']) {
                $sql .= " and c.customer_address like '%".$data['customer_address']."%' ";
            }
            // 关键字
            if ($data['customer_key']) {
                $sql .= " and c.customer_key like '%".$data['customer_key']."%' ";
            }
            // 婚期
            if ($data['marry_day']) {
                $sql .= " and c.marry_day like '%".$data['marry_day']."%' ";
            }
            // 预算
            if ($data['budget']) {
                $sql .= " and c.budget like '%".$data['budget']."%' ";
            }
            // 再约时间
            if ($data['next_time']) {
                $sql .= " and c.next_time like '%".$data['next_time']."%' ";
            }
            // 客户备注
            if ($data['customer_remark']) {
                $sql .= " and c.customer_remark like '%".$data['customer_remark']."%' ";
            }
            // 追踪记录
            if ($data['track_record']) {
                $sql .= " and c.track_record like '%".$data['track_record']."%' ";
            }
            // 是否加急
            if ($data['is_urgent'] == '是') {
                $sql .= " and c.is_urgent = 1";
            }else if ($data['is_urgent'] == '否') {
                $sql .= " and c.is_urgent = 2";
            }
            // 订单号
            if ($data['order_number']) {
                $sql .= " and c.order_number = '".$data['order_number']."' ";
            }
            // 订单金额
            if ($data['totalpay_money']) {
                $sql .= " and c.totalpay_money = '".$data['totalpay_money']."' ";
            }
            // 实收金额
            if ($data['fact_money']) {
                $sql .= " and c.fact_money = '".$data['fact_money']."' ";
            }
            // 不在追踪原因
            if ($data['loss_cause']) {
                $sql .= " and c.loss_cause like '%".$data['loss_cause']."%' ";
            }
            // 筛客人
            if ($data['sk_staff']) {
                $sql .= " and c.sk_staff = '".$data['sk_staff']."' ";
            }
            // 分配人
            if ($data['fp_staff']) {
                $sql .= " and c.fp_staff = '".$data['fp_staff']."' ";
            }
            // 老顾客姓名
            if ($data['introducer_name']) {
                $sql .= " and c.introducer_name = '".$data['introducer_name']."' ";
            }
            // 老顾客电话
            if ($data['introducer_tel']) {
                $sql .= " and c.introducer_tel = '".$data['introducer_tel']."' ";
            }
            // 老顾客单号
            if ($data['introducer_ordernum']) {
                $sql .= " and c.introducer_ordernum like '%".$data['introducer_ordernum']."%' ";
            }
            // 电访量
            if ($data['tel_visit_num']) {
                $sql .= " and c.tel_visit_num = '".$data['tel_visit_num']."' ";
            }
            // 最后追踪时间
            if ($data['last_trackday']) {
                $sql .= " and c.last_trackday like '%".$data['last_trackday']."%' ";
            }
            // 接单点
            if ($data['customer_orderaddress']) {
                $sql .= " and c.customer_orderaddress like '%".$data['customer_orderaddress']."%' ";
            }
            // 客户分区
            if ($data['customer_area']) {
                $sql .= " and c.customer_area like '%".$data['customer_area']."%' ";
            }
            // 客资标签
            if ($data['customer_label']) {
                $sql .= " and c.customer_label like '%".$data['customer_label']."%' ";
            }
            // 推广编号
            if ($data['channel_plan_number']) {
                $sql .= " and c.channel_plan_number like '%".$data['channel_plan_number']."%' ";
            }
            // 微信添加状态
            if ($data['wechat_status'] || $data['wechat_status']==='0') {
            	$sql .= " AND wechat_status=".$data['wechat_status'];
            }
            if(count($arr)){
                foreach($arr as $k => $v){
                    $res = explode('=',$v);
                    $condition[$res[0]][] = $res[1];
                }
            }

            if(count($condition)){
                foreach($condition as $k => $v){
                    if($k == 'dj_group_id' || $k == 'sales_group_id'){
                        $arr='"'.implode('","',$v).'"';//给每个元素添加引号
                        $sql .= " and f.{$k} in ($arr) ";
                    }else{
                        $arr='"'.implode('","',$v).'"';//给每个元素添加引号
                        $sql .= " and c.{$k} in ($arr) ";
                    }
                }
            }
            // if($data['tab']&&$data['tab'] != 1){
            //     $res = db('s_customer_tab')->where('id',$data['tab'])->find();
            //     $info = json_decode($res['sql'],true);
            //     $sql .= $info['where'];
            // }
            if($data['tab']&&$data['tab']==2){//待追踪
                // $sql .= " and c.is_fp = 1 and c.c_star_day is null and c.is_intostore = 1 and c.is_valid in (1,2) and c.is_loss = 2 ";
                $sql .= " and c.is_fp = 1 and c.c_star_day is null and c.is_intostore = 1 and c.is_loss = 2 ";
            }elseif($data['tab']&&$data['tab']==3){//待分配
                if(session('is_sk')==1){
                    $sql .= " and c.is_fp in (2,4) and c.is_already_sk=1 ";
                }else{
                    $sql .= " and c.is_fp in (2,4) ";
                }
            }elseif($data['tab']&&$data['tab']==4){//追踪中
                // $sql .= " and c.is_fp = 1 and c.is_loss=2 and c.c_star_day is not null and c.is_intostore = 1 and c.is_valid in (1,2) and c.is_success=2 ";
                $sql .= " and c.is_fp = 1 and c.is_loss=2 and c.c_star_day is not null and c.is_intostore = 1 and c.is_success=2 ";
            }elseif($data['tab']&&$data['tab']==5){//成单
                $sql .= " and c.is_success in (1,3) ";
            }elseif($data['tab']&&$data['tab']==6){//进店未成单
                $sql .= " and c.is_success = 2 and c.is_intostore in (2,3,5)";
            }
            // elseif($data['tab']&&$data['tab']==7){//流失
            //     $sql .= " and is_loss = 1 ";
            // }
            elseif($data['tab']&&$data['tab']==8){//待筛客
                $sql .= " and c.is_sk = 1 and c.is_already_sk = 2 ";
            }elseif($data['tab']&&$data['tab']==9){//已筛客
                $sql .= " and c.is_sk = 1 and c.is_already_sk = 1 ";
            }
            //当日接收
            elseif($data['tab']&&($data['tab']==10)){
                $start = date('Y-m-d 00:00:00');
                $end   = date('Y-m-d 23:59:59');
                $sql .= " and  c.jr_day between '".$start."' and '".$end."'";
                // $sql .= " and  to_days(jr_day) = to_days(now())";
            }
            //三日内追踪
            elseif($data['tab']&&($data['tab']==11)){
                $start = date('Y-m-d 00:00:00', strtotime('-3 day'));
                $end   = date('Y-m-d');
                $sql .= " and  c.last_trackday between '".$start."' and '".$end."'";
            }
            //、当日预进店 三日内预进店
            elseif($data['tab']&&($data['tab']==12)){
                $start = date('Y-m-d 00:00:00');
                $end   = date('Y-m-d 23:59:59',strtotime('+ 2days'));
                $sql .= " and c.yjd_day between '".$start."' and '".$end."'";
            }
            //有效客资
            elseif($data['tab']&&($data['tab']==13)){
                $sql .= " and c.is_valid=1 ";
            }
            //无效客资
            elseif($data['tab']&&($data['tab']==14)){
                $sql .= " and c.is_valid=3 ";
            }
            /*
            //待定客资
            
            //驳回客资
            elseif($data['tab']&&($data['tab']==16)){
                $sql .= " and  c.is_valid=4 ";
            }
            //过期客资
            elseif($data['tab']&&($data['tab']==18)){
                //客资过期时间
                $key = 'brand_valid_date_'.md5(session('brandclass'));
                $valid_date = cache('?'.$key);
                if(!$valid_date){
                    $info = sx_call('5a3bbb5d0988d',['brandclass'=>session('brandclass')]);
                    if($info['code'] == 200){
                        $valid_date = $info['data'][0]['valid_date'];
                        cache($key,$valid_date,1800);
                    }else{
                        $valid_date = 60;
                    }
                }else{
                    $valid_date = cache($key);
                }
                if($valid_date == 0){
                    $valid_date = 60;
                }
                $lastDate = date('Y-m-d H:i:s',time() - ($valid_date * 86400));
                //客资过期判定规则
                $rule = db_config('valid_date_rule');
                $rule = $rule ? $rule : 'dj_day';
                $sql .= " and  c.$rule < '".$lastDate."'";
            }*/
            // 今日需追踪
            elseif($data['tab'] && ($data['tab'] == 17)){
                $start = date('Y-m-d 00:00:00');
                $end   = date('Y-m-d 23:59:59');
                 $sql .= " and c.is_loss=2 and c.is_success=2 and (c.next_time is not null and c.next_time  <'".$end."' AND DATE_FORMAT(c.last_trackday, '%Y-%m-%d') < DATE_FORMAT(c.next_time, '%Y-%m-%d') OR ( c.c_star_day IS NULL) )  ";
                // 似乎这个才是正确的 eric1123
                // $sql .= " and is_loss=2 and ( next_time <= '".$start."' AND last_trackday < next_time OR ( c_star_day IS NULL) )  ";
                // $sql .= " and is_loss=2 and is_success=2 and ( next_time <= '".$end."' AND last_trackday < '".date('Y-m-d')."' OR ( c_star_day IS NULL) )  ";
                // $sql .= " and is_loss=2 and is_success=2 and ( next_time <= '".$end."' AND last_trackday < '".date('Y-m-d')."' OR ( c_star_day IS NULL) )  ";
            }elseif($data['tab'] && ($data['tab'] == 19)){ // 已加好友时间
                $sql .= " and c.add_friend_time is not null ";
            }
        }
        
        if($data['group']){
            $ids = getGroupStaffIds(session('staff_id'));
            $ids = implode(',',$ids);
            $sql .= " and (c.sk_staff_id in ($ids) or c.dj_staff_id in ($ids) or c.sales_staff_id in ($ids))";
        }
        if($data['dep']){
            $sql .= ' and (c.dj_department_id='.session('department_id').' or c.sales_department_id='.session('department_id').')';
        }
        // 流失 不在追踪  eric 20181106
        if($data['tab']&&$data['tab']==7){
            $sql .= " and c.is_loss = 1 ";
        }else{
            if ($data['is_loss'] != 1) {
                //查询不含不再追踪的客资
                $sql .= " and c.is_loss = 2 ";
            }
            // else if(!$data['is_valid'] || $data['is_valid'] == ''){
            //     $sql .= " and is_loss = 1 ";
            // }
            /*
            if ($data['is_loss'] == 1) {
                //查询时，显示不在追踪的客资，也就是不管追踪状态是什么，该怎么查就怎么查
                if($data['is_valid']){
                    //$sql .= " and (is_valid in (".$data['is_valid'].") or is_loss=1 ) ";
                    $sql .= " and is_valid in (".$data['is_valid'].") ";
                }
                else{
                    $sql .= " and is_loss = 1 ";
                }
            }else{
                //查询时，如果不再追踪的客资不显示

                //if($data['is_loss'])  $sql .= " and is_loss = 2";
                $sql .= " and is_loss = 2";
            }*/
        }
        //列表页查询是否包含erp客资设定
        $list_search_is_in_erp = db_config('list_search_is_in_erp');
        if($list_search_is_in_erp != 1){
            $sql .= ' and c.c_from=1 ';
        }
        $sql .= " and c.is_status = 1 and c.is_examine=1 ";
        // $sql .= " and is_status = 1 and is_act=1 ";
        return $sql;
    }

    //所有客资
    function allCrm($staffId){
        $res = db('CCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_status'=>1))->count();
        return $res;
    }
    //已订单
    function orderCrm($staffId){
        $res = db('CCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_success'=>1,'is_status'=>1))->count();
        return $res;
    }
    //待追踪
    function noStaffId($staffId){
        // $res = db('CCustomerinfo')->where(array('dj_staff_id'=>$staffId['staff_id'],'c_star_day'=>null,'is_fp'=>1,'is_status'=>1))->where('dj_day','between',[$staffId['start_day'],$staffId['end_day']])->count();
        $res = db('CCustomerinfo')
            ->where(array('c_star_day'=>null,'is_fp'=>1,'is_status'=>1))
            ->where('jr_day','between',[$staffId['start_day'],$staffId['end_day']])
            ->where('sales_staff_id','in',$staffId['staff_id'])
            ->group('sales_staff_id')
            ->column('count(id) as num,sales_staff_id','sales_staff_id');
            // ->select();
        // echo db()->getLastSql();die;
        return $res;
    }
    // 接收的客资数量
    public function jrCustomers($param){
        $where = [
            'is_status' => 1,
            'c_from'    => 1,
            'is_fp'     => 1,
            'brandclass_id' => session('brandclass_id'),
        ];
        $res = db('c_customerinfo')
            ->where($where)
            ->where('shop_code', $param['shop_code'])
            ->where('jr_day','between',[$param['start_day'],$param['end_day']])
            ->where('sales_staff_id','in',$param['staff_id'])
            ->group('sales_staff_id')
            ->column('count(id) as num,sales_staff_id','sales_staff_id');
        // echo db()->getLastSql();
        return $res;
    }
    // 筛客人接收到的客资数量
    public function skCustomers($param){
        $where = [
            'is_status' => 1,
            'c_from'    => 1,
            'brandclass_id' => session('brandclass_id'),
        ];
        $res = db('c_customerinfo')
            ->where($where)
            ->where('dj_day','between',[$param['start_day'],$param['end_day']])
            ->where('sk_staff_id','in',$param['staff_id'])
            ->group('sk_staff_id')
            ->column('count(id) as num,sk_staff_id','sk_staff_id');
        // echo db()->getLastSql();
        return $res;
    }
    //待分配
    function noFp($staffId){
        $res = db('CCustomerinfo')->where('dj_staff_id',$staffId)->where('is_fp','in','2,4')->where('is_status',1)->count();
        return $res;
    }

    //追踪中
    function traking($staffId){
        $res = db('CCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_success'=>2,'is_fp'=>1,'is_status'=>1))->count();
        return $res;
    }

    //进店未订单
    function jdwdCrm($staffId){
        $data['dj_staff_id']=$staffId;
        $data['is_intostore']=array('in','2,3');
        $data['is_success']=2;
        $res = db('CCustomerinfo')->where($data)->count();
        return $res;
    }
    //mc地址查询
    function mcAddress($data){
        if(empty($data)){
            return false;
        }
        $url="59fd885ed3628";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $detail=$res['data'];
        }
        return $detail;
    }
    //客户地址查询
    function address($data){
        if(empty($data)){
            return false;
        }
        // $url="59fd885ed3628";
        // $res=sx_call($url,$data);
        // if($res['code']==200){
        //     $detail=$res['data'];
        // }
        if(!$data['shop_code']){
            $data['shop_code'] = session('shop_code');
        }
        //取crm设定的省市区
        $detail = db('s_shop_address')->where($data)->select();

        return $detail;
    }
    //查询crm地址
    function crm_address($data){
        $detail = db('s_address')->where($data)->select();

        return $detail;
    }
    //客户地址模糊查询
    function getAddressByLike($param){
        if(empty($param)){
            return false;
        }
        if(!$param['shop_code']){
            $data['shop_code'] = session('shop_code');
        }
        if($param['name']){
            $name='name like :name';
            $nameArray=['name'=>$param['name'].'%'];
        }
        if((int)$param['type']){
            $data['type'] = (int)$param['type'];
        }
        if((int)$param['pid']){
            $data['pid'] = (int)$param['pid'];
        }
        //取crm设定的省市区
        $detail = db('s_shop_address')->where($name,$nameArray)->where($data)->select();
        return $detail;
    }
    //客户地址查询
    function getCity($data){
        $mc = new \app\common\lib\mcInterface();
        return  $mc->cacheData('59fd885ed3628',$data);
        /*
        $url="59fd885ed3628";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $detail=$res['data'];
        }
        return $detail;*/
    }
    //通过省id获取地域
    function getRegionByProvinceId($data){
        $mc = new \app\common\lib\mcInterface();
        return  $mc->cacheData('5a704aa96e503',$data);

        // $url="5a704aa96e503";
        // $res=sx_call($url,$data);
        // if($res['code']==200){
        //     $detail=$res['data'];
        // }
        // return $detail;
    }
    //店面查询
    function shop($data){
        $mc = new \app\common\lib\mcInterface();
        return  $mc->getShops($data);

        // $url="5a005e0038270";
        // $res=sx_call($url,$data);
        // if($res['code']==200){
        //     $detail=$res['data'];
        // }
        // return $detail;
    }

    //获取任职某一店面下岗位的员工，包括兼职岗位
    function getShopAllStaff($data){
        $mc = new \app\common\lib\mcInterface();
        return  $mc->cacheData('5a7424f13aa54',$data);
        
        // $detail = cache('shopAllStaffs_'.$data['shop_code']);
        // if(empty($detail)){
        //     $url="5a7424f13aa54";
        //     $res=sx_call($url,$data);
        //     if($res['code']==200){
        //         $detail=$res['data'];
        //         cache('shopAllStaffs_'.$data['shop_code'],$detail);
        //     }
        // }

        return $detail;
    }

    /**
     * 发送模板消息
     * @param Integer  $content json格式模板消息内容
     * @param String  $brandclass_id 品牌id
     * @param String   $shop_code 店面唯一识别码
     * @author {wangyining}<{wangyining@suxuantech.cn}> 2017-10-17 $
     */
    function sendMsg($data){
        $mc = new \app\common\lib\mcInterface();
        return  $mc->cacheData('5a4b81bc26160',$data);

        // $url="5a4b81bc26160";
        // $res=sx_call($url,$data);
        // if($res['code']==200){
        //     $detail=$res['data'];
        // }
        // return $detail;
    }

    /**
     * 发送模板消息  20181103
     * @param staffname
     * @param shop_code
     *
     * @return array
     */
    public function getStaffInfoByName($param){
        $info = cache('staffname_'.$param['staffname']);
        if (!$info) {
            $url = '5a01766b4a3dd';
            $res = sx_call($url,$param);
            if($res['code']==200){
                $info = $res['data'];
                cache('staffname_'.$param['staffname'], $info);
            }else{
                $info = [];
            }
        }
        return $info;
    }

    //获取必填项对应id
    public function get_set_id($data,$add_shop_code,$shop_code){
        // $channel=cache('crm_channel_'.$add_shop_code);//客户渠道
        $channel = getChannels(['shop_code'=>$add_shop_code]);
        $consultation_type=cache('crm_consultation_type_'.$data['brandclass_id']);//消费类型
        $access_model=cache('crm_access_model');//获取方式
        $source=cache('crm_source');//客户来源
        $intention=cache('crm_intention');//客户意向
        $area=cache('crm_area');//分区
        $region=cache('crm_region');//地域
        $orderAddress=cache('crm_orderAddress');//接单点
        $address=cache('crm_address');
        $consulation_shop=cache('crm_consulation_shop');

        if(isset($data['sales_staff']) && !empty($data['sales_staff'])){
            $p['shop_code'] = $shop_code;
            $p['work_type'] = RECEIVE_WORK_TYPE;
            $staffs = getShopStaffs($p);
            $temp = [];
            foreach($staffs as $k=>$v){
                $temp[$v['staffname']] = $v;
            }
            if(!empty($temp[$data['sales_staff']])){
                $ids['sales_staff_id']    = $temp[$data['sales_staff']]['id'];
                $ids['sales_staff_number']= $temp[$data['sales_staff']]['staffnumber'];
                unset($p,$staffs,$temp);
            }else{
                $ids['sales_staff_id']=null;
                $ids['sales_staff_number']='';
            }
        }else{
            $ids['sales_staff_id']=null;
            $ids['sales_staff_number']='';
        }

        if($data['customer_channel']){
            // if(!$channel){
            //     $channel=db('s_channel')->where('shop_code',$add_shop_code)->select();
            //     cache('crm_channel_'.$add_shop_code,$channel);
            // }
            foreach($channel as $key => $val){
                if($data['customer_channel']==$val['channel_name']){
                    $ids['customer_channel_id']=$val['id'];
                }
            }
        }

        if($data['consultation_type']){
            if(!$consultation_type){
                $consultation_type=$this->consumptionType();
                cache('crm_consultation_type_'.$data['brandclass_id'],$consultation_type);
            }
            foreach($consultation_type as $k => $v){
                if($data['consultation_type']==$v['consumption_name']){
                    $ids['consultation_type_id']=$v['id'];
                }
            }
        }

        if($data['access_model']){
            if(!$access_model){
                $access_model=$this->accessModel();
                cache('crm_access_model',$access_model);
            }
            foreach ($access_model as $k => $v ) {
                if($data['access_model']==$v['accessmodel']){
                    $ids['access_model_id']=$v['id'];
                }
            }
        }
        if($data['customer_cource']){//来源
            if(!$source){
                $source=$this->source();
                cache('crm_source',$source);
            }
            foreach($source as $k => $v){
                if($data['customer_cource']==$v['cus_name']){
                    $ids['customer_cource_id']=$v['id'];
                }
            }
        }
        if($data['customer_intention']){//客户意向
            if(!$intention){
                $intention=$this->intention();
                cache('crm_intention',$intention);
            }
            foreach($intention as $k => $v){
                if($data['customer_intention']==$v['intention_name']){
                    $ids['customer_intention_id']=$v['id'];
                }
            }
        }
        if($data['customer_area']){
            if(!$area){
                $area=$this->areaSet();
                cache('crm_area',$area);
            }
            foreach($area as $k => $v){
                if($data['customer_area']==$v['area_name']){
                    $ids['customer_area_id']=$v['id'];
                }
            }
        }
//        if($data['customer_region']){
//            if(!$region){
//                $region=$this->region();
//                cache('crm_region',$region);
//            }
//            foreach($region as $k => $v){
//                if($data['customer_region']==$v['region_name']){
//                    $ids['customer_region_id']=$v['id'];
//                }
//            }
//        }
        if($data['customer_orderaddress']){
            if(!$orderAddress){
                $orderAddress=$this->orderAddress();
                cache('crm_orderAddress',$orderAddress);
            }
            foreach($orderAddress as $k => $v){
                if($data['customer_orderaddress']==$v['acceptoraddress_name']){
                    $ids['customer_orderaddress_id']=$v['id'];
                }
            }
        }

        //意向店面，所有非营销店
        if($data['consulation_shop']){
            $mc = new \app\common\lib\mcInterface();
            $consulation_shop=  $mc->getShops(array('is_marketing'=>2));
            foreach($consulation_shop as $k => $v){
                if($data['consulation_shop']==$v['shop_name']){
                    $ids['consulation_shop_code']=$v['shop_code'];
                }
            }
        }

        if(!$address){
//            $address=$this->getCity();
//            $address=$this->address();
            $url="59fd885ed3628";
            $res=sx_call($url,[]);
            if($res['code']==200){
                $address=$res['data'];
                cache('crm_address',$address);
            }
        }
        if($data['province']){
            foreach($address as $k => $v){
                if($data['province']==$v['name']){
                    $ids['province_id']=$v['id'];
                    $pid=$v['pid'];
                }
            }

            if(!$region){
                $region=$this->region();
                cache('crm_region',$region);
            }
            foreach($region as $k => $v){
                if($v['id']==$pid){
                    $ids['customer_region_id']=$pid;
                    $ids['customer_region']=$v['region_name'];
                }
            }


        }
        if($data['city']){
            foreach($address as $k => $v){
                if($data['city']==$v['name']){
                    $ids['city_id']=$v['id'];
                }
            }
        }
        if($data['county']){
            foreach($address as $k => $v){
                if($data['county']==$v['name']){
                    $ids['county_id']=$v['id'];
                }
            }
        }
        cache('ids',$ids);
        return $ids;
    }

    //验证手机号和名字重复
    function checkNameTel($param){
        $count = db("c_customerinfo")->where('customer_tel',$param['customer_tel'])->count();
        return $count;
    }
    //查询归属店是否筛客
    public function is_sk($belong_shop_code){
        $mc = new \app\common\lib\mcInterface();
        $info = $mc->cacheData('5a39fd8c6c9f7',['shop_code'=>$belong_shop_code]);
        return $info[0]['is_sk'];
        // $info = sx_call('5a39fd8c6c9f7',['shop_code'=>$belong_shop_code]);
        // return $info['data'][0]['is_sk'];
    }
    //筛客人列表
    public function sklist($param,$workType = 24){
        $param = !empty($param) ? $param : session('shop_code').','.session('belong_shop_code');
        // $url = '5a1510583e3a5';
        $url = '5b75341456d18';
        $data['shop_code'] = $param ? $param : session('shop_code');
        $data['work_type'] = $workType;
        $res = sx_call($url,$data);
        if($res['code'] == 200){
            return $res['data'];
        }else{
            return false;
        }
    }
    // consultation_type_id : 消费类型
    public function isRepeat($brandclass,$tel,$wechat,$qq,$mate_tel,$id=0,$consultation_type_id='',$shop_code = ''){
        //判断 mc客资有效期配置 为空的话 不限制
        //客资过期时间
        $key = 'brand_valid_date_'.md5($brandclass);
        $valid_date = cache($key);
        if(!$valid_date){
            $info = sx_call('5a3bbb5d0988d',['brandclass'=>$brandclass]);
            if($info['code'] == 200){
                $valid_date = $info['data'][0]['valid_date'];
                cache($key,$valid_date,86400);
            }else{
                $valid_date = 60;
            }
        }
        if ($valid_date === null || $valid_date === '') {
            return array('code'=>200,'msg'=>'mc客资有效期配置 为空 不限制','data'=>[]);
        }
        $brandclass = $brandclass ? $brandclass : session('brandclass');
        $array=array();

        if($tel){
            $contact[] = $tel;
        }
        if($qq){
            $contact[] = $qq;
        }
        if($wechat){
            $contact[] = $wechat;
        }
        if($mate_tel){
            $contact[] = $mate_tel;
        }
        if(!$contact){
            return array('code'=>201,'msg'=>'缺少联系方式','data'=>[]);
        }

        $sql1 = " 1=1 ";
        $sql1s = " 1=1 ";
        if($id){
            $sql1 .= ' and (c_id is null or c_id <> '.$id.') ';
            $sql1s .= ' and (id is null or id <> '.$id.') ';
        }
        $c_ids = db('c_customer_contact')->where($sql1)->where('contact','in',$contact)->where('brandclass',$brandclass)
            ->order('id desc')->column('c_id');

        if(empty($c_ids)){
            return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
        }else{
            /*if($id){
                $customerinfo_res = db('c_customerinfo')->field('consultation_type_id')->where('id',$id)->where('customer_tel|customer_wechat|customer_qq|mate_tel','in',$contact)->find();
                if ($customerinfo_res) {
                    return array('code'=>200,'msg'=>'客资本身，可以录入','data'=>'');
                }
            }*/

            //是否店内排重
            $shop_repeat = config('shop_repeat');

            //判断 不同消费类型的客资，是否可以重复
            $shop_code = $shop_code ? $shop_code : session('shop_code');
            $cus_valid = db_config('cus_validdate_'.$shop_code);
            if ($cus_valid == 1 && $consultation_type_id > 0) {
                if($shop_repeat){
                    $sql1s .= " and add_shop_code='".$shop_code."' ";
                }
                $ros = db('c_customerinfo')->field('id,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_name,customer_number,mate_tel,dj_day,add_shop_name,dj_staff,sales_staff_id,sales_staff,shop_name,is_success,customer_channel,is_fp,is_valid,is_intostore,c_star_day,brandclass_id,brandclass,is_loss,consultation_type_id')->where('is_status',1)->where('is_examine', '1')->where($sql1s)->where('customer_tel|customer_wechat|customer_qq|mate_tel','in',$contact)->where('consultation_type_id',$consultation_type_id)->find();
                if ($ros) {
                    return array('code'=>201,'msg'=>'客资重复，不可录入','data'=>$ros);
                }else{
                    return array('code'=>200,'msg'=>"设置了 不同资讯类型的客资，可以重复",'data'=>[]);
                }
            }            
            foreach($c_ids as $k=>$c_id){
                if(!$c_id){
                    unset($c_ids[$k]);
                }
            }
            if(empty($c_ids)){
                return array('code'=>201,'msg'=>'客资有重复，但未找到客资编号','data'=>[]);
            }

            //取排重范围状态
            $unrepeatStatus = db_config('unrepeat_status');
            if($unrepeatStatus){
                $unrepeatStatus = explode(',', $unrepeatStatus);
            }else{
                $unrepeatStatus = [];
            }
            $whereRepeat = [];
            if(in_array('unvalid', $unrepeatStatus)){
                $whereRepeat['is_valid'] = ['<>',3];
            }
            if(in_array('lossed', $unrepeatStatus)){
                $whereRepeat['is_loss'] = 2;
            }
            if(in_array('is_success', $unrepeatStatus)){
                $whereRepeat['is_success'] = 2;
            }
            if($shop_repeat){
                $whereRepeat['add_shop_code'] = $shop_code;
            }
            if ($cus_valid == 1 && $consultation_type_id > 0) {
                $whereRepeat['consultation_type_id'] = $consultation_type_id;
            }

            $sql = ' 1=1 ';

            // 根据排重范围查询客资
            // $order = db('c_customerinfo')->where('id','in',$c_ids)->order('id desc')->find();
            if($valid_date == 0){//为0,则永不过期
                $arr= db("c_customerinfo")
                    ->field('id,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_name,customer_number,customer_channel,mate_tel,dj_day,add_shop_name,dj_staff,sales_staff_id,sales_staff,shop_name,is_success,is_fp,is_valid,is_intostore,c_star_day,brandclass_id,brandclass,is_loss')->where($whereRepeat)->where('id','in',$c_ids)->where('is_status',1)->where('is_examine', '1')->master()->find();
                if(!empty($arr)){
                    return array('code'=>201,'msg'=>'已设置为永不过期,不可录入','data'=>$arr);
                }else{
                    return array('code'=>200,'msg'=>'可以录入','data'=>'');
                }
            }

            $lastDate = date('Y-m-d H:i:s',time() - ($valid_date * 86400));
            //客资过期判定规则
            $rule = db_config('valid_date_rule');
            $rule = $rule ? $rule : 'dj_day';
            $where = ' '.$rule.' is null or '.$rule.' > \''.$lastDate.'\'';
            $arr= db("c_customerinfo")
                ->field('id,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_name,customer_number,mate_tel,dj_day,add_shop_name,dj_staff,sales_staff_id,sales_staff,shop_name,is_success,customer_channel,is_fp,is_valid,is_intostore,c_star_day,brandclass_id,brandclass,is_loss')->where('id','in',$c_ids)->where('is_status',1)->where('is_examine', '1')->where($where)->where($whereRepeat)->master()->order('id desc')->find();
            $sql = db()->getLastSql();
            if($arr){
                return array('code'=>201,'msg'=>'未过有效期,不能录入','data'=>$arr);
            }else{
                $valid_date_notice = db_config('valid_date_notice');
                if($valid_date_notice) { //客资过期是否提示
                    return array('code'=>205,'sql'=>$sql,'msg'=>'与该联系方式重复的客资已过期,可以录入');
                }else{
                    return array('code'=>200,'sql'=>$sql,'msg'=>''.db()->getLastSql(),'data'=>''.json_encode($arr));
                }
            }

        }
    }


    public function isContactRepeat($brandclass,$tel,$wechat,$qq,$mate_tel){
        $array=array();
        if($tel)         $array['tel']=$tel;
        if($wechat)      $array['wechat']=$wechat;
        if($qq)          $array['qq']=$qq;
        if($mate_tel)    $array['mate_tel']=$mate_tel;

        $sql=implode(',',$array);
        $arr=db('c_customer_contact')->where('brandclass',$brandclass)->where('contact','in',$sql)->select();
        //$a=db()->getLastSql();
        return $arr;
    }

    // 客资录入
    function addCustomer($data){
        // var_dump($data);exit; 
        //转介绍次数
        testTime(__FILE__,__LINE__);
        if($data['customer_type'] == 2){
            if(empty($data['customer_channel_id'])){
                $data['customer_channel_id'] = -1;
            }
            if(empty($data['customer_channel'])){
                $data['customer_channel'] = '空渠道';
            }

            $num = db_config('zhuanjieshao_number_'.session('shop_code'));
            if ($num > 0) {
                $count = db('c_customerinfo')->where('introducer_tel',$data['introducer_tel'])->where('dj_day','between',[date('Y-m-d'),date('Y-m-d 23:59:59')])->count();
                if( !empty($data['introducer_tel']) && $num && $count>$num){
                    return array('code'=>121,'msg'=>'今天转介绍次数已达上限,不能提报');
                }
            }
        }
        if(!$data['dj_staff_id']){
            return array('code'=>100,'msg'=>'未获取到追踪人，无法保存。');
        }
        testTime(__FILE__,__LINE__);
        $data['customer_name'] = trim(strip_tags($data['customer_name']));
        $data['customer_tel']  = trim($data['customer_tel']);
        $data['customer_wechat']= trim(strip_tags($data['customer_wechat']));
        $data['customer_qq']    = trim(strip_tags($data['customer_qq']));
        $data['customer_weibo'] = trim(strip_tags($data['customer_weibo']));
        $data['customer_idnumber'] = trim(strip_tags($data['customer_idnumber']));

        $data['mate_name']  = trim(strip_tags($data['mate_name']));
        $data['mate_tel']   = trim($data['mate_tel']);
        $data['mate_wechat']= trim(strip_tags($data['mate_wechat']));
        $data['mate_qq']    = trim(strip_tags($data['mate_qq']));
        $data['mate_weibo'] = trim(strip_tags($data['mate_weibo']));
        $data['mate_idnumber']=trim(strip_tags($data['mate_idnumber']));

        $data['customer_address'] = trim(strip_tags($data['customer_address']));
        $data['customer_key'] = trim(strip_tags($data['customer_key']));
        $data['budget'] = trim(strip_tags($data['budget']));
        $data['customer_remark'] = trim(strip_tags($data['customer_remark']));
        $data['ad_page'] = trim(strip_tags($data['ad_page']));

        $data['dj_day']=date('Y-m-d H:i:s',time());
        $data['yx_day']=date('Y-m-d H:i:s',time());
        $data['creator_day']=date('Y-m-d H:i:s',time());
        $is_send_msg = $data['is_send_msg'];
        $sms_model = $data['sms_model'];
        unset($data['is_send_msg']);
        unset($data['sms_model']);
        if(!$data['create_time'])   $data['create_time']=date('Y-m-d H:i:s',time());
        if($data['customer_tel']){//录入时是否获取手机号
            $data['tel_staff_id']=$data['dj_staff_id'];
            $data['tel_staff']=$data['dj_staff'];
            $data['tel_time']=date('Y-m-d H:i:s',time());
            $data['is_first_tel']=1;
        }
        if($data['customer_wechat']){//录入时是否获取微信
            $data['wechat_staff_id']=$data['dj_staff_id'];
            $data['wechat_staff']=$data['dj_staff'];
            $data['wechat_time']=date('Y-m-d H:i:s',time());
            $data['is_first_wechat']=1;
        }
        if($data['customer_qq']){//录入时是否获取QQ
            $data['qq_staff_id']=$data['dj_staff_id'];
            $data['qq_staff']=$data['dj_staff'];
            $data['qq_time']=date('Y-m-d H:i:s',time());
            $data['is_first_qq']=1;
        }
        if($data['sign_id']){
            $data['sign_time'] = date('Y-m-d H:i:s',time());
        }
        $dj=getStaffInfoById($data['dj_staff_id']);
        testTime(__FILE__,__LINE__);
        if($data['sales_staff_id']){
            $sales=getStaffInfoById($data['sales_staff_id']);
            $fp_day = date('Y-m-d H:i:s',time());
            $data['fp_day']=$fp_day;
            $data['jr_day']=$fp_day;
            //如果要传了追踪人，追踪部门和追踪部门名称要取传过来的，不取员工的，因为考虑兼职情况
            // $data['sales_department_id']= $sales['department_id'];
            // $data['sales_department_name']= $sales['department_name'];
            $data['sales_staff']=$data['sales_staff'] ? $data['sales_staff'] : $sales['staffname'];
            $data['sales_staff_number']=$sales['staff_number'] ? $sales['staff_number'] : $sales['staffnumber'];
            $data['is_fp']=1;
            $data['fp_staff_id']=$data['dj_staff_id'];//分配人id
            $data['fp_staff']=$data['dj_staff'];
            $data['fp_staff_number']=$data['dj_staff_number'];
            $data['fp_department_id'] = $dj['department_id'];
            $data['fp_department_name'] = $dj['department_name'];
        }
        if($data['dj_department_id']){
            $data['dj_department_name'] = $dj['department_name'];
        }else{
            $data['dj_department_id'] = $dj['department_id'];
            $data['dj_department_name'] = $dj['department_name'];
        }
        //提报类型（1：新客；门市提交2：现客；非门市提交3：老客;erp传来的接口，订单已成交的,现在不写，erp接口有了补上）
        testTime(__FILE__,__LINE__);
        //老客加在这
        if(session('work_type') == MS_WORK_TYPE){
            $data['introducer_type'] = 1;
        }else{
            $data['introducer_type'] = 2;
        }

        if(!$data['photo_day']){
            unset($data['photo_day']);
        }

        if(!$data['photo_day'])       unset($data['photo_day']);
        if(!$data['ready_baby_day'])  unset($data['ready_baby_day']);
        if(!$data['baby_birthday'])   unset($data['baby_birthday']);
        if(!$data['marry_day'])       unset($data['marry_day']);
        if(!$data['wedding_date'])    unset($data['wedding_date']);

        /*
        $str = '';
        preg_match_all('/<img.*?src="(.*?)".*?>/is',$data['img_record'],$array);
        foreach ($array[1] as $key => $value) {
            $str .= '<img class="images" layer-src="'.$value.'" src="'.$value.'" />';
        }
        $record['sales_remark']=$str;
        */
        //插入手机号时，查询归属地，区号等  
        if($data['customer_tel']){
            $telInfo = $this->insTelInfo($data['customer_tel']);
            if ($telInfo) {
                $data['tel_belong'] = $telInfo['tel_belong'];
                $data['tel_operator'] = $telInfo['tel_operator'];
                $data['tel_area_code'] = $telInfo['tel_area_code'];
                if (!$data['province'] || !$data['city']) {
                    $arr = explode(' ',$telInfo['tel_belong']);
                    if(count($arr) == 1){
                        $pParam['name'] = $arr[0];
                        $pParam['type'] = 1;
                        $province = $this->getAddressByLike($pParam);
                        $data['province_id'] = $province[0]['id'];
                        $data['province'] = $province[0]['name'];
                    }else{
                        $pParam['name'] = $arr[0];
                        $pParam['type'] = 1;
                        $province = $this->getAddressByLike($pParam);
                        $data['province_id'] = $province[0]['id'];
                        $data['province'] = $province[0]['name'];
                        // 获取城市
                        $cParam['name'] = $arr[1];
                        $cParam['type'] = 2;
                        $cParam['pid'] = $province[0]['id'];
                        $city = $this->getAddressByLike($cParam);
                        $data['city_id'] = $city[0]['id'];
                        $data['city'] = $city[0]['name'];
                    }
                }
            }
        }
        testTime(__FILE__,__LINE__);
        //这条客资所有联系方式
        $contact=array();
        $contactList=array();
        if($data['customer_tel']){
            array_push($contact,$data['customer_tel']);
        }
        if($data['customer_wechat']){
            array_push($contact,$data['customer_wechat']);
        }
        if($data['customer_qq']){
            array_push($contact,$data['customer_qq']);
        }
        if($data['mate_tel']){
            array_push($contact,$data['mate_tel']);
        }
        if($data['mate_wechat']){
            array_push($contact,$data['mate_wechat']);
        }
        if($data['mate_qq']){
            array_push($contact,$data['mate_qq']);
        }
        $contact=array_unique($contact);

        $data['img_record'] = trim($data['img_record']);
        if($data['img_record']){
            $record['sales_remark'] = save_clips_to_file($data['img_record'],'upload/img/'.date('Ymd',time()));
            $record['sales_remark'] = DeleteHtml($record['sales_remark']);
            if(!is_mobile()){
                $data['customer_remark'] = $record['sales_remark'];
            }
        }
        testTime(__FILE__,__LINE__);
        unset($data['img_record']);
        if($record['sales_remark']){
            $day = date('Y-m-d H:i', time());
            $remark = preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', '', $record['sales_remark']);
            $data['track_record'] ='<font color="#f08080">'.$day.'</font>&nbsp;'.$remark."<br/>";
        }
        $rep = $this->isRepeat($data['brandclass'], $data['customer_tel'],$data['customer_wechat'], $data['customer_qq'],$data['mate_tel'],'',$data['consultation_type_id'],$data['add_shop_code']);
        testTime(__FILE__,__LINE__);
        // var_dump($data['customer_tel']);
        // var_dump($rep);die;
        //是否开启客资重复审核
        $examine = db_config('cus_examine_'.session('shop_code'));
        if($rep['code'] == 201){
            $doub= 1;//客资重复标记
            if($examine == 0) {
                $arr = $rep['data'];//$this->getCustomerInfo($rep['data']);
                $msg = "您录入的客资信息重复，已存在的客资信息如下：<br/>";
                //记追踪记录
                $params['customer_id'] = $arr['id'];
                $params['customer_name'] = $arr['customer_name'];
                $params['customer_number'] = $arr['customer_number'];
                $sales_remark = '由【'.$data['dj_staff'].'】于 '.$data['dj_day'].' 录入重复客资，被系统拦截！';
                $sales_remark .= '重复客资ID:'.$arr['id'];
                if($arr['customer_tel']){
                    $sales_remark .= ',手机号：'.$arr['customer_tel'];
                }
                if($arr['customer_wechat']){
                    $sales_remark .= ',微信：'.$arr['customer_wechat'];
                }
                if($arr['customer_qq']){
                    $sales_remark .= ',QQ：'.$arr['customer_qq'];
                }
                $params['sales_remark'] = $sales_remark;
                $params['sales_day'] = date('Y-m-d H:i:s',time());
                $params['sales_staff'] = session('staff_name');
                $params['sales_staff_id'] = session('staff_id');
                $params['sales_staff_number'] = session('staff_number');
                $params['shop_name'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                $params['track_type'] = '拦截提醒';
                db('CSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$arr['id'],null);
                getSalesTracking($arr['id']);//获取最近三次追踪记录同步更新到客资表
                
                if ($arr['sales_staff']) {
                    $msg .= '客资提报人：' . $arr['dj_staff'] . '<br/>';
                    $msg .= '客资提报人所属店面：' . $arr['add_shop_name'] . '<br/>';
                    $msg .= '客资ID：'.$arr['id'].'<br/>';
                    $msg .= '客资姓名：'.$arr['customer_name'].'<br/>';
                    if($arr['customer_tel']){
                        $msg .= '手机号：'.$arr['customer_tel'].'<br/>';
                    }
                    if($arr['customer_wechat']){
                        $msg .= '微信：'.$arr['customer_wechat'].'<br/>';
                    }
                    if($arr['customer_qq']){
                        $msg .= 'QQ：'.$arr['customer_qq'].'<br/>';
                    }
                    $msg .= '客户渠道：'.$arr['customer_channel'].'<br/>';
                    $msg .= '客资当前状态：'.getIsValidAttr($arr['is_valid']).'<br/>';
                    $sal = $arr['is_loss']==1 ? '不再追踪' : ($arr['c_star_day'] ? '追踪中' : '待追踪');
                    $msg .= '是否分配：'.getIsFP($arr['is_fp']).'<br/>';
                    $msg .= '追踪状态：' . $sal . '<br/>';
                    $msg .= '追踪人：' . ($arr['sales_staff']) . '<br/>';
                    $msg .= '是否进店：' . getIsIntostore($arr['is_fp']) . '<br/>';
                    $msg .= '是否成交：' . getIsSuccess($arr['is_success']) . '<br/>';
                    $msg .= '客资录入时间：' . $arr['dj_day'] . '<br/>';
                    $msg .= '请核对信息后再录入';

                    //重复提醒
                    // $notice = db_config('cus_repeat_notice');
                    // if($notice){
                        $message['send_type']      = 1;
                        $message['send_title']     = '拦截提醒';
                        $message['send_msg']       = $sales_remark;
                        $message['customer_id']    = $arr['id'];
                        $message['receive_id']     = $arr['sales_staff_id'];
                        $message['receive_name']   = $arr['sales_staff'];
                        $message['receive_status'] = 0;
                        $message['operation_type'] = 1;
                        $message['operation']      = [];
                        $message['time_out']       = 240;
                        sendSystemMessage($message);
                    // }

                    $returnData = array('code' => 201, 'msg' => $msg);
                    //$returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].' ]的[ '.$arr['dj_staff'].' ]录入过，并且分配给了[ '.$arr['sales_staff'].' ]');
                } else {
                    $msg .= '客资提报人：' . $arr['dj_staff'] . '<br/>';
                    $msg .= '客资提报人所属店面：' . $arr['add_shop_name'] . '<br/>';
                    $msg .= '客资ID：'.$arr['id'].'<br/>';
                    $msg .= '客资姓名：'.$arr['customer_name'].'<br/>';
                    if($arr['customer_tel']){
                        $msg .= '手机号：'.$arr['customer_tel'].'<br/>';
                    }
                    if($arr['customer_wechat']){
                        $msg .= '微信：'.$arr['customer_wechat'].'<br/>';
                    }
                    if($arr['customer_qq']){
                        $msg .= 'QQ：'.$arr['customer_qq'].'<br/>';
                    }
                    $msg .= '客户渠道：'.$arr['customer_channel'].'<br/>';
                    $msg .= '客资当前状态：'.getIsValid($arr['is_valid']).'<br/>';
                    $msg .= '是否分配：' . getIsFP($arr['is_fp']) . '<br/>';
                    $msg .= '是否进店：' . getIsIntostore($arr['is_fp']) . '<br/>';
                    $msg .= '是否成交：' . getIsSuccess($arr['is_success']) . '<br/>';
                    $msg .= '客资录入时间：' . $arr['dj_day'] . '<br/>';
                    $msg .= '请核对信息后再录入';
                    $returnData = array('code' => 201, 'msg' => $msg);
                    //$returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].']的[ '.$arr['dj_staff'].' ]录入过，未进行分配');
                }
                $lanjieCount = db('c_customer_from')->where('cid',$arr['id'])->count();
                if ($lanjieCount) {
                    db('c_customer_from')->where('cid',$arr['id'])->setInc('lanjie_num',1);
                }else{
                    $lanjieData['cid'] = $arr['id'];
                    $lanjieData['lanjie_num'] = 1;
                    db('c_customer_from')->insert($lanjieData);
                }
                return $returnData;
            }else{
                $data['is_examine'] = 2;
            }
        }
        testTime(__FILE__,__LINE__);
        // echo db()->getLastSql();exit;

        // print_r($data);die;
        db()->startTrans();//开启事务
        try {
            $data['customer_number'] = str_shuffle(time().generate_code());
            $data['update_time'] = date('Y-m-d H:i:s');

            $res=db('CCustomerinfo')->insert($data);
            $customerId = db()->getLastInsID();testTime(__FILE__,__LINE__);
            //小组信息
            $groupInfo = getGroupInfo($data['dj_staff_id']);
            $group = [];
            $group['cid'] = $customerId;
            if(!empty($groupInfo)){
                $group['dj_group_id'] = $groupInfo['id'];
                $group['dj_group_name'] = $groupInfo['group_name'];
            }testTime(__FILE__,__LINE__);
            if($customerId){
                db('c_customer_from')->insert($group);
                //录入日志
                $log ='';
                if($data['customer_type'] == 1){
                    $log .= '客资类型：新客资<br/>';
                }
                if($data['customer_type'] == 2){
                    $log .= '客资类型：转介绍<br/>';
                }
                if($data['customer_name']){
                    $log .= '客资姓名：'.$data['customer_name'].'<br/>';
                }
                if($data['customer_sex']){
                    $log .= '客资性别：'.$data['customer_sex'].'<br/>';
                }
                if($data['customer_number']){
                    $log .= '客户编号：'.$data['customer_number'].'<br/>';
                }
                if($data['customer_tel']){
                    $log .= '客户手机：'.$data['customer_tel'].'<br/>';
                }
                if($data['customer_wechat']){
                    $log .= '客户微信：'.$data['customer_wechat'].'<br/>';
                }
                if($data['customer_qq']){
                    $log .= '客户QQ：'.$data['customer_qq'].'<br/>';
                }
                if($data['customer_birthday']){
                    $log .= '客户生日：'.$data['customer_birthday'].'<br/>';
                }
                if($data['channel_plan_number']){
                    $log .= '推广编号：'.$data['channel_plan_number'].'<br/>';
                }
                if($data['ad_page']){
                    $log .= '广告落地页：'.$data['ad_page'].'<br/>';
                }
                if($data['consulation_shop']){
                    $log .= '意向店面：'.$data['consulation_shop'].'<br/>';
                }
                if($data['budget']){
                    $log .= '预算：'.$data['budget'].'<br/>';
                }
                if($data['customer_key']){
                    $log .= '关键词：'.$data['customer_key'].'<br/>';
                }
                if($data['mate_name']){
                    $log .= '配偶姓名：'.$data['mate_name'].'<br/>';
                }
                if($data['mate_sex']){
                    $log .= '配偶性别：'.$data['mate_sex'].'<br/>';
                }
                if($data['mate_tel']){
                    $log .= '配偶手机：'.$data['mate_tel'].'<br/>';
                }
                if($data['mate_wechat']){
                    $log .= '配偶微信：'.$data['mate_wechat'].'<br/>';
                }
                if($data['mate_qq']){
                    $log .= '配偶QQ：'.$data['mate_qq'].'<br/>';
                }
                if($data['mate_birthday']){
                    $log .= '配偶生日：'.$data['mate_birthday'].'<br/>';
                }
                if($data['marry_day']){
                    $log .= '婚期：'.$data['marry_day'].'<br/>';
                }else if ($data['wedding_date']){
                    $log .= '婚期：'.$data['wedding_date'].'<br/>';
                }
                if($data['customer_channel']){
                    $log .= '渠道名称：'.$data['customer_channel'].'<br/>';
                }
                if($data['consultation_type']){
                    $log .= '消费类型：'.$data['consultation_type'].'<br/>';
                }
                if($data['access_model']){
                    $log .= '获取方式：'.$data['access_model'].'<br/>';
                }
                if($data['customer_cource']){
                    $log .= '客户来源：'.$data['customer_cource'].'<br/>';
                }
                if($data['customer_intention']) {
                    $log .= '客户意向：' . $data['customer_intention'] . '<br/>';
                }
                if($data['customer_remark']){
                    $log .= '客户备注：'.$data['customer_remark'].'<br/>';
                }
                if($data['province']){
                    $log .= '省：'.$data['province'].'<br/>';
                }
                if($data['city']){
                    $log .= '市：'.$data['city'].'<br/>';
                }
                if($data['county']){
                    $log .= '区县：'.$data['county'].'<br/>';
                }
                if($data['customer_address']){
                    $log .= '客户地址：'.$data['customer_address'].'<br/>';
                }
                if($data['dj_staff']){
                    $log .= '登记人：'.$data['dj_staff'].'<br/>';
                }
                if($data['sales_staff']){
                    $log .= '追踪人：'.$data['sales_staff'].'<br/>';
                }
                if($data['sk_staff']){
                    $log .= '筛客人：'.$data['sk_staff'].'<br/>';
                }
                if($data['brandclass']){
                    $log .= '事业部：'.$data['brandclass'].'<br/>';
                }
                if($data['add_shop_name']){
                    $log .= '提报店：'.$data['add_shop_name'].'<br/>';
                }
                if($data['shop_name']){
                    $log .= '归属店：'.$data['shop_name'].'<br/>';
                }
                if($data['dj_day']){
                    $log .= '录入时间：'.$data['dj_day'].'<br/>';
                }
                if($data['zjs_from'] == 1){
                    $log .= '转介绍类型：老顾客转介绍<br/>';
                }
                if($data['zjs_from'] == 2){
                    $log .= '转介绍类型：员工亲友转介绍<br/>';
                }
                if($data['introducer_name']){
                    $log .= '介绍人姓名：'.$data['introducer_name'].'<br/>';
                }
                if($data['introducer_tel']){
                    $log .= '介绍人手机：'.$data['introducer_tel'].'<br/>';
                }
                if($data['introducer_ordernum']){
                    $log .= '介绍人单号：'.$data['introducer_ordernum'].'<br/>';
                }
                if($data['introducer_number']){
                    $log .= '介绍人编号：'.$data['introducer_number'].'<br/>';
                }
                if($data['customer_label']){
                    $log .= '客资标签：'.$data['customer_label'].'<br/>';
                }

                history_log($log,[],$customerId,session('staff_id'),session('staff_name'));
                // if($data['customer_tel']){
                    // history_log(['customer_tel'=>$data['customer_tel']],[],$customerId,$data['dj_staff_id'],$data['dj_staff'],'crm','Customer','editCustomerTel');
                // }
            }testTime(__FILE__,__LINE__);
            foreach($contact as $k => $v){
                $contactList[$k]['c_id']=$customerId;
                $contactList[$k]['contact']=$v;
                $contactList[$k]['brandclass']=$data['brandclass'];
            }
            $res = db('c_customer_contact')->insertAll($contactList);
            $error = isTableExist('l_error_log');
            if($error){
                $errorLog['action'] = '客资ID【'.$customerId.'】录入客资时插入排重表结果：'.$res;
                $errorLog['error_reason'] = json_encode($contactList);
                $errorLog['create_time'] = date('Y-m-d H:i:s');
                db('l_error_log')->insert($errorLog);
            }testTime(__FILE__,__LINE__);
            // $errId++;
            // if($record['sales_remark']){
            //$customerInfo=db('CCustomerinfo')->field('customer_number,customer_name')->where('id',$customerId)->find();
            $record['gtType']=4;
            $record['customer_id']=$customerId;
            $record['customer_name']=$data['customer_name'];
            $record['customer_number']=$data['customer_number'];
            $record['sales_staff_id']=$data['dj_staff_id'];
            $record['sales_staff']=$data['dj_staff'];
            $record['sales_staff_number']=$data['dj_staff_number'];
            $record['shop_name']=$data['shop_name'];
            $record['shop_code']=$data['shop_code'];
            $record['sales_day']=date('Y-m-d H:i:s',time());
            // if($data['shop_code'] == $data['add_shop_code']){
                $record['sales_remark'] = '录入-前端'.$record['sales_remark'];
                db('c_salestrackinginfo')->insert($record);
                getSalesTracking($customerId);testTime(__FILE__,__LINE__);
                // $errId++;
            // }
            //发送短信
            if($sms_model && $is_send_msg){
                $send_msg = db('s_message_templateinfo')->where('id',$sms_model)->value('mtemplate_content');
                $sms = db_config('sms_'.session('shop_code'));
                $param = [
                    'ids' => $customerId,//客资id
                    'model_id' => $sms_model,//模板id
                    'send_msg' => $send_msg,//发送的模板内容
                    'send_config' => $sms,//短信账号
                ];
                $this->send_message($param);
            }testTime(__FILE__,__LINE__);
            db()->commit();
        } catch (Exception $e) {//1001001001
            db()->rollback();//回滚
            return array('code'=>105,'msg'=>'客资录入失败','data'=>$e->getMessage());
        }
        if($doub == 1 && $examine == 1){testTime(__FILE__,__LINE__);
            //如果是重复的待审核客资,发消息
            // 发送消息用数据
            $messageD['send_type']      = 1;
            $messageD['send_time']      = date('Y-m-d H:i:s');
            $messageD['send_title']     = '客资重复提醒';
            $messageD['send_msg']       = '您提报的客资，姓名：'.$data['customer_name'].'为重复客资，请等待审核。';
            $messageD['receive_id']     = $data['dj_staff_id'];
            $messageD['receive_name']   = $data['dj_staff_number'];
            $messageD['receive_status'] = 1;
            $messageD['receive_time']   = date('Y-m-d H:i:s');
            $messageD['operation_type'] = 2;
            $messageD['operation']      = '';
            $messageD['time_out']       = 180;
            $resM = sendSystemMessage($messageD);testTime(__FILE__,__LINE__);
            //给上级发信息
            if(session('staff_number')){
                $le = [
                    'type'=>1,
                    'number'=>session('main_position_code')
                ];
                $level = $this->getHignerLevel($le);
                if(is_array($level) && count($level) > 0){
                    foreach($level as $k=>$v){
                        $mess['send_type']      = 1;
                        $mess['send_time']      = date('Y-m-d H:i:s');
                        $mess['send_title']     = '客资重复提醒';
                        $mess['send_msg']       = $data['dj_staff'].'提报的客资，姓名：'.$data['customer_name'].'为重复客资，请前去审核。';
                        $mess['receive_id']     = $v['id'];
                        $mess['receive_name']   = $v['staffname'];
                        $mess['receive_status'] = 1;
                        $mess['receive_time']   = date('Y-m-d H:i:s');
                        $mess['operation_type'] = 2;
                        $mess['operation']      = '';
                        $mess['time_out']       = 180;
                        sendSystemMessage($mess);
                    }
                }
            }
            testTime(__FILE__,__LINE__);
            return $customerId;
        }
        if($res!=false && $examine == 0){//未重复的客资
            testTime(__FILE__,__LINE__);
            // 如果提报人的工作类型是话务(21),分配给自己
            $staffinfo = getStaffInfoById(session('staff_id'));
            testTime(__FILE__,__LINE__);
            $workTypes = RECEIVE_WORK_TYPE;
            if ($staffinfo['work_types']) {
                $type = explode(',', $staffinfo['work_types']);
                array_push($type, $staffinfo['main_work_type']);
            }else{
                $type = $staffinfo['main_work_type'];
            }
            if (is_array($type)) {
                $is_in = in_array($workTypes, $type);
            }else{
                if ($workTypes == $type) {
                    $is_in = true;
                }else{
                    $is_in = false;
                }
            }
            // $work_type=explode(',',trim(session('main_work_type').','.session('work_type'),','));
            // if(in_array(RECEIVE_WORK_TYPE,$work_type)) {}       检验工作类型中有没有话务，其实可以这样更简单些的....
            if ($is_in && !$data['sales_staff_id']) {
                testTime(__FILE__,__LINE__);
                $upgroup['sales_group_id'] = $groupInfo['id'];
                $upgroup['sales_group_name'] = $groupInfo['group_name'];
                if($customerId){
                    db('c_customer_from')->where('cid',$customerId)->update($upgroup);
                }
                testTime(__FILE__,__LINE__);
                // 分配  用数据
                $sales_staff_info=getStaffInfoById(session('staff_id'));
                $date = date('Y-m-d H:i:s');
                $dataN['sales_staff_id']    = session('staff_id');
                $dataN['sales_staff']       = session('staff_name');
                $dataN['sales_staff_number']= session('staff_number');
                $dataN['fp_day']            = $date;
                $dataN['is_fp']             = 1;
                $dataN['jr_day']            = $date;
                $dataN['sales_department_id']  = $sales_staff_info['department_id'];
                $dataN['sales_department_name']= $sales_staff_info['department_name'];

                db('c_customerinfo')->where('id', $customerId)->update($dataN);
                testTime(__FILE__,__LINE__);
                //                push_list($listNameN, $messageN);
                // 分配日志
                $fpLogData = [
                    'cid'              => $customerId,
                    'fp_model'         => 4,
                    'fp_status'        => 1,
                    'fp_time'          => $date,
                    'jr_time'          => $date,
                    'fp_staff_id'      => session('staff_id'),
                    'fp_staff_name'    => session('staff_name'),
                    'fp_shop_code'     => session('shop_code'),
                    'fp_shop_name'     => session('shop_name'),
                    'fp_brandclass_id' => session('brandclass_id'),
                    'jr_staff_id'      => session('staff_id'),
                    'jr_staff_name'    => session('staff_name'),
                    'jr_shop_code'     => $data['shop_code'],
                    'jr_shop_name'     => $data['shop_name'],
                ];
                // var_dump($fpLogData);
                // exit;
                testTime(__FILE__,__LINE__);
                $resLog = fpLogs($fpLogData);
                // 发送微信模板消息
                $overTime = date('Y-m-d H:i:s', (time()+$timeOut));
                $wxConfirmUrl = config('app_host').'/crm/weixin/receiveCustomerDetail/cid/'.$customerId;
                $sex = $data['customer_sex']?'('.$data['customer_sex'].')':'';
                $content = [
                    'touser'       => session('staff_id'),
                    'template_id'  => OPENTM_FP,
                    'url'          => $wxConfirmUrl,
                    'data'         => [
                        'first'=>[
                            'value'=> '您好，您有一笔新客资啦，快去追踪吧！',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $data['customer_name'].' '.$sex.'[ID：'.$customerId.']',
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $data['customer_tel'].'/ 微信：'.$data['customer_wechat'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> '话务录入',
                            'color'=> '#173177'
                        ],
                        'keyword4'=>[
                            'value'=> $overTime,
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> '请尽快处理，谢谢',
                            'color'=> '#173177'
                        ]
                    ]
                ];
                testTime(__FILE__,__LINE__);
                $send_data['content'] = json_encode($content);
                $remind = getRemind($data['brandclass_id']);
                if(in_array('tui',$remind['sd']['send_method']) && in_array('sales',$remind['sd']['send_receive'])){
                    sendMsg($send_data);
                }
                testTime(__FILE__,__LINE__);
            }else{
                // 不筛客
                if ($data['is_sk'] != 1) {
                    testTime(__FILE__,__LINE__);
                    $fpStatus=db_config('fp_switch_'.$data['shop_code']);
                    // 开启分配，并且 接收人不存在
                    if($fpStatus==1 && (!$data['sales_staff_id'] || $data['sales_staff_id'] == '')){
                        // if(!$data['sales_staff_id']){
                        // 系统分配队列
                        $listName_fp = 'fpCustomerList';
                        $message_fp['receive']  = '-1';
                        $message_fp['body']     = $customerId;
                        $message_fp['staff_id'] = $data['dj_staff_id'];
                        $message_fp['shop_code']= $data['shop_code'];
                        push_list($listName_fp, $message_fp);
                    }else{
                        // 存在接收人，发消息
                        if ($data['sales_staff_id']) {
                            // 发送消息用数据
                            $messageD['customer_id']      = $customerId;
                            $messageD['send_type']      = 1;
                            $messageD['send_time']      = $data['fp_day'];
                            $messageD['send_title']     = '分配提醒';
                            $messageD['send_msg']       = '您收到一笔新客资，姓名：'.$data['customer_name'].'，请查收。';
                            $messageD['receive_id']     = $data['sales_staff_id'];
                            $messageD['receive_name']   = $data['sales_staff'];
                            $messageD['receive_status'] = 1;
                            $messageD['receive_time']   = $data['fp_day'];
                            $messageD['operation_type'] = 2;
                            $messageD['operation']      = '';
                            $timeOut = db_config('fp_timeout_'.$data['shop_code']);
                            $messageD['time_out']       = $timeOut ? $timeOut : 60;
                            $resM = sendSystemMessage($messageD);

                            // 分配日志
                            $fpLogData = [
                                'cid'              => $customerId,
                                'fp_model'         => 3,
                                'fp_status'        => 1,
                                'fp_time'          => $data['fp_day'],
                                'jr_time'          => $data['fp_day'],
                                'fp_staff_id'      => session('staff_id'),
                                'fp_staff_name'    => session('staff_name'),
                                'fp_shop_code'     => session('shop_code'),
                                'fp_shop_name'     => session('shop_name'),
                                'fp_brandclass_id' => session('brandclass_id'),
                                'jr_staff_id'      => $data['sales_staff_id'],
                                'jr_staff_name'    => $data['sales_staff'],
                                'jr_shop_code'     => $data['shop_code'],
                                'jr_shop_name'     => $data['shop_name'],
                            ];
                            $groupInfo = getGroupInfo($data['sales_staff_id']);
                            if(!empty($groupInfo)){
                                $upgroup['sales_group_id'] = $groupInfo['id'];
                                $upgroup['sales_group_name'] = $groupInfo['group_name'];
                            }
                            if($customerId){
                               db('c_customer_from')->where('cid',$customerId)->update($upgroup);
                            }
                            $resLog = fpLogs($fpLogData);
                            // 发送微信模板消息
                            $overTime = date('Y-m-d H:i:s', (time()+$timeOut));
                            $wxConfirmUrl = trim(config('app_host'),'/').'/crm/weixin/receiveCustomerDetail/cid/'.$customerId;
                            $sex = $data['customer_sex']?'('.$data['customer_sex'].')':'';
                            $content = [
                                'touser'       => $data['sales_staff_id'],
                                'template_id'  => OPENTM_FP,
                                'url'          => $wxConfirmUrl,
                                'data'         => [
                                    'first'=>[
                                        'value'=> '您好，您有一笔新客资啦，快去追踪吧！',
                                        'color'=> '#173177'
                                    ],
                                    'keyword1'=>[
                                        'value'=> $data['customer_name'].' '.$sex.'[ID：'.$customerId.']',
                                        'color'=> '#173177'
                                    ],
                                    'keyword2'=>[
                                        'value'=> $data['customer_tel'].'/ 微信：'.$data['customer_wechat'],
                                        'color'=> '#173177'
                                    ],
                                    'keyword3'=>[
                                        'value'=> '录入指定',
                                        'color'=> '#173177'
                                    ],
                                    'keyword4'=>[
                                        'value'=> $overTime,
                                        'color'=> '#173177'
                                    ],
                                    'remark'=>[
                                        'value'=> '请尽快处理，谢谢',
                                        'color'=> '#173177'
                                    ]
                                ]
                            ];
                            $send_data['content'] = json_encode($content);
                            $remind = getRemind($data['brandclass_id']);
                            if(in_array('tui',$remind['sd']['send_method']) && in_array('sales',$remind['sd']['send_receive'])){
                                sendMsg($send_data);
                            }
                        }
                    }
                    testTime(__FILE__,__LINE__);
                }
                // 筛客 并且存在追踪人
                else{
                    if ($data['sales_staff_id']) {
                        // 记录分配日志
                        $fpLogData = [
                            'cid'              => $customerId,
                            'fp_model'         => 3,
                            'fp_status'        => 1,
                            'fp_time'          => $data['fp_day'],
                            'jr_time'          => $data['fp_day'],
                            'fp_staff_id'      => session('staff_id'),
                            'fp_staff_name'    => session('staff_name'),
                            'fp_shop_code'     => session('shop_code'),
                            'fp_shop_name'     => session('shop_name'),
                            'fp_brandclass_id' => session('brandclass_id'),
                            'jr_staff_id'      => $data['sales_staff_id'],
                            'jr_staff_name'    => $data['sales_staff'],
                            'jr_shop_code'     => $data['shop_code'],
                            'jr_shop_name'     => $data['shop_name'],
                        ];
                        $groupInfo = getGroupInfo($data['sales_staff_id']);
                        if(!empty($groupInfo)){
                            $upgroup['sales_group_id'] = $groupInfo['id'];
                            $upgroup['sales_group_name'] = $groupInfo['group_name'];
                        }
                        if($customerId){
                            db('c_customer_from')->where('cid',$customerId)->update($upgroup);
                        }
                        $resLog = fpLogs($fpLogData);
                    }
                }
            }
            return $customerId;
        }
        return $customerId;
    }
    // 客资录入
    function addCustomer_child($data){
        //转介绍次数
        $num = db_config('zhuanjieshao_number_'.session('shop_code'));
        $count = db('c_customerinfo')->where('introducer_tel',$data['introducer_tel'])->where('dj_day','between',[date('Y-m-d'),date('Y-m-d 23:59:59')])->count();
        if($data['customer_type'] == 2 && !empty($data['introducer_tel']) && $num && $count>$num){
            return array('code'=>121,'msg'=>'今天转介绍次数已达上限,不能提报');
        }

        $data['baby_name'] = trim(strip_tags($data['baby_name']));
        $data['baby_address'] = trim(strip_tags($data['baby_address']));

        $data['customer_name'] = trim(strip_tags($data['customer_name']));
        $data['customer_tel']  = trim($data['customer_tel']);
        $data['customer_wechat']= trim(strip_tags($data['customer_wechat']));
        $data['customer_qq']    = trim(strip_tags($data['customer_qq']));
        $data['customer_weibo'] = trim(strip_tags($data['customer_weibo']));
        $data['customer_idnumber'] = trim(strip_tags($data['customer_idnumber']));

        $data['mate_name']  = trim(strip_tags($data['mate_name']));
        $data['mate_tel']   = trim($data['mate_tel']);
        $data['mate_wechat']= trim(strip_tags($data['mate_wechat']));
        $data['mate_qq']    = trim(strip_tags($data['mate_qq']));
        $data['mate_weibo'] = trim(strip_tags($data['mate_weibo']));
        $data['mate_idnumber']=trim(strip_tags($data['mate_idnumber']));

        $data['customer_address'] = trim(strip_tags($data['customer_address']));
        $data['customer_key'] = trim(strip_tags($data['customer_key']));
        $data['budget'] = trim(strip_tags($data['budget']));
        $data['customer_remark'] = trim(strip_tags($data['customer_remark']));
        $data['ad_page'] = trim(strip_tags($data['ad_page']));

        $data['dj_day']=date('Y-m-d H:i:s',time());
        $data['yx_day']=date('Y-m-d H:i:s',time());
        $data['creator_day']=date('Y-m-d H:i:s',time());
        $is_send_msg = $data['is_send_msg'];
        $sms_model = $data['sms_model'];
        unset($data['is_send_msg']);
        unset($data['sms_model']);
        if(!$data['create_time'])   $data['create_time']=date('Y-m-d H:i:s',time());
        if($data['customer_tel']){//录入时是否获取手机号
            $data['tel_staff_id']=$data['dj_staff_id'];
            $data['tel_staff']=$data['dj_staff'];
            $data['tel_time']=date('Y-m-d H:i:s',time());
            $data['is_first_tel']=1;
        }
        if($data['customer_wechat']){//录入时是否获取微信
            $data['wechat_staff_id']=$data['dj_staff_id'];
            $data['wechat_staff']=$data['dj_staff'];
            $data['wechat_time']=date('Y-m-d H:i:s',time());
            $data['is_first_wechat']=1;
        }
        if($data['customer_qq']){//录入时是否获取QQ
            $data['qq_staff_id']=$data['dj_staff_id'];
            $data['qq_staff']=$data['dj_staff'];
            $data['qq_time']=date('Y-m-d H:i:s',time());
            $data['is_first_qq']=1;
        }
        $dj=getStaffInfoById($data['dj_staff_id']);
        if($data['sales_staff_id']){
            $sales=$this->get_staff_list(array('id'=>$data['sales_staff_id']));
            $fp_day = date('Y-m-d H:i:s',time());
            $data['fp_day']=$fp_day;
            $data['jr_day']=$fp_day;
            $data['sales_department_id']= $sales[0]['department_id'];
            $data['sales_staff']=$sales[0]['staffname'];
            $data['sales_staff_number']=$sales[0]['staffnumber'];
            $data['sales_department_id']= $sales['department_id'];
            $data['sales_department_name']= $sales['department_name'];
            $data['is_fp']=1;
            $data['fp_staff_id']=$data['dj_staff_id'];//分配人id
            $data['fp_staff']=$data['dj_staff'];
            $data['fp_staff_number']=$data['dj_staff_number'];
            $data['fp_department_id'] = $dj['department_id'];
            $data['fp_department_name']= $dj['department_name'];
        }
        if($data['dj_department_id']){
            $data['dj_department_name'] = $dj['department_name'];
        }else{
            $data['dj_department_id'] = $dj['department_id'];
            $data['dj_department_name'] = $dj['department_name'];
        }
        if($data['sign_id']){
            $data['sign_time'] = date('Y-m-d H:i:s',time());
        }
        //提报类型（1：新客；门市提交2：现客；非门市提交3：老客;erp传来的接口，订单已成交的,现在不写，erp接口有了补上）

        //老客加在这
        if(session('work_type') == MS_WORK_TYPE){
            $data['introducer_type'] = 1;
        }else{
            $data['introducer_type'] = 2;
        }

        if(!$data['photo_day']){
            unset($data['photo_day']);
        }

        if(!$data['photo_day'])       unset($data['photo_day']);
        if(!$data['ready_baby_day'])  unset($data['ready_baby_day']);
        if(!$data['baby_birthday'])   unset($data['baby_birthday']);
        if(!$data['marry_day'])       unset($data['marry_day']);

        /*
        $str = '';
        preg_match_all('/<img.*?src="(.*?)".*?>/is',$data['img_record'],$array);
        foreach ($array[1] as $key => $value) {
            $str .= '<img class="images" layer-src="'.$value.'" src="'.$value.'" />';
        }
        $record['sales_remark']=$str;
        */
        //插入手机号时，查询归属地，区号等
        if($data['customer_tel']){
            $info = getData($data['customer_tel']);
            $arr = explode(' ',$info);
            $data['tel_belong'] = $arr[1].' '.$arr[2];
            $data['tel_operator'] = $arr[3];
            $data['tel_area_code'] = $arr[5];

        }


        //这条客资所有联系方式
        $contact=array();
        $contactList=array();
        if($data['customer_tel']){
            array_push($contact,$data['customer_tel']);
        }
        if($data['customer_wechat']){
            array_push($contact,$data['customer_wechat']);
        }
        if($data['customer_qq']){
            array_push($contact,$data['customer_qq']);
        }
        if($data['mate_tel']){
            array_push($contact,$data['mate_tel']);
        }
        if($data['mate_wechat']){
            array_push($contact,$data['mate_wechat']);
        }
        if($data['mate_qq']){
            array_push($contact,$data['mate_qq']);
        }
        $contact=array_unique($contact);

        if($data['img_record']){
            $data['img_record'] = trim($data['img_record']);
            $record['sales_remark'] = save_clips_to_file($data['img_record'],'upload/img/'.date('Ymd',time()));
            $record['sales_remark'] = DeleteHtml($record['sales_remark']);
            $data['customer_remark'] = $record['sales_remark'];
            unset($data['img_record']);
        }

        if($record['sales_remark']){
            $day = date('Y-m-d H:i', time());
            $remark = preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', '', $record['sales_remark']);
            $data['track_record'] ='<font color="#f08080">'.$day.'</font>&nbsp;'.$remark."<br/>";
        }
        $rep = $this->isRepeat($data['brandclass'], $data['customer_tel'],$data['customer_wechat'], $data['customer_qq'],$data['mate_tel'],0,$data['consultation_type_id'],$data['add_shop_code']);
        $doub = 0;
        /* if($rep['code'] == 201){
            $doub= 1;//客资重复标记
            $arr = $rep['data'];//$this->getCustomerInfo($rep['data']);
            $msg = "您 录入的客资信息重复，已存在的客资信息如下：<br/>";
            if($arr['sales_staff']){
                $msg .= '客资提报人：'.$arr['dj_staff'].'<br/>';
                $msg .= '客资提报人所属店面：'.$arr['add_shop_name'].'<br/>';
                // $msg .= '客资所属店面：'.$arr['shop_name'].'<br/>';
                // $msg .= '客资当前状态：'.getIsValidAttr($arr['is_valid']).'<br/>';
                $sal = $arr['is_loss']==1 ? '不再追踪' : ($arr['c_star_day'] ? '追踪中' : '待追踪');
                // $msg .= '是否分配：'.getIsFP($arr['is_fp']).'<br/>';
                $msg .= '追踪状态：'.$sal.'<br/>';
                $msg .= '追踪人：'.($arr['sales_staff']).'<br/>';
                $msg .= '是否进店：'.getIsIntostore($arr['is_fp']).'<br/>';
                $msg .= '是否成交：'.getIsSuccess($arr['is_success']).'<br/>';
                $msg .= '客资录入时间：'.$arr['dj_day'].'<br/>';
                $msg .= '请核对信息后再录入';
                $returnData = array('code' => 201,'msg' =>$msg);
                // $returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].' ]的[ '.$arr['dj_staff'].' ]录入过，并且分配给了[ '.$arr['sales_staff'].' ]');
            }else{
                $msg .= '客资提报人：'.$arr['dj_staff'].'<br/>';
                $msg .= '客资提报人所属店面：'.$arr['add_shop_name'].'<br/>';
                // $msg .= '客资所属店面：'.$arr['shop_name'].'<br/>';
                // $msg .= '客资当前状态：'.getIsValidAttr($arr['is_valid']).'<br/>';
                $msg .= '是否分配：'.getIsFP($arr['is_fp']).'<br/>';
                $msg .= '是否进店：'.getIsIntostore($arr['is_fp']).'<br/>';
                $msg .= '是否成交：'.getIsSuccess($arr['is_success']).'<br/>';
                $msg .= '客资录入时间：'.$arr['dj_day'].'<br/>';
                $msg .= '请核对信息后再录入';

                //记追踪记录
                $params['customer_id'] = $arr['id'];
                $params['customer_name'] = $arr['customer_name'];
                $params['customer_number'] = $arr['customer_number'];
                $sales_remark = '由【'.$data['dj_staff'].'】于 '.$data['dj_day'].' 录入重复客资，被系统拦截！';
                $sales_remark .= '重复客资ID:'.$arr['id'];
                if($arr['customer_tel']){
                    $sales_remark .= ',手机号：'.$arr['customer_tel'];
                }
                if($arr['customer_wechat']){
                    $sales_remark .= ',微信：'.$arr['customer_wechat'];
                }
                if($arr['customer_qq']){
                    $sales_remark .= ',QQ：'.$arr['customer_qq'];
                }
                $params['sales_remark'] = $sales_remark;
                $params['sales_remark'] = $sales_remark;
                $params['sales_day'] = date('Y-m-d H:i:s',time());
                $params['sales_staff'] = session('staff_name');
                $params['sales_staff_id'] = session('staff_id');
                $params['sales_staff_number'] = session('staff_number');
                $params['shop_name'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('CSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$arr['id'],null);
                getSalesTracking($arr['id']);//获取最近三次追踪记录同步更新到客资表
                //弹窗消息
                $message['send_type']      = 1;
                $message['send_title']     = '系统消息';
                $message['send_msg']       = $sales_remark;
                $message['customer_id']    = $arr['id'];
                $message['receive_id']     = $arr['sales_staff_id'];
                $message['receive_name']   = $arr['sales_staff'];
                $message['receive_status'] = 0;
                $message['operation_type'] = 1;
                $message['operation']      = [];
                $message['time_out']       = 240;
                sendSystemMessage($message);
                $returnData = array('code' => 201,'msg' =>$msg);
               // $returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].']的[ '.$arr['dj_staff'].' ]录入过，未进行分配');
            }
            return $returnData;
        }*/
        if($rep['code'] == 201){
            $doub= 1;//客资重复标记
            $examine = db_config('cus_examine_'.session('shop_code'));
            if($examine == 0) {
                $arr = $rep['data'];//$this->getCustomerInfo($rep['data']);
                $msg = "您 录入的客资信息重复，已存在的客资信息如下：<br/>";
                if ($arr['sales_staff']) {
                    $msg .= '客资提报人：' . $arr['dj_staff'] . '<br/>';
                    $msg .= '客资提报人所属店面：' . $arr['add_shop_name'] . '<br/>';
                    $msg .= '客资ID：'.$arr['id'].'<br/>';
                    $msg .= '客资姓名：'.$arr['customer_name'].'<br/>';
                    if($arr['customer_tel']){
                        $msg .= '手机号：'.$arr['customer_tel'].'<br/>';
                    }
                    if($arr['customer_wechat']){
                        $msg .= '微信：'.$arr['customer_wechat'].'<br/>';
                    }
                    if($arr['customer_qq']){
                        $msg .= 'QQ：'.$arr['customer_qq'].'<br/>';
                    }
                    //$msg .= '客资当前状态：'.getIsValidAttr($arr['is_valid']).'<br/>';
                    $sal = $arr['is_loss']==1 ? '不再追踪' : ($arr['c_star_day'] ? '追踪中' : '待追踪');
                    //$msg .= '是否分配：'.getIsFP($arr['is_fp']).'<br/>';
                    $msg .= '追踪状态：' . $sal . '<br/>';
                    $msg .= '追踪人：' . ($arr['sales_staff']) . '<br/>';
                    $msg .= '是否进店：' . getIsIntostore($arr['is_fp']) . '<br/>';
                    $msg .= '是否成交：' . getIsSuccess($arr['is_success']) . '<br/>';
                    $msg .= '客资录入时间：' . $arr['dj_day'] . '<br/>';
                    $msg .= '请核对信息后再录入';

                    //记追踪记录
                    $params['customer_id'] = $arr['id'];
                    $params['customer_name'] = $arr['customer_name'];
                    $params['customer_number'] = $arr['customer_number'];
                    $sales_remark = '由【'.$data['dj_staff'].'】于 '.$data['dj_day'].' 录入重复客资，被系统拦截！';
                    $sales_remark .= '重复客资ID:'.$arr['id'];
                    if($arr['customer_tel']){
                        $sales_remark .= ',手机号：'.$arr['customer_tel'];
                    }
                    if($arr['customer_wechat']){
                        $sales_remark .= ',微信：'.$arr['customer_wechat'];
                    }
                    if($arr['customer_qq']){
                        $sales_remark .= ',QQ：'.$arr['customer_qq'];
                    }
                    $params['sales_remark'] = $sales_remark;
                    $params['sales_day'] = date('Y-m-d H:i:s',time());
                    $params['sales_staff'] = session('staff_name');
                    $params['sales_staff_id'] = session('staff_id');
                    $params['sales_staff_number'] = session('staff_number');
                    $params['shop_name'] = session('shop_name');
                    $params['shop_code'] = session('shop_code');
                    db('CSalestrackinginfo')->insert($params);
                    cache('getCustomerTrackInfos'.$arr['id'],null);
                    getSalesTracking($arr['id']);//获取最近三次追踪记录同步更新到客资表

                    //重复提醒
                    // $notice = db_config('cus_repeat_notice');
                    // if($notice){
                        $message['send_type']      = 1;
                        $message['send_title']     = '拦截提醒';
                        $message['send_msg']       = $sales_remark;
                        $message['customer_id']    = $arr['id'];
                        $message['receive_id']     = $arr['sales_staff_id'];
                        $message['receive_name']   = $arr['sales_staff'];
                        $message['receive_status'] = 0;
                        $message['operation_type'] = 1;
                        $message['operation']      = [];
                        $message['time_out']       = 240;
                        sendSystemMessage($message);
                    // }
                    $returnData = array('code' => 201, 'msg' => $msg);
                    //$returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].' ]的[ '.$arr['dj_staff'].' ]录入过，并且分配给了[ '.$arr['sales_staff'].' ]');
                } else {
                    $msg .= '客资提报人：' . $arr['dj_staff'] . '<br/>';
                    $msg .= '客资提报人所属店面：' . $arr['add_shop_name'] . '<br/>';
                    $msg .= '客资ID：'.$arr['id'].'<br/>';
                    $msg .= '客资姓名：'.$arr['customer_name'].'<br/>';
                    if($arr['customer_tel']){
                        $msg .= '手机号：'.$arr['customer_tel'].'<br/>';
                    }
                    if($arr['customer_wechat']){
                        $msg .= '微信：'.$arr['customer_wechat'].'<br/>';
                    }
                    if($arr['customer_qq']){
                        $msg .= 'QQ：'.$arr['customer_qq'].'<br/>';
                    }
                    $msg .= '是否分配：' . getIsFP($arr['is_fp']) . '<br/>';
                    $msg .= '是否进店：' . getIsIntostore($arr['is_fp']) . '<br/>';
                    $msg .= '是否成交：' . getIsSuccess($arr['is_success']) . '<br/>';
                    $msg .= '客资录入时间：' . $arr['dj_day'] . '<br/>';
                    $msg .= '请核对信息后再录入';

                    $returnData = array('code' => 201, 'msg' => $msg);
                    //$returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].']的[ '.$arr['dj_staff'].' ]录入过，未进行分配');
                }
                return $returnData;
            }else{
                $data['is_examine'] = 2;
            }
        }
        db()->startTrans();//开启事务
        try {
            $data['customer_number'] = str_shuffle(time().generate_code());
            $data['update_time'] = date('Y-m-d H:i:s');
            $res=db('CCustomerinfo')->insert($data);

            $customerId = db()->getLastInsID();

            //小组信息
            $groupInfo = getGroupInfo($data['dj_staff_id']);
            $group = [];
            $group['cid'] = $customerId;
            if(!empty($groupInfo)){
                $group['dj_group_id'] = $groupInfo['id'];
                $group['dj_group_name'] = $groupInfo['group_name'];
            }
            if($customerId){
                db('c_customer_from')->insert($group);
                // 录入日志
                $log ='';
                if($data['customer_type'] == 1){
                    $log .= '客资类型：新客资<br/>';
                }
                if($data['customer_type'] == 2){
                    $log .= '客资类型：转介绍<br/>';
                }
                if($data['baby_name']){
                    $log .= '宝宝姓名：'.$data['baby_name'].'<br/>';
                }
                if($data['baby_sex']){
                    $log .= '宝宝性别：'.$data['baby_sex'].'<br/>';
                }
                if($data['baby_birthday']){
                    $log .= '宝宝生日：'.$data['baby_birthday'].'<br/>';
                }
                if($data['customer_name']){
                    $log .= '妈妈姓名：'.$data['customer_name'].'<br/>';
                }
                if($data['customer_sex']){
                    $log .= '妈妈性别：'.$data['customer_sex'].'<br/>';
                }
                if($data['customer_number']){
                    $log .= '客户编号：'.$data['customer_number'].'<br/>';
                }
                if($data['customer_tel']){
                    $log .= '妈妈手机：'.$data['customer_tel'].'<br/>';
                }
                if($data['customer_wechat']){
                    $log .= '妈妈微信：'.$data['customer_wechat'].'<br/>';
                }
                if($data['customer_qq']){
                    $log .= '妈妈QQ：'.$data['customer_qq'].'<br/>';
                }
                if($data['customer_birthday']){
                    $log .= '妈妈生日：'.$data['customer_birthday'].'<br/>';
                }
                if($data['channel_plan_number']){
                    $log .= '推广编号：'.$data['channel_plan_number'].'<br/>';
                }
                if($data['ad_page']){
                    $log .= '广告落地页：'.$data['ad_page'].'<br/>';
                }
                if($data['consulation_shop']){
                    $log .= '意向店面：'.$data['consulation_shop'].'<br/>';
                }
                if($data['budget']){
                    $log .= '预算：'.$data['budget'].'<br/>';
                }
                if($data['customer_key']){
                    $log .= '关键词：'.$data['customer_key'].'<br/>';
                }
                if($data['mate_name']){
                    $log .= '爸爸姓名：'.$data['mate_name'].'<br/>';
                }
                if($data['mate_sex']){
                    $log .= '爸爸性别：'.$data['mate_sex'].'<br/>';
                }
                if($data['mate_tel']){
                    $log .= '爸爸手机：'.$data['mate_tel'].'<br/>';
                }
                if($data['mate_wechat']){
                    $log .= '爸爸微信：'.$data['mate_wechat'].'<br/>';
                }
                if($data['mate_qq']){
                    $log .= '爸爸QQ：'.$data['mate_qq'].'<br/>';
                }
                if($data['mate_birthday']){
                    $log .= '爸爸生日：'.$data['mate_birthday'].'<br/>';
                }
                if($data['marry_day']){
                    $log .= '婚期：'.$data['marry_day'].'<br/>';
                }
                if($data['customer_channel']){
                    $log .= '渠道名称：'.$data['customer_channel'].'<br/>';
                }
                if($data['consultation_type']){
                    $log .= '消费类型：'.$data['consultation_type'].'<br/>';
                }
                if($data['access_model']){
                    $log .= '获取方式：'.$data['access_model'].'<br/>';
                }
                if($data['customer_cource']){
                    $log .= '客户来源：'.$data['customer_cource'].'<br/>';
                }
                if($data['customer_intention']) {
                    $log .= '客户意向：' . $data['customer_intention'] . '<br/>';
                }
                if($data['customer_remark']){
                    $log .= '客户备注：'.$data['customer_remark'].'<br/>';
                }
                if($data['province']){
                    $log .= '省：'.$data['province'].'<br/>';
                }
                if($data['city']){
                    $log .= '市：'.$data['city'].'<br/>';
                }
                if($data['county']){
                    $log .= '区县：'.$data['county'].'<br/>';
                }
                if($data['customer_address']){
                    $log .= '客户地址：'.$data['customer_address'].'<br/>';
                }
                if($data['dj_staff']){
                    $log .= '登记人：'.$data['dj_staff'].'<br/>';
                }
                if($data['sales_staff']){
                    $log .= '追踪人：'.$data['sales_staff'].'<br/>';
                }
                if($data['sk_staff']){
                    $log .= '筛客人：'.$data['sk_staff'].'<br/>';
                }
                if($data['brandclass']){
                    $log .= '事业部：'.$data['brandclass'].'<br/>';
                }
                if($data['add_shop_name']){
                    $log .= '提报店：'.$data['add_shop_name'].'<br/>';
                }
                if($data['shop_name']){
                    $log .= '归属店：'.$data['shop_name'].'<br/>';
                }
                if($data['dj_day']){
                    $log .= '录入时间：'.$data['dj_day'].'<br/>';
                }
                if($data['zjs_from'] == 1){
                    $log .= '转介绍类型：老顾客转介绍<br/>';
                }
                if($data['zjs_from'] == 2){
                    $log .= '转介绍类型：员工亲友转介绍<br/>';
                }
                if($data['introducer_name']){
                    $log .= '介绍人姓名：'.$data['introducer_name'].'<br/>';
                }
                if($data['introducer_tel']){
                    $log .= '介绍人手机：'.$data['introducer_tel'].'<br/>';
                }
                if($data['introducer_ordernum']){
                    $log .= '介绍人单号：'.$data['introducer_ordernum'].'<br/>';
                }
                if($data['introducer_number']){
                    $log .= '介绍人编号：'.$data['introducer_number'].'<br/>';
                }
                if($data['customer_label']){
                    $log .= '客资标签：'.$data['customer_label'].'<br/>';
                }

                history_log($log,[],$customerId,session('staff_id'),session('staff_name'));
            }
            foreach($contact as $k => $v){
                $contactList[$k]['c_id']=$customerId;
                $contactList[$k]['contact']=$v;
                $contactList[$k]['brandclass']=$data['brandclass'];
            }
            db('c_customer_contact')->insertAll($contactList);
            // $errId++;
            // if($record['sales_remark']){
                //$customerInfo=db('CCustomerinfo')->field('customer_number,customer_name')->where('id',$customerId)->find();
                $record['gtType']=4;
                $record['customer_id']=$customerId;
                $record['customer_name']=$data['customer_name'];
                $record['customer_number']=$data['customer_number'];
                $record['sales_staff_id']=$data['dj_staff_id'];
                $record['sales_staff']=$data['dj_staff'];
                $record['sales_staff_number']=$data['dj_staff_number'];
                $record['shop_name']=$data['shop_name'];
                $record['shop_code']=$data['shop_code'];
                $record['sales_day']=date('Y-m-d H:i:s',time());
                if($data['shop_code'] == $data['add_shop_code']){
                    $record['sales_remark'] = 'PC录入-前端-'.$record['sales_remark'];
                }

                db('c_salestrackinginfo')->insert($record);
                getSalesTracking($customerId);
                // $errId++;
            // }
            //发送短信
            if($sms_model && $is_send_msg){
                $send_msg = db('s_message_templateinfo')->where('id',$sms_model)->value('mtemplate_content');
                $sms = db_config('sms_'.session('shop_code'));
                $param = [
                    'ids' => $customerId,//客资id
                    'model_id' => $sms_model,//模板id
                    'send_msg' => $send_msg,//发送的模板内容
                    'send_config' => $sms,//短信账号
                ];
                $this->send_message($param);
            }
            db()->commit();
        } catch (Exception $e) {//1001001001
            db()->rollback();//回滚
            return array('error'=>1,'msg'=>'录入失败','data'=>$e->getMessage());
        }

        if($doub == 1 && ($data['is_examine'] == 2)){
            //如果是重复的待审核客资,发消息
            // 发送消息用数据
            $messageD['send_type']      = 1;
            $messageD['send_time']      = date('Y-m-d H:i:s');
            $messageD['send_title']     = '客资重复提醒';
            $messageD['send_msg']       = '您提报的客资，姓名：'.$data['customer_name'].'为重复客资，请等待审核。';
            $messageD['receive_id']     = $data['dj_staff_id'];
            $messageD['receive_name']   = $data['dj_staff_number'];
            $messageD['receive_status'] = 1;
            $messageD['receive_time']   = date('Y-m-d H:i:s');
            $messageD['operation_type'] = 2;
            $messageD['operation']      = '';
            $messageD['time_out']       = 180;
            $resM = sendSystemMessage($messageD);
            //给上级发信息
            if(session('staff_number')){
                $le = [
                    'type'=>1,
                    'number'=>session('main_position_code')
                ];
                $level = $this->getHignerLevel($le);
                if(is_array($level) && count($level) > 0){
                    foreach($level as $k=>$v){
                        $mess['send_type']      = 1;
                        $mess['send_time']      = date('Y-m-d H:i:s');
                        $mess['send_title']     = '客资重复提醒';
                        $mess['send_msg']       = $data['dj_staff'].'提报的客资，姓名：'.$data['customer_name'].'为重复客资，请前去审核。';
                        $mess['receive_id']     = $v['id'];
                        $mess['receive_name']   = $v['staffname'];
                        $mess['receive_status'] = 1;
                        $mess['receive_time']   = date('Y-m-d H:i:s');
                        $mess['operation_type'] = 2;
                        $mess['operation']      = '';
                        $mess['time_out']       = 180;
                        sendSystemMessage($mess);
                    }
                }
            }
            return $customerId;
        }
        if($res!=false && !db_config('cus_examine_'.session('shop_code'))){//未重复的客资
            // $staff_id, $staff_name, $staff_number, $shop_code,$identity, $cid, $old_data, $new_data
            // 数据统计队列
            $listName = 'historyDataList';
            $cinfo = [
                'id'    => $customerId,
                'dj_id' => $data['dj_staff_id'],
                'dj_day'=> $data['dj_day'],
            ];
            $message = array(
                // 数据统计类型（1：单条；2：批量导入）
                'type'       => 1,
                // 批量导入的客资的eid
                // 'eid'        => '',
                'staff_id'   => $data['dj_staff_id'],
                'identity'   => 'record',
                'cinfo'      => $cinfo,
                'old_data'   => array(),
                'new_data'   => $data,
                'controller' => 'Customer',
                'action'     => 'addCustomer',
            );
            push_list($listName,$message);
            // redisQueue::init()->rPush($listName, $message);
            // action_log($data,'',$customerId,$data['dj_staff_id'],$data['dj_staff']);
            // 如果提报人的工作类型是话务(21),分配给自己
            $staffinfo = getStaffInfoById(session('staff_id'));
            $workTypes = RECEIVE_WORK_TYPE;
            if ($staffinfo['work_type']) {
                $type = explode(',', $staffinfo['work_type']);
                array_push($type, $staffinfo['main_work_type']);
            }else{
                $type = $staffinfo['main_work_type'];
            }
            if (is_array($type)) {
                $is_in = in_array($workTypes, $type);
            }else{
                if ($workTypes == $type) {
                    $is_in = true;
                }else{
                    $is_in = false;
                }
            }
            // $work_type=explode(',',trim(session('main_work_type').','.session('work_type'),','));
            // if(in_array(RECEIVE_WORK_TYPE,$work_type)) {}       检验工作类型中有没有话务，其实可以这样更简单些的....
            if ($is_in && !$data['sales_staff_id']) {

                $upgroup['sales_group_id'] = $groupInfo['id'];
                $upgroup['sales_group_name'] = $groupInfo['group_name'];
                if($customerId){
                    db('c_customer_from')->where('cid',$customerId)->update($upgroup);
                }
                // 分配  用数据
                $date = date('Y-m-d H:i:s');
                $dataN['sales_staff_id']    = session('staff_id');
                $dataN['sales_staff']       = session('staff_name');
                $dataN['sales_staff_number']= session('staff_number');
                $dataN['fp_day']            = $date;
                $dataN['is_fp']             = 1;
                $dataN['jr_day']            = $date;

                /*  $listNameN = 'historyDataList';
                  $old = [
                      'is_fp' => 2,
                  ];
                  $cinfoN = [
                      'id'    => $customerId,
                      'dj_id' => $data['dj_staff_id'],
                      'dj_day'=> $data['dj_day'],
                  ];
                  $messageN = array(
                      'type'      => 1,
                      'staff_id'  => session('staff_id'),
                      'identity'  => 'sale',
                      'cinfo'     => $cinfoN,
                      'old_data'  => $old,
                      'new_data'  => $dataN,
                      'controller'=> 'Customer',
                      'action'    => 'addCustomer',
                  );*/
                db('c_customerinfo')->where('id', $customerId)->update($dataN);
                // push_list($listNameN, $messageN);
                // 分配日志
                $fpLogData = [
                    'cid'              => $customerId,
                    'fp_model'         => 4,
                    'fp_status'        => 1,
                    'fp_time'          => $date,
                    'jr_time'          => $date,
                    'fp_staff_id'      => session('staff_id'),
                    'fp_staff_name'    => session('staff_name'),
                    'fp_shop_code'     => session('shop_code'),
                    'fp_shop_name'     => session('shop_name'),
                    'fp_brandclass_id' => session('brandclass_id'),
                    'jr_staff_id'      => session('staff_id'),
                    'jr_staff_name'    => session('staff_name'),
                    'jr_shop_code'     => $data['shop_code'],
                    'jr_shop_name'     => $data['shop_name'],
                ];
                // var_dump($fpLogData);
                // exit;
                $resLog = fpLogs($fpLogData);
            }else{
                // 不筛客
                if ($data['is_sk'] != 1) {
                    $fpStatus=db_config('fp_switch_'.$data['shop_code']);
                    // 开启分配，并且 接收人不存在
                    if($fpStatus==1 && !$data['sales_staff_id']){
                        // if(!$data['sales_staff_id']){
                        // 系统分配队列
                        $listName_fp = 'fpCustomerList';
                        $message_fp['receive']  = '-1';
                        $message_fp['body']     = $customerId;
                        $message_fp['staff_id'] = $data['dj_staff_id'];
                        $message_fp['shop_code']= $data['shop_code'];
                        push_list($listName_fp, $message_fp);
                    }else{
                        // 存在接收人，发消息
                        if ($data['sales_staff_id']) {
                            // 发送消息用数据
                            $messageD['send_type']      = 1;
                            $messageD['send_time']      = $data['fp_day'];
                            $messageD['send_title']     = '分配提醒';
                            $messageD['send_msg']       = '您收到一笔新客资，姓名：'.$data['customer_name'].'，请查收。';
                            $messageD['receive_id']     = $data['sales_staff_id'];
                            $messageD['receive_name']   = $data['sales_staff'];
                            $messageD['receive_status'] = 1;
                            $messageD['receive_time']   = $data['fp_day'];
                            $messageD['operation_type'] = 2;
                            $messageD['operation']      = '';
                            $timeOut = db_config('fp_timeout_'.$data['shop_code']);
                            $messageD['time_out']       = $timeOut ? $timeOut : 60;
                            $resM = sendSystemMessage($messageD);

                            // 分配日志
                            $fpLogData = [
                                'cid'              => $customerId,
                                'fp_model'         => 3,
                                'fp_status'        => 1,
                                'fp_time'          => $data['fp_day'],
                                'jr_time'          => $data['fp_day'],
                                'fp_staff_id'      => session('staff_id'),
                                'fp_staff_name'    => session('staff_name'),
                                'fp_shop_code'     => session('shop_code'),
                                'fp_shop_name'     => session('shop_name'),
                                'fp_brandclass_id' => session('brandclass_id'),
                                'jr_staff_id'      => $data['sales_staff_id'],
                                'jr_staff_name'    => $data['sales_staff'],
                                'jr_shop_code'     => $data['shop_code'],
                                'jr_shop_name'     => $data['shop_name'],
                            ];
                            $groupInfo = getGroupInfo($data['sales_staff_id']);
                            if(!empty($groupInfo)){
                                $upgroup['sales_group_id'] = $groupInfo['id'];
                                $upgroup['sales_group_name'] = $groupInfo['group_name'];
                            }
                            if($customerId){
                                db('c_customer_from')->where('cid',$customerId)->update($upgroup);
                            }
                            $resLog = fpLogs($fpLogData);

                        }
                    }
                }
                // 筛客 并且存在追踪人
                else{
                    if ($data['sales_staff_id']) {
                        // 记录分配日志
                        $fpLogData = [
                            'cid'              => $customerId,
                            'fp_model'         => 3,
                            'fp_status'        => 1,
                            'fp_time'          => $data['fp_day'],
                            'jr_time'          => $data['fp_day'],
                            'fp_staff_id'      => session('staff_id'),
                            'fp_staff_name'    => session('staff_name'),
                            'fp_shop_code'     => session('shop_code'),
                            'fp_shop_name'     => session('shop_name'),
                            'fp_brandclass_id' => session('brandclass_id'),
                            'jr_staff_id'      => $data['sales_staff_id'],
                            'jr_staff_name'    => $data['sales_staff'],
                            'jr_shop_code'     => $data['shop_code'],
                            'jr_shop_name'     => $data['shop_name'],
                        ];
                        $groupInfo = getGroupInfo($data['sales_staff_id']);
                        if(!empty($groupInfo)){
                            $upgroup['sales_group_id'] = $groupInfo['id'];
                            $upgroup['sales_group_name'] = $groupInfo['group_name'];
                        }
                        if($customerId){
                            db('c_customer_from')->where('cid',$customerId)->update($upgroup);
                        }
                        $resLog = fpLogs($fpLogData);
                        // 发送微信模板消息
                        $overTime = date('Y-m-d H:i:s', (time()+$timeOut));
                        $wxConfirmUrl = config('url_domain_root').'/crm/weixin/receiveCustomer/cid/'.$customerId;
                        $sex = $data['customer_sex']?'('.$data['customer_sex'].')':'';
                        $content = [
                            'touser'       => $data['sales_staff_id'],
                            'template_id'  => OPENTM_FP,
                            'url'          => $wxConfirmUrl,
                            'data'         => [
                                'first'=>[
                                    'value'=> '您好，您有一笔新客资啦，快去追踪吧！',
                                    'color'=> '#173177'
                                ],
                                'keyword1'=>[
                                    'value'=> $data['customer_name'].' '.$sex.'[ID：'.$customerId.']',
                                    'color'=> '#173177'
                                ],
                                'keyword2'=>[
                                    'value'=> $data['customer_tel'],
                                    'color'=> '#173177'
                                ],
                                'keyword3'=>[
                                    'value'=> '录入指定',
                                    'color'=> '#173177'
                                ],
                                'keyword4'=>[
                                    'value'=> $overTime,
                                    'color'=> '#173177'
                                ],
                                'remark'=>[
                                    'value'=> '请尽快处理，谢谢',
                                    'color'=> '#173177'
                                ]
                            ]
                        ];
                        $send_data['content'] = json_encode($content);
                        $remind = getRemind($data['brandclass_id']);
                        if(in_array('tui',$remind['sd']['send_method']) && in_array('sales',$remind['sd']['send_receive'])){
                            sendMsg($send_data);
                        }
                    }
                }
            }
            return $customerId;
        }
    }

    //筛客
    public function skCustomer($param){
        $has = $this->getCustomerInfo($param['id']);
        if (!$has) {
            $return = array('code' => 900,'msg' =>'用户数据不存在，请检查！');
        }
        // 待定客资 不算已筛客 但是记录筛客时间
        if ($param['is_valid'] == 2) {
            unset($param['is_already_sk']);
        }
        $param['sk_time'] = date('Y-m-d H:i:s',time());

        if (!$param['customer_tel'] && !$param['customer_wechat'] &&  !$param['customer_qq']) {
            $return = array('code' => 300,'msg' =>'请填写手机号、微信、QQ任一项联系方式');
        }
        // 渠道不存在，返回报错
        // if (!$data['customer_channel_id']) {
        //     $returnData = array('code' => 400,'msg' =>'请填写客资来源渠道');
        //     return json($returnData);
        // }


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

        if(strpos($param['customer_tel'],'*')){
            unset($param['customer_tel']);
        }
        if(strpos($param['mate_tel'],'*')){
            unset($param['mate_tel']);
        }

        if(empty($has['customer_tel'])&&!empty($param['customer_tel'])){
            $param['tel_staff_id']=session('staff_id');
            $param['tel_staff']=session('staff');
            $param['tel_time']=date('Y-m-d H:i:s',time());
        }
        if(empty($has['customer_wechat'])&&!empty($param['customer_wechat'])){
            $param['wechat_staff_id']=session('staff_id');
            $param['wechat_staff']=session('staff');
            $param['wechat_time']=date('Y-m-d H:i:s',time());
        }
        if(empty($has['customer_qq'])&&!empty($param['customer_qq'])){
            $param['qq_staff_id']=session('staff_id');
            $param['qq_staff']=session('staff');
            $param['qq_time']=date('Y-m-d H:i:s',time());
        }
        foreach ($param as $key => $value) {
            if ($value != $has[$key]) {
                $newDateIn[$key] = $value;
                $oldDateIn[$key] = $has[$key];
            }
        }
        // 没有任何修改
        if (!$newDateIn) {
            // $returnData = array('code' => 900,'msg' =>'没有修改');
            $return = array('code' => 1,'msg' =>'编辑客资信息成功');
            return json($return);
        }
        db()->startTrans();
        try{
            $param['update_time'] = date('Y-m-d H:i:s');
            db('c_customerinfo')->where('id',$param['id'])->update($param);

            //联系方式变动 修改customer_contact表
            $contact=array();
            $contactList=array();
            if($param['customer_tel']&&$param['customer_tel']!=$has['customer_tel']){
                if(empty($has['customer_tel'])){
                    array_push($contact,$param['customer_tel']);
                }else{
                    db('c_customer_contact')->where('brandclass',$has['brandclass'])->where('contact',$has['customer_tel'])->update(array('contact'=>$param['customer_tel']));
                }
            }
            if($has['customer_tel']&&empty($param['customer_tel'])){
                db('c_customer_contact')->where('contact',$has['customer_tel'])->delete();
            }

            if($param['customer_wechat']&&$param['customer_wechat']!=$has['customer_wechat']){
                if(empty($has['customer_wechat'])){
                    array_push($contact,$param['customer_wechat']);
                }else{
                    db('c_customer_contact')->where('brandclass',$has['brandclass'])->where('contact',$has['customer_wechat'])->update(array('contact'=>$param['customer_wechat']));
                }
            }
            if($has['customer_wechat']&&empty($param['customer_wechat'])){
                db('c_customer_contact')->where('contact',$has['customer_wechat'])->delete();
            }

            if($param['customer_qq']&&$param['customer_qq']!=$has['customer_qq']){
                if(empty($has['customer_qq'])){
                    array_push($contact,$param['customer_qq']);
                }else{
                    db('c_customer_contact')->where('brandclass',$has['brandclass'])->where('contact',$has['customer_qq'])->update(array('contact'=>$param['customer_qq']));
                }
            }
            if($has['customer_qq']&&empty($param['customer_qq'])){
                db('c_customer_contact')->where('contact',$has['customer_qq'])->delete();
            }

            if($param['mate_tel']&&$param['mate_tel']!=$has['mate_tel']){
                if(empty($has['mate_tel'])){
                    array_push($contact,$param['mate_tel']);
                }else{
                    db('c_customer_contact')->where('brandclass',$has['brandclass'])->where('contact',$has['mate_tel'])->update(array('contact'=>$param['mate_tel']));
                }
            }
            if($has['mate_tel']&&empty($param['mate_tel'])){
                db('c_customer_contact')->where('contact',$has['mate_tel'])->delete();
            }
            $contact=array_unique($contact);
            foreach($contact as $k => $v){
                $contactList[$k]['c_id']       = $has['id'];
                $contactList[$k]['contact']    = $v;
                $contactList[$k]['brandclass'] = $has['brandclass'];
            }
            db('c_customer_contact')->insertAll($contactList);

            if($param['is_valid'] == 1){
                //统计队列
                $listName = 'historyDataList';
                $cinfo = [
                    'id'     => $has['id'],
                    'dj_id'  => $has['dj_staff_id'],
                    'dj_day' => $has['dj_day'],
                    'sel_id' => $has['sk_staff_id'],
                    'sel_day'=> $has['sk_time'],
                ];
                $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) {
                // 待定客资 不进入分配队列
                if ($param['is_valid'] != 2) {
                    $sysconfig=db('c_sysconfig')->where('ckey','fp_switch_'.session('shop_code'))->find();
                    if($sysconfig['cvalue']==1){
                        // echo '2';
                        // 系统分配队列
                        $listName_fp = 'fpCustomerList';
                        $message_fp['receive']  = '-1';
                        $message_fp['body']     = $param['id'];
                        $message_fp['staff_id'] = $has['dj_staff_id'];
                        $message_fp['shop_code']= $has['shop_code'];
                        //redisQueue::init()->rPush($listName_fp, $message_fp);
                        push_list($listName_fp, $message_fp);
                    }
                }
            }
            action_log($param,'',$param['id'],session('staff_id'),session('staff_name'));
            $return = array('code' => 1,'msg' => '筛客成功');
            db()->commit();
        }catch (\Exception $e){
            db()->rollback();
            $return = array('code' => 400,'msg' => '筛客失败');
        }
        return json($return);
    }

    // 重新分配筛客
    public function allotSk($param){
        // 员工信息
        $staffInfo = getStaffInfoById($param['sid']);
        // 筛客人
        $skList['sk_staff_id']= $param['sid'];
        $skList['sk_staff']   = $staffInfo['staffname'];
        $res = db('c_customerinfo')->where('id', 'in', $param['cid'])->update($skList);

        if ($res === false) {
            $returnData['code'] = 100;
            $returnData['msg']  = '分配筛客人失败。';
            $returnData['error']= db()->getLastSql();
        }else{
            $cids = explode(',', $param['cid']);
            foreach ($cids as $key => $value) {
                if (!$value) {
                    continue;
                }
                // 去pool表里查一下，如果pool表里有，type=7
                db('c_fp_pool')->where('cid', $value)->where('pool_type',7)->delete();
                // 记日志
                $cInfo = db('c_customerinfo')->where('id', $value)->field('sk_staff,sk_staff_id')->find();
                $newData['sk_staff_id']= $param['sid'];
                $newData['sk_staff']   = $staffInfo['staffname'];

                history_log($newData,$cInfo,$value,session('staff_id'),session('staff_name'));
                unset($newData);
                unset($cInfo);
            }
            unset($cids);
            $returnData['code'] = 200;
            $returnData['msg']  = '分配筛客人成功。';
        }
        unset($skList);
        unset($param);
        return $returnData;
    }

    // 重新分配追踪人
    public function allotSale($param){
        $date = date('Y-m-d H:i:s');
        // 接收客资的 员工信息
        $staffInfo = getStaffInfoById($param['sid']);
        // 分配人
        $cData['fp_staff']          = session('staff_name');
        $cData['fp_staff_id']       = session('staff_id');
        $cData['fp_staff_number']   = session('staff_number');
        $cData['fp_department_id']  = session('department_id');
        $cData['fp_department_name']= session('department_name');
        // $cData['brandclass']        = session('brandclass') ? session('brandclass') : $staffInfo['brandclass'];
        // $cData['brandclass_id']     = session('brandclass_id') ? session('brandclass_id') : $staffInfo['brandclass_id'];
        // 追踪人
        $cData['sales_staff']       = $staffInfo['staffname'] ? $staffInfo['staffname'] : $staffInfo['staff_name'];
        $cData['sales_staff_id']    = $param['sid'];
        $cData['sales_staff_number']= $staffInfo['staffnumber'] ? $staffInfo['staffnumber'] : $staffInfo['staff_number'];
        if($param['department_id']){
            $cData['sales_department_id']  = $param['department_id'];
            $cData['sales_department_name']= $param['department_name'];
        }elseif($staffInfo['department_id']){
            $cData['sales_department_id'] = $staffInfo['department_id'];
            $cData['sales_department_name'] = $staffInfo['department_name'];
        }
        if($param['shop_code']){
            $cData['shop_code'] = $param['shop_code'];
            $cData['shop_name'] = $param['shop_name'];
        }

        // 分配状态及时间
        $cData['fp_day'] = $date;
        $cData['jr_day'] = $date;
        $cData['is_fp']  = FP_STATUS_SUCESS;
        // 分配追踪人
        $cData['update_time'] = $date;
        $cids = explode(',', $param['cid']);

        // 提醒明细
        $txmx = true;
        // 客资分配临界点 超过此值，则不提醒明细
        $kzfpljd = db_config('kzfpljd') ? db_config('kzfpljd') : 20;
        if (count($cids)>$kzfpljd) {
            $txmx = false;
        }
        // 客资原追踪人
        $old_sales_staff = [];

        //追踪人小组信息
        $groupInfo = getGroupInfo($param['sid']);
        // insert log 和 fp_log 数据
        $lData = [];
        $fData = [];
        $ip = \think\Request::instance()->ip();
        $allot_cids = '';
        $orderFp = flase;
        // 订单客资是否允许分配：
        if (db_config('orderCusIsAllowFp_'.session('brandclass_id')) == 1) {
            $orderFp = true;
        }
        foreach ($cids as $key => $value) {
            $has = db('c_customerinfo')->where('id',$value)
                ->field('id,customer_name,customer_tel,customer_wechat,customer_channel,is_success,is_fp,fp_staff,fp_staff_id,fp_staff_number,fp_day,sales_staff,sales_staff_id,sales_staff_number,jr_day,shop_code,shop_name,brandclass_id')
                ->find();
            // 客资原本的追踪人
            $old_sales_staff[$has['sales_staff_id']][] = $has;
            $is_success = $has['is_success'];
            if ($orderFp===true) {
                $is_success=2;
            }
            if ($is_success == 2) {
                $right = check_right('menu1541663886');
                if(!$right && $has['sales_staff_id']){
                    $returnData['code'] = 101;
                    $returnData['msg']  = '分配失败，客资已经被分配，您没有客资再分配权限。';
                    return $returnData;
                }

                $allot_cids .= $value.',';
                // action_log 用数据
                $lData[$key]['module']     = 'crm';
                $lData[$key]['controller'] = 'Customer';
                $lData[$key]['action']     = 'customerAllotOne';
                $lData[$key]['old_data']   = json_encode($has);
                $lData[$key]['data']       = json_encode($cData);
                $lData[$key]['customer_id']= $value;
                $lData[$key]['staff_name'] = session('staff_name');
                $lData[$key]['staff_id']   = session('staff_id');
                $lData[$key]['ip']         = $ip;
                $lData[$key]['create_time']= $date;
                // 分配日志用数据
                $fData[$key]['cid']              = $value;
                $fData[$key]['fp_model']         = 2;
                $fData[$key]['fp_status']        = 1;
                $fData[$key]['fp_time']          = $date;
                $fData[$key]['jr_time']          = $date;
                $fData[$key]['fp_staff_id']      = session('staff_id');
                $fData[$key]['fp_staff_name']    = session('staff_name');
                $fData[$key]['fp_shop_code']     = session('shop_code');
                $fData[$key]['fp_shop_name']     = session('shop_name');
                $fData[$key]['fp_brandclass_id'] = $has['brandclass_id'];
                $fData[$key]['jr_staff_id']      = $param['sid'];
                $fData[$key]['jr_staff_name']    = $staffInfo['staffname'] ? $staffInfo['staffname'] : $staffInfo['staff_name'];
                $fData[$key]['jr_shop_code']     = $param['shop_code'];
                $fData[$key]['jr_shop_name']     = $param['shop_name'];
            }
            unset($has);
        }
        $allot_cids = trim($allot_cids, ',');
        if (!strlen($allot_cids)) {
            $returnData['code'] = 200;
            $returnData['msg']  = '分配成功。';
            return $returnData;
        }
        // 处理数据
        db()->startTrans();
        try {
            // 更新客资表
            db('c_customerinfo')->where('id', 'in', $allot_cids)->update($cData);
            $sql = db()->getLastSql();
            // insertAll action_log fp_log
            db('action_log','db_logs')->insertAll($lData);
            db('l_fp_logs')->insertAll($fData);
            // 删除pool表
            db('c_fp_pool')->where('cid', 'in', $allot_cids)->where('pool_type', 1)->delete();
            //更新追踪人小组信息
            db('c_customer_from')->where('cid','in',$allot_cids)->update(['sales_group_id'=>$groupInfo['id'],'sales_group_name'=>$groupInfo['group_name']]);
            db()->commit();
            $returnData['code'] = 200;
            $returnData['msg']  = '分配成功。';
            $returnData['sql']  = $sql;
        } catch (\Exception $e) {
            db()->rollback();
            db('action_log','db_logs')
                ->where('customer_id', 'in', $allot_cids)
                ->where('action', 'customerAllotOne')
                ->where('ip',$ip)
                ->where('staff_name',session('staff_name'))
                ->where('staff_id',session('staff_id'))
                ->where('create_time', $date)
                ->delete();
            $returnData['code'] = 100;
            $returnData['msg']  = '分配失败。';
            $returnData['error']= $e->getMessage();
        }
        // 数据处理完成之后， 开始发消息 弹窗 和 微信模板消息 20201217
        $remind = getRemind($staffInfo['brandclass_id']);
        // 弹窗
        if($param['sid'] != session('staff_id') && in_array('tan',$remind['sd']['send_method']) && in_array('sales',$remind['sd']['send_receive'])){
            // 给客资的新追踪人发消息
            $messageD['send_type']      = 1;
            $messageD['send_time']      = $date;
            $messageD['send_title']     = '分配提醒';
            $messageD['send_msg']       = '您分配到'.count($cids).'笔客资，请查收。';
            $messageD['receive_id']     = $cData['sales_staff_id'];
            $messageD['receive_name']   = $cData['sales_staff'];
            $messageD['receive_status'] = 1;
            $messageD['receive_time']   = $date;
            $timeOut = db_config('fp_timeout_'.$param['shop_code']);
            $messageD['time_out']       = $timeOut ? $timeOut : 60;
            $messageD['operation_type'] = 2;
            $messageD['customer_id']    = $allot_cids;
            $resM = sendSystemMessage($messageD);
            // 给客资的原追踪人发消息
            foreach ($old_sales_staff as $k => $v) {
                $messageSales['send_type']      = 1;
                $messageSales['send_time']      = $date;
                $messageSales['send_title']     = '分配提醒';
                $messageSales['receive_id']     = $k;
                $messageSales['receive_name']   = $v['sales_staff'];
                $messageSales['receive_status'] = 1;
                $messageSales['receive_time']   = $date;
                $messageSales['time_out']       = $timeOut ? $timeOut : 60;
                $messageSales['operation_type'] = 2;
                $messageSales['send_msg'] = '您有'.count($v).'笔客资，分配给了'.$cData['sales_staff'].'。<br />';
                if ($txmx) {
                    foreach ($v as $kk => $vv) {
                        $messageSales['send_msg'] .= $vv['id'].'|'.$vv['customer_name'].'|'.$vv['customer_tel'].'|'.$vv['customer_wechat'].'<br />';
                    }
                }
                // var_dump($messageSales);
                sendSystemMessage($messageSales);
                unset($messageSales);
            }
        }
        // 发送微信模板消息
        if($param['sid'] != session('staff_id') && in_array('tui',$remind['sd']['send_method']) && in_array('sales',$remind['sd']['send_receive'])){
            $wxConfirmUrl = config('app_host').'/crm/weixin/receiveCustomerDetail/cid/'.$allot_cids;
            $content = [
                'touser'       => $param['sid'],
                'template_id'  => OPENTM_MFP,
                'url'          => $wxConfirmUrl,
                'data'         => [
                    'first'=>[
                        'value'=> '系统消息',
                        'color'=> '#173177'
                    ],
                    'keyword1'=>[
                        'value'=> '您分配到'.count($cids).'笔客资，请查收。',
                        'color'=> '#173177'
                    ],
                    'keyword2'=>[
                        'value'=> $date,
                        'color'=> '#173177'
                    ],
                    'remark'=>[
                        'value'=> '请尽快追踪，谢谢',
                        'color'=> '#173177'
                    ],
                ],
            ];
            $send_data['content'] = json_encode($content);
            sendMsg($send_data);
            // 给客资的原追踪人发模板消息
            foreach ($old_sales_staff as $k => $v) {
                if ($txmx) {
                    foreach ($v as $kk => $vv) {
                        $ids .= $vv['id'].',';
                    }
                    $ids = trim($ids,',');
                    $wxConfirmUrl = config('app_host').'/crm/weixin/receiveCustomerDetail/cid/'.$ids;
                    $contentSales = [
                        'touser'       => $k,
                        'template_id'  => OPENTM_MFP,
                        'url'          => $wxConfirmUrl,
                        'data'         => [
                            'first'=>[
                                'value'=> '系统消息',
                                'color'=> '#173177'
                            ],
                            'keyword1'=>[
                                'value'=> '您有'.count($v).'笔客资，分配给了'.$cData['sales_staff'].'。',
                                'color'=> '#173177'
                            ],
                            'keyword2'=>[
                                'value'=> $date,
                                'color'=> '#173177'
                            ],
                            'remark'=>[
                                'value'=> '请悉知。',
                                'color'=> '#173177'
                            ],
                        ],
                    ];
                }else{
                    $contentSales = [
                        'touser'       => $k,
                        'template_id'  => OPENTM_MFP,
                        'data'         => [
                            'first'=>[
                                'value'=> '系统消息',
                                'color'=> '#173177'
                            ],
                            'keyword1'=>[
                                'value'=> '您有'.count($v).'笔客资，分配给了'.$cData['sales_staff'].'。',
                                'color'=> '#173177'
                            ],
                            'keyword2'=>[
                                'value'=> $date,
                                'color'=> '#173177'
                            ],
                            'remark'=>[
                                'value'=> '请悉知。',
                                'color'=> '#173177'
                            ],
                        ],
                    ];
                }
                $sendSales['content'] = json_encode($contentSales);
                sendMsg($sendSales);
                unset($ids,$wxConfirmUrl,$sendSales,$contentSales);
            }
        }
        return $returnData;
    }
    // 客资再分配追踪人
    public function anotherAllotSale($param){
        $date = date('Y-m-d H:i:s');
        // 员工信息
        $staffInfo = getStaffInfoById($param['sid']);
        // 分配人
        $cData['fp_staff']       = session('staff_name');
        $cData['fp_staff_id']    = session('staff_id');
        $cData['fp_staff_number']= session('staff_number');
        // 追踪人
        $cData['sales_staff']       = $staffInfo['staffname'];
        $cData['sales_staff_id']    = $param['sid'];
        $cData['sales_staff_number']= $staffInfo['staffnumber'];
        $cData['sales_department_id'] = $staffInfo['department_id'];
        $cData['shop_code'] = $param['shop_code'];
        $cData['shop_name'] = $param['shop_name'];
        // 分配状态及时间
        $cData['fp_day'] = $date;
        $cData['jr_day'] = $date;
        $cData['is_fp']  = FP_STATUS_SUCESS;
        // 分配追踪人
        $cData['update_time'] = $date;
        $cids = explode(',', $param['cid']);
        //追踪人小组信息
        $groupInfo = getGroupInfo($param['sid']);
        // insert log 和 fp_log 数据
        $lData = [];
        $fdata = [];
        $ip = \think\Request::instance()->ip();
        $allot_cids = '';
        foreach ($cids as $key => $value) {
            $has = db('c_customerinfo')->where('id',$value)
                ->field('is_success,is_fp,fp_staff,fp_staff_id,fp_staff_number,fp_day,sales_staff,sales_staff_id,sales_staff_number,jr_day,shop_code,shop_name,brandclass_id')
                ->find();
            // 未定单,未分配客资分配  追踪中，已订单客资不分配
            if ($has['is_success'] == 2) {
                $allot_cids .= $value.',';
                // action_log 用数据
                $lData[$key]['module']     = 'crm';
                $lData[$key]['controller'] = 'Customer';
                $lData[$key]['action']     = 'customerAllotOne';
                $lData[$key]['old_data']   = json_encode($has);
                $lData[$key]['data']       = json_encode($cData);
                $lData[$key]['customer_id']= $value;
                $lData[$key]['staff_name'] = session('staff_name');
                $lData[$key]['staff_id']   = session('staff_id');
                $lData[$key]['ip']         = $ip;
                $lData[$key]['create_time']= $date;
                // 分配日志用数据
                $fData[$key]['cid']              = $value;
                $fData[$key]['fp_model']         = 2;
                $fData[$key]['fp_status']        = 1;
                $fData[$key]['fp_time']          = $date;
                $fData[$key]['jr_time']          = $date;
                $fData[$key]['fp_staff_id']      = session('staff_id');
                $fData[$key]['fp_staff_name']    = session('staff_name');
                $fData[$key]['fp_shop_code']     = session('shop_code');
                $fData[$key]['fp_shop_name']     = session('shop_name');
                $fData[$key]['fp_brandclass_id'] = $has['brandclass_id'];
                $fData[$key]['jr_staff_id']      = $param['sid'];
                $fData[$key]['jr_staff_name']    = $staffInfo['staffname'];
                $fData[$key]['jr_shop_code']     = $has['shop_code'];
                $fData[$key]['jr_shop_name']     = $has['shop_name'];
            }
        }

        $allot_cids = trim($allot_cids, ',');

        if (!strlen($allot_cids)) {
            $returnData['code'] = 200;
            $returnData['msg']  = '分配成功。';
            return $returnData;
        }

        db()->startTrans();
        try {
            // 更新客资表
            db('c_customerinfo')->where('id', 'in', $param['cid'])->update($cData);
            // insertAll action_log fp_log
            db('action_log','db_logs')->insertAll($lData);
            db('l_fp_logs')->insertAll($fData);
            // 删除pool表
            db('c_fp_pool')->where('cid', 'in', $param['cid'])->where('pool_type', 1)->delete();
            //更新追踪人小组信息
            db('c_customer_from')->where('cid','in',$param['cid'])->update(['sales_group_id'=>$groupInfo['id'],'sales_group_name'=>$groupInfo['group_name']]);
            db()->commit();
            $returnData['code'] = 200;
            $returnData['msg']  = '分配成功。';
        } catch (\Exception $e) {
            db()->rollback();
            db('action_log','db_logs')
                ->where('customer_id', 'in', $param['cid'])
                ->where('action', 'customerAllotOne')
                ->where('ip',$ip)
                ->where('staff_name',session('staff_name'))
                ->where('staff_id',session('staff_id'))
                ->where('create_time', $date)
                ->delete();
            $returnData['code'] = 100;
            $returnData['msg']  = '分配失败。';
            $returnData['error']= $e->getMessage();
        }
        return $returnData;
    }

    //选择条件下的类型
    public function searchTwo($data){
        if($data['name']=="customer_type"){//客户类型
            $arr[0]['id']=1;
            $arr[0]['name']="新客资";
            $arr[1]['id']=2;
            $arr[1]['name']="转介绍";
        }elseif($data['name']=="zjs_from"){//转介绍类型
            $arr[0]['id']=1;
            $arr[0]['name']="老顾客转介绍";
            $arr[1]['id']=2;
            $arr[1]['name']="员工亲友转介绍";
        }elseif($data['name']=="customer_channel"){//客资渠道
            $detail=$this->getChannel();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['customer_channel'];
                $arr[$k]['name']=$v['channel_name'];
            }
        }elseif($data['name']=="order_type"){//订单类型
            $arr[0]['id']=1;
            $arr[0]['name']='网付订单';
            $arr[1]['id']=2;
            $arr[1]['name']='线下订单';

        }elseif($data['name']=="access_model_id"){//获取方式
            $detail=$this->accessModel(array('shop_code'=>session('shop_code')));
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['accessmodel'];
            }
        }elseif($data['name']=="consultation_type_id"){//消费类型
            $detail=$this->consumptionType();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['consumption_name'];
            }
        }elseif($data['name']=="customer_cource_id"){//客资来源
            $detail=$this->source();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['cus_name'];
            }
        }elseif($data['name']=="customer_area_id"){//客户分区
            $detail=$this->areaSet(array('shop_code'=>session('shop_code')));
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['area_name'];
            }
        }elseif($data['name']=="customer_region_id"){//客户地域
            $detail=$this->region(array('shop_code'=>session('shop_code')));
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['region_name'];
            }
        }elseif($data['name']=="op_signinfo_id"){
            $detail=$this->markSet();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['mark_name'];
            }
        }elseif($data['name']=="sales_staff_id"){
            /*if(session('is_belong')==1){
                $staff_list=$this->get_staff_lists();
            }elseif(session('is_belong')==2){
                $staff_list=$this->get_staff_lists(array('brandclass'=>session('brandclass')));
            }elseif(session('is_belong')==3||session('is_belong')==4){
                $shop_code = session('belong_shop_code') ? session('belong_shop_code') : session('shop_code');
                $staff_list=$this->get_staff_lists(array('shop_code'=>$shop_code));
            }*/
            $arr = [];
            // crm设置了客资归属店
            $checked_shop = db_config('dj_shops_'.session('shop_code'));
            if ($checked_shop) {
                foreach($checked_shop as $k=>$v){
                    $paramG['shop_code'] = $v['shop_code'];
                    $paramG['work_type'] = RECEIVE_WORK_TYPE;
                    $staff = getShopStaffs($paramG);
                    foreach($staff as $key=>$val){
                        $temp[] = $val;
                    }
                }
                foreach ($temp as $k => $v) {
                    $arr[$k]['id']=$v['id'];
                    $arr[$k]['name']=$v['staffname'];
                }
            }else{
                $data['work_type'] = RECEIVE_WORK_TYPE;
                $data['shop_code'] = session('belong_shop_code') ? session('belong_shop_code') : session('shop_code');
                if(check_right('menu1512637269')){ //查看全部客资
                    $staff_list=getShopStaffs($data);
                    foreach($staff_list as $k=>$v){
                        $arr[$k]['id']=$v['id'];
                        $arr[$k]['name']=$v['staffname'];
                    }
                }elseif(check_right('menu1531471639')){ //查看部门客资
                    $data['department_id'] = $data['department_id'] ? $data['department_id'] : session('department_id');
                    $staff_list=getShopStaffs($data);
                    foreach($staff_list as $k=>$v){
                        $arr[$k]['id']=$v['id'];
                        $arr[$k]['name']=$v['staffname'];
                    }
                }elseif(check_right('menu1529653231')){ //查看小组客资
                    $staff_list=getShopStaffs($data);
                    //查询小组成员，排重，看谁符合 20200910
                    // $group_id = db('c_staff_group_relation')->where('is_admin',1)->where('staff_id',session('staff_id'))->column('group_id');
                    $group_id = db('c_staff_group')->where('shop_code',session('shop_code')) ->where('find_in_set(:id,admin)',['id'=>session('staff_id')])->value('id');
                    $staff = db('c_staff_group_relation')->where('group_id','in',$group_id)->group('staff_id')->column('staff_id');
                    foreach($staff_list as $k=>$v){
                        if(in_array($v['id'],$staff)){
                            $arr[$k]['id']=$v['id'];
                            $arr[$k]['name']=$v['staffname'];
                        }
                    }
                }
            }
            $arr = array_values($arr);
        }elseif($data['name']=="op_signinfo"){
            $detail=controller('Customer','lib')->markSet();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['mark_name'];
            }
        }elseif($data['name']=="sign_id"||$data['name']=="sign_name"){
            $detail=controller('crm/Setting','lib')->gettrackingKmarkerList();
            foreach($detail as $k=>$v){
                //$arr[$k]['id']=$v['id'];//追踪标记先按名称查，以防止电商查不到网销标记的客资-sdm
                $arr[$k]['id']=$v['tracksign'];
                $arr[$k]['name']=$v['tracksign'];
            }
        }elseif($data['name']=="seles_step"){
            $detail=$this->get_seles_step();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['step_stage'];
                $arr[$k]['name']=$v['step_name'];
            }
        }elseif($data['name']=="unvalid_id"){ // 无效原因 20210105
            $mc = new \app\common\lib\mcInterface();
            $temp = $this->getUnValidReason();
            if ($temp) {
                foreach ($temp as $k => $v) {
                    $arr[$k]['id']=$v['id'];
                    $arr[$k]['name']=$v['reason'];
                }
            }
        }elseif($data['name']=="loss_cause"){ // 不再追踪原因
            $reason = db('s_file_reason')->where('shop_code',session('shop_code'))->select();
            if ($reason) {
                foreach ($reason as $k => $v) {
                    $arr[$k]['id']=$v['reason'];
                    $arr[$k]['name']=$v['reason'];
                }
            }
        }elseif($data['name']=="consulation_shop_code"){
            $detail=$this->get_shop(['brandclass_id'=>session('brandclass_id'), 'is_marketing'=>2]);
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['shop_code'];
                $arr[$k]['name']=$v['shop_name'];
            }
        }elseif($data['name']=="is_loss"){
            $arr[0]['id']=2;
            $arr[0]['name']="否";
            $arr[1]['id']=1;
            $arr[1]['name']="是";
        }elseif($data['name']=="customer_sex" || $data['name'] == 'baby_sex'){
            $arr[0]['id']='男';
            $arr[0]['name']="男";
            $arr[1]['id']='女';
            $arr[1]['name']="女";
            if(session('shop_type') == 2){
                $arr[2]['id']='龙凤胎';
                $arr[2]['name']="龙凤胎";
                $arr[3]['id']='双胞胎男';
                $arr[3]['name']="双胞胎男";
                $arr[4]['id']='双胞胎女';
                $arr[4]['name']="双胞胎女";
                $arr[5]['id']="多胞胎";
                $arr[5]['name']="多胞胎";
            }
        }
        // 根据追踪店面查询
        elseif($data['name']=="shop_code"){
            $shopList = [];
            $param['staff_id']        = session('staff_id');
            $param['brandclass_id']   = session('brandclass_id');
            $param['shop_type']       = session('shop_type');
            $param['shop_code']       = session('shop_code');
            $param['belong_shop_code']= session('belong_shop_code');
            $param['belong_shop_name']= session('belong_shop_name');
            $shopList = getBelongShop($param);
            $arr = [];
            foreach ($shopList as $key => $value) {
                $temp['id'] = $value['shop_code'];
                $temp['name'] = $value['shop_name'];
                array_push($arr,$temp);
            }
            unset($param,$shopList);
        }
        elseif($data['name'] == 'dj_group_id' || $data['name'] == 'sales_group_id'){
            $info = db('c_staff_group')->where('shop_code',session('shop_code')) ->where('find_in_set(:id,admin)',['id'=>session('staff_id')])->select();
            $arr = [];
            foreach ($info as $key => $value) {
                $temp['id'] = $value['id'];
                $temp['name'] = $value['group_name'];
                array_push($arr,$temp);
            }
        }
        // 根据追踪部门查询 20200727
        elseif ($data['name']=="sales_department_id") {
            $shop_code = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
            $mc = new \app\common\lib\mcInterface();
            $departmentList = $mc->getDepartmentByShopcode($shop_code);
            $arr = [];
            foreach ($departmentList as $key => $value) {
                $temp['id'] = $value['id'];
                $temp['name'] = $value['department_name'];
                array_push($arr,$temp);
            }
        }
        return $arr;
    }
    //类型查询
    public function searchTypt($data){
        $arr=array('id'=>$data['value']);
        if($data['key']=="customer_channel_id"){//客资渠道
            $detail=$this->channel($arr);
            return array('name'=>$detail[0]['channel_name']);
        }elseif($data['key']=="customer_type"){//客户类型
            if($data['value']==1){
                return array('name'=>"新客资");
            }elseif($data['value']==2){
                return array('name'=>"转介绍");
            }
        }elseif($data['key']=="access_model_id"){//获取方式
            $detail=$this->accessModel($arr);
            return array('name'=>$detail[0]['accessmodel']);
        }elseif($data['key']=="customer_area_id"){//客户分区
            $detail=$this->areaSet($arr);
            return array('name'=>$detail[0]['area_name']);
        }elseif($data['key']=="customer_region_id"){//客户地域
            $detail=$this->region($arr);
            return array('name'=>$detail[0]['region_name']);
        }elseif($data['key']=="customer_orderaddress_id"){//接单点
            $detail=$this->orderAddress($arr);
            return array('name'=>$detail[0]['acceptoraddress_name']);
        }
    }

    //删除客资
    public function delCustomer($ids){
        if(!check_right('menu1512970570')){
            $returnData = array('code' => 10,'msg' =>'没有删除权限');
            return ($returnData);
        }
        $sel=db('c_customerinfo')->where('id','in',implode(',',$ids))->where('is_success','in',[1,3])->select();
        if(!empty($sel)){
            return (array('code' => 101,'msg' =>'存在已订单的客资，不可删除！'));
        }
        db()->startTrans();//开启事务
        try{
            $res=db('c_customerinfo')->where('id','in',implode(',',$ids))->update(['is_status' => '2','update_time'=>date('Y-m-d H:i:s'),'del_time'=>date('Y-m-d H:i:s')]);
            $data=db('c_customerinfo')->field('customer_tel,customer_wechat,customer_qq,mate_tel')->where('id','in',implode(',',$ids))->select();
            /*$contact=array();
            foreach($data as $k => $v){
                if(!empty($v['customer_tel'])){
                    array_push($contact,$v['customer_tel']);
                }
                if(!empty($v['customer_wechat'])){
                    array_push($contact,$v['customer_wechat']);
                }
                if(!empty($v['customer_qq'])){
                    array_push($contact,$v['customer_qq']);
                }
                if(!empty($v['mate_tel'])){
                    array_push($contact,$v['mate_tel']);
                }
            }*/
            db('c_customer_contact')->where('c_id','in',implode(',',$ids))->delete();
            db('c_customer_order')->where('customer_id','in',implode(',',$ids))->update(['is_delete'=>1]);
            //删除pool表数据
            db('c_fp_pool')->where('cid','in',implode(',',$ids))->delete();
            //日志
            $time = date('Y-m-d H:i:s');
            $log = [];
            foreach($ids as $k=>$v){
                $log[$k]['module']='crm';
                $log[$k]['controller']='Customer';
                $log[$k]['action']='delcustomer';
                $log[$k]['ip']=get_client_ip();
                $log[$k]['data']='已删除客资：ID：'.$v;
                $log[$k]['old_data']='未删除';
                $log[$k]['customer_id']=$v;
                $log[$k]['staff_id']=session('staff_id');
                $log[$k]['staff_name']=session('staff_name');
                $log[$k]['create_time']=$time;
            }
            db('action_log','db_logs')->insertAll($log);
            db()->commit();
            $returnData = array('code' => 1,'msg' =>'删除客资成功！','data'=>$ids);
            return ($returnData);
        }catch (\Exception $e){
            db()->rollback();
            $returnData = array('code' => 1000,'msg' =>'删除客资失败','error'=>$e->getMessage());
            return ($returnData);
        }

        //foreach($ids as $k){
        // $res=db('c_customerinfo')->where('id', $k)->update(['is_status' => '2']);
        //}


       // if ($res === false) {
       //     $this->error('删除客资失败');
       // } else {


       //     $this->success('删除客资成功','/',$ids);
       // }
    }


    //获取最新导入excel文件历史记录
    public function new_list($data){
        $limit = $data['limit'] ? $data['limit'] : 10;
        $page = $data['page'] ? $data['page'] : 1;

        $excel=db('c_excel_import')->where(array('staff_id'=>session('staff_id')))->limit($limit)->page($page)->ORDER("addtime desc")->select();
        $count = db('c_excel_import')->where(array('staff_id'=>session('staff_id')))->count();
        $prev = $page-1<1 ? 1 : $page-1;
        $next = $count/$limit>$page ? $page+1 : $page;
        return array('code'=>1,'msg'=>'成功','data'=>$excel,'prev'=>$prev,'next'=>$next,'page'=>$page,'count'=>$count,'last'=>ceil($count/$limit));
//        $this->success('成功','/',$excel);
    }

    //删除导入文件历史
    public function delFile($id){
        $file = db('c_excel_import')->where(array('id' => $id))->find();
        if($file['file_url'])   unlink($file['file_url']);
        if($file['fail_file_url'])   unlink($file['fail_file_url']);
        $res = db('c_excel_import')->where(array('id' => $id))->delete();

        if ($res === false) {
            $this->error('操作失败');
        } else {
            $this->success('操作成功');
        }
    }

    //获取指定个数的excel列名称
    public function stringFromColumnIndex($pColumnIndex = 0)
    {
        static $_indexCache = array();

        if (!isset($_indexCache[$pColumnIndex])) {
            if ($pColumnIndex < 26) {
                $_indexCache[$pColumnIndex] = chr(65 + $pColumnIndex);
            } elseif ($pColumnIndex < 702) {
                $_indexCache[$pColumnIndex] = chr(64 + ($pColumnIndex / 26)) . chr(65 + $pColumnIndex % 26);
            } else {
                $_indexCache[$pColumnIndex] = chr(64 + (($pColumnIndex - 26) / 676)) . chr(65 + ((($pColumnIndex - 26) % 676) / 26)) . chr(65 + $pColumnIndex % 26);
            }
        }
        return $_indexCache[$pColumnIndex];
    }

    //上传excel文件
    function uploadExcel($file,$file_name,$data){
        //ini_set('memory_limit','1024M');
        $info = $file->validate(['ext' => 'xlsx'])->move(ROOT_PATH . 'application' . DS . 'data' . DS . 'excel');//上传验证后缀名,以及上传之后移动的地址
        if ($info) {
            //echo $info->getFilename();
            $exclePath = $info->getSaveName();  //获取文件名
            $file_url = ROOT_PATH . 'application' . DS . 'data'  . DS . 'excel' . DS . $exclePath;   //上传文件的地址
            // $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            // $obj_PHPExcel =$objReader->load($file_url, $encode = 'utf-8');  //加载文件内容,编码utf-8
            // $excel_array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
            // $first=reset($excel_array);
            // //$title=array('customer_name'=>'客户姓名','customer_sex'=>'性别','customer_tel'=>'手机号','customer_wechat'=>'微信','customer_weibo'=>'微博','customer_qq'=>'QQ','province'=>'省','city'=>'市','county'=>'区','customer_address'=>'详细地址','customer_type'=>'客户类型','consultation_type'=>'消费类型','consulation_shop'=>'意向店面','customer_channel'=>'客户渠道','customer_cource'=>'客户来源','customer_intention'=>'客户意向','customer_orderaddress'=>'接单点','access_model'=>'获取方式','customer_area'=>'客户分区','customer_region'=>'客户地域');
            // $title=import_header();//excel标准表头
            // array_shift($excel_array);

            //  检验模板格式
            // if(count($first)!=count($title)){
            //     $this->error('您导入的文件模板格式错误','/');
            // }
            // if(count($excel_array)<1){
            //     $this->error('您导入的文件没有数据','/');
            // }

            $excel_file['file_name']=$file_name;
            $excel_file['file_url']=$file_url;
            $excel_file['staff_id']=session('staff_id');
            $excel_file['staff_name']=session('staff_name');
            $excel_file['addtime']=date('Y-m-d H:i:s',time());
            $excel_file['belong_shop_code']=$data['shop_code'];
            $excel_file['belong_shop_name']=$data['shop_name'];
            //$excel_file['all_number']=count($excel_array);
            unset($excel_array);
            //是否筛客
            $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)){
                    $excel_file['is_sk']=1;//是否筛客
                }
            }

            db()->startTrans();//开启事务
            try {
                $res=db('c_excel_import')->insert($excel_file);
                $id=db('c_excel_import')->getLastInsID();
                db()->commit();
            } catch (Exception $e) {
                db()->rollback();
            }

            $shop_code = $data['shop_code'] ? $data['shop_code'] : (session('belong_shop_code') ? session('belong_shop_code') : session('shop_code'));
            $shop_name = $data['shop_name'] ? $data['shop_name'] : (session('belong_shop_name') ? session('belong_shop_name') : session('shop_name'));
            $message['body']['file_url']=$file_url;
            $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'=>$shop_name,'shop_code'=>$shop_code,'brandclass_id'=>session('brandclass_id'),'brandclass'=>session('brandclass'),'add_shop_code'=>session('shop_code'),'add_shop_name'=>session('shop_name'),'department_id'=>session('department_id'));
            //$message['body']['data']=$excel_array;
            //$message['body']['num']=$num;

            $dir='../application/data/excel/error';
            if (!is_dir($dir)){
                mkdir($dir);
            }
            $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
            $obj_PHPExcel =$objReader->load($file_url, $encode = 'utf-8');  //加载文件内容,编码utf-8
            $array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
            $excel_array = [];
            foreach($array as $k=>$v){
                if($v[0] != '' && $v[0] != null){
                    $excel_array[] = $v;
                }
            }
            array_shift($excel_array);
            $all_number=count($excel_array);
            if($id){
                if($all_number <= 100){
                    try{
                        controller('crm/ExcelImportSync','lib')->cus_import_sync($message['body']);
                    }catch(\Exception $e){
                        echo $e->getMessage();
                        var_dump($e);
                    }

                }else{
                    $resutl=push_list("excelImportRedisList", $message);
                    //redisQueue::init()->rPush('excelImportRedisList', $message);
                    $this->success('客资文件上传成功',"/",$file_name);
                }
            }
        } else {
            echo $file->getError();
        }
    }
    //生成错误文件
    function cusFailFile($fail_file,$header = []){
        // echo '1';exit;
        $PHPExcel = new PHPExcel();
        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle('customer'); //给当前活动sheet设置名称

        if(session('shop_type') ==2 || $fail_file['shop_type'] == 2){
            $title=array('宝宝姓名','宝宝性别','宝宝生日(格式20180101)','预产期','妈妈姓名','妈妈手机号','微信','QQ','微博','爸爸姓名','爸爸手机号','省','市','区','详细地址','客户类型','渠道名称','获取方式','消费类型','客户来源','推广编号','广告落地页','客户分区','客户意向','意向店面','接单点','追踪人','客资备注','转介绍人','关键字','错误原因');
        }else{
            $title=array('客户姓名','性别','手机号','微信','QQ','微博','省','市','区','详细地址','客户类型','渠道名称','获取方式','消费类型','客户来源','客户分区','客户意向','意向店面','接单点','追踪人','客户备注','转介绍人','关键字','错误原因');
        }
        if($header){
            $title = $header;
            $title['error'] = '错误原因';
        }
//        var_dump($header);
//        var_dump($title);
        // echo '-------------------';
        // echo json_encode($title);
        // exit;
        // $title=array('客户姓名','性别','手机号','微信','微博','QQ','省','市','区','详细地址','客户类型','客户渠道','获取方式','消费类型','客户来源','客户分区','客户意向','意向店面','接单点','追踪人','登记人','录入员工id','登记日期','分配人','分配人id','分配日期','接入日期','录入员工部门code','录入员工部门名','事业部名', '事业部ID','是否有效','标记有效时间','预计进店日期','是否进店','实际进店日期','开始追踪日期','错误原因');

        $index = 1;
        $excelTitle = array_values($title);//过渡一下，传header和不传header都可以使用。
        for($i=0;$i<count($excelTitle);$i++){
            $range[$i] = controller("crm/Customer","lib")->stringFromColumnIndex($i);
            $PHPSheet->setCellValue($range[$i].$index, $excelTitle[$i]);
        }
        // var_dump($range);
        // var_dump($fail_file);
        if(count($fail_file['fail_array'])>0){
            foreach($fail_file['fail_array'] as $k=>$v){
                $index++;
                // var_dump(array_values($v));
                if($header){
                    $ii = 0;
                    foreach($title as $kk=>$vv){
                        // echo "<<<"."{$range[$kk]}{$index}".">>>";
                        $PHPSheet->setCellValue("{$range[$ii]}{$index}",$v[$kk]);
                        $ii++;
                    }
                }else{
                    foreach(array_values($v) as $kk=>$vv){
                        // echo "<<<"."{$range[$kk]}{$index}".">>>";
                        $PHPSheet->setCellValue("{$range[$kk]}{$index}",$vv);
                    }
                }
            }
        }
        $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');
        $file_url = ROOT_PATH . 'application' . DS . 'data'  . DS . 'excel';
        $file_name=$file_url."/error/".'error'.$fail_file['eid'].'.xlsx';
        // echo $file_name;
        $PHPWriter->save($file_name);
        return $file_name;
    }

    //导出
    function export($title,$data,$file){
        set_time_limit(0);
        ini_set("memory_limit","512M");
        $PHPExcel = new PHPExcel();
        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
        if (!\PHPExcel_Settings::setCacheStorageMethod($cacheMethod)) {
            die($cacheMethod . " 缓存方法不可用" . EOL);
        }

        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle('customer'); //给当前活动sheet设置名称
        $index = 1;
        for($i=0;$i<count($title);$i++){
            switch ($title[$i]) {
                case '宝宝生日(格式20180101)':
                    $width = 17;
                    break;
                default:
                    $width = 10;
                    break;
            }
            $range[$i] = controller("crm/Customer","lib")->stringFromColumnIndex($i);
            $PHPExcel->setActiveSheetIndex(0);
            $PHPExcel->getActiveSheet()->getColumnDimension($range[$i])->setWidth($width);
            $PHPSheet->setCellValue($range[$i].$index, $title[$i]);
            $PHPExcel->getDefaultStyle()->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
            $PHPExcel->getDefaultStyle()->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        }
        // var_dump($data);
        // exit;
        if(count($data)>0){
            foreach($data as $k=>$v){
                if ($v['customer_type']) {
                    $v['customer_type'] = $v['customer_type']==1?'新客资':'转介绍';
                }
                if ($v['is_valid']) {
                    $v['is_valid'] = getIsValidAttr($v['is_valid']);
                }
                if ($v['is_intostore']) {
                    $v['is_intostore']=getIsIntostore($v['is_intostore']);
                }
                if ($v['is_fp']) {
                    $v['is_fp']=getIsFP($v['is_fp']);
                }
                if ($v['is_success']) {
                    $v['is_success']=getIsSuccess($v['is_success']);
                }
                if ($v['is_loss']) {
                    $v['is_loss']=getIsLoss($v['is_loss']);
                }
                if ($v['order_type'] == 1) {
                    $v['order_type']='线上';
                }elseif($v['order_type'] == 2){
                    $v['order_type']='线下';
                }
                if ($v['c_from'] == 1) {
                    $v['c_from']='CRM';
                }elseif($v['c_from'] == 2){
                    $v['c_from']='ERP';
                }
                if ($v['introducer_type']) {
                    $v['introducer_type']=getIntroducerType($v['introducer_type']);
                }
                if($v['track_record']){
                    $v['track_record'] = strip_tags($v['track_record']);
                }
                $index++;
                foreach(array_values($v) as $kk=>$vv){
                    $PHPSheet->setCellValue("{$range[$kk]}{$index}",$vv);
                }
            }
        }
        $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');
        //header("Content-type:text/html;charset=utf-8");
        header('Content-type: application/vnd.ms-excel');//告诉浏览器输出07Excel文件
        header('Content-Disposition: attachment;filename='.$file);//告诉浏览器输出浏览器名称
        header("Content-Description: File Transfer");
        header('Cache-Control: max-age=0');//禁止缓存
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        $PHPWriter->save("php://output");
        exit;
    }

    //下载源文件
    function before_file($id){
        $data=db('c_excel_import')->where(array('id'=>$id))->find();
        $this->down_file($data['file_url'],$data['file_name']);
    }

    //下载失败文件
    function fail_file($id){
        $data=db('c_excel_import')->where(array('id'=>$id))->find();
        $this->down_file($data['fail_file_url'],'错误数据-'.$data['file_name']);
    }

    //下载文件
    function down_file($url,$name){
        $file=fopen($url,"r");
        header("Content-Type: application/octet-stream");
        header("Accept-Ranges: bytes");
        header("Accept-Length: ".filesize($url));
        header("Content-Disposition: attachment; filename=".$name);
        echo fread($file,filesize($url));
        fclose($file);

    }

    //获取当月任务
    function getRenwu($month){
        $res = db('SKpiStaffgoal')->where('shop_code',session('shop_code'))->where('year',date('Y',time()))->where('position_name',session('main_position_name'))->where('month',$month)->find();

        return $res;
    }
    /*
     * 插入手机归属地信息
     * tel : 男手机号
     * */
    public function insTelInfo($tel){
        //查询是否已有此手机号信息
        $info = $this->getTelInfo($tel);
        if(!empty($info)){
            return $info;
        }
        // $res = preg_match('/^1[3|4|5|6|7|8][0-9]{9}$/', $tel) ? true : false;
        //修改手机号时，查询归属地，区号等
        $telInfo = getData($tel);
        if ($telInfo) {
            // var_dump($telInfo);die;
            $arr = explode(' ',$telInfo);
            if($arr[1] == $arr[2]){
                $customerInfo['tel_belong'] = $arr[1];
            }else{
                $customerInfo['tel_belong'] = $arr[1].' '.$arr[2];
            }
            $customerInfo['tel_operator'] = $arr[3];
            $customerInfo['tel_area_code'] = $arr[5];
            //插入客资电话信息表
            db()->startTrans();
            if($customerInfo['tel_belong']){
                $id = db('c_customer_tel')->insertGetId(['customer_tel'=>$tel,'tel_belong'=>$customerInfo['tel_belong'],'tel_operator'=>$customerInfo['tel_operator'],'tel_area_code'=>$customerInfo['tel_area_code']]);
                if($id){
                    db()->commit();
                    return $customerInfo;
                }else{
                    db()->rollback();
                    return false;
                }
            }else{
                db()->rollback();
                return false;
            }
        }else{
            return false;
        }
    }
    /*
     * 查询手机归属地信息
     * */
    public function getTelInfo($tel){
        $res = db('c_customer_tel')->where('customer_tel',$tel)->find();
        return $res;
    }
    /**
     * 获取客资详情，取c_customerinfo表数据   20200609
     * @param  string $cid customer的id，customInfo表的主键
     * @return array
     * @author Eric
     */
    public function getCustomerInfo($id){

        $customerInfo = db('c_customerinfo')->where('id',(int)$id)->find();
        $customerInfo['telInfo'] = $customerInfo['customer_tel'] ? $this->getTelInfo($customerInfo['customer_tel']) : null;
        $customerInfo['mtelInfo'] = $customerInfo['mate_tel'] ? $this->getTelInfo($customerInfo['mate_tel']) : null;

        $customerInfo['cus_tel'] = $customerInfo['customer_tel'];
        $customerInfo['cus_mate_tel'] = $customerInfo['mate_tel'];
        if(!check_right('menu1512998373')&&session('staff_id')!=$customerInfo['tel_staff_id']){
            $customerInfo['customer_tel'] = !empty($customerInfo['customer_tel']) ? substr($customerInfo['customer_tel'], 0, 3).'****'.substr($customerInfo['customer_tel'], 7) : '';
            $customerInfo['mate_tel'] = !empty($customerInfo['mate_tel']) ? substr($customerInfo['mate_tel'], 0, 3).'****'.substr($customerInfo['mate_tel'], 7) : '';
        }
        if($customerInfo['tel_staff_id']&&session('staff_id')!=$customerInfo['tel_staff_id'])     $customerInfo['auth_tel']='no';

        if(!((check_right('menu1513409629')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id'])&&$customerInfo['customer_qq'])      $customerInfo['auth_qq']='no';
        if(!((check_right('menu1513409629')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id'])&&$customerInfo['customer_wechat'])  $customerInfo['auth_wechat']='no';
        if(!((check_right('menu1513409629')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id'])&&$customerInfo['customer_weibo'])   $customerInfo['auth_weibo']='no';

        if(!((check_right('menu1513409657')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id']))     $customerInfo['auth_customer_channel']='no';
        if(!((check_right('menu1513409684')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id']))     $customerInfo['auth_access_model']='no';
        if(!((check_right('menu1513409704')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id']))     $customerInfo['auth_consultation_type']='no';
        //客户来源
        if(!((check_right('menu1513409882')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id']))     $customerInfo['auth_customer_cource']='no';

        //客资分区 
        if(!((check_right('menu1513410084')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id']))     $customerInfo['auth_customer_area']='no';

        if($customerInfo['customer_remark']){
            $customerInfo['customer_remark'] = strip_tags($customerInfo['customer_remark']);
        }

        $mc = config('ext.app_config');
        $addr = $mc['sx_mc']['addr'];
        $allChannel = getChannels();

        // 渠道图标
        if ($customerInfo['customer_channel_id']) {
            $customerInfo['customer_channel_name'] = $customerInfo['customer_channel'];
            $customerInfo['customer_channel'] = '<img onerror="javascript:this.remove()" src="'.$addr.'/public/channelimg/'.$allChannel[$customerInfo['customer_channel_id']]['channel_info_id'].'.png" style="width:25px;padding-right:5px;">'.$customerInfo['customer_channel'];
        }
        // 消费类型图标
        if ($customerInfo['consultation_type_id']) {
            $customerInfo['consultation_type'] = '<img onerror="javascript:this.remove()" src="'.$addr.'/public/consumptionimg/'.$customerInfo['consultation_type_id'].'.png" style="width:25px;padding-right:5px;">'.$customerInfo['consultation_type'];
        }
        // 客资生日
        if ($customerInfo['customer_birthday']) {
            $customerInfo['customer_birthday'] = date('Y-m-d', strtotime($customerInfo['customer_birthday']));
        }
        // 配偶生日
        if ($customerInfo['mate_birthday']) {
            $customerInfo['mate_birthday'] = date('Y-m-d', strtotime($customerInfo['mate_birthday']));
        }
        // 预产期
        if ($customerInfo['ready_baby_day']) {
            $customerInfo['ready_baby_day'] = date('Y-m-d', strtotime($customerInfo['ready_baby_day']));
        }
        // 宝宝生日
        if ($customerInfo['baby_birthday']) {
            $customerInfo['baby_birthday'] = date('Y-m-d', strtotime($customerInfo['baby_birthday']));
        }
        // 结婚日期
        if ($customerInfo['marry_day']) {
            $customerInfo['marry_day'] = date('Y-m-d', strtotime($customerInfo['marry_day']));
        }

        /* if(!$customerInfo['telInfo'] && $customerInfo['customer_tel']){
             $customerInfo['telInfo'] = $this->insTelInfo($customerInfo['customer_tel']);
             if(empty($customerInfo['telInfo'])){
                 $customerInfo['telInfo'] = $this->insTelInfo($customerInfo['customer_tel']);
             }
         }
         if(!$customerInfo['mtelInfo'] && $customerInfo['mate_tel']){
             $customerInfo['mtelInfo'] = $this->insTelInfo($customerInfo['mate_tel']);
             if(empty($customerInfo['mtelInfo'])){
                 $customerInfo['mtelInfo'] = $this->insTelInfo($customerInfo['mate_tel']);
             }
         }*/
        // $customerInfo['auth'] = check_right('menu1512998373');
        // dump($customerInfo);die;
        // $customerInfo['customer_intention'] = $this->getIntentionName($customerInfo['customer_intention']);
        return $customerInfo;
    }
    /**
     * 获取客资详情，取c_customerinfo表数据
     * @param  string $cid customer的id，customInfo表的主键
     * @return array
     * @author Eric
     */
    public function getCustomerInfoIntostore($id){
        $customerInfo = db('c_customerinfo c')->join('c_customer_intostore i','c.id=i.cid','left')->where('c.id',(int)$id)->where('c.is_status',1)->order('i.id desc')->field('c.id,i.cid,i.yjd_day,i.syjd_day,i.consulation_shop_code,i.consulation_shop_name,i.reception_id,i.reception_name,i.op_signinfo,i.op_signday,i.loss_reason,i.loss_time,i.is_intostore,i.is_success,i.giftinfo,i.costs,i.reback,i.intostore_remark,c.is_valid,c.is_loss,c.customer_number,c.customer_tel,c.customer_wechat,c.customer_qq,c.customer_name,c.mate_tel,c.mate_name,c.mate_wechat,c.mate_qq,c.customer_address,c.consultation_type,c.consultation_type_id,c.customer_channel,c.customer_cource,c.customer_cource_id,c.customer_intention,c.customer_intention_id,c.seles_step,c.op_signinfo_id,c.channel_plan_number,c.customer_orderaddress,c.budget,c.access_model,c.customer_area,c.customer_region,c.next_time,c.marry_day,c.sign_id,c.sign_name,c.province_id,c.city_id,c.county_id,c.customer_capacity,c.customer_capacity_id,c.dj_staff,c.sales_staff,c.dj_staff_id,c.sales_staff_id,c.dj_day,c.order_day,c.yp_day,c.order_start_time,c.totalpay_money,c.fact_money,c.order_number,c.customer_remark,c.shop_name,c.add_shop_name,c.shop_code,c.add_shop_code,c.customer_birthday,c.mate_birthday,c.marry_day,c.customer_sex,c.mate_sex,c.yjd_action_day,c.brandclass_id,c.brandclass,c.sales_department_name,c.dj_department_name,c.baby_name,c.baby_sex,c.add_friend_time,c.baby_birthday,c.customer_label,c.ready_marry_day,c.wechat_status,c.age_area')->find();

        if(empty($customerInfo)){
            $customerInfo = db('c_customerinfo')->where('id',(int)$id)->find();
        }
        $customerInfo['telInfo'] = $this->getTelInfo($customerInfo['customer_tel']);
        $customerInfo['mtelInfo'] = $this->getTelInfo($customerInfo['mate_tel']);

        $customerInfo['cus_tel'] = $customerInfo['customer_tel'];
        $customerInfo['cus_mate_tel'] = $customerInfo['mate_tel'];
        if(!check_right('menu1512998373')&&session('staff_id')!=$customerInfo['tel_staff_id']){
            $customerInfo['customer_tel'] = !empty($customerInfo['customer_tel']) ? substr($customerInfo['customer_tel'], 0, 3).'****'.substr($customerInfo['customer_tel'], 7) : '';
            $customerInfo['mate_tel'] = !empty($customerInfo['mate_tel']) ? substr($customerInfo['mate_tel'], 0, 3).'****'.substr($customerInfo['mate_tel'], 7) : '';
        }
        if($customerInfo['tel_staff_id']&&session('staff_id')!=$customerInfo['tel_staff_id'])     $customerInfo['auth_tel']='no';
        if(!((check_right('menu1513409629')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id'])&&$customerInfo['customer_qq'])      $customerInfo['auth_qq']='no';
        if(!((check_right('menu1513409629')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id'])&&$customerInfo['customer_wechat'])  $customerInfo['auth_wechat']='no';
        if(!((check_right('menu1513409629')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id'])&&$customerInfo['customer_weibo'])   $customerInfo['auth_weibo']='no';

        if(!((check_right('menu1513409657')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id']))     $customerInfo['auth_customer_channel']='no';
        if(!((check_right('menu1513409684')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id']))     $customerInfo['auth_access_model']='no';
        if(!((check_right('menu1513409704')&&($customerInfo['add_shop_code']==session('shop_code')||$customerInfo['shop_code']==session('shop_code')))||session('staff_id')==$customerInfo['dj_staff_id']))     $customerInfo['auth_consultation_type']='no';

        return $customerInfo;
    }
    public function getCustomerInfos($cids){
        $customerInfo = db('c_customerinfo')->where('id','in',$cids)->select();
        return $customerInfo;
    }
    /**
     * 获取客户意向名
     * @param  string $id
     * @return array
     * @author Eric
     */
    public function getIntentionName($id){
        // 客户意向
        $url = '59fd5f6c1d340';
        $intentionName = sx_call($url,$id);
        return $intentionName['data']['intention_name'];
    }
    /**
     * 根据URL，调用端口(空参数)，成功返回data，不成功，返回空数组
     * @param  string 端口url（59fd5ec462c88）
     * 如果通过事业部id查询不到分区，就不传参数查询所有分区
     * @return array
     * @author Eric
     */
    public function callInterface($url, $data){
        $return = [];
        $request = sx_call($url,$data);
        if($request['code'] == 200){
            $return = $request['data'];
        }
        return $return;
    }

    /**
     * 获取客资详情，相关的各种设定（）// 客户分区设定// 客户地域设定// 客户意向设定// 客户来源设定// 接单点设定// 消费类型设定// 消费能力设定// 渠道名称设定// 渠道类型设定// 获取方式设定
     * @param  string
     * @return array
     * @author Eric
     */
    public function getCustomerAllSet($shop_code){
        // 查缓存
//        $return = cache('CustomerAllSet'.$shop_code);
        // $return = false;
//        if (!$return) {
        $data['shop_code'] = $shop_code;

        // 来源渠道
        $channelInfoUrl = '59fd5e729e5a8';
//        $allSet['channelInfo'] = self::callInterface($channelInfoUrl, $data);//mc设定
        $allSet['channelInfo'] = $this->getChannel();//crm设定
        // 客户来源
        $cussourceUrl = '59fd5ec462c88';
        $allSet['cussource'] = self::callInterface($cussourceUrl, $data);
        foreach($allSet['cussource'] as $k=>$v){
            if($v['type_id'] == 0){
                unset($allSet['cussource'][$k]);
            }
        }
        // 获取方式
        $accessModelUrl = '59fd5f0792e10';
        $allSet['accessModel'] = self::callInterface($accessModelUrl, $data);

        // 咨询类型(消费类型)
        $consultationTypeUrl = '59fd58574204a';
        $allSet['consultationType'] = self::consumptionType();

        // 客户意向
        $intentionSetUrl = '59fd5f6c1d340';
        $allSet['intentionSet'] = self::callInterface($intentionSetUrl, $data);

        // 客资地域
        $regionSetUrl = '59fd5fa926b98';
        $allSet['regionSet'] = self::callInterface($regionSetUrl, $data);

        // 客户分区
        $areaSetUrl = '5a004e9c3e030';
        $allSet['areaSet'] = self::callInterface($areaSetUrl, $data);

        // 追踪标记
        // $signSetUrl = "5a0c42f43e986";
        $allSet['signSet'] = $this->markSet();
        //客资标记
        $allSet['sign'] = controller('crm/Setting','lib')->gettrackingKmarkerList();

        //意向店面
        $allSet['intentionShop']=controller('crm/Customer','lib')->get_shop(array('brandclass'=>session('brandclass'),'is_marketing'=>2));

        //追踪失败原因
        $allSet['reason'] = db('s_file_reason')->where('shop_code',session('shop_code'))->select();
        // 消费能力
        $capacityUrl = '5a0c43da3e99a';
        $allSet['capacity'] = self::callInterface($capacityUrl, $data);

        // 邀约人员
        // $url = '';
        // $allSet[''] = self::callInterface($url);

        // 分配人员
        // $url = '';
        // $allSet[''] = self::callInterface($url);

//            $CustomerAllSet = json_encode($allSet);
        // 存缓存
//            $return = cache('CustomerAllSet'.$shop_code, $CustomerAllSet);
//            $return = $CustomerAllSet;
//        }
        return $allSet;
    }
    /**
     * 获取客资追踪记录，取c_salestrackinginfo表数据
     * @param  string   cid       客资id
     * @param  string   c_unique  客资唯一编号
     * @return array
     * @author Eric
     */
    public function getCustomerTrackInfos($id,$unique=''){
        
        // 客资信息
        // $trackInfo = cache('track_log_cid_'.$id);
        $field = 'c.id,c.customer_name,c.customer_tel,c.customer_wechat,c.customer_channel,c.customer_label,c.sign_name,c.is_success,c.is_intostore,s.sales_staff,s.sales_day,s.sales_remark,s.audio_path,c.c_from,c.dj_staff,c.dj_day,s.gtType';

        if(empty($trackInfo)){
            $info = db('c_customerinfo')->alias('c')
                ->join('c_salestrackinginfo s','c.id=s.customer_id','left')
                // ->where('c.c_from', 1)
                ->where('c.is_status',1)->where('c.is_examine',1)
                ->where('s.customer_id',$id)
                ->order('s.sales_day desc')
                ->field($field)
                ->select();
                
                
            if(!check_right('menu1512998373')) {
                foreach ($info as $k => $v) {
                    $info[$k]['customer_tel'] = !empty($v['customer_tel']) ? substr($v['customer_tel'], 0, 3) . '****' . substr($v['customer_tel'], 7) : '';
                }
            }
            foreach ($info as $key => $value) {
                $trackInfo[$value['id']]['id'] = $value['id'];
                $trackInfo[$value['id']]['customer_name'] = $value['customer_name'];
                $trackInfo[$value['id']]['customer_tel'] = $value['customer_tel'];
                $trackInfo[$value['id']]['mate_name'] = $value['mate_name'];
                $trackInfo[$value['id']]['mate_tel'] = $value['mate_tel'];
                $trackInfo[$value['id']]['customer_wechat'] = $value['customer_wechat'];
                $trackInfo[$value['id']]['customer_channel'] = $value['customer_channel'];
                $trackInfo[$value['id']]['customer_label'] = $value['customer_label'] ? explode(',',$value['customer_label']) : [];
                $trackInfo[$value['id']]['sign_name'] = $value['sign_name'];
                $trackInfo[$value['id']]['is_success']=getIsSuccess($value['is_success']);
                $trackInfo[$value['id']]['is_intostore'] = getIsIntostore($value['is_intostore']);
                if ($value['c_from']==2 && $value['is_success']!=2) {
                    $value['sales_staff'] = $value['dj_staff'];
                    $value['sales_day']   = $value['dj_day'];
                    $value['sales_remark']= 'ERP开单';
                }
                $trackInfo[$value['id']]['track'][$key]['sales_staff'] = $value['sales_staff'];
                $trackInfo[$value['id']]['track'][$key]['sales_day']   = $value['sales_day'];
                $trackInfo[$value['id']]['track'][$key]['sales_remark']= $value['sales_remark'];
                $trackInfo[$value['id']]['track'][$key]['audio_path']  = $value['audio_path'];
                $trackInfo[$value['id']]['track'][$key]['gtType']  = $value['gtType'];
            }
            // cache('track_log_cid_'.$id,$trackInfo,1800);
        }
        return $trackInfo;
    }


    /**
     * 获取客资修改日志记录，取crm_logs库action_logs表
     * @param  string $cNumber；customer的customer_number
     * @return array
     * @author Eric
     */
    public function getCustomerChangeLogs($cid){
        $changeLogs = array();
        $where = array(
            'customer_id'=> $cid,
            'controller' => ['in',['Customer','App']],
//            'action'     => 'customerinfo'
        );
        $changeLogs = db('action_log','db_logs')->where($where)->order('create_time desc')->select();
        return $changeLogs;
    }

    /**
     * 获取客资历史订单，现在没有，需要调其他接口
     * @param  string
     * @return array
     * @author Eric
     */
    public function getCustomerHistoryOrders($cid){
//        $changeLogs = cache('getCustomerHistoryOrders'.$cid);
//        if(!$changeLogs){
        $changeLogs = db('CCustomerOrder')->where('customer_id',$cid)->order("id desc")->select();
//            cache('getCustomerHistoryOrders'.$cid,json_encode($changeLogs));
//        }

        return $changeLogs;
    }

    /**
     * 获取同一个事业部下，重复  手机号,微博，微信，qq的   数量
     * @param  string cTel， 客户电话号
     * @param  string bClass 客户所属事业部（品牌）
     * @return int
     * @author Eric
     */
    public function countCustomerCondition($condition, $value, $bClass){
        $where = array(
            $condition   => $value,
            'brandclass' => $bClass
        );
        $count = db('c_customerinfo')->where($where)->count();
        return $count;
    }


    /**
     * 查看cache中是否存在对应规则及员工集合
     * @param  str    shop_code
     * @return array  rules 规则集合
     * @author Eric
     */
    public function getFpRuleStaffs($shop_code){
         $ruleStaffs = cache('fpRuleStaffs_'.$shop_code);
        if (!$ruleStaffs) {
            $rules  = controller("crm/Setting","lib")->getRule($shop_code);
            $ruleStaffs = $this->getStaffs($rules, $shop_code);
            cache('fpRuleStaffs_'.$shop_code, $ruleStaffs);
        }
        return $ruleStaffs;
    }

    /**
     * 根据规则集合，查询所有符合分配规则的员工集合
     * @param  array  rules 规则集合
     * @return array
     * @author Eric
     */
    public function getStaffs($rules, $shopCode){
        // 调mc接口
        foreach ($rules as $key => $value) {
            // 如果是按照 部门、职位 分配，查mc表 如果部门或者岗位为空，则查询店下所有员工
            if ($value['department_name']) {
                $url = '5a0a624728618';
                $data = array(
                    'department_id'=>$value['department_id'],
                    'shop_code'    =>$shopCode
                );
                $res = sx_call($url, $data);
                if ($res['code'] == 200) {
                    $staff = $res['data'];
                }
                // echo '1';
                // var_dump($staff);
            }
            else if ($value['position_name']) {
                $url = '5a0a624728618';
                $data = array(
                    'position_id'=>$value['position_id'],
                    'shop_code'  =>$shopCode
                );
                $res = sx_call($url, $data);
                if ($res['code'] == 200) {
                    $staff = $res['data'];
                }
                // echo '2';
                // var_dump($staff);
            }
            // exit;
            // 如果按照 小组 分配，查crm表
            else if ($value['group_name']) {
                $staff = controller("crm/Statistics","lib")->getStaffs($value['group_id']);
                // echo '3';
                // var_dump($staff);
            }else if ($value['staff_type']) {
                switch ($value['staff_type']) {
                    case 'department_name':
                        $temp = json_decode($value['staff_value'], true);
                        $did  = $temp[0]['department_id'];
                        $url  = '5a0a624728618';
                        $data = array(
                            // 'department_id'=>$value['department_id'],
                            'department_id'=>$did,
                            'shop_code'    =>$shopCode
                        );
                        $res = sx_call($url, $data);
                        if ($res['code'] == 200) {
                            $staff = $res['data'];
                        }
                        break;
                    case 'position_name':
                        $temp = json_decode($value['staff_value'], true);
                        $pid  = $temp[0]['position_id'];
                        $url  = '5a0a624728618';
                        $data = array(
                            // 'position_id'=>$value['position_id'],
                            'position_id'=>$pid,
                            'shop_code'  =>$shopCode
                        );
                        $res = sx_call($url, $data);
                        if ($res['code'] == 200) {
                            $staff = $res['data'];
                        }
                        break;
                    case 'group_name':
                        $temp = json_decode($value['staff_value'], true);
                        $gid  = $temp[0]['group_id'];
                        $staff= controller("crm/Statistics","lib")->getStaffs($gid);
                        break;
                    case 'staff_name':
                        $temp = json_decode($value['staff_value'], true);
                        $staff = [];
                        foreach ($temp as $k => $val) {
                            $staff[$k]['id'] = $val['staff_id'];
                            $staff[$k]['staffname'] = $val['staff_name'];
                            $saInfo = getStaffInfoById($val['staff_id']);
                            $staff[$k]['staffnumber'] = $saInfo['staffnumber'];
                        }
                        break;
                }
            }
            // exit;
            // 分配方式 传递
            $atype = $value['allocationtype'];
            $atypev= $value['allocationtype_value'];
            $atime = $value['active_time'];

            // 分配方式
            $staffs[$key]['allocationtype'] = $value['allocationtype'];
            $staffs[$key]['allocationtype_value'] = $value['allocationtype_value'];

            // 客资筛选方式
            $staffs[$key]['customer_condition'] = $value['customer_condition'];
            $staffs[$key]['customer_value'] = $value['customer_value'];

            // 规则id
            $staffs[$key]['id'] = $value['id'];
            // 员工
            $staffs[$key]['member'] = self::getMembers($staff, $atype, $atypev, $atime);
        }
        $staffsJ = json_encode($staffs);
        return $staffs;
    }
    // 查询
    public static function getMembers($staff, $atype, $atypev,$atime){
        // 按条件分配
        if ($atype==1) {
            // 根据分配规则排序员工  LT：录入；YT：标记有效；DT：有效成单数
            $target = new Target();
            $targetList = $target->getAllTarget();
            if(!key_exists($atypev, $targetList)){
                return $staff;
            }
            $targetMethod = $targetList[$atypev]['method'];
            $day = getdateArea($atime);
            foreach ($staff as $k => $v) {
                $condition = [
                    'staff_id'  => $v['id'],
                    'start_day' => $day[0],
                    'end_day'   => $day[1],
                ];
                $staff[$k]['rate'] = $target->$targetMethod($condition);
            }

            $staff = my_sort($staff, 'rate', 'SORT_DESC');
            return $staff;
            /*
            switch ($atypev) {
                // 订单转化率:order_rate DT/YT
                case 'order_rate':
                    // 时间区域
                    $date = getdateArea($atime);
                    foreach ($staff as $k => $v) {
                        $dt = db('c_day_number')
                            ->where('addtime','between',[$date[0], $date[1]])
                            ->where('staff_id', $v['id'])
                            ->sum('valid_order');
                        $yt = db('c_day_number')
                            ->where('addtime','between',[$date[0], $date[1]])
                            ->where('staff_id', $v['id'])
                            ->sum('valid_customer');
                        $staff[$k]['rate'] = $dt/$yt;
                    }
                    $staff = my_sort($staff, 'rate');
                    break;
                // 进店转化率:in_rate 实际进店数，进客(st)/YT
                case 'in_rate':
                    // 时间区域
                    $date = getdateArea($atime);
                    foreach ($staff as $k => $v) {
                        $st = db('c_day_number')
                            ->where('addtime','between',[$date[0], $date[1]])
                            ->where('staff_id', $v['id'])
                            ->sum('syjd_jk');
                        $yt = db('c_day_number')
                            ->where('addtime','between',[$date[0], $date[1]])
                            ->where('staff_id', $v['id'])
                            ->sum('valid_customer');
                        $staff[$k]['rate'] = $st/$yt;
                    }
                    $staff = my_sort($staff, 'rate');
                // 客资有效率:customer_rate YT/LT
                case 'customer_rate':
                    // 时间区域
                    $date = getdateArea($atime);
                    foreach ($staff as $k => $v) {
                        $yt = db('c_day_number')
                            ->where('addtime','between',[$date[0], $date[1]])
                            ->where('staff_id', $v['id'])
                            ->sum('valid_customer');
                        $lt = db('c_day_number')
                            ->where('addtime','between',[$date[0], $date[1]])
                            ->where('staff_id', $v['id'])
                            ->sum('dj_customer');
                        $staff[$k]['rate'] = $yt/$lt;
                    }
                    $staff = my_sort($staff, 'rate');
                    break;
                default:

                    break;
            }
            //*/
        }else{ // 平均分配
            $staff = my_sort($staff, 'id');
        }
        // $staff = my_sort($staff, 'id');
        return $staff;
    }

    // 根据员工集合 返回集合中在线的员工
    public function getMemberOnline($members){
        $memberOnline = [];
        foreach ($members as $key => $value) {
            $salf_not_online_is_fp = db_config('not_online_is_fp_'.$value['id']);
            // echo 'no1--|'.json_encode($value).'|\r\n';
            // 员工是否在线
            $connect = $salf_not_online_is_fp ? true : self::getStaffOnlineStatus($value['id']);
            // echo 'no2--|'.$connect.'|\r\n';
            if (!$connect) {
                continue;
            }else{
                $memberOnline[$key] = $value;
            }
        }
        // var_dump($memberOnline);
        // exit;
        // echo 'memberOnline1:'.json_encode($memberOnline);
        $memberOnline = my_sort($memberOnline, 'id');
        // echo 'memberOnline2:'.json_encode($memberOnline);
        return $memberOnline;
    }

    // 平均（P）分配客资 customerID, ruleID, 员工集合
    public function fpCustomerP($cid, $rid, $staffs){
        // 当前应该分配的key值
        $key = cache('fpCustomerP'.$rid);
        // 如果key存在
        $num = count($staffs);
        if (!$key || $key >= $num) {
            $key = 0;
        }
        // var_dump($num);
        $sales_staff = [
            'sales_staff_id'    => $staffs[$key]['id'],
            'sales_staff'       => $staffs[$key]['staffname'],
            'sales_staff_number'=> $staffs[$key]['staffnumber'],
            'sales_department_id' =>$staffs[$key]['department_id'],
        ];
        $next = $key+1;
        cache('fpCustomerP'.$rid, $next);
//        cache('fpCustomerP-num-'.$rid, $num);
        return $sales_staff;
        // var_dump($next);
        // exit;
        // foreach ($staffs as $k => $v) {
        //     // $key 大于 $k 跳出循环
        //     if ($key > $k) {
        //         continue;
        //     }
        //     // 查看员工是否在线
        //     $connect = self::getStaffOnlineStatus($v['id']);
        //     // 如果员工不在线跳出循环
        //     if ($connect === false) {
        //         continue;
        //     }else{ // 如果员工在线记录员工信息，计算下一个要分配的key值 并存到缓存
        //         $next = $key+1;
        //         cache('fpCustomerP'.$rid, $next);
        //         $sales_staff = [
        //             'sales_staff_id'    => $v['id'],
        //             'sales_staff'       => $v['staffname'],
        //             'sales_staff_number'=> $v['staffnumber'],
        //         ];
        //         break;
        //     }
        // }
        // 返回要分配的员工信息
        return $sales_staff;
    }

    // 按条件（T）分配客资
    public function fpCustomerT($cid, $rid, $staffs){
        // 找出员工列表中不忙的
        $saleId = '';
        $temp   = '';
        $newStaff = [];
        foreach ($staffs as $key => $value) {
            // 员工是否在线
            $connect = self::getStaffOnlineStatus($value['id']);
            if (!$connect) {
                continue;
            }
            $newStaff[$key] = $value;

            // 查找处理中的客资数量
            $where = array(
                'sales_staff_id'=> $value['id'],
                'c_end_day'     => null
            );
            $count = db('c_customerinfo')->where($where)->count();
            $newStaff[$key]['count'] = $count;
        }
        $newStaff = my_sort($newStaff, 'count');
        $staff = array_shift($newStaff);

        $sales_staff['sales_staff_id']     = $staff['id'];
        $sales_staff['sales_staff']        = $staff['staffname'];
        $sales_staff['sales_staff_number'] = $staff['staffnumber'];
        $sales_staff['sales_department_id'] = $staff['department_id'];
        return $sales_staff;
    }

    // 获取 店面 设定的 接收超时时间 Eric
    public function getShopTimeout(){
        $key = 'fp_timeout_'.session('shop_code');
        $timeOut = cache($key);
        if (!$timeOut) {
            $res = db('c_sysconfig')->where('ckey', $key)->find();
            $timeOut = $res['cvalue'];
            cache($key, $timeOut);
        }
        return $timeOut;
    }

    // 获取错误信息
    public function getError(){
        return ['errid'=>$this->errid,'errmsg'=>$this->errmsg];
    }

    // 更新客资(customerinfo)及消息表(message)，开启事务 Eric
    public function updateCM($dataC, $whereC, $dataM, $whereM){

        // 开启事务
        db()->startTrans();
        try {
            $dataC['update_time'] = date('Y-m-d H:i:s');
            db('c_customerinfo')->where($whereC)->update($dataC);
            db('c_message')->where($whereM)->update($dataM);
            db()->commit();
            // $this->errmsg = db()->getLastSql();
            return true;
        } catch (Exception $e) {
            $error = db()->getLastSql();
            $this->errid = 1;
            $this->errmsg= $error;
            db()->rollback();
            return false;
        }
    }
    public function getMessageById($id){
        $msgInfo = db('c_message')->find((int)$id);

        return $msgInfo;

    }
    public function getMessageByCustomerId($customerId){
        $msgInfo = db('c_message')->where('customer_id',(int)$customerId)->find();
        return $msgInfo;
    }
    // 获取最新的消息
    public function getMessageList($mid){
        $time = time();
        // 存在获取mid之后的消息
        $where = array(
            'receive_id'=> session('staff_id'),
            'is_delete' => 0
        );
        if ($mid && $mid != 0) {
            // 最新的消息 大于mid的消息
            $messageList = db('c_message')
                ->where($where)
                ->where('id','gt',$mid)
                ->order('read_status asc')
                ->order('id desc')
                ->limit(10)
                ->select();
            //echo db()->getLastSql();
        }
        // 不存在，获取倒数10条
        else{
            // 最新的消息id
            $messageList = db('c_message')->where($where)->order('read_status asc')->order('id desc')->limit(10)->select();
            // echo db('c_message')->getLastSql();
        }
        foreach ($messageList as $key => $value) {
            $timeOut = $value['time_out'] - $time;

            // 可操作，未接收，未超时
            if ($value['operation_type']==1 && $value['receive_status']==0 && $timeOut<DEFAULT_SECOND) {
                $messageList[$key]['operation'] = '';
                $messageList[$key]['operation_type'] = 2;
            }else{
                $messageList[$key]['operation'] = json_decode($value['operation'],true);
            }
        }
        //$messageList = my_sort($messageList, 'id');
        return $messageList;
    }

    // 获取最新的 弹框 消息
    public function getPopList($mid){
        $time = time();
        $gtime = $time-DEFAULT_SECOND;
        // 存在获取mid之后的消息
        if ($mid && $mid != 0) {
            $where = array(
                'receive_id'=> session('staff_id'),
                'send_type' => 1,
                'is_delete' => 0
            );
            $popList = db('c_message')
                ->where($where)
                ->where('id','gt',$mid)
                ->where('time_out', 'gt', $gtime)
                ->order('id desc')
                ->limit(5)
                ->select();
        }
        // 不存在，获取倒数5条
        else{
            $where = array(
                'receive_id'=> session('staff_id'),
                'send_type' => 1,
                'is_delete' => 0
            );
            $popList = db('c_message')
                ->where($where)
                ->where('time_out', 'gt', $time)
                ->order('id desc')
                ->limit(5)
                ->select();
            // echo db()->getLastSql();
        }
        $arr = [];
        $arrIds = [];

        foreach ($popList as $key => $value) {
            $timeOut = $value['time_out'] - $time;

            if ($value['send_type'] == 1 && $value['read_status'] == 0 && $timeOut > 0) {
                array_push($arr,$value['customer_id']);
                array_push($arrIds,$value['id']);
                $popList[$key]['pop_status'] = 1;
                $popList[$key]['time_out'] = $timeOut;
                $popList[$key]['operation'] = json_decode($value['operation'],true);
            }
        }
        $num = count($arr);
        if($num>3){
            $popList = [];
            $ids = implode(',',$arr);
            $mids = implode('_',$arrIds);
            $msg['id'] = $mids;
            $msg['send_type'] = 1;
            $msg['send_id'] = -1;
            $msg['send_name'] = 'system';
            $msg['send_time'] = date('Y-m-d H:i:s');
            $msg['send_title'] = '分配提醒';
            $msg['send_msg'] = '您收到'.$num.'笔客资，请注意查收！';
            $msg['operation_type'] = 1;
            $msg['operation'][0] = ['button'=>'接收','url'=>'/crm/Customer/customerReceive.html?cid='.$ids.'&'];
            $msg['operation'][1] = ['button'=>'放弃','url'=>'/crm/Customer/customerDrop.html?cid='.$ids.'&'];
            $msg['time_out'] = $timeOut;
            $msg['customer_id'] = $ids;
            $msg['receive_id'] = session('staff_id');
            $msg['receive_name'] = session('staff_name');
            $msg['receive_status'] = 0;
            $msg['is_delete'] = 0;
            $msg['pop_status'] = 1;
            array_push($popList,$msg);
        }

//        $popList = my_sort($popList, 'id');
//        dump($popList);die;
        return $popList;
    }

    // 获取最近一条消息的id
    public function getNewMessageId(){
        $where = array(
            'receive_id'=> session('staff_id'),
            'is_delete' => 0
        );
        // 最新的消息id
        $mid = db('c_message')->where($where)->max('id');
        return $mid;
    }

    // 获取未读消息的数目 Eric
    // params maxId int 最大消息ID，如果传了，则只取小于此ID的未读消息数量---songdemei
    //
    public function getNewMessageNum($maxId = 0){
        $where = [
            'receive_id' => session('staff_id'),
            'read_status'=> 0,
            'is_delete'  => 0,
        ];
        $time = time()-DEFAULT_SECOND;
        $msg = db('c_message')
            ->where($where);
        if((int)$maxId > 0){
            $msg->where('id','<=',$maxId);
        }
        $num = $msg
            // ->where('time_out', 'lt', $time)
            ->count();
        return $num;
    }

    // 客户端请求监听  Eric
    public function webSubscribe($channel, $callback){

        $message = '';
        $staffid = session('staff_id');
        while (!$message || $message['receive_id'] != $staffid) {
            $res = redisQueue::init()->subscribe($channel, $callback);
            // 监听频道超时
            if ($res === false) {
                return false;
            }
            $message = json_decode($res ,true);
        }
        $time = time();
        $message['time_out'] = $message['time_out']-$time;
        $message['operation']= json_decode($message['operation'], true);
        return $message;
    }

    /*------------------------移动端方法------start------------------------*/
    //提报记录
    public function customerTiBao($param){
        $page = $param['page'] ? $param['page'] : 1;
        $limit = 5;
        if($param['time'] == 1){
            $time = 'month';
        }elseif($param['time'] == 2){
            $time = 'last month';
        }else{
            $time = 0;
        }
        if($param['time1']){
            $time1 = $param['time1'];
        }
        if($param['time2']) {
            $time2 = $param['time2'];
        }
        $sql = ' c_from=1 and is_status=1 and is_loss=2 ';
        if($param['flag'] == 1){//提报
            $sql .= ' and dj_staff_id='.session('staff_id');
        }elseif($param['flag'] == 2){//分配给我的
            $sql .= ' and is_fp=1 and sales_staff_id='.session('staff_id');
        }else{//全部
            $sql .= ' and dj_staff_id='.session('staff_id') .' or (is_fp=1 and sales_staff_id='.session('staff_id').')';
        }
        if($param['time2']){
            if($param['time1'] == $param['time2']){
                $res = db('CCustomerinfo')
                    ->where('is_status',1)
                    ->where('c_from',1)
                    ->where('customer_name|customer_tel','like','%'.$param['search'].'%')
                    ->where($sql)
                    ->whereTime('dj_day',$time1)
                    ->order('id desc')
                    ->page($page,$limit)
                    ->select();

                $res['count'] = db('CCustomerinfo')
                    ->where('is_status',1)
                    ->where('c_from',1)
                    ->where('customer_name|customer_tel','like','%'.$param['search'].'%')
                    ->where($sql)
                    ->whereTime('dj_day',$time1)
                    ->order('id desc')
                    ->count('id');
            }else{
                $res = db('CCustomerinfo')
                    ->where('is_status',1)
                    ->where('c_from',1)
                    ->where('customer_name|customer_tel','like','%'.$param['search'].'%')
                    ->where($sql)
                    ->whereTime('dj_day','between',["$time1","$time2"])
                    ->order('id desc')
                    ->page($page,$limit)
                    ->select();

                $res['count'] = db('CCustomerinfo')
                    ->where('is_status',1)
                    ->where('c_from',1)
                    ->where('customer_name|customer_tel','like','%'.$param['search'].'%')
                    ->where($sql)
                    ->whereTime('dj_day','between',["$time1","$time2"])
                    ->order('id desc')
                    ->count('id');
            }

        }else{
            $res = db('CCustomerinfo')
                ->where('is_status',1)
                ->where('c_from',1)
                ->where('customer_name|customer_tel','like','%'.$param['search'].'%')
                ->where($sql)
                ->whereTime('dj_day',$time)
                ->order('id desc')
                ->page($page,$limit)
                ->select();

            $res['count'] = db('CCustomerinfo')
                ->where('is_status',1)
                ->where('c_from',1)
                ->where('customer_name|customer_tel','like','%'.$param['search'].'%')
                ->where($sql)
                ->whereTime('dj_day',$time)
                ->order('id desc')
                ->count('id');
        }

        return $res;
    }
    //提报记录
    public function customerTiBaoByTime($time){
        if($time == 1){
            $res = db('CCustomerinfo')
                ->where('is_status',1)
                ->where('c_from',1)
                ->where('dj_staff_id',session('staff_id'))
                ->where("dj_day",'like',"%".date('Y-m')."%")
                ->order('dj_day desc')
                ->select();
        }elseif($time == 2){
            $res = db('CCustomerinfo')
                ->where('is_status',1)
                ->where('c_from',1)
                ->where('dj_staff_id',session('staff_id'))
                ->where("dj_day",'like',"%".date('Y-m',strtotime('-1 month'))."%")
                ->order('dj_day desc')
                ->select();
        }
        return $res;
    }
    //提报记录
    public function customerTiBaoBT($time){
        $res = db('CCustomerinfo')
            ->where('is_status',1)
            ->where('c_from',1)
            ->where('dj_staff_id',session('staff_id'))
            ->where("dj_day",'between',[$time['time1'],$time['time2']])
            ->order('dj_day desc')
            ->select();
        return $res;
    }
    //当月提报
    public function getMonthTB(){
        //crm提报的新客资
        $res = db('CCustomerinfo')
            ->where('dj_staff_id',session('staff_id'))
            ->where("dj_day",'like',"%".date('Y-m')."%")
            ->where('customer_type',1)
            ->where('c_from',1)
            ->where('is_status',1)
            ->count();
        //crm提报的转介绍客资
        $res1 = db('CCustomerinfo')
            ->where('dj_staff_id',session('staff_id'))
            ->where("dj_day",'like',"%".date('Y-m')."%")
            ->where('customer_type',2)
            ->where('c_from',1)
            ->where('is_status',1)
            ->count();
        return [$res,$res1];
    }
    //当月转化率
    public function getMonthZH(){
        $jindian = db('CCustomerinfo')
            ->where('dj_staff_id',session('staff_id'))
            ->where("syjd_day",'like',"%".date('Y-m')."%")
            ->where('is_intostore',2)
            ->where('c_from',1)
            ->where('is_status',1)
            ->field('id')
            ->count();
        $succ = db('CCustomerinfo')
            ->where('dj_staff_id',session('staff_id'))
            ->where("order_day",'like',"%".date('Y-m')."%")
            ->where('is_success',1)
            ->where('c_from',1)
            ->where('is_status',1)
            ->field('id')
            ->count();

        return sprintf('%.2f',($succ/$jindian)*100);
    }
    //移动端客资名搜索
    public function customerNameSearch($name){
        $is_erp = is_install('sx_erp');
        if($is_erp){
            $erp = config('ext.app_config')['sx_erp'];
            // 店面类型 （1：婚纱；2：儿童；3：旅拍；4：艺术；5：其他）
            $shop_type = session('shop_type');
            if ($shop_type == 2) {
                $shop_type = 1;
                $addr = $erp['addr_child'];
                $url = trim($addr,'/').'/SX_ChildCrmApi/Sel_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Customerinfo='.$name.'&Brandid='.session('brandclass_id').'&shop_code=""';
            }else{
                $shop_type = 0;
                $addr = $erp['addr'];
                // 婚纱0，儿童1
                $url = trim($addr,'/').'/SX_CrmApi/Sel_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Customerinfo='.$name.'&Brandid='.session('brandclass_id').'&shop_code=""';
            }
            // $url = $addr.'SX_CrmApi/Sel_CustomerOrderInfo?Token=^******^&CustomerType=0'.'&Customerinfo=黑&Shop_code=ZX002';
            $data = '';
            $res = requestERP($url, $data);
            $staffInfo = $this->get_staff_list();
            $staff = array_column($staffInfo,'id','staffname');
            if($res['Code'] == 200){
                foreach($res['Data'] as $k=>$v){
                    // 如果查询条件与男士姓名或者男士手机号一致 显示男士信息 否则显示女士信息
                    if ($name == $v["mname"] || $name == $v["mphone"]) {
                        $res['Data'][$k]['customer_name'] = $v["mname"];
                        $res['Data'][$k]['customer_tel'] = $v["mphone"];
                    }else{
                        $res['Data'][$k]['customer_name'] = $v["wname"];
                        $res['Data'][$k]['customer_tel'] = $v["wphone"];
                    }
                    $res['Data'][$k]['order_number'] = $v["orderId"];
                    $res['Data'][$k]['customer_number'] = $v["customer_from_index"] ? $v["customer_from_index"] : '';
                    $res['Data'][$k]['introducer_type'] = $v["order_type"] < 3 ? '新客' : ($v['order_type'] >= 3 and $v['order_type'] < 6 ? '现客' :($v['order_type'] >= 6 ? '老客' : '新客'));
                    $res['Data'][$k]['shop_code'] = $v["shop_code"] ? $v["shop_code"] :'';
                    $res['Data'][$k]['shop_name'] = $v["shop_name"] ? $v["shop_name"] :'';
                    $res['Data'][$k]['reception_id'] = $staff[$v['storeconsuitant1']] ? $staff[$v['storeconsuitant1']] :0;
                    $res['Data'][$k]['reception_name'] = $v["storeconsuitant1"] ? $v["storeconsuitant1"] :'';
                    // $res['Data'][$k]['sales_staff'] = $v["storeconsuitant2"] ? $v["storeconsuitant1"] :$v["storeconsuitant1"];
                }
            }else{
                $res = array('Code'=>'300','Msg'=>'未查询到订单数据','Data'=>'');
            }
            return ($res);
        }else{
            $res = db('CCustomerinfo')
                ->where('customer_name|customer_tel|mate_tel|mate_name|order_number','like','%'.$name.'%')
                ->where('order_number','<>','')
                ->where('add_shop_code',session('shop_code'))
                ->field('customer_name,customer_tel,order_number,introducer_type,customer_number,mate_tel,shop_code,shop_name,reception_id,reception_name')
                ->select();
            if(empty($res)){
                return array('Code'=>'300','Msg'=>'未查询到订单数据','Data'=>'');
            }else{
                foreach($res as $k=>$v){
                    $res[$k]['introducer_type'] = $v["introducer_type"] == 1 ? '新客' : ($v['introducer_type'] == 2 ? '现客' :($v['introducer_type'] >= 3 ? '老客' : '新客'));
                }
                return array('Code'=>'200','Msg'=>'查询成功','Data'=>$res);
            }
        }
    }
    //appwxerp  客资名搜索
    public function customerNameSearchAppwx($name){
        $is_erp = is_install('sx_erp');
        if($is_erp){
            $erp = config('ext.app_config')['sx_erp'];
            // 店面类型 （1：婚纱；2：儿童；3：旅拍；4：艺术；5：其他）
            $shop_type = session('shop_type');
            if ($shop_type == 2) {
                $shop_type = 1;
                $addr = $erp['addr_child'];
                $url = trim($addr,'/').'/SX_ChildCrmApi/Sel_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Customerinfo='.$name.'&Brandid='.session('brandclass_id').'&shop_code=""';
            }else{
                $shop_type = 0;
                $addr = $erp['addr'];
                // 婚纱0，儿童1
                $url = trim($addr,'/').'/SX_CrmApi/Sel_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Customerinfo='.$name.'&Brandid='.session('brandclass_id').'&shop_code=""';
            }
            // $url = $addr.'SX_CrmApi/Sel_CustomerOrderInfo?Token=^******^&CustomerType=0'.'&Customerinfo=黑&Shop_code=ZX002';
            $data = '';
            $res = requestERP($url, $data);
            $staffInfo = $this->get_staff_list();
            $staff = array_column($staffInfo,'id','staffname');
            if($res['Code'] == 200){
                foreach($res['Data'] as $k=>$v){
                    // 如果查询条件与男士姓名或者男士手机号一致 显示男士信息 否则显示女士信息
                    if ($name == $v["mname"] || $name == $v["mphone"]) {
                        $res['Data'][$k]['customer_name'] = $v["mname"];
                        $res['Data'][$k]['customer_tel'] = $v["mphone"];
                    }else{
                        $res['Data'][$k]['customer_name'] = $v["wname"];
                        $res['Data'][$k]['customer_tel'] = $v["wphone"];
                    }
                    $res['Data'][$k]['order_number'] = $v["orderId"];
                    $res['Data'][$k]['customer_number'] = $v["customer_from_index"] ? $v["customer_from_index"] : '';
                    $res['Data'][$k]['introducer_type'] = $v["order_type"] < 3 ? '新客' : ($v['order_type'] >= 3 and $v['order_type'] < 6 ? '现客' :($v['order_type'] >= 6 ? '老客' : '新客'));
                    $res['Data'][$k]['shop_code'] = $v["shop_code"] ? $v["shop_code"] :'';
                    $res['Data'][$k]['shop_name'] = $v["shop_name"] ? $v["shop_name"] :'';
                    $res['Data'][$k]['reception_id'] = $staff[$v['storeconsuitant1']] ? $staff[$v['storeconsuitant1']] :0;
                    $res['Data'][$k]['reception_name'] = $v["storeconsuitant1"] ? $v["storeconsuitant1"] :'';
                    // $res['Data'][$k]['sales_staff'] = $v["storeconsuitant2"] ? $v["storeconsuitant1"] :$v["storeconsuitant1"];
                }
            }else{
                $res = array('Code'=>'300','Msg'=>'未查询到订单数据','Data'=>'');
            }
            return ($res);
        }else{
            $res = db('CCustomerinfo')
                ->where('customer_tel|mate_tel',$name)
                ->where('order_number','<>','')
                ->where('add_shop_code',session('shop_code'))
                ->field('customer_name,customer_tel,order_number,introducer_type,customer_number,mate_tel,shop_code,shop_name,reception_id,reception_name')
                ->select();
            if(empty($res)){
                return array('Code'=>'300','Msg'=>'未查询到订单数据','Data'=>'');
            }else{
                foreach($res as $k=>$v){
                    $res[$k]['introducer_type'] = $v["introducer_type"] == 1 ? '新客' : ($v['introducer_type'] == 2 ? '现客' :($v['introducer_type'] >= 3 ? '老客' : '新客'));
                }
                return array('Code'=>'200','Msg'=>'查询成功','Data'=>$res);
            }
        }
    }
    /*
     * PC端修改介绍人信息---start---
     * */
    public function editIntroducer($data){
        $param['introducer_name'] = $data['introducer_name'] ? trim($data['introducer_name']) : '';
        $param['introducer_tel'] = $data['introducer_tel'] ? trim($data['introducer_tel']) : '';
        $param['introducer_ordernum'] = $data['introducer_ordernum'] ? trim($data['introducer_ordernum']) : '';
        $param['introducer_number'] = $data['introducer_number'] ? trim($data['introducer_number']) : '';
        $param['introducer_type'] = $data['introducer_type'] ? trim($data['introducer_type']) : '';
        $param['id'] = $data['id'] ? intval($data['id']) : 0;
        $param['update_time'] = date('Y-m-d H:i:s');
        if(empty($data['id'])){
            return array('code'=>'300','msg'=>'未获取到客资ID','data'=>'');
        }else{
            db()->startTrans();
            try{
                db('c_customerinfo')->where('id',$param['id'])->update($param);
                action_log($param,[],$param['id'],session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>'200','msg'=>'修改介绍人信息成功！','data'=>'');
            }catch (Exception $e){
                db()->rollback();
                return array('code'=>'300','msg'=>'修改介绍人信息失败！','data'=>$e->getMessage());
            }
        }
    }
    /*
     * PC端修改介绍人信息---end---
     * */
    /*------------------------移动端方法------end------------------------*/
    //追踪标记  和 客资标记 A客，B客
    public function customerSign($param){
        if($param['id']){
            // if($param['syjd_day'] == 'null'){
            //     $param['syjd_day'] = null;
            // }
            if($param['op_signinfo_id'] && !$param['op_signday']){
                $param['op_signday'] = date('Y-m-d H:i:s',time());
            }
            if($param['sign_id']){
                $param['sign_time'] = date('Y-m-d H:i:s',time());
            }
            // if($param['order_day'] == 'null'){
            //     $param['order_day'] = null;
            // }
            // if($param['next_time'] == 'null'){
            //     $param['next_time'] = null;
            // }
            foreach($param as $k=>$v){
                if(empty($v) || $v == '请选择'){
                    unset($param[$k]);
                }
            }

            db()->startTrans();
            $param['update_time'] = date('Y-m-d H:i:s',time());
            $re = db('CCustomerinfo')->where('id', $param['id'])->update($param);
            if($re !== false){
                $info = $this->getCustomerInfo($param['id']);//客资信息
                // 录入record，筛客filter，销售sale
                if($param['is_success'] == 1){
                    $param['order_status'] = 1;
                    $param['order_valid'] = 2;
                }
                $listName = 'historyDataList';
                $oldDate = array(
                    'fp_staff_id'       => $info['fp_staff_id'],
                    'fp_staff'          => $info['fp_staff'],
                    'fp_staff_number'   => $info['fp_staff_number'],
                    'is_fp'             => $info['is_fp'],
                    'sales_staff_id'    => $info['sales_staff_id'],
                    'sales_staff'       => $info['sales_staff'],
                    'sales_staff_number'=> $info['sales_staff_number'],
                    'fp_day'            => $info['fp_day'],
                );
                $cinfo = [
                    'id'     => $info['id'],
                    'dj_id'  => $info['dj_staff_id'],
                    'dj_day' => $info['dj_day'],
                    'sel_id' => $info['sk_staff_id'],
                    'sel_day'=> $info['sk_time'],
                    'jr_id'  => $info['sales_staff_id'],
                    'jr_day' => $info['jr_day'],
                ];
                $message = array(
                    'type' => 1,
                    'staff_id'   => session('staff_id'),
                    'identity'   => 'sale',
                    'cinfo'      => $cinfo,
                    'old_data'   => $oldDate,
                    'new_data'   => $param,
                    'controller' => 'Customer',
                    'action'     => 'customerSign',
                );
                $r =  push_list($listName, $message);
                // redisQueue::init()->rPush($listName, $message);
                if($r){
                    action_log($param, '', $param['id'], session('staff_id'), session('staff_name'));
                    db()->commit();
                    $res = array('code'=>200,'msg'=>'标记成功');
                }else{
                    db()->rollback();
                    $res = array('code'=>103,'msg'=>'标记出错');
                }
            }else{
                db()->rollback();
                $res = array('code'=>104,'msg'=>'标记出错');
            }
        }else{
            $res = array('code'=>300,'msg'=>'ID未获取到');
        }
        return $res;
    }

    //不再追踪（不再追踪原因）
    public function notTraking($data){
        if($data['id']){
            $data['is_loss']=1;
            $data['loss_day']=date('Y-m-d H:i:s',time());
            if($data['loss_cause']){
                $data['loss_cause']=trim($data['loss_cause']);
            }else{
                unset($data['loss_cause']);
            }
            $info = $this->getCustomerInfo($data['id']);
            db()->startTrans();
            try{
                $data['update_time'] = date('Y-m-d H:i:s',time());
                $result=db('c_customerinfo')->where('id',$data['id'])->update($data);
                // 写入追踪表
                $dataValid = [
                    'gtType'            => '4',
                    'customer_id'       => $data['id'],
                    'customer_name'     => $info['customer_name'],
                    'customer_number'   => $info['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'      => '不再追踪:'.$data['loss_cause'],
                ];
                db('c_salestrackinginfo')->insert($dataValid);
                getSalesTracking($data['id']);//获取最近三次追踪记录同步更新到客资表
                action_log($data,[],$data['id'],session('staff_id'),session('staff_name'));
                db()->commit();
                $res = array('code'=>200,'msg'=>'操作成功');
            }catch (Exception $e){
                db()->rollback();
                $res = array('code'=>101,'msg'=>'操作失败');
            }
        }else{
            $res = array('code'=>102,'msg'=>'未获取到此条客资信息');
        }
        return $res;
    }

    //发送短信
    public function send_message($param){
        $customerInfos = $this->getCustomerInfos($param['ids']);

        $db = db('CSendMessageLog');
        $db->startTrans();
        try{
//            preg_match("/(?:\{)(.*)(?:\})/i",$param['send_msg'], $name);
//            preg_match("/(?:\[)(.*)(?:\])/i",$param['send_msg'], $sex);
//            preg_match("/(?:\[\[\[)(.*)(?:\]\]\])/i",$param['send_msg'], $code);
//            preg_match("/(?:\[\[)(.*)(?:\]\])/i",$param['send_msg'], $syjd_time);
            $i = 1;
            foreach($customerInfos as $k=>$v){

                if($v['customer_sex'] == '男'){
                    $m = '先生';
                }elseif($v['customer_sex'] == '女'){
                    $m = '女士';
                }else{
                    $m = '';
                }
                $tel = $param['receiver_flag'] == 'mate' ? $v['mate_tel']  : $v['customer_tel'];
                if(empty($tel)){
                    $db->rollBack();
                    return array('msg'=>'未获取到手机号码，不能发送短信！','code'=>109,'data'=>'');
                }
                //字符串替换
                $send_msg1 = str_replace('{name}',$param['receiver_flag'] == 'mate' ? $v['mate_name']  : $v['customer_name'],$param['send_msg']);
                $send_msg = str_replace('[sex]',$m,$send_msg1);
                if(session('telphone')){
                    $send_msg = str_replace('[mobile]',session('telphone'),$send_msg);
                }
                //进店码
                if($param['flag'] == 'yjd'){
                    $jdCode = db('c_customer_jdm')->where('c_id',$v['id'])->where('is_jd',2)->value('jd_code');
                    $send_msg = str_replace('[[[code]]]',$jdCode,$send_msg);
                    $v['yjd_day'] = date('Y-m-d H:i',strtotime($v['yjd_day']));
                    $send_msg = str_replace('[[syjd_time]]',$v['yjd_day'],$send_msg);
                }
//门店信息
                if($v['consulation_shop_code']){
                    $shop = $this->get_shop(['shop_code'=>$v['consulation_shop_code']]);
                    $send_msg = str_replace('[[shop_address]]',$shop[0]['shopaddress'],$send_msg);
                    $send_msg = str_replace('[[shop_name]]',$v['consulation_shop'],$send_msg);
                }
                //门市信息
                if((strstr($send_msg,'[[sales_phone]]')||(strstr($send_msg,'[[sales_staff]]'))&&$v['sales_staff_id'])){
                    $staff = getStaffInfoById($v['sales_staff_id']);
                    $send_msg = str_replace('[[sales_staff]]',$staff['turestaffname'],$send_msg);
                    $send_msg = str_replace('[[sales_phone]]',$staff['telephone'],$send_msg);
                }
                $data = array(
                    'send_id' => session('staff_id'),
                    'send_name'=>session('staff_name'),
                    'send_content'=>$send_msg,
                    'model_id'=>$param['model_id'],
                    'send_time'=>date('Y-m-d H:i:s',time()),
                    'receive_id'=>$v['id'],
                    'receive_name'=>$param['receiver_flag'] == 'mate' ? $v['mate_name']  : $v['customer_name'],
                    'receive_phone'=>$tel,
                );
                //调用短信接口
                $url = '5a17b86088f1a';
                $da = array(
                    'mobile' => $tel,
                    'content' => $send_msg
                );
                if(!$param['send_config']){
                     $da['shop_code'] = session('shop_code');
//                    array_push($da,['shop_code'=>session('shop_code')]);
                }else{
                    $da['send_config'] = $param['send_config'];
//                    array_push($da,['send_config'=>$param['send_config']]);
                }
                $res = sx_call($url,$da);
                if($res['code'] != 200){
                    $db->rollback();
                    return array('msg'=>'第'.$i.'条时短信接口调用失败','code'=>100,'data'=>$res['msg']);
                }
                $db->insert($data);
                $i++;
            }
            history_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
        }catch (Exception $e){
            $db->rollBack();
            return array('msg'=>'短信发送失败','code'=>100,'data'=>$e->getMessage());
        }
        return array('msg'=>'短信发送成功','code'=>200);
    }
    //发送短信--通知类
    public function send_message_notice($param){
        $customerInfos = $this->getCustomerInfos($param['ids']);

        $db = db('CSendMessageLog');
        $db->startTrans();
        try{
            $i = 1;
            foreach($customerInfos as $k=>$v){
                $content = '';
                if($v['customer_sex'] == '男'){
                    $m = '先生';
                }elseif($v['customer_sex'] == '女'){
                    $m = '女士';
                }else{
                    $m = '';
                }
                $param['sex'] = $m;
                $tel = $param['receiver_flag'] == 'mate' ? $v['mate_tel']  : $v['customer_tel'];
                if(empty($tel)){
                    $db->rollBack();
                    return array('msg'=>'未获取到手机号码，不能发送短信！','code'=>109,'data'=>'');
                }else{
                    $param['_mobile'] = $tel;
                }
                //进店码
                if($param['flag'] == 'yjd'){
                    $param['code'] = $v['id'];
                    $param['yjd_day'] = $v['yjd_day'];
                    $content .= '进店码：'.$v['id'].';';
                    $content .= '预约时间：'.$v['yjd_day'].';';
                }
                //门店信息
                if($v['consulation_shop_code']){
                    $shop = $this->get_shop(['shop_code'=>$v['consulation_shop_code']]);
                    $param['shop_address'] = $shop[0]['shopaddress'];
                    $param['shop_name'] = $v['consulation_shop'];
                    if($v['consulation_shop']){
                        $content .= '门店：'.$v['consulation_shop'].';';
                    }
                    if($shop[0]['shopaddress']){
                        $content .= '地址：'.$shop[0]['shopaddress'].';';
                    }
                }
                //门市信息
                if($v['consulation_shop_code']&&$v['sales_staff_id']){
                    $staff = getStaffInfoById($v['sales_staff_id']);
                    $param['sales_staff'] = $staff['turestaffname'];
                    $param['sales_phone'] = $staff['telephone'];
                    if($staff['turestaffname']){
                        $content .= '接待人：'.$staff['turestaffname'].';';
                    }
                    if($staff['telephone']){
                        $content .= '电话：'.$staff['telephone'].';';
                    }
                }
                $data = array(
                    'send_id' => session('staff_id'),
                    'send_name'=>session('staff_name'),
                    'send_content'=>$content,
                    'model_id'=>$param['_template_id'],
                    'send_time'=>date('Y-m-d H:i:s',time()),
                    'receive_id'=>$v['id'],
                    'receive_name'=>$param['receiver_flag'] == 'mate' ? $v['mate_name']  : $v['customer_name'],
                    'receive_phone'=>$tel,
                );
                //调用短信接口
                $url = '5d78e60eeb6a2';
                $res = sx_call($url,$param);
                if($res['data']['content']){
                    $data['send_content'] = $res['data']['content'];
                }
                
                if($res['code'] != 200){
                    $db->rollback();
                    return array('msg'=>'第'.$i.'条时短信接口调用失败','code'=>100,'data'=>$res['msg']);
                }
                $db->insert($data);
                $i++;
            }
            history_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
        }catch (Exception $e){
            $db->rollBack();
            return array('msg'=>'短信发送失败','code'=>100,'data'=>$e->getMessage());
        }
        return array('msg'=>'短信发送成功','code'=>200);
    }
    //追踪添加
    public function addSalesTracking($param){

        $param['sales_day'] = date('Y-m-d H:i:s',time());
        $param['sales_staff'] = session('staff_name');
        $param['sales_staff_id'] = session('staff_id');
        $param['sales_staff_number'] = session('staff_number');
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $call_id =  db_config('call_id_');
        $call = db('SCallCenter')->where('id',$call_id)->value('call_name');
        if(session('user') && session('ip') && $call == 'IP呼叫中心'){
            $param['audio_path'] = session('ip').':'.session('port').'/osip_playwave.cpc?guid='.cache('guid_'.$param['customer_tel']);
        }

        foreach($param as $k=>$v){
            if(empty($v) || $v == '请选择'){
                unset($param[$k]);
            }
        }
        db()->startTrans();//开启事务
        try{
            db('CSalestrackinginfo')->insert($param);
            $id = db('CSalestrackinginfo')->getLastInsID();
            if($id){
                db('c_customerinfo')->where('id',$param['customer_id'])->setInc('tel_visit_num');//电访量
                cache('getCustomerTrackInfos'.$param['customer_id'],null);
                //修改追踪时间
                $info = $this->getCustomerInfo($param['customer_id']);//客资信息
                $time = date('Y-m-d H:i:s',time());
                if(empty($info['c_star_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }
                $arr['update_time'] = $time;
                db('CCustomerinfo')->where('id',$param['customer_id'])->update($arr);

                /*$listName = 'historyDataList';
                $cinfo = [
                    'id'     => $info['id'],
                    'dj_id'  => $info['dj_staff_id'],
                    'dj_day' => $info['dj_day'],
                    'sel_id' => $info['sk_staff_id'],
                    'sel_day'=> $info['sk_time'],
                    'jr_id'  => $info['sales_staff_id'],
                    'jr_day' => $info['jr_day'],
                ];
                $message = array(
                    'type' => 1,
                    'staff_id'   => session('staff_id'),
                    'identity'   => 'sale',
                    'cinfo'      => $cinfo,
                    'old_data'   => array(),
                    'new_data'   => array('tel_num'=>1),
                    'controller' => 'Customer',
                    'action'     => 'addSalesTracking',
                );
                $msg = push_list($listName, $message);
                // redisQueue::init()->rPush($listName, $message);
                if($msg === false){
                    db()->rollback();
                    return false;
                }*/
            }
            cache('guid_'.$param['customer_tel'],null);
            action_log($param,'',$param['customer_id'],session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'客户信息已记录成功!','id'=>$id,'data'=>$param);
        }catch (Exception $e){
            db()->rollBack();//回滚
            return array('code'=>100,'id'=>0,'msg'=>'客户信息记录失败','data'=>$e->getMessage());
        }
    }
    //追踪修改
    public function editSalesTracking($param){
        if ($param['noTrack']==1) {
            $param['no_track'] = "继续追踪";
        }elseif ($param['noTrack']==2) {
            $param['no_track'] = "驳回";
        }elseif ($param['noTrack']==3) {
            $param['no_track'] = "预约进店";
        }elseif ($param['noTrack']==4) {
            $param['no_track'] = "不再追踪";
        }
        $param['sales_remark'] = save_clips_to_file($param['sales_remark'],'upload/img/'.date('Ymd',time()));
        $param['sales_remark'] = DeleteHtml($param['sales_remark']);
        $date = date('Y-m-d H:i:s',time());
        $param['sales_day'] = $date;
        $param['sales_staff'] = session('staff_name');
        $param['sales_staff_id'] = session('staff_id');
        $param['sales_staff_number'] = session('staff_number');
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $reason = trim($param['reason']);
        $reject_reason = trim($param['reject_reason']);
        $consultation_type_id = $param['consultation_type_id'];
        $customer_intention_id = $param['customer_intention_id'];
        $sign_id = intval($param['sign_id']);
        $sign_name = $param['sign_name'];
        $op_signinfo_id = intval($param['op_signinfo_id']);
        $op_signinfo = $param['op_signinfo'];
        $customer_capacity_id = intval($param['customer_capacity_id']);
        $customer_capacity = $param['customer_capacity'];
        $customer_cource_id = $param['customer_cource_id'];
        $customer_cource = $param['customer_cource'];

        $data['is_valid'] = $param['is_valid'];
        $data['yjd_day'] = $param['yjd_day'];
        $data['consulation_shop_code'] = $param['consulation_shop_code'];
        $data['consulation_shop'] = $param['consulation_shop'];
        $data['reception_id'] = $param['reception_id'];
        $data['reception_name'] = $param['reception_name'];
        $data['customer_sex'] = $param['customer_sex'];
        $data['customer_intention'] = $param['customer_intention'];
        $data['channel_plan_number'] = $param['channel_plan_number'];
        $data['age_area'] = $param['age_area'];

        $customer_label = array_unique(explode(',',trim($param['customer_label'],',')));
        $data['customer_label'] = implode(',',$customer_label);
        $data['wechat_status'] = $param['wechat_status'];
        $data['add_friend_time'] = $param['add_friend_time'] ? date('Y-m-d H:i:s',strtotime($param['add_friend_time'])) : NULL;
        if(session('shop_type') == 2){
            $data['baby_name'] = $param['baby_name'];
            $data['baby_sex'] = $param['baby_sex'];
        }
        $data['mate_name'] = $param['mate_name'];
        $data['mate_tel'] = $param['mate_tel'];
        // 有修改客资的权限 这个是不是应该在控制器里做
        // if (check_right('menu1512970667')) {
        //     $data['customer_address'] = $param['customer_address'];
        // }
        if ($param['customer_address']) {
            $data['customer_address'] = $param['customer_address'];
        }
        $data['customer_remark'] = $param['customer_remark'];
        $data['mate_wechat'] = $param['mate_wechat'];
        if($param['yp_day']) $data['yp_day'] = $param['yp_day'];

        $noTrack = $param['noTrack'];
        $province_id = $param['province_id'];
        $province = $param['province'];
        $city_id = $param['city_id'];
        $city = $param['city'];
        $county_id = $param['county_id'];
        $county = $param['county'];
        $receiver_flag = $param['receiver_flag'];
        if(session('shop_type') != 2){
            // 婚期
            $marry_day = $param['marry_day'] ? date('Y-m-d H:i:s',strtotime($param['marry_day'])) : NULL;
        }
        // 预算
        $budget    = $param['budget'] ? trim($param['budget']) : NULL;
        $baby_birthday    = $param['baby_birthday'] ? trim($param['baby_birthday']) : NULL;

        // 再约时间
        $next_time = $param['next_time'] ? date('Y-m-d H:i:s',strtotime($param['next_time'])) : NULL;
        foreach($param as $k=>$v){
            if(empty($v) || $v == '请选择'){
                unset($param[$k]);
            }
        }
        // 是否取消预约（2：取消预约）
        $quit_yjd = $param['quit_yjd'];

        $info = $this->getCustomerInfo($param['customer_id']);//客资信息
        $old = '';
        $new = '';
        if (session('shop_type')==2) {
            $customer_name_type = "妈妈";
        }else{
            $customer_name_type = "客户";
        }
        if($param['customer_name'] != $info['customer_name']){
            $old .= $customer_name_type.'姓名：'.$info['customer_name'].'<br/>';
            $new .= $customer_name_type.'姓名：'.$param['customer_name'].'<br/>';
        }
        if($param['customer_tel'] != $info['customer_tel']){
            $old .= $customer_name_type.'手机：'.$info['customer_tel'].'<br/>';
            $new .= $customer_name_type.'手机：'.$param['customer_tel'].'<br/>';
        }
        if($param['customer_sex'] != $info['customer_sex']&&session('shop_type')!=2){
            $old .= $customer_name_type.'性别：'.$info['customer_sex'].'<br/>';
            $new .= $customer_name_type.'性别：'.$param['customer_sex'].'<br/>';
        }
        if($param['customer_wechat'] != $info['customer_wechat']){
            $old .= $customer_name_type.'微信：'.$info['customer_wechat'].'<br/>';
            $new .= $customer_name_type.'微信：'.$param['customer_wechat'].'<br/>';
        }
        if($param['add_friend_time'] != $info['add_friend_time']){
            $old .= '添加好友时间：'.$info['add_friend_time'].'<br/>';
            $new .= '添加好友时间：'.$param['add_friend_time'].'<br/>';
        }
        if($param['province'] != $info['province']){
            $old .= '省：'.$info['province'].'<br/>';
            $new .= '省：'.$param['province'].'<br/>';
        }
        if($param['city'] != $info['city']){
            $old .= '市：'.$info['city'].'<br/>';
            $new .= '市：'.$param['city'].'<br/>';
        }
        if($param['county'] != $info['county']){
            $old .= '区县：'.$info['county'].'<br/>';
            $new .= '区县：'.$param['county'].'<br/>';
        }
        if($param['sign_name'] != $info['sign_name']){
            $old .= '客资标记：'.$info['sign_name'].'<br/>';
            $new .= '客资标记：'.$param['sign_name'].'<br/>';
        }
        if($param['is_valid'] != $info['is_valid']){
            $old .= '是否有效：'.getIsValidAttr($info['is_valid']).'<br/>';
            $new .= '是否有效：'.getIsValidAttr($param['is_valid']).'<br/>';
        }
        if($param['customer_intention'] != $info['customer_intention']){
            $old .= '客资意向：'.$info['customer_intention'].'<br/>';
            $new .= '客资意向：'.$param['customer_intention'].'<br/>';
        }
        if(customize('hebmx')){
            //哈尔滨摩西，追踪时不修改消费类型。
            // $param['consultation_type'] = $info['consultation_type'];
        }else{
            if($param['consultation_type'] != $info['consultation_type']){
                $old .= '消费类型：'.$info['consultation_type'].'<br/>';
                $new .= '消费类型：'.$param['consultation_type'].'<br/>';
            }
        }
        
        if($param['customer_capacity'] != $info['customer_capacity']){
            $old .= '消费能力：'.$info['customer_capacity'].'<br/>';
            $new .= '消费能力：'.$param['customer_capacity'].'<br/>';
        }
        if($param['budget'] != $info['budget']){
            $old .= '预算：'.$info['budget'].'<br/>';
            $new .= '预算：'.$param['budget'].'<br/>';
        }
        if($param['marry_day'] != $info['marry_day']){
            $old .= '婚期：'.$info['marry_day'].'<br/>';
            $new .= '婚期：'.$param['marry_day'].'<br/>';
        }
        if($param['next_time'] != $info['next_time']){
            $old .= '再约时间：'.$info['next_time'].'<br/>';
            $new .= '再约时间：'.$param['next_time'].'<br/>';
        }
        if($param['step_name'] != $info['step_name']){
            $old .= '追踪阶段：'.$info['step_name'].'<br/>';
            $new .= '追踪阶段：'.$param['step_name'].'<br/>';
        }
        if($param['op_signinfo'] != $info['op_signinfo']){
            $old .= '追踪标记：'.$info['op_signinfo'].'<br/>';
            $new .= '追踪标记：'.$param['op_signinfo'].'<br/>';
        }
        if($param['channel_plan_number'] != $info['channel_plan_number']){
            $old .= '推广编号：'.$info['channel_plan_number'].'<br/>';
            $new .= '推广编号：'.$param['channel_plan_number'].'<br/>';
        }
        

        $log = $param;

        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        unset($param['quit_yjd']);
        unset($param['budget']);
        unset($param['customer_address']);
        unset($param['customer_remark']);
        unset($param['customer_label']);
        unset($param['marry_day']);
        unset($param['next_time']);
        unset($param['province_id']);
        unset($param['province']);
        unset($param['city_id']);
        unset($param['city']);
        unset($param['county_id']);
        unset($param['county']);
        unset($param['sign_id']);
        unset($param['sign_name']);
        unset($param['op_signinfo_id']);
        unset($param['op_signinfo']);
        unset($param['channel_plan_number']);
        unset($param['customer_capacity_id']);
        unset($param['customer_capacity']);
        unset($param['consultation_type_id']);
        unset($param['customer_intention_id']);
        unset($param['is_valid']);
        unset($param['yjd_day']);
        unset($param['consulation_shop_code']);
        unset($param['consulation_shop']);
        unset($param['reception_id']);
        unset($param['reception_name']);
        unset($param['customer_sex']);
        unset($param['baby_sex']);
        unset($param['baby_name']);
        unset($param['mate_name']);
        unset($param['mate_tel']);
        unset($param['noTrack']);
        unset($param['reject_reason']);
        unset($param['reason']);
        unset($param['baby_birthday']);
        unset($param['add_friend_time']);
        unset($param['mate_wechat']);
        unset($param['receiver_flag'],$param['age_area']);
        unset($param['yp_day']);
        if(!$param['id']){ //qq，微信聊天之后直接保存，没有通话时间，直接保存的
            db()->startTrans();
            try{
                //修改追踪时间
                $time = date('Y-m-d H:i:s',time());
                if(empty($info['c_star_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                        'customer_sex' => $data['customer_sex'],
                        'customer_name' => $param['customer_name'],
                        'baby_sex' => $data['baby_sex'],
                        'baby_name' => $data['baby_name'],
                        'mate_name' => $data['mate_name'],
                        'mate_tel' => $data['mate_tel'],
                        // 'customer_address' => $data['customer_address'],
                        'mate_wechat' => $data['mate_wechat'],
                        'age_area' => $data['age_area'],
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                        'customer_sex' => $data['customer_sex'],
                        'customer_name' => $param['customer_name'],
                        'baby_sex' => $data['baby_sex'],
                        'baby_name' => $data['baby_name'],
                        'mate_name' => $data['mate_name'],
                        'mate_tel' => $data['mate_tel'],
                        // 'customer_address' => $data['customer_address'],
                        'mate_wechat' => $data['mate_wechat'],
                        'age_area' => $data['age_area'],
                    );
                }
                if($param['seles_step'] && $param['seles_step'] != $info['seles_step']){
                    $arr['seles_step'] = $param['seles_step'];
                    $arr['step_name'] = $param['step_name'];
                }
                if($param['consultation_type'] && $param['consultation_type'] != $info['consultation_type']){
                    $arr['consultation_type_id'] = $consultation_type_id;
                    $arr['consultation_type'] = $param['consultation_type'];
                }
                $old .= '最后追踪时间：'.$info['last_trackday'].'<br/>';
                $new .= '最后追踪时间：'.$arr['last_trackday'].'<br/>';
                //没有追踪部门则添加
                if(empty($info['sales_department_id'])){
                    // $arr['sales_department_id'] = session('department_id');
                    $salesInfo = getStaffInfoById($info['sales_staff_id']);
                    $arr['sales_department_id'] = $salesInfo['department_id'];
                }
                //没有录入部门则添加
                if(empty($info['dj_department_id'])){
                    $sInfo = getStaffInfoById($info['dj_staff_id']);
                    $arr['dj_department_id'] = $sInfo['department_id'];
                }

                if($data['yjd_day'] && ($data['yjd_day'] != $info['yjd_day'])){
                    $old .= '预约进店时间：'.$info['yjd_day'].'<br/>';
                    $new .= '预约进店时间：'.$data['yjd_day'].'<br/>';
                }
                if($data['consulation_shop_code'] && ($data['consulation_shop_code'] != $info['consulation_shop_code'])){
                    $arr['consulation_shop_code'] = $data['consulation_shop_code'];
                    $arr['consulation_shop'] = $data['consulation_shop'];
                    $old .= '意向店面：'.$info['consulation_shop'].'<br/>';
                    $new .= '意向店面：'.$param['consulation_shop'].'<br/>';
                }
                if($data['reception_id'] && ($data['reception_id'] != $info['reception_id'])){
                    $arr['reception_id'] = $data['reception_id'];
                    $arr['reception_name'] = $data['reception_name'];
                    $old .= '接待人：'.$info['reception_name'].'<br/>';
                    $new .= '接待人：'.$param['reception_name'].'<br/>';
                }

                if ($customer_cource_id && $customer_cource_id!=$info['customer_cource_id']) {
                    $arr['customer_cource_id'] = $customer_cource_id;
                    $arr['customer_cource'] = $customer_cource;
                    $old .= '客户来源：'.$info['customer_cource'].'<br/>';
                    $new .= '客户来源：'.$$customer_cource.'<br/>';
                }
                if($param['unvalid_id'] && ($param['unvalid_id'] != $info['unvalid_id'])){
                    $arr['unvalid_id'] = $param['unvalid_id'];
                    $arr['unvalid_reason'] = $param['unvalid_reason'];
                    $old .= '无效原因：'.$info['unvalid_reason'].'<br/>';
                    $new .= '无效原因：'.$param['unvalid_reason'].'<br/>';
                }
                if($param['customer_qq'] != $info['customer_qq']){
                    $arr['customer_qq'] = $param['customer_qq'];
                    $old .= '客户QQ：'.$info['customer_qq'].'<br/>';
                    $new .= '客户QQ：'.$param['customer_qq'].'<br/>';
                }

                //新联系方式
                $new_contact = [];
                //手机
                $customer_tel = $param['customer_tel'];
                if ($customer_tel) {
                    if($customer_tel != $info['customer_tel']){
                        if (!$info['customer_tel']) {
                            $arr['tel_staff_id']= session('staff_id');
                            $arr['tel_staff']   = session('staff_name');
                            $arr['tel_time']    = $time;
                        }
                        $arr['customer_tel'] = $customer_tel;
                        $repeat = $this->isRepeat(session('brandclass'),$customer_tel,0,0,0,$param['customer_id'],$consultation_type_id);
                        if($repeat['code'] == 201){
                            db()->rollback();
                            return array('code'=>100,'msg'=>'手机号重复,不可更改','data'=>'');
                        }
                    }
                    $new_contact[] = [
                        'c_id' => $param['customer_id'],
                        'contact'=> $customer_tel,
                        'brandclass'=> session('brandclass')
                    ];
                }
                // 配偶手机
                $mate_tel = $data['mate_tel'];
                if ($mate_tel) {
                    if($mate_tel != $info['mate_tel']){
                        $arr['mate_tel'] = $mate_tel;
                        $repeat = $this->isRepeat(session('brandclass'),$mate_tel,0,0,0,$param['customer_id'],$consultation_type_id);
                        if($repeat['code'] == 201){
                            db()->rollback();
                            return array('code'=>100,'msg'=>'配偶手机号重复,不可更改','data'=>'');
                        }
                    }
                    $contact = array_column($new_contact,'contact');
                    if(!in_array($mate_tel,$contact)){
                        $new_contact[] = [
                            'c_id' => $param['customer_id'],
                            'contact'=> $mate_tel,
                            'brandclass'=> session('brandclass')
                        ];
                    }
                }
                // 微信
                $customer_wechat = $param['customer_wechat'];
                if ($customer_wechat) {
                    if($customer_wechat != $info['customer_wechat']){
                        if (!$info['customer_wechat']) {
                            $arr['is_first_wechat']= 1;
                            $arr['wechat_staff_id']= session('staff_id');
                            $arr['wechat_staff']   = session('staff_name');
                            $arr['wechat_time']    = $time;
                        }
                        $arr['customer_wechat'] = $customer_wechat;
                        $repeat = $this->isRepeat(session('brandclass'),0,$customer_wechat,0,0,$param['customer_id'],$consultation_type_id);
                        if($repeat['code'] == 201){
                            db()->rollback();
                            return array('code'=>100,'msg'=>'微信号重复,不可更改','data'=>'');
                        }
                    }
                    $contact = array_column($new_contact,'contact');
                    if(!in_array($customer_wechat,$contact)){
                        $new_contact[] = [
                            'c_id' => $param['customer_id'],
                            'contact'=> $customer_wechat,
                            'brandclass'=> session('brandclass')
                        ];
                    }
                }
                // 配偶微信
                $mate_wechat = $data['mate_wechat'];
                if ($mate_wechat) {
                    if($mate_wechat != $info['mate_wechat']){
                        $arr['mate_wechat'] = $mate_wechat;
                        $repeat = $this->isRepeat(session('brandclass'),0,$mate_wechat,0,0,$param['customer_id'],$consultation_type_id);
                        if($repeat['code'] == 201){
                            db()->rollback();
                            return array('code'=>100,'msg'=>'配偶微信号重复,不可更改','data'=>'');
                        }
                    }
                    $contact = array_column($new_contact,'contact');
                    if(!in_array($mate_wechat,$contact)){
                        $new_contact[] = [
                            'c_id' => $param['customer_id'],
                            'contact'=> $mate_wechat,
                            'brandclass'=> session('brandclass')
                        ];
                    }
                }
                // var_dump($new_contact);die;
                // QQ
                $customer_qq = $param['customer_qq'];
                if ($customer_qq) {
                    if($customer_qq != $info['customer_qq']){
                        $arr['customer_qq'] = $customer_qq;
                        $repeat = $this->isRepeat(session('brandclass'),0,$customer_qq,0,0,$param['customer_id'],$consultation_type_id);
                        if($repeat['code'] == 201){
                            db()->rollback();
                            return array('code'=>100,'msg'=>'QQ号重复,不可更改','data'=>'');
                        }
                    }
                    $contact = array_column($new_contact,'contact');
                    if(!in_array($customer_qq,$contact)){
                        $new_contact[] = [
                            'c_id' => $param['customer_id'],
                            'contact'=> $customer_qq,
                            'brandclass'=> session('brandclass')
                        ];
                    }
                }
                unset($param['customer_wechat']);
                unset($param['mate_wechat']);
                //删除客资旧联系方式
                db('c_customer_contact')->where('c_id',$param['customer_id'])->delete();
                //插入新的联系方式
                db('c_customer_contact')->insertAll($new_contact);

                // 有效状态 
                if($data['is_valid'] && ($info['is_valid'] != $data['is_valid'])){
                    $arr['is_valid'] = $data['is_valid'];
                    $arr['yx_day'] = $time;
                }
                // 客资标记
                if ($sign_id && ($sign_id != $info['sign_id']) ) {
                    $arr['sign_id']   = $sign_id;
                    $arr['sign_name'] = $sign_name;
                    $arr['sign_time'] = $time;
                }
                // 客资标签
                if ($data['customer_label'] && ($data['customer_label'] != $info['customer_label']) ) {
                    $arr['customer_label']   = $data['customer_label'];
                    $old .= '客资标签：'.$info['customer_label'].'<br/>';
                    $new .= '客资标签：'.$arr['customer_label'].'<br/>';
                }
                // 预拍日期
                if ($data['yp_day'] && ($data['yp_day'] != $info['yp_day']) ) {
                    $arr['yp_day']   = $data['yp_day'];
                    $old .= '预拍日期：'.$info['yp_day'].'<br/>';
                    $new .= '预拍日期：'.$arr['yp_day'].'<br/>';
                }
                // 客资备注
                if ($data['customer_remark'] && ($data['customer_remark'] != $info['customer_remark']) ) {
                    $arr['customer_remark']   = $data['customer_remark'];
                    $old .= '客资备注：'.$info['customer_remark'].'<br/>';
                    $new .= '客资备注：'.$arr['customer_remark'].'<br/>';
                }
                // 消费能力
                if ($customer_capacity_id && $customer_capacity_id!= $info['customer_capacity_id']) {
                    $arr['customer_capacity_id']   = $customer_capacity_id;
                    $arr['customer_capacity'] = $customer_capacity;
                }
                if($op_signinfo_id && $op_signinfo_id && ($op_signinfo_id != $info['op_signinfo_id'])){
                    $arr['op_signinfo_id'] = $op_signinfo_id;
                    $arr['op_signinfo'] = $op_signinfo;
                    $arr['op_signday'] = $time;
                }
                // 客户意向
                if ($data['customer_intention'] && ($data['customer_intention'] != $info['customer_intention'])) {
                    $arr['customer_intention_id'] = $customer_intention_id;
                    $arr['customer_intention'] = $data['customer_intention'];
                }
                // 添加好友时间
                if ($data['wechat_status']==1) {
                    $arr['add_friend_time'] = $data['add_friend_time'];
                    $arr['wechat_status'] = $data['wechat_status'];
                }else{
                    if ($data['add_friend_time'] && ($data['add_friend_time'] != $info['add_friend_time'])) {
                        $arr['add_friend_time'] = $data['add_friend_time'];
                        $arr['wechat_status'] = $data['wechat_status'];
                    }
                }
                // var_dump($data['wechat_status']);
                // var_dump($arr);die;
                // 推广编号
                if ($data['channel_plan_number'] && ($data['channel_plan_number'] != $info['channel_plan_number'])) {
                    $arr['channel_plan_number'] = $data['channel_plan_number'];
                }
                // 预算
                if ($budget && ($budget != $info['budget'])) {
                    $arr['budget'] = $budget;
                    // $param['budget'] .= '<br /> 预算：'.$budget;
                }

                if(session('shop_type') != 2){
                    // 婚期
                    if ($marry_day && ($marry_day != $info['marry_day'])) {
                        $arr['marry_day'] = $marry_day;
                        // $param['marry_day'] .= '<br /> 婚期：'.$marry_day;
                    }
                    // 预计婚期
                    if ($param['ready_marry_day'] && ($param['ready_marry_day'] != $info['ready_marry_day']) ) {
                        $arr['ready_marry_day']   = $param['ready_marry_day'];
                        $old .= '预计婚期：'.$info['ready_marry_day'].'<br/>';
                        $new .= '预计婚期：'.$param['ready_marry_day'].'<br/>';
                    }
                }
                if(session('shop_type') == 2){
                    // 宝宝生日
                    if ($baby_birthday && ($baby_birthday!=$info['baby_birthday'])) {
                        $arr['baby_birthday'] = $baby_birthday;
                        // $param['baby_birthday'] .= '<br /> 宝宝生日：'.$baby_birthday;
                    }
                }

                // 再约时间
                if ($next_time && ($next_time != $info['next_time']) ) {
                    $arr['is_next'] = 1;
                    $arr['next_time'] = $next_time;
                    $param['next_time'] .= '<br /> 再约时间：'.$next_time;
                    if($next_time){
                        //查询再约提前时间  天
                        $adv = db('s_reminditemset')->where('id','remind2')->where('brandclass_id',session('brandclass_id'))->where('isopen',1)->field('advancehour')->find();
                        if($adv['advancehour'] || $adv['advancehour'] == 0){
                            $adv = $adv['advancehour'] == 0 ? '今天' : $adv['advancehour'].'天后';
                            $hour = date('H',strtotime($next_time));
                            if($hour == 0){
                                $time = date('Y-m-d 10:00:00',strtotime($next_time)-86400*$adv['advancehour']);
                            }else{
                                $time = date('Y-m-d H:i:s',strtotime($next_time)-86400*$adv['advancehour']);
                            }
                            $message = array(
                                'customer_id' => $param['customer_id'],
                                'send_type'   => 1,
                                'send_title'   => '再约提醒',
                                'send_msg'    => '当前名为：'.$info['customer_name'].'的客资，'.$adv.' 再约电访',
                                'receive_id'  => session('staff_id'),
                                'receive_name'=> session('staff_name'),
                                'operation_type'=> 2,
                                'time_out'=> 120,
                                'next_time'=>$next_time
                            );
                            $pool = array(
                                'cid' => $param['customer_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($pool);
                            if(!$inc1){
                                db()->rollback();
                                $returnData = array('code' => 10,'msg' =>'提前'.$adv['advancehour'].'天再约进店失败');
                                return ($returnData);
                            }else{
                                db()->commit();
                            }
                        }//查询再约提前时间  分钟
                        $adv = db('s_reminditemset')->where('id','next_before_minute')->where('brandclass_id',session('brandclass_id'))->where('isopen',1)->field('advancehour')->find();
                        if($adv['advancehour']){
                            $time = date('Y-m-d H:i:s',strtotime($next_time)-60*$adv['advancehour']);
                            $message = array(
                                'customer_id' => $param['customer_id'],
                                'send_type'   => 1,
                                'send_title'   => '再约提醒',
                                'send_msg'    => '当前名为：'.$info['customer_name'].'的客资，'.$adv['advancehour'].'分钟后再约电访',
                                'receive_id'  => session('staff_id'),
                                'receive_name'=> session('staff_name'),
                                'operation_type'=> 2,
                                'time_out'=> 120,
                                'next_time'=>$next_time
                            );
                            $pool = array(
                                'cid' => $param['customer_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($pool);
                            if(!$inc1){
                                db()->rollback();
                                $returnData = array('code' => 10,'msg' =>'提前'.$adv['advancehour'].'分钟再约进店失败');
                                return ($returnData);
                            }else{
                                db()->commit();
                            }
                        }
                    }
                }else if (!$next_time) {
                	$arr['is_next']  = 2;
                    $arr['next_time']= NULL;
                }

                // 省市区
                if($province_id && ($info['province_id'] != $province_id)){
                    $arr['province_id'] = $province_id;
                    $arr['province'] = $province;
                }
                if($city_id && ($info['city_id'] != $city_id)){
                    $arr['city_id'] = $city_id;
                    $arr['city'] = $city;
                }
                if($county_id && ($info['county_id'] != $county_id)){
                    $arr['county_id'] = $county_id;
                    $arr['county'] = $county;
                }
                if ($data['customer_address'] && ($info['customer_address'] != $data['customer_address'])) {
                    $arr['customer_address'] = $data['customer_address'];
                }

                /* foreach($arr as $k=>$v){
                    if(empty($v)){
                        unset($arr[$k]);
                    }
                } */
                //如果 手机，微信不一样的话 且 因为 null值被过滤的话 重新复制 null 记录
                /*if ($customer_tel != $info['customer_tel']&&!$arr['customer_tel']) {
                    $arr['customer_tel'] = '';
                }
                if ($customer_wechat != $info['customer_wechat']&&!$arr['customer_wechat']) {
                    $arr['customer_wechat'] = '';
                }
                if ($mate_tel != $info['mate_tel']&&!$arr['mate_tel']) {
                    $arr['mate_tel'] = '';
                }
                if ($mate_wechat != $info['mate_wechat']&&!$arr['mate_wechat']) {
                    $arr['mate_wechat'] = '';
                }*/

                $arr['update_time'] = date('Y-m-d H:i:s');
                // var_dump($arr);die;
                if($noTrack == 2){
                    // 是否取消预约（2：取消预约）
                    if ($info['yjd_day'] && $info['is_intostore']==1 && $info['is_success']==2) {
                        $yjd['id']        = $param['customer_id'];
                        $yjd['yjd_day']        = $info['yjd_day'];
                        $yjd['customer_number']= $info['customer_number'];
                        $resqy = $this->quitYjd($yjd);
                        if($resqy['code'] != 200){
                            db()->rollback();
                            return array('code'=>100,'msg'=>$resqy['msg'],'data'=>'');
                        }
                        $param['sales_remark'] = $param['sales_remark'];
                    }
                    // $remark = preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', '', $param['sales_remark']);
                    $result = $this->customerReject(['cid'=>$param['customer_id'],'reject_staff_id'=>$param['reject_staff_id'],'send_msg'=>$param['sales_remark'],'reject_reason'=>$reject_reason,'gtType'=>$param['gtType'],'customer_tel'=>$param['customer_tel'],'consultation_type'=>$param['consultation_type'],'tel_static'=>$param['tel_static'],'no_track'=>$param['no_track']]);
                    // var_dump($result);die;
                    if($result['code'] != 200){
                        db()->rollback();
                        return array('code'=>300,'msg'=>$result['msg'],'data'=>$result['data']);
                    }
                    db('CCustomerinfo')->where('id',$param['customer_id'])->update($arr);
                }
                if($noTrack == 3){
                    // print_r($arr);die;
                    if($arr['customer_tel'] != $info['customer_tel'] || $arr['mate_tel'] != $info['mate_tel']){
                        //如果修改了手机号，要先把客资的联系方式修改掉，防止发短信的时候找不到手机号，如果联系方式没变，放在后面修改客资信息
                        $cont = [];
                        if($arr['customer_tel']) $cont['customer_tel'] = $arr['customer_tel'];
                        if($arr['mate_tel']) $cont['mate_tel'] = $arr['mate_tel'];
                        db('CCustomerinfo')->where('id',$param['customer_id'])->update($cont);
                    }

                    // 预约进店 预约时间是否必选（深圳天长定制） 默认0（必选） 天长1（非必选）
                    $isYjdMust = config('isYjdMust');
                    if (!$data['yjd_day'] && $isYjdMust!=1) {                        
                        return array('code'=>1000,'msg'=>'请填写必填项：预约时间','data'=>'');
                    }
                    if (!$data['consulation_shop_code']) {
                        return array('code'=>1000,'msg'=>'请填写必填项：意向店面','data'=>'');
                    }
                    
                    $yjd = array(
                        'id' => $param['customer_id'],
                        'consulation_shop_code' => $data['consulation_shop_code'],
                        'consulation_shop' => $data['consulation_shop'],
                        'reception_id' => $data['reception_id'],
                        'reception_name' => $data['reception_name'],
                        'yjd_day' => $data['yjd_day'],
                        'intostore_note' => $param['sales_remark'],
                        'model_id'=>intval($param['model_id']),
                        'gtType' => $param['gtType'],
                        'customer_tel' => $param['customer_tel'],
                        'consultation_type' => $param['consultation_type'],
                        'tel_static' => $param['tel_static'],
                        'no_track' => $param['no_track'],
                        'receiver_flag' => $receiver_flag
                    );
                    if(session('shop_type') == 2){
                        $res = $this->customerYJD_child($yjd);
                    }else{
                        $res = $this->customerYJD($yjd);
                    }
                    if($res['code'] != 200){
                        db()->rollback();
                        return array('code'=>100,'msg'=>$res['msg'],'error'=>$res['error'],'data'=>$res['data']);
                    }
                    db('CCustomerinfo')->where('id',$param['customer_id'])->update($arr);
                }
                if($noTrack == 4){
                    // $remark = preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', '', $param['sales_remark']);
                    $arr = array_merge($arr,['is_loss'=>1,'loss_day'=>$time,'loss_cause'=>$reason,'loss_remark'=>$param['sales_remark'],'update_time'=>date('Y-m-d H:i:s')]);
                    db('CCustomerinfo')->where('id',$param['customer_id'])->update($arr);
                    //删除pool表数据
                    // db('c_fp_pool')->where('id',$param['customer_id'])->delete();
                    $old = '';
                    $new = '不再追踪：原因：'.$reason.',备注：'.$param['sales_remark'];
                    action_log($new,$old,$param['customer_id'],session('staff_id'),session('staff_name'));
                }
                if($noTrack == 1 || $noTrack == 4){
                    if($noTrack == 1){
                        // 是否取消预约（2：取消预约）
                        if ($quit_yjd == 2 && $info['yjd_day'] && $info['is_success']==2) {
                        // if ($quit_yjd == 2 && $info['yjd_day'] && $info['is_intostore']==1 && $info['is_success']==2) {
                            $yjd['yjd_day']        = $info['yjd_day'];
                            $yjd['customer_number']= $info['customer_number'];
                            $resqy = $this->quitYjd($yjd);
                            if($resqy['code'] != 200){
                                db()->rollback();
                                return array('code'=>100,'msg'=>$resqy['msg'],'data'=>'');
                            }
                            $param['sales_remark'] = ($param['sales_remark'] ? $param['sales_remark'].'--' : '').'取消预约';
                        }
                        // exit;
                        db('c_customerinfo')->where('id',$param['customer_id'])->setInc('tel_visit_num');//电访量
                    }
                    if($noTrack == 4){
                        // 是否取消预约（2：取消预约）
                        if ($info['yjd_day'] && $info['is_intostore']==1 && $info['is_success']==2) {
                            $yjd['yjd_day']        = $info['yjd_day'];
                            $yjd['customer_number']= $info['customer_number'];
                            $resqy = $this->quitYjd($yjd);
                            if($resqy['code'] != 200){
                                db()->rollback();
                                return array('code'=>100,'msg'=>$resqy['msg'],'data'=>'');
                            }
                            $param['sales_remark'] = $reason.($param['sales_remark'] ? '--'.$param['sales_remark'] : '').'--取消预约';
                        }else{
                            $param['sales_remark'] = $reason.($param['sales_remark'] ? '--'.$param['sales_remark'] : '');
                        }
                    }
                    unset($param['mate_name']);
                    unset($param['marry_day']);
                    unset($param['next_time']);
                    $track['customer_id'] = $param['customer_id'];
                    $track['customer_name'] = $info['customer_name'];
                    $track['customer_number'] = $info['customer_number'];
                    $track['sales_remark'] = $param['no_track'].':'.$param['sales_remark'];
                    $track['sales_day'] = date('Y-m-d H:i:s',time());
                    $track['sales_staff'] = session('staff_name');
                    $track['sales_staff_id'] = session('staff_id');
                    $track['sales_staff_number'] = session('staff_number');
                    $track['shop_name'] = session('shop_name');
                    $track['shop_code'] = session('shop_code');
                    $track['gtType'] = $param['gtType'] ? $param['gtType'] : 1;
                    $track['customer_tel'] = $param['customer_tel'];
                    $track['customer_intention'] = $param['customer_intention'];
                    $track['consultation_type'] = $param['consultation_type'];
                    $track['tel_static'] = $param['tel_static'] ? $param['tel_static'] :1;
                    $track['no_track'] = $param['no_track'];
                    db('CSalestrackinginfo')->insertGetId($track);
                    db('CCustomerinfo')->where('id',$param['customer_id'])->update($arr);

                    //return array('code'=>201,'msg'=>db('CCustomerinfo')->getLastSql(),'data'=>'');
                    // 从其他到有效 发消息 eric 181212
                    if($data['is_valid']==1 && $info['is_valid'] != 1){
                        $time = date('Y-m-d H:i:s');
                        $messageD['send_type']      = 1;
                        $messageD['send_time']      = $time;
                        $messageD['send_title']     = '标记提醒';
                        $messageD['send_msg']       = '有一笔客资标记为有效，ID：'.$info['id'].'，请确认。';
                        $messageD['customer_id']    = $info['id'];
                        $messageD['receive_id']     = $info['dj_staff_id'];
                        $messageD['receive_name']   = $info['dj_staff'];
                        $messageD['receive_status'] = 1;
                        $messageD['receive_time']   = $time;
                        $messageD['operation_type'] = 2;
                        $messageD['operation']      = '';
                        $timeOut = db_config('fp_timeout_'.$info['shop_code']);
                        $messageD['time_out']       = $timeOut ? $timeOut : 60;
                        $resM = sendSystemMessage($messageD);
                        // 发送微信模板消息
                        $content = [
                            'touser'       => $info['dj_staff_id'],
                            'template_id'  => OPENTM_YX,
                            'data'         => [
                                'first'=>[
                                    'value'=> '系统消息',
                                    'color'=> '#173177'
                                ],
                                'keyword1'=>[
                                    'value'=> $info['customer_name'],
                                    'color'=> '#173177'
                                ],
                                'keyword2'=>[
                                    'value'=> $info['sales_staff'],
                                    'color'=> '#173177'
                                ],
                                'keyword3'=>[
                                    'value'=> $time,
                                    'color'=> '#173177'
                                ],
                                'remark'=>[
                                    'value'=> '有一笔客资标记为有效，ID：'.$info['id'].'，请确认。',
                                    'color'=> '#173177'
                                ],
                            ],
                        ];
                        $send_data['content'] = json_encode($content);
                        $res = sendMsg($send_data);
                    }
                    cache('getCustomerTrackInfos'.$param['customer_id'],null);
                    getSalesTracking($param['customer_id']);//获取最近三次追踪记录同步更新到客资表
                    // 是否安装erp
                    $is_erp = is_install('sx_erp');
                    if ($is_erp) {
                        // 如果已经邀约时间，并且没有订单，没有订单开始时间，则同步信息到erp
                        // if ($info['yjd_action_day'] && $info['is_success'] ==2 && !$info['order_start_time']) {
                        //     $erpData = $arr;
                        //     $erpData['brandclass_id']  = $info['brandclass_id'];
                        //     $erpData['customer_number']= $info['customer_number'];
                        //     $this->updateToErp($erpData);
                        //     unset($erpData);
                        // }
                    }
                }

                if($noTrack == 1){
                    history_log($new,$old,$param['customer_id'],session('staff_id'),session('staff_name'));
                }
                db()->commit();
                return array('code'=>200,'msg'=>'追踪成功','data'=>'');
            }catch (Exception $e){
                db()->rollBack();//回滚
                return array('code'=>100,'msg'=>'追踪失败','data'=>$e->getMessage());
            }
        }
    }

    // 取消预约 0308
    public function quitYjd($param){
        $isTable = isTableExist('c_customer_intostore');
        // 如果进店表存在
        if ($isTable) {
            $cid = db('c_customerinfo')->where('customer_number',$param['customer_number'])->value('id');
            $intoWhere['status']= '1';
            $intoWhere['cid']   = $cid;
            $into_info = db('c_customer_intostore')
                ->where($intoWhere)->where('syjd_day','null')->where('yjd_day','>=',date("Y-m-d 00:00:00"))
                ->field('id')->select();
            if (!$into_info) {
                $lastSql = db()->getLastSql();
                // return array('code'=>100,'msg'=>'取消预约失败','data'=>$lastSql);
                return array('code'=>200,'msg'=>'取消预约成功','data'=>'');
            }
            $iIds = '';
            foreach ($into_info as $key => $value) {
                $iIds .= $value['id'].',';
            }
            $iIds = trim($iIds, ',');
            // $iId = db('c_customer_intostore')->where('cid', $cid)->order('yjd_day desc')->value('id');
            
            $iData['status'] = 2;

            $cData['update_time'] = date('Y-m-d H:i:s');
            $cData['yjd_day']     = NUll;

            db()->startTrans();
            try{
                db('c_customer_intostore')->where('id', 'in', $iIds)->update($iData);
                db('c_customerinfo')->where('id',$cid)->update($cData);
                db()->commit();
                return array('code'=>200,'msg'=>'取消预约成功','data'=>'');
            }catch (\Exception $e){
                db()->rollback();
                return array('code'=>101,'msg'=>'取消预约失败','data'=>$e->getMessage());
            }
        }else{
            $is_erp = is_install('sx_erp');
            if ($is_erp) {
                $erp = config('ext.app_config');
                $addr = $erp['sx_erp']['addr'];
                // 婚纱
                $url = trim($addr,'/').'/SX_CrmApi/Add_Guestinfo?Token=^******^&CustomerType=0';

                $dataN["Customer_name"] = '';
                $dataN["Customer_tel"] = '';
                $dataN["Customer_wechat"] = '';
                $dataN["Customer_qq"] = '';
                $dataN["Customer_sex"] = '';
                $dataN["Consultation_type"] = '';
                $dataN["Customer_area"] = '';
                $dataN["Customer_birthday"] = '';
                $dataN["Customer_intention"] = '';
                $dataN["Customer_orderaddress"] = '';
                $dataN["Customer_address"] = '';
                $dataN["Yp_day"] = '';
                $dataN["Wedding_date"] = '';
                $dataN["Mate_name"] = '';
                $dataN["Mate_sex"] = '';
                $dataN["Mate_tel"] = '';
                $dataN["Mate_wechat"] = '';
                $dataN["Mate_qq"] = '';
                $dataN["Mate_birthday"] = '';
                $dataN["Customer_remark"] = '';
                $dataN["Customer_from"] = '';
                $dataN["Customer_channel"] = '';
                $dataN["Customer_cource"] = '';
                $dataN["Sales_staff"] = '';
                $dataN["Sales_staff_number"] = '';
                $dataN["Dj_staff"] = '';
                $dataN["Crmentryrenbm"] = '';
                $dataN["Crmentryren"] = '';
                $dataN["shop_codezzr"] = '';
                $dataN["shop_namezzr"] = '';
                $dataN["departidzzr"] = '';
                $dataN["departnamezzr"] = '';

                $dataN["Customer_type"]= '1';
                $dataN["Shop_name"]    = '1';
                $dataN["Shop_code"]    = '1';
                $dataN["Brandid"]      = '1';

                $dataN["Yjd_day"]      = $param['yjd_day'];
                $dataN["From_index"]   = $param['customer_number'] ? $param['customer_number'] : '';
                $dataN['quitYjd']      = 2;
                // var_dump($dataN);
                // exit;
                $dataN = json_encode($dataN);
                // 调 erp 接口
                $response = requestERP($url, $dataN);
                if ($response['Code'] != 200) {
                    db()->rollback();
                    return array('code'=>100,'msg'=>'erp接口调用失败，请重试。','error'=>json_encode($response));
                }else{
                    $data['yjd_day'] = NULL;
                    db('c_customerinfo')->where('customer_number',$param['customer_number'])->update($data);
                    return array('code'=>200,'msg'=>'');
                }
            }
            else{
                $data['update_time'] = date('Y-m-d H:i:s');
                $data['yjd_day']     = NUll;
                db()->startTrans();
                try{
                    db('c_customerinfo')->where('customer_number',$param['customer_number'])->update($data);
                    db()->commit();
                    return array('code'=>200,'msg'=>'取消预约成功','data'=>'');
                }catch (\Exception $e){
                    db()->rollback();
                    return array('code'=>101,'msg'=>'取消预约失败','data'=>$e->getMessage());
                }
            }
        }
        
    }

    //新客资来电添加
    public function addNewCusCall($param){
        $info['data'] = getStaffInfoById(session('staff_id'));
        $param['dj_staff'] = $info['data']['staffname'];
        $param['dj_staff_id'] = $info['data']['id'];
        $param['dj_staff_number'] = $info['data']['staffnumber'];
        $param['shop_name'] = session('shop_name');
        $param['shop_code'] = session('shop_code');
        $param['audio_path'] = session('ip').':'.session('port').'/osip_playwave.cpc?guid='.cache('guid_'.$param['customer_tel']);
        foreach($param as $k=>$v){
            if(empty($v) || $v == '请选择'){
                unset($param[$k]);
            }
        }
        db()->startTrans();
        try{
            db('CCallRegistration')->insert($param);
            action_log($param,[],$param['customer_id'],session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'新客户来电插入成功',);
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'新客户来电插入失败','error'=>$e->getMessage());
        }
    }
    //老客资来电添加
    public function addOldCusCall($param){
        $info['data'] = getStaffInfoById(session('staff_id'));
        $c_info = $this->getCustomerInfo($param['customer_id']);
        $param['dj_staff'] = $info['data']['staffname'];
        $param['dj_staff_id'] = $info['data']['id'];
        $param['dj_staff_number'] = $info['data']['staffnumber'];
        $param['shop_name'] = $info['data']['shop_name'];
        $param['shop_code'] = $info['data']['shop_code'];
        $param['customer_sex'] = $c_info['customer_sex'];
        $param['customer_wechat'] = $c_info['customer_wechat'];
        $param['customer_weibo'] = $c_info['customer_weibo'];
        $param['customer_qq'] = $c_info['customer_qq'];
        $param['customer_address'] = $c_info['customer_address'];
        $param['customer_sex'] = $c_info['customer_sex'];
        $param['access_model'] = $c_info['access_model'];
        $param['customer_region'] = $c_info['customer_region'];
        db()->startTrans();
        try{
            db('CCallRegistration')->insert($param);
            action_log($param,[],$param['customer_id'],session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'老客户来电插入成功',);
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'老客户来电插入失败','error'=>$e->getMessage());
        }
    }

    //提醒用的发送信息函数
    /*
     * @param title 标题
     * @param msg   信息内容
     * @param id    客资id
     * @param day   提前几天发送
     * @param time  再约/生日/结婚纪念日日期
     * return boolean
     * */
    public function remindSendMessage($title,$msg,$id,$day,$time,$flag){
        //调用消息队列
        db()->startTrans();
        try{
            // 消息  用数据  //send_type:'消息类型:1:短消息(弹窗)；2：通知', 默认接收
            $message = array(
                'send_type'   => '2',
                'send_title'   => $title,
                'send_msg'    => $msg,
                'receive_id'  => session('staff_id'),
                'receive_name'=> session('staff_name'),
                'operation_type'=> 2,
                'time_out'=> 120,
            );
            sendSystemMessage($message);
            $day = intval($day);
            $day = date('m-d', strtotime("+ $day day"));

            //信息发送成功后修改字段为已发送，避免再次发送
            if ($day == date('m-d', strtotime($time))) {
                if ($flag == 'customer_birthday') {
                    db('CCustomerinfo')->where('id', $id)->update(array('is_send_birthday_msg' => 1));
                }
                if ($flag == 'marry_day') {
                    db('CCustomerinfo')->where('id', $id)->update(array('is_send_wedd_msg' => 1));
                }
                if ($flag == 'yjd_day') {
                    db('CCustomerinfo')->where('id', $id)->update(array('is_send_yjd_msg' => 1));
                }
                if ($flag == 'syjd_day') {
                    db('CCustomerinfo')->where('id', $id)->update(array('is_send_syjd_msg' => 1));
                }
                if ($flag == 'next_time') {
                    db('CCustomerinfo')->where('id', $id)->update(array('is_send_next_msg' => 1));
                }
            }
            //清除缓存
            cache('remind_' . session('staff_id'), null);
            db()->commit();
            return true;
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>200,'msg'=>'提醒发送失败','data'=>'');
        }
    }
    //移动端用查询事业部下有多少符合的店面
    public function getShopInfo($param){
        if($param['brandclass']){
            $data['brandclass'] = $param['brandclass'];
        }
        if($param['is_dig']){
            $data['is_dig'] = $param['is_dig'];
        }
        if($param['brandclass_id']){
            $data['brandclass_id'] = $param['brandclass_id'];
        }
        if($param['is_marketing']){
            $data['is_marketing'] = $param['is_marketing'];
        }
        // $url = '5a005e0038270';
        // $res = sx_call($url,$data);
        
        $mc = new \app\common\lib\mcInterface();
        $res = $mc->getShops($data);
        if($res !== false){
            return ['code'=>'200','data'=>$res];
        }else{
            return ['code'=>$mc->_code,'msg'=>$mc->_msg,'data'=>[]];
        }
    }
    //客资提醒
    function isNextTimeRemind()
    {
        return array('code'=>200,'msg'=>'');
        //检测是否有需要修改的信息
        /*$check = db('CCustomerinfo')
            ->whereOr('sales_staff_id = :sales_staff_id1 and is_next = :is_next and is_send_next_msg =:is_send_next_msg',['sales_staff_id1'=>session('staff_id'),'is_next'=>1,'is_send_next_msg'=>1])
            ->whereOr('sales_staff_id = :sales_staff_id2 and is_send_birthday_msg =:is_send_birthday_msg',['sales_staff_id2'=>session('staff_id'),'is_send_birthday_msg'=>1])
            ->whereOr('sales_staff_id = :sales_staff_id3 and is_send_wedd_msg =:is_send_wedd_msg',['sales_staff_id3'=>session('staff_id'),'is_send_wedd_msg'=>1])
            ->whereOr('sales_staff_id = :sales_staff_id4 and is_send_yjd_msg =:is_send_yjd_msg',['sales_staff_id4'=>session('staff_id'),'is_send_yjd_msg'=>1])
            ->select();
        db()->startTrans();
        try{
            if(!empty($check)){
                //当前时间大于提醒时间时，修改提醒字段
                foreach($check as $k=>$v){
                    if(date('Y-m-d',time()) > $v['next_time']){
                        db('CCustomerinfo')->where('id',$v['id'])->update(array('is_next'=>2,'next_time'=>null,'is_send_next_msg'=>2));
                    }
                    if(date('m-d',time()) > date('m-d',strtotime($v['customer_birthday']))){
                        db('CCustomerinfo')->where('id',$v['id'])->update(array('is_send_birthday_msg'=>2));
                    }
                    if(date('m-d',time()) > date('m-d',strtotime($v['wedding_date']))){
                        db('CCustomerinfo')->where('id',$v['id'])->update(array('is_send_wedd_msg'=>2));
                    }
                    if(date('m-d',time()) > date('m-d',strtotime($v['yjd_day']))){
                        db('CCustomerinfo')->where('id',$v['id'])->update(array('is_send_yjd_msg'=>2));
                    }
                    if(date('m-d',time()) > date('m-d',strtotime($v['syjd_day']))){
                        db('CCustomerinfo')->where('id',$v['id'])->update(array('is_send_syjd_msg'=>2));
                    }
                }
            }
            //提醒设定
            $remind = db('s_reminditemset')->where('shop_code', session('shop_code'))->where('isopen', 1)->select();

            if(!empty($remind)){
                foreach ($remind as $k => $v) {
                    $day = date('m-d', strtotime('+' . $v['advancehour'] . ' days'));
                    if ($v['id'] == 'remind1') {
                        $info = db('CCustomerinfo')->where('sales_staff_id', session('staff_id'))->where('is_send_syjd_msg', 2)->where('syjd_day', 'like', '%' . $day . '%')->field('id,customer_name,customer_tel,syjd_day')->select();
                    } elseif ($v['id'] == 'remind2') {
                        $info = db('CCustomerinfo')->where('sales_staff_id', session('staff_id'))->where('is_next', 1)->where('is_send_next_msg', 2)->where('next_time', 'like', '%' . $day . '%')->field('id,customer_name,customer_tel,next_time')->select();
                    } elseif ($v['id'] == 'remind3') {
                        $info = db('CCustomerinfo')->where('sales_staff_id', session('staff_id'))->where('yjd_day', 'like', '%' . $day . '%')->where('is_send_yjd_msg', 2)->field('id,customer_name,customer_tel,yjd_day')->select();
                    }else{
                        $info = db('CCustomerinfo')
                            ->whereOr('sales_staff_id = :sales_staff_id2 and customer_birthday like :customer_birthday AND is_send_birthday_msg = :is_send_birthday_msg',['sales_staff_id2'=>session('staff_id'),'customer_birthday'=>'%-'.$day.'%','is_send_birthday_msg'=>2])
                            ->whereOr('sales_staff_id = :sales_staff_id3 and wedding_date like :wedding_date AND is_send_wedd_msg = :is_send_wedd_msg',['sales_staff_id3'=>session('staff_id'),'wedding_date'=>'%-'.$day.'%','is_send_wedd_msg'=>2])
                            ->field('id,customer_name,customer_tel,wedding_date,customer_birthday')
                            ->select();
                    }
        //          print_r(db()->getLastSql());die;
        //      print_r($info);
                    if(!empty($info)){
                        if($v['advancehour'] == 0){
                            $v['advancehour'] = '今天';
                        }else{
                            $v['advancehour'] = $v['advancehour'].' 天后';
                        }
                        foreach($info as $ke=>$ve){
                            if(date('m-d',strtotime($ve['customer_birthday'])) == $day){
                                $msg = '请注意:当前名为 '.$ve['customer_name'].',手机号为 '.$ve['customer_tel'].' 的客资, '.$v['advancehour'].' 是他生日!';
                                $title = '客资生日提醒';
                                $this->remindSendMessage($title,$msg,$ve['id'],$v['advancehour'],$ve['customer_birthday'],'customer_birthday');
                            }elseif(date('m-d',strtotime($ve['wedding_date'])) == $day){
                                $msg = '请注意:当前名为 '.$ve['customer_name'].',手机号为 '.$ve['customer_tel'].' 的客资, '.$v['advancehour'].' 是他的结婚纪念日!';
                                $title = '客资结婚纪念日提醒';
                                $this->remindSendMessage($title,$msg,$ve['id'],$v['advancehour'],$ve['wedding_date'],'wedding_date');
                            }elseif(date('m-d',strtotime($ve['yjd_day'])) == $day){
                                $msg = '请注意:当前名为 '.$ve['customer_name'].',手机号为 '.$ve['customer_tel'].' 的客资, '.$v['advancehour'].' 是预进店日期!';
                                $title = '客资预进店提醒';
                                $this->remindSendMessage($title,$msg,$ve['id'],$v['advancehour'],$ve['yjd_day'],'yjd_day');
                            }elseif(date('m-d',strtotime($ve['syjd_day'])) == $day){
                                $msg = '请注意:当前名为 '.$ve['customer_name'].',手机号为 '.$ve['customer_tel'].' 的客资, '.$v['advancehour'].' 进店!';
                                $title = '客资进店提醒';
                                $this->remindSendMessage($title,$msg,$ve['id'],$v['advancehour'],$ve['syjd_day'],'syjd_day');
                            }elseif(date('m-d',strtotime($ve['next_time'])) == $day){
                                $msg = '当前名为 '.$ve['customer_name'].',手机号为 '.$ve['customer_tel'].' 的客资, '.$v['advancehour'].' 再约进店，请注意接待!';
                                $title = '客资再约提醒';
                                $this->remindSendMessage($title,$msg,$ve['id'],$v['advancehour'],$ve['next_time'],'next_time');
                            }
                        }
                    }
                }
            }
            db()->commit();
            return array('code'=>200,'msg'=>'');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>200,'msg'=>'');
        }*/
    }
    public function getCustomerByTel($param){
        $res = db('c_customerinfo')->where('customer_tel|mate_tel',$param['customer_tel'])->find();
        if(!empty($res)){
            return array('code'=>200,'msg'=>'新客户','data'=>$res);
        }else{
            $telInfo = getData($param['customer_tel']);
            $arr = explode(' ',$telInfo);
            if($arr[1] == $arr[2]){
                $tel_belong = $arr[1];
            }else{
                $tel_belong = $arr[1].' '.$arr[2];
            }
            return array('code'=>100,'msg'=>'新客户','data'=>$tel_belong);
        }
    }
    //获取呼叫前缀
    public function getCallPrefix(){
        $res = db('SCallPrefix')->where('shop_code',session('shop_code'))->select();
        return $res;
    }
    //预约进店
    /**
     * @param $param
     * @return array
     * @throws Exception
     */
    public function customerYJD($param){
        $id = intval($param['id']);
        $customerInfo = db('c_customerinfo')->where('id', $id)->find();

        $data['consulation_shop_code'] =$into['consulation_shop_code']= $param['consulation_shop_code'];
        $data['consulation_shop']      =$into['consulation_shop_name']= $param['consulation_shop'];
        $data['yjd_day']           =$into['yjd_day']    = $param['yjd_day'] ? $param['yjd_day'] : null;
        $data['intostore_note'] = save_clips_to_file($param['intostore_note'],'upload/img/'.date('Ymd',time()));
        $data['intostore_note'] = DeleteHtml($data['intostore_note']);
        $data['yjd_action_day'] = date('Y-m-d H:i:s',time());

        //默认最多只能修改昨天的
        if(date('Ymd',strtotime($data['yjd_day']))<date('Ymd',strtotime('-1 days'))){
            // 预约进店 预约时间是否必选（深圳天长定制） 默认0（必选） 天长1（非必选）
            $isYjdMust = config('isYjdMust');
            if ($isYjdMust!=1) {
                return array('code' =>105,'msg' =>'只能预约到昨天','data'=>'');
            }
        }
        if(!empty($param['reception_id']) || !empty($customerInfo['reception_id'])){
            $data['reception_id']   = $into['reception_id']   = intval($param['reception_id']);
            $data['reception_name'] = $into['reception_name'] = $param['reception_name'];
        }
        $into['cid'] = $id;
        $into['operate_id'] = $param['staff_id'] ? $param['staff_id'] : session('staff_id');
        $into['operate_name'] = $param['staff_name'] ? $param['staff_name'] : session('staff_name');
        $into['create_time'] = date('Y-m-d H:i:s');
        $into['intostore_remark'] = $data['intostore_note'];
        if ($customerInfo['is_success']) {
            $into['is_success'] = $customerInfo['is_success'];
        }

        // staffnumber
        $receptionInfo = getStaffInfoById($data['reception_id']);
        // 店面类型 （1：婚纱；2：儿童；3：旅拍；4：艺术；5：其他）
        $shop_type = session('shop_type');
        if ($shop_type == 2) {
            $shop_type = 1;
        }else{
            $shop_type = 0;
        }
        
        $logData = [
            'consulation_shop'      => $customerInfo['consulation_shop'],
            'yjd_day'               => $customerInfo['yjd_day'],
            'intostore_note'        => $customerInfo['intostore_note'],
            'reception_name'        => $customerInfo['reception_name'],
        ];
        $mark = '';
        if(!$data['yjd_day']){
            // 预约进店 预约时间是否必选（深圳天长定制） 默认0（必选） 天长1（非必选）
            $isYjdMust = config('isYjdMust');
            if ($isYjdMust!=1) {
                return array('code' =>101,'msg' =>'预约时间不能为空','data'=>'');
            }
        }
        if(!$data['consulation_shop_code']){
            return array('code' =>101,'msg' =>'意向店面不能为空','data'=>$param);
        }
        if($customerInfo['is_valid'] != 1){
            $data['is_valid'] = 1;
            $data['yx_day'] = date('Y-m-d H:i:s',time());
            $mark .= ' 已改为有效；';
        }
        if($customerInfo['is_loss'] != 2){
            $data['is_loss'] = 2;
            $data['loss_day'] = NULL;
            $mark .= ' 已撤销不再追踪；';
        }

        //修改追踪时间
        $time = date('Y-m-d H:i:s',time());
        if(empty($customerInfo['c_star_day'])){
            $data['c_star_day'] = $time;
            $data['c_end_day'] = $time;
            $data['last_trackday'] = $time;
            $mark .= ' 更新开始追踪时间：'.$time;
        }else{
            $data['c_end_day'] = $time;
            $data['last_trackday'] = $time;
            $mark .= ' 更新最后追踪时间：'.$time;
        }

        $shop_code = $customerInfo['shop_code'];
        $shop_name = $customerInfo['shop_name'];
        $brandclass_id = $customerInfo['brandclass_id'];
        $brandclass = $customerInfo['brandclass'];

        // $yjd_day = date('Y-m-d H:i:s',strtotime($data['yjd_day']));
        //如果标记预约，存入pool表
        //查询再约提前时间
        $adv = db('s_reminditemset')->where('id','remind3')->where('brandclass_id',$brandclass_id)->where('isopen',1)->field('advancehour')->find();
        if($adv['advancehour'] || $adv['advancehour'] == 0){
            $hour = date('H',strtotime($data['yjd_day']));
            if($hour == 0){
                $time = date('Y-m-d 10:00:00',strtotime($data['yjd_day'])-86400*$adv['advancehour']);
            }else{
                $time = date('Y-m-d H:i:s',strtotime($data['yjd_day'])-86400*$adv['advancehour']);
            }
            if($customerInfo['customer_tel']){
                $notice =  '电话：【'.$customerInfo['customer_tel'].'】';
            }elseif($customerInfo['customer_wechat']){
                $notice =  '微信：【'.$customerInfo['customer_wechat'].'】';
            }elseif($customerInfo['customer_qq']){
                $notice =  'QQ：【'.$customerInfo['customer_qq'].'】';
            }

            $message = array(
                'customer_id' => $id,
                'send_type'   => 1,
                'send_title'  => '预约提醒',
                'send_msg'    => '当前ID:【'.$id.'】,名为：【'.$customerInfo['customer_name'].'】,'.$notice.'的客资，【'.date('Y-m-d H:i',strtotime($data['yjd_day'])).'】预约进店',
                'receive_id'  => $customerInfo['sales_staff_id'],
                'receive_name'=> $customerInfo['sales_staff'],
                'operation_type'=> 2,
                'time_out'=> 120,
                'consulation_shop'=>$data['consulation_shop'],
                'yjd_time' => $data['yjd_day']
            );
            $pool = array(
                'cid' => $id,
                'msg' => json_encode($message),
                'fp_time_out' => strtotime($time),
                'count'=>0,
                'pool_type' => 2,
                'create_time' => date('Y-m-d H:i:s',time()),
            );
        }
        // 查询预约提前时间
        $before = db('s_reminditemset')->where('id','yyjd_before_minute')->where('brandclass_id',$brandclass_id)->where('isopen',1)->value('advancehour');
        if($before>0){
            $time1 = strtotime($data['yjd_day'])-60*$before;

            $notice = '';
            if($customerInfo['customer_tel']){
                $notice =  '电话：【'.$customerInfo['customer_tel'].'】';
            }elseif($customerInfo['customer_wechat']){
                $notice =  '微信：【'.$customerInfo['customer_wechat'].'】';
            }elseif($customerInfo['customer_qq']){
                $notice =  'QQ：【'.$customerInfo['customer_qq'].'】';
            }

            $message1 = array(
                'customer_id' => $id,
                'send_type'   => 1,
                'send_title'  => '预约提醒',
                'send_msg'    => '当前ID:【'.$id.'】,名为：【'.$customerInfo['customer_name'].'】,'.$notice.'的客资，【'.date('Y-m-d H:i',strtotime($data['yjd_day'])).'】预约进店,现提前'.$before.'分钟提醒。',
                'receive_id'  => $customerInfo['sales_staff_id'],
                'receive_name'=> $customerInfo['sales_staff'],
                'operation_type'=> 2,
                'time_out'=> 120,
                'consulation_shop'=>$data['consulation_shop'],
                'yjd_time' => $data['yjd_day']
            );
            $pool1 = array(
                'cid' => $id,
                'msg' => json_encode($message1),
                'fp_time_out' => $time1,
                'count'=>0,
                'pool_type' => 2,
                'create_time' => date('Y-m-d H:i:s',time()),
            );
        }
        //查询预约延后时间
        $after = db('s_reminditemset')->where('id','yyjd_after_minute')->where('brandclass_id',$brandclass_id)->where('isopen',1)->value('advancehour');
        if($after>0){
            $time2 = strtotime($data['yjd_day'])+60*$after;

            $notice = '';
            if($customerInfo['customer_tel']){
                $notice =  '电话：【'.$customerInfo['customer_tel'].'】';
            }elseif($customerInfo['customer_wechat']){
                $notice =  '微信：【'.$customerInfo['customer_wechat'].'】';
            }elseif($customerInfo['customer_qq']){
                $notice =  'QQ：【'.$customerInfo['customer_qq'].'】';
            }

            $message2 = array(
                'customer_id' => $id,
                'send_type'   => 1,
                'send_title'  => '预约提醒',
                'send_msg'    => '当前ID:【'.$id.'】,名为：【'.$customerInfo['customer_name'].'】,'.$notice.'的客资，【'.date('Y-m-d H:i',strtotime($data['yjd_day'])).'】预约进店后未进店，请及时沟通！',
                'receive_id'  => $customerInfo['sales_staff_id'],
                'receive_name'=> $customerInfo['sales_staff'],
                'operation_type'=> 2,
                'time_out'=> 120,
                'consulation_shop'=>$data['consulation_shop'],
                'yjd_time' => $data['yjd_day']
            );
            $pool2 = array(
                'cid' => $id,
                'msg' => json_encode($message2),
                'fp_time_out' => $time2,
                'count'=>0,
                'pool_type' => 11,//预约后未进店提醒
                'create_time' => date('Y-m-d H:i:s',time()),
            );
        }
        $isTable = isTableExist('c_customer_intostore');
        db()->startTrans();
        $is_erp = is_install('sx_erp');
        try{
            // $erp = false;
            if($is_erp && !$isTable){
                $erp = config('ext.app_config');
                $addr = $erp['sx_erp']['addr'];
                // 婚纱0，儿童1
                $url = trim($addr,'/').'/SX_CrmApi/Add_Guestinfo?Token=^******^&CustomerType='.$shop_type;
                // var_dump($customerInfo);
                $dataN["Customer_name"] = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
                $dataN["Customer_tel"] = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
                $dataN["Customer_wechat"] = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
                $dataN["Customer_qq"] = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
                $dataN["Customer_sex"] = $customerInfo['customer_sex'] ? $customerInfo['customer_sex'] : '';
                $dataN["Consultation_type"] = $customerInfo['consultation_type'] ? $customerInfo['consultation_type'] : '';
                $dataN["Customer_area"] = $customerInfo['customer_area'] ? $customerInfo['customer_area'] : '';

                if ($customerInfo['customer_birthday']) {
                    $customer_birthday = date('Y-m-d',strtotime($customerInfo['customer_birthday']));
                }else{
                    $customer_birthday = '';
                }
                $dataN["Customer_birthday"] = $customer_birthday;
                // 客户意向
                $dataN["Customer_intention"] = $customerInfo['customer_intention'] ? $customerInfo['customer_intention'] : '';
                $dataN["Customer_orderaddress"] = $customerInfo['customer_orderaddress'] ? $customerInfo['customer_orderaddress'] : '';
                $dataN["Customer_address"] = $customerInfo['customer_address'] ? $customerInfo['customer_address'] : '';
                $dataN["Yjd_day"] = $data['yjd_day'];

                if ($customerInfo['yp_day']) {
                    $yp_day = date('Y-m-d',strtotime($customerInfo['yp_day']));
                }else{
                    $yp_day = '';
                }
                $dataN["Yp_day"] = $yp_day;

                if ($customerInfo['marry_day']) {
                    $wedding_date = date('Y-m-d',strtotime($customerInfo['marry_day']));
                }else{
                    $wedding_date = '';
                }
                $dataN["Wedding_date"] = $wedding_date;

                $dataN["Mate_name"] = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
                $dataN["Mate_sex"] = $customerInfo['mate_sex'] ? $customerInfo['mate_sex'] : '';
                $dataN["Mate_tel"] = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
                $dataN["Mate_wechat"] = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
                $dataN["Mate_qq"] = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';

                if ($customerInfo['mate_birthday']) {
                    $mate_birthday = date('Y-m-d',strtotime($customerInfo['mate_birthday']));
                }else{
                    $mate_birthday = '';
                }
                $dataN["Mate_birthday"] = $mate_birthday;

                // $dataN["Dj_staff"] = session('staff_name') ? session('staff_name') : '';
                $dataN["Customer_remark"] = $data['intostore_note'] ? strip_tags($data['intostore_note']) : '';
                $dataN["Shop_name"] = $data['consulation_shop'] ? $data['consulation_shop'] : '';
                $dataN["Shop_code"] = $data['consulation_shop_code'] ? $data['consulation_shop_code'] : '';
                $dataN["Customer_from"] = 'CRM';
                $dataN["Brandid"] = $customerInfo['brandclass_id'] ? $customerInfo['brandclass_id'] : '';
                $dataN["From_index"] = $customerInfo['customer_number'] ? $customerInfo['customer_number'] : '';
                // 渠道
                $dataN["Customer_channel"] = $customerInfo['customer_channel'] ? $customerInfo['customer_channel'] : '';
                // 来源
                $dataN["Customer_cource"] = $customerInfo['customer_cource'] ? $customerInfo['customer_cource'] : '';
                // '客户类型，1新单、2转介绍',
                $dataN["Customer_type"] = $customerInfo['customer_type'] ? $customerInfo['customer_type'] : '';

                // 人员信息（登记人，追踪人，门市） 20181031
                $department = $this->getDepartment();
                // crm 接待人员，取 意向店面下的工作类型为门市的人
                $dataN["Sales_staff"] = $data['reception_name'] ? $data['reception_name'] : '';
                $dataN["Sales_staff_number"] = $receptionInfo['staffnumber'] ? $receptionInfo['staffnumber'] : '';
                // 登记人信息
                $dataN["Dj_staff"] = $customerInfo['dj_staff'] ? $customerInfo['dj_staff'] : '';
                // 登记人部门
                $dataN["Crmentryrenbm"] = $department[$customerInfo['dj_department_id']]['department_name'] ? $department[$customerInfo['dj_department_id']]['department_name'] : '';
                // 追踪人
                $dataN["Crmentryren"] = $customerInfo['sales_staff'] ? $customerInfo['sales_staff'] : '';
                // 追踪人所属店面狗号
                $dataN["shop_codezzr"] = $customerInfo['shop_code'] ? $customerInfo['shop_code'] : '';
                $dataN["shop_namezzr"] = $customerInfo['shop_name'] ? $customerInfo['shop_name'] : '';
                // 追踪人所属部门
                $dataN["departidzzr"]  = $customerInfo['sales_department_id'] ? $customerInfo['sales_department_id'] : '';
                $dataN["departnamezzr"]= $department[$customerInfo['sales_department_id']]['department_name'] ? $department[$customerInfo['sales_department_id']]['department_name'] : '';
                $dataN['quitYjd'] = $param['quitYjd'] ? (int)$param['quitYjd'] : 1;
                // var_dump($dataN);
                // exit;
                $dataN = json_encode($dataN);
                // $dataN = urlencode($dataN);
                // print_r($dataN);
                // print_r($url);
                // $response = requestERP($url, $dataN);
                // print_r($response);
                // exit;
                // 调 erp 接口
                $response = requestERP($url, $dataN);
                if ($response['Code'] != 200) {
                    db()->rollback();
                    return array('code'=>100,'msg'=>'erp接口调用失败，请重试。','error'=>json_encode($response));
                }else{
                    $data['update_time'] = date('Y-m-d H:i:s');
                    db('c_customerinfo')->where('id',$id)->update($data);
                    // newData oldData customer_id staff_id staff_name
                }
            }else{//未安装ERP
                $data['update_time'] = date('Y-m-d H:i:s');
                db('c_customerinfo')->where('id',$id)->update($data);
            }
            //插入进店表
            if($isTable){
                // 预约进店 预约时间是否必选（深圳天长定制） 默认0（必选） 天长1（非必选）
                $isYjdMust = config('isYjdMust');
                if ($isYjdMust===1) {
                    $intoInfo = db('c_customer_intostore')->where('cid',$id)->where('status',1)->where('yjd_day|create_time','>=',date('Y-m-d 00:00:00'))->where('is_intostore',1)->order('id desc')->find();
                }else{
                    $intoInfo = db('c_customer_intostore')->where('cid',$id)->where('status',1)->where('yjd_day','>=',date('Y-m-d 00:00:00'))->where('is_intostore',1)->where('consulation_shop_code',$data['consulation_shop_code'])->order('id desc')->find();
                }
                // echo db()->getLastSql();die;
                //当前客资如果是已进店的，不能再约到当前了。
                $todayInto = db('c_customer_intostore')->where('cid',$id)->where('status',1)->where('yjd_day','like',date('Y-m-d',strtotime($data['yjd_day'])).'%')->where('consulation_shop_code',$data['consulation_shop_code'])->find();
                if($todayInto && in_array($todayInto['is_intostore'],[2,3,5])){
                    db()->rollback();
                    return array('code' =>102,'msg' =>'指定日期已有邀约，不可再邀。','data'=>'');
                }
                //
                //*/
                if($intoInfo){
                    db('c_customer_intostore')->where('id',$intoInfo['id'])->update(['status'=>99]);
                    // $oldInto = 
                    if(in_array($intoInfo['is_intostore'],[2,3,5])){
                        $into['reback'] = 2;
                    }
                    db('c_customer_intostore')->insert($into);
                }else{
                    db('c_customer_intostore')->insert($into);
                }
            }

            //生成进店码,存入进店码表
            // $jd_code = get_rand_string(8,1);
            // $cid = db('c_customer_jdm')->where('jd_code',$jd_code)->value('c_id');

            // while($cid){
            //     $jd_code = get_rand_string(8,1);
            //     $cid = db('c_customer_jdm')->where('jd_code',$jd_code)->value('c_id');
            // }

            $code = [
                'c_id' => $id,
                'shop_code'    => $shop_code,
                'shop_name'    => $shop_name,
                'brandclass_id'=> $brandclass_id,
                'brandclass'   => $brandclass,
                // 'jd_code'      => $jd_code,
                'jd_code'      => $id,
            ];
            db('c_customer_jdm')->insert($code);
            //预约短信模板
            $yyModel  =  db_config('yy_sms_model_'.$shop_code);
            $flags = ['mate','customer'];
            if($yyModel && in_array($param['receiver_flag'], $flags)){
                if(empty($customerInfo['customer_tel'])){
                    db()->rollback();
                    return array('code'=>45,'msg'=>'未获取到客户手机号，不能发送短信');
                }
                $sms = db_config('sms_'.session('shop_code'));
                $smsparam = [
                    'ids' => $id,//客资id
                    '_template_id' => $yyModel,//模板id
                    'send_config' => $sms,//短信账号
                    'flag'=>'yjd',
                    'receiver_flag'=>$param['receiver_flag']
                ];
                $s = $this->send_message_notice($smsparam);
                if($s['code'] != 200){
                    db()->rollback();
                    return array('code' =>100,'msg' =>'预约进店发送短信失败','data'=>$s['data']);
                }

            }
            $newData = [
                'consulation_shop'      => $data['consulation_shop'],
                'yjd_day'               => $data['yjd_day'],
                'intostore_note'        => $data['intostore_note'],
                'reception_name'        => $data['reception_name'],
            ];

            if($logData['consulation_shop'] == $newData['consulation_shop']){
                unset($logData['consulation_shop'],$newData['consulation_shop']);
            }
            if($logData['yjd_day'] == $newData['yjd_day']){
                unset($logData['yjd_day'],$newData['yjd_day']);
            }
            if($logData['intostore_note'] == $newData['intostore_note']){
                unset($logData['intostore_note'],$newData['intostore_note']);
            }
            if($logData['reception_name'] == $newData['reception_name']){
                unset($logData['reception_name'],$newData['reception_name']);
            }
            action_log($newData,$logData,$id);
            //追踪记录
            $params['customer_id'] = $id;
            $params['customer_name'] = $customerInfo['customer_name'];
            $params['customer_number'] = $customerInfo['customer_number'];
            $params['sales_remark'] = '预约进店备注:预约时间：'.$data['yjd_day'].'，备注：'.$data['intostore_note'].';'.$mark;
            $params['sales_day'] = date('Y-m-d H:i:s',time());
            $params['sales_staff'] = $param['staff_name'] ? $param['staff_name'] : session('staff_name');
            $params['sales_staff_id'] = $param['staff_id'] ? $param['staff_id'] : session('staff_id');
            $params['sales_staff_number'] = $param['staff_number'] ? $param['staff_number'] : session('staff_number');
            $params['shop_name'] = $shop_name;
            $params['shop_code'] =$shop_code;
            $params['gtType'] = $param['gtType'];
            $params['customer_tel'] = $param['customer_tel'];
            $params['consultation_type'] = $param['consultation_type'];
            $params['tel_static'] = $param['tel_static'];
            $params['no_track'] = '预约进店';
            db('CSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$id,null);
            
            //修改客资表近三次追踪记录
            getSalesTracking($id);

            //如果是爆破活动，修改对应的爆破表数据
            if($customerInfo['is_act'] == 2){
                db('c_swap_customer')->where('customer_number',$customerInfo['customer_number'])->update([['yjd_day'=>$data['yjd_day'],'yjd_action_day']=>$time]);
            }
            if($customerInfo['sales_staff_id']){
                if($pool){
                    db('c_fp_pool')->insertGetId($pool);
                }
                if($pool1){
                    db('c_fp_pool')->insertGetId($pool1);
                }
                if($pool2){
                    db('c_fp_pool')->insertGetId($pool2);
                }
            }

            db()->commit();
            return array('code'=>200,'msg'=>'预约成功');
        }catch (\Exception $e){
            db()->rollback();
            return array('code' =>100,'msg' =>'预约进店失败','data'=>$e->getMessage());
        }
    }
    //预约进店 儿童
    /**
     * @param $param
     * @return array
     * @throws Exception
     */
    public function customerYJD_child($param){
        $id = intval($param['id']);
        $data['consulation_shop_code'] =$into['consulation_shop_code']= $param['consulation_shop_code'];
        $data['consulation_shop']     =$into['consulation_shop_name'] = $param['consulation_shop'];
        $data['yjd_day']             =$into['yjd_day']  = $param['yjd_day'] ? $param['yjd_day'] : null;
        $data['intostore_note'] = save_clips_to_file($param['intostore_note'],'upload/img/'.date('Ymd',time()));
        $data['intostore_note'] = DeleteHtml($data['intostore_note']);
        $data['yjd_action_day'] = date('Y-m-d H:i:s',time());
        //默认最多只能修改昨天的
        if(date('Ymd',strtotime($data['yjd_day']))<date('Ymd',strtotime('-1 days'))){
            return array('code' =>105,'msg' =>'最多只能预约到昨天','data'=>'');
        }
        if(!empty($param['reception_id'])){
            $data['reception_id']       = $into['reception_id']   = intval($param['reception_id']);
            $data['reception_name']     = $into['reception_name']   = $param['reception_name'];
        }
        $into['cid'] = $id;
        $into['operate_id'] = session('staff_id');
        $into['operate_name'] = session('staff_name');
        $into['create_time'] = date('Y-m-d H:i:s');
        $into['intostore_remark'] = $data['intostore_note'];
        // staffnumber
        $receptionInfo = getStaffInfoById($data['reception_id']);
        // 店面类型 （1：婚纱；2：儿童；3：旅拍；4：艺术；5：其他）
        $s_shop_type = session('shop_type');
        if ($s_shop_type == 2) {
            $shop_type = 1;
        }else{
            $shop_type = 0;
        }
        $customerInfo = db('c_customerinfo')->where('id', $id)->find();
        $logData = [
            'consulation_shop'      => $customerInfo['consulation_shop'],
            'yjd_day'               => $customerInfo['yjd_day'],
            'intostore_note'        => $customerInfo['intostore_note'],
            'reception_name'        => $customerInfo['reception_name'],
        ];
        $mark= '';
        if($data['yjd_day']>$customerInfo['yjd_day']){
            if($customerInfo['is_valid'] != 1){
                $data['is_valid'] = 1;
                $data['yx_day'] = date('Y-m-d H:i:s',time());
                $mark .= '已改为有效；';
            }
            if($customerInfo['is_loss'] == 1){
                $data['is_loss'] = 2;
                $data['loss_day'] = NULL;
                $data['loss_cause'] = NULL;
                $mark .= '已撤销不再追踪；';
            }
            // $yjd_day = date('Y-m-d H:i:s',strtotime($data['yjd_day']));
            //如果标记预约，存入pool表
            //查询再约提前时间
            $adv = db('s_reminditemset')->where('id','remind3')->where('brandclass_id',session('brandclass_id'))->where('isopen',1)->field('advancehour')->find();
            if($adv['advancehour'] || $adv['advancehour'] == 0){
                $hour = date('H',strtotime($data['yjd_day']));
                if($hour == 0){
                    $time = date('Y-m-d 10:00:00',strtotime($data['yjd_day'])-86400*$adv['advancehour']);
                }else{
                    $time = date('Y-m-d H:i:s',strtotime($data['yjd_day'])-86400*$adv['advancehour']);
                }
                $notice = '';
                if($customerInfo['customer_tel']){
                    $notice =  '电话：【'.$customerInfo['customer_tel'].'】';
                }elseif($customerInfo['customer_wechat']){
                    $notice =  '微信：【'.$customerInfo['customer_wechat'].'】';
                }elseif($customerInfo['customer_qq']){
                    $notice =  'QQ：【'.$customerInfo['customer_qq'].'】';
                }

                $message = array(
                    'customer_id' => $id,
                    'send_type'   => 1,
                    'send_title'  => '预约提醒',
                    'send_msg'    => '当前ID:【'.$id.'】,名为：【'.$customerInfo['customer_name'].'】,'.$notice.'的客资，【'.date('Y-m-d H:i',strtotime($data['yjd_day'])).'】预约进店',
                    'receive_id'  => session('staff_id'),
                    'receive_name'=> session('staff_name'),
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'consulation_shop'=>$data['consulation_shop'],
                    'yjd_time' => $data['yjd_day']
                );
                $pool = array(
                    'cid' => $id,
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime($time),
                    'count'=>0,
                    'pool_type' => 2,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
            }
            //查询预约提前时间
            $before = db('s_reminditemset')->where('id','yyjd_before_minute')->where('brandclass_id',session('brandclass_id'))->where('isopen',1)->value('advancehour');
            if($before>0){
                $time1 = strtotime($data['yjd_day'])-60*$before;

                $notice = '';
                if($customerInfo['customer_tel']){
                    $notice =  '电话：【'.$customerInfo['customer_tel'].'】';
                }elseif($customerInfo['customer_wechat']){
                    $notice =  '微信：【'.$customerInfo['customer_wechat'].'】';
                }elseif($customerInfo['customer_qq']){
                    $notice =  'QQ：【'.$customerInfo['customer_qq'].'】';
                }

                $message1 = array(
                    'customer_id' => $id,
                    'send_type'   => 1,
                    'send_title'  => '预约提醒',
                    'send_msg'    => '当前ID:【'.$id.'】,名为：【'.$customerInfo['customer_name'].'】,'.$notice.'的客资，【'.date('Y-m-d H:i',strtotime($data['yjd_day'])).'】预约进店',
                    'receive_id'  => session('staff_id'),
                    'receive_name'=> session('staff_name'),
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'consulation_shop'=>$data['consulation_shop'],
                    'yjd_time' => $data['yjd_day']
                );
                $pool1 = array(
                    'cid' => $id,
                    'msg' => json_encode($message1),
                    'fp_time_out' => $time1,
                    'count'=>0,
                    'pool_type' => 2,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
            }
            //查询预约提前时间
            $after = db('s_reminditemset')->where('id','yyjd_after_minute')->where('brandclass_id',session('brandclass_id'))->where('isopen',1)->value('advancehour');
            if($after>0){
                $time2 = strtotime($data['yjd_day'])+60*$after;

                $notice = '';
                if($customerInfo['customer_tel']){
                    $notice =  '电话：【'.$customerInfo['customer_tel'].'】';
                }elseif($customerInfo['customer_wechat']){
                    $notice =  '微信：【'.$customerInfo['customer_wechat'].'】';
                }elseif($customerInfo['customer_qq']){
                    $notice =  'QQ：【'.$customerInfo['customer_qq'].'】';
                }

                $message2 = array(
                    'customer_id' => $id,
                    'send_type'   => 1,
                    'send_title'  => '预约提醒',
                    'send_msg'    => '当前ID:【'.$id.'】,名为：【'.$customerInfo['customer_name'].'】,'.$notice.'的客资，【'.date('Y-m-d H:i',strtotime($data['yjd_day'])).'】预约进店后未进店，请及时沟通！',
                    'receive_id'  => session('staff_id'),
                    'receive_name'=> session('staff_name'),
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'consulation_shop'=>$data['consulation_shop'],
                    'yjd_time' => $data['yjd_day']
                );
                $pool2 = array(
                    'cid' => $id,
                    'msg' => json_encode($message2),
                    'fp_time_out' => $time2,
                    'count'=>0,
                    'pool_type' => 11,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
            }
        }
        $isTable = isTableExist('c_customer_intostore');
        db()->startTrans();
        $is_erp = is_install('sx_erp');
        try{
            // $erp = false;
            if($is_erp && !$isTable){
                $erp = config('ext.app_config');

                $addr = $erp['sx_erp']['addr_child'];
                // 婚纱0，儿童1
                // $url = $addr.'SX_CrmApi/Add_Guestinfo?Token=^******^&CustomerType='.$shop_type;
                $url = trim($addr,'/').'/SX_ChildCrmApi/Add_Guestinfo?Token=^******^&CustomerType='.$shop_type;

                $dataN["Customer_name"] = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
                $dataN["Customer_tel"] = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
                $dataN["Customer_wechat"] = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
                $dataN["Customer_qq"] = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
                $dataN["Customer_sex"] = $customerInfo['customer_sex'] ? $customerInfo['customer_sex'] : '';
                $dataN["Consultation_type"] = $customerInfo['consultation_type'] ? $customerInfo['consultation_type'] : '';
                $dataN["Customer_area"] = $customerInfo['customer_area'] ? $customerInfo['customer_area'] : '';

                if ($customerInfo['customer_birthday']) {
                    $customer_birthday = date('Y-m-d',strtotime($customerInfo['customer_birthday']));
                }else{
                    $customer_birthday = '';
                }
                $dataN["Customer_birthday"] = $customer_birthday;
                
                // 渠道
                $dataN["Customer_channel"] = $customerInfo['customer_channel'] ? $customerInfo['customer_channel'] : '';
                // 来源
                $dataN["Customer_cource"] = $customerInfo['customer_cource'] ? $customerInfo['customer_cource'] : '';

                $dataN["Customer_intention"] = $customerInfo['customer_intention'] ? $customerInfo['customer_intention'] : '';
                $dataN["Customer_orderaddress"] = $customerInfo['customer_orderaddress'] ? $customerInfo['customer_orderaddress'] : '';
                $dataN["Customer_address"] = $customerInfo['customer_address'] ? $customerInfo['customer_address'] : '';
                $dataN["Yjd_day"] = $data['yjd_day'];

                if ($customerInfo['yp_day']) {
                    $yp_day = date('Y-m-d',strtotime($customerInfo['yp_day']));
                }else{
                    $yp_day = '';
                }
                $dataN["Yp_day"] = $yp_day;

                if ($customerInfo['marry_day']) {
                    $wedding_date = date('Y-m-d',strtotime($customerInfo['marry_day']));
                }else{
                    $wedding_date = '';
                }
                $dataN["Wedding_date"] = $wedding_date;

                $dataN["Mate_name"] = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
                $dataN["Mate_sex"] = $customerInfo['mate_sex'] ? $customerInfo['mate_sex'] : '';
                $dataN["Mate_tel"] = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
                $dataN["Mate_wechat"] = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
                $dataN["Mate_qq"] = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';

                if ($customerInfo['mate_birthday']) {
                    $mate_birthday = date('Y-m-d',strtotime($customerInfo['mate_birthday']));
                }else{
                    $mate_birthday = '';
                }
                $dataN["Mate_birthday"] = $mate_birthday;

                $dataN["Sales_staff"] = $data['reception_name'] ? $data['reception_name'] : '';
                $dataN["Sales_staff_number"] = $receptionInfo['staffnumber'] ? $receptionInfo['staffnumber'] : '';
                $dataN["Customer_remark"] = $data['intostore_note'] ? $data['intostore_note'] : '';
                $dataN["Shop_name"] = $data['consulation_shop'] ? $data['consulation_shop'] : '';
                $dataN["Shop_code"] = $data['consulation_shop_code'] ? $data['consulation_shop_code'] : '';
                $dataN["Customer_from"] = 'CRM';
                $dataN["Brandid"] = $customerInfo['brandclass_id'] ? $customerInfo['brandclass_id'] : '';
                $dataN["From_index"] = $customerInfo['customer_number'] ? $customerInfo['customer_number'] : '';
                $department = $this->getDepartment();
                // 登记人信息
                $dataN["Dj_staff"] = $customerInfo['dj_staff'] ? $customerInfo['dj_staff'] : '';
                // 登记人部门
                $dataN["Crmentryrenbm"] = $department[$customerInfo['dj_department_id']]['department_name'] ? $department[$customerInfo['dj_department_id']]['department_name'] : '';
                // 追踪人
                $dataN["Crmentryren"] = $customerInfo['sales_staff'] ? $customerInfo['sales_staff'] : '';
                // 追踪人所属店面狗号
                $dataN["shop_codezzr"] = $customerInfo['shop_code'] ? $customerInfo['shop_code'] : '';
                $dataN["shop_namezzr"] = $customerInfo['shop_name'] ? $customerInfo['shop_name'] : '';
                // 追踪人所属部门
                $dataN["departidzzr"]  = $customerInfo['sales_department_id'] ? $customerInfo['sales_department_id'] : '';
                $dataN["departnamezzr"]= $department[$customerInfo['sales_department_id']]['department_name'] ? $department[$customerInfo['sales_department_id']]['department_name'] : '';
                $dataN['quitYjd'] = $param['quitYjd'] ? (int)$param['quitYjd'] : 1;

                //儿童相关字段
                $dataN['bbname']   = $customerInfo['baby_name'] ? $customerInfo['baby_name'] : '';
                $dataN['bbsex']    = $customerInfo['baby_sex'] ? $customerInfo['baby_sex'] : '';
                $dataN["bbithdate"]= $customerInfo['baby_birthday'] ? date('Ymd', strtotime($customerInfo['baby_birthday'])) : '';
                $dataN['yc_day']   = $customerInfo['ready_baby_day'] ? $customerInfo['ready_baby_day'] : '';
                $dataN['bb_hospital']= $customerInfo['baby_address'] ? $customerInfo['baby_address'] : '';

                $dataN = json_encode($dataN);
                // $dataN = urlencode($dataN);
                // print_r($dataN);
                // print_r($url);
                // $response = requestERP($url, $dataN);
                // print_r($response);
                // exit;

                // 调 erp 接口
                $response = requestERP($url, $dataN);
                if ($response['Code'] != 200) {
                    db()->rollback();
                    return array('code'=>100,'msg'=>'erp接口调用失败，请重试。','error'=>json_encode($response));
                }else{
                    $data['update_time'] = date('Y-m-d H:i:s');
                    db('c_customerinfo')->where('id',$id)->update($data);
                    // newData oldData customer_id staff_id staff_name
                }

            }else{//未安装ERP
                $data['update_time'] = date('Y-m-d H:i:s');
                db('c_customerinfo')->where('id',$id)->update($data);
            }
            //插入进店表
            if($isTable){
                $into_id = db('c_customer_intostore')->where('cid',$id)->where('status',1)->where('yjd_day','>=',date('Y-m-d 00:00:00'))->value('id');
                if(in_array($customerInfo['is_intostore'],[2,3,5])){
                    $into['reback'] = 2;
                }
                if($into_id){
                    db('c_customer_intostore')->where('id',$into_id)->update($into);
                }else{
                    db('c_customer_intostore')->insert($into);
                }
            }
            $newData = [
                'consulation_shop'      => $data['consulation_shop'],
                'yjd_day'               => $data['yjd_day'],
                'intostore_note'        => $data['intostore_note'],
                'reception_name'        => $data['reception_name'],
            ];
            action_log($newData,$logData,$id,session('staff_id'),session('staff_name'));
            //生成进店码,存入进店码表
            $jd_code = get_rand_string(8,1);
            $cid = db('c_customer_jdm')->where('jd_code',$jd_code)->value('c_id');
            while($cid){
                $jd_code = get_rand_string(8,1);
                $cid = db('c_customer_jdm')->where('jd_code',$jd_code)->value('c_id');
            }
            $code = [
                'c_id' => $id,
                'shop_code'  => session('shop_code'),
                'shop_name'  => session('shop_name'),
                'brandclass_id'  => session('brandclass_id'),
                'brandclass'  => session('brandclass'),
                'jd_code'     => $jd_code,
            ];
            db('c_customer_jdm')->insert($code);
            //预约短信模板
            $yyModel  = $param['model_id'] ? $param['model_id'] : db_config('yy_sms_model_'.session('shop_code'));
            if($yyModel){
                if(empty($customerInfo['customer_tel'])){
                    db()->rollback();
                    return array('code'=>45,'msg'=>'未获取到客户手机号，不能发送短信');
                }
                //发送短信
                $send_msg = db('s_message_templateinfo')->where('id',$yyModel)->value('mtemplate_content');
                if($jd_code){
//                    $send_msg .= ',进店码：'.$jd_code.',进店后失效!';
                }
                $sms = db_config('sms_'.session('shop_code'));
                $param = [
                    'ids' => $id,//客资id
                    'model_id' => $yyModel,//模板id
                    'send_msg' => $send_msg,//发送的模板内容
                    'send_config' => $sms,//短信账号
                    'flag' => 'yjd',
                ];
                $this->send_message($param);
            }
            //追踪记录
            $params['customer_id'] = $id;
            $params['customer_name'] = $customerInfo['customer_name'];
            $params['customer_number'] = $customerInfo['customer_number'];

            $params['sales_remark'] = '预约进店备注:预约时间：'.$data['yjd_day'].'，备注：'.$data['intostore_note'].';'.$mark;
            $params['sales_day'] = date('Y-m-d H:i:s',time());
            $params['sales_staff'] = session('staff_name');
            $params['sales_staff_id'] = session('staff_id');
            $params['sales_staff_number'] = session('staff_number');
            $params['shop_name'] = session('shop_name');
            $params['shop_code'] = session('shop_code');
            $params['gtType'] = $param['gtType'];
            $params['customer_tel'] = $param['customer_tel'];
            $params['consultation_type'] = $param['consultation_type'];
            $params['tel_static'] = $param['tel_static'];
            $params['no_track'] = '预约进店';
            db('CSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$id,null);
            //修改追踪时间
            $info = $this->getCustomerInfo($id);//客资信息
            $time = date('Y-m-d H:i:s',time());
            if(empty($info['c_star_day'])){
                $arr = array(
                    'c_star_day' => $time,
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }else{
                $arr = array(
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }
            if($info['is_loss'] == 1){
                $arr['is_loss'] = 2;
                $arr['loss_day'] = NULL;
                $arr['loss_cause'] = NULL;
            }
            db('CCustomerinfo')->where('id',$id)->update($arr);
            //修改客资为有效
            if($info['is_valid'] != 1 || empty($info['yx_day'])){
                $upd = array(
                    'is_valid' => 1,
                    'yx_day' => $time
                );
                db('CCustomerinfo')->where('id',$id)->update($upd);
            }
            //修改客资表近三次追踪记录
            getSalesTracking($id);

            /*$listName = 'historyDataList';
            $cinfo = [
                'id'     => $info['id'],
                'dj_id'  => $info['dj_staff_id'],
                'dj_day' => $info['dj_day'],
                'sel_id' => $info['sk_staff_id'],
                'sel_day'=> $info['sk_time'],
                'jr_id'  => $info['sales_staff_id'],
                'jr_day' => $info['jr_day'],
            ];
            $message = array(
                'type' => 1,
                'staff_id'   => session('staff_id'),
                'identity'   => 'sale',
                'cinfo'      => $cinfo,
                'old_data'   => array(),
                'new_data'   => array('tel_num'=>1),
                'controller' => 'Customer',
                'action'     => 'addSalesTracking',
            );
            push_list($listName, $message);*/
            if($pool){
                db('c_fp_pool')->insertGetId($pool);
            }
            if($pool1){
                db('c_fp_pool')->insertGetId($pool1);//预约提前提醒
            }
            if($pool2){
                db('c_fp_pool')->insertGetId($pool2);//预约延后提醒
            }
            //如果是爆破活动，修改对应的爆破表数据
            if($info['is_act'] == 2){
                db('c_swap_customer')->where('customer_number',$info['customer_number'])->update([['yjd_day'=>$data['yjd_day'],'yjd_action_day']=>$time]);
            }
            db()->commit();
            return array('code'=>200,'msg'=>'预约成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code' =>100,'msg' =>'预约进店失败','data'=>$e->getMessage());
        }
    }
    //订单详情表操作
    public function insert_order_detail($param){
        $data['order_sn'] = $param['order_sn'];
        $data['pay_time'] = $param['pay_time'] ? date('Y-m-d H:i:s',strtotime($param['pay_time'])) : date('Y-m-d H:i:s',time());
        $data['create_time'] = $param['create_time'] ? date('Y-m-d H:i:s',strtotime($param['create_time'])) : date('Y-m-d H:i:s',time());
        $data['order_valid'] = $param['order_valid'];
        $data['order_type'] = $param['order_type'];

        if($param['order_fact'] && !$param['two_pin_fact']){
            $data['pay_type'] = 1;
            $data['order_fact'] = $param['order_fact'];
            return db('c_order_detail')->insertGetId($data);
        }elseif(!$param['order_fact'] && $param['two_pin_fact']){
            $data['pay_type'] = 2;
            $data['order_fact'] = $param['two_pin_fact'];
            return db('c_order_detail')->insertGetId($data);
        }elseif($param['order_fact'] && $param['two_pin_fact']){
            $data['pay_type'] = 1;
            $data['order_fact'] = $param['order_fact'];
            $id = db('c_order_detail')->insertGetId($data);
            if($id){
                $data['pay_type'] = 2;
                $data['order_fact'] = $param['two_pin_fact'];
                return db('c_order_detail')->insertGetId($data);
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    //转订单
    public function zhuanOrder($param){
        $time = date('Y-m-d H:i:s',time());
        $pay_time = trim($param['pay_time']);
        $targetTimeStamp = strtotime($param['target_time']);
        if($targetTimeStamp < 1000){
            $targetTimeStamp = time();
        }
        $target_time = date('Y-m-d H:i:s' ,$targetTimeStamp);

        if($param['target_time'] && $target_time > $time){
            $arr = array('code'=>600,'msg'=>'开单时间不能大于当前时间','data'=>$param['target_time']);
            return $arr;
        }
        $param['order_fact'] = intval($param['order_fact']);
        $consulation_shop_code = $param['consulation_shop_code'];
        $consulation_shop = $param['consulation_shop'];
        $consulation_shop_sn = $param['consulation_shop_sn'];
        $photo_shop_code = $param['photo_shop_code'];
        $photo_shop_name = $param['photo_shop_name'];
        $bbithdate = date('Ymd',strtotime($param['baby_birthday']));
        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('shop_name');
        $data['setkey'] = session('setkey');
        $data['target_time'] = $param['target_time'] ? date('Y-m-d H:i:s',strtotime($param['target_time'])) : $time;
        $data['create_time'] = $time;
        $data['customer_id'] = (int)$param['customer_id'];
        $data['customer_name'] = $param['customer_name'];
        $data['customer_channel_id'] = (int)$param['customer_channel_id'];
        $data['customer_channel'] = $param['customer_channel'];
        $data['order_fact'] = $param['order_fact'];
        $data['order_amount'] = $param['order_amount'];
        $data['two_pin_fact'] = $param['two_pin_fact'];
        $data['two_pin_amount'] = $param['two_pin_amount'];
        $data['consultation_type'] = $param['consultation_type'];
        $data['order_source'] = $param['order_source'];
        $data['order_note'] = $param['order_note'];
        $data['order_sn'] = $param['order_sn'];
        $data['order_type'] = $param['order_type'];

        // 客户来源
        $cData['customer_cource_id'] = (int)$param['customer_cource_id'];
        $cData['customer_cource'] = $param['customer_cource'];
        // 意向店面
        $cData['consulation_shop_code']= $param['consulation_shop_code'] ? $param['consulation_shop_code'] : '';
        $cData['consulation_shop']= $param['consulation_shop'] ? $param['consulation_shop'] : '';
        // 消费类型
        $cData['consultation_type_id']= (int)$param['consultation_type_id'];
        $cData['consultation_type']   = $param['consultation_type'];

        // $cData['customer_channel_id'] = (int)$param['customer_channel_id'];
        // $cData['customer_channel']    = $param['customer_channel'];

        $reception_id   = $param['reception_id'] ? intval($param['reception_id']) : NULL;
        $reception_name = $param['reception_name'] ? trim($param['reception_name']) : NULL;

        // 根据事业部id查询事业部信息
        $brandclass_id = (int)session('brandclass_id');
        $data['brandclass_id'] = $brandclass_id;
        $data['brandclass'] = session('brandclass');


        // 订单有效标准 线下 （order_rule） 1：实收款；2：占比
        $ordervalid = getPercent($data['order_fact'],$data['order_amount'],$brandclass_id,'order');

        if($ordervalid){
            $cData['is_success'] = 1;
            $cData['order_day']  = $data['target_time'];

            $data['order_valid'] = 2;
            $data['earnest_money'] = 0;
            $data['order_fact'] = $param['order_fact'];
            $data['two_pin_fact'] = $param['two_pin_fact'];
        }else{
            $cData['is_success'] = 3;
            $data['order_valid'] = 1;
            $data['earnest_money'] = 0;
            $data['order_fact'] = $param['order_fact'];
            $data['two_pin_fact'] = $param['two_pin_fact'];
        }
        $customerInfo = db('c_customerinfo')->where('id', $data['customer_id'])->find();
        if($param['sign_id'] != $customerInfo['sign_id']){
            if ($param['sign_id'] == 'NaN' || $param['sign_id'] == 0) {
                $cData['sign_id']  = '';
                $cData['sign_name']= '';
            }else{
                $cData['sign_id'] = $param['sign_id'];
                $cData['sign_name'] = $param['sign_name'];
            }
            
            $cData['sign_time'] = $time;
        }
        if($data['order_type'] == 1){
            // 线上订单进店标准 （onlinecash_id） 1：实收款；2：占比
            if(!$customerInfo['syjd_day']){
                $percent = getPercent($data['order_fact'],$data['order_amount'],$brandclass_id,'into');
                if($percent){
                    $cData['is_intostore'] = 2;
                    $cData['syjd_day']  = $customerInfo['syjd_day'] ? $customerInfo['syjd_day'] : $time;
                }
            }
        }
        // 是否安装erp
        $is_erp = is_install('sx_erp');
        $one_order = db_config('one_customer_more_order');//同一客资允许多次订单,有过成交，就一直成交
        if($one_order == 2){
            if($customerInfo['order_number']){
                return array('code'=>104,'msg'=>'此客资不是有效订单或已设置为不允许同一客资多次订单');
            }
        }
        //查询最后一次进客数据
        /*$isTable = isTableExist('c_customer_intostore');
        if($isTable){
            $into_id = db('c_customer_intostore')->where('cid',$data['customer_id'])->where('yjd_day','like','%'.date('Y-m-d').'%')->order('id desc')->value('id');
            if(empty($into_id)){
                $into_id = db('c_customer_intostore')->where('cid',$data['customer_id'])->order('id desc')->value('id');
            }
            $into = [];
            if($into_id){
                $data['into_id'] = $into_id;//订单表
                $into['consulation_shop_code'] = $cData['consulation_shop_code'];
                $into['consulation_shop_name'] = $cData['consulation_shop'];
                $into['reception_id'] = $reception_id;
                $into['reception_name'] = $reception_name;
                $into['is_success'] = $cData['is_success'];
                $into['update_time'] = $time;
                $into['operate_id'] = session('staff_id');
                $into['operate_name'] = session('staff_name');
            }
        }*/

        if ($is_erp === false) {
            db()->startTrans();
            try {
                $order_sn = $data['order_sn'] ? trim($data['order_sn']) : 'sx_crm'.time().generate_code();
                $data['order_sn'] = $order_sn;
                $oid = db('c_customer_order')->insert($data);
                history_log($data, [], $data['customer_id'], session('staff_id'), session('staff_name'));
                //写入流水表
                $arr = array(
                    'order_sn' => $data['order_sn'],
                    'order_fact' => $param['order_fact'],
                    'two_pin_fact' => $data['two_pin_fact'],
                    'order_type' => $data['order_type'] ? $data['order_type'] : 2,
                    'order_valid' => $data['order_valid'],
                    'pay_time' => date('Y-m-d',time()),
                    'create_time' => date('Y-m-d H:i:s',time())
                );

                $this->insert_order_detail($arr);
                // db('c_order_detail')->insert($arr);
                // 写入客资表
                $cData['order_number'] = $order_sn;

                if($param['order_type'] == 1){
                    // 线上订单进店标准 （onlinecash_id） 1：实收款；2：占比
                    if(!$customerInfo['syjd_day']){
                        $percent = getPercent($data['order_fact'],$data['order_amount'],$brandclass_id,'into');
                        if($percent){
                            $cData['is_intostore'] = 2;
                            $cData['syjd_day']  = $customerInfo['syjd_day'] ? $customerInfo['syjd_day'] : $time;
                        }
                    }
                }else{
                    //非网付订单，成单即算进客
                    $cData['is_intostore']  = 2;
                    $cData['syjd_day'] = $customerInfo['syjd_day'] ? $customerInfo['syjd_day'] : $time;
                }
                $cData['order_type']    = (int)$param['order_type'] ? (int)$param['order_type'] : 2;
                $cData['order_start_time'] = $data['target_time'] ?  $data['target_time'] : $time;
                $cData['totalpay_money']   = $data['order_amount']+$data['two_pin_amount'];
                $cData['fact_money']       = $data['order_fact']+$data['two_pin_fact']+$data['earnest_money'];
                //修改客资为有效
                $info = db('c_customerinfo')->where('id',$data['customer_id'])->find();
                if($info['is_valid'] != 1 || empty($info['yx_day'])){
                    $cData['is_valid'] = 1;
                    $cData['yx_day'] = $time;
                }
                if (!$info['c_star_day']) {
                    $cData['c_star_day'] = $time;
                }
                $cData['c_end_day'] = $time;
                $cData['last_trackday'] = $time;
                $cData['update_time'] = date('Y-m-d H:i:s');

                if($one_order != 2 && $customerInfo['is_success'] == 1){
                    $cData['is_success'] = 1;
                }
                db('c_customerinfo')->where('id', $data['customer_id'])->update($cData);

                if($cData['is_success']){
                    //如果是爆破活动，修改对应的爆破表数据
                    if($info['is_act'] == 2){
                        db('c_swap_customer')->where('customer_number',$info['customer_number'])->update(['is_success'=>$cData['is_success']]);
                    }
                }

                //追踪记录
                $params['customer_id'] = $data['customer_id'];
                $params['customer_name'] = $customerInfo['customer_name'];
                $params['customer_number'] = $customerInfo['customer_number'];
                $params['sales_remark'] = '转订单-'.$data['order_note'];
                $params['sales_day'] = date('Y-m-d H:i:s',time());
                $params['sales_staff'] = session('staff_name');
                $params['sales_staff_id'] = session('staff_id');
                $params['sales_staff_number'] = session('staff_number');
                $params['shop_name'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('CSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$data['customer_id'],null);
                //修改追踪时间
                $time = date('Y-m-d H:i:s',time());
                if(empty($info['c_star_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }
                db('CCustomerinfo')->where('id',$data['customer_id'])->update($arr);
                getSalesTracking($data['customer_id']);
                //修改进客信息
                /*if($into_id){
                    db('c_customer_intostore')->where('id',$into_id)->update($into);
                }*/
                // 发送站内弹窗消息
                $message['send_type']      = 1;
                $message['send_time']      = $param['create_time'];
                $message['send_title']     = '订单提醒';
                $message['send_msg'] = '您有一笔客资已订单，ID：'.$customerInfo['id'].'，姓名：'.$customerInfo['customer_name'];
                if($customerInfo['customer_tel']){
                    $message['send_msg'] .= '，手机：'.$customerInfo['customer_tel'];
                }elseif($customerInfo['mate_tel']){
                    $message['send_msg'] .= '，手机：'.$customerInfo['mate_tel'];
                }
                $message['send_msg'] .='，请确认。';
                $message['receive_id']     = $customerInfo['sales_staff_id'];
                $message['receive_name']   = $customerInfo['sales_staff'];
                $message['receive_status'] = 1;
                $message['receive_time']   = date('Y-m-d H:i:s');
                $message['operation_type'] = 2;
                $message['operation']      = '';
                $message['customer_id']    = $customerInfo['id'];

                $timeOut = db_config('fp_timeout_'.session('shop_code'));
                $message['time_out']       = $timeOut ? $timeOut : 60;
                sendSystemMessage($message);
                db()->commit();
                $arr = array('code'=>200,'msg'=>'转订单成功','order_sn'=>$order_sn);
            } catch (Exception $e) {
                db()->rollback();
                $arr = array('code'=>100,'msg'=>'转订单失败','data'=>$e->getMessage());
            }
            return $arr;
        }

        $dataErp = [];
        if(intval($param['order_fact']) > 0){
            if(trim($param['paytype']) == "" || trim($param['collectitem_name']) == "" || trim($param['collectitem_belongs']) == ""){
                $arr = array('code'=>601,'msg'=>'有收款时，必须选择收款方式和款项','data'=>'');
                return $arr;
            }
            //付款方式
            $dataErp['paytype'] = intval($param['paytype']);
            //实收
            $dataErp['payment_money'] = intval($param['order_fact']);
            //收款款项
            $dataErp['fundname'] = $param['collectitem_name'];
            //收款款项所属
            $dataErp['suoshu'] = $param['collectitem_belongs'];
            //付款分类
            $dataErp['payclass'] = 0;
            //收款人
            $dataErp['cashierman'] = session('staff_name');
            //收款日期 yyyymmdd
            $dataErp['paymentdate'] = $pay_time ? date('Ymd',strtotime($pay_time)) : date('Ymd');
        }
        // 地址
        $dataErp['address']          = $customerInfo['customer_address'] ? $customerInfo['customer_address'] : '';
        // 客户来源
        $dataErp['cssname']          = $cData['customer_cource'] ? $cData['customer_cource'] : '';
        // 来源渠道
        $dataErp['customer_channel'] = $customerInfo['customer_channel'] ? $customerInfo['customer_channel'] : '';
        // 客户分区
        $dataErp['area']             = $customerInfo['customer_area'] ? $customerInfo['customer_area'] : '';
        // 介绍人编号
        $dataErp['introducerid']     = $customerInfo['introducer_number'] ? $customerInfo['introducer_number'] : '';
        // 介绍人姓名
        $dataErp['introducer_name']  = $customerInfo['introducer_name'] ? $customerInfo['introducer_name'] : '';
        // 结婚日期
        $dataErp['weddingdate']      = $customerInfo['marry_day'] ? $customerInfo['marry_day'] : '';
        // 订单备注  data里有
        $dataErp['customernote']     = $data['order_note'] ? strip_tags($data['order_note']) : '';
        // 宝宝姓名 目前客资表中没有
        $dataErp['bbname']           = $customerInfo['baby_name'] ? $customerInfo['baby_name'] : '';
        // 宝宝昵称 目前客资表中没有
        $dataErp['bnickname']        = $customerInfo['bnickname'] ? $customerInfo['bnickname'] : '';
        // 宝宝生日（阳历）
        $dataErp['bbithdate']        = $bbithdate ? $bbithdate : '';
        // 宝宝生日（阳历） 目前客资表中没有
        $dataErp['liunardate']       = $customerInfo['liunardate'] ? $customerInfo['liunardate'] : '';
        // 宝宝性别 目前客资表中没有
        $dataErp['bbsex']            = $customerInfo['baby_sex'] ? $customerInfo['baby_sex'] : '';
        // 宝宝生肖 目前客资表中没有
        $dataErp['bzodiac']          = $customerInfo['bzodiac'] ? $customerInfo['bzodiac'] : '';
        // 联系邮箱 目前客资表中没有
        $dataErp['email']            = $customerInfo['email'] ? $customerInfo['email'] : '';
        // 客户所属店面
        // $dataErp['shop_code']        = '';
        $dataErp['shop_code']        = $consulation_shop_code; // 开单店面
        $dataErp['shop_sn']          = $consulation_shop_sn; // 开单店面
        $dataErp['Photoshopcode']    = $photo_shop_code; // 拍照店面
        $dataErp['Photoshopname']    = $photo_shop_name; // 拍照店面
        // 客户所属店面
        $dataErp['shop_name']        = $consulation_shop;
        // 消费类型
        $dataErp['Consumption_type'] = $cData['consultation_type'];
        // 套餐名称 目前客资表中没有
        $dataErp['Package_name']     = $customerInfo['Package_name'] ? $customerInfo['Package_name'] : '';
        // 订单日期
        // $dataErp['Targetdate']       = $time;
        $dataErp['Targetdate']       = $target_time ? date('Ymd',strtotime($target_time)) : date('Ymd', strtotime($time));
        // 销售门市
        $dataErp['Storeconsuitant1'] = $reception_name ? $reception_name : '';
        $rescep = getStaffInfoById($reception_id);
        $dataErp['Storeconsuitant1_number'] = $rescep['id'] ? $rescep['id'] :  ($rescep['staff_id'] ? $rescep['staff_id'] : '');
        // $dataErp['Storeconsuitant1'] = $receptionInfo['staffnumber'] ? $receptionInfo['staffnumber'] : '';
        // 网销门市 目前没有用 sales_satff
        $dataErp['Storeconsuitant2'] = $customerInfo['sales_staff'] ? $customerInfo['sales_staff'] : '';
        $dataErp['Storeconsuitant2_number'] = $customerInfo['sales_staff_number'] ? $customerInfo['sales_staff_number'] : '';
        // $dataErp['Storeconsuitant2'] = '';
        // 接单点
        $dataErp['Acceptor_address'] = $customerInfo['customer_orderaddress'] ? $customerInfo['customer_orderaddress'] : '';
        // 预产日期
        $dataErp['Yc_day']           = $customerInfo['ready_baby_day'] ? $customerInfo['ready_baby_day'] : '';
        // 宝宝出生地
        $dataErp['Bb_hospital']      = $customerInfo['baby_address'] ? $customerInfo['baby_address'] : '';
        // 客资系统来源
        $dataErp['Customer_from']    = 'CRM';
        // 客资编号
        $dataErp['customer_from_index']= $customerInfo['customer_number'];
        // 事业部id
        $dataErp['Brandid']          = session('brandclass_id');
        // 操作店
        $dataErp['Opershop']         = session('shop_name');

        if ($customerInfo['customer_sex'] == '女') {
            $dataErp['wname']      = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
            $dataErp['wphone']     = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
            $dataErp['wwechat']    = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
            $dataErp['wqq']        = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
            $dataErp['wbirthdate'] = $customerInfo['customer_birthday'] ? $customerInfo['customer_birthday'] : '';
            $dataErp['wIdtype']    = $customerInfo['customer_idtype'] ? $customerInfo['customer_idtype'] : '';
            $dataErp['wid']        = $customerInfo['customer_idnumber'] ? $customerInfo['customer_idnumber'] : '';
            $dataErp['mname']      = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
            $dataErp['mphone']     = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
            $dataErp['mwechat']    = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
            $dataErp['mqq']        = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';
            $dataErp['mbirthdate'] = $customerInfo['mate_birthday'] ? $customerInfo['mate_birthday'] : '';
            $dataErp['mIdtype']    = $customerInfo['mate_idtype'] ? $customerInfo['mate_idtype'] : '';
            $dataErp['mid']        = $customerInfo['mate_idnumber'] ? $customerInfo['mate_idnumber'] : '';
        }else if ($customerInfo['customer_sex'] == '男') {
            $dataErp['mname']      = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
            $dataErp['mphone']     = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
            $dataErp['mwechat']    = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
            $dataErp['mqq']        = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
            $dataErp['mbirthdate'] = $customerInfo['customer_birthday'] ? $customerInfo['customer_birthday'] : '';
            $dataErp['mIdtype']    = $customerInfo['customer_idtype'] ? $customerInfo['customer_idtype'] : '';
            $dataErp['mid']        = $customerInfo['customer_idnumber'] ? $customerInfo['customer_idnumber'] : '';
            $dataErp['wname']      = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
            $dataErp['wphone']     = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
            $dataErp['wwechat']    = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
            $dataErp['wqq']        = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';
            $dataErp['wbirthdate'] = $customerInfo['mate_birthday'] ? $customerInfo['mate_birthday'] : '';
            $dataErp['wIdtype']    = $customerInfo['mate_idtype'] ? $customerInfo['mate_idtype'] : '';
            $dataErp['wid']        = $customerInfo['mate_idnumber'] ? $customerInfo['mate_idnumber'] : '';
        }else{
            $dataErp['wname']      = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
            $dataErp['wphone']     = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
            $dataErp['wwechat']    = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
            $dataErp['wqq']        = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
            $dataErp['wbirthdate'] = $customerInfo['customer_birthday'] ? $customerInfo['customer_birthday'] : '';
            $dataErp['wIdtype']    = $customerInfo['customer_idtype'] ? $customerInfo['customer_idtype'] : '';
            $dataErp['wid']        = $customerInfo['customer_idnumber'] ? $customerInfo['customer_idnumber'] : '';
            $dataErp['mname']      = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
            $dataErp['mphone']     = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
            $dataErp['mwechat']    = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
            $dataErp['mqq']        = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';
            $dataErp['mbirthdate'] = $customerInfo['mate_birthday'] ? $customerInfo['mate_birthday'] : '';
            $dataErp['mIdtype']    = $customerInfo['mate_idtype'] ? $customerInfo['mate_idtype'] : '';
            $dataErp['mid']        = $customerInfo['mate_idnumber'] ? $customerInfo['mate_idnumber'] : '';
        }
        $dataErp = json_encode($dataErp);
        // ----------  ERP接口数据  结束  -------- //
        // $response = requestERP($url, $dataErp);
        // print_r($response['Data ']);
        // echo '1111111';
        // print_r($response['Data']);
        // exit;
        // 开启事务
        $time = date('Y-m-d H:i:s',time());
        db()->startTrans();
        try {
            // 调 erp 接口  改成放到所有操作数据库的最后进行。
            $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);
            $res = $erpInterface->addNewOrder($dataErp);

            if ($res === false) {
                db()->rollback();
                $arr = array('code'=>300,'msg'=>'转订单失败,ERP请求有误','error'=>$erpInterface->error);
            }else{
                $order_sn = $res;
                $data['order_sn'] = $order_sn;
                $data['photo_shop_code'] = $photo_shop_code;
                $data['photo_shop_name'] = $photo_shop_name;
                $oid = db('c_customer_order')->insert($data);

                history_log($data, [], $data['customer_id'], session('staff_id'), session('staff_name'));
                //写入流水表
                $arr = array(
                    'order_sn' => $data['order_sn'],
                    'order_fact' => $param['order_fact'],
                    'two_pin_fact' => $data['two_pin_fact'],
                    'order_type' => $data['order_type'] ? $data['order_type'] : 1,
                    'order_valid' => $data['order_valid'],
                    'pay_time' => date('Y-m-d',time()),
                    'create_time' => date('Y-m-d H:i:s',time())
                );
                $this->insert_order_detail($arr);
                // db('c_order_detail')->insert($arr);
                // 写入客资表
                $cData['order_number'] = $order_sn;
                if($param['order_type'] == 1){
                    //网付订单，计算进店规则
                    if(!$customerInfo['syjd_day']){
                        $percent = getPercent($data['order_fact'],$data['order_amount'],$brandclass_id,'into');
                        if($percent){
                            $cData['is_intostore'] = 2;
                            $cData['syjd_day']  = $customerInfo['syjd_day'] ? $customerInfo['syjd_day'] : $time;
                        }
                    }
                }
                //$cData['order_day'] = $time;//前面已算好，有效单时才会更新这个时间
                $cData['order_type']    = $data['order_type'];
                $cData['order_start_time'] = $data['target_time'];
                $cData['totalpay_money']   = $data['order_amount']+$data['two_pin_amount'];
                $cData['fact_money']       = $data['order_fact']+$data['two_pin_fact']+$data['earnest_money'];
                //修改客资为有效
                if($customerInfo['is_valid'] != 1 || empty($customerInfo['yx_day'])){
                    $cData['is_valid'] = 1;
                    $cData['yx_day'] = $time;
                }
                
                if (!$customerInfo['c_star_day']) {
                    $cData['c_star_day'] = $time;
                    $cData['c_end_day'] = $time;
                }
                $cData['last_trackday'] = $time;
                $cData['update_time'] = $time;
                db('c_customerinfo')->where('id', $data['customer_id'])->update($cData);

                // $info = db('CCustomerinfo')->where('id',$data['customer_id'])->find();
                if($cData['is_success']){
                    //如果是爆破活动，修改对应的爆破表数据
                    if($customerInfo['is_act'] == 2){
                        db('c_swap_customer')->where('customer_number',$customerInfo['customer_number'])->update(['is_success'=>$cData['is_success']]);
                    }
                }
                
                //追踪记录
                $params['customer_id'] = $data['customer_id'];
                $params['customer_name'] = $customerInfo['customer_name'];
                $params['customer_number'] = $customerInfo['customer_number'];
                $params['sales_remark'] = '转订单';
                $params['sales_day'] = date('Y-m-d H:i:s',time());
                $params['sales_staff'] = session('staff_name');
                $params['sales_staff_id'] = session('staff_id');
                $params['sales_staff_number'] = session('staff_number');
                $params['shop_name'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('CSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$data['customer_id'],null);
                // //修改追踪时间
                // 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['customer_id'])->update($arr);
                getSalesTracking($data['customer_id']);
                //修改进客信息
                /*if($into_id){
                    db('c_customer_intostore')->where('id',$into_id)->update($into);
                }*/
                // 发送站内弹窗消息
                $message['send_type']      = 1;
                $message['send_time']      = $param['create_time'];
                $message['send_title']     = '订单提醒';
                $message['send_msg'] = '您有一笔客资已订单，ID：'.$customerInfo['id'].'，姓名：'.$customerInfo['customer_name'];
                if($customerInfo['customer_tel']){
                    $message['send_msg'] .= '，手机：'.$customerInfo['customer_tel'];
                }elseif($customerInfo['mate_tel']){
                    $message['send_msg'] .= '，手机：'.$customerInfo['mate_tel'];
                }
                $message['send_msg'] .='，请确认。';
                $message['receive_id']     = $customerInfo['sales_staff_id'];
                $message['receive_name']   = $customerInfo['sales_staff'];
                $message['receive_status'] = 1;
                $message['receive_time']   = date('Y-m-d H:i:s');
                $message['operation_type'] = 2;
                $message['operation']      = '';
                $message['customer_id']    = $customerInfo['id'];

                $timeOut = db_config('fp_timeout_'.session('shop_code'));
                $message['time_out']       = $timeOut ? $timeOut : 60;
                sendSystemMessage($message);
                db()->commit();
                $arr = array('code'=>200,'msg'=>'转订单成功');
            }
        } catch (\Exception $e) {
            // $error = db()->getLastSql();
            // $this->errid = 1;
            // $this->errmsg= $error;
            db()->rollback();
            $arr = array('code'=>100,'msg'=>'网付订单失败','data'=>$e->getMessage(),'lastSql'=>db()->getLastSql());
            $errorData['action']      = '网付订单失败';
            $errorData['error_reason']= json_encode($arr);
            $errorData['create_time'] = date('Y-m-d H:i:s');
            db('l_error_log')->insert($errorData);
        }
        return $arr;
    }

    //转订单 new
    public function zhuanOrderNew($param){
        $time = date('Y-m-d H:i:s',time());
        $pay_time = trim($param['pay_time']);//订单日期
        $targetTimeStamp = strtotime($param['target_time']);//付款日期
        if($targetTimeStamp < 1000){
            $targetTimeStamp = time();
        }
        $target_time = date('Y-m-d H:i:s' ,$targetTimeStamp);

        if($param['target_time'] && $target_time > $time){
            $arr = array('code'=>600,'msg'=>'开单时间不能大于当前时间','data'=>$param['target_time']);
            return $arr;
        }

        $param['order_fact'] = intval($param['order_fact']);
        $consulation_shop_code = $param['consulation_shop_code'];
        $consulation_shop = $param['consulation_shop'];
        $consulation_shop_sn = $param['consulation_shop_sn'];
        $photo_shop_code = $param['photo_shop_code'];
        $photo_shop_name = $param['photo_shop_name'];
        $bbithdate = date('Ymd',strtotime($param['baby_birthday']));

        $data['customer_id'] = (int)$param['customer_id'];

        $customerInfo = db('c_customerinfo')->where('id', $data['customer_id'])->find();

        $data['shop_code'] = session('shop_code');
        $data['shop_name'] = session('shop_name');
        $data['setkey'] = session('setkey');
        $data['target_time'] = $param['target_time'] ? date('Y-m-d H:i:s',strtotime($param['target_time'])) : $time;
        $data['create_time'] = $time;
        $data['customer_name'] = $param['customer_name'];
        $data['customer_channel_id'] = (int)$param['customer_channel_id']?:$customerInfo['customer_channel_id'];
        $data['customer_channel'] = $param['customer_channel']?:$customerInfo['customer_channel'];
        $data['order_fact'] = $param['order_fact'];
        $data['order_amount'] = $param['order_amount']?:$param['package_price'];
        $data['two_pin_fact'] = $param['two_pin_fact'];
        $data['two_pin_amount'] = $param['two_pin_amount'];
        $data['consultation_type'] = $param['consultation_type'];
        $data['order_source'] = $param['order_source'];
        $data['order_note'] = $param['order_note'];
        $data['order_sn'] = $param['order_sn'];
        $data['order_type'] = $param['order_type'];
        $data['customer_area'] = $param['customer_area'] ?: $customerInfo['customer_area'];

        // 客户来源
        $cData['customer_cource_id'] = (int)$param['customer_cource_id'];
        $cData['customer_cource'] = $param['customer_cource'];
        // 意向店面
        $cData['consulation_shop_code']= $param['consulation_shop_code'] ? $param['consulation_shop_code'] : '';
        $cData['consulation_shop']= $param['consulation_shop'] ? $param['consulation_shop'] : '';
        // 消费类型
        $cData['consultation_type_id']= (int)$param['consultation_type_id'];
        $cData['consultation_type']   = $param['consultation_type'];

        //客户姓名
        if ($cData['customer_name'] != $param['customer_name']) {
            $cData['customer_name'] = $param['customer_name'];
        }
        //客户电话
        if ($cData['customer_tel'] != $param['customer_tel']) {
            $repeat = $this->isRepeat(session('brandclass'),$param['customer_tel'],0,0,0,$param['customer_id'],$param['consultation_type_id']);
            if($repeat['code'] == 201){
                db()->rollback();
                return array('code'=>102,'msg'=>'手机号重复,不可更改','data'=>'');
            }
        }

        //客户地址
        $cData['customer_address'] = $param['customer_address'];

        // $cData['customer_channel_id'] = (int)$param['customer_channel_id'];
        // $cData['customer_channel']    = $param['customer_channel'];

        $reception_id   = $param['reception_id'] ? intval($param['reception_id']) : NULL;
        $reception_name = $param['reception_name'] ? trim($param['reception_name']) : NULL;

        // $data['sales_staff'] = $reception_name;
        // $data['sales_staff_id'] = $reception_id;

        // 根据事业部id查询事业部信息
        $brandclass_id = (int)session('brandclass_id');
        $data['brandclass_id'] = $brandclass_id;
        $data['brandclass'] = session('brandclass');


        // 订单有效标准 线下 （order_rule） 1：实收款；2：占比
        $ordervalid = getPercent($data['order_fact'],$data['order_amount'],$brandclass_id,'order');

        if($ordervalid){
            $cData['is_success'] = 1;
            $cData['order_day']  = $data['target_time'];

            $data['order_valid'] = 2;
            $data['earnest_money'] = 0;
            $data['order_fact'] = $param['order_fact'];
            $data['two_pin_fact'] = $param['two_pin_fact'];
        }else{
            $cData['is_success'] = 3;
            $data['order_valid'] = 1;
            $data['earnest_money'] = 0;
            $data['order_fact'] = $param['order_fact'];
            $data['two_pin_fact'] = $param['two_pin_fact'];
        }
        
        if($param['sign_id'] != $customerInfo['sign_id']){
            if ($param['sign_id'] == 'NaN' || $param['sign_id'] == 0) {
                $cData['sign_id']  = '';
                $cData['sign_name']= '';
            }else{
                $cData['sign_id'] = $param['sign_id'];
                $cData['sign_name'] = $param['sign_name'];
            }
            
            $cData['sign_time'] = $time;
        }
        if($data['order_type'] == 1){
            // 线上订单进店标准 （onlinecash_id） 1：实收款；2：占比
            if(!$customerInfo['syjd_day']){
                $percent = getPercent($data['order_fact'],$data['order_amount'],$brandclass_id,'into');
                if($percent){
                    $cData['is_intostore'] = 2;
                    $cData['syjd_day']  = $customerInfo['syjd_day'] ? $customerInfo['syjd_day'] : $time;
                }
            }
        }
        // 是否安装erp
        $is_erp = is_install('sx_erp');
        $one_order = db_config('one_customer_more_order');//同一客资允许多次订单,有过成交，就一直成交
        if($one_order == 2){
            if($customerInfo['order_number']){
                return array('code'=>104,'msg'=>'此客资不是有效订单或已设置为不允许同一客资多次订单');
            }
        }

        $dataErp = [];
        if(intval($param['order_fact']) > 0){
            if(trim($param['paytype']) == "" || trim($param['collectitem_name']) == "" || trim($param['collectitem_belongs']) == ""){
                $arr = array('code'=>601,'msg'=>'有收款时，必须选择收款方式和款项','data'=>'');
                return $arr;
            }
            //付款方式
            $dataErp['paytype'] = intval($param['paytype_id']);
            //实收
            $dataErp['payment_money'] = intval($param['order_fact']);
            //收款款项
            $dataErp['fundname'] = $param['collectitem_name'];
            //收款款项所属
            $dataErp['suoshu'] = $param['collectitem_belongs'];
            //付款分类
            $dataErp['payclass'] = 0;
            //收款人
            $dataErp['cashierman'] = session('staff_name');
            //收款日期 yyyymmdd
            $dataErp['paymentdate'] = $pay_time ? date('Ymd',strtotime($pay_time)) : date('Ymd');
        }
        // 地址
        $dataErp['address']          = $cData['customer_address'] ? : $customerInfo['customer_address'];
        // 客户来源
        $dataErp['cssname']          = $cData['customer_cource'] ? $cData['customer_cource'] : '';
        // 来源渠道
        $dataErp['customer_channel'] = $customerInfo['customer_channel'] ? $customerInfo['customer_channel'] : '';
        // 客户分区
        $dataErp['area']             = $param['customer_area'] ?: $customerInfo['customer_area'];
        // 介绍人编号
        $dataErp['introducerid']     = $customerInfo['introducer_number'] ? $customerInfo['introducer_number'] : '';
        // 介绍人姓名
        $dataErp['introducer_name']  = $customerInfo['introducer_name'] ? $customerInfo['introducer_name'] : '';
        // 结婚日期
        $dataErp['weddingdate']      = $customerInfo['marry_day'] ? $customerInfo['marry_day'] : '';
        // 订单备注  data里有
        $dataErp['customernote']     = $data['order_note'] ? strip_tags($data['order_note']) : '';
        // 宝宝姓名 目前客资表中没有
        $dataErp['bbname']           = $customerInfo['baby_name'] ? $customerInfo['baby_name'] : '';
        // 宝宝昵称 目前客资表中没有
        $dataErp['bnickname']        = $customerInfo['bnickname'] ? $customerInfo['bnickname'] : '';
        // 宝宝生日（阳历）
        $dataErp['bbithdate']        = $bbithdate ? $bbithdate : '';
        // 宝宝生日（阳历） 目前客资表中没有
        $dataErp['liunardate']       = $customerInfo['liunardate'] ? $customerInfo['liunardate'] : '';
        // 宝宝性别 目前客资表中没有
        $dataErp['bbsex']            = $customerInfo['baby_sex'] ? $customerInfo['baby_sex'] : '';
        // 宝宝生肖 目前客资表中没有
        $dataErp['bzodiac']          = $customerInfo['bzodiac'] ? $customerInfo['bzodiac'] : '';
        // 联系邮箱 目前客资表中没有
        $dataErp['email']            = $customerInfo['email'] ? $customerInfo['email'] : '';
        // 客户所属店面
        // $dataErp['shop_code']        = '';
        $dataErp['shop_code']        = $consulation_shop_code; // 开单店面
        $dataErp['shop_sn']          = $consulation_shop_sn; // 开单店面
        $dataErp['Photoshopcode']    = $photo_shop_code; // 拍照店面
        $dataErp['Photoshopname']    = $photo_shop_name; // 拍照店面
        // 客户所属店面
        $dataErp['shop_name']        = $consulation_shop;
        // 消费类型
        $dataErp['Consumption_type'] = $cData['consultation_type'];
        // 套餐名称 目前客资表中没有
        $dataErp['Package_name']     = $customerInfo['Package_name'] ? $customerInfo['Package_name'] : '';
        // 订单日期
        // $dataErp['Targetdate']       = $time;
        $dataErp['Targetdate']       = $target_time ? date('Ymd',strtotime($target_time)) : date('Ymd', strtotime($time));
        // 销售门市
        $dataErp['Storeconsuitant1'] = $reception_name ? $reception_name : '';
        $rescep = getStaffInfoById($reception_id);
        $dataErp['Storeconsuitant1_number'] = $rescep['id'] ? $rescep['id'] :  ($rescep['staff_id'] ? $rescep['staff_id'] : '');
        // $dataErp['Storeconsuitant1'] = $receptionInfo['staffnumber'] ? $receptionInfo['staffnumber'] : '';
        // 网销门市 目前没有用 sales_satff
        $dataErp['Storeconsuitant2'] = $customerInfo['sales_staff'] ? $customerInfo['sales_staff'] : '';
        $dataErp['Storeconsuitant2_number'] = $customerInfo['sales_staff_number'] ? $customerInfo['sales_staff_number'] : '';
        // $dataErp['Storeconsuitant2'] = '';
        // 接单点
        $dataErp['Acceptor_address'] = $customerInfo['customer_orderaddress'] ? $customerInfo['customer_orderaddress'] : '';
        // 预产日期
        $dataErp['Yc_day']           = $customerInfo['ready_baby_day'] ? $customerInfo['ready_baby_day'] : '';
        // 宝宝出生地
        $dataErp['Bb_hospital']      = $customerInfo['baby_address'] ? $customerInfo['baby_address'] : '';
        // 客资系统来源
        $dataErp['Customer_from']    = 'CRM';
        // 客资编号
        $dataErp['customer_from_index']= $customerInfo['customer_number'];
        // 事业部id
        $dataErp['Brandid']          = session('brandclass_id');
        // 操作店
        $dataErp['Opershop']         = session('shop_name');

        if ($customerInfo['customer_sex'] == '男') {
            $dataErp['mname']      = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
            $dataErp['mphone']     = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
            $dataErp['mwechat']    = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
            $dataErp['mqq']        = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
            $dataErp['mbirthdate'] = $customerInfo['customer_birthday'] ? $customerInfo['customer_birthday'] : '';
            $dataErp['mIdtype']    = $customerInfo['customer_idtype'] ? $customerInfo['customer_idtype'] : '';
            $dataErp['mid']        = $customerInfo['customer_idnumber'] ? $customerInfo['customer_idnumber'] : '';
            $dataErp['wname']      = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
            $dataErp['wphone']     = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
            $dataErp['wwechat']    = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
            $dataErp['wqq']        = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';
            $dataErp['wbirthdate'] = $customerInfo['mate_birthday'] ? $customerInfo['mate_birthday'] : '';
            $dataErp['wIdtype']    = $customerInfo['mate_idtype'] ? $customerInfo['mate_idtype'] : '';
            $dataErp['wid']        = $customerInfo['mate_idnumber'] ? $customerInfo['mate_idnumber'] : '';
        }else{ //女
            $dataErp['wname']      = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
            $dataErp['wphone']     = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
            $dataErp['wwechat']    = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
            $dataErp['wqq']        = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
            $dataErp['wbirthdate'] = $customerInfo['customer_birthday'] ? $customerInfo['customer_birthday'] : '';
            $dataErp['wIdtype']    = $customerInfo['customer_idtype'] ? $customerInfo['customer_idtype'] : '';
            $dataErp['wid']        = $customerInfo['customer_idnumber'] ? $customerInfo['customer_idnumber'] : '';
            $dataErp['mname']      = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
            $dataErp['mphone']     = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
            $dataErp['mwechat']    = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
            $dataErp['mqq']        = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';
            $dataErp['mbirthdate'] = $customerInfo['mate_birthday'] ? $customerInfo['mate_birthday'] : '';
            $dataErp['mIdtype']    = $customerInfo['mate_idtype'] ? $customerInfo['mate_idtype'] : '';
            $dataErp['mid']        = $customerInfo['mate_idnumber'] ? $customerInfo['mate_idnumber'] : '';
        }

        //appwxerp 转单
        if ($param['entrance_type'] == 'appwxerp') {
            $dataErp['orderId'] = $data['order_sn'];
            $dataErp['ordernote'] = $data['order_note'];
            $dataErp['cssname_id'] = $cData['customer_cource_id'];
            $dataErp['area_id'] = $param['customer_area_id'];
            $dataErp['consumption_type'] = $cData['consultation_type'];
            $dataErp['consumption_type_id'] = $cData['consultation_type_id'];
            $dataErp['package_name'] = $param['package_name'];
            $dataErp['targetdate'] = $dataErp['Targetdate'];
            $dataErp['storeconsuitant1'] = $dataErp['Storeconsuitant1'];
            $dataErp['storeconsuitant1_id'] = $dataErp['Storeconsuitant1_number'];
            $dataErp['customer_from']    = 'CRM';
            $dataErp['productid'] = $param['api_code'];
            $dataErp['is_zhuandan'] = $param['is_zhuandan'];

            $dataErp['staffid'] = session('staff_id');
            $dataErp['staffname'] = session('staff_name');
            $dataErp['staffnumber'] = session('staff_number');

            if ($param['is_zhuandan'] == 1) {  //进客转单
                $dataErp['jinkeid'] = $param['jinkeid'];

                $data['order_type'] = 2;
                $data['into_id'] = $param['jinkeid'];

                if(empty($param['jinkeid'])){
                    return array('code'=>105,'msg'=>'未获取到进店ID');
                }
                $into = db('c_customer_intostore')->where('id',$param['jinkeid'])->where('cid', $data['customer_id'])->where('status',1)->find();
                if(empty($into)){
                    return array('code'=>106,'msg'=>'未通过进店ID获取到进客数据');
                }
                $intostore = [
                    'cid'=>$data['customer_id'],
                    'syjd_day'=> $into['syjd_day'] ? $into['syjd_day'] : $target_time,
                    'consulation_shop_code'=>$param['consulation_shop_code'] ? $param['consulation_shop_code'] : ($customerInfo['consulation_shop_code'] ? $customerInfo['consulation_shop_code'] : NULL),
                    'consulation_shop_name'=>$param['consulation_shop_name'] ? $param['consulation_shop_name'] :($customerInfo['consulation_shop']?$customerInfo['consulation_shop']:NULL),
                    'reception_id'=>$param['reception_id'] ? $param['reception_id'] : ($customerInfo['reception_id']?$customerInfo['reception_id']:NULL),
                    'reception_name'=>$param['reception_name'] ? $param['reception_name'] : ($customerInfo['reception_name']?$customerInfo['reception_name']:NULL),
                    'operate_id'=>session('staff_id'),
                    'operate_name'=>session('staff_name'),
                    'is_intostore'=>2,
                    'sys_loss'=>1,
                    'loss_reason'=>NULL,
                    'loss_time'=>NULL,
                    'is_success'=>3,
                    'update_time'=>$date,
                ];
            }
        }

        $dataErp = json_encode($dataErp);
        // ----------  ERP接口数据  结束  -------- //
        // $response = requestERP($url, $dataErp);
        // print_r($response['Data ']);
        // echo '1111111';
        // print_r($response['Data']);
        // exit;
        // 开启事务
        $time = date('Y-m-d H:i:s',time());
        
        try {
            // 调 erp 接口  改成放到所有操作数据库的最后进行。
            $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>session('shop_type')]);
            if ($param['entrance_type'] == 'appwxerp') {
                $res = $erpInterface->addNewOrderAppWx($dataErp);
            }else{
                $res = $erpInterface->addNewOrder($dataErp);
            }

            if ($res === false) {
                db()->rollback();
                $arr = array('code'=>300,'msg'=>'转订单失败,ERP请求有误','error'=>$erpInterface->error);
            }else{
                if ($param['entrance_type'] != 'appwxerp' || $param['is_zhuandan'] != 1){
                    db()->startTrans();
                    $order_sn = $res;
                    $data['order_sn'] = $order_sn;
                    $data['photo_shop_code'] = $photo_shop_code;
                    $data['photo_shop_name'] = $photo_shop_name;
                    $oid = db('c_customer_order')->insert($data);

                    history_log($data, [], $data['customer_id'], session('staff_id'), session('staff_name'));
                    //写入流水表
                    $arr = array(
                        'order_sn' => $data['order_sn'],
                        'order_fact' => $param['order_fact'],
                        'two_pin_fact' => $data['two_pin_fact'],
                        'order_type' => $data['order_type'] ? $data['order_type'] : 1,
                        'order_valid' => $data['order_valid'],
                        'pay_time' => date('Y-m-d',time()),
                        'create_time' => date('Y-m-d H:i:s',time())
                    );
                    $this->insert_order_detail($arr);
                    // db('c_order_detail')->insert($arr);

                    if ($param['entrance_type'] == 'appwxerp' && $param['is_zhuandan'] == 1) {
                        db('c_customer_intostore')->where('id',$param['jinkeid'])->update($intostore);
                    }

                    // 写入客资表
                    $cData['order_number'] = $order_sn;
                    if($param['order_type'] == 1){
                        //网付订单，计算进店规则
                        if(!$customerInfo['syjd_day']){
                            $percent = getPercent($data['order_fact'],$data['order_amount'],$brandclass_id,'into');
                            if($percent){
                                $cData['is_intostore'] = 2;
                                $cData['syjd_day']  = $customerInfo['syjd_day'] ? $customerInfo['syjd_day'] : $time;
                            }
                        }
                    }
                    //$cData['order_day'] = $time;//前面已算好，有效单时才会更新这个时间
                    $cData['order_type']    = $data['order_type'];
                    $cData['order_start_time'] = $data['target_time'];
                    $cData['totalpay_money']   = $data['order_amount']+$data['two_pin_amount'];
                    $cData['fact_money']       = $data['order_fact']+$data['two_pin_fact']+$data['earnest_money'];
                    //修改客资为有效
                    if($customerInfo['is_valid'] != 1 || empty($customerInfo['yx_day'])){
                        $cData['is_valid'] = 1;
                        $cData['yx_day'] = $time;
                    }
                    
                    if (!$customerInfo['c_star_day']) {
                        $cData['c_star_day'] = $time;
                        $cData['c_end_day'] = $time;
                    }
                    $cData['last_trackday'] = $time;
                    $cData['update_time'] = $time;
                    db('c_customerinfo')->where('id', $data['customer_id'])->update($cData);

                    // $info = db('CCustomerinfo')->where('id',$data['customer_id'])->find();
                    if($cData['is_success']){
                        //如果是爆破活动，修改对应的爆破表数据
                        if($customerInfo['is_act'] == 2){
                            db('c_swap_customer')->where('customer_number',$customerInfo['customer_number'])->update(['is_success'=>$cData['is_success']]);
                        }
                    }
                    
                    //追踪记录
                    $params['customer_id'] = $data['customer_id'];
                    $params['customer_name'] = $customerInfo['customer_name'];
                    $params['customer_number'] = $customerInfo['customer_number'];
                    $params['sales_remark'] = '转订单';
                    $params['sales_day'] = date('Y-m-d H:i:s',time());
                    $params['sales_staff'] = session('staff_name');
                    $params['sales_staff_id'] = session('staff_id');
                    $params['sales_staff_number'] = session('staff_number');
                    $params['shop_name'] = session('shop_name');
                    $params['shop_code'] = session('shop_code');
                    db('CSalestrackinginfo')->insert($params);
                    cache('getCustomerTrackInfos'.$data['customer_id'],null);
                    getSalesTracking($data['customer_id']);

                    // 发送站内弹窗消息
                    $message['send_type']      = 1;
                    $message['send_time']      = $param['create_time'];
                    $message['send_title']     = '订单提醒';
                    $message['send_msg'] = '您有一笔客资已订单，ID：'.$customerInfo['id'].'，姓名：'.$customerInfo['customer_name'];
                    if($customerInfo['customer_tel']){
                        $message['send_msg'] .= '，手机：'.$customerInfo['customer_tel'];
                    }elseif($customerInfo['mate_tel']){
                        $message['send_msg'] .= '，手机：'.$customerInfo['mate_tel'];
                    }
                    $message['send_msg'] .='，请确认。';
                    $message['receive_id']     = $customerInfo['sales_staff_id'];
                    $message['receive_name']   = $customerInfo['sales_staff'];
                    $message['receive_status'] = 1;
                    $message['receive_time']   = date('Y-m-d H:i:s');
                    $message['operation_type'] = 2;
                    $message['operation']      = '';
                    $message['customer_id']    = $customerInfo['id'];

                    $timeOut = db_config('fp_timeout_'.session('shop_code'));
                    $message['time_out']       = $timeOut ? $timeOut : 60;
                    sendSystemMessage($message);
                    db()->commit();
                }
                
                $arr = array('code'=>200,'msg'=>'转订单成功');
            }
        } catch (\Exception $e) {
            // $error = db()->getLastSql();
            // $this->errid = 1;
            // $this->errmsg= $error;
            db()->rollback();
            $arr = array('code'=>100,'msg'=>'网付订单失败','data'=>$e->getMessage(),'lastSql'=>db()->getLastSql());
            $errorData['action']      = '网付订单失败';
            $errorData['error_reason']= json_encode($arr);
            $errorData['create_time'] = date('Y-m-d H:i:s');
            db('l_error_log')->insert($errorData);
        }
        return $arr;
    }

    //转客资
    public function zhuanCustomer($param){
        $limit = $param['limit'] ? $param['limit'] : 10;
        $page = $param['page'] ? $param['page'] : 1;
        $result['code'] = 0;
        $result['msg'] = '';
        if(check_right('menu1512637269')){
            $res = db('c_call_registration')->where('shop_code',session('shop_code'))->where('customer_id','null')->order('id desc')->select();
            $count = db('c_call_registration')->where('shop_code',session('shop_code'))->where('customer_id','null')->order('id desc')->count();
        }else{
            $res = db('c_call_registration')->where('dj_staff_id',session('staff_id'))->where('customer_id','null')->order('id desc')->select();
            $count = db('c_call_registration')->where('shop_code',session('shop_code'))->where('customer_id','null')->order('id desc')->count();
        }
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        return ($res);
    }
    public function zhuanKeZi($param){
        foreach($param as $k=>$v){
            if(empty($v) || $v == '请选择'){
                unset($param[$k]);
            }
        }
        $ord_id = $param['id'];
        unset($param['id']);
        $info = db('c_call_registration')->where('id',$ord_id)->find();
        if(empty($param['customer_tel']) && empty($param['customer_name'])){
            return array('code'=>300,'msg'=>'客资信息不正确','data'=>'');
        }
        $param['shop_code'] = $info['shop_code'];
        $param['shop_name'] = $info['shop_name'];
        $param['add_shop_code'] = session('belong_shop_code');
        $param['add_shop_name'] = session('belong_shop_name');
        $param['brandclass_id'] = session('brandclass_id');
        $param['brandclass'] = session('brandclass');
        $param['dj_staff'] = $info['dj_staff'];
        $param['dj_staff_id'] = $info['dj_staff_id'];
        $param['customer_orderaddress'] = $info['customer_orderaddress'];
        $param['introducer_name'] = $info['introducer_name'];
        //查询归属地是否筛客
        $b_is_sk = $this->is_sk(session('belong_shop_code'));
        if($b_is_sk ==1 || session('is_sk') == 1){
            $param['is_sk'] == 1;
            //未选择筛客人则随机
            if(!$param['sk_staff_id']){
                $sklist = $this->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'];
                }
            }
        }
        db()->startTrans();
        $res = $this->addCustomer($param);
        if($res){
            $cInfo = db('c_customerinfo')->where(['customer_name'=>$info['customer_name'],'customer_tel' => $info['customer_tel']])->field('id')->find();
            db('c_call_registration')->where('id',$ord_id)->update(['customer_id'=>$cInfo['id']]);
            action_log($param,'',$cInfo['id'],session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'转客资成功','data'=>$param);
        }else{
            db()->rollback();
            return array('code'=>100,'msg'=>'转客资失败','data'=>'');
        }
    }
    function delNewCall($id){
        db()->startTrans();
        $res = db('c_call_registration')->where('id',$id)->delete();
        if($res){
            action_log($id,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'新客资来电删除成功','data'=>'');
        }else{
            db()->rollback();
            return array('code'=>100,'msg'=>'新客资来电删除失败','data'=>'');
        }

    }
    public function getCallInfo($id){
        return db('c_call_registration')->where('id',$id)->find();
    }
    //获取渠道补充
    public function getChannel($shop_code,$staff_id='',$channel_info_id=''){
        // $channel = session('channel');
        // if(empty($channel)){
        $staff_id = $staff_id ? $staff_id : session('staff_id');
        if(empty($channel)){
            if(empty($shop_code)) $shop_code = session('shop_code');
            $trench = db('c_staff_trench_mate')->where('shop_code',$shop_code)->where('staff_id',$staff_id)->value('trench');
            $findSql = ' FIND_IN_SET("'.$shop_code.'",share_shops) ';
            if($channel_info_id){
                $where['channel_info_id'] = $channel_info_id;    
            }

            if($trench && session('main_work_type')!= SYSTEM_AUTH_ADMIN){
                $channel = db('s_channel')->where($findSql)->where('channel_name','in',explode(',',$trench))->order('order_sort asc')->where($where)->select();
            }else{
                $channel = db('s_channel')->where($where)->where($findSql)->order('order_sort asc')->select();
            }
            
            session('channel_'.$shop_code.'_'.$staff_id,$channel);
            if(session('shop_code')){
                foreach ($channel as $k => $v) {
                    $signids = json_decode($v['bind_sign_ids'],true);
                    if($signids[session('shop_code')]){
                        $channel[$k]['sign_id'] = $signids[session('shop_code')]['sign_id'];
                        $channel[$k]['sign_name'] = $signids[session('shop_code')]['sign_name'];
                    }
                }
            }
        }
        return $channel;
    }

    /**
     * 每天提醒三天内收到的，但未邀约进店的未成单的客资。
     * @return boole
     */
    public function three_day_remind(){
        $today = date('Y-m-d');
        $three_day_remind = cache('three_day_remind');
        if ($today > $three_day_remind) {
            // 3天前
            $three_days_ago = date('Y-m-d', strtotime('-3 days'));
            $where['is_status'] = 1;
            $where['c_from'] = 1;
            $where['sales_staff_id'] = session('staff_id');
            // 没有邀约
            $countY = db('c_customerinfo')
                ->where($where)
                ->where('yjd_day', 'null')
                ->where('jr_day', 'between time', [$three_days_ago, $today])
                ->count('id');
            // 没有订单
            $countO = db('c_customerinfo')
                ->where($where)
                ->where('order_start_time', 'null')
                ->where('jr_day', 'between time', [$three_days_ago, $today])
                ->count('id');
            $count = $countY + $countO;
            // 数量大于0 发消息
            if ($count > 0) {
                // 发送消息用数据
                $messageD['send_type']      = 1;
                $messageD['send_title']     = '追踪提醒';
                $messageD['send_msg']       = '您有'.$count.'笔客资，尚未邀约、成单，请尽快处理。';
                $messageD['receive_id']     = session('staff_id');
                $messageD['receive_name']   = session('staffname');
                $messageD['receive_status'] = 1;
                $messageD['receive_time']   = time();
                $messageD['operation_type'] = 2;
                $messageD['operation']      = '';
                $timeOut = db_config('fp_timeout_'.session('shop_code'));
                $messageD['time_out']       = $timeOut;

                $resM = sendSystemMessage($messageD);
            }
            cache('three_day_remind', $today);
        }
    }
    //订单编辑
    public function editOrder($param){
        $time = date('Y-m-d H:i:s',time());
        $data['order_fact'] = $param['order_fact'];
        $data['order_amount'] = $param['order_amount'];
        $data['two_pin_fact'] = $param['two_pin_fact'];
        $data['two_pin_amount'] = $param['two_pin_amount'];
        $data['order_sn'] = $param['order_sn'];
        $data['target_time'] = $param['target_time'];


        $id = db('c_customer_order')->where('order_sn',$data['order_sn'])->value('id');
        if(($param['old_order_sn'] != $param['order_sn']) && $id){
            return array('code'=>100,'msg'=>'订单号已存在，请重新输入');
        }
        //订单信息
        $orderInfo = db('c_customer_order')->where('order_sn',$param['old_order_sn'])->find();
        if(empty($orderInfo['id'])){
            return array('code'=>404,'msg'=>'此客资还未成单，请先转订单！');
        }
        //客资信息
        $order_start_time = $data['target_time'];
        if(empty($order_start_time)){
            $order_start_time = db('c_customerinfo')->where('id',$param['customer_id'])->value('order_start_time');
            $data['target_time'] = $order_start_time ? $order_start_time : $time;
        }

        // 根据事业部id查询事业部信息
        $brandclass_id = (int)session('brandclass_id');
        $brandclassInfo= controller('index/Customer','lib')->getBrandClassInfo($brandclass_id);

        $cusInfo['order_number'] = $data['order_sn'];

        // 订单有效标准 （order_rule） 1：实收款；2：占比
        if($brandclassInfo['order_rule'] == 1){
            if($data['order_fact']+$data['two_pin_fact'] >= $brandclassInfo['proportion']){
                //流水信息
                $dData['order_sn'] = $data['order_sn'];
                $dData['pay_time']  = $time;
                $dData['order_valid']  = 2;
                $dData['order_fact']  = $data['order_fact'] - $orderInfo['earnest_money'] - $orderInfo['order_fact'];
                $dData['two_pin_fact']  = $data['two_pin_fact'] - $orderInfo['two_pin_fact'];
                $dData['create_time']  = $time;

                $data['order_valid'] = 2;
                // $data['order_fact'] = $data['order_fact']+$orderInfo['earnest_money'];
                $data['earnest_money'] = 0;
                $data['update_time']   = $time;

                $cusInfo['is_success'] = 1;
                $cusInfo['order_day'] = $data['target_time'];
                $cusInfo['order_start_time'] = $order_start_time ? $order_start_time : $time;
                $cusInfo['totalpay_money'] = $data['order_amount']+$data['two_pin_amount'];
                $cusInfo['fact_money'] = $data['order_fact']+$data['two_pin_fact'];
            }else{
                $data['order_valid'] = 1;
                $data['earnest_money'] = $data['order_fact'];
                $data['order_fact'] = 0;
                $data['update_time']   = $time;


                $dData['order_sn'] = $data['order_sn'];
                $dData['pay_time']  = $time;
                $dData['order_valid']  = 1;
                $dData['order_fact']  = $param['order_fact'] - $orderInfo['earnest_money'] - $orderInfo['order_fact'];
                $dData['two_pin_fact']  = $param['two_pin_fact'] - $orderInfo['two_pin_fact'];
                $dData['create_time']  = $time;

                $cusInfo['is_success'] = 3;
                $cusInfo['order_day'] = null;
                $cusInfo['order_start_time'] = $order_start_time ? $order_start_time : $time;
                $cusInfo['totalpay_money'] = $param['order_amount']+$param['two_pin_amount'];
                $cusInfo['fact_money'] = $param['order_fact']+$param['two_pin_fact'];
            }
        }else if($brandclassInfo['order_rule'] == 2){
            if( (($data['order_fact']+$data['two_pin_fact']) / $data['order_amount']) >= ($brandclassInfo['proportion']/100) ){
                $dData['order_sn'] = $data['order_sn'];
                $dData['pay_time']  = $time;
                $dData['order_valid']  = 2;
                $dData['order_fact']  = $data['order_fact'] - $orderInfo['earnest_money'] - $orderInfo['order_fact'];
                $dData['two_pin_fact']  = $data['two_pin_fact'] - $orderInfo['two_pin_fact'];
                $dData['create_time']  = $time;

                $data['order_valid'] = 2;
                $data['earnest_money'] = 0;
                $data['update_time']   = $time;

                $cusInfo['is_success'] = 1;
                $cusInfo['order_day'] = $data['target_time'];
                $cusInfo['order_start_time'] = $order_start_time ? $order_start_time : $time;
                $cusInfo['totalpay_money'] = $data['order_amount']+$data['two_pin_amount'];
                $cusInfo['fact_money'] = $data['order_fact']+$data['two_pin_fact'];
            }else{
                $dData['order_sn'] = $data['order_sn'];
                $dData['pay_time']  = $time;
                $dData['order_valid']  = 1;
                $dData['order_fact']  = $param['order_fact'] - $orderInfo['earnest_money'] - $orderInfo['order_fact'];
                $dData['two_pin_fact']  = $param['two_pin_fact'] - $orderInfo['two_pin_fact'];
                $dData['create_time']  = $time;

                $data['order_valid'] = 1;
                $data['earnest_money'] = $data['order_fact'];
                $data['order_fact'] = 0;
                $data['update_time']   = $time;


                $cusInfo['is_success'] = 3;
                $cusInfo['order_day'] = null;
                $cusInfo['order_start_time'] = $order_start_time ? $order_start_time : $time;
                $cusInfo['totalpay_money'] = $param['order_amount']+$param['two_pin_amount'];
                $cusInfo['fact_money'] = $param['order_fact']+$param['two_pin_fact'];
            }
        }else{
            if( (($data['order_fact']+$data['two_pin_fact']) / $data['order_amount']) >= ($brandclassInfo['proportion']/100) ){
                $dData['order_sn'] = $data['order_sn'];
                $dData['pay_time']  = $time;
                $dData['order_valid']  = 2;
                $dData['order_fact']  = $data['order_fact'] - $orderInfo['earnest_money'] - $orderInfo['order_fact'];
                $dData['two_pin_fact']  = $data['two_pin_fact'] - $orderInfo['two_pin_fact'];
                $dData['create_time']  = $time;

                $data['order_valid'] = 2;
                $data['earnest_money'] = 0;
                $data['update_time']   = $time;


                $cusInfo['is_success'] = 1;
                $cusInfo['order_day'] = $data['target_time'];
                $cusInfo['order_start_time'] = $order_start_time ? $order_start_time : $time;
                $cusInfo['totalpay_money'] = $data['order_amount']+$data['two_pin_amount'];
                $cusInfo['fact_money'] = $data['order_fact']+$data['two_pin_fact'];
            }else{
                $dData['order_sn'] = $data['order_sn'];
                $dData['pay_time']  = $time;
                $dData['order_valid']  = 1;
                $dData['order_fact']  = $param['order_fact'] - $orderInfo['earnest_money'] - $orderInfo['order_fact'];
                $dData['two_pin_fact']  = $param['two_pin_fact'] - $orderInfo['two_pin_fact'];
                $dData['create_time']  = $time;

                $data['order_valid'] = 1;
                $data['earnest_money'] = $data['order_fact'];
                $data['order_fact'] = 0;
                $data['update_time']   = $time;


                $cusInfo['is_success'] = 3;
                $cusInfo['order_day'] = null;
                $cusInfo['order_start_time'] = $order_start_time ? $order_start_time : $time;
                $cusInfo['totalpay_money'] = $param['order_amount']+$param['two_pin_amount'];
                $cusInfo['fact_money'] = $param['order_fact']+$param['two_pin_fact'];
            }
        }
        $info = db('c_customerinfo')->where('id',$param['customer_id'])->find();
        db()->startTrans();
        try{
            //修改订单表
            db('c_customer_order')->where('order_sn',$param['old_order_sn'])->update($data);
            //修改客资表
            $cusInfo['order_number'] = $data['order_sn'];
            $cusInfo['update_time']  = $time;
            db('c_customerinfo')->where('id',$param['customer_id'])->update($cusInfo);
            //修改流水表
            //当修改单号时更新原来的流水单号
            if($data['order_sn'] != $param['old_order_sn']){
                db('c_order_detail')->where('order_sn',$param['old_order_sn'])->update(['order_sn'=>$data['order_sn']]);
            }
            $dData['order_type'] = $orderInfo['order_type'];
            $dData['order_sn'] = $data['order_sn'];
            $this->insert_order_detail($dData);

            //记录日志
            $old = [];
            $new = [];
            $key = array_keys($info);
            foreach($cusInfo as $k=>$v){
                if($cusInfo[$k] != $info[$k] && in_array($k,$key)){
                    $old[$k] = $info[$k];
                    $new[$k] = $cusInfo[$k];
                }
            }
            action_log($new,$old,$param['id'],session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'msg'=>'编辑订单成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'编辑订单失败','data'=>$e->getMessage());
        }
    }
    // 客资驳回
    public function customerReject($param){
        // 权限
        $auth = check_right('menu1517278817');
        if (!$auth) {
            $return = array('error'=>'1','msg'=>'您没有驳回权限，如需驳回请找管理员授权后重新登录系统操作。');
            // return json($return);
            return $return;
            exit;
        }

        // 取post值
        $cid = (int)$param['cid'];
        $send_msg = $param['send_msg'].'<br />';
        $reject_reason = $param['reject_reason'];
        // 根据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,c_star_day')->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 = ['c_star_day'=>date('Y-m-d H:i:s'),'is_valid'=>'4','yx_day'=>date('Y-m-d H:i:s'),'reject_reason'=>$reject_reason,'reject_remark'=>$send_msg];
                if (!$cInfo['c_star_day']) {
                    $data['c_star_day'] = date('Y-m-d H:i:s');
                }
                $data['last_trackday'] = date('Y-m-d H:i:s');
                $data['is_valid'] = '4';
                $data['yx_day'] = date('Y-m-d H:i:s');
                $data['reject_reason'] = $reject_reason;
                $data['reject_remark'] = $send_msg;

                if ((int)$param['reject_staff_id']) {
                    $rejStaff = getStaffInfoById((int)$param['reject_staff_id']);
                    $data['sk_staff_id'] = (int)$param['reject_staff_id'];
                    $data['sk_staff'] = $rejStaff['staffname'];

                    $receive_id  = $data['sk_staff_id'];
                    $receive_name= $data['sk_staff'];
                }
                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'            => $param['gtType'],
                    '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'      => '客资驳回:'.$reject_reason.' '.$send_msg,
                    'customer_tel'      => $param['customer_tel'],
                    'consultation_type' => $param['consultation_type'],
                    'tel_static'        => $param['tel_static'],
                    'no_track'          => $param['no_track'],
                ];
                db('c_salestrackinginfo')->insert($dataValid);
                getSalesTracking($cid);//获取最近三次追踪记录同步更新到客资表
                // echo db()->getLastSql();
                if (!$receive_id && !$receive_name) {
                    // 向上一级发信息  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'];
                    }
                }
                
                $remind = getRemind(session('brandclass_id'));
                // 181212 Eric
                if($receive_id != session('staff_id') && in_array('tan',$remind['bh']['send_method']) && in_array('dj',$remind['bh']['send_receive'])){
                    $message['send_type']      = 1;
                    $message['send_title']     = '驳回提醒';
                    $message['send_msg']       = '您有一笔客资被驳回，姓名：'.$cInfo['customer_name'].'，驳回理由：'.$reject_reason.'，请确认。';
                    $message['customer_id']    = $cid;
                    $message['receive_id']     = $receive_id;
                    $message['receive_name']   = $receive_name;
                    $message['receive_status'] = 0;
                    $message['operation_type'] = 2;
                    $message['operation']      = NULL;
                    $message['time_out'] = 120;
                    $sendStatus = sendSystemMessage($message);
                }

                // 向上一级发信息  微信
                if($receive_id  != session('staff_id') && in_array('tui',$remind['bh']['send_method']) && in_array('dj',$remind['bh']['send_receive'])){
                    $content = [
                        'touser'       => $receive_id,
                        'template_id'  => OPENTM_BH,
                        'data'         => [
                            'first'=>[
                                'value'=> '您好，您有一笔客资被驳回',
                                'color'=> '#173177'
                            ],
                            'keyword1'=>[
                                'value'=> $cInfo['customer_name'].'('.$cInfo['customer_sex'].')',
                                'color'=> '#173177'
                            ],
                            'keyword2'=>[
                                'value'=> $cInfo['customer_tel'],
                                'color'=> '#173177'
                            ],
                            'keyword3'=>[
                                'value'=> $receive_name,
                                'color'=> '#173177'
                            ],
                            'keyword4'=>[
                                'value'=> $send_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) {
                    db()->commit();
                    $old = '是否有效：'.getIsValidAttr($cInfo['is_valid']);
                    $new = '是否有效：驳回;原因：'.$reject_reason.'；备注：'.$send_msg;

                    action_log($new,$old,$cid,session('staff_id'),session('staff_name'));
                    $return = ['msg'=>'已驳回','code'=>200,'data'=>''];
                // }else{
                //     db()->rollback();
                //     $return = ['msg'=>'操作失败，请联系管理员','code'=>100];
                // }
            } catch (Exception $e) {
                // echo db()->getLastSql();
                $return = ['msg'=>'操作失败，请联系管理员'.$e->getMessage(),'code'=>300];
                db()->rollback();
            };
        }else{
            $return = ['msg'=>'您不是当前客资的追踪人或筛客人或没有驳回权限','code'=>400];
        }
        return $return;
    }

    public function moreSearchCus($data){
        set_time_limit(0);
        $limit = $data['limit'] ? $data['limit'] : 20;
        $page = $data['page'] ? $data['page'] : 1;
        $tel = array_filter($data['tel']);

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

        if(session('shop_type') == 2){
            $field = 'id,baby_name,baby_sex,customer_name,customer_tel,mate_tel,customer_qq,customer_wechat,shop_name,add_shop_name,customer_channel,customer_cource,dj_staff,dj_day,sales_staff,is_valid,sign_name,c_star_day,is_status,is_success,op_signinfo';
        }else{
            $field = 'id,customer_name,customer_tel,mate_tel,customer_qq,customer_wechat,shop_name,add_shop_name,customer_channel,customer_cource,dj_staff,dj_day,is_fp,sales_staff,is_valid,sign_name,c_star_day,is_status,is_success,op_signinfo';
        }
        
        if(config('search_use_full_text_index')){
            $searchTel = implode(' ', $tel);
            $res = db('c_customerinfo c')
            ->where(' MATCH(c.customer_number,c.customer_name,c.customer_tel,c.customer_wechat,c.customer_qq,c.mate_name,c.mate_tel,c.mate_wechat,c.mate_qq,c.baby_name,c.order_number) AGAINST (\''.$searchTel.'\' in boolean mode) ')
            ->where('brandclass_id',session('brandclass_id'))
            ->where('is_status',1)
            ->limit($limit)->page($page)
            ->field($field)
            ->select();
        }else{
            $searchTel = "'".implode("','", $tel)."'";
            $res = db('c_customerinfo c')
            // ->where('customer_tel|mate_tel|customer_qq|customer_wechat|mate_wechat|mate_qq','in',$tel)
            ->where('c.id in(select c_id from c_customer_contact where contact in('.$searchTel.'))')
            ->where('brandclass_id',session('brandclass_id'))
            ->where('is_status',1)
            ->limit($limit)->page($page)
            ->field($field)
            ->select();
        }
        if(empty($res)){
            foreach($res as $k=>$v){
                $res[$k]['id'] = '';
                if(session('shop_type') == 2) {
                    $res[$k]['baby_name'] = '';
                    $res[$k]['baby_sex'] = '';
                }
                $res[$k]['customer_name'] = '';
                $res[$k]['customer_tel'] = $tel;
                $res[$k]['shop_name'] = '';
                $res[$k]['add_shop_name'] = '';
                $res[$k]['customer_channel'] = '';
                $res[$k]['customer_cource'] = '';
                $res[$k]['dj_staff'] = '';
                $res[$k]['dj_day'] = '';
                $res[$k]['sales_staff'] = '';
                $res[$k]['is_valid'] = '';
                $res[$k]['sign_name'] = '';
                $res[$k]['track_status'] = '';
                $res[$k]['is_status'] = '';
                $res[$k]['is_success'] = '';
            }
        }else{
            foreach($res as $k=>$v) {
                $res[$k]['is_fp'] = getIsFP($v['is_fp']);
                $res[$k]['is_valid'] = getIsValidAttr($v['is_valid']);
                $res[$k]['is_success'] = getIsSuccess($v['is_success']);
                $res[$k]['track_status'] = $v['c_star_day'] ? '追踪中' : '待追踪';
            }
        }

        if($res){
            $result['data'] = $res;
            $result['count'] = count($res);
        }else{
            $result['data'] = array();
            $result['count'] = 0;
        }
        return $result;
    }
    function searchErpOrder($condition){
        $is_erp = is_install('sx_erp');
        if (!$is_erp) {
            return false;
        }
        $brandId = $condition['brand_id']?$condition['brand_id']:'';

        $keyword = $condition['keyword']?trim($condition['keyword']):'';
        $shopType = $condition['shop_type']?$condition['shop_type']:0;
        $startDate = $condition['start_date']?$condition['start_date']:'';
        $endDate = $condition['end_date']?$condition['end_date']:'';

        $erp = config('ext.app_config')['sx_erp'];
        if(session('shop_type') == 2){
            $addr= $erp['addr_child'];
            $url = trim($addr,'/').'/SX_ChildCrmApi/Sel_CustomerOrderList?Token=^******^&CustomerType='.$shopType;
        }else{
            $addr= $erp['addr'];
            $url = trim($addr,'/').'/SX_CrmApi/Sel_CustomerOrderList?Token=^******^&CustomerType='.$shopType;
        }
        $url = $url.'&orderinfo='.$keyword.'&brandid='.$brandId.'&startdate='.$startDate.'&enddate='.$endDate;
        $dataErp = '[]';
        $response = requestERP($url, $dataErp);
        if($response['Code'] == 200){
            $numbers = [];
            foreach($response['Data'] as $k=>$v){//取出客资编号组成数组
                array_push($numbers,$v['customer_from_index']);
            }
            //查询符合的所有客资
            $cusInfo = db('c_customerinfo')->where('customer_number','in',$numbers)->column('customer_number,order_type,sales_staff,syjd_day,c_from,reception_name,dj_staff','customer_number');

            foreach($response['Data'] as $k=>$v){
                $response['Data'][$k]['getDate'] = $v['getDate'] ? date('Y-m-d',strtotime($v['getDate'])) :'';
                if(empty($v['customer_from_index'])){
                    // $response['Data'][$k]['order_type'] = 1;
                    $response['Data'][$k]['dj_staff'] = '';
                    $response['Data'][$k]['sales_staff'] = $v['storeconsuitant2'] ? $v['storeconsuitant2'] : '';
                    $response['Data'][$k]['reception_name'] = $v['storeconsuitant1'] ? $v['storeconsuitant1'] : '';
                    $response['Data'][$k]['syjd_day'] = '';
                    $response['Data'][$k]['c_from'] = 'CRM';
                }else{
                    // $response['Data'][$k]['order_type'] = $cusInfo[$v['customer_from_index']]['order_type'];
                    $response['Data'][$k]['dj_staff'] = $cusInfo[$v['customer_from_index']]['dj_staff'];
                    $response['Data'][$k]['sales_staff'] = $v['storeconsuitant2'] ? $v['storeconsuitant2'] : $cusInfo[$v['customer_from_index']]['sales_staff'];
                    $response['Data'][$k]['reception_name'] = $v['storeconsuitant1'] ? $v['storeconsuitant1'] : $cusInfo[$v['customer_from_index']]['reception_name'];
                    $response['Data'][$k]['syjd_day'] = $cusInfo[$v['customer_from_index']]['syjd_day'];
                    $response['Data'][$k]['c_from'] = $cusInfo[$v['customer_from_index']]['c_from']==2 ? 'ERP' : 'CRM';
                }
            }
            return $response['Data'];
        }else{
            return [
                'code'=>$response['Code'],
                'msg'=>$response['Msg'],
            ];
        }
    }
    //集团信息，包含：事业部信息，店面信息
    public function companyInfo(){
        $brandInfo = cache('companyInfo');
        if(empty($brandInfo)){
            $url = '5a38840b15ba9';
            $brand = sx_call($url,[]);
            if($brand['code'] == 200){
                $brandInfo = array_column($brand['data'],null,'id');
                foreach($brandInfo as $k=>$v) {
                    $shop = controller('crm/Customer','lib')->get_shop(['brandclass_id'=>$v['id']]);
                    $brandInfo[$k]['shop'] = array_column($shop,null,'shop_code');
                }
                cache('companyInfo',$brandInfo);
            }
        }
        return $brandInfo;
    }
    //获取客资无效原因接口
    public function getUnvalidReason($data){
        $reason = cache('unValidReason');
        if(empty($reason)){
            $mc = new \app\common\lib\mcInterface();
            $reason = $mc->cacheData('5af3fe7a0a668',$data);
            if($reason === false){
                $reason = array('code'=>$mc->_code,'msg'=>'查询无效客资原因失败'.$mc->_msg,'data'=>'');
            }else{
                 cache('unValidReason'.$reason);
            }
            // $url = '5af3fe7a0a668';
            // $res = sx_call($url,$data);
            // if($res['code'] == 200){
            //     $reason = $res['data'];
            //     cache('unValidReason'.$reason);
            // }else{
            //     $reason = array('code'=>100,'msg'=>'查询无效客资原因失败','data'=>'');
            // }
        }
        return $reason;
    }

    /*----------------------------------------------为了追踪重新写的------------------------------------------------*/
    // 编辑客资信息
    public function editCustomer($param){
        db()->startTrans();//开启事务
        try {
            // 修改客资信息
            $param['update_time'] = date('Y-m-d H:i:s');
            db('c_customerinfo')->where('id', $param['cid'])->update($param);
            return array('code'=>200,'msg'=>'编辑客资信息成功');
        } catch (\Exception $e) {
            db()->rollBack();//回滚
            return array('code'=>100,'msg'=>'编辑客资信息失败','error'=>$e->getMessage());
        }
    }

    // 录入追踪记录
    public function insertSalesTracking($param){
        db()->startTrans();//开启事务
        try {
            // 新增追踪记录
            db('c_salestrackinginfo')->insert($param);
            // 将最近三条追踪记录更新到客资表
            getSalesTracking($param['cid']);
            return array('code'=>200,'msg'=>'添加追踪记录成功');
        } catch (\Exception $e) {
            db()->rollBack();//回滚
            return array('code'=>100,'msg'=>'添加追踪记录失败','error'=>$e->getMessage());
        }
    }

    // 驳回客资， （更新客资表，修改客资状态为驳回，并且发送  弹窗或者模板消息）
    public function rejectCustomer($param){
        $date = date('Y-m-d H:i:s');
        $cid = $param['cid'];
        // 根据cid取客资名称和编号
        $cInfo = db('c_customerinfo')->where('id', $cid)->field('is_valid,customer_name,customer_number,customer_tel,customer_sex,dj_staff_id,dj_staff,sk_staff_id,sk_staff,sales_staff_id')->find();

        if($cInfo['is_valid'] == 4){
            return array('code'=>500,'msg'=>'已是驳回客资,不用再次驳回！');
        }

        $data['is_valid']      = 4;
        $data['yx_day']        = $date;
        $data['reject_reason'] = $param['reject_reason'];
        $data['reject_remark'] = $param['reject_remark'];
        $date['update_time']   = $date;
        db()->startTrans();
        try {
            // 更新客资表
            db('c_customerinfo')->where('id', $cid)->update($data);
            // 向上一级发信息  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'];
            }
            $message['send_type']      = 1;
            $message['send_title']     = '驳回提醒';
            $message['send_msg']       = '您有一笔客资被驳回，ID：'.$cid.'；姓名：'.$cInfo['customer_name'].'，驳回理由：'.$data['reject_reason'].'，请确认。';
            $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;
            $sendStatusPc = sendSystemMessage($message);

            // 向上一级发信息  微信
            $content = [
                'touser'       => $receive_id,
                'template_id'  => OPENTM_BH,
                'data'         => [
                    'first'=>[
                        'value'=> '您好，您有一笔客资被驳回',
                        'color'=> '#173177'
                    ],
                    'keyword1'=>[
                        'value'=> 'ID：'.$cid.'；'.$cInfo['customer_name'].'('.$cInfo['customer_sex'].')',
                        'color'=> '#173177'
                    ],
                    'keyword2'=>[
                        'value'=> $cInfo['customer_tel'],
                        'color'=> '#173177'
                    ],
                    'keyword3'=>[
                        'value'=> $receive_name,
                        'color'=> '#173177'
                    ],
                    'keyword4'=>[
                        'value'=> $data['reject_reason'],
                        'color'=> '#173177'
                    ],
                    'keyword5'=>[
                        'value'=> date('Y-m-d'),
                        'color'=> '#173177'
                    ],
                    'remark'=>[
                        'value'=>'请您尽快处理驳回信息，谢谢',
                        'color'=>'#173177'
                    ]
                ]
            ];
            $send_data['content'] = json_encode($content);
            $sendStatusWx = sendMsg($send_data);
            if ($sendStatusPc) {
                db()->commit();
                $return = ['msg'=>'已驳回','code'=>200];
            }else{
                db()->rollback();
                $return = ['msg'=>'操作失败，请联系管理员','code'=>100];
            }
        } catch (\Exception $e) {
            $return = ['error'=>$e->getMessage(),'msg'=>'操作失败，请联系管理员','code'=>300];
            db()->rollback();
        }
        return $return;
    }

    // 不在追踪， （修改客资状态为不在追踪，暂时不需要 发送 弹窗或者模板消息）
    public function lossCustomer($param){
        db()->startTrans();//开启事务
        try {
            // 修改客资信息
            $param['update_time'] = date('Y-m-d H:i:s');
            db('c_customerinfo')->where('id', $param['cid'])->update($param);
            return array('code'=>200,'msg'=>'不在追踪，操作成功');
        } catch (\Exception $e) {
            db()->rollBack();//回滚
            return array('code'=>100,'msg'=>'不在追踪，操作失败','error'=>$e->getMessage());
        }
    }

    // 预约进店， （修改客资信息，根据是否安装erp，判断是否调用erp接口）
    public function yyjdCustomer($param){
        $date = date('Y-m-d H:i:s');
        // 修改客资信息
        $param['update_time'] = $date;
        db('c_customerinfo')->where('id', $param['cid'])->update($param);

        //如果标记预约，存入pool表
        //查询再约提前时间
        $adv = db('s_reminditemset')->where('id','remind3')->where('brandclass_id',session('brandclass_id'))->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($param['yjd_day'])-86400*$adv['advancehour']);
            $message = array(
                'customer_id' => $param['cid'],
                'send_type'   => 1,
                'send_title'  => '预约提醒',
                'send_msg'    => '当前名为：【'.$param['customer_name'].'】的客资，'.date('Y-m-d',strtotime($param['yjd_day'])).' 预约进店',
                'receive_id'  => session('staff_id'),
                'receive_name'=> session('staff_name'),
                'operation_type'=> 2,
                'time_out'=> 120,
                'consulation_shop'=>$param['consulation_shop'],
                'yjd_time' => $param['yjd_day']
            );
            $pool = array(
                'cid' => $param['cid'],
                'msg' => json_encode($message),
                'fp_time_out' => strtotime($time),
                'count'=>0,
                'pool_type' => 2,
                'create_time' => date('Y-m-d H:i:s',time()),
            );
        }
        db('c_fp_pool')->insert($pool);

        // 是否安装erp
        $is_erp = is_install('sx_erp');
        // 如果安装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');
            $addr = $erp['sx_erp']['addr'];
            // 婚纱0，儿童1
            $url = trim($addr,'/').'/SX_CrmApi/Add_Guestinfo?Token=^******^&CustomerType='.$shop_type;
            $customerInfo = db('c_customerinfo')
                ->where('id', $param['cid'])
                ->field('customer_number,customer_name,customer_tel,customer_wechat,customer_qq,customer_sex,consultation_type,customer_area,customer_birthday,customer_cource,customer_intention,customer_orderaddress,customer_address,yjd_day,yp_day,marry_day,mate_name,mate_sex,mate_tel,mate_wechat,mate_qq,mate_birthday,intostore_note,consulation_shop,consulation_shop_code,brandclass_id,is_valid,yx_day')
                ->find();
            if ($param['customer_name']) {
                $customerInfo['customer_name']= $param['customer_name'];
            }
            if ($param['customer_tel']) {
                $customerInfo['customer_tel'] = $param['customer_tel'];
            }
            if ($param['customer_sex']) {
                $customerInfo['customer_sex'] = $param['customer_sex'];
            }
            // var_dump($customerInfo);
            $dataN["Customer_name"]     = $customerInfo['customer_name'] ? $customerInfo['customer_name'] : '';
            $dataN["Customer_tel"]      = $customerInfo['customer_tel'] ? $customerInfo['customer_tel'] : '';
            $dataN["Customer_wechat"]   = $customerInfo['customer_wechat'] ? $customerInfo['customer_wechat'] : '';
            $dataN["Customer_qq"]       = $customerInfo['customer_qq'] ? $customerInfo['customer_qq'] : '';
            $dataN["Customer_sex"]      = $customerInfo['customer_sex'] ? $customerInfo['customer_sex'] : '';
            $dataN["Consultation_type"] = $customerInfo['consultation_type'] ? $customerInfo['consultation_type'] : '';
            $dataN["Customer_area"]     = $customerInfo['customer_area'] ? $customerInfo['customer_area'] : '';

            if ($customerInfo['customer_birthday']) {
                $customer_birthday = date('Y-m-d',strtotime($customerInfo['customer_birthday']));
            }else{
                $customer_birthday = '';
            }
            $dataN["Customer_birthday"]     = $customer_birthday;
            $dataN["Customer_cource"]       = $customerInfo['customer_cource'] ? $customerInfo['customer_cource'] : '';
            $dataN["Customer_intention"]    = $customerInfo['customer_intention'] ? $customerInfo['customer_intention'] : '';
            $dataN["Customer_orderaddress"] = $customerInfo['customer_orderaddress'] ? $customerInfo['customer_orderaddress'] : '';
            $dataN["Customer_address"]      = $customerInfo['customer_address'] ? $customerInfo['customer_address'] : '';
            $dataN["Yjd_day"]               = $param['yjd_day'];

            if ($customerInfo['yp_day']) {
                $yp_day = date('Y-m-d',strtotime($customerInfo['yp_day']));
            }else{
                $yp_day = '';
            }
            $dataN["Yp_day"] = $yp_day;

            if ($customerInfo['marry_day']) {
                $wedding_date = date('Y-m-d',strtotime($customerInfo['marry_day']));
            }else{
                $wedding_date = '';
            }
            $dataN["Wedding_date"]= $wedding_date;

            $dataN["Mate_name"]   = $customerInfo['mate_name'] ? $customerInfo['mate_name'] : '';
            $dataN["Mate_sex"]    = $customerInfo['mate_sex'] ? $customerInfo['mate_sex'] : '';
            $dataN["Mate_tel"]    = $customerInfo['mate_tel'] ? $customerInfo['mate_tel'] : '';
            $dataN["Mate_wechat"] = $customerInfo['mate_wechat'] ? $customerInfo['mate_wechat'] : '';
            $dataN["Mate_qq"]     = $customerInfo['mate_qq'] ? $customerInfo['mate_qq'] : '';

            if ($customerInfo['mate_birthday']) {
                $mate_birthday = date('Y-m-d',strtotime($customerInfo['mate_birthday']));
            }else{
                $mate_birthday = '';
            }
            $dataN["Mate_birthday"] = $mate_birthday;

            $dataN["Dj_staff"]           = session('staff_name') ? session('staff_name') : '';
            $dataN["Sales_staff"]        = $data['reception_name'] ? $data['reception_name'] : '';
            $dataN["Sales_staff_number"] = $receptionInfo['staffnumber'] ? $receptionInfo['staffnumber'] : '';
            $dataN["Customer_remark"]    = $data['intostore_note'] ? $data['intostore_note'] : '';
            $dataN["Shop_name"]          = $data['consulation_shop'] ? $data['consulation_shop'] : '';
            $dataN["Shop_code"]          = $data['consulation_shop_code'] ? $data['consulation_shop_code'] : '';
            $dataN["Customer_from"]      = 'CRM';
            $dataN["Brandid"]            = $customerInfo['brandclass_id'] ? $customerInfo['brandclass_id'] : '';
            $dataN["From_index"]         = $customerInfo['customer_number'] ? $customerInfo['customer_number'] : '';
            $dataN = json_encode($dataN);

            $response = requestERP($url, $dataN);
            if ($response['Code'] != 200) {
                return array('code'=>100,'msg'=>'erp接口调用失败，请重试。','error'=>json_encode($response));
            }
        }
        //如果是爆破活动，修改对应的爆破表数据
        if($info['is_act'] == 2){
            db('c_swap_customer')->where('customer_number',$info['customer_number'])->update([['yjd_day'=>$param['yjd_day'],'yjd_action_day']=>$date]);
        }
        db()->commit();
        return array('code'=>200,'msg'=>'预约成功');
    }
    /*----------------------------------------------为了追踪重新写的------------------------------------------------*/
    public function getHignerLevel($data){
        $url = '5b20eb32badd8';
        $data['get_leave'] = 2;
        $info = sx_call($url,$data);
        if($info['code'] == 200){
            return $info['data'];
        }else{
            return false;
        }
    }
    //查询所有部门
    public function getDepartment(){
        $dep = cache('department');
        if(empty($dep)){
            $url = '5a0aef152b750';
            $info = sx_call($url,[]);
            if($info['code'] == 200){
                $arr = [];
                foreach($info['data'] as $k=>$v){
                    $arr[$v['id']] = $v;
                }
                cache('department',$arr);
                return $arr;
            }else{
                return false;
            }
        }else{
            return $dep;
        }
    }
    //事业部信息
    public function getBrandClass($data){
        $url = '5a38840b15ba9';
        $info = sx_call($url,$data);
        if($info['code'] == 200){
            return $info['data'];
        }else{
            return [];
        }
    }
    // 获取员工事业部下可操作店
    public function getBrandActionShop($param){
        $data = input();
        $p = [
            'staff_id'=> session('staff_id'),
            'brandclass_id'=> $data['brandclass_id'],
            'shop_type' => session('shop_type')
        ];
        $djshops = getShops($p);//可操作店
        return array_values($djshops);
    }
    //短信记录
    public function getMsgList($param){
        $phone = [];
        if($param['customer_tel']) $phone[] = $param['customer_tel'];
        if($param['mate_tel']) $phone[] = $param['mate_tel'];
        if(empty($phone)){
            $info = db('c_send_message_log')
                ->where("receive_id",$param['id'])
                ->order('send_time desc')
                ->select();
        }else{
            $info = db('c_send_message_log')
                ->where("receive_id",$param['id'])
                ->whereOr('receive_phone','in',$phone)
                ->order('send_time desc')
                ->select();
        }
        return $info;
    }

    // crm直接调erp开单时，自己开单
    public function createOrder($param){
        $date = date('Y-m-d H:i:s');
        $cid = $param['customer_id'];
        $res = db('c_customerinfo')->where('id',$cid)->field('id,customer_sex,customer_number,customer_name,customer_channel_id,customer_channel,is_valid,is_intostore,consultation_type,customer_area,add_shop_code,shop_code,shop_name,brandclass_id,brandclass,mate_tel,mate_name,mate_wechat,customer_wechat,customer_birthday,mate_birthday,customer_tel')->find();
        // return $cInfo;
        // 更新客资表
        $cData['customer_address'] = $param['address'];

        if($res['customer_sex'] == '男'){
            //联系方式
            if($param['mphone'] && $param['mphone'] != $res['customer_tel']){
                $cData['customer_tel'] = trim($param['mphone']);
            }
            if($param['mwechate'] && $param['mwechate'] != $res['customer_wechat']){
                $cData['customer_wechat'] = trim($param['mwechate']);
            }
            if($param['wphone'] && $param['wphone'] != $res['mate_tel']){
                $cData['mate_tel'] = trim($param['wphone']);
            }
            if($param['wwechate'] && $param['wwechate'] != $res['mate_wechat']){
                $cData['mate_wechat'] = trim($param['wwechate']);
            }
            //生日
            if($param['mbirthdate'] && $param['mbirthdate'] != $res['customer_birthday']){
                $cData['customer_birthday'] = $param['mbirthdate'];
            }
            if($param['wbirthdate'] && $param['wbirthdate'] != $res['mate_birthday']){
                $cData['mate_birthday'] = $param['wbirthdate'];
            }
            //姓名
            if($param['mname'] && $param['mname'] != $res['customer_name']){
                $cData['customer_name'] = $param['mname'];
            }
            if($param['wname'] && $param['wname'] != $res['mate_name']){
                $cData['mate_name'] = $param['wname'];
            }
        }else{
            //联系方式
            if($param['mphone'] && $param['mphone'] != $res['mate_tel']){
                $cData['mate_tel'] = trim($param['mphone']);
            }
            if($param['mwechate'] && $param['mwechate'] != $res['mate_wechat']){
                $cData['mate_wechat'] = trim($param['mwechate']);
            }
            if($param['wphone'] && $param['wphone'] != $res['customer_tel']){
                $cData['customer_tel'] = trim($param['wphone']);
            }
            if($param['wwechate'] && $param['wwechate'] != $res['customer_wechat']){
                $cData['customer_wechat'] = trim($param['wwechate']);
            }
            //生日
            if($param['mbirthdate'] && $param['mbirthdate'] != $res['mate_birthday']){
                $cData['mate_birthday'] = $param['mbirthdate'];
            }
            if($param['wbirthdate'] && $param['wbirthdate'] != $res['mate_birthday']){
                $cData['customer_birthday'] = $param['wbirthdate'];
            }
            //姓名
            if($param['mname'] && $param['mname'] != $res['mate_name']){
                $cData['mate_name'] = $param['mname'];
            }
            if($param['wname'] && $param['wname'] != $res['customer_name']){
                $cData['customer_name'] = $param['wname'];
            }
        }

        // 客资订单信息
        $cData['order_number'] = $param['OrderId'];
        $cData['order_start_time'] = $date;
        $cData['order_type'] = 1;

        // 有效状态
        if ($res['is_valid'] != 1 && $res['is_valid'] != 3) {
            $cData['is_valid'] = 1;
            $cData['yx_day'] = $date;
        }
        // 进店状态
        if ($res['is_intostore'] != 2) {
            $cData['is_intostore'] = 2;
            $cData['syjd_day'] = $date;
        }
        // 消费类型
        if ($res['consultation_type'] != $param['Consumption_type'] && $param['Consumption_type']) {
            $conditions['brandclass_id'] = $res['brandclass_id'];
            $conditions['consultation_type'] = $param['Consumption_type'];
            $temp_id = $this->get_set_id($conditions,$res['add_shop_code'],$res['shop_code']);
            $cData['consultation_type_id'] = $temp_id['consultation_type_id'];
        }
        // 客户分区
        if ($res['customer_area_id'] != $param['Area_id'] && $param['Area_id']) {
            $cData['customer_area_id']= $param['Area_id'];
            $cData['customer_area']   = $param['Area_name'];
        }
        db('c_customerinfo')->where('id', $cid)->update($cData);

        // 创建订单
        $oData['order_sn']          = $param['OrderId'];
        $oData['customer_id']       = $cid;
        $oData['customer_name']     = $res['customer_name'];
        $oData['customer_channel_id']=$res['customer_channel_id'];
        $oData['customer_channel']  = $res['customer_channel'];
        $oData['consultation_type'] = $param['Consumption_type'];
        $oData['target_time']       = $param['Targetdate'];
        $oData['create_time']       = $date;
        $oData['shop_code']         = $res['shop_code'];
        $oData['shop_name']         = $res['shop_name'];
        $oData['order_type']        = 1;
        $oData['order_note']        = $param['customernote'];
        $oData['brandclass_id']     = $res['brandclass_id'];
        $oData['brandclass']        = $res['brandclass'];
        // $oData['customer_orderaddress'] = '';
        db('c_customer_order')->insert($oData);

        return $res;
    }
    /*
     * 查询所有事业部
     * */
    public function getBrands($data){
        $detail = cache('brandclass');
        if(empty($detail)){
            $url = '5a3bbb5d0988d';
            $info = sx_call($url,$data);
            if($info['code'] == 200){
                $detail = $info['data'];
                cache('brandclass',$detail);
            }
        }
        return $detail;
    }
    
    // 如果已经邀约时间，并且没有订单，没有订单开始时间，则同步信息到erp
    public function updateToErp($param){
        $erp = config('ext.app_config');
        $addr = $erp['sx_erp']['addr'];

        $url = $addr.'SX_CrmApi/Update_Guestinfo?Token=^******^';

        $dataN['Customer_name']         = $param['customer_name'] ? $param['customer_name'] : '';
        $dataN['Customer_tel']          = $param['customer_tel'] ? $param['customer_tel'] : '';
        $dataN['Customer_wechat']       = $param['customer_wechat'] ? $param['customer_wechat'] : '';
        $dataN['Customer_qq']           = $param['customer_qq'] ? $param['customer_qq'] : '';
        $dataN['Customer_sex']          = $param['customer_sex'] ? $param['customer_sex'] : '';
        $dataN['Customer_birthday']     = $param['customer_birthday'] ? $param['customer_birthday'] : '';
        $dataN['Consultation_type']     = $param['consultation_type'] ? $param['consultation_type'] : '';
        $dataN['Consultation_type_id']  = $param['consultation_type_id'] ? $param['consultation_type_id'] : '';
        $dataN['Customer_area']         = $param['customer_area'] ? $param['customer_area'] : '';
        $dataN['Customer_area_id']      = $param['customer_area_id'] ? $param['customer_area_id'] : '';
        $dataN['Customer_cource']       = $param['customer_cource'] ? $param['customer_cource'] : '';
        $dataN['Customer_cource_id']    = $param['customer_cource_id'] ? $param['customer_cource_id'] : '';
        $dataN['Customer_intention']    = $param['customer_intention'] ? $param['customer_intention'] : '';
        $dataN['Customer_intention_id'] = $param['customer_intention_id'] ? $param['customer_intention_id'] : '';
        $dataN['Customer_orderaddress'] = $param['customer_orderaddress'] ? $param['customer_orderaddress'] : '';
        $dataN['Customer_address']      = $param['customer_address'] ? $param['customer_address'] : '';
        $dataN['Yjd_day']               = $param['yjd_day'] ? $param['yjd_day'] : '';
        $dataN['Yp_day']                = $param['yp_day'] ? $param['yp_day'] : '';
        $dataN['Wedding_date']          = $param['marry_day'] ? $param['marry_day'] : '';
        $dataN['Mate_name']             = $param['mate_name'] ? $param['mate_name'] : '';
        $dataN['Mate_sex']              = $param['mate_sex'] ? $param['mate_sex'] : '';
        $dataN['Mate_tel']              = $param['mate_tel'] ? $param['mate_tel'] : '';
        $dataN['Mate_wechat']           = $param['mate_wechat'] ? $param['mate_wechat'] : '';
        $dataN['Mate_qq']               = $param['mate_qq'] ? $param['mate_qq'] : '';
        $dataN['Mate_birthday']         = $param['mate_birthday'] ? $param['mate_birthday'] : '';
        $dataN['Customer_remark']       = $param['customer_remark'] ? $param['customer_remark'] : '';
        $dataN['Shop_name']             = $param['consulation_shop'] ? $param['consulation_shop'] : '';
        $dataN['Shop_code']             = $param['consulation_shop_code'] ? $param['consulation_shop_code'] : '';
        $dataN['Customer_from']         = 'CRM';
        $dataN['Brandid']               = $param['brandclass_id'];
        $dataN['From_index']            = $param['customer_number'];
        $dataN['Staffid']               = session('staff_id');//操作人id
        // 追踪人所属店面狗号
        $dataN["shop_codezzr"] = $param['shop_code'] ? $param['shop_code'] : '';
        $dataN["shop_namezzr"] = $param['shop_name'] ? $param['shop_name'] : '';
        // 追踪人所属部门
        $department = $this->getDepartment();
        $dataN["departidzzr"]  = $param['sales_department_id'] ? $param['sales_department_id'] : '';
        $dataN["departnamezzr"]= $department[$param['sales_department_id']]['department_name'] ? $department[$param['sales_department_id']]['department_name'] : '';
        // crm 接待人员，取 意向店面下的工作类型为门市的人
        $dataN["Sales_staff"] = $param['reception_name'] ? $param['reception_name'] : '';

        // 追踪人
        $dataN["Crmentryren"] = $param['sales_staff'] ? $param['sales_staff'] : '';

        $dataN = json_encode($dataN);

        $response = requestERP($url, $dataN);
        // var_dump($response);die;
        if ($response['Code'] != 200) {
            return array('code'=>$response['Code'],'msg'=>$response['Msg'],'error'=>json_encode($response));
        }else{
            return array('code' => 200, 'msg'=>'success');
        }
    }



// -------------------------------------------- 儿童排控 (选片、摄影) 开始 -------------------------------------------- //


    //获取某个列表上方下方 排控统计数量
    public function reloadTableNum($photodate,$shop_code){

    /*
        // 查设定 (可排程)
        $pc_set = db('s_pcdefault_monthset','sx_erp')
            ->where('pctype', 0) // 0:拍照排程;1:选片排程
            ->where('shop_code', $shop_code)
            ->where('pcday',$photodate)
            ->column('pcday,pctime,timecount,area','id');

        //根据排程设定 得到的空数据
        $setData = [];
        foreach($pc_set as $key => $value){
            for($i = 0; $i < $value['timecount']; $i++){
                $setData[] = [
                    'setTime' => $value['pctime'],
                    'setArea' => $value['area']
                ];
            }
        }

        $res['day'] = $photodate;
        $res['allPc'] = count($setData);
        unset($pc_set);

        // 查排程 已排程
        $pc_list = db('c_customerphoto','sx_erp')->alias('p')
            ->join('c_customerinfo c','c.customerid = p.customerid', 'left')
            ->where('p.shop_code', $shop_code)
            ->where('p.photodate',$photodate)
            ->field('c.area,p.photodate,p.phototime,p.photostate,p.currentfc,p.phototype,p.id')
            ->order('p.photodate')
            ->select();

        $res['yPc'] = count($pc_list);

        //将设定数据与排程数据整合
        foreach($setData as $key => $val) {
            $is_continue = 0;
            foreach ($pc_list as $k => $v) {

                //若此排程设定已与实际排程数据匹配，则直接跳出本次循环
                if($is_continue == 1){
                    continue;
                }

                //若排程设定中 时间和分区不限制
                $setPcTime = empty($val['setTime']) ? $v['phototime'] : $val['setTime'];
                $setArea = $val['setArea']=='全部' ? $v['area'] : $val['setArea'];

                if($v['phototime'] == $setPcTime && $v['area'] == $setArea){
                    unset($setData[$key],$pc_list[$k]);
                    $is_continue = 1;
                }
            }
            if($is_continue == 1){
                continue;
            }
        }


        $res['nPc'] = count($setData);
        unset($pc_list,$setData);
*/

        //获取总排控数 已排控 可排控
        $res = $this->getPcNum($photodate,$shop_code);

        //已排程 摄影师 摄影助理 化妆师数量
        //摄影师
        $syer = db('c_customerphoto','sx_erp')
            ->where('shop_code',$shop_code)
            ->where('photodate',$photodate)
            ->field('cameraman AS staffname,COUNT(1) AS num')
            ->group('cameraman')
            ->select();

        foreach($syer as $syKey => $syVal){
            if(empty($syVal['staffname']))  unset($syer[$syKey]);
        }

        $res['syer'] = $syer;

        // 摄影助理
        $syzler = db('c_customerphoto','sx_erp')
            ->where('shop_code',$shop_code)
            ->where('photodate',$photodate)
            ->field('photoassistant AS staffname,COUNT(1) AS num')
            ->group('photoassistant')
            ->select();

        foreach($syzler as $zlKey => $zlVal){
            if(empty($zlVal['staffname']))  unset($syzler[$zlKey]);
        }
        $res['syzler'] = $syzler;

        //化妆师
        $hzer = db('c_customerphoto','sx_erp')
            ->where('shop_code',$shop_code)
            ->where('photodate',$photodate)
            ->field('dresser AS staffname,COUNT(1) AS num')
            ->group('dresser')
            ->select();

        foreach($hzer as $hzKey => $hzVal){
            if(empty($hzVal['staffname']))  unset($hzer[$hzKey]);
        }
        $res['hzer'] = $hzer;

        unset($syer,$syzler,$hzer);

        return $res;

    }

    /*
     * 获取可排控数量
     * $shop_code   店面识别码
     * $photodate   时间
     */
    public function getPcNum($photodate,$shop_code){
        // 查设定 (可排程)
        $pc_set = db('s_pcdefault_monthset','sx_erp')
            ->where('pctype', 0) // 0:拍照排程;1:选片排程
            ->where('shop_code', $shop_code)
            ->where('pcday',$photodate)
            ->field('pcday,sum(timecount) num')
            ->find();

        $res['day'] = $photodate;
        $res['allPc'] = $pc_set['num'];
        //unset($pc_set);

        // 查排程 已排程
        $pc_list = db('c_customerphoto','sx_erp')
            ->where('shop_code', $shop_code)
            ->where('photodate',$photodate)
            ->field('photodate,count(orderId) as num')
            ->find();

        $res['yPc'] = $pc_list['num'];
        $res['nPc'] = $res['allPc'] - $res['yPc'];
        return $res;
    }
    /**
     * 检查客资的订单是否是有效订单
     * 需要在网付订单、开单接口、收款接口、退款接口进行统一调用。
     *
     * @param  [type] $customerInfo [客资订单信息：含订单号，事业部ID，订单总金额，订单已付金额，订单类型，订单店面]
     * @return [type]               [description]
     */
    public function checkOrderValid($customerInfo){
        if(customize('jueduirenqi')){
            if($customerInfo['customer_cource'] == '网络转款' && $customerInfo['fact_money'] >= 500){
                return true;
            }
        }

        $mc = new \app\common\lib\mcInterface();
        $brandInfo = $mc->getBrand($customerInfo['brandclass_id']);
         // 订单有效标准 （order_rule） 1：实收款；2：占比
        if($brandInfo['order_rule'] == 1){
            if($customerInfo['fact_money'] >= $brandInfo['proportion']){
                return true;
            }else{
                return false;
            }
        }else{
            if(intval($customerInfo['totalpay_money']) <= 0){
                return false;
            }
            if($customerInfo['fact_money']/$customerInfo['totalpay_money'] >= $brandInfo['proportion']){
                return true;
            }else{
                return false;
            }
        }

    }
    /*
     *  获取每一天的排程
     *  $shop_code    店面识别码
     *  $photodate          日期（例:20181114）
     */
    public function getPcListDay($photodate,$shop_code){

        $pc_set = db('s_pcdefault_monthset','sx_erp')
            ->where('pctype', 0) // 0:拍照排程;1:选片排程
            ->where('shop_code', $shop_code)
            ->where('pcday',$photodate)
            ->column('pcday,pctime,timecount,area','id');

        //根据排程设定 得到的空数据
        $setData = [];
        foreach($pc_set as $key => $value){

            for($i = 0; $i < $value['timecount']; $i++){
                $setData[] = [
                    'setTime' => $value['pctime'],
                    'setArea' => $value['area']
                ];
            }
        }

        unset($pc_set);

        //已排程数据
        $pc_list = db('c_customerphoto','sx_erp')->alias('p')
            ->join('c_customerinfo c','c.customerid = p.customerid', 'left')
            ->join('c_customerorder o','o.customerid = c.customerid', 'left')
            ->where('p.shop_code', $shop_code)
            ->where('p.photodate',$photodate)
            ->field('c.customerid,c.mname,c.wname,c.bbname,c.wphone,c.mphone,c.cssname,c.area,o.orderId,o.targetdate,o.consumption_type,o.acceptor_address,o.total_money,o.payment_money,o.nopayment_money,o.ordertopic,o.dresstheme,o.ordernote,p.currentfc,p.phototype,p.photodate,p.phototime,p.photostate,p.cameraman,p.photoassistant,p.lighting_engineer,p.designer,p.mentor_a,p.mentor_b,p.dresser,p.photonote,p.photobase,p.id,p.id as photoid,p.shop_code,p.jiaji,p.huazhuangzhuli,p.communication_date,p.communicationtime,p.communication_state,p.communication_man,p.secretaireman,p.shop_name,p.shop_code')
            ->order('p.photodate')
            ->select();

        //将设定数据与排程数据整合
        foreach($setData as $key => $val) {
            $is_continue = 0;
            foreach ($pc_list as $k => $v) {

                //若此排程设定空数据已插入实际排程数据，则直接跳出本次循环
                if($is_continue == 1){
                    continue;
                }

                //若排程设定中 时间和分区不限制
                $setPcTime = empty($val['setTime']) ? $v['phototime'] : $val['setTime'];
                $setArea = $val['setArea']=='全部' ? $v['area'] : $val['setArea'];

                if($v['phototime'] == $setPcTime && $v['area'] == $setArea){

                    $setData[$key] = $v;
                    $setData[$key]['setArea'] = $val['setArea'];
                    $setData[$key]['setTime'] = $val['setTime'];
                    unset($pc_list[$k]);
                    $is_continue = 1;
                }
            }
            if($is_continue == 1){
                continue;
            }
        }

        //与不符合设定规则的数据合并
        $all_list = array_merge($setData,$pc_list);
        unset($setData,$pc_list);

        return $all_list;
    }

    /*
     * 获取短信模板
     * 
     */
    public function getModel($shop_code){
        $shop_code = $shop_code ? $shop_code : session('shop_code');
        $ret = db('SMessageTemplateinfo')->where('shop_code',$shop_code)->where('status',1)->field('id,mtemplate_name,mtemplate_content')->select();
        if(!empty($ret)){
            $res = array('code'=>200,'msg'=>'','data'=>$ret);
        }else{
            $res = array('code'=>100,'msg'=>'未查询到短信模板','data'=>'');
        }
        return $res;
    }
    // -------------------------------------------- 儿童排控 (选片、摄影) 结束 -------------------------------------------- //

    /*
     * 反驳回
     * */
    public function customerUnValidUpdate($param){
        $cid = (int)$param['cid'];
        $isValid = $param['is_valid_fbh'] ? (int)$param['is_valid_fbh'] : 5;
        $send_msg = $param['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']){
            db()->startTrans();
            // 更新 客资表，插入  追踪记录表
            try {
                // 更新客资表
                $data = ['is_valid'=>$isValid];
                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());
                }
                $data['update_time'] = date('Y-m-d H:i:s',time());
                $data['c_end_day'] = date('Y-m-d H:i:s',time());
                $data['last_trackday'] = 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'];
                }
                $remind = getRemind(session('brandclass_id'));
                // 181212 Eric
                if($receive_id  != session('staff_id') && in_array('tan',$remind['fbh']['send_method']) && in_array('sales',$remind['fbh']['send_receive'])){
                    $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');
                $remind = getRemind(session('brandclass_id'));
                // 181212 Eric
                if($receive_id  != session('staff_id') && in_array('tan',$remind['fbh']['send_method']) && in_array('sales',$remind['fbh']['send_receive'])){
                    $content = [
                        'touser'       => $receive_id,
                        'template_id'  => OPENTM_BH,
                        'data'         => [
                            'first'=>[
                                'value'=> '您好，您有一笔客资被反驳回',
                                'color'=> '#173177'
                            ],
                            'keyword1'=>[
                                'value'=> $cInfo['customer_name'].'('.$cInfo['customer_sex'].')',
                                'color'=> '#173177'
                            ],
                            'keyword2'=>[
                                'value'=> $cInfo['customer_tel'],
                                'color'=> '#173177'
                            ],
                            'keyword3'=>[
                                'value'=> $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);
                }

                $old = '客资状态：驳回';
                $log = '客资状态：反驳回<br/>';
                $log .= '反驳回原因：'.$send_msg;
                action_log($log, $old, $cid, session('staff_id'), session('staff_name'));
                db()->commit();
                $return = ['msg'=>'已反驳回','code'=>200];

            } catch (Exception $e) {
                $return = ['code'=>100,'msg'=>'操作失败，请联系管理员','data'=>$e->getMessage()];
                db()->rollback();
            };
        }else{
            $return = ['code'=>101,'msg'=>'您不是当前客资的录入人或筛客人或没有反驳回权限'];
        }
        return $return;
    }
    //手机端修改渠道花费
    public function appChannelCostEdit($data){
            $cost_date = $data['cost_date'];
            $province_id = $data['province_id'] ? $data['province_id'] : 0;
            $city_id = $data['city_id'] ? $data['city_id'] : 0;
            $department_id = $data['department_id']? $data['department_id']:0;
            $province_name = $data['province_name'] ? $data['province_name'] : null;
            $city_name = $data['city_name'] ? $data['city_name'] : null;
            $department_name = $data['department_name']? $data['department_name']:null;
            $channel_id = $data['channel_id'] ? $data['channel_id'] : 0;

            $belong_shop_code = $data['belong_shop_code'] ? $data['belong_shop_code'] : NULL;
            $belong_shop_name = $data['belong_shop_name'] ? $data['belong_shop_name'] : NULL;
            /**
             * TODO:
             *
             * 1.对日期进行验证，查看是否允许添加此日期的
             * 2.看城市和部门有没有传，如查传了，就保存成城市和部门的花费，如果没传，城市和部门设置为null，表示不按城市或部门进行设置
             * 3.取相同条件的花费，看表里有没有，如果有，则更新cost字段。如果没有，添加一条。
             */
            $data['province_id'] = $province_id ? $province_id : 0;
            $data['province_name'] = $province_name ? $province_name : null;
            $data['city_id'] = $city_id ? $city_id : 0;
            $data['city_name'] = $city_name ? $city_name : null;
            $data['department_id'] = $department_id ? $department_id : 0;
            $data['department_name'] = $department_name ? $department_name : null;
            $data['channel_id'] = $channel_id;
            $data['belong_shop_code'] = $belong_shop_code ? $belong_shop_code : null;
            $data['belong_shop_name'] = $belong_shop_name ? $belong_shop_name : null;

            $cost_date = date('Y-m-d',strtotime($cost_date));
            $cost = $data['cost'];
            $channelInfo = db('s_channel')->where('id',$channel_id)->where('shop_code',$data['shop_code'])->find();

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

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

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

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

                    if(!empty($data['province_id'])){
                        $region = $this->getRegionByProvinceId(['id'=>$data['province_id']]);
                        $ins['region_id'] = $region['id'];
                        $ins['region_name'] = $region['region_name'];
                        $insert['region_id'] = $region['id'];
                        $insert['region_name'] = $region['region_name'];
                    }
                    db('s_channel_cost')->insert($ins);

                    db('c_customer_cost')->insert($insert);
                    $new = '';
                    $new .= '操作店面：'.$ins['shop_name'].'<br/>';
                    if($ins['belong_shop_name'])$new .= '归属店：'.$ins['belong_shop_name'].'<br/>';
                    if($ins['department_name'])$new .= '部门：'.$ins['department_name'].'<br/>';
                    if($ins['region_name'])$new .= '地域：'.$ins['region_name'].'<br/>';
                    if($ins['province_name'])$new .= '省：'.$ins['province_name'].'<br/>';
                    if($ins['city_name'])$new .= '市：'.$ins['city_name'].'<br/>';
                    $new .= '渠道：'.$ins['channel_name'].'<br/>';
                    $new .= '花费：'.$ins['cost'].'<br/>';
                    $new .= '日期：'.$ins['cost_date'].'<br/>';
                    action_log($new,[],0,session('staff_id'),session('staff_name'));
                }
                db()->commit();
                $ret['code'] = 200;
                $ret['msg'] = '操作成功';
                return $ret;
            }catch (\Exception $e){
                db()->rollback();
                $ret['code'] = 100;
                $ret['msg'] = '操作失败';
                $ret['data'] = $e->getMessage();
                return $ret;
            }
    }
    //标记无效
    public function signUnValid($param){
        $info = $this->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{
            $data['update_time'] = date('Y-m-d H:i:s',time());
            db('c_customerinfo')->where('id',$param['id'])->update($data);
            //追踪记录
            $params['customer_id'] = $param['id'];
            $params['customer_name'] = $info['customer_name'];
            $params['customer_number'] = $info['customer_number'];
            // $params['sales_remark'] = '标记无效';
            $params['sales_remark'] = '标记无效--'.$data['unvalid_reason'];

            $params['sales_day'] = date('Y-m-d H:i:s',time());
            $params['sales_staff'] = session('staff_name');
            $params['sales_staff_id'] = session('staff_id');
            $params['sales_staff_number'] = session('staff_number');
            $params['shop_name'] = session('shop_name');
            $params['shop_code'] = session('shop_code');
            db('CSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$param['id'],null);
            //修改追踪时间
            $time = date('Y-m-d H:i:s',time());
            if(empty($info['c_star_day'])){
                $arr = array(
                    'c_star_day' => $time,
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }else{
                $arr = array(
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }
            db('CCustomerinfo')->where('id',$param['id'])->update($arr);
            getSalesTracking($param['id']);
            $old = [];
            $new = [];
            $key = array_keys($info);
            foreach($data as $k=>$v){
                if($data[$k] != $info[$k] && in_array($k,$key)){
                    $old[$k] = $info[$k];
                    $new[$k] = $data[$k];
                }
            }
            action_log($new,$old,$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'=>'标记无效失败');
        }
    }
    //标记无效
    public function signValid($id){
        $info = $this->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;
        }

        db()->startTrans();
        try{
            $data['update_time'] = date('Y-m-d H:i:s',time());
            $res = db('c_customerinfo')->where('id',$id)->update($data);
            //追踪记录
            $params['customer_id'] = $id;
            $params['customer_name'] = $info['customer_name'];
            $params['customer_number'] = $info['customer_number'];
            $params['sales_remark'] = '标记有效';
            $params['sales_day'] = date('Y-m-d H:i:s',time());
            $params['sales_staff'] = session('staff_name');
            $params['sales_staff_id'] = session('staff_id');
            $params['sales_staff_number'] = session('staff_number');
            $params['shop_name'] = session('shop_name');
            $params['shop_code'] = session('shop_code');
            db('CSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$id,null);
            //修改追踪时间
            $time = date('Y-m-d H:i:s',time());
            if(empty($info['c_star_day'])){
                $arr = array(
                    'c_star_day' => $time,
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }else{
                $arr = array(
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }
            db('CCustomerinfo')->where('id',$id)->update($arr);
            //修改客资表近三次追踪记录
            getSalesTracking($id);
            $old = [];
            $new = [];
            $key = array_keys($info);
            foreach($data as $k=>$v){
                if($data[$k] != $info[$k] && in_array($k,$key)){
                    $old[$k] = $info[$k];
                    $new[$k] = $data[$k];
                }
            }
            action_log($new,$old,$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]);
            }
            //提醒查询
            $remind = getRemind(session('brandclass_id'));
            // 181212 Eric
            if($info['dj_staff_id']  != session('staff_id') && in_array('tan',$remind['valid']['send_method']) && in_array('dj',$remind['valid']['send_receive'])){
                $messageD['send_type']      = 1;
                $messageD['send_time']      = $time;
                $messageD['send_title']     = '标记提醒';
                $messageD['send_msg']       = '有一笔客资标记为有效，ID：'.$info['id'].'，请确认。';
                $messageD['customer_id']    = $info['id'];
                $messageD['receive_id']     = $info['dj_staff_id'];
                $messageD['receive_name']   = $info['dj_staff'];
                $messageD['receive_status'] = 1;
                $messageD['receive_time']   = $time;
                $messageD['operation_type'] = 2;
                $messageD['operation']      = '';
                $timeOut = db_config('fp_timeout_'.$info['shop_code']);
                $messageD['time_out']       = $timeOut ? $timeOut : 60;
                $resM = sendSystemMessage($messageD);
            }
            if($info['dj_staff_id']  != session('staff_id') && in_array('tui',$remind['valid']['send_method']) && in_array('dj',$remind['valid']['send_receive'])){
                // 发送微信模板消息
                $content = [
                    'touser'       => $info['dj_staff_id'],
                    'template_id'  => OPENTM_YX,
                    'data'         => [
                        'first'=>[
                            'value'=> '系统消息',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $info['customer_name'],
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $info['sales_staff'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> $time,
                            'color'=> '#173177'
                        ],
                        'remark'=>[
                            'value'=> '有一笔客资标记为有效，ID：'.$info['id'].'，请确认。',
                            'color'=> '#173177'
                        ],
                    ],
                ];
                $send_data['content'] = json_encode($content);
                $res = sendMsg($send_data);
            }

            db()->commit();
            return array('code'=>200,'msg'=>'标记有效成功');
        }catch (Exception $e){
            db()->rollback();
            return array('code'=>300,'msg'=>'标记有效失败');
        }
    }

    //消息列表取标题
    public function getSendTitle(){
        $temp = cache('send_title');
        if(empty($temp)){
            $temp = db('c_message')->field('send_title')->group('send_title')->select();
            cache('send_title',$temp);
        }
        return $temp;
    }
    //消息 删除
    public function delSendTitle($id,$sum){
        $temp = db('c_message')->where('id','in',$id)->delete();
        if ($temp) {
            action_log(date("Y-m-d H:i:s",time()).session('staff_name')."删除消息".$sum."条",db('c_message')->getLastSql(),session('staff_id'),session('staff_id'),'','crm','Customer','getAllMsgDel');
            return true;
        }else{
            return false;
        }
    }
    //消息 删除
    public function delAllMsg(){
        $temp = db('c_message')->where('receive_id',session('staff_id'))->delete();
        if ($temp) {
            action_log(date("Y-m-d H:i:s",time()).session('staff_name')."清空消息".$temp."条",db('c_message')->getLastSql(),session('staff_id'),session('staff_id'),'','crm','Customer','delAllMsg');
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取本事业部下的预计婚期
     * 
     * @param  brandclass_id  客资id
     * 
     * @return array 
     * @author lilong<lilong@suxuantech.cn>
     */
    public function ready_marry_day($params){
        if(!isTableExist('s_merry_day_set')) return [];
        $where['brandclass_id'] = (int)$params['brandclass_id'] ? (int)$params['brandclass_id'] : session('brandclass_id');
        $where['is_delete'] = 2;
        $returnData = db('s_merry_day_set')->where($where)->select();
        return $returnData;
    }

    /**
     * 新增追踪记录，不添加action_log，只insert追踪记录表，  所有参数的验证在进入该方法前验证完毕，本方法不做任何验证  
     * 
     * @param  cid            客资id
     * @param  trackinfo      要添加的追踪信息（数组，必须与追踪记录表，字段名一致）
     * @param  staffinfo      操作人相关信息（数组）
     * 
     * @return int            lastInsertId
     * @author lilong<lilong@suxuantech.cn>
     */
    public function addCustomerTrackInfo($params){
        $cid       = $params['cid'];
        $trackinfo = $params['trackinfo'];
        $staffinfo = $params['staffinfo'];

        $cInfo = db('c_customerinfo')->where('id',$cid)
            ->field('id,customer_number,customer_name,customer_tel,consultation_type,customer_intention')
            ->find();

        $trackData['gtType']            = $trackinfo['gtType'] ? $trackinfo['gtType'] : 1;
        $trackData['customer_id']       = $cInfo['id'];
        $trackData['customer_name']     = $cInfo['customer_name'];
        $trackData['customer_number']   = $cInfo['customer_number'];
        $trackData['sales_day']         = $trackinfo['sales_day'] ? date('Y-m-d H:i:s',strtotime($trackinfo['sales_day'])) : date('Y-m-d H:i:s');
        $trackData['sales_staff']       = $staffinfo['staffname'];
        $trackData['sales_staff_id']    = $staffinfo['id'];
        $trackData['sales_staff_number']= $staffinfo['staffnumber'];
        $trackData['customer_intention']= $cInfo['customer_intention'];
        $trackData['customer_tel']      = $cInfo['customer_tel'];
        $trackData['tel_starttime']     = $trackinfo['tel_starttime'] ? date('Y-m-d H:i:s',strtotime($trackinfo['tel_starttime'])) : NULL;
        $trackData['tel_endtime']       = $trackinfo['tel_endtime'] ? date('Y-m-d H:i:s',strtotime($trackinfo['tel_endtime'])) : NULL;
        $trackData['tel_alltime']       = $trackinfo['tel_alltime'] ? $trackinfo['tel_alltime'] : NULL;
        $trackData['sales_remark']      = $trackinfo['sales_remark'] ? $trackinfo['sales_remark'] : NULL;
        $trackData['tel_type']          = $trackinfo['tel_type'] ? $trackinfo['tel_type'] : NULL;
        $trackData['seles_step']        = $trackinfo['seles_step'] ? $trackinfo['seles_step'] : NULL;
        $trackData['step_name']         = $trackinfo['step_name'] ? $trackinfo['step_name'] : NULL;
        $trackData['consultation_type'] = $cInfo['consultation_type'];
        $trackData['tel_static']        = $trackinfo['tel_static'] ? $trackinfo['tel_static'] : NULL;
        $trackData['shop_name']         = $staffinfo['shop_name'];
        $trackData['shop_code']         = $staffinfo['shop_code'];
        $trackData['audio_path']        = $trackinfo['audio_path'] ? $trackinfo['audio_path'] : NULL;
        $trackData['no_track']          = $trackinfo['no_track'] ? $trackinfo['no_track'] : 1;

        $lastid = db('c_salestrackinginfo')->insertGetId($trackData);
        if ($lastid===false) {
            $return['code'] = 100;
            $return['msg']  = '添加失败';
            $return['data'] = db()->getLastSql();
        }else{
            $return['code'] = 200;
            $return['msg']  = '添加成功';
            $return['data'] = $lastid;
        }
        return $return;
    }
    // 处理微信状态
    public function setWxStatus($param){
    	$cid = (int)$param['cid'];
    	$wxstatus = (int)$param['wxstatus'];
    	$cInfo = db('c_customerinfo')->where('id',$cid)->find();
    	if (!$cInfo) {
    		$return['code'] = 100;
			$return['msg']  = '查询客资信息失败！';
			$return['data'] = json_encode($param);
    		return $return;
    	}
    	$return['code'] = 200;
    	$return['msg']  = '';
    	if ($cInfo['wechat_status']!=$param['wxstatus']) {
    		db()->startTrans();
    		try {
    			$now = date('Y-m-d H:i:s');
    			if (!$cInfo['c_star_day']) {
    				$upCInfo['c_star_day'] = $now;
    			}
    			
    			$upCInfo['last_trackday']  = $now;
    			$upCInfo['update_time']    = $now;
    			if ($wxstatus=='1') {
    				if ($cInfo['wechat_status']==0) {
    					$insCInfo['sales_remark'] = session('staff_name').'通过扫描二维码，复制了微信号，微信状态由：未标记，修改为：待通过';
    					$upCInfo['wechat_status']  = $wxstatus;
    				}else{
    					$insCInfo['sales_remark'] = session('staff_name').'通过扫描二维码，复制了微信号';
    				}
    			}else if ($wxstatus=='2') {
    				$insCInfo['sales_remark'] = session('staff_name').'，将微信状态由：'.getWxStatus($cInfo['wechat_status']).'，修改为：已加上';
    				$upCInfo['add_friend_time']= $now;
                    $upCInfo['wechat_status']  = $wxstatus;
    			}else if ($wxstatus=='3') {
    				$insCInfo['sales_remark'] = session('staff_name').'，将微信状态由：'.getWxStatus($cInfo['wechat_status']).'，修改为：未加上';
                    $upCInfo['wechat_status']  = $wxstatus;
    			}

    			// 更新客资表 
    			db('c_customerinfo')->where('id',$cid)->update($upCInfo);
    			// 记录追踪记录
    			$insCInfo['gtType'] = '2';
    			$insCInfo['customer_id'] = $cid;
    			$insCInfo['customer_name'] = $cInfo['customer_name'];
    			$insCInfo['customer_number'] = $cInfo['customer_number'];
    			$insCInfo['sales_day'] = $now;
    			$insCInfo['sales_staff'] = session('staff_name');
    			$insCInfo['sales_staff_id'] = session('staff_id');
    			$insCInfo['sales_staff_number'] = session('staff_number');
    			
    			$insCInfo['step_name'] = $cInfo['step_name'];
    			$insCInfo['shop_name'] = session('shop_code');
    			$insCInfo['shop_code'] = session('shop_name');
    			db('c_salestrackinginfo')->insert($insCInfo);
    			getSalesTracking($cid);
    			// 记录日志
    			history_log('微信状态：'.getWxStatus($wxstatus), '微信状态：'.getWxStatus($cInfo['wechat_status']),$cid, session('staff_id'), session('staff_name'));
    			db()->commit();
    		} catch (\Exception $e) {
    			db()->rollback();
    			$return['code'] = 100;
    			$return['msg']  = '操作失败：'.$e->getMessage();
    		}
    	}
    	
    	return $return;
    }

    //修改客资信息 2021-11-23
    public function getCustomerInfoEdit($data)
    {

        if (!$data['id']) {
            $returnData = array('code' => 100,'msg' =>'用户ID数据为空，请重试');
            return $returnData;
        }

        // var_dump($data);die;
        if(!empty($data['province_id'])){
            $region = controller("Customer","lib")->getRegionByProvinceId(['id'=>$data['province_id']]);
            $data['customer_region_id'] = $region['id'];
            $data['customer_region'] = $region['region_name'];
        }


        $has = $this->getCustomerInfo($data['id']);
        if (!$has) {
            $returnData = array('code' => 900,'msg' =>'用户数据不存在，请检查！');
            return $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;
                }
            }
        }

        // 渠道不存在，返回报错
        // if (!$data['customer_channel_id']) {
        //     $returnData = array('code' => 400,'msg' =>'请填写客资来源渠道');
        //     return $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 $returnData;
        //    }
        // }

        //修改者是否有修改手机号权限 是否是录入者
        $customerInfo = $has;
        //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($data['customer_tel'] && !preg_match("/^1[3|4|5|6|7|8|9][0-9]{9}$/", $data['customer_tel'])){
            $returnData = array('code' => 150, 'msg' => '【'.$data['customer_tel'].'】手机号格式错误');
            return $returnData;
        }
        if(empty($customerInfo['customer_tel'])&&!empty($data['customer_tel'])){
            $data['tel_staff_id']=session('staff_id');
            $data['tel_staff']=session('staff_name');
            $data['tel_time']=date('Y-m-d H:i:s',time());
        }
        if(empty($customerInfo['customer_wechat'])&&!empty($data['customer_wechat'])){
            $data['wechat_staff_id']=session('staff_id');
            $data['wechat_staff']=session('staff_name');
            $data['wechat_time']=date('Y-m-d H:i:s',time());
        }
        if(empty($customerInfo['customer_qq'])&&!empty($data['customer_qq'])){
            $data['qq_staff_id']=session('staff_id');
            $data['qq_staff']=session('staff_name');
            $data['qq_time']=date('Y-m-d H:i:s',time());
        }
        // 对比提交数据和原始数据
        foreach ($data as $key => $value) {
            if ($value != strip_tags($has[$key])) {
                // $kStr = translate('c_customerinfo',$key);
                // if ($kStr) {
                //     $oldDate[$kStr]  = $has[$key];
                //     $newDate[$kStr]  = $value;
                // }
                $newDateIn[$key] = $value;
                $oldDateIn[$key] = strip_tags($has[$key]);
            }
        }

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

        if($newDateIn['sign_id']){
            $newDateIn['sign_time'] = date('Y-m-d H:i:s',time());
        }

        if($newDateIn['next_time']){
            $newDateIn['is_next'] = 1;
            //如果标记再约，存入pool表
            //查询再约提前时间  天
            $adv = db('s_reminditemset')->where('id','remind2')->where('shop_code',session('shop_code'))->where('isopen',1)->field('advancehour')->find();
            if($adv['advancehour'] || $adv['advancehour'] == 0){
                $adv = $adv['advancehour'] == 0 ? '今天' : $adv['advancehour'].'天后';
                $hour = date('H',strtotime($data['next_time']));
                if($hour == 0){
                    $time = date('Y-m-d 10:00:00',strtotime($data['next_time'])-86400*$adv['advancehour']);
                }else{
                    $time = date('Y-m-d H:i:s',strtotime($data['next_time'])-86400*$adv['advancehour']);
                }
                $message = array(
                    'customer_id' => $data['id'],
                    'send_type'   => 1,
                    'send_title'   => '再约提醒',
                    'send_msg'    => '当前名为：'.$data['customer_name'].'的客资，'.$adv.' 再约电访',
                    'receive_id'  => session('staff_id'),
                    'receive_name'=> session('staff_name'),
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'next_time'=>$newDateIn['next_time']
                );
                $arr = array(
                    'cid' => $data['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime($time),
                    'count'=>0,
                    'pool_type' => 6,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db()->startTrans();
                $inc1 = db('c_fp_pool')->insertGetId($arr);
                if(!$inc1){
                    db()->rollback();
                    $returnData = array('code' => 0,'msg' =>'再约进店失败');
                    return $returnData;
                }else{
                    db()->commit();
                }
            }
            //查询再约提前时间  分钟
            $adv = db('s_reminditemset')->where('id','next_before_minute')->where('shop_code',session('shop_code'))->where('isopen',1)->field('advancehour')->find();
            if($adv['advancehour']){
                $time = date('Y-m-d H:i:s',strtotime($data['next_time'])-60*$adv['advancehour']);
                $message = array(
                    'customer_id' => $data['id'],
                    'send_type'   => 1,
                    'send_title'   => '再约提醒',
                    'send_msg'    => '当前名为：'.$data['customer_name'].'的客资，'.$adv['advancehour'].'分钟后再约电访',
                    'receive_id'  => session('staff_id'),
                    'receive_name'=> session('staff_name'),
                    'operation_type'=> 2,
                    'time_out'=> 120,
                    'next_time'=>$newDateIn['next_time']
                );
                $arr = array(
                    'cid' => $data['id'],
                    'msg' => json_encode($message),
                    'fp_time_out' => strtotime($time),
                    'count'=>0,
                    'pool_type' => 6,
                    'create_time' => date('Y-m-d H:i:s',time()),
                );
                db()->startTrans();
                $inc1 = db('c_fp_pool')->insertGetId($arr);
                if(!$inc1){
                    db()->rollback();
                    $returnData = array('code' => 0,'msg' =>'再约进店失败');
                    return $returnData;
                }else{
                    db()->commit();
                }
            }
        }

        if($newDateIn['budget']){
            $newDateIn['budget'] = DeleteHtml($newDateIn['budget']);//去除预算的table标签
        }

        // 没有任何修改
        if (!$newDateIn) {
            // $returnData = array('code' => 900,'msg' =>'没有修改');
            $returnData = array('code' => 200,'msg' =>'编辑客资信息成功');
            return $returnData;
        }

        // 手机号修改日志
        if ($newDateIn['customer_tel']) {
            $data['tel_staff_id']= session('staff_id');
            $data['tel_staff']   = session('staff_name');
            $data['tel_time']=date('Y-m-d H:i:s',time());
        //history_log(['customer_tel'=>$newDateIn['customer_tel']],['customer_tel'=>$oldDateIn['customer_tel']],$has['id'],session('staff_id'),session('staff_name'),'crm','Customer','editCustomerTel');
        }
        
        // 开启事务
        db()->startTrans();
        try {
            // 更新时间
            $newDateIn['update_time'] = date('Y-m-d H:i:s');
            $res = db('c_customerinfo')->where('id', $data['id'])->update($newDateIn);
            // 如果修改客资备注 
            if(isset($newDateIn['customer_remark'])){
                $record['gtType']=4;
                $record['customer_id']=$customerInfo['id'];
                $record['customer_name']=$customerInfo['customer_name'];
                $record['customer_number']=$customerInfo['customer_number'];
                $record['sales_staff_id']=session('staff_id');
                $record['sales_staff']=session('staff_name');
                $record['sales_staff_number']=session('staff_number');
                $record['shop_name']=session('shop_name');
                $record['shop_code']=session('shop_code');
                $record['sales_day']=date('Y-m-d H:i:s',time());
                $record['sales_remark'] = '修改客资备注：'.$newDateIn['customer_remark'];
                db('c_salestrackinginfo')->insert($record);
                getSalesTracking($customerInfo['id']);
            }
            /*foreach ($newDateIn as $key => $value) {
                if ($key=='customer_remark') {
                    $record['gtType']=4;
                    $record['customer_id']=$customerInfo['id'];
                    $record['customer_name']=$customerInfo['customer_name'];
                    $record['customer_number']=$customerInfo['customer_number'];
                    $record['sales_staff_id']=session('staff_id');
                    $record['sales_staff']=session('staff_name');
                    $record['sales_staff_number']=session('staff_number');
                    $record['shop_name']=session('shop_name');
                    $record['shop_code']=session('shop_code');
                    $record['sales_day']=date('Y-m-d H:i:s',time());
                    $record['sales_remark'] = '修改客资备注：'.$value;
                    db('c_salestrackinginfo')->insert($record);
                    getSalesTracking($customerInfo['id']);
                }
            }*/
            history_log($newDateIn, $oldDateIn,$data['id'], session('staff_id'), session('staff_name'));

            // 是否安装erp
            // $is_erp = is_install('sx_erp');

            // if ($is_erp) {
                // 如果已经邀约时间，并且没有订单，没有订单开始时间，则同步信息到erp
                // if ($customerInfo['yjd_action_day'] && $customerInfo['is_success'] ==2 && !$customerInfo['order_start_time']) {
                //     $erpData = $newDateIn;
                //     $erpData['brandclass_id']  = $customerInfo['brandclass_id'];
                //     $erpData['customer_number']= $customerInfo['customer_number'];
                //     $res = controller("crm/Customer","lib")->updateToErp($erpData);
                //     unset($erpData);
                // }
            // }

            if($newDateIn['is_intostore']){
                //如果是爆破活动，修改对应的爆破表数据
                if($customerInfo['is_act'] == 2){
                    db('c_swap_customer')->where('customer_number',$customerInfo['customer_number'])->update(['is_intostore'=>$newDateIn['is_intostore']]);
                }

                //进店操作变动记录追踪日志
                $str = getIsIntostore($newDateIn['is_intostore']);
                //追踪记录
                $params['customer_id'] = $data['id'];
                $params['customer_name'] = $customerInfo['name'];
                $params['customer_number'] = $customerInfo['number'];
                $params['sales_remark'] = $str;
                $params['sales_day'] = date('Y-m-d H:i:s',time());
                $params['sales_staff'] = session('staff_name');
                $params['sales_staff_id'] = session('staff_id');
                $params['sales_staff_number'] = session('staff_number');
                $params['shop_name'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('CSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$data['id'],null);
                //修改追踪时间
                $info = $this->getCustomerInfo($data['id']);//客资信息
                $time = date('Y-m-d H:i:s',time());
                if(empty($info['c_star_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }
                db('CCustomerinfo')->where('id',$data['id'])->update($arr);
                //修改客资表近三次追踪记录
                getSalesTracking($data['id']);
                //进店日志
                history_log('是否进店：'. getIsIntostore($newDateIn['is_intostore']), '是否进店：'.getIsIntostore($oldDateIn['is_intostore']),$data['id'], session('staff_id'), session('staff_name'));
            }
            
            //客资标为无效删除其联系方式
            if($newDateIn['is_valid']==3){
                $oldContact=array();
                if($has['customer_tel'])       array_push($oldContact,$has['customer_tel']);
                if($has['customer_wechat'])    array_push($oldContact,$has['customer_wechat']);
                if($has['customer_qq'])        array_push($oldContact,$has['customer_qq']);
                db('c_customer_contact')->where('c_id',$has['id'])->where('contact','in',implode(',',$oldContact))->delete();
            }else{
                // var_dump(session('valid_date'));
                $valid_date = session('valid_date')*86400;
                $end_day = strtotime($has['dj_day']) + $valid_date;
                // 如果当前时间小于 过期时间 说明排重表里有这个联系方式  更新联系方式  如果大于，说明已经过期了，排重表里应该没有，不更新
                if (time() < $end_day || !$valid_date) {
                    // 查看排重表
                    $contact = db('c_customer_contact')
                        ->where('brandclass',$has['brandclass'])
                        ->where('c_id', $has['id'])
                        ->column('contact');
                    // 接收到的联系方式
                    $customer_contact = [];
                    if ($data['customer_tel']) {
                        array_push($customer_contact,$data['customer_tel']);
                    }
                    if ($data['customer_wechat']) {
                        array_push($customer_contact,$data['customer_wechat']);
                    }
                    if ($data['customer_qq']) {
                        array_push($customer_contact,$data['customer_qq']);
                    }
                    if ($data['mate_tel']) {
                        array_push($customer_contact,$data['mate_tel']);
                    }
                    if ($data['mate_wechat']) {
                        array_push($customer_contact,$data['mate_wechat']);
                    }
                    if ($data['mate_qq']) {
                        array_push($customer_contact,$data['mate_qq']);
                    }
                    $ins = array_diff($customer_contact, $contact);
                    $contactList = [];
                    foreach($ins as $k => $v){
                        $contactList[$k]['c_id']       = $has['id'];
                        $contactList[$k]['contact']    = $v;
                        $contactList[$k]['brandclass'] = $has['brandclass'];
                    }
                    db('c_customer_contact')->insertAll($contactList);

                    $del = array_diff($contact, $customer_contact);
                    foreach ($del as $k => $v) {
                        db('c_customer_contact')->where('c_id', $has['id'])->where('contact',$v)->delete();
                    }
                }
            }
            db()->commit();
            $returnData = array('code' => 200,'msg' => '编辑客资信息成功');
            return $returnData;
        } catch (Exception $e) {
            db()->rollback();
            $returnData = array('code' => 10002,'msg' =>'操作失败','data'=>$e->getMessage());
            return $returnData;
        }
    }

}

