<?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){
        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'));
            // if ($res['data']['shop_type'] != 2) {
            //     return array('code'=>102,'error'=>101,'msg'=>'不是儿童店账号，无法登录，请确定。','data'=>$res);
            // }
            $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('crm_l_login_log');
                if($isTable){
                    $logId = db('crm_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('work_shop',$loginRes['work_shop']);
        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('ShopSn', $loginRes['ShopSn']);//店面简码
        session('staff_sn', $loginRes['staff_sn']);//员工简码

        // 如果有小组,放到session
        // $group_id = db('c_staff_group_relation')->where('staff_id',$loginRes['staff_id'])->value('group_id');
        // if($group_id){
        //     $ginfo = db('crm_c_staff_group')->where('id',$group_id)->field('id,group_name')->find();
        //     session('group_id',$ginfo['id']);
        //     session('group_name',$ginfo['group_name']);
        //     $loginRes['group_id'] = $ginfo['id'];
        //     $loginRes['group_name'] = $ginfo['group_name'];
        // }
        // mc 的产品id
        session('mc_productid',$loginRes['productid']);
        // 不用crm设定的小组了，取mc的小组设定
        session('group_id',$loginRes['mc_group_id']);
        session('group_name',$loginRes['mc_group_name']);
        session('is_group_admin',$loginRes['group_admin']);

        $loginRes['group_id']  = $loginRes['mc_group_id'];
        $loginRes['group_name']= $loginRes['mc_group_name'];

        //呼叫中心信息
        $call_id =  db_config('call_id');
        if($call_id){
            //检测用户坐席信息
            $callInfo = db('crm_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('crm_s_call_man')->where('staff_id',$loginRes['staff_id'])->update($arr);
            }
            $call = db('CrmSCallCenter')->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;
        }
        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',$loginRes['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',$loginRes['status']);
        }
        cookie('current_position_code',null);
        //操作session表
        $db = db('CrmSSession');
        $staffInfo = $db->where(array('staff_id' => $loginRes['staff_id']))->find();
        $sql = "show columns from crm_s_session like 'login_time'";
        $aa = db()->execute($sql);
        if($aa){
            $param['login_time'] = date('Y-m-d H:i:s',time());
        }
        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'] = 1;
                db('CrmSSession')->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'] = 1;
                db('CrmSSession')->insert($param);
            }
            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('CrmSSession')->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('CrmCMessage')->where('send_type',$type)->where('is_delete',0)->where('receive_id',session('staff_id'))->select();
        return $res;
    }
    /*
     * 通知
     * */
    public function notice_list(){
        return db('CrmCMessage')->where('send_type',2)->where('is_delete',0)->where('receive_id',session('staff_id'))->select();
    }
    /*
     * 查看信息，通知
     */
    function update_message($id){
        $info = db('CrmCMessage')->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('CrmCMessage')->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('crm_s_session')->where('staff_id',$staffId)->find();
        if(!empty($res)){
            db('crm_s_session')->where('staff_id',$staffId)->update(['logout_time'=>date('Y-m-d H:i:s')]);
            //退出日志
            db('crm_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('crm_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){
            if ($res['data']['shop_type'] != 2) {
                return array('code'=>102,'error'=>101,'msg'=>'不是儿童店账号，无法登录，请确定。','data'=>$res);
            }
            //绑定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('crm_l_login_log');
            if($isTable) {
                $logId = db('crm_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);
            }
            $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 ";
            $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('crm_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('crm_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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->where($arr['sql'],$arr['arr'])->whereTime('dj_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //有效进店
    public function validJD($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CrmCCustomerinfo')->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('CrmCCustomerinfo')->where('is_success',1)->where('is_valid',3)->where($res['sql'],$res['arr'])->whereTime('dj_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //营收
    public function fact($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CrmCCustomerinfo')->where($res['sql'],$res['arr'])->whereTime('dj_day',$where)->where('is_status',1)->sum('fact_money');
        return $res;
    }
    //流失
    public function loss($arr){
        if(check_right('menu1512637269')) {//查看所有客资权限
            $res = db('CrmCCustomerinfo')-> 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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('crm_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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->where(array('is_success'=>1))->where($res['sql'],$res['arr'])->whereTime('dj_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //实际进店
    public function factIn($info,$where){
        $res=$this->get_sales_auth($info);
        $res = db('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->where(array('c_star_day'=>null,'is_fp'=>1))->where('is_intostore',1)->where('is_valid','in',[1,2])->where('dj_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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_fp'=>2))->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($staffId);
        $res = db('CrmCCustomerinfo')->where(array('is_fp'=>2))->where($res['sql'],$res['arr'])->whereTime('dj_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //获取到电话的客资数量
    public function getTelCount($data){
        if(check_right('menu1512637269')) {//查看所有客资权限
            $res = db('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->where(array('is_valid'=>1,'is_fp'=>1))->where('dj_staff_id|sales_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('CrmCCustomerinfo')->where(array('sales_staff_id'=>$staffId))->where('yjd_day','<>','')->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($staffId);
        $res = db('CrmCCustomerinfo')->where($res['sql'],$res['arr'])->where('yjd_day','<>','')->whereTime('dj_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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->where(array('is_intostore'=>1,'is_success'=>2))->where($res['sql'],$res['arr'])->whereTime('dj_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //进店(邀约)
    function jd_crm($info,$where){
        //$res = db('CrmCCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_intostore'=>1))->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($info,$where);
        $res = db('CrmCCustomerinfo')->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('crm_c_customerinfo')->where('shop_code',$shop_code)->whereTime('dj_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('crm_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('crm_s_sales_routines')->where('shop_code',session('shop_code'))->order('id asc')->select();
        foreach($res as $k=>$v){
            $res[$k]['count'] = db('CrmCCustomerinfo')
                ->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('CrmCCustomerinfo')
            ->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('CrmCCustomerinfo')->where('is_valid',3)->where($res['sql'],$res['arr'])->whereTime('dj_day',$where)->where('is_status',1)->count('id');
        return $res;
    }

    //沟通进度
    function get_seles_step(){
        $res = db('crm_s_sales_routines')->where(array('shop_code'=>session('shop_code')))->select();
        return $res;
    }
    //追踪失败原因
    function get_reason(){
        return db('crm_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('CrmCCustomerinfo')//->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('CrmCCustomerinfo')
                // ->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('CrmCCustomerinfo')
                // ->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('CrmCCustomerinfo')
                // ->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($id,$times){
        $day = getdateArea($times);
        $param = array(
            'start_day' => $day[0],
            'end_day' => $day[1],
            'staff_id' => $id,
        );

        $ret = $this->get_staff_info(array('staff_id'=>$id));
        $position_name = $ret['data']['main_position_name'];
        $shop_code = $ret['data']['shop_code'];
        if($times != 'last_month'){
            $time = 'month';
        }else{
            $time = $times;
        }
        //获取当前主岗位的五维图
        $wwt = db('CrmSStaffAbility')->where('shop_code',$shop_code)->where('position_name',$position_name)->where('times',$time)->find();
        $param['staff_id'] = $id;
        $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);
            }
            $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('CrmSKpiStaffgoal')
                ->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('CrmSKpiStaffgoal')
                ->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('CrmSKpiStaffgoal')
                ->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('CrmSKpiStaffgoal')
                ->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('CrmSKpiStaffgoal')
                    ->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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_c_customerinfo')->alias('c')
                    ->join('crm_c_customer_order o','c.id=o.customer_id','left')
                    ->join('crm_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('crm_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('crm_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('crm_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('CrmCCustomerinfo')->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'];
    }

    //客户来源  不调mc接口了，直接取库（erp儿童和crm合库）
    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);
        //     }
        // }
        $data['shop_code'] = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        $source = db('s_cussource')
            ->where('shop_code', 'like','%'.$data['shop_code'].'%')
            ->field('id,cus_name')
            ->select();
        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)){
            $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;
    }

    //客资地域
    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 areaSets()
    {
        return db('s_areaset')->group('area')->select();
    }
    //客户追踪标记
    function markSet($shopCode=''){
        /*$url="5a0c42f43e986";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $detail=$res['data'];
        }*/
        //标记取前端的不是MC的
        if (is_array($shopCode)) {
            $where = $shopCode;
        }else{
            $where['shop_code'] = $shopCode;
        }
        $detail = db('crm_s_markset')->where($where)->select();
        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 getHospital($data=''){
        $data['shop_code'] = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        $hospital = db('s_hospitalset')
            ->where('shop_code', 'like', '%'.$data['shop_code'].'%')
            ->field('id,hospital')
            ->select();
        return $hospital;
    }
    //消费类型
    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);
        //         }
        //     }
        // }
        $data['shop_code'] = $data['shop_code'] ? $data['shop_code'] : session('shop_code');
        $return = db('s_consumptiontype')
            ->where('shop_code', 'like', '%'.$data['shop_code'].'%')
            ->field('id,consumption_name')
            ->select();
        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(){
        /*$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]);
        // var_dump($position_code);die;
        if($info['code'] == 200) {
            return $info['data'];
        }else{
            return false;
        }*/
        $mc = new \app\common\lib\mcInterface();
        $position = $this->get_staff_info(['staff_id'=>session('staff_id')]);
        $position_code = $position['main_position_code'].','.$position['position_code'];
        $info = $mc->getPosition(['position_code'=>$position_code]);
        if (empty($info) || $info===false) {
            return false;
        }else{
            return $info;
        }
    }

    //人员
    function get_staff_list($data){
        $url="5a01766b4a3dd";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $info=$res['data'];
        }
        return $info;
    }
    //人员
    function get_staff_lists($data){
        $url="5a7424f13aa54";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $info=$res['data'];
        }
        return $info;
    }

    //店面
    function get_shop($data){
        // $info = session('consulation_shop');
        // if(empty($info)){
            $url="5a005e0038270";
            $res=sx_call($url,$data);
            // var_dump($res);die;
            if($res['code']==200){
                $info=$res['data'];
                // session('consulation_shop',$info);
            }
        // }
        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.customer_type,c.dj_day,c.create_time,c.is_fp,c.is_loss,erp_loss,c.dj_staff,s.sales_staff_name,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,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,c.bonus,c.brandclass,c.shop_name,c.add_shop_name,customer_address,order_type,c.dj_group_name,c.sales_group_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.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.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,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,c.bonus,c.brandclass,c.shop_name,c.add_shop_name,customer_address,order_type,c.dj_group_name,c.sales_group_name';
        }
        $clumn = $str ? 'c.id,c.'.str_replace(',',',c.',$str) : $default_coluwn;

        $join = [
            ['crm_c_swap_customer s','c.customer_number=s.customer_number', 'left'],
        ];
        $customer = db('crm_c_customerinfo c')->join($join)->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['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;
    }
    /**
     * 获取权限相关的限制条件
     * 
     * @return [type] [description]
     */
    public function getSearchRightSql($data){

        $sql = '';
        /**
         * 如果手机号精准搜索，则走这个SQL语句，
         * 需要配置config.ini内的search下的fullmobile=1,
         * 注意：精准查询不判断权限
         * auth:songdemei 20191223
         */
        if(ini('search.fullmobile') && $data['fullmobile']){
            return $sql;
        }

        switch (true) {
        case check_right('menu1512637269'):
            # 所有权限
            break;
        case check_right('menu1559716412'):
            #查看事业部客资
            $sql .= " and c.brandclass = '".session('brandclass')."' ";
            break;
        case check_right('menu1559716359'):
            #查看门店客资
            $sql .= " and (c.shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
            break;
        case check_right('menu1531471639'):
            #查看部门客资
            if($data['dep']){
                $sql .= ' and (c.dj_department_id='.session('department_id').' or c.sales_department_id='.session('department_id').')';
            }else{
                $sql .= " and (dj_staff_id='" . session('staff_id') . "' or sales_staff_id='" . session('staff_id') . "' )";
            }
            break;
        case check_right('menu1529653231'):

            #查看小组客资
            if($data['group']){
                $groupIds = [];
                if(session('group_id')){
                    $groupIds[] = session('group_id');
                }
                if(session('group_admin')){
                    list($groupIds[],$groupIds[]) = explode(',', session('group_admin'));
                }
                $sql .= " and (dj_group_id in (" . implode(',', $groupIds) . ") or sales_group_id in (" . implode(',', $groupIds) . ") )";
            }else{
                $sql .= " and (dj_staff_id='" . session('staff_id') . "' or sales_staff_id='" . session('staff_id') . "' )";
            }

            break;
        default:
            # 只能查看自己的客资,其中部门客资查询权限和小组客资查询条件，
            # 放在页面上有个部门客资和小组客资的复选框。
            # 
            $sql .= " and (dj_staff_id='" . session('staff_id') . "' or sales_staff_id='" . session('staff_id') . "' )";
            break;
        }
        //print_r($sql);die;
        return $sql;
    }
    //获取客资数据
    function customerListData($data){
        ini_set('memory_limit','-1');
        $listTime = microtime(true).'==>Line'.__LINE__.';';
        if ($data['end_time']) {
            $end_time = $data['end_time'];
            $data['end_time'] = date("Y-m-d 23:59:59",strtotime("$end_time +1days") );
        }else{
            $end_time = date("Y-m-d 23:59:59", strtotime("+1 days") );
            $data['end_time'] = $end_time;
        }

        // 如果是各种追踪
        if ($data['tab']==21||$data['tab']==22||$data['tab']==23||$data['tab']==24||$data['tab']==25||$data['tab']==26||$data['tab']==27||$data['tab']==20) {
            unset($data['start_time']);

            $data['all_time'] = $data['all_time'] ? $data['all_time'] : 'dj_day';

            /**  2021-03-16 南宁qqbaby  **/
            if (in_array($data['tab'], [27,20,172])) {
                unset($data['is_loss']);
            }
            /**  2021-03-16 南宁qqbaby end  **/

            // $sql = $this->customerSearch($data);
            $sqlArr = $this->customerSearch($data);
            $sql = $sqlArr[0];
            $oSql = $sqlArr[1];
            $sql_tab211 = $sqlArr[2];
            $sql.= $this->getSearchRightSql($data);
            // $sql.= ' and c.is_success <> 1 ';
        }else{
            // $sql = $this->customerSearch($data);
            $sqlArr = $this->customerSearch($data);
            $sql = $sqlArr[0];
            $oSql = $sqlArr[1];
            $sql_tab211 = $sqlArr[2];
            $sql.= $this->getSearchRightSql($data);
        }
        // var_dump($sql);die;
        $client_customer_id = $data['client_customer_id'];
        if($client_customer_id){
            $tab = $data['tab'];
            //$data = ['id'=>$client_customer_id];
            $sql = 'c.id = "'.$client_customer_id.'"';
        }

        if(check_right('menu1512637269')){
        }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')."' ";
                }
            }
        }

        $order = '';
        if($data['sidx']){
            if($data['sidx'] == 'customer_channel_list'){
                $data['sidx'] = 'customer_channel_id';
            }
            $data['sord'] = $data['sord'] == 'desc'?' desc ':' asc ';
            $order .= ' '.$data['sidx'].' '.$data['sord'];
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if($order == ''){
            // 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.dj_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']==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']== 21){
                $order .= " c.dj_day desc ";
            }    
            if($data['tab']&&$data['tab']== 22){
                $order .= " c.dj_day desc ";
            }    
            if($data['tab']&&$data['tab']== 23){
                $order .= " c.dj_day desc ";
            }    
            if($data['tab']&&$data['tab']== 24){
                $order .= " c.dj_day desc ";
            }    
            if($data['tab']&&$data['tab']== 25){
                $order .= " c.dj_day desc ";
            }    
            if($data['tab']&&$data['tab']== 26){
                $order .= " c.dj_day desc ";
            }    
        }

        $column = cache('colColumn_'.session('staff_id').'_'.session('shop_type'));
        
        if (!$column) {
            $info = db('crm_s_custom_column')->where('staff_id',session('staff_id'))->where('shop_type',session('shop_type'))->find();
            if(!empty($info)){
                cache('colColumn_'.session('staff_id').'_'.session('shop_type'),$info['custom_column']);
                cache('colNames_'.session('staff_id').'_'.session('shop_type'),$info['custom_name']);
                cache('colModel_'.session('staff_id').'_'.session('shop_type'),$info['custom_model']);
            }
        }
        $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){
                    $my1 .= 'c.'.$v.',';
                }
            }
            $check_list = trim($my1,',');
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        if (customize('nnqqbaby')) {
            $brandField = 'c.b_name as brandclass';
        }else{
            $brandField = 'c.brandclass';
        }
        
        //预约进店 2021-07-16
        if ($data['tab']==211) {
            // 列表页显示字段
            $def .= "c.id,c.recommend_staff,c.customer_channel,c.customer_channel_id,c.huoqu_num,c.baby_time,c.sign_name,c.is_valid,c.op_signinfo,c.customer_number,c.baby_name,c.baby_sex,c.baby_weight,c.baby_stature,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.add_friend_time,c.city,c.county,c.baby_address,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.track_record,c.is_intostore,c.syjd_day,c.loss_cause,c.customer_type,c.dj_day,c.record_day,c.create_time,c.is_fp,c.is_loss,c.erp_loss,c.dj_staff,c.sales_staff,c.fp_staff,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.tel_visit_num,c.last_trackday,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.bonus_deal,c.bonus,'.$brandField.',c.shop_name,c.add_shop_name,c.dj_department_name,c.sales_department_name,c.customer_address,c.dj_group_name,c.sales_group_name,pc_time,o.orderyouxiao as is_success,o.targetdate as order_start_time,o.orderyouxiaodate as order_day,c.consultation_type,c.consultation_type_id,o.consumption_type as o_consultation_type,ec.area as o_customer_area,o.package_name,c.hospital_photo_time,c.hospital_photo_cameraman,c.hospital_photo_assistant,c.wechat_status,c.step_name,ci.yjd_day as intostore_yjd_day,ci.operate_name as intostore_operate_name,ci.create_time as intostore_create_time,ci.fp_rec_time as intostore_fp_rec_time,ci.reception_name as intostore_reception_name,ci.is_intostore as intostore_is_intostore,ci.intostore_remark,o.orderId,o.bargain_money";
        }else{
            // 列表页显示字段
            $def = 'c.id,c.recommend_staff,c.customer_channel,c.customer_channel_id,c.huoqu_num,c.baby_time,c.sign_name,c.is_valid,c.op_signinfo,c.customer_number,c.baby_name,c.baby_sex,c.baby_weight,c.baby_stature,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.add_friend_time,c.city,c.county,c.baby_address,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.track_record,c.is_intostore,c.syjd_day,c.loss_cause,c.customer_type,c.dj_day,c.record_day,c.create_time,c.is_fp,c.is_loss,c.erp_loss,c.dj_staff,c.sales_staff,c.fp_staff,c.introduce_staff_name,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.tel_visit_num,c.last_trackday,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.bonus_deal,c.bonus,'.$brandField.',c.shop_name,c.add_shop_name,c.dj_department_name,c.sales_department_name,c.customer_address,c.dj_group_name,c.sales_group_name,MAX(sm.pc_time) as pc_time,MAX(o.orderyouxiao) as is_success,MIN(o.targetdate) as order_start_time,MAX(o.orderyouxiaodate) as order_day,c.consultation_type,c.consultation_type_id,GROUP_CONCAT(o.consumption_type) as o_consultation_type,GROUP_CONCAT(ec.area) as o_customer_area,GROUP_CONCAT(o.package_name) as package_name,c.hospital_photo_time,c.hospital_photo_cameraman,c.hospital_photo_assistant,c.wechat_status,c.step_name,o.orderId';
        }

        $data['rows'] = (int)$data['rows'] ? (int)$data['rows'] : 100;
        $data['page'] = (int)$data['page'] ? (int)$data['page'] : 1;
        // 查询总数
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        /*
        $orderTable = isIndexExist('crm_customer_id','c_customerorder')?' c_customerorder o FORCE INDEX(crm_customer_id) ':' c_customerorder o ';
        $customer = db('crm_c_customerinfo')->alias('c')->where($sql)
            ->join('crm_l_pc_log sm', 'c.id=sm.cid AND is_delete=2 AND sm.`status`<4', 'left')
            ->join($orderTable,'c.id=o.crm_customer_id AND o.blankoutannal<>1','left')
            // ->join('c_customerorder o','c.customer_number=o.crm_customer_number AND o.blankoutannal<>1','left')
            ->group('c.id')
            ->count();
        */
        // 判断有无索引
        $index_sql = 'show index from c_customerorder where key_name = "crm_customer_id"';
        $index = db('c_customerorder')->query($index_sql);
        if(!empty($index)){
            $customer = db('crm_c_customerinfo')->alias('c')->where($sql)
                ->join('crm_l_pc_log sm', 'c.id=sm.cid AND is_delete=2 AND sm.`status`<4', 'left')
                ->join('c_customerorder o force index (crm_customer_id)','c.id=o.crm_customer_id AND o.blankoutannal<>1','left')
                ->group('c.id')
                ->count();
        }else{
            $customer = db('crm_c_customerinfo')->alias('c')->where($sql)
                ->join('crm_l_pc_log sm', 'c.id=sm.cid AND is_delete=2 AND sm.`status`<4', 'left')
                ->join('c_customerorder o','c.id=o.crm_customer_id AND o.blankoutannal<>1','left')
                ->group('c.id')
                ->count();
        }
        
        // $customer = db('crm_c_customerinfo')->alias('c')->where($sql)
        //     ->join('crm_l_pc_log sm', 'c.id=sm.cid AND is_delete=2 AND sm.`status`<4', 'left')
        //     ->join('c_customerorder o','c.id=o.crm_customer_id AND o.blankoutannal<>1','left')
        //     // ->join('c_customerorder o','c.customer_number=o.crm_customer_number AND o.blankoutannal<>1','left')
        //     ->group('c.id')
        //     ->count();

        $countSql = db()->getLastSql();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // 先关联预约上门表 erp订单表查询客资信息
        // var_dump($sql);die;
        // var_dump($oSql);die;

        //预约进店 2021-07-16
        if ($data['tab']==211) {
            $sql_tab211 .= " and ci.consulation_shop_code='".session('shop_code')."'";
            $customer1 = db("crm_c_customer_intostore ci")
                ->join("crm_c_customerinfo c","ci.cid=c.id",'left')
                ->join("c_customerorder o","ci.id=o.crm_into_id",'left')
                ->join('c_paymentcontent p',"p.orderId=o.orderId","left")
                ->join('c_customerinfo ec','o.customerid=ec.customerid','left')
                ->join('crm_l_pc_log sm', 'c.id=sm.cid AND is_delete=2 AND sm.`status`<4', 'left')
                ->where($sql_tab211)
                ->field($def)
                ->order($order)
                ->limit($data['rows'])->page($data['page'])
                ->select();
        }else{
            $customer1 = db('crm_c_customerinfo')->alias('c')->where($sql)
                ->join('crm_l_pc_log sm', 'c.id=sm.cid AND is_delete=2 AND sm.`status`<4', 'left')
                ->join('c_customerorder o','c.id=o.crm_customer_id AND o.blankoutannal<>1','left')
                // ->join('c_customerorder o','c.customer_number=o.crm_customer_number AND o.blankoutannal<>1','left')
                ->join('c_customerinfo ec','o.customerid=ec.customerid','left')
                // ->join('crm_s_channel h','h.id = c.customer_channel_id')
                ->field($def)
                ->group('c.id')->order($order)
                ->limit($data['rows'])->page($data['page'])
                ->select();
        }

        $listsql1 = db()->getLastSql();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $tels = '';
        $orderId_tab211 = [];
        foreach ($customer1 as $key => $value) {
            $tels .= $value['customer_tel'].',';
            $orderId_tab211[] = $v['orderId'];
        }
        $tels = trim($tels,',');
        //预约进店 2021-07-16
        if ($data['tab']==211) {
            $pay = db('c_paymentcontent')->where("orderId","in",$orderId_tab211)->where("isshishou","实收")->where("suoshu","in","前期款','前期补款'")->group("orderId")->column("count(payment_money) as payment_money","orderId");
        }
        // 根据手机号查询手机号相关信息  20191220
        $inSql = db('c_customerinfo')->alias('c')
            ->join('c_customerorder o','c.customerid=o.customerid','left')
            ->join('c_customerphoto p', 'o.orderId=p.orderId', 'left')
            ->join('crm_c_customerinfo cc', 'cc.id=o.crm_customer_id', 'left')
            // ->where('c.wphone', 'in', $tels)->where('o.blankoutannal', 0)
            ->where('cc.customer_tel', 'in', $tels)->where('o.blankoutannal', 0)
            // ->where('c.wphone','not null')->where('c.wphone', '<>', '')
            ->where('cc.customer_tel','not null')->where('cc.customer_tel', '<>', '')
            ->where($oSql)
            ->field('c.id as cid, MAX(p.id) AS pid')->buildSql();
        
        $otherInfo = db('c_customerinfo')->alias('c')
            ->join($inSql.' temp', 'temp.cid = c.id', 'left')
            ->join('c_customerorder o','c.customerid=o.customerid','left')
            ->join('c_customerphoto p', 'o.orderId=p.orderId and temp.pid=p.id', 'left')
            ->join('crm_c_customerinfo cc', 'cc.id=o.crm_customer_id', 'left')
            // ->where('c.wphone', 'in', $tels)->where('o.blankoutannal', 0)
            ->where('cc.customer_tel', 'in', $tels)->where('o.blankoutannal', 0)
            // ->where('c.wphone','not null')->where('c.wphone', '<>', '')
            ->where('cc.customer_tel','not null')->where('cc.customer_tel', '<>', '')
            ->where($oSql)
            // ->group('c.wphone')
            ->group('cc.customer_tel')
            // 一销套系bargain_money，一销实收yixiaoshishou，二销套系supplementary_money，二销实收erxiaoshishou
            ->column('cc.customer_tel,GROUP_CONCAT(o.orderId) as orderIds,GROUP_CONCAT(o.allfinishfate) as allfinishfate,GROUP_CONCAT(p.photodate) as photodate,SUM(bargain_money) as yxtx,SUM(yixiaoshishou) as yxss,SUM(supplementary_money) as extx,SUM(erxiaoshishou) as exss','cc.customer_tel');

        $listsql2 = db()->getLastSql();
        // var_dump($listsql2);
        // die;
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // var_dump($otherInfo);die;
        foreach ($otherInfo as $key => $value) {
            $finishArr = explode(',', $value['allfinishfate']);
            $otherInfo[$key]['allfinishfate'] = min($finishArr);
            $photoArr = explode(',', $value['photodate']);
            $otherInfo[$key]['photodate'] = max($photoArr);
        }

        foreach ($customer1 as $key => $value) {
            //预约进店 2021-07-16
            if ($data['tab']==211) {
                $customer1[$key]['payment_money'] = $pay[$value['orderId']];
            }else{
                $customer1[$key]['payment_money'] = '';
            }
            
            if ($otherInfo[$value['customer_tel']]) {
                $customer1[$key]['orderIds'] = $otherInfo[$value['customer_tel']]['orderIds'];
                $customer1[$key]['allfinishfate'] = $otherInfo[$value['customer_tel']]['allfinishfate'];
                $customer1[$key]['photodate'] = $otherInfo[$value['customer_tel']]['photodate'];
                $customer1[$key]['yxtx'] = $otherInfo[$value['customer_tel']]['yxtx'];
                $customer1[$key]['yxss'] = $otherInfo[$value['customer_tel']]['yxss'];
                $customer1[$key]['extx'] = $otherInfo[$value['customer_tel']]['extx'];
                $customer1[$key]['exss'] = $otherInfo[$value['customer_tel']]['exss'];
            }else{
                $customer1[$key]['orderIds'] = '';
                $customer1[$key]['allfinishfate'] = '';
                $customer1[$key]['photodate'] = '';
                $customer1[$key]['yxtx'] = 0;
                $customer1[$key]['yxss'] = 0;
                $customer1[$key]['extx'] = 0;
                $customer1[$key]['exss'] = 0;
            }
        }
        
        // $inSql = db('crm_c_customerinfo')->alias('c')
        //     ->join('crm_l_pc_log sm', 'c.id=sm.cid', 'left')
        //     ->join('c_customerinfo ec', 'ec.wphone=c.customer_tel','left')
        //     ->join('c_customerorder o','ec.customerid=o.customerid','left')
        //     ->join('c_customerphoto p', 'o.orderId=p.orderId', 'left')
        //     ->where($sql)->field('c.id,MAX(sm.id) as smid,MAX(o.id) as oid,MAX(p.photodate) as photodate')->group('c.id')->buildSql();
        // $customer1 = db('crm_c_customerinfo')->alias('c')
        //     ->join($inSql.' b', 'b.id = c.id', 'left')
        //     ->join('crm_l_pc_log sm', 'c.id=sm.cid', 'left')
        //     ->join('c_customerorder o','o.id = b.oid','left')
        //     ->where($sql)->field($def.',b.photodate,sm.pc_time,sm.pc_type')
        //     ->order($order)
        //     ->limit($data['rows'])->page($data['page'])->select();
        
        $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'];
        $temp = [];
        $mc = config('ext.app_config');
        $addr = $mc['sx_mc']['addr'];
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $allChannel = getChannels();
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        // 是否有查看手机号权限
        $telAuth = true;
        if(!check_right('menu1512998373')){
            $telAuth = false;
        }
        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['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);
            }
            $v['is_loss'] = $v['is_loss'] == 1 ? '是':'否';
            if(!$telAuth){
                $v['customer_tel'] = !empty($v['customer_tel']) ? substr($v['customer_tel'], 0, 3).'****'.substr($v['customer_tel'], 7) : '';
            }
            // 渠道图标
            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'];
            }
            // var_dump($allChannel[$v['customer_channel_id']]);
            if($allChannel[$v['customer_channel_id']]){
                $v['customer_channel_info'] = $allChannel[$v['customer_channel_id']]['channel_info_name'];
                $v['customer_channel_class'] = $allChannel[$v['customer_channel_id']]['channel_class_name'];
            }
            // 消费类型图标
            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'];
            }

            $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['record_day'] = $v['record_day'] ? date('Y-m-d',strtotime($v['record_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',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['pc_time'] = $v['pc_time'] ? date('m.d',strtotime($v['pc_time'])) : '';
            // $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 ? '已发' : '未发';
            $v['is_valid'] = getIsValidAttr($v['is_valid']);
            $v['is_fp'] = getIsFP($v['is_fp']);
            $v['consultation_type'] = $v['o_consultation_type'] ? $v['o_consultation_type'] : $v['consultation_type'];
            $v['hospital_photo_time'] = $v['hospital_photo_time'] ? date('Y-m-d',strtotime($v['hospital_photo_time'])) : '';
            // 服务状态
            $v['service_sta'] = '';
            if ($v['orderIds']) {
                if ($v['allfinishfate']) {
                    $v['service_sta'] = '订单完成';
                }else if ($v['photodate']) {
                    $v['service_sta'] = '流程中';
                }else{
                    $v['service_sta'] = '未拍';
                }
            }
            if (!$v['is_success'] && $v['order_start_time']) {
                $v['is_success'] = 3;
            }
            $v['is_success'] = getIsSuccess($v['is_success']);
            $v['customer_remark'] = strip_tags($v['customer_remark']);
            //进店状态
            $v['intostore_is_intostores'] = $v['intostore_is_intostore'] ? getIsIntostore($v['intostore_is_intostore']) : '';
            $temp[$k] = $v;
        }
        $listTime .= microtime(true).'==>Line'.__LINE__.';';
        $temp1 = [];
        foreach($temp as $k=>$v){
            $temp1[$k][] = $v;
            // $temp1[$v['c_unique']][] = $v;
            // $temp1[$v['customer_tel']][] = $v;
        }
        $temp2 = [];
        $j = 0;
        foreach ($temp1 as $key => $value) {
            foreach ($value as $k => $v) {
                //预约进店 2021-07-16
                if ($data['tab']==211) {
                    $temp2[$key] = $v;
                }else{
                    // 双数
                    if ($j%2!=0) {
                        $v['customer_tel'] = '<font color="red">'.$v['customer_tel'].'</font>';
                        $temp2[$v['id']] = $v;
                    }else{
                        $temp2[$v['id']] = $v;
                    }
                }
            }
            $j++;
        }
        $i=0;
        $newRow = [];
        foreach ($temp2 as $key => $v) {
            $cus[$i]['id']=$v['id'];
            $cus[$i]['cell']=array_values($v);
            $newRow[$i] = $v;
            $i++;
        }
        $detail['listsql1'] = $listsql1;
        $detail['listsql2'] = $listsql2;
        $detail['countSql'] = $countSql;
        $detail['listTime'] = $listTime;
        // $detail['rows']=$cus;
        $detail['new_rows'] = $newRow;
        $detail['userdata']['amount']=3320;
        $detail['userdata']['tax']=336;
        $detail['userdata']['total']=3320;
        $detail['userdata']['name']='Totals:';
        
        return $detail;
    }

    //客资数量
    function searchNum($data,$tab=0){
        $linkTime = microtime(true).'==>Line'.__LINE__.';';
        $tab = $data['tab']?(int)$data['tab']:0;
        if ($data['end_time']) {
            $end_time = $data['end_time'];
            $data['end_time'] = date("Y-m-d 23:59:59",strtotime("$end_time +1days") );
        }else{
            $end_time = date("Y-m-d 23:59:59", strtotime("+1 days") );
            $data['end_time'] = $end_time;
        }
        // echo microtime(true).'==>Line'.__LINE__.'<br />';
        // $sql = $this->customerSearch($data);

        // 如果是各种追踪
        if ($data['tab']==21||$data['tab']==22||$data['tab']==23||$data['tab']==24||$data['tab']==25||$data['tab']==26||$data['tab']==27||$data['tab']==20) {
            unset($data['start_time']);

            /**  2021-03-16 南宁qqbaby  **/
            if (in_array($data['tab'], [27,20,172])) {
                unset($data['is_loss']);
            }
            /**  2021-03-16 南宁qqbaby end  **/
        }

        $sqlArr = $this->customerSearch($data);
        $sql = $sqlArr[0];
        // var_dump($sql);die;
        $sql.= $this->getSearchRightSql($data);
        // echo microtime(true).'==>Line'.__LINE__.'<br />';
        // var_dump($sql);
        // exit;
        // 不再追踪 tab == 7
        $data['is_loss'] = 1;
        $data['tab'] = 7;
        // $sqlLoss = $this->customerSearch($data);
        $sqlLossArr = $this->customerSearch($data);
        $sqlLoss = $sqlLossArr[0];
        $sql_tab211 = $sqlArr[2];
        // echo microtime(true).'==>Line'.__LINE__.'<br />';
        $sqlLoss.= $this->getSearchRightSql($data);
        // echo microtime(true).'==>Line'.__LINE__.'<br />';
        // var_dump($sqlLoss);
        // exit;
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        // 各种追踪(21-26)
        $data['all_time'] = 'dj_day';
        unset($data['start_time'],$data['is_loss'],$data['tab']);
        // $zz_sql = $this->customerSearch($data);

        $zz_sqlArr = $this->customerSearch($data);
        $zz_sql = $zz_sqlArr[0];

        // echo microtime(true).'==>Line'.__LINE__.'<br />';
        $zz_sql.= $this->getSearchRightSql($data);
        // echo microtime(true).'==>Line'.__LINE__.'<br />';
        $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 =$sql16 = $sql17 = $sql;

        $sql21 = $sql22 = $sql23 = $sql24 = $sql25 = $sql26 = $zz_sql;

        $index_sql = 'show index from crm_c_customerinfo where key_name = "all_time"';
        $index = db('crm_c_customerinfo')->query($index_sql);//判断有无索引
        if(!empty($index) && !config('search_use_full_text_index')){
            $table = 'crm_c_customerinfo c force index(all_time)';
        }else{
            $table = 'crm_c_customerinfo c';
        }
        $table = 'crm_c_customerinfo c';
        $orderTable = isIndexExist('crm_customer_id','c_customerorder')?' c_customerorder o FORCE INDEX(crm_customer_id) ':' c_customerorder o ';
        // echo microtime(true).'==>Line'.__LINE__.'<br />';
        // 全部
        if(!$tab || $tab == 1){
            $detail['all_crm'] = $detail['tab_all']= db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')->where($sql1)->group('c.id')->count();
            // $detail['all_crm'] = $detail['tab_all']= db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join('c_customerorder o','o.crm_customer_number=c.customer_number', 'left')->where($sql1)->group('c.id')->count();
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        // 今日需追踪
        if(!$tab || $tab == 17){
            $tWhere = " is_loss=2 and c.is_success=2 and (next_time is not null and next_time  <'".date("Y-m-d 23:59:59")."' AND DATE_FORMAT(last_trackday, '%Y-%m-%d') < DATE_FORMAT(next_time, '%Y-%m-%d') OR ( c_star_day IS NULL) )  ";
            $detail['today_sales']  = $detail['tab_today_sales'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where($sql17)
                ->where($tWhere)
                ->group('c.id')
                ->count();
            // echo db()->getLastSql();
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        //待追踪
        if(!$tab || $tab == 2){
            $detail['no_traking'] = $detail['tab_no_tracking'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')->where(array('c_star_day'=>null,'is_fp'=>1,'is_intostore'=>1,'is_loss'=>2,))->where('is_valid','in','1,2')->where($sql2)->group('c.id')->count();
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        // echo db()->getLastSql();die;
        //待分配
        if(!$tab || $tab == 3){
            $detail['no_fp'] = $detail['tab_no_fp'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')->where('is_fp','in','2,4')->where('is_success', 2)->where($sql3)->group('c.id')->count();
            // echo db()->getLastSql();die;
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        // 孕妈追踪
        if(!$tab || $tab == 21){
            // $t_date = date('Y-m-d 00:00:00', strtotime("+30 days"));
            // $e_date = date('Y-m-d 23:59:59', strtotime('+124 days'));
            $ymTimeare = db_config('ymTimeare_'.session('shop_code'));
            if (!$ymTimeare) {
                $ymTimeare = db_config('default_ymTimeare');
            }
            $t_date = date('Y-m-d 00:00:00', strtotime("+".$ymTimeare['start']." days"));
            $e_date = date('Y-m-d 23:59:59', strtotime("+".$ymTimeare['end']." days"));
            $whereSql = 'c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'"';
            $detail['pregnant_tel'] = $detail['pregnant_tel_tab'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where($whereSql)->where($sql21)->group('c.id')->count();
            unset($t_date,$e_date,$whereSql);
            // echo db()->getLastSql();die;
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        // 出生追踪
        if(!$tab || $tab == 22){
            // $t_date = date('Y-m-d 00:00:00', strtotime('-20 days'));
            // $e_date = date('Y-m-d 23:59:59', strtotime('-20 days'));
            $csTimeare = db_config('csTimeare_'.session('shop_code'));
            if (!$csTimeare) {
                $csTimeare = db_config('default_csTimeare');
            }
            $t_date = date('Y-m-d 00:00:00', strtotime("-".$csTimeare['start']." days"));
            $e_date = date('Y-m-d 23:59:59', strtotime("-".$csTimeare['end']." days"));
            $whereSql = 'c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'" or c.baby_birthday between "'.$t_date.'" and "'.$e_date.'"';
            $detail['born_tel'] = $detail['born_tel_tab'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where($whereSql)->where($sql22)->group('c.id')->count();
            unset($t_date,$e_date,$whereSql);
            // echo db()->getLastSql();die;
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        // 满月追踪
        if(!$tab || $tab == 23){
            // $t_date = date('Y-m-d 00:00:00', strtotime('-20 days'));
            // $e_date = date('Y-m-d 23:59:59', strtotime('-10 days'));
            $myTimeare = db_config('myTimeare_'.session('shop_code'));
            if (!$myTimeare) {
                $myTimeare = db_config('default_myTimeare');
            }
            $t_date = date('Y-m-d 00:00:00', strtotime("-".$myTimeare['start']." days"));
            $e_date = date('Y-m-d 23:59:59', strtotime("-".$myTimeare['end']." days"));
            $whereSql = 'c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'" or c.baby_birthday between "'.$t_date.'" and "'.$e_date.'"';
            $detail['manyue_tel'] = $detail['manyue_tel_tab'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where($whereSql)->where($sql23)->group('c.id')->count();
            unset($t_date,$e_date,$whereSql);
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        // 百天追踪
        if(!$tab || $tab == 24){
            // $t_date = date('Y-m-d 00:00:00', strtotime('-100 days'));
            // $e_date = date('Y-m-d 23:59:59', strtotime('-90 days'));
            $btTimeare = db_config('btTimeare_'.session('shop_code'));
            if (!$btTimeare) {
                $btTimeare = db_config('default_btTimeare');
            }
            $t_date = date('Y-m-d 00:00:00', strtotime("-".$btTimeare['start']." days"));
            $e_date = date('Y-m-d 23:59:59', strtotime("-".$btTimeare['end']." days"));
            $whereSql = 'c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'" or c.baby_birthday between "'.$t_date.'" and "'.$e_date.'"';
            $detail['baitian_tel'] = $detail['baitian_tel_tab'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where($whereSql)->where($sql24)->group('c.id')->count();
            unset($t_date,$e_date,$whereSql);
            // echo db()->getLastSql();die;
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        // 半岁追踪
        if(!$tab || $tab == 25){
            // $t_date = date('Y-m-d 00:00:00', strtotime('-190 days'));
            // $e_date = date('Y-m-d 23:59:59', strtotime('-180 days'));
            $bsTimeare = db_config('bsTimeare_'.session('shop_code'));
            if (!$bsTimeare) {
                $bsTimeare = db_config('default_bsTimeare');
            }
            $t_date = date('Y-m-d 00:00:00', strtotime("-".$bsTimeare['start']." days"));
            $e_date = date('Y-m-d 23:59:59', strtotime("-".$bsTimeare['end']." days"));
            $whereSql = 'c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'" or c.baby_birthday between "'.$t_date.'" and "'.$e_date.'"';
            $detail['bansui_tel'] = $detail['bansui_tel_tab'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where($whereSql)->where($sql25)->group('c.id')->count();
            unset($t_date,$e_date,$whereSql);
            // echo db()->getLastSql();die;
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        // 周岁追踪
        if(!$tab || $tab == 26){
            // $t_date = date('Y-m-d 00:00:00', strtotime('-370 days'));
            // $e_date = date('Y-m-d 23:59:59', strtotime('-360 days'));
            $zsTimeare = db_config('zsTimeare_'.session('shop_code'));
            if (!$zsTimeare) {
                $zsTimeare = db_config('default_zsTimeare');
            }
            $t_date = date('Y-m-d 00:00:00', strtotime("-".$zsTimeare['start']." days"));
            $e_date = date('Y-m-d 23:59:59', strtotime("-".$zsTimeare['end']." days"));
            $whereSql = 'c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'" or c.baby_birthday between "'.$t_date.'" and "'.$e_date.'"';
            $detail['zhousui_tel'] = $detail['zhousui_tel_tab'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where($whereSql)->where($sql26)->group('c.id')->count();
            unset($t_date,$e_date,$whereSql);
            // echo db()->getLastSql();die;
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        //已成单
        if(!$tab || $tab == 5){
            $orderSql = 'o.orderyouxiao = 1 OR o.id IS NOT NULL';
            $detail['crm_order'] = $detail['tab_order'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')->where($orderSql)->where($sql5)->group('c.id')->count();
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        //不再追踪
        if(!$tab || $tab == 7){
            $detail['loss'] = $detail['tab_loss'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id', 'left')->join($orderTable,'o.crm_customer_id=c.id', 'left')->where($sqlLoss)->group('c.id')->count();
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';
        //进店未成交
        if(!$tab || $tab == 6){
            $detail['jdwd'] = $detail['tab_jdwd'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id','left')->join($orderTable,'o.crm_customer_id=c.id', 'left')->where(array('is_success'=>2,'is_loss'=>2))->where('is_intostore','in','2,3,5')->where($sql6)->count();//进店未成单
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';

        // 预计今日进店
        if(!$tab || $tab == 12){
            // 今天 明天
            $today = date('Y-m-d 00:00:00');
            $end   = date('Y-m-d 23:59:59');
            $detail['today_yjd'] = $detail['tab_today_yjd'] = db($table)->join('crm_l_pc_log sm','sm.cid=c.id','left')->join($orderTable,'o.crm_customer_id=c.id', 'left')->where('yjd_day', 'between time', [$today, $end])->where($sql12)->count();
        }
        $linkTime .= microtime(true).'==>Line'.__LINE__.';';

        $detail['linkTime'] = $linkTime;

        if (customize('nnqqbaby')) {
            // A/D类客资
            if(!$tab || $tab == 172)
            $today = date('Y-m-d');
            $adWhere = " DATE_FORMAT(c.last_trackday, '%Y-%m-%d')<'$today' AND c.sign_name IN ('A','D') AND c.is_valid IN (1,6)";
            $detail['ad'] = db($table)
                ->where($sql)->where($adWhere)
                ->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->count('c.id');
            $linkTime .= microtime(true).'==>Line'.__LINE__.';';
            // 过保护期客资
            if(!$tab || $tab == 20)
            $detail['sign_protect_num'] = db($table)
                ->where($sql)
                ->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where('sign_id_is_protected',1)->where('sign_time',">",date('Y-m-d',strtotime('-1 years')))
                ->count('c.id');
            // 超期客资  超期未标记客资
            if(!$tab || $tab == 30)
            $detail['valid_status_chaoqi_num'] = db($table)
                ->where($sql)
                ->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where('valid_status_is_chaoqi',1)
                ->where('is_valid',2)
                ->count('c.id');
            //驳回
            if(!$tab || $tab == 27){
                $detail['tab_bohui'] = db($table)
                ->where($sql)
                ->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where('is_valid',4)
                ->count('c.id');

                $detail['tab_bohui_sql'] = db()->getlastsql();
            }
            //反驳回
            if(!$tab || $tab == 28){
                $detail['tab_fanbohui'] = db($table)
                ->where($sql)
                ->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where('is_valid',5)
                ->count('c.id');
            }
            //待判定
            if(!$tab || $tab == 173){
                $detail['no_status'] = db($table)
                ->where($sql)
                ->join($orderTable,'o.crm_customer_id=c.id', 'left')
                ->where('is_valid',2)
                ->count('c.id');
            }
        }


        if (customize('sjzsgbaby')) {
            //预约进店 2021-07-16
            if (!$tab || $tab==211) {
                $sql_tab211 .= " and ci.consulation_shop_code='".session('shop_code')."'";
                $detail['crm_intostore'] = db("crm_c_customer_intostore ci")
                    ->where($sql_tab211)
                    ->count();
            }
        }
        return $detail;
    }

    //客资查询
    function customerSearch($data){
        foreach($data as $k=>$v){
            if($v == 'undefined'){
                unset($data[$k]);
            }
        }
        $arr = [];
        $condition = [];
        $sql = " 1=1 ";
        /**
         * 如果手机号精准搜索，则走这个SQL语句，
         * 需要配置config.ini内的search下的fullmobile=1,
         * 注意：精准查询不判断权限
         * auth:songdemei 20191223
         */
        if(ini('search.fullmobile') && $data['fullmobile']){
            $sqlfull = ' 1=1 ';
            if($data['tab']&&$data['tab']==7){
                $sqlfull .= " and c.is_loss = 1 ";
            }
            //精准查询时，就算是不再追踪，也必出现
            $sqlfull .= ' and (c.customer_tel = "'.$data['fullmobile'].'" or c.mate_tel= "'.$data['fullmobile'].'") ';
            $sqlfull .= " and c.is_status = 1 and c.is_examine=1 ";
            //列表页查询是否包含erp客资设定
            $list_search_is_in_erp = db_config('list_search_is_in_erp');
            if($list_search_is_in_erp != 1){
                $sqlfull .= ' and c.c_from=1 ';
            }
            // $sql .= " and is_status = 1 and is_act=1 ";
            $return[0] = $sqlfull;
            $return[1] = '';
            return $return;
        }

        //2021-07-26 消息弹框入口 k值验证 且tab没有值 消息带有url地址 客资id数据
        $tk_k = $data['tk_k'];
        $tk_id = $data['tk_id'];
        if (!isset($data['tab']) && !empty($tk_k) && !empty($tk_id) && $tk_k == substr(md5($tk_id.session('staff_id').config('SX_AUTH_KEY')),8,16)) {
            $sqltk = " 1=1  and c.id in($tk_id)";
            $return[0] = $sqltk;
            $return[1] = '';
            return $return;
        }

        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']){
                    // $staffIds = controller('crm/Customer')->getDepartmentStaffs($data['department_id']);
                    // $staffIds = array_column($staffIds,'id');
                    // $staffIds = implode(',',$staffIds);
                    // $sql .= " and dj_staff_id in(".$staffIds.")";
                    $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']."' ";//$sql .= " and customer_number = :customer_number ";  $arr['customer_number']=$data['customer_number'];
            if($data['province_id'])       $sql .= " and c.province_id = '".$data['province_id']."' ";//$sql .= " and customer_number = :customer_number ";  $arr['customer_number']=$data['customer_number'];
            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['county_id'])       $sql .= " and c.county_id = '".$data['county_id']."' ";
            if($data['customer_number'])       $sql .= " and c.customer_number like '%".$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 in (".$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['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'].") ";

            // 流失 不在追踪  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 ";
                }
                /*
                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";
                }*/
            }
            // 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) 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']."%') ";
                }
                //*/
                $sql .= " and c.customer_contact like '%".$data['more_like']."%'";
            }
            // 更多选择中 渠道名称下拉框
            if($data['customer_channel']){
                $channel = "'".str_replace(',',"','",$data['customer_channel'])."'";
                $sql .= " and c.customer_channel in (".$channel.") ";
            }else{
                //员工绑定渠道后，只能看到绑定渠道的客资 管理员除外
                $trench = db('crm_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){
                    $def_channel = "'".implode("','",explode(',',$trench))."'";
                    $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 <> '' ";
                        break;
                    case 'get_wechat': $sql .=" and c.customer_wechat is not null and c.customer_wechat != '' ";
                        break;
                    case 'get_qq': $sql .=" and c.customer_qq is not null and c.customer_qq != 0 ";
                        break;
                    case 'get_wechat_on': $sql .=" and c.customer_wechat is not null and c.wechat_status = 2 ";
                        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']."' ";
            }
            $oSql = ' 1=1 ';
            $sql_tab211 = '1=1';
            // // 客资成交/未成交
            // if ($data['is_success']==='0') {
            //     $sql .= " and (o.orderyouxiao = '0' OR o.orderyouxiao='' OR o.orderyouxiao IS NULL) ";
            // }
            // else if ($data['is_success']==='1') {
            //     $sql .= " and o.orderyouxiao = 1 ";
            // }
            // 手机成交3/未成交2
            // else if ($data['is_success']==='2') {
            //     $oSql.=' and o.orderyouxiao=0 ';
            // }else if ($data['is_success']==='3') {
            //     $oSql.=' and o.orderyouxiao=1 ';
            // }

            //2021-04-15 已订单,未成交和已成交的查询，能支持多选
            if (!empty($data['is_success']) || $data['is_success']==='0') {
                $sql .= " and (";
                $success_s = [];
                //未成交
                if (in_array(0, explode(",", $data['is_success']))) {
                    $success_s[] = " o.orderyouxiao IS NULL ";
                }
                //已成交
                if (in_array(1, explode(",", $data['is_success']))) {
                    $success_s[] = " o.orderyouxiao = 1 ";
                }
                //已订单
                if (in_array(3, explode(",", $data['is_success']))) {
                    $success_s[] = " o.orderyouxiao = '0' ";
                }
                $sql .= implode(" OR ", $success_s);
                $sql .= ") ";
            }

            // var_dump($sql);die;
            // 手机号订单收款金额
            if($data['min_money'] && $data['max_money']){
                $oSql .= " and o.payment_money between '".trim($data['min_money'])."' and '".trim($data['max_money'])."' ";
                $sql .= " and o.payment_money between '".trim($data['min_money'])."' and '".trim($data['max_money'])."' ";
            }else if($data['min_money'] && empty($data['max_money'])){
                $oSql .= " and o.payment_money >= '".trim($data['min_money'])."' ";
                $sql .= " and o.payment_money >= '".trim($data['min_money'])."' ";
            }else if(empty($data['min_money']) && $data['max_money']){
                $oSql .= " and o.payment_money <= '".trim($data['max_money'])."' ";
                $sql .= " and o.payment_money <= '".trim($data['max_money'])."' ";
            }
            unset($data['min_money'],$data['max_money']);

            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['sm_status']){
                $sql .= " and sm.status = '".$data['sm_status']."' ";
            }

            if($data['all_time']&&!empty($data['all_time'])){
                if($data['start_time'] && $data['end_time']){
                    if ($data['all_time']=='targetdate') {
                        $sql .= " and o.".$data['all_time']." BETWEEN '".date('Ymd',strtotime($data['start_time']))."' and '".date('Ymd',strtotime($data['end_time'].'-1 day'))."' ";
                    }else if ($data['all_time']=='orderyouxiaodate') {
                        $start= date('Y-m-d 00:00:00',strtotime($data['start_time']));
                        $end  = date('Y-m-d 23:59:59',strtotime($data['end_time'].'-1 day'));
                        $sql .= " and o.".$data['all_time']." BETWEEN '".$start."' and '".$end."' ";
                    }else if ($data['all_time']=='pc_time') {
                        $sql .= " and sm.".$data['all_time']." BETWEEN '".date('Y-m-d',strtotime($data['start_time']))."' and '".date('Y-m-d',strtotime($data['end_time'].'-1 day'))."' ";
                    }else if ($data['all_time']=='brithday_ready_day') {
                        $start= date('Y-m-d 00:00:00',strtotime($data['start_time']));
                        $end  = date('Y-m-d 23:59:59',strtotime($data['end_time'].'-1 day'));
                        $sql .= ' and (c.ready_baby_day BETWEEN "'.$start.'" AND "'.$end.'" OR c.baby_birthday BETWEEN "'.$start.'" AND "'.$end.'") ';
                    }else if ($data['all_time']=='yjd_day') {
                        $start= date('Y-m-d 00:00:00',strtotime($data['start_time']));
                        $end  = date('Y-m-d 23:59:59',strtotime($data['end_time']));
                        $sql_tab211 .= ' and ci.yjd_day BETWEEN "'.$start.'" AND "'.$end.'"';
                    }else if ($data['all_time']=='syjd_day') {
                        $start= date('Y-m-d 00:00:00',strtotime($data['start_time']));
                        $end  = date('Y-m-d 23:59:59',strtotime($data['end_time']));
                        $sql_tab211 .= ' and ci.syjd_day BETWEEN "'.$start.'" AND "'.$end.'"';
                    }else{
                        $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' ";
                    }
                }elseif($data['start_time'] && !$data['end_time']){
                    if ($data['all_time']=='targetdate') {
                        $sql .= " and o.".$data['all_time']." > '".date('Ymd',strtotime($data['start_time'].'-1 day'))."' ";
                    }else if ($data['all_time']=='orderyouxiaodate') {
                        $start= date('Y-m-d 00:00:00',strtotime($data['start_time']));
                        $end  = date('Y-m-d 23:59:59',strtotime($data['end_time'].'-1 day'));
                        $sql .= " and o.".$data['all_time']." BETWEEN '".$start."' and '".$end."' ";
                    }else if ($data['all_time']=='brithday_ready_day') {
                        $start = date('Y-m-d 00:00:00',strtotime($data['start_time']));
                        $sql .= ' and (c.ready_baby_day > "'.$start.'" OR c.baby_birthday > "'.$start.'") ';
                    }else if ($data['all_time']=='yjd_day') {
                        $sql_tab211 .= " and ci.yjd_day > '".date('Y-m-d 00:00:00',strtotime($data['start_time']))."' ";
                    }else if ($data['all_time']=='syjd_day') {
                        $sql_tab211 .= " and ci.syjd_day > '".date('Y-m-d 00:00:00',strtotime($data['start_time']))."' ";
                    }else{
                        $sql .= " and c.".$data['all_time']." > '".date('Y-m-d 00:00:00',strtotime($data['start_time']))."' ";
                    }
                }elseif(!$data['start_time'] && $data['end_time']){
                    if ($data['all_time']=='targetdate') {
                        $sql .= " and o.".$data['all_time']." < '".date('Ymd',strtotime($data['end_time'].'-1 day'))."' ";
                    }else if ($data['all_time']=='orderyouxiaodate') {
                        $start= date('Y-m-d 00:00:00',strtotime($data['start_time']));
                        $end  = date('Y-m-d 23:59:59',strtotime($data['end_time'].'-1 day'));
                        $sql .= " and o.".$data['all_time']." BETWEEN '".$start."' and '".$end."' ";
                    }else if ($data['all_time']=='brithday_ready_day') {
                        $end = date('Y-m-d 23:59:59',strtotime($data['end_time']));
                        $sql .= ' and (c.ready_baby_day < "'.$end.'" OR c.baby_birthday < "'.$end.'") ';
                    }else if ($data['all_time']=='yjd_day') {
                        $sql_tab211 .= " and ci.yjd_day < '".date('Y-m-d 00:00:00',strtotime($data['end_time']))."' ";
                    }else if ($data['all_time']=='syjd_day') {
                        $sql_tab211 .= " and ci.syjd_day < '".date('Y-m-d 00:00:00',strtotime($data['end_time']))."' ";
                    }else{
                        $sql .= " and c.".$data['all_time']." < '".date('Y-m-d 23:59: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 == 'day'){
                        $start=date('Y-m-d 00:00:00');
                        $end=date('Y-m-d 23:59:59');
                    }else{
                        $start=date('Y-m-01');
                        $end=date('Y-m-d 23:59:59');
                    }
                    $sql .= ' and  c.dj_day BETWEEN "'.$start.'"';
                    $sql .= " and  '".$end."'";
                    //2021-07-19 石家庄时光baby 预约进店
                    if ($data['all_time']=='yjd_day') {
                        $sql_tab211 .= " and  c.yjd_day BETWEEN '".$start."' and  '".$end."'";
                    }else if ($data['all_time']=='syjd_day') {
                        $sql_tab211 .= " and ci.syjd_day BETWEEN '".$start."' and  '".$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 == 'day'){
                       $start=date('Y-m-d 00:00:00');
                       $end=date('Y-m-d 23:59:59');
                   }else{
                       $start=date('Y-m-01');
                       $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);
            // exit;
            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) ";
                }
            }
            // 小组
            
            if ($data['customer_channel_list']) {
                $sql .= " and c.customer_channel like '%".$data['customer_channel_list']."%' ";
            }
            // 详细地址
            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 o.orderId like '%".$data['order_number']."%' ";
            // }
            // // 订单金额
            // if ($data['totalpay_money']) {
            //     $sql .= " and o.total_money = '".$data['totalpay_money']."' ";
            // }
            // // 实收金额
            // if ($data['fact_money']) {
            //     $sql .= " and o.payment_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 like '%".$data['introducer_name']."%' ";
            }
            // 老顾客电话
            if ($data['introducer_tel']) {
                $sql .= " and c.introducer_tel like '%".$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['baby_time']) {
                $sql .= " and c.baby_time like '%".$data['baby_time']."%' ";
            }
            // 2020-08-05 推广编号
            if($data['channel_plan_number']){ 
                $sql .= " and c.channel_plan_number = '".trim($data['channel_plan_number'])."' ";
            }
            // 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 ";
            }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{ 777777777
                    $sql .= " and c.is_fp in (2,4) and (o.orderyouxiao = '0' OR o.orderyouxiao='' OR o.orderyouxiao IS NULL)  ";
                // }
            }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 ";
            }elseif($data['tab']&&$data['tab']==5){//成单
                $sql .= " and (o.orderyouxiao=1 OR o.id IS NOT NULL)  ";
            }
            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');
                $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']==15)){
                $sql .= " and  c.is_valid=2 ";
            }
            //驳回客资
            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 ";
            }
            // 孕妈追踪
            else if ($data['tab'] && $data['tab']==21) {
                $ymTimeare = db_config('ymTimeare_'.session('shop_code'));
                if (!$ymTimeare) {
                    $ymTimeare = db_config('default_ymTimeare');
                }
                $t_date = date('Y-m-d 00:00:00', strtotime("+".$ymTimeare['start']." days"));
                $e_date = date('Y-m-d 23:59:59', strtotime("+".$ymTimeare['end']." days"));
                $sql .= ' and c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'"';
                unset($t_date,$e_date);
            }
            // 出生追踪
            else if ($data['tab'] && $data['tab']==22) {
                $csTimeare = db_config('csTimeare_'.session('shop_code'));
                if (!$csTimeare) {
                    $csTimeare = db_config('default_csTimeare');
                }
                $t_date = date('Y-m-d 00:00:00', strtotime("-".$csTimeare['start']." days"));
                $e_date = date('Y-m-d 23:59:59', strtotime("-".$csTimeare['end']." days"));
                $sql .= ' and (c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'" or c.baby_birthday between "'.$t_date.'" and "'.$e_date.'") ';
                unset($t_date,$e_date);
            }
            // 满月追踪
            else if ($data['tab'] && $data['tab']==23) {
                $myTimeare = db_config('myTimeare_'.session('shop_code'));
                if (!$myTimeare) {
                    $myTimeare = db_config('default_myTimeare');
                }
                $t_date = date('Y-m-d 00:00:00', strtotime("-".$myTimeare['start']." days"));
                $e_date = date('Y-m-d 23:59:59', strtotime("-".$myTimeare['end']." days"));
                $sql .= ' and (c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'" or c.baby_birthday between "'.$t_date.'" and "'.$e_date.'") ';
                unset($t_date,$e_date);
            }
            // 百天追踪
            else if ($data['tab'] && $data['tab']==24) {
                $btTimeare = db_config('btTimeare_'.session('shop_code'));
                if (!$btTimeare) {
                    $btTimeare = db_config('default_btTimeare');
                }
                $t_date = date('Y-m-d 00:00:00', strtotime("-".$btTimeare['start']." days"));
                $e_date = date('Y-m-d 23:59:59', strtotime("-".$btTimeare['end']." days"));
                $sql .= ' and (c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'" or c.baby_birthday between "'.$t_date.'" and "'.$e_date.'") ';
                unset($t_date,$e_date);
            }
            // 半岁追踪
            else if ($data['tab'] && $data['tab']==25) {
                $bsTimeare = db_config('bsTimeare_'.session('shop_code'));
                if (!$bsTimeare) {
                    $bsTimeare = db_config('default_bsTimeare');
                }
                $t_date = date('Y-m-d 00:00:00', strtotime("-".$bsTimeare['start']." days"));
                $e_date = date('Y-m-d 23:59:59', strtotime("-".$bsTimeare['end']." days"));
                $sql .= ' and (c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'" or c.baby_birthday between "'.$t_date.'" and "'.$e_date.'") ';
                unset($t_date,$e_date);
            }
            // 周岁追踪
            else if ($data['tab'] && $data['tab']==26) {
                $zsTimeare = db_config('zsTimeare_'.session('shop_code'));
                if (!$zsTimeare) {
                    $zsTimeare = db_config('default_zsTimeare');
                }
                $t_date = date('Y-m-d 00:00:00', strtotime("-".$zsTimeare['start']." days"));
                $e_date = date('Y-m-d 23:59:59', strtotime("-".$zsTimeare['end']." days"));
                $sql .= ' and (c.ready_baby_day between "'.$t_date.'" and "'.$e_date.'" or c.baby_birthday between "'.$t_date.'" and "'.$e_date.'") ';
                unset($t_date,$e_date);
            }
            // A/D类客资 （与登记时间无关，所有标记 ）
            else if ($data['tab'] && $data['tab'] == 172) {
                // $sql .= " AND c.sign_name IN ('A','D') AND c.is_valid IN (1,6) ";
                $today = date('Y-m-d');
                $sql .= " AND DATE_FORMAT(c.last_trackday, '%Y-%m-%d')<'$today' AND c.sign_name IN ('A','D') AND c.is_valid IN (1,6)";
            }
            // 客资标记过保护期
            elseif($data['tab'] && ($data['tab'] == 20)){ 
                // 标记时间小于一年前的客资
                $sign_time = date('Y-m-d',strtotime('-1 years'));
                $sql .= ' and c.sign_id_is_protected=1 and sign_time>"'.$sign_time.'"';
            }
            //驳回
            else if ($data['tab'] && $data['tab']==27) {
                $sql .= " and  c.is_valid=4 ";
            }
            //反驳回
            else if ($data['tab'] && $data['tab']==28) {
                $sql .= " and  c.is_valid=5 ";
            }
            // 超期未标记客资
            elseif($data['tab'] && ($data['tab'] == 30)){ 
                $sql .= ' and c.valid_status_is_chaoqi=1 and c.is_valid=2';
            //未判定
            }elseif ($data['tab'] && $data['tab'] == 173) {
                $sql .= ' and c.is_valid=2 ';
            }
        }
        $sql .= " and c.is_status = 1 and c.is_examine=1 ";

        /*
        if($data['group']){
            $groupIds = [];
            if(session('group_id')){
                $groupIds[] = session('group_id');
            }
            if(session('group_admin')){
                list($groupIds[],$groupIds[]) = explode(',', session('group_admin'));
            }
            $sql .= " and (dj_group_id in (" . implode(',', $groupIds) . ") or sales_group_id in (" . implode(',', $groupIds) . ") )";
        }
        if($data['dep']){
            $sql .= ' and (c.dj_department_id='.session('department_id').' or c.sales_department_id='.session('department_id').')';
        }
        */
        // */
        if($data['fullmobile']){
            $sql = ' c.customer_tel = "'.$data['fullmobile'].'" or c.mate_tel= "'.$data['fullmobile'].'" ';
            $sql .= " and c.is_status = 1 and c.is_examine=1 ";
        }
        //列表页查询是否包含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 in (1,3) ';
        }else{
            $sql .= ' and c.c_from in (1,2,3) ';
        }
        // $sql .= " and is_status = 1 and is_act=1 ";
        $return[0] = $sql;
        $return[1] = $oSql;
        $return[2] = $sql_tab211;
        return $return;
    }

    //所有客资
    function allCrm($staffId){
        $res = db('CrmCCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_status'=>1))->count();
        return $res;
    }
    //已订单
    function orderCrm($staffId){
        $res = db('CrmCCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_success'=>1,'is_status'=>1))->count();
        return $res;
    }
    //待追踪
    function noStaffId($staffId){
        // $res = db('CrmCCustomerinfo')->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('CrmCCustomerinfo')
            ->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('crm_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 jrCustomers_not($param){
        $where = [
            'is_status' => 1,
            'c_from'    => 1,
            'is_fp'     => 1,
            'brandclass_id' => session('brandclass_id')
        ];
        $res = db('crm_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'])
            ->field('dj_staff_id,sales_staff_id')
            ->select();
        $ros = [];
        foreach ($res as $key => $value) {
            $ros[$value['sales_staff_id']] += $value['sales_staff_id'] == $value['dj_staff_id'] ? 0 : 1;
        }
        // echo db()->getLastSql();
        return $ros;
    }
    // 筛客人接收到的客资数量
    // public function skCustomers($param){
    //     $where = [
    //         'is_status' => 1,
    //         'c_from'    => 1,
    //         'brandclass_id' => session('brandclass_id'),
    //     ];
    //     $res = db('crm_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('CrmCCustomerinfo')->where('dj_staff_id',$staffId)->where('is_fp','in','2,4')->where('is_status',1)->count();
        return $res;
    }

    //追踪中
    function traking($staffId){
        $res = db('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('crm_s_shop_address')->where($data)->select();

        return $detail;
    }
    //查询crm地址
    function crm_address($data){
        $detail = db('crm_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'].'%'];
        }
        //取crm设定的省市区
        $detail = db('crm_s_shop_address')->where($name,$nameArray)->where($data)->select();
        return $detail;
    }
    //客户地址查询
    function getCity($data){
        $url="59fd885ed3628";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $detail=$res['data'];
        }
        return $detail;
    }
    //通过省id获取地域
    function getRegionByProvinceId($data){
        $url="5a704aa96e503";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $detail=$res['data'];
        }
        return $detail;
    }
    //店面查询
    function shop($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->getAllStaffList($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){
        $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){
        $sign_name = cache('crm_sign_'.$shop_code);//客资标记
        $package_name = cache('crm_packageName_'.$shop_code);//客资标记
        // $channel   = cache('crm_channel_'.$add_shop_code);//客户渠道
        //$channel = getChannels($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');
        $brand=cache('crm_brand');
        // 追踪人
        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']='';
        }
        // 医拍摄影师   20200615
        if(isset($data['hospital_photo_cameraman']) && !empty($data['hospital_photo_cameraman'])){
            $p['shop_code'] = $shop_code;
            $p['work_type'] = PZ_WORK_TYPE;
            $hhc_staffs = getShopStaffs($p);
            $temp = [];
            foreach($hhc_staffs as $k=>$v){
                $temp[$v['staffname']] = $v;
            }
            if(!empty($temp[$data['hospital_photo_cameraman']])){
                $ids['hospital_photo_cameraman_id'] = $temp[$data['hospital_photo_cameraman']]['id'];
                unset($p,$hhc_staffs,$temp);
            }else{
                $ids['hospital_photo_cameraman_id']=null;
            }
        }else{
            $ids['hospital_photo_cameraman_id']=null;
        }
        // 医拍摄影助理
        if(isset($data['hospital_photo_assistant']) && !empty($data['hospital_photo_assistant'])){
            $p['shop_code'] = $shop_code;
            $p['work_type'] = SYZL_WORK_TYPE;
            $hpa_staffs = getShopStaffs($p);
            $temp = [];
            foreach($hpa_staffs as $k=>$v){
                $temp[$v['staffname']] = $v;
            }
            if(!empty($temp[$data['hospital_photo_assistant']])){
                $ids['hospital_photo_assistant_id'] = $temp[$data['hospital_photo_assistant']]['id'];
                unset($p,$hpa_staffs,$temp);
            }else{
                $ids['hospital_photo_assistant_id']=null;
            }
        }else{
            $ids['hospital_photo_assistant_id']=null;
        }
        // 推广人
        if(isset($data['recommend_staff']) && !empty($data['recommend_staff'])){
            $p['shop_code'] = $shop_code;
            $p['work_type'] = KZTB_WORK_TYPE;
            $tgr_staffs = getShopStaffs($p);
            $temp = [];
            foreach($tgr_staffs as $k=>$v){
                $temp[$v['staffname']] = $v;
            }
            if(!empty($temp[$data['recommend_staff']])){
                $ids['recommend_staff_id'] = $temp[$data['recommend_staff']]['id'];
                unset($p,$tgr_staffs,$temp);
            }else{
                $ids['recommend_staff_id']=null;
            }
        }else{
            $ids['recommend_staff_id']=null;
        }
        // 客资标记   20200615    
        if($data['sign_name']){
            if(!$sign_name){
                $sign_name = db('crm_s_tracksign')->where('shop_code',$shop_code)->select();
                cache('crm_sign_'.$shop_code,$sign_name);
            }
            foreach($sign_name as $key => $val){
                if($data['sign_name']==$val['tracksign']){
                    $ids['sign_id']=$val['id'];
                }
            }
        }
        // 意向套系
        if($data['package_name']){
            if(!$package_name){
                //意向套系
                $erpInterface = new \app\common\lib\erpInterface(['shop_type'=>$shop_code]);        
                $orderInfo = $erpInterface->getCreateOrderInfo(['shop_code'=>$shop_code]);
                $orderInfo['dt_s_packageset'] = my_sort($orderInfo['dt_s_packageset'],'package_price','SORT_ASC');
                $package_name = $orderInfo['dt_s_packageset'];
                cache('crm_packageName_'.$shop_code,$package_name);
            }
            foreach($package_name as $key => $val){
                if($data['package_name']==$val['package_name']){
                    $ids['package_name']=$val['package_name'];
                }
            }
        }

        // 渠道名称
        if($data['customer_channel']){
            /*
            if(!$channel){
                $findSql = ' FIND_IN_SET("'.$add_shop_code.'",share_shops) ';
                $channel=db('crm_s_channel')->where($findSql)->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']){
            if(!$consulation_shop){
                $consulation_shop=$this->shop(array('is_marketing'=>2));
                cache('crm_consulation_shop',$consulation_shop);
            }
            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'];
                }
            }
        }


        // 南宁qqbaby  2021-03-15
        if (customize('nnqqbaby')) {
            if($data['b_name']){
                if(!$brand){
                    $brand = db('crm_s_brandset')->select();
                    cache('crm_brand',$brand);
                }
                foreach($brand as $key => $val){
                    if($data['b_name']==$val['name']){
                        $ids['b_id']=$val['id'];
                    }
                }
            }
        }

        cache('ids',$ids);
        return $ids;
    }

    //验证手机号和名字重复
    function checkNameTel($param){
        $count = db("crm_c_customerinfo")->where('customer_tel',$param['customer_tel'])->count();
        return $count;
    }
    //查询归属店是否筛客
    public function is_sk($belong_shop_code){
        $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';
        $res = sx_call($url,array('shop_code'=>$param,'work_type'=>$workType));
        // var_dump($res);die;
        if($res['code'] == 200){
            return $res['data'];
        }else{
            return false;
        }
    }
    /**
     * 客户、获取  排重方法，6+1  
     * @param customer_tel      母亲手机 tel
     * @param customer_wechat   母亲微信 wechat
     * @param mate_tel          父亲手机 mate_tel
     * @param mate_wechat       父亲微信 mate_wechat
     * @param customer_channel  渠道
     * @param brandclass        事业部
     * @param brandclass_id     事业部id 
     *
     * @return 
     */
    // public function isRepeat($id=0,$brandclass,$tel,$wechat,$mate_tel,$mate_wechat,$customer_channel){
    // public function isRepeat_old($brandclass,$tel,$wechat,$qq,$mate_tel,$id=0,$mate_wechat,$customer_channel='',$orz=[]){
    //     //判断 mc客资有效期配置 为空的话 不限制
    //     //客资过期时间
    //     $key = 'brand_valid_date_'.md5($brandclass);
    //     $valid_date = cache($key);
    //     if(!$valid_date && $valid_date!==0){
    //         $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($wechat){
    //         $contact[] = $wechat;
    //     }
    //     if($mate_tel){
    //         $contact[] = $mate_tel;
    //     }
    //     if($mate_wechat){
    //         $contact[] = $mate_wechat;
    //     }
    //     if(!$contact){
    //         return array('code'=>202,'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.') ';
    //     }
    //     if (!$customer_channel) {
    //         $customer_channel = '';
    //     }
        
    //     $c_ids = db('crm_c_customer_contact')
    //         ->where($sql1)
    //         ->where('contact','in',$contact)
    //         ->where('customer_channel',$customer_channel)
    //         ->where('brandclass',$brandclass)
    //         ->order('id desc')->column('c_unique, c_id','id');
    //     // echo db()->getLastSql();
    //     // var_dump($c_ids);
    //     // exit;
    //     if(empty($c_ids)){
    //         $c_unique = db('crm_c_customer_main')->where('wphone|wwechat|mphone|mwechat','in',$contact)->order('update_time desc')->value('c_unique');
    //         unset($contact);
    //         return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'', 'c_unique'=>$c_unique);
    //     }else{
    //         $c_uniques = [];
    //         foreach ($c_ids as $key => $value) {
    //             $c_uniques[] = $value['c_unique'];
    //         }
    //         $c_uniques = array_unique($c_uniques);
            
    //         // 重复渠道不可录入 设定为，是，既重复渠道可不录入
    //         if (db_config('more_channel_'.$orz['add_shop_code']) == 1) {
    //             $tempids = db('c_customer_contact t')
    //                 ->join('c_customerinfo c','c.id=t.c_id','left')
    //                 ->where('t.c_unique', 'in',$c_uniques)
    //                 // ->where('t.contact','in',$contact)
    //                 ->where('t.brandclass',$brandclass)
    //                 ->where('c.add_shop_code',$orz['add_shop_code'])
    //                 ->column('t.c_id');
    //         }else{
    //             $tempids = db('crm_c_customer_contact')
    //                 ->where('c_unique', 'in',$c_uniques)
    //                 ->where('customer_channel',$customer_channel)
    //                 ->where('brandclass',$brandclass)
    //                 ->column('c_id');
    //         }
    //         // echo db()->getLastSql();
    //         // exit;
    //         $tempids = array_unique($tempids);
    //         $repeatArr= db("crm_c_customerinfo")->where('id','<>',$id)
    //             ->where('id','in',$tempids)->where('is_status',1)->where($sql1s)
    //             ->field('id,c_unique,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')->master()->order('id desc')->find();

    //         unset($contact,$c_ids,$c_uniques,$tempids);
    //         if ($repeatArr) {
    //             return array('code'=>201,'msg'=>'客资重复，不可录入','data'=>$repeatArr,'c_unique'=>$repeatArr['c_unique']);
    //         }else{
    //             return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'','c_unique'=>$repeatArr['c_unique']);
    //         }

    //         /*
    //         $ros = db('crm_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($sql1s)->where('customer_tel|customer_wechat|mate_tel|mate_wechat','in',$contact)->find();
    //         if ($ros) {
    //             return array('code'=>201,'msg'=>'客资重复，不可录入','data'=>$ros);
    //         }
    //         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;
    //         }

    //         $sql = ' 1=1 ';

    //         //判断是否成单一月以上
    //         $order = db('crm_c_customerinfo')->where('id','in',$c_ids)->order('id desc')->find();
    //         if($valid_date == 0){//为0,则永不过期
    //             $arr= db("crm_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)->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("crm_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($where)->where($whereRepeat)->master()->order('id desc')->find();
    //         if($arr){
    //             return array('code'=>201,'msg'=>'未过有效期,不能录入','data'=>$arr);
    //         }else{
    //             $valid_date_notice = db_config('valid_date_notice');
    //             if($valid_date_notice) { //客资过期是否提示
    //                 return array('code'=>205,'msg'=>'与该联系方式重复的客资已过期,可以录入');
    //             }else{
    //                 return array('code'=>200,'msg'=>''.db()->getLastSql(),'data'=>''.json_encode($arr));
    //             }
    //         }
    //         */
    //     }
    // }

    /**
     * 客户、获取  排重方法， 新的  
     * @param orz    组织结构，目前是add_shop_code,shop_code,brandclass
     * @param con    联系方式，父母手机号及微信
     * @param other  其他排重条件，目前是渠道
     * @param cid    客资id
     *
     * @return 
     */
    public function isRepeat($orz=[],$con=[],$other=[],$cid=0){
        // 如果是 成都天使印象 并且有 无限制录入客资权限
        //< if (customize('cdtsyx') && check_right('menu1512970661')) {
        //<     return array('code'=>200,'msg'=>'1','data'=>[]);
        //< }

        // 如果是 南宁qqbaby  2021-03-12   
        /* 南宁的规则还走通用的， 
        if (customize('nnqqbaby')) {
            $brandclass = $orz['brandclass'] ? $orz['brandclass'] : session('brandclass');
            $shop_code = $orz['shop_code'] ? $orz['shop_code'] : session('shop_code');
            // 根据 add_shop_code 判断使用哪个 排重方法 20200514
            $repRuleCode = config('add_report_shop');
            // 规则2 
            if ( strpos($repRuleCode[2],$shop_code) !== false) {
                $res = $this->isRepeatRuleTwo($brandclass,$con['customer_tel'],$con['customer_wechat'],$con['customer_qq'],$con['mate_tel'],$cid,$shop_code,$con['consultation_type_id']);
                return $res;
            }
            // 规则1
            else {
                $res = $this->isRepeatRuleOne($brandclass,$con['customer_tel'],$con['customer_wechat'],$con['customer_qq'],$con['mate_tel'],$cid,$shop_code,$con['consultation_type_id']);
                return $res;
            }
            exit;
        }else{
            unset($con['customer_qq']);
            unset($con['consultation_type_id']);
        }
        */
        $brandclass = $orz['brandclass'] ? $orz['brandclass'] : session('brandclass');
        //判断 mc客资有效期配置 为空的话 不限制
        //客资过期时间
        $key = 'brand_valid_date_'.md5($brandclass);
        $valid_date = cache($key);
        if(!$valid_date && $valid_date!==0){
            $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'=>[]);
        }
        
        $array=array();


        // 查看排重字段
        $exclusion_field = config('exclusion_field');
        if($con['customer_tel'] && in_array('customer_tel', $exclusion_field)){
            $contact[] = trim($con['customer_tel']);
        }
        if($con['customer_wechat'] && in_array('customer_wechat', $exclusion_field)){
            $contact[] = trim($con['customer_wechat']);
        }
        if($con['mate_tel'] && in_array('mate_tel', $exclusion_field)){
            $contact[] = trim($con['mate_tel']);
        }
        if($con['mate_wechat'] && in_array('mate_wechat', $exclusion_field)){
            $contact[] = trim($con['mate_wechat']);
        }
        if(!$contact){
            /******            2021-05-07 参与排重的字段 如果一个也没有填 不影响也可以录入              *********/
            return array('code'=>202,'msg'=>'缺少联系方式','data'=>[]);
            // return array('code'=>200,'msg'=>'缺少联系方式','data'=>[]);
        }
        // var_dump($contact);
        // 编辑的时候， 排除自己
        $sql1 = " 1=1 ";
        if($cid){
            $sql1 .= ' and (c_id is null or c_id <> '.$cid.') ';
        }
        // 判断使用哪种方式排重（6+1方式，使用渠道排重； 小阿福方式，通过一胎/二胎方式）
        // $repeat_way = config('repeat_way');
        $repeat_way = db_config('customer_repeat_method');
        $repeat_way = $repeat_way?$repeat_way:config('repeat_way');
        if ($repeat_way == '6j1') {
            $customer_channel = $other['channel'] ? $other['channel'] : '';
        }else if ($repeat_way == 'xaf') {
            $customer_channel = $other['baby_time'] ? $other['baby_time'] : '一胎';
        }else{
            $customer_channel = $other['channel'] ? $other['channel'] : '';
            $customer_channel = '';
        }
        
        // 重复渠道不可录入的店
        $exclusion_channel = config('exclusion_channel');
        if (customize('nnqqbaby') || in_array($orz['add_shop_code'], $exclusion_channel)) {
            $c_ids = db('crm_c_customer_contact t')
                ->join('crm_c_customerinfo c','c.id=t.c_id','left')
                ->where($sql1)
                ->where('t.contact','in',$contact)
                // ->where('customer_channel',$customer_channel)
                ->where('t.brandclass',$brandclass)
                ->where('c.add_shop_code',$orz['add_shop_code'])
                ->order('t.id desc')->column('t.c_unique, c_id','t.id');
            $sql = db()->getLastSql();
        }else{
            if($repeat_way == 'all'){
                $c_ids = db('crm_c_customer_contact')
                    ->where($sql1)
                    ->where('contact','in',$contact)
                    ->where('brandclass',$brandclass)
                    ->order('id desc')->column('c_unique, c_id','id');
            }else{
                $c_ids = db('crm_c_customer_contact')
                    ->where($sql1)
                    ->where('contact','in',$contact)
                    ->where('customer_channel',$customer_channel)
                    ->where('brandclass',$brandclass)
                    ->order('id desc')->column('c_unique, c_id','id');
            }
            $sql = db()->getLastSql();
        }
        /*
        if (session('staff_name')=='eric') {
            var_dump($c_ids);
            var_dump($sql);die;
        }
        */
        if(empty($c_ids)){
            $c_unique = db('crm_c_customer_main')->where('wphone','in',$contact)->order('update_time desc')->value('c_unique');
            unset($contact);
            return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'', 'c_unique'=>$c_unique,'sql'=>$sql);
        }else{
            $tempids = array_column($c_ids, 'c_id');
            
            //取排重范围状态
            $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($valid_date === 0){
                $wheretime = ' 1=1 ';
            }else{
                $lastDate = date('Y-m-d H:i:s',time() - ($valid_date * 86400));
                //客资过期判定规则
                $rule = db_config('valid_date_rule');
                $rule = $rule ? $rule : 'dj_day';
                $wheretime = ' '.$rule.' is null or '.$rule.' > \''.$lastDate.'\'';
            }
            $repeatEdit = config('repeat_edit_shop');
            //如果配置了这个参数，则表示在录入时，如果有重复的客资，直接找出来进行列新，
            //所以这里面会判断重复，然后面录入客资的界面，如果重了，直接更新。
            if(in_array($orz['add_shop_code'], $repeatEdit)){
                $whereRepeat = $wheretime = '';
            }

            // echo db()->getLastSql();
            // exit;
            $tempids = array_unique($tempids);
            $repeatArr= db("crm_c_customerinfo")
                ->where('id','in',$tempids)
                ->where('id','<>',$cid)
                ->where($whereRepeat)
                ->where($wheretime)
                ->where('is_status',1)
                ->where('c_from',1)
                ->field('id,c_unique,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')->master()->order('id desc')->find();

            /*
            if (session('staff_name')=='eric') {
                var_dump($repeatArr);
                var_dump(db()->getLastSql());die;
            }
            */
            $sql = db()->getLastSql();
            unset($contact,$c_ids,$c_uniques,$tempids);
            if ($repeatArr) {
                return array('code'=>201,'msg'=>'客资重复，不可录入','data'=>$repeatArr,'c_unique'=>$repeatArr['c_unique'],'sql'=>$sql);
            }else{
                return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'','c_unique'=>$repeatArr['c_unique'],'sql'=>$sql);
            }
        }
    }

    // 分配规则一  电销部 本店内不能重复，
    public function isRepeatRuleOne($brandclass,$tel,$wechat,$mate_tel,$mate_wechat,$id=0,$shop_code = '',$cus_info){
        if($tel){
            $contact[] = $tel;
        }
        if($wechat){
            $contact[] = $wechat;
        }
        if($mate_tel){
            $contact[] = $mate_tel;
        }
        if(!$contact){
            return array('code'=>199,'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('crm_c_customer_contact')->where($sql1)->where('contact','in',$contact)->where('add_shop_code',$shop_code)->order('id desc')->column('c_id');南宁版customer_channel存储的是shop_code
        $c_ids = db('crm_c_customer_contact')->where($sql1)->where('contact','in',$contact)->where('customer_channel',$shop_code)
            ->order('id desc')->column('c_id');
        // echo db()->getLastSql();die;
        if(empty($c_ids)){
            return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
        }else{
            $ros = db('crm_c_customerinfo')
                ->field('id,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_name,customer_number,mate_tel,mate_name,baby_name,baby_sex,baby_birthday,province,city,county,customer_address,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('c_from', '1')
                // ->where('is_liuzhuan',1)
                ->where($sql1s)
                ->where('id', 'in', $c_ids)
                ->order('id desc')
                // ->where('customer_tel|customer_wechat|mate_tel','in',$contact)
                ->select();
            // echo db()->getLastSql();die;
            if ($ros) {
                // if (count($ros)>0) {
                //     foreach ($ros as $key => $value) {
                //         $this->supplement($value,$cus_info);
                //     }
                // }
                
                return array('code'=>201,'msg'=>'客资重复，不可录入','data'=>$ros);
            }else{
                return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
            }
        }
    }
    // 分配规则二  电商部 本店内可以重复录入，规则如下 且不能遵循 系统设定（重新分配会情况状态及标记）
        // 标记无效的客资，超过3天允许录入
        // 录入七天内未判定 ABC客 不允许录入，超过七天允许录入 
        // 根据客资标记设定的保护期 ，保护期内不允许录入  超过保护期，允许录入 不限定渠道等
    public function isRepeatRuleTwo($brandclass,$tel,$wechat,$mate_tel,$mate_wechat,$id=0,$shop_code = '',$cus_info){
        if($tel){
            $contact[] = $tel;
        }
        if($wechat){
            $contact[] = $wechat;
        }
        if($mate_tel){
            $contact[] = $mate_tel;
        }
        if(!$contact){
            return array('code'=>199,'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('crm_c_customer_contact')->where($sql1)->where('contact','in',$contact)->where('add_shop_code',$shop_code)->order('id desc')->column('c_id');南宁版customer_channel存储的是shop_code
        $c_ids = db('crm_c_customer_contact')->where($sql1)->where('contact','in',$contact)->where('customer_channel',$shop_code)
            ->order('id desc')->column('c_id');
        if(empty($c_ids)){
            return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
        }else{
            // 查最后一条重复的客资 
            $res = db("crm_c_customerinfo")
                ->field('id,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_name,customer_number,mate_tel,mate_name,baby_name,baby_sex,baby_birthday,province,city,county,customer_address,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,is_valid,yx_day,sign_id,sign_name,sign_time')
                ->where('is_status',1)->where('c_from', '1')
                ->where($sql1s)
                ->where('id', 'in', $c_ids)
                ->order('id desc')
                // ->where('customer_tel|customer_wechat|mate_tel','in',$contact)
                ->find();
            // echo db()->getLastSql();die;
            $today = date('Ymd');
            if ($res) {
                // 无效客资 标记无效日期加3天小于等于今天 可以录入 否则不允许录入
                if ($res['is_valid'] == 3) {
                    $yx_day = date("Ymd",strtotime("+3 day",strtotime($res['yx_day'])));
                    if ($yx_day<=$today) {
                        return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
                    }else{
                        return array('code'=>201,'msg'=>'无效客资未超过3天','data'=>$res);
                    }
                }
                // 待定 登记日期加7天 小于等于今天 可以录入 否则不允许录入
                else if ($res['is_valid']==2) {
                    return array('code'=>201,'msg'=>'待定客资不允许重复录入','data'=>$res);
                    /*
                    $dj_day = date("Ymd",strtotime("+7 day",strtotime($res['dj_day'])));
                    if ($dj_day<=$today) {
                        return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
                    }else{
                        return array('code'=>201,'msg'=>'录入未超过7天','data'=>$res);
                    }*/
                }
                // 有效 判断 AB类，30天后允许重复录入  C类，10天后允许重复录入  D类，7天后允许重复录入 成交类，跨月允许重复录入 其他，跨月允许重复录入
                else if ($res['is_valid']==1) {

                    if ($res['sign_name']=='A' || $res['sign_name']=='B') {
                        $sign_time = date("Ymd",strtotime("+30 day",strtotime($res['sign_time'])));
                        if ($sign_time<=$today) {
                            return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
                        }else{
                            return array('code'=>201,'msg'=>'标记为A/B['.$res['sign_time'].']的客资暂时不允许录入','data'=>$res);
                        }
                    }elseif ($res['sign_name']=='C') {
                        $sign_time = date("Ymd",strtotime("+10 day",strtotime($res['sign_time'])));
                        if ($sign_time<=$today) {
                            return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
                        }else{
                            return array('code'=>201,'msg'=>'标记为C['.$res['sign_time'].']的客资暂时不允许录入','data'=>$res);
                        }
                    }elseif ($res['sign_name']=='D') {
                        $sign_time = date("Ymd",strtotime("+7 day",strtotime($res['sign_time'])));
                        if ($sign_time<=$today) {
                            return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
                        }else{
                            return array('code'=>201,'msg'=>'标记为D['.$res['sign_time'].']的客资暂时不允许录入','data'=>$res);
                        }
                    }elseif ($res['sign_name']=='成交') {
                        $sign_time = date("Ym",strtotime(strtotime($res['sign_time'])));
                        if (date('Ym')>$sign_time) {
                            return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
                        }else{
                            return array('code'=>201,'msg'=>'标记为成交['.$res['sign_time'].']的暂时不允许录入','data'=>'');
                        }
                    }else{
                        $sign_time = date("Ym",strtotime(strtotime($res['sign_time'])));
                        if (date('Ym')>$sign_time) {
                            return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
                        }else{
                            return array('code'=>201,'msg'=>'标记为'.$res['sign_name'].'['.$res['sign_time'].']的暂时不允许录入','data'=>'');
                        }
                    }
                    /*
                    $sign_time = date("Ymd",strtotime("+$sign_por_day day",strtotime($res['sign_time'])));
                    
                    if ($sign_time<=$today) {
                        return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
                    }else{
                        return array('code'=>201,'msg'=>'未过客资保护期','data'=>$res);
                    }
                    */
                }
                // 驳回反驳回
                else if ($res['is_valid']==4 || $res['is_valid']==5) {
                    return array('code'=>201,'msg'=>'驳回或反驳回的客资，不允许录入','data'=>$res);
                }
                // 不算的客资 15天后允许重复录入
                else if ($res['is_valid']==6) {
                    $yx_day = date("Ymd",strtotime("+15 day",strtotime($res['yx_day'])));
                    if ($yx_day<=$today) {
                        return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
                    }else{
                        return array('code'=>201,'msg'=>'不算客资未超过15天','data'=>$res);
                    }
                }
                // 其他情况 
                else{
                    return array('code'=>201,'msg'=>'争议客资，不允许录入','data'=>$res);
                }
            }else{
                return array('code'=>200,'msg'=>'客资未重复，可以录入','data'=>'');
            }
        }
    }

    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('crm_c_customer_contact')->where('brandclass',$brandclass)->where('contact','in',$sql)->select();
        //$a=db()->getLastSql();
        return $arr;
    }

    /*
     * 补充客资信息
     * $old     原本客资信息
     * $new     新录入客资信息
     * $sql1s   客资判重sql
     * $contact 客资判重联系信息
     * $consultation_type_id  消费类型
     */
    public function supplement($old,$new){
        $updateData = [];
        if(empty($old['customer_name']) && !empty($new['customer_name'])){
            $updateData['customer_name'] = $new['customer_name'];
        }
        if(empty($old['customer_wechat']) && !empty($new['customer_wechat'])){
            $updateData['customer_wechat'] = $new['customer_wechat'];
        }
        if(empty($old['customer_qq']) && !empty($new['customer_qq'])){
            $updateData['customer_qq'] = $new['customer_qq'];
        }
        if(empty($old['customer_weibo']) && !empty($new['customer_weibo'])){
            $updateData['customer_weibo'] = $new['customer_weibo'];
        }
        if(empty($old['mate_tel']) && !empty($new['mate_tel'])){
            $updateData['mate_tel'] = $new['mate_tel'];
        }
        if(empty($old['mate_name']) && !empty($new['mate_name'])){
            $updateData['mate_name'] = $new['mate_name'];
        }
        if(empty($old['baby_name']) && !empty($new['baby_name'])){
            $updateData['baby_name'] = $new['baby_name'];
        }
        if(empty($old['baby_sex']) && !empty($new['baby_sex'])){
            $updateData['baby_sex'] = $new['baby_sex'];
        }
        if(empty($old['baby_birthday']) && !empty($new['baby_birthday']) && $new['baby_birthday'] != '1970-01-01'){
            $updateData['baby_birthday'] = $new['baby_birthday'];
        }
        if(empty($old['customer_address']) && !empty($new['customer_address'])){
            $updateData['customer_address'] = $new['customer_address'];
        }
        // /*
        //客资标记不是有效的话 修改追踪人
        if($old['is_valid']!=1 && !empty($new['sales_staff'])){
            $updateData['sales_staff'] = $new['sales_staff'];

            $get_set['sales_staff'] = $new['sales_staff'];
            // 员工信息
            $sales_staf_arr = $this->get_set_id($get_set);
            $updateData['sales_staff_id'] = $sales_staf_arr['sales_staff_id'];
            $updateData['sales_staff_number'] = $sales_staf_arr['sales_staff_number'];
        }
        // */
        $address=cache('crm_address');
        if(!$address){
            $url="59fd885ed3628";
            $res=sx_call($url,[]);
            if($res['code']==200){
                $address=$res['data'];
                cache('crm_address',$address);
            }
        }
        if(empty($old['province']) && !empty($new['province'])){
            foreach($address as $k => $v){
                if($new['province']==$v['name']){

                    $updateData['province_id'] = $v['id'];
                    $updateData['province'] = $new['province'];

                }
            }
        }
        if(empty($old['city']) && !empty($new['city'])){
            foreach($address as $k => $v){
                if($new['city']==$v['name']){
                    $updateData['city_id'] = $v['id'];
                    $updateData['city'] = $new['city'];
                }
            }
        }
        if(empty($old['county']) && !empty($new['county'])){
            foreach($address as $k => $v){
                if($new['county']==$v['name']){
                    $updateData['county_id'] = $v['id'];
                    $updateData['county'] = $new['county'];
                }
            }
        }
        
        db()->startTrans();
        try {
            $res = db('crm_c_customerinfo')
                ->where('id',$old['id'])
                ->update($updateData);
            history_log($updateData,$old,$old['id'],$old['dj_staff_id'],$old['dj_staff_name'],'CRM','Customer','import');
            db()->commit();
            return true;
        } catch (\Exception $e) {
            db()->rollback();
            return false;
        }
    }

    //客资录入
    /*
    function addCustomer($data){
        // var_dump($data);exit;
        //转介绍次数
        $num = db_config('zhuanjieshao_number_'.session('shop_code'));
        $count = db('crm_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){
            if(empty($data['customer_channel_id'])){
                $data['customer_channel_id'] = -1;
            }
            if(empty($data['customer_channel'])){
                $data['customer_channel'] = '空渠道';
            }
            if( !empty($data['introducer_tel']) && $num && $count>$num){
                return array('code'=>121,'msg'=>'今天转介绍次数已达上限,不能提报');
            }
        }

        $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['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['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'];
        }

        //提报类型（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']);
        
        //插入手机号时，查询归属地，区号等
        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);

        $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'];
            }
        }

        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/>";
        }
        $orz['add_shop_code'] = $data['add_shop_code'];
        $orz['shop_code'] = $data['shop_code'];

        $rep = $this->isRepeat($data['brandclass'], $data['customer_tel'],$data['customer_wechat'], $data['customer_qq'],$data['mate_tel'],'',$data['consultation_type_id'],$orz);
        //是否开启客资重复审核
        $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/>";
                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 .= '请核对信息后再录入';

                    //记追踪记录
                    $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('CrmCSalestrackinginfo')->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'].' ]录入过，并且分配给了[ '.$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'].' ]录入过，未进行分配');
                }
                var_dump($returnData);
                exit;
                return $returnData;
            }
        }

        // 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');
            //小组信息
            $groupInfo = getGroupInfo($data['dj_staff_id']);
            if(!empty($groupInfo)){
                $data['dj_group_id'] = $groupInfo['id'];
                $data['dj_group_name'] = $groupInfo['group_name'];
            }
            $res=db('CrmCCustomerinfo')->insert($data);
            $customerId = db()->getLastInsID();

            if($customerId){
                //录入日志
                $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/>';
                }
                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/>';
                }

                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');
               }
            }
            foreach($contact as $k => $v){
                $contactList[$k]['c_id']=$customerId;
                $contactList[$k]['contact']=$v;
                $contactList[$k]['brandclass']=$data['brandclass'];
            }
            $res = db('crm_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);
            }
            // $errId++;
            // if($record['sales_remark']){
            //$customerInfo=db('CrmCCustomerinfo')->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('crm_c_salestrackinginfo')->insert($record);
                getSalesTracking($customerId);
                // $errId++;
            }
            //发送短信
            if($sms_model && $is_send_msg){
                $send_msg = db('crm_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('code'=>105,'msg'=>'客资录入失败','data'=>$e->getMessage());
        }
        if($doub == 1 && $examine == 1){
            //如果是重复的待审核客资,发消息
            // 发送消息用数据
            $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 && $examine == 0){//未重复的客资
            // $staff_id, $staff_name, $staff_number, $shop_code,$identity, $cid, $old_data, $new_data
            // 如果提报人的工作类型是话务(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']) {
                // 分配  用数据
                $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'] = $data['dj_department_id'];

                db('crm_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('crm_c_customerinfo')->where('id',$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('crm_c_customerinfo')->where('id',$customerId)->update($upgroup);
                        }
                        $resLog = fpLogs($fpLogData);
                    }
                }
            }
            return $customerId;
        }
        return $customerId;
    }
    */

    /*
     *   客资录入
     *
     *  转介绍客资次数(数量)验证
     *  验证各种信息的准确性(消费类型，客户来源，渠道名称等)
     *  格式化要进入数据库的数据
     *  开启事务
     *  try catch
     *  不管是不是重复客资，后来的数据要更新到新客户上，如果没有客户，要新建一个客户
     *  先进主表，在进客资表，排重表，追踪记录，操作日志 
     *  看看登记和追踪人是否为同一人，否则根据设定发送弹窗、模板消息，如果没有，看看有没有自动分配，
     *  如果有追踪人(如果没有追踪人当前人为话务)，记录分配日志，追踪记录，
     *  看看有没有录入短信，发短信  
     */
    function addCustomer_child($data){
        $now = date('Y-m-d H:i:s',time());
        //转介绍次数
        $num = db_config('zhuanjieshao_number_'.session('shop_code'));
        $count = db('crm_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'=>'今天转介绍次数已达上限,不能提报');
        }
        //渠道绑定标记
        if(!$data['sign_id'] && $data['customer_channel_id'] && $data['customer_type'] == 1){
            $channel = db('crm_s_channel')->where('id',$data['customer_channel_id'])->where("find_in_set('".$data['add_shop_code']."',share_shops)")->find();
            $data['sign_id'] = $channel['sign_id'];
            $data['sign_name'] = $channel['sign_name'];
        }
        $data['baby_name']     = trim(strip_tags($data['baby_name']));
        $data['baby_address']  = trim(strip_tags($data['baby_address']));
        $data['baby_birthday'] = $data['baby_birthday'] ? date('Y-m-d H:i:s', strtotime($data['baby_birthday'])) : NULL;
        $data['ready_baby_day']= $data['ready_baby_day'] ? date('Y-m-d H:i:s', strtotime($data['ready_baby_day'])) : NULL;
        $data['record_day']= $data['record_day'] ? date('Y-m-d H:i:s', strtotime($data['record_day'])) : date('Y-m-d H:i:s');

        $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']     = $now;
        $data['yx_day']     = $now;
        // $data['creator_day']= $now;
        $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'] = $now;

        if($data['customer_tel']){//录入时是否获取手机号
            $data['tel_staff_id']=$data['dj_staff_id'];
            $data['tel_staff']=$data['dj_staff'];
            $data['tel_time']=$now;
            $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']=$now;
            $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']=$now;
        //     $data['is_first_qq']=1;
        // }
        if($data['sales_staff_id']){
            // $sales=$this->get_staff_list(array('id'=>$data['sales_staff_id']));
            $data['fp_day']     = $now;
            $data['jr_day']     = $now;
            $data['is_fp']      = 1;
            $data['fp_staff']   = $data['dj_staff'];
            $data['fp_staff_id']= $data['dj_staff_id'];
            // $data['sales_department_id']= $sales[0]['department_id'];
            // $data['sales_staff']=$sales[0]['staffname'];
            // $data['sales_staff_number']=$sales[0]['staffnumber'];
            // $data['fp_staff_number']=$data['dj_staff_number'];
        }

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

        //插入手机号时，查询归属地，区号等
        $token = db_config('sx_secret_key_'.session('shop_code'));
        if($data['customer_tel'] && $token){
            $info = getData($data['customer_tel']);
            if ($info) {
                $arr = explode(' ',$info);
                $data['tel_belong'] = $arr[1].' '.$arr[2];
                $data['tel_operator'] = $arr[3];
                $data['tel_area_code'] = $arr[5];
            }
        }

        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'] = strip_tags($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']);
            $remakk = strip_tags($remark);
            $data['track_record'] ='<font color="#f08080">'.$day.'</font>&nbsp;'.$remark."<br/>";
        }

        // 正则验证联系方式 母亲手机号、微信号二选一，必选 返回参与排重的联系方式
        $rescon = checkContact($data);
        if ($rescon['code'] != 200) {
            return $rescon;
        }else{
            $contact = $rescon['data'];
            unset($rescon);
        }
        // 判重客资 eric6+1  0508  所有地方都要检查一下，
        if ($data['customer_type'] == 2) {
            $channel = '';
        }else{
            $channel = $data['customer_channel'];
        }
        // 组织结构
        // $orz['add_shop_code'] = $data['add_shop_code'];
        // $orz['shop_code'] = $data['shop_code'];
        // $rep = $this->isRepeat($data['brandclass'], $data['customer_tel'], $data['customer_wechat'], '', $data['mate_tel'], 0, $data['mate_wechat'], $channel,$orz);        
        // 组织结构
        $orz = [
            'add_shop_code'=> $data['add_shop_code'],
            'shop_code'    => $data['shop_code'],
            'brandclass'   => $data['brandclass'],
        ];
        // 联系方式
        $con = [
            'customer_tel'   => $data['customer_tel'],
            'customer_wechat'=> $data['customer_wechat'],
            'mate_tel'       => $data['mate_tel'],
            'mate_wechat'    => $data['mate_wechat'],
            'qq'             => $data['customer_qq'],
            'consultation_type_id' => $data['consultation_type_id'],
        ];
        // 其他排重条件
        $other['channel'] = $channel;

        $baby_time = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>'baby_time'));
        if (!$baby_time) {
            unset($data['baby_time']);
        }else{
            if (!$data['baby_time']) {
                $data['baby_time'] = '一胎';
            }
            $other['baby_time'] = $data['baby_time'];
        }
        $rep = $this->isRepeat($orz,$con,$other,0);
        // print_r($rep);
        // var_dump($rep);
        // exit;
        $fptest = '';
        db()->startTrans();//开启事务
        try {
            // 不管是不是重复客资，后来的数据要更新到新客户上，如果没有客户，要新建一个客户
            if ($data['customer_tel']) {
                $tempMain = dealMain($rep['c_unique'], $data);
                if ($tempMain['code'] == 200) {
                    $data['c_unique'] = $tempMain['c_unique'];
                }
            }
            $doub = 0;

            $repeatEdit = config('repeat_edit_shop');
            //如果配置了这个参数，如果重了，直接更新。
            if($rep['code'] == 201 && in_array($data['add_shop_code'], $repeatEdit)){
                $fptest  .= 'update exists'; 
                $res = $this->saveRepeatCustomer($rep['data'],$data,get_client_ip(),session('staff_name'),session('staff_id'));
                db()->commit();
                return ['code'=>200,'customer_id'=>$rep['data']['id'],'is_repeat'=>1,'save'=>1];
            }elseif($rep['code'] == 201){
                $doub= 1;//客资重复标记
                if(!db_config('cus_examine_'.session('shop_code'))) {
                    $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 = '由 ';
                        if($data['dj_department_name']){
                            $sales_remark.= '部门为：['.$data['dj_department_name'].'] 的';
                        }
                        $sales_remark.= '【'.$data['dj_staff'].'】于 '.$data['dj_day'].' 录入重复客资';
                        $message_remark .= "您好，您录入的客资";
                        if($data['customer_channel']){
                            $sales_remark.=',录入信息(渠道：'.$data['customer_channel'].')';
                        }
                        if($data['track_record']){
                            $sales_remark.='(备注：'.$data['track_record'].')';
                        }
                        $sales_remark.=',被系统拦截！';
                        $sales_remark .= '重复客资ID:'.$arr['id'];
                        
                        if($arr['customer_tel']){
                            $sales_remark .= ',手机号：'.$arr['customer_tel'];
                            $message_remark.=' 手机号：'.$arr['customer_tel'];
                        }
                        if($arr['customer_wechat']){
                            $sales_remark .= ',微信：'.$arr['customer_wechat'];
                            $message_remark .= ',微信：'.$arr['customer_wechat'];
                        }
                        if($arr['customer_qq']){
                            $sales_remark .= ',QQ：'.$arr['customer_qq'];
                            $message_remark .= ',QQ：'.$arr['customer_qq'];
                        }
                        $message_remark.=' 于 '.$data['dj_day'].' 由';
                        if($data['dj_department_name']){
                            $message_remark.= '部门为：['.$data['dj_department_name'].'] 的';
                        }
                        $message_remark.='【'.session('staff_name').'】 重复录入';
                        if($data['customer_channel']){
                            $message_remark.=',录入信息(渠道：'.$data['customer_channel'].')';
                        }
                        $message_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');
                        $params['c_unique'] = $data['c_unique'];
                        db('CrmCSalestrackinginfo')->insert($params);
                        cache('getCustomerTrackInfos'.$arr['id'],null);
                        getSalesTracking($arr['id']);//获取最近三次追踪记录同步更新到客资表
                        
                        $message['send_type']      = 1;
                        $message['send_title']     = '拦截提醒';
                        $message['send_msg']       = $message_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 .= '是否分配：' . 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'].' ]录入过，未进行分配');
                    }
                    db()->commit();
                    // var_dump($returnData);
                    // exit;
                    return $returnData;
                }else{
                    $data['is_examine'] = 2;
                }
                if ((int)$rep['data']['id']) {
                    dealCus($data,(int)$rep['data']['id']);
                }
                // elseif ($rep['code'] != 200) {
                // $returnData = array('code' => 201,'msg' =>$rep['msg']);
                // return $returnData;
                // }
            }
            // exit;
            // $data['customer_number'] = str_shuffle(time().generate_code());
            $data['update_time'] = $now;
            $isValidNew = isValidNew($data);
            if(customize('xmfc6j1')){
                if ($data['customer_tel'] && $isValidNew) {
                    $data['valid_new'] = 1;
                    $data['is_valid'] = 1;
                }else{
                    $data['valid_new'] = 0;
                    $data['is_valid'] = 3;
                }
            }else{
                $data['valid_new'] = $isValidNew?1:0;
                $data['is_valid'] = 2;
            }
            
            // var_dump($isValidNew);
            /*/ exit;
            if (!$data['customer_tel'] || $isValidNew) {
                $data['valid_new'] = 1;
                $data['is_valid'] = 2;
            }else{
                $data['valid_new'] = 0;
                $data['is_valid'] = 2;
            }
            //*/
            if($data['customer_tel']){
                $hq_num = db('crm_c_customerinfo')
                    ->where('customer_tel',$data['customer_tel'])
                    ->count();
                if ($hq_num) {
                    $data['huoqu_num'] = $hq_num+1;
                }else{
                    $data['huoqu_num'] = 1;
                }
            }else{
                $data['huoqu_num'] = 1;
            }
            $fptest .= 'insert sales staff:'.$data['sales_staff_id'].';';
            $customerId = db('crm_c_customerinfo')->insertGetId($data);
            // 转介绍客资 写入转介绍关系表  并添加一条
            if ($data['customer_type'] == 2 && $data['zjs_from'] == '1') {
                $mid = db('crm_c_customer_main')->where('wphone',$data['introducer_tel'])->value('id');
                $intrData['mid'] = $mid;
                if ($data['zjs_rel'] == '1') { // 亲属
                    $intrData['type'] = 1;
                }else{
                    $intrData['type'] = 2;
                }
                if ($data['customer_tel']) {
                    $intrMid = db('crm_c_customer_main')->where('wphone',$data['customer_tel'])->value('id');
                }else {
                    $intrMid = db('crm_c_customer_main')->where('wwechat',$data['customer_wechat'])->value('id');
                }
                $intrData['introduct_mid'] = $intrMid;
                $intrData['create_time'] = date('Y-m-d H:i:s');
                db('crm_c_client_introduct')->insert($intrData);
                // c_customer_track  添加客户轨迹
                $cTrackData['wphone'] = $data['introducer_tel'];
                $cTrackData['orderId'] = $data['introducer_ordernum'];
                $cTrackData['operating_name'] = $data['dj_staff'];
                $cTrackData['operating_time'] = date('Y-m-d H:i:s');
                $cTrackData['operating_content'] = '录入转介绍客资';
                $cTrackData['remark_details'] = '录入转介绍客资，客户姓名：'.$data['customer_name'].'；客户手机：'.$data['customer_tel'].'；客户微信：'.$data['customer_wechat'];
                $cTrackData['operating_type'] = '转介绍客资';
                $cTrackData['type_subordinate'] = '转介绍客资';
                db('c_customer_track')->insert($cTrackData);
            }

            foreach($contact as $k => $v){
                $contactList[$k]['c_id']            = $customerId;
                $contactList[$k]['c_unique']        = $data['c_unique'];
                $contactList[$k]['contact']         = $v;
                $contactList[$k]['brandclass']      = $data['brandclass'];

                //2021-03-15 南宁qqbaby 定制
                if (customize('nnqqbaby')) {
                    $contactList[$k]['customer_channel']= $data['add_shop_code'];
                }else{
                    $repeat_way = db_config('customer_repeat_method');
                    $repeat_way = $repeat_way?$repeat_way:config('repeat_way');
                    switch ($repeat_way) {
                        case 'xaf':
                            $contactList[$k]['customer_channel']= $data['baby_time']?$data['baby_time']:'一胎';
                            break;
                        case 'all':
                            $contactList[$k]['customer_channel']= '';
                            break;
                        default:
                            $contactList[$k]['customer_channel']= $data['customer_channel'];
                            break;
                    }
                    // if ($data['baby_time'] && config('repeat_way')=='xaf') {
                    //     $contactList[$k]['customer_channel']= $data['baby_time'];
                    // }else{
                    //     $contactList[$k]['customer_channel']= $data['customer_channel'];
                    // }
                }
            }
            
            // 0509
            db('crm_c_customer_contact')->insertAll($contactList);
            // $errId++;
            if($record['sales_remark']){
                //$customerInfo=db('CrmCCustomerinfo')->field('customer_number,customer_name')->where('id',$customerId)->find();
                $record['gtType']=4;
                $record['c_unique']       = $data['c_unique'];
                $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('crm_c_salestrackinginfo')->insert($record);
                getSalesTracking($customerId);
                // $errId++;
            }
            //发送短信
            if($sms_model && $is_send_msg){
                $send_msg = db('crm_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($customerId && !db_config('cus_examine_'.session('shop_code'))){
            // 如果提报人的工作类型是话务(21),分配给自己
            $staffinfo = getStaffInfoById(session('staff_id'));
            $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;
                }
            }
            $fptest .= 'is fp:'.($is_in?1:0).json_encode($staffinfo).';';
            // $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']) {
                //$groupInfo = getGroupInfo($data['sales_staff_id']);
                $groupInfo = getStaffInfoById($data['sales_staff_id']);
                $upgroup= [];
                $upgroup['sales_group_id'] = $groupInfo['group_id'];
                $upgroup['sales_group_name'] = $groupInfo['group_name'];
                if($customerId){
                    db('crm_c_customerinfo')->where('id',$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_group_id']    = session('group_id');
                $dataN['sales_group_name']  = session('group_name');

                $dataN['fp_day']            = $date;
                $dataN['is_fp']             = 1;
                $dataN['jr_day']            = $date;
                db('crm_c_customerinfo')->where('id', $customerId)->update($dataN);

                // 分配日志
                $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'],
                ];;
                $resLog = fpLogs($fpLogData);
            }else{
                $fptest .= 'is sk:'.$data['is_sk'].';';
                // 不筛客
                if ($data['is_sk'] != 1) {
                    $fpStatus=db_config('fp_switch_'.$data['shop_code']);
                    // 开启分配，并且 接收人不存在
                    if($fpStatus==1 && !$data['sales_staff_id']){
                        $fptest .= 'to fp list:'.';';
                        // 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('crm_c_customerinfo')->where('id',$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('crm_c_customerinfo')->where('id',$customerId)->update($upgroup);
                        }
                        $resLog = fpLogs($fpLogData);
                    }
                }
            }
            $customerLogStr = '';
        }
        action_log(array_filter($data),[],$customerId,session('staff_id'),session('staff_name'));
        return ['code'=>200,'customer_id'=>$customerId,'test'=>$fptest];
    }

    //筛客
    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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_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('crm_c_customer_contact')->insertAll($contactList);

            if($param['is_valid'] == 1){
                // if ($pushStatus) {
                // 待定客资 不进入分配队列
                if ($param['is_valid'] != 2) {
                    $sysconfig=db('crm_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('crm_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('crm_c_fp_pool')->where('cid', $value)->where('pool_type',7)->delete();
    //             // 记日志
    //             $cInfo = db('crm_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']);
        // var_dump($staffInfo);
        // exit;
        // 分配人
        $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_group_id']    = $param['group_id'] ? $param['group_id'] : $staffInfo['group_id'];
        $cData['sales_group_name']  = $param['group_name'] ? $param['group_name'] : $staffInfo['group_name'];
        // var_dump($param['group_id']);
        // var_dump($staffInfo['group_id']);
        // var_dump($cData);
        // exit;
        $cData['sales_department_id']  = $param['department_id'] ? $param['department_id'] : $staffInfo['department_id'];
        $cData['sales_department_name']= $param['department_name'] ? $param['department_name'] : $staffInfo['department_name'];
        // 客资标记
        if(isset($param['sign_name'])){
            $cData['sign_name'] = $param['sign_name'];
        }
        if(isset($param['sign_id'])){
            $cData['sign_id'] = $param['sign_id'];
        }
        // 追踪标记
        if(isset($param['op_signinfo'])){
            $cData['op_signinfo'] = $param['op_signinfo'];
        }
        if(isset($param['op_signinfo_id'])){
            $cData['op_signinfo_id'] = $param['op_signinfo_id'];
        }
        // 开始追踪时间
        if (isset($param['c_star_day'])) {
            $cData['c_star_day'] = NULL;
        }
        $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']);

        //2021-06-15 分配清除最后追踪时间：
        if (db_config('allocation_last_tracking') == 1) {
            $cData['last_trackday'] = NULL;
        }
        //追踪人小组信息
        // $groupInfo = getGroupInfo($param['sid']);
        // insert log 和 fp_log 数据
        $lData = [];
        $fData = [];
        $ip = \think\Request::instance()->ip();
        $allot_cids = '';
        $dj_staffs = [];
        $orderFp = flase;
        // 订单客资是否允许分配：
        if (db_config('orderCusIsAllowFp_'.session('brandclass_id')) == 1) {
            $orderFp = true;
        }
        foreach ($cids as $key => $value) {
            $has = db('crm_c_customerinfo')->where('id',$value)
                ->field('is_success,is_fp,fp_staff,fp_staff_id,fp_day,sales_staff,sales_staff_id,sign_id,sign_name,op_signinfo,op_signinfo_id,jr_day,shop_code,shop_name,brandclass_id,sales_department_id,sales_department_name')
                // ->field('is_success,dj_staff,dj_staff_id,is_fp,fp_staff,fp_staff_id,fp_staff_number,fp_day,sales_staff,sales_staff_id,sales_staff_number,sign_id,sign_name,op_signinfo,op_signinfo_id,jr_day,shop_code,shop_name,brandclass_id,sales_department_id,sales_department_name')
                ->find();
            $dj_staffs[$has['dj_staff_id']]['dj_staff_id'] = $has['dj_staff_id'];
            $dj_staffs[$has['dj_staff_id']]['dj_staff'] = $has['dj_staff'];
            $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']     = $param['shop_code'];
                $fData[$key]['fp_shop_name']     = $param['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']     = $staffInfo['shop_code'];
                $fData[$key]['jr_shop_name']     = $staffInfo['shop_name'];
            }
            // textlog('fenpeilog:'.$value."\r\n".json_encode($has)."\r\n".json_encode($param)."\r\n".json_encode($cData));


            //2021-04-15 上海优尼可 shynk 已订单的客资信息修改 ，同步到ERP里面的订单信息（只同步追踪人，就是网销门市，宝宝姓名、生日）
            if (customize('shynk')) {
                $erp_order = db('c_customerorder')->where('crm_customer_id',$value)->find();
                if($erp_order){
                    db('c_customerorder')->where('crm_customer_id',$value)->update(['storeconsuitant2'=>$staffInfo['staffname']]);
                }
            }
        }
        $allot_cids = trim($allot_cids, ',');

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

        db()->startTrans();
        try {
            // 更新客资表
            db('crm_c_customerinfo')->where('id', 'in', $allot_cids)->update($cData);
            // insertAll action_log fp_log
            db('crm_action_log','db_logs')->insertAll($lData);
            db('crm_l_fp_logs')->insertAll($fData);
            // 删除pool表
            db('crm_c_fp_pool')->where('cid', 'in', $allot_cids)->where('pool_type', 1)->delete();
            
            db()->commit();
            $returnData['code'] = 200;
            $returnData['msg']  = '分配成功。';
        } catch (\Exception $e) {
            db()->rollback();
            db('crm_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();
        }
        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('crm_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('crm_c_customerinfo')->where('id', 'in', $param['cid'])->update($cData);
            // insertAll action_log fp_log
            db('crm_action_log','db_logs')->insertAll($lData);
            db('crm_l_fp_logs')->insertAll($fData);
            // 删除pool表
            db('crm_c_fp_pool')->where('cid', 'in', $param['cid'])->where('pool_type', 1)->delete();
            //更新追踪人小组信息
            db('crm_c_customerinfo')->where('id','in',$param['cid'])->update(['sales_group_id'=>$staffInfo['group_id'],'sales_group_name'=>$staffInfo['group_name']]);
            db()->commit();
            $returnData['code'] = 200;
            $returnData['msg']  = '分配成功。';
        } catch (\Exception $e) {
            db()->rollback();
            db('crm_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']=="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_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(session('shop_code'));
            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));
            }*/
            $data['work_type'] = 21;
            if(session('belong_shop_code')){
                $data['shop_code'] = session('belong_shop_code');
            }else{
                //已设置的归属店
                $shops = db_config('dj_shops_'.session('shop_code'));
                $data['shop_code'] = implode(',',array_column($shops,'shop_code'));
            }
            //$detail=controller("Customer","lib")->get_staff_list();
            $staff_list = [];
            if(check_right('menu1559716359')){ //查看本店客资
                $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')){ //查看小组客资
                // 查询小组成员， 20200804
                $mc = new \app\common\lib\mcInterface();
                $groupStaff = $mc->getStaffInfoByGid(['group_id'=>session('group_id')]);
                foreach($groupStaff as $k=>$v){
                    $arr[$k]['id']=$v['id'];
                    $arr[$k]['name']=$v['staffname'];
                }
            }
            $arr = array_values($arr);
        }elseif($data['name']=="fp_staff_id"){
            // $data['work_type'] = 22;
            if(session('belong_shop_code')){
                $data['shop_code'] = session('belong_shop_code');
            }else{
                //已设置的归属店
                $shops = db_config('dj_shops_'.session('shop_code'));
                $data['shop_code'] = implode(',',array_column($shops,'shop_code'));
            }
            $staff_list=getShopStaffs($data);
            foreach($staff_list as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['staffname'];
            }
        }elseif($data['name']=="recommend_staff"){
            $data['work_type'] = KZTB_WORK_TYPE;
            if(session('belong_shop_code')){
                $data['shop_code'] = session('belong_shop_code');
            }else{
                //已设置的归属店
                $shops = db_config('dj_shops_'.session('shop_code'));
                $data['shop_code'] = implode(',',array_column($shops,'shop_code'));
            }
            $staff_list=getShopStaffs($data);
            foreach($staff_list as $k=>$v){
                // $arr[$k]['id']=$v['id'];
                $arr[$k]['id']=$v['staffname'];
                $arr[$k]['name']=$v['staffname'];
            }
        }
        // 医拍摄影师
        else if ($data['name']=="hospital_photo_cameraman_id") {
            $param['shop_code'] = session('shop_code');
            $param['work_type'] = PZ_WORK_TYPE;
            $photo_cameraman = getShopStaffs($param);
            foreach($photo_cameraman as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['staffname'];
            }
        }
        // 医拍摄影助理
        else if ($data['name']=="hospital_photo_assistant_id") {
            $param['shop_code'] = session('shop_code');
            $param['work_type'] = SYZL_WORK_TYPE;
            $photo_assistant = getShopStaffs($param);
            foreach($photo_assistant as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['staffname'];
            }
        }
        elseif($data['name']=="op_signinfo"){
            $detail=controller('Customer','lib')->markSet(session('shop_code'));
            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']=="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'){
            $mc = new \app\common\lib\mcInterface();
            $gParam['brandclass_id'] = session('brandclass_id') ? session('brandclass_id') : NULL;
            $gParam['shop_code'] = session('shop_code') ? session('shop_code') : NULL;
            $gParam['staff_id'] = session('staff_id');
            $group = $mc->getGroupInfo($gParam);
            $arr = [];
            foreach ($group as $key => $value) {
                $temp['id'] = $value['id'];
                $temp['name'] = $value['group_name'];
                array_push($arr,$temp);
            }
        }elseif ($data['name'] == 'club_name') {
            $where['brandclass_id'] = session('brandclass_id');
            $detail=db('crm_s_club')->where($where)->field('id,club_name')->select();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['club_name'];
                $arr[$k]['name']=$v['club_name'];
            }
        }elseif ($data['name'] == 'baby_address') {
            $detail=db('s_hospitalset')->where("find_in_set('".session('shop_code')."',shop_code)")->field('hospital')->select();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['hospital'];
                $arr[$k]['name']=$v['hospital'];
            }
        }
        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('crm_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('crm_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('crm_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('crm_c_customer_contact')->where('c_id','in',implode(',',$ids))->delete();
            db('crm_c_customer_order')->where('customer_id','in',implode(',',$ids))->update(['is_delete'=>1]);
            db('crm_s_wx_relation')->where('cid','in',implode(',',$ids))->update(['cid'=>null]);
            //删除pool表数据
            db('crm_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']=$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('crm_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('crm_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('crm_c_excel_import')->where(array('staff_id'=>session('staff_id')))->limit($limit)->page($page)->ORDER("addtime desc")->select();
        $excel = db('crm_c_excel_import')->alias('i')
            ->join('crm_c_excel_import_data d', 'i.id = d.eid', 'left')
            ->where('i.staff_id', session('staff_id'))
            ->field('i.id,i.file_name,i.file_url,i.`status`,i.addtime,i.belong_shop_name,COUNT(d.id) AS all_number,SUM(d.import_status=1) AS import_number,SUM(d.import_status=2) AS fail_number')
            ->group('d.eid')->ORDER("i.addtime desc")
            ->select();
        $count = db('crm_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('crm_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('crm_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){
        set_time_limit(0);
        //ini_set('memory_limit','1024M');
        $basePath = ROOT_PATH.'public'.DS.'data'.DS.'excel';
        //上传验证后缀名,以及上传之后移动的地址
        $info = $file->validate(['ext' => 'xlsx'])->move($basePath);
        if ($info) {
            $exclePath = $info->getSaveName();  //获取文件名
            $file_url = $basePath.DS.$exclePath;
            // 导入记录表
            $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['brandclass_id'] = session('brandclass_id');
            $excel_file['brandclass'] = session('brandclass');
            $excel_file['add_shop_name'] = session('shop_name');
            $excel_file['add_shop_code'] = session('shop_code');
            // 查看导入的问题
            $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
            //加载文件内容,编码utf-8
            $obj_PHPExcel = $objReader->load($file_url, $encode='utf-8');
            $array = $obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式

            // 去掉表头
            $first = array_shift($array);
            $num   = 1;
            $allNum= count($array);
            $title = import_header_child();//标准表头格式
            $header= [];
            // 翻译表头
            foreach($title as $key => $val){
                foreach($first as $k => $v){
                    if($first[$k]==$title[$key]){
                        $header[$key] = $k;
                    }
                }
            }

            db()->startTrans();//开启事务 insertGetId
            try {
                $excel_file['all_number'] = $allNum;
                $id = db('crm_c_excel_import')->insertGetId($excel_file);
                session('upload_eid',$id);
                $insertData = [];
                // var_dump($allNum);
                // exit;
                $shop_code = $data['shop_code'];
                $shop_name = $data['shop_name'];
                if ($shop_code == session('shop_code')) {
                    // 判断当前导入人的工作类型 工作类型是话务(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;
                        }
                    }
                }
                
                foreach($array as $k=>$v){
                    $temp['eid'] = $id;
                    $temp['baby_name'] = trim(addslashes($v[$header['baby_name']]));
                    $temp['baby_sex'] = trim(addslashes($v[$header['baby_sex']]));
                    $temp['baby_weight'] = trim(addslashes($v[$header['baby_weight']]));
                    $temp['baby_stature'] = trim(addslashes($v[$header['baby_stature']]));
                    $temp['baby_birthday'] = $v[$header['baby_birthday']] ? date('Y-m-d', strtotime($v[$header['baby_birthday']])) : NULL;
                    $temp['ready_baby_day']= $v[$header['ready_baby_day']] ? date('Y-m-d', strtotime($v[$header['ready_baby_day']])) : NULL;
                    $temp['record_day'] = $v[$header['record_day']] ? date('Y-m-d', strtotime($v[$header['record_day']])) : NULL;
                    $temp['baby_address'] = trim(addslashes($v[$header['baby_address']]));
                    
                    $temp['hospital_photo_cameraman'] = trim(addslashes($v[$header['hospital_photo_cameraman']]));
                    $temp['hospital_photo_assistant'] = trim(addslashes($v[$header['hospital_photo_assistant']]));
                    $temp['hospital_photo_time'] = $v[$header['hospital_photo_time']] ? date('Y-m-d 00:00:00', strtotime($v[$header['hospital_photo_time']])) : NULL;

                    $temp['customer_name'] = $this->filterEmoji(trim(addslashes($v[$header['customer_name']])));
                    $temp['customer_tel'] = trim(addslashes($v[$header['customer_tel']]));
                    $temp['customer_wechat'] = trim(addslashes($v[$header['customer_wechat']]));
                    $temp['customer_qq'] = trim(addslashes($v[$header['customer_qq']]));
                    $temp['customer_weibo'] = trim(addslashes($v[$header['customer_weibo']]));
                    $temp['mate_name'] = trim(addslashes($v[$header['mate_name']]));
                    $temp['mate_tel'] = trim(addslashes($v[$header['mate_tel']]));
                    $temp['province'] = trim(addslashes($v[$header['province']]));
                    $temp['city'] = trim(addslashes($v[$header['city']]));
                    $temp['county'] = trim(addslashes($v[$header['county']]));
                    $temp['customer_address'] = trim(addslashes($v[$header['customer_address']]));
                    $temp['customer_type'] = trim(addslashes($v[$header['customer_type']]));
                    $temp['recommend_staff'] = trim(addslashes($v[$header['recommend_staff']]));
                    $temp['introducer_name'] = trim(addslashes($v[$header['introducer_name']]));
                    $temp['sign_name'] = trim(addslashes($v[$header['sign_name']]));
                    $temp['customer_channel'] = trim(addslashes($v[$header['customer_channel']]));
                    $temp['access_model'] = trim(addslashes($v[$header['access_model']]));
                    $temp['consultation_type'] = trim(addslashes($v[$header['consultation_type']]));
                    $temp['customer_cource'] = trim(addslashes($v[$header['customer_cource']]));
                    $temp['channel_plan_number'] = trim(addslashes($v[$header['channel_plan_number']]));
                    $temp['ad_page'] = trim(addslashes($v[$header['ad_page']]));
                    $temp['customer_area'] = trim(addslashes($v[$header['customer_area']]));
                    $temp['customer_intention'] = trim(addslashes($v[$header['customer_intention']]));
                    $temp['consulation_shop'] = trim(addslashes($v[$header['consulation_shop']]));
                    $temp['customer_orderaddress'] = trim(addslashes($v[$header['customer_orderaddress']]));
                    $temp['package_name'] = trim(addslashes($v[$header['package_name']]));
                    $temp['dj_staff'] = session('staff_name');
                    $temp['dj_staff_id'] = session('staff_id');
                    $temp['dj_staff_number'] = session('staff_number');
                    $temp['dj_group_id'] = session('group_id');
                    $temp['dj_group_name'] = session('group_name');
                    $temp['dj_department_id'] = session('department_id');
                    $temp['dj_department_name'] = session('department_name');
                    $temp['add_shop_code'] = session('shop_code');
                    $temp['add_shop_name'] = session('shop_name');
                    // $temp['dj_day'] = date('Y-m-d H:i:s');
                    $temp['dj_day'] = $v[$header['dj_day']] ? date('Y-m-d H:i:s', strtotime($v[$header['dj_day']])) : date('Y-m-d H:i:s');
                    $temp['fp_staff'] = $v[$header['sales_staff']] ? session('staff_name') : NULL;
                    if ($is_in && !$header['sales_staff']) {
                        $temp['sales_staff_id']    = session('staff_id');
                        $temp['sales_staff']       = session('staff_name');
                        $temp['sales_staff_number']= session('staff_number');
                    }else{
                        $temp['sales_staff_id']    = NULL;
                        $temp['sales_staff']       = trim(addslashes($v[$header['sales_staff']]));
                        $temp['sales_staff_number']= NULL;
                    }
                    // $temp['sales_staff']       = trim(addslashes($v[$header['sales_staff']]));
                    $temp['shop_name'] = $shop_name;
                    $temp['shop_code'] = $shop_code;
                    $temp['brandclass_id']= session('brandclass_id');
                    $temp['brandclass']   = session('brandclass');
                    $temp['customer_remark'] = trim(addslashes($v[$header['customer_remark']]));
                    $temp['introduce_staff_name'] = trim(addslashes($v[$header['introduce_staff_name']]));
                    $temp['customer_key'] = trim(addslashes($v[$header['customer_key']]));
                    $temp['create_time'] = date('Y-m-d H:i:s');
                    $temp['baby_time'] = $v[$header['baby_time']] ? trim(addslashes($v[$header['baby_time']])) : '一胎';
                    // var_dump($temp);die;
                    array_push($insertData, $temp);
                    // sleep(1);
                    if($num >= 10 || $k == $allNum-1){
                        db('crm_c_excel_import_data')->insertAll($insertData);
                        // var_dump(cache('upload_percent_'.$id));
                        // db('crm_c_excel_import')->where('id',$id)->update(array('upload_num'=>$k+1));
                        $num = 0;
                        $insertData = [];
                    }
                    $num++;
                    unset($temp);
                }
                unset($insertData);
                db()->commit();
            } catch (\Exception $e) {
                db()->rollback();
                // echo $e->getMessage();
                // var_dump($e);
                return array('code' => 101, 'msg'=>'数据保存失败', 'error'=>$e->getMessage());
            }
            
            $message['body']['eid']=$id;
            // $message['body']['staff']= array(
            //     'staff_id'       => session('staff_id'),
            //     'staff_name'     => session('staff_name'),
            //     'staff_number'   => session('staff_number'),
            //     'group_id'       => session('group_id'),
            //     'group_name'     => session('group_name'),
            //     'department_id'  => session('department_id'),
            //     'department_name'=> session('department_name'),
            //     'add_shop_code'  => session('shop_code'),
            //     'add_shop_name'  => session('shop_name'),
            //     'shop_name'      => $shop_name,
            //     'shop_code'      => $shop_code,
            //     'brandclass_id'  => session('brandclass_id'),
            //     'brandclass'     => session('brandclass'),
            // );
            try {
                $dir = $basePath.DS.'error';
                if (!is_dir($dir)){
                    @mkdir($dir, 0777, true);
                }
            } catch (\Exception $e) {
                return array('code' => 101, 'msg'=>'创建目录失败，请检查 public 目录权限', 'error'=>$e->getMessage());
            }
            
            $resutl=push_list("excelImportRedisList", $message);
            cache('upload_percent_'.$id,['eid'=>$id,'all_number'=>$allNum,'upload_num'=>0,'status'=>0]);
            return array('code'=>200,'msg'=>'文件上传成功','data'=>$id);
        } else {
            return array('code'=>100,'msg'=>'文件上传失败','error'=>$file->getError());
        }
    }
    function filterEmoji($str)
    {
        $str = preg_replace_callback(
        '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);
        return $str;
    }

    //生成错误文件
    function cusFailFile($fail_file,$header = []){
        // echo '1';exit;
        $PHPExcel = new PHPExcel();
        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle('customer'); //给当前活动sheet设置名称
        $title=array("宝宝姓名","宝宝性别","宝宝生日(格式20180101)","预产期","妈妈姓名","妈妈手机号","微信","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.'public'.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;
        
        // 录入必选项配置
        $lrMust = explode(',',trim(db_config('lr_must_'.session('brandclass_id'))));
        $lrMustName = import_header_child();
        $lrMustTitle = [];
        foreach ($lrMust as $key => $value) {
            $lrMustTitle[] = $lrMustName[$value];
        }
        for($i=0;$i<count($title);$i++){
            switch ($title[$i]) {
                case '宝宝生日(格式20180101)':
                    $width = 17;
                case '预产期':
                case '填写日期':
                case '微信':
                case '妈妈手机号':
                case '渠道名称':
                    $PHPExcel->getActiveSheet()->getStyleByColumnAndRow($i,'1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('fc3131');//设置背景色为fc3131
                    break;
                default:
                    $width = 10;
                    break;
            }
            if(in_array($title[$i],$lrMustTitle)){
                $PHPExcel->getActiveSheet()->getStyleByColumnAndRow($i,'1')->getFill()->setFillType(\PHPExcel_Style_Fill::FILL_SOLID)->getStartColor()->setRGB('fc3131');//设置背景色为fc3131
            }
            $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,'Excel5');
        $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');
        // var_dump($PHPWriter);die;
        //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('crm_c_excel_import')->where(array('id'=>$id))->find();
        $this->down_file($data['file_url'],$data['file_name']);
    }

    //下载失败文件
    function fail_file($id){
        $data=db('crm_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('CrmSKpiStaffgoal')->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) {
            $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('crm_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;
            }
        }
    }
    /*
     * 查询手机归属地信息
     * */
    public function getTelInfo($tel){
        $res = db('crm_c_customer_tel')->where('customer_tel',$tel)->find();
        return $res;
    }
    /**
     * 获取客资详情，取c_customerinfo表数据
     * @param  string $cid customer的id，customInfo表的主键
     * @return array
     * @author Eric
     */
    public function getCustomerInfo($id){

        // $customerInfo = db('crm_c_customerinfo')->where('id',(int)$id)->find();
        // $column = 'id,baby_name,baby_sex,baby_birthday,marry_day,ready_baby_day,customer_name,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_birthday,home_phone,email,introduce_staff_name,customer_channel,customer_channel_id,channel_plan_number,ad_page,access_model,access_model_id,consultation_type,consultation_type_id,customer_intention,customer_intention_id,customer_cource,customer_cource_id,sign_id,sign_name,sign_time,customer_idtype,customer_idnumber,province,province_id,city,city_id,county,county_id,customer_address,customer_key,budget,baby_address,customer_area,customer_area_id,consulation_shop,consulation_shop_code,op_signday,op_signinfo,op_signinfo_id,dj_day,dj_staff,dj_staff_id,dj_group_id,dj_group_name,dj_department_id,dj_department_name,is_fp,fp_day,fp_staff,fp_staff_id,sales_staff,sales_staff_id,sales_group_id,sales_group_name,sales_department_id,sales_department_name,shop_code,shop_name,is_intostore,syjd_day,is_next,next_time,is_success,order_day,mate_name,mate_tel,mate_wechat,mate_qq,mate_weibo,mate_birthday,mate_idtype,mate_idnumber,customer_remark,is_valid';
        $customerInfo = db('crm_c_customerinfo')
            // ->alias('c')
            // ->join('c_customerorder o','c.customer_number=o.crm_customer_number','left')
            // ->join('c_customerphoto p', 'o.orderId=p.orderId', 'left')
            ->where('id',$id)
            // ->field($column)
            ->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('menu1555556591')) {
            $customerInfo['auth_tel']='yes';
        }

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

        $order_number = db('c_customerinfo')->alias('c')
            ->join('c_customerorder o','c.customerid = o.customerid','left')
            ->where('c.wphone', $customerInfo['customer_tel'])->order('o.id desc')->value('o.orderId');
        // var_dump($order_number);die;
        if ($order_number) {
            $customerInfo['order_number'] = $order_number;;
        }
        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'];
            $customerInfo['channel_code'] = $allChannel[$customerInfo['customer_channel_id']]['channel_code'];
        }
        // 消费类型图标
        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'];
        }


        return $customerInfo;
    }
    /**
     * 获取客资详情，取c_customerinfo表数据
     * @param  string $cid customer的id，customInfo表的主键
     * @return array
     * @author Eric
     */
    public function getCustomerInfoIntostore($id){
        $customerInfo = db('crm_c_customerinfo c')
            ->join('crm_c_customer_intostore i','c.id=i.cid','left')
            ->where('c.id',(int)$id)->where('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_intention,c.customer_intention_id,c.seles_step,c.op_signinfo_id,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.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_id,c.baby_name,c.baby_sex,c.add_friend_time,c.baby_birthday,c.ready_baby_day,c.customer_label')
        ->find();
        if(empty($customerInfo)){
            $customerInfo = db('crm_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('crm_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,$add_shop_code,$staffId=0){
        // 查缓存
        // $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($add_shop_code,$staffId);//crm设定
        // 客户来源
        $cussourceUrl = '59fd5ec462c88';
        $allSet['cussource'] = self::source();
        // 宝宝医院
        $allSet['hospital'] = self::getHospital();
        // 咨询类型(消费类型)
        $consultationTypeUrl = '59fd58574204a';
        $allSet['consultationType'] = self::consumptionType();

        // $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);

        // 客户意向
        $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($shop_code);
        //客资标记
        $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('crm_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=''){
        if (!$unique) {
            $unique = db('crm_c_customerinfo')->where('id',$id)->value('c_unique');
        }
        // 客资信息
        //$trackInfo = cache('track_log_'.$unique);
        $field = 'c.id,c.c_unique,c.baby_name,c.baby_sex,c.baby_birthday,c.ready_baby_day,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';

        $baby_time = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>'baby_time'));
        if ($baby_time) {
            $field .= ',c.baby_time';
        }
        if(empty($trackInfo)){
            //成都有很多客资没有c_unique，所以要做下判断
            if($unique){
                $info = db('crm_c_customerinfo')->alias('c')
                ->join('crm_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.c_unique',$unique)
                ->order('s.sales_day desc')
                ->field($field)
                ->select();
            }else{
                $info = db('crm_c_customerinfo')->alias('c')
                ->join('crm_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']]['c_unique'] = $value['c_unique'];
                $trackInfo[$value['id']]['baby_name'] = $value['baby_name'];
                $trackInfo[$value['id']]['baby_sex'] = $value['baby_sex'];
                $trackInfo[$value['id']]['baby_birthday'] = $value['baby_birthday'];
                $trackInfo[$value['id']]['ready_baby_day'] = $value['ready_baby_day'];
                $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'];
                $trackInfo[$value['id']]['sign_name'] = $value['sign_name'];
                $trackInfo[$value['id']]['baby_time'] = $value['baby_time'];
                $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'];
            }
            cache('track_log_'.$unique,$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' => 'Customer',
            // 'action'     => 'customerinfo'
        );
        $changeLogs = db('crm_action_log','db_logs')->where($where)->order('create_time desc')->select();
        return $changeLogs;
    }

    /**
     * 获取客资历史订单，现在没有，需要调其他接口
     * @param  string
     * @return array
     * @author Eric
     */
    public function getCustomerHistoryOrders($cid,$mid){
        // $changeLogs = cache('getCustomerHistoryOrders'.$cid);
        // if(!$changeLogs){
        // $changeLogs = db('CrmCCustomerOrder')->where('customer_id',$cid)->select();
            // cache('getCustomerHistoryOrders'.$cid,json_encode($changeLogs));
        // }
        // $orders = db('c_customerorder')->alias('o')
        //     ->join('crm_c_customerinfo c', 'c.c_unique=o.crm_c_unique', 'left')
        //     ->where('c.id',$cid)
        //     ->field('o.orderId,o.targetdate,o.storeconsuitant1,o.total_money,o.payment_money,o.shop_order_name,o.ordernote')
        //     ->select();
        // 
        if (!$cid&&$mid) {
            $cInfo['customer_tel'] = db('crm_c_customer_main')->where('id',$mid)->value('wphone');
        }else{
            $cInfo = db('crm_c_customerinfo')->where('id', $cid)->field('customer_tel,c_unique,customer_number')->find();
        }

        if($cInfo['customer_tel']){
            $orders = db('c_customerorder')->alias('o')
                ->join('c_customerinfo c', 'c.customerid=o.customerid', 'left')
                ->join('crm_c_customerinfo crm_c', 'crm_c.id=o.crm_customer_id', 'left')
                ->join('c_customerorder_servicefc s','s.orderId=o.orderId and s.currentfc=1','left')
                ->where('c.wphone',$cInfo['customer_tel'])->whereOr('o.crm_customer_id',$cid)
                ->field('o.id,o.orderId as order_sn,o.consumption_type as consultation_type,o.targetdate,o.storeconsuitant1,o.total_money,o.payment_money,o.bargain_money as order_fact,o.supplementary_money as two_pin_fact,o.shop_order_name,o.ordernote,o.crm_customer_number,o.crm_c_unique,o.crm_customer_id,s.allfc,c.customer_channel,crm_c.sales_staff,crm_c.c_from,crm_c.id as crm_id')
                ->select();
            // foreach ($orders as $key => $value) {
            //     $inData = [];
            //     if (!$value['crm_customer_number']) {
            //         $inData['crm_customer_number'] = $cInfo['customer_number'];
            //     }
            //     if (!$value['crm_c_unique']) {
            //         $inData['crm_c_unique'] = $cInfo['c_unique'];
            //     }
            //     if (!empty($inData)) {
            //         db('c_customerorder')->where('id',$value['id'])->update($inData);
            //     }
            // }
        }
        if ($orders) {
            foreach ($orders as $key => $value) {
                $orders[$key]['targetdate'] = date('Y-m-d', strtotime($value['targetdate']));
                $orders[$key]['target_time'] = date('Y-m-d', strtotime($value['targetdate']));
                $orders[$key]['shop_name'] = $value['shop_order_name'];
                //2021.03.11 解除订单
                if ($value['crm_customer_id'] == $cid && check_right("menu1615433005") && customize('nnqqbaby')) {
                    $orders[$key]['relieve_order'] = 1;
                }

                //2021.06.16 绑定订单
                if ((empty($value['crm_customer_id']) || empty($value['crm_id']) || $value['c_from'] == 2) && check_right("menu1623835115") && customize('nnqqbaby')) {
                    $orders[$key]['binding_order'] = 1;
                }

                $orders[$key]['sales_staff'] = $value['sales_staff'] ?: '';
            }
        }
        return $orders;
    }

    /**
     * 获取同一个事业部下，重复  手机号,微博，微信，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('crm_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('crm_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('crm_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('crm_c_customerinfo')->where($whereC)->update($dataC);
            db('crm_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('crm_c_message')->find((int)$id);

        return $msgInfo;

    }
    public function getMessageByCustomerId($customerId){
        $msgInfo = db('crm_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('crm_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('crm_c_message')->where($where)->order('read_status asc')->order('id desc')->limit(10)->select();
            // echo db('crm_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('crm_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('crm_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('crm_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('crm_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'], ture);
        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('CrmCCustomerinfo')
                    ->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('CrmCCustomerinfo')
                    ->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('CrmCCustomerinfo')
                    ->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('CrmCCustomerinfo')
                    ->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('CrmCCustomerinfo')
                ->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('CrmCCustomerinfo')
                ->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('CrmCCustomerinfo')
                ->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('CrmCCustomerinfo')
                ->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('CrmCCustomerinfo')
            ->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('CrmCCustomerinfo')
            ->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('CrmCCustomerinfo')
            ->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('CrmCCustomerinfo')
            ->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('CrmCCustomerinfo')
            ->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=^******^&Orderinfo='.$name.'&Brandid='.session('brandclass_id');
    //         }else{
    //             $shop_type = 0;
    //             $addr = $erp['addr'];
    //             // 婚纱0，儿童1
    //             $url = trim($addr,'/').'/SX_CrmApi/Sel_CustomerOrderInfo?Token=^******^&Orderinfo='.$name.'&Brandid='.session('brandclass_id');
    //         }
    //         // $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,staff_name','staffname');
    //         if($res['Code'] == 200){
    //             foreach($res['Data'] as $k=>$v){
    //                 $res['Data'][$k]['customer_name'] = $v["mname"] ? $v["mname"] :$v["wname"];
    //                 $res['Data'][$k]['customer_tel'] = $v["mphone"] ? $v["mphone"] :$v["wphone"];
    //                 $res['Data'][$k]['order_number'] = $v["orderId"];
    //                 $res['Data'][$k]['customer_number'] = $v["customer_from_index"] ? $v["customer_from_index"] : ''; //crm_customer_number  c_customerorder表里
    //                 // $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["storeconsuitant1"] ? $staff["storeconsuitant1"] :0;
    //                 $res['Data'][$k]['reception_name'] = $v["storeconsuitant1"] ? $v["storeconsuitant1"] :'';
    //             }
    //         }else{
    //             $res = array('Code'=>'300','Msg'=>'未查询到订单数据','Data'=>'');
    //         }
    //         return ($res);
    //     }else{
    //         $res = db('CrmCCustomerinfo')
    //             ->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,customer_number,mate_tel,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);
    //         }
    //     }
    // }
    public function customerNameSearch($name){
        $res = getseachintroducer($name);
        if($res['Code'] == 200){
            foreach($res['Data'] as $k=>$v){
                $res['Data'][$k]['customer_name'] = $v["wname"] ? $v["wname"] :$v["mname"];
                $res['Data'][$k]['customer_tel'] = $v["wphone"] ? $v["wphone"] :$v["mphone"];
                $res['Data'][$k]['order_number'] = $v["orderId"];
                $res['Data'][$k]['customer_number'] = $v["crm_customer_number"] ? $v["crm_customer_number"] : ''; //crm_customer_number  c_customerorder表里
                // $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["storeconsuitant1"] ? $staff["storeconsuitant1"] :0;
                $res['Data'][$k]['reception_name'] = $v["storeconsuitant1"] ? $v["storeconsuitant1"] :'';
            }
            return array('Code'=>'200','Msg'=>'查询成功','Data'=>$res['Data']);
        }else{
            return array('Code'=>'300','Msg'=>'未查询到订单数据','Data'=>'');
        }
    }
    /*
     * 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('crm_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('CrmCCustomerinfo')->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;
                }
                // 写入追踪表
                $dataValid = [
                    'gtType'            => '4',
                    'c_unique'       => $info['c_unique'],
                    'customer_id'       => $param['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'      => '追踪标记:'.$info['op_signinfo'],
                ];
                db('crm_c_salestrackinginfo')->insert($dataValid);
                getSalesTracking($param['id']);//获取最近三次追踪记录同步更新到客资表
                action_log($param, '', $param['id'], session('staff_id'), session('staff_name'));
                db()->commit();
                $res = array('code'=>200,'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('crm_c_customerinfo')->where('id',$data['id'])->update($data);
                // 写入追踪表
                $dataValid = [
                    'gtType'            => '4',
                    'c_unique'       => $info['c_unique'],
                    '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('crm_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('CrmCSendMessageLog');
        $customerInfos = db('crm_c_customerinfo')
            ->where('id','in',$param['ids'])
            ->where('is_status','1')
            ->field('id,customer_tel,mate_tel,customer_name,mate_name,yjd_day,consulation_shop_code,consulation_shop,sales_staff_id')
            ->select();

        $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){
                $send_msg = '';
                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('crm_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);
                }else{
                    $send_msg = str_replace('[[shop_address]]','',$send_msg);
                }
                //门市信息
                if((strstr($send_msg,'[[sales_phone]]')||(strstr($send_msg,'[[sales_staff]]'))&&$v['sales_staff_id'])){
                    $staff = $this->get_staff_info(['staff_id'=>$v['sales_staff_id']]);
                    // $staff = getStaffInfoById($v['sales_staff_id']);
                    $staff = $staff['data'];
                    $send_msg = str_replace('[[sales_staff]]',$staff['staffname'],$send_msg);
                    $send_msg = str_replace('[[sales_phone]]',$staff['telephone'],$send_msg);
                }
                // var_dump($send_msg);
                // exit;
                $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(
                    'shop_code'=> session('shop_code'),
                    'mobile'   => $tel,
                    'content'  => $send_msg
                );
                // if(!$param['send_config']){
                //     array_push($da,['shop_code'=>session('shop_code')]);
                // }else{
                //     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()->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)){
                    continue;
                }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'].';';
                }elseif($param['flag'] == 'smp'){
                    $content .= '上门时间：'.$param['pc_time'];
                    $content .= '核销码：'.$param['hx_code'];
                }
                //门店信息
                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 = $this->get_staff_info(['staff_id'=>$v['sales_staff_id']]);
                    $staff = $staff['data'];
                    $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'];
                }
                // var_dump($res);
                if($res['code'] != 200){
                    db()->rollback();
                    return array('msg'=>'第'.$i.'条时短信接口调用失败','code'=>100,'data'=>$res['msg']);
                }
                db('crm_c_send_message_log')->insert($data);
                $i++;
            }
            // die;
            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);
    }
    //追踪添加 0629
    public function addSalesTracking($param){
        $c_unique = db('crm_c_customerinfo')->where('id',$param['customer_id'])->value('c_unique');
        $param['c_unique'] = $c_unique;
        $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');
        $param['tel_type'] = 1;
        $call_id =  db_config('call_id');
        $call = db('CrmSCallCenter')->where('id',$call_id)->value('call_name');
        if(session('user') && session('ip') && $call == 'IP呼叫中心'){
            if (cache('guid_'.$param['customer_tel'])) {
                $param['audio_path'] = session('ip').':'.session('port').'/osip_playwave.cpc?guid='.cache('guid_'.$param['customer_tel']);
                $param['tel_static'] = 1;
            }
        }elseif ($call == '呼叫中心(七陌)') {
            $call_t = db('crm_c_call_temporary')->where(['time'=>$param['customer_tel'],'sales_staff_id'=>['exp','is null'],'status'=>['exp','is null']])->order('id desc')->find();
            $call_temporary = json_decode($call_t['txt'],true);
            //接听状态：dealing（已接）,notDeal（振铃未接听）,leak（ivr放弃）,queueLeak（排队放弃）,blackList（黑名单）,voicemail（留言）,limit（并发限制）注意：只有dealing和voicemail状态的通话有录音，其他状态的通话录音地址不可用
            $param['audio_path'] = $call_temporary['State'] === 'dealing' ? $call_temporary['FileServer']."/".$call_temporary['RecordFile'] : '';//FileServer/RecordFile
        }
        $param['sales_remark'] = $param['customer_remark'];
        unset($param['customer_remark']);
        // var_dump($param['audio_path']);
        foreach($param as $k=>$v){
            if(empty($v) || $v == '请选择'){
                unset($param[$k]);
            }
        }
        db()->startTrans();//开启事务
        try{
            db('CrmCSalestrackinginfo')->insert($param);
            $id = db('CrmCSalestrackinginfo')->getLastInsID();
            if($id){
                db('crm_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_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,
                    );
                }
                $arr['update_time'] = $time;
                db('crm_c_customerinfo')->where('id',$param['customer_id'])->update($arr);
            }
            db('crm_c_call_temporary')->where(['time'=>$param['customer_tel'],'sales_staff_id'=>['exp','is null'],'status'=>['exp','is null']])->update(['status'=>1]);
            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'] = "不再追踪";
        }
        $call_center_time = $param['call_center_time'];
        unset($param['call_center_time']);

        $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'];
        $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['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'];
        $data['customer_address'] = $param['customer_address'];
        $data['customer_remark'] = $param['customer_remark'];
        $data['mate_wechat'] = $param['mate_wechat'];
        $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'] ? date('Y-m-d 00:00:00',strtotime($param['baby_birthday'])) : NULL;
        $ready_baby_day = $param['ready_baby_day'] ? date('Y-m-d 00:00:00',strtotime($param['ready_baby_day'])) : 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'];
        $data['customer_label'] = $param['customer_label'];
        $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['is_valid'] == 3) {
                $new .= '无效原因：'.$param['unvalid_reason'].'<br/>';
            }
        }
        if($param['customer_intention'] != $info['customer_intention']){
            $old .= '客资意向：'.$info['customer_intention'].'<br/>';
            $new .= '客资意向：'.$param['customer_intention'].'<br/>';
        }
        if($param['consultation_type'] != $info['consultation_type']){
            $old .= '消费类型：'.$info['consultation_type'].'<br/>';
            $new .= '消费类型：'.$param['consultation_type'].'<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['customer_remark'] != $info['customer_remark']){
            $old .= '客资备注：'.$info['customer_remark'].'<br/>';
            $new .= '客资备注：'.$param['customer_remark'].'<br/>';
        }
        if($param['sales_remark'] != $info['sales_remark']){
            $old .= '备注：'.$info['sales_remark'].'<br/>';
            $new .= '备注：'.$param['sales_remark'].'<br/>';
        }
        if($param['package_name'] != $info['package_name'] && customize('shynk')){
            $old .= '意向套系：'.$info['package_name'].'<br/>';
            $new .= '意向套系：'.$param['package_name'].'<br/>';
            if($info['package_name'] && !$param['package_name']){
                $sales_remark = '删除原意向套系：'.$info['package_name'];
            }elseif(!$info['package_name'] && $param['package_name']){
                $sales_remark = '新增意向套系：'.$param['package_name'];
            }else{
                $sales_remark = '原意向套系：'.$info['package_name'].',修改为：'.$param['package_name'];
            }
        }

        $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['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['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['ready_baby_day']);
        unset($param['add_friend_time']);
        unset($param['mate_wechat']);
        unset($param['receiver_flag']);

        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'],
                        'customer_remark' => $data['customer_remark'],
                        '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'],
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                        'customer_sex' => $data['customer_sex'],
                        'customer_name' => $param['customer_name'],
                        'customer_remark' => $data['customer_remark'],
                        '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'],
                    );
                }
                // 录入必选项定制 电访编辑验证 录入时验证 20200106
                if (ini('lr_must.shop_code')==session('shop_code')) {
                    // 判断字段是否存在
                    $column = isColumnExist(array('table'=>'crm_c_customerinfo','column'=>ini('lr_must.field')));
                    if ($column) {
                        if($param['pinlei'] != $info['pinlei']){
                            $old .= '品类：'.$info['pinlei'].'<br/>';
                            $new .= '品类：'.$param['pinlei'].'<br/>';
                            $arr['pinlei'] = $param['pinlei'];
                        }
                    }
                }
                if($param['seles_step'] && $param['seles_step'] != $info['seles_step']){
                    $arr['seles_step'] = $param['seles_step'];
                    $arr['step_name'] = $param['step_name'];
                }
                if($consultation_type_id && $consultation_type_id != $info['consultation_type_id']){
                    $arr['consultation_type_id'] = $consultation_type_id;
                    $arr['consultation_type'] = $param['consultation_type'];
                }
                if($customer_intention_id && $customer_intention_id != $info['customer_intention_id']){
                    $arr['customer_intention_id'] = $customer_intention_id;
                    $arr['customer_intention'] = $param['customer_intention'];
                }
                $old .= '最后追踪时间：'.$info['last_trackday'].'<br/>';
                $new .= '最后追踪时间：'.$arr['last_trackday'].'<br/>';
                //没有追踪部门则添加
                if(empty($info['sales_department_id'])){
                    $arr['sales_department_id'] = session('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/>';
                }
                //新联系方式
                $new_contact = [];
                //手机   190609
                $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;
                        // 编辑客资时 手机号发生变动时  对应的 主表也要发生变动
                        $needDealMain = true;
                    }
                    $exclusion_field = config('exclusion_field');
                    if (in_array('customer_tel',$exclusion_field)) {
                        $new_contact[] = $customer_tel;
                    }
                // }

                // 配偶手机
                $mate_tel = $data['mate_tel'];
                // if ($mate_tel) {
                    if($mate_tel != $info['mate_tel']){
                        $arr['mate_tel'] = $mate_tel;
                    }
                    $exclusion_field = config('exclusion_field');
                    if (in_array('mate_tel',$exclusion_field)) {
                        $new_contact[] = $mate_tel;
                    }
                // }
                // 微信
                $customer_wechat = $param['customer_wechat'];
                // if ($customer_wechat) {
                    if($customer_wechat != $info['customer_wechat']){
                        if (!$info['customer_wechat']) {
                            $arr['wechat_staff_id']= session('staff_id');
                            $arr['wechat_staff']   = session('staff_name');
                            $arr['wechat_time']    = $time;
                        }
                        $arr['customer_wechat'] = $customer_wechat;
                    }
                    $exclusion_field = config('exclusion_field');
                    if (in_array('customer_wechat',$exclusion_field)) {
                        $new_contact[] = $customer_wechat;
                    }
                // }
                // 微信
                $mate_wechat = $param['mate_wechat'];
                // if ($mate_wechat) {
                    if($mate_wechat != $info['mate_wechat']){
                        $arr['mate_wechat'] = $mate_wechat;
                    }
                    $exclusion_field = config('exclusion_field');
                    if (in_array('mate_wechat',$exclusion_field)) {
                        $new_contact[] = $mate_wechat;
                    }
                // }
                unset($param['customer_wechat']);
                unset($param['mate_wechat']);
                // var_dump($new_contact);die;
                if (!empty($new_contact)) {
                    
                    //插入新的联系方式
                    // 20191112 需要写一个公共的写入排重表的方法（cid，contact） 该方法重新取客资id对应的渠道，baby_time,customer_type,事业部
                    // db('crm_c_customer_contact')->insertAll($new_contact);
                    updateContact($param['customer_id'],$new_contact);
                }
                // 有效状态 
                if($data['is_valid'] && ($info['is_valid'] != $data['is_valid'])){
                    $arr['is_valid'] = $data['is_valid'];
                    $arr['yx_day'] = $time;
                    if ($data['is_valid'] == 3) {
                        $arr['unvalid_id'] = $param['unvalid_id'];
                        $arr['unvalid_reason'] = $param['unvalid_reason'];
                    }
                }
                // 客资标记
                if ($sign_id && ($sign_id != $info['sign_id']) ) {
                    $arr['sign_id']   = $sign_id;
                    $arr['sign_name'] = $sign_name;
                    $arr['sign_time'] = $time;
                }
                // 追踪标记
                if($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['add_friend_time'] && ($data['add_friend_time'] != $info['add_friend_time'])) {
                    $arr['add_friend_time'] = $data['add_friend_time'];
                }
                // 预算
                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 ($data['customer_label'] != $info['customer_label'] ) {
                    $arr['customer_label'] = $data['customer_label'] ?: ['exp','null'];
                    $old .= '客资标签：'.$info['customer_label'].'<br/>';
                    $new .= '客资标签：'.$arr['customer_label'].'<br/>';
                }
                // 宝宝生日
                if ($baby_birthday && ($baby_birthday != $info['baby_birthday'])) {
                    $arr['baby_birthday'] = $baby_birthday;
                    $old .= '宝宝生日：'.$info['baby_birthday'].'<br/>';
                    $new .= '宝宝生日：'.$baby_birthday.'<br/>';
                }
                if ($ready_baby_day && ($ready_baby_day != $info['ready_baby_day'])) {
                    $arr['ready_baby_day'] = $ready_baby_day;
                    $old .= '预产期：'.$info['ready_baby_day'].'<br/>';
                    $new .= '预产期：'.$ready_baby_day.'<br/>';
                }

                // 再约时间
                if ($next_time && ($next_time != $info['next_time']) ) {
                    $arr['is_next'] = 1;
                    $arr['next_time'] = $next_time;
                    $param['next_time'] .= '<br /> 再约时间：'.$next_time;
                    //查询再约提前时间  天
                    $adv = db('crm_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('crm_c_fp_pool')->insertGetId($pool);
                        if(!$inc1){
                            db()->rollback();
                            $returnData = array('code' => 10,'msg' =>'提前'.$adv['advancehour'].'天再约进店失败');
                            return ($returnData);
                        }else{
                            db()->commit();
                        }
                    }//查询再约提前时间  分钟
                    $adv = db('crm_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('crm_c_fp_pool')->insertGetId($pool);
                        if(!$inc1){
                            db()->rollback();
                            $returnData = array('code' => 10,'msg' =>'提前'.$adv['advancehour'].'分钟再约进店失败');
                            return ($returnData);
                        }else{
                            db()->commit();
                        }
                    }
                }
                // 省市区
                if($info['province_id'] != $province_id){
                    $arr['province_id'] = $province_id;
                    $arr['province'] = $province;
                }
                if($info['city_id'] != $city_id){
                    $arr['city_id'] = $city_id;
                    $arr['city'] = $city;
                }
                if($info['county_id'] != $county_id){
                    $arr['county_id'] = $county_id;
                    $arr['county'] = $county;
                }

                foreach($arr as $k=>$v){
                    if(empty($v) && $k!='customer_remark'){
                        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');

                if(customize('shynk')){
                    $arr['package_name'] = $param['package_name'];
                }

                // var_dump($arr);
                // exit;
                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'],'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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->where('id',$param['customer_id'])->update($cont);
                    }

                    if (!$data['yjd_day'] || !$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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->where('id',$param['customer_id'])->update($arr);
                    //删除pool表数据
                    // db('crm_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_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'].'--取消预约';
                        }
                        db('crm_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'].'--取消预约';
                        }else{
                            $param['sales_remark'] = '不再追踪：'.$reason.'--'.$param['sales_remark'];
                        }
                    }
                    unset($param['mate_name']);
                    unset($param['marry_day']);
                    unset($param['next_time']);
                    $track['c_unique'] = $info['c_unique'];
                    $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'].''.$sales_remark;

                    if ($call_center_time && db_config('call_id')) {
                        $sales_day = date("Y-m-d H:i:s",$call_center_time);

                        $call_t = db('crm_c_call_temporary')->where(['cid'=>$param['customer_id'],'sales_staff_id'=>session('staff_id'),'time'=>$call_center_time,'status'=>['exp','is null']])->find();
                        if ($call_t) {
                            $call_temporary = json_decode($call_t['txt'],true);
                            $track['tel_starttime'] = $call_temporary['Ring'];//通话振铃时间（话务进入呼叫中心系统的时间）
                            $track['tel_endtime'] = $call_temporary['End'];//通话结束时间
                            if ($call_temporary['Begin']) {
                                $track['tel_alltime'] = strtotime($call_temporary['End'])-strtotime($call_temporary['Begin'])."秒";//通话接通时间（双方开始通话的时间,如果被叫没接听的话为空）
                            }
                            $track['tel_type'] = 1;
                            //接听状态：dealing（已接）,notDeal（振铃未接听）,leak（ivr放弃）,queueLeak（排队放弃）,blackList（黑名单）,voicemail（留言）,limit（并发限制）注意：只有dealing和voicemail状态的通话有录音，其他状态的通话录音地址不可用
                            $track['tel_static'] = $call_temporary['State'] === 'dealing' ? 1 : 2;
                            $track['audio_path'] = $call_temporary['State'] === 'dealing' ? $call_temporary['FileServer']."/".$call_temporary['RecordFile'] : '';//FileServer/RecordFile

                            db('crm_c_call_temporary')->where('id', $call_t['id'])->update(['status'=>1]);
                        }
                    }else{
                        $sales_day = date('Y-m-d H:i:s',time());
                    }

                    $track['sales_day'] = $sales_day;
                    $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'] :2;
                    $track['no_track'] = $param['no_track'];

                    $track['seles_step']= $param['seles_step'] ? $param['seles_step'] : '';
                    $track['step_name'] = $param['step_name'] ? $param['step_name'] : '';

                    if (!$param['track_id']) {
                        db('CrmCSalestrackinginfo')->insertGetId($track);
                    }else{
                        unset($track['customer_tel'],$track['gtType'],$track['tel_static']);
                        db('crm_c_salestrackinginfo')
                            ->where('id', $param['track_id'])
                            ->update($track);
                    }
                    // var_dump($arr);
                    // exit;
                    db('crm_c_customerinfo')->where('id',$param['customer_id'])->update($arr);

                    //return array('code'=>201,'msg'=>db('CrmCCustomerinfo')->getLastSql(),'data'=>'');
                    // 从其他到有效 发消息 eric 181212
                    if($data['is_valid']==1 && $info['is_valid'] != 1){
                        $remind = db('crm_s_reminditemset')->where('id', 'valid')->where('brandclass_id', $info['brandclass_id'])->find();
                        if ($remind['send_method']) {
                            // 包含 弹窗
                            if (strpos($remind['send_method'],'tan')) {
                                $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);
                            }
                            // 包含 微信推送
                            if (strpos($remind['send_method'],'tui')) {
                                // 发送微信模板消息
                                $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);
                        // }
                    }
                }
                // 当需要 更新 main表时
                if ($needDealMain) {
                    $cInfo = db('crm_c_customerinfo')->where('id',$param['customer_id'])->find();
                    $dealRes = dealMain($cInfo['c_unique'],$cInfo);
                    if ($dealRes['code'] == 200) {
                        if ($dealRes['c_unique'] != $cInfo['c_unique']) {
                            db('crm_c_customerinfo')->where('id',$param['customer_id'])->update(['c_unique' =>$dealRes['c_unique']] );
                            db('crm_c_customer_contact')->where('c_id',$param['customer_id'])->update(['c_unique' =>$dealRes['c_unique']] );
                            db('crm_c_salestrackinginfo')->where('customer_id',$param['customer_id'])->update(['c_unique' =>$dealRes['c_unique']] );
                        }
                    }
                }
                if($noTrack == 1){
                    history_log($new,$old,$param['customer_id'],session('staff_id'),session('staff_name'));
                }

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

                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('crm_c_customer_intostore');
        // 如果进店表存在
        if ($isTable) {
            $cid = db('crm_c_customerinfo')->where('customer_number',$param['customer_number'])->value('id');
            $iId = db('crm_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('crm_c_customer_intostore')->where('id',$iId)->update($iData);
                db('crm_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('crm_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('crm_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){
        unset($param['tel_starttime'],$param['tel_endtime']);
        $info = $this->get_staff_info(array('staff_id'=>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('crm_c_call_registration')->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 = $this->get_staff_info(array('staff_id'=>session('staff_id')));
        $c_info = $this->getCustomerInfo($param['customer_id']);
        //追踪记录
        $params['customer_id'] = $param['customer_id'];
        $params['c_unique'] = $c_info['c_unique'];
        $params['customer_name'] = $c_info['customer_name'];
        $params['customer_number'] = $c_info['customer_number'];
        $params['sales_remark'] = '老客户来电；备注：'.$param['customer_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['tel_starttime'] = $param['tel_starttime'];
        $params['tel_endtime'] = $param['tel_endtime'];
        $params['tel_alltime'] = $param['tel_alltime'];
        $params['gtType'] = 1;
        $params['tel_type'] = 2;
        $params['customer_tel'] = $param['customer_tel'];
        $params['consultation_type'] = $param['consultation_type'];
        $params['tel_static'] = 1;
        $params['no_track'] = '老客户来电';
        $params['audio_path'] = session('ip').':'.session('port').'/osip_playwave.cpc?guid='.cache('guid_'.$param['customer_tel']);

        unset($param['tel_starttime'],$param['tel_endtime']);

        $param['customer_id'] = $c_info['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'];
        $param['audio_path'] = session('ip').':'.session('port').'/osip_playwave.cpc?guid='.cache('guid_'.$param['customer_tel']);
        db()->startTrans();
        try{
            db('crm_c_call_registration')->insert($param);
            $sql = db()->getLastSql();
            db('CrmCSalestrackinginfo')->insert($params);
            $sql1 = db()->getLastSql();
            cache('getCustomerTrackInfos'.$param['customer_id'],null);
            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(),'sql'=>$sql,'sql1'=>$sql1);
        }
    }

    //提醒用的发送信息函数
    /*
     * @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('CrmCCustomerinfo')->where('id', $id)->update(array('is_send_birthday_msg' => 1));
                }
                if ($flag == 'marry_day') {
                    db('CrmCCustomerinfo')->where('id', $id)->update(array('is_send_wedd_msg' => 1));
                }
                if ($flag == 'yjd_day') {
                    db('CrmCCustomerinfo')->where('id', $id)->update(array('is_send_yjd_msg' => 1));
                }
                if ($flag == 'syjd_day') {
                    db('CrmCCustomerinfo')->where('id', $id)->update(array('is_send_syjd_msg' => 1));
                }
                if ($flag == 'next_time') {
                    db('CrmCCustomerinfo')->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);
        return $res;
    }
    //客资提醒
    function isNextTimeRemind()
    {
        return array('code'=>200,'msg'=>'');
        //检测是否有需要修改的信息
        /*$check = db('CrmCCustomerinfo')
            ->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->where('id',$v['id'])->update(array('is_send_birthday_msg'=>2));
                    }
                    if(date('m-d',time()) > date('m-d',strtotime($v['wedding_date']))){
                        db('CrmCCustomerinfo')->where('id',$v['id'])->update(array('is_send_wedd_msg'=>2));
                    }
                    if(date('m-d',time()) > date('m-d',strtotime($v['yjd_day']))){
                        db('CrmCCustomerinfo')->where('id',$v['id'])->update(array('is_send_yjd_msg'=>2));
                    }
                    if(date('m-d',time()) > date('m-d',strtotime($v['syjd_day']))){
                        db('CrmCCustomerinfo')->where('id',$v['id'])->update(array('is_send_syjd_msg'=>2));
                    }
                }
            }
            //提醒设定
            $remind = db('crm_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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')->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('CrmCCustomerinfo')
                            ->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('crm_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('CrmSCallPrefix')->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('crm_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'))){
            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'] = 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：其他）
        $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']){
            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 .= '已撤销不再追踪；';
            }

            // $yjd_day = date('Y-m-d H:i:s',strtotime($data['yjd_day']));
            //如果标记预约，存入pool表
            //查询再约提前时间
            $adv = db('crm_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']);
                }
                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('crm_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'])).'】预约进店,现提前'.$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('crm_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'  => $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('crm_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('crm_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('crm_c_customerinfo')->where('id',$id)->update($data);
            }

            //插入进店表
            if($isTable){

                $into_id = db('crm_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('crm_c_customer_intostore')->where('id',$into_id)->update(['status'=>99]);
                    db('crm_c_customer_intostore')->insert($into);
                }else{
                    db('crm_c_customer_intostore')->insert($into);
                }
            }

            //生成进店码,存入进店码表
            $jd_code = get_rand_string(8,1);
            $cid = db('crm_c_customer_jdm')->where('jd_code',$jd_code)->value('c_id');
            while($cid){
                $jd_code = get_rand_string(8,1);
                $cid = db('crm_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('crm_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('crm_s_message_templateinfo')->where('id',$yyModel)->value('mtemplate_content');
                if($send_msg){
                    $sms = db_config('sms_'.session('shop_code'));
                    if($jd_code){
                        $send_msg .= ',进店码：'.$jd_code.',进店后失效!';
                    }
                    $param = [
                        'ids' => $id,//客资id
                        'model_id' => $yyModel,//模板id
                        'send_msg' => $send_msg,//发送的模板内容
                        'send_config' => $sms,//短信账号
                        'flag'=>'yjd',
                        'receiver_flag'=>$param['receiver_flag']
                    ];
                    $s = $this->send_message($param);
                    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,session('staff_id'),session('staff_name'));
            //追踪记录
            $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('CrmCSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$id,null);
            //修改追踪时间
            $info = $this->getCustomerInfo($id);//客资信息
            $time = date('Y-m-d H:i:s',time());
            if(empty($info['c_start_day'])){
                $arr = array(
                    'c_star_day' => $time,
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }else{
                $arr = array(
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }
            if($info['is_loss'] == 1){
                $arr['is_loss'] = 2;
                $arr['loss_day'] = NULL;
                $arr['loss_cause'] = NULL;
            }
            db('CrmCCustomerinfo')->where('id',$id)->update($arr);
            //修改客资为有效
            if($info['is_valid'] != 1 || empty($info['yx_day'])){
                $upd = array(
                    'is_valid' => 1,
                    'yx_day' => $time
                );
                db('CrmCCustomerinfo')->where('id',$id)->update($upd);
            }
            //修改客资表近三次追踪记录
            getSalesTracking($id);


            //如果是爆破活动，修改对应的爆破表数据
            if($info['is_act'] == 2){
                db('crm_c_swap_customer')->where('customer_number',$info['customer_number'])->update([['yjd_day'=>$data['yjd_day'],'yjd_action_day']=>$time]);
            }
            if($customerInfo['sales_staff_id']){
                if($pool){
                    db('crm_c_fp_pool')->insertGetId($pool);
                }
                if($pool1){
                    db('crm_c_fp_pool')->insertGetId($pool1);
                }
                if($pool2){
                    db('crm_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('crm_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('crm_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('crm_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('crm_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('crm_c_customer_intostore');
        db()->startTrans();
        $is_erp = is_install('sx_erp');
        try{
            $data['update_time'] = date('Y-m-d H:i:s');
            db('crm_c_customerinfo')->where('id',$id)->update($data);
            //插入进店表
            if($isTable){
                $into_id = db('crm_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('crm_c_customer_intostore')->where('id',$into_id)->update($into);
                }else{
                    db('crm_c_customer_intostore')->insert($into);
                }
            }
            // echo db()->getLastSql();
            $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('crm_c_customer_jdm')->where('jd_code',$jd_code)->value('c_id');
            while($cid){
                $jd_code = get_rand_string(8,1);
                $cid = db('crm_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('crm_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('crm_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['c_unique']    = $customerInfo['c_unique'];
            $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'] ? $param['customer_tel'] : $customerInfo['customer_tel'];
            $params['consultation_type'] = $param['consultation_type'];
            $params['tel_static'] = $param['tel_static'];
            $params['no_track'] = '预约进店';
            db('CrmCSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$id,null);
            //修改追踪时间
            $info = $this->getCustomerInfo($id);//客资信息
            $time = date('Y-m-d H:i:s',time());
            if(empty($info['c_start_day'])){
                $arr = array(
                    'c_star_day' => $time,
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }else{
                $arr = array(
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }
            if($info['is_loss'] == 1){
                $arr['is_loss'] = 2;
                $arr['loss_day'] = NULL;
                $arr['loss_cause'] = NULL;
            }
            db('CrmCCustomerinfo')->where('id',$id)->update($arr);
            //修改客资为有效
            if($info['is_valid'] != 1 || empty($info['yx_day'])){
                $upd = array(
                    'is_valid' => 1,
                    'yx_day' => $time
                );
                db('CrmCCustomerinfo')->where('id',$id)->update($upd);
            }
            //修改客资表近三次追踪记录
            getSalesTracking($id);

            if($pool){
                db('crm_c_fp_pool')->insertGetId($pool);
            }
            if($pool1){
                db('crm_c_fp_pool')->insertGetId($pool1);//预约提前提醒
            }
            if($pool2){
                db('crm_c_fp_pool')->insertGetId($pool2);//预约延后提醒
            }
            //如果是爆破活动，修改对应的爆破表数据
            if($info['is_act'] == 2){
                db('crm_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('crm_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('crm_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('crm_c_order_detail')->insertGetId($data);
            if($id){
                $data['pay_type'] = 2;
                $data['order_fact'] = $param['two_pin_fact'];
                return db('crm_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']);
        $target_time = date('Y-m-d H:i:s', strtotime($param['target_time']));
        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['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('crm_c_customerinfo')->where('id', $data['customer_id'])->find();
        if($param['sign_id'] != $customerInfo['sign_id']){
            $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('crm_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('crm_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('crm_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('crm_c_order_detail')->insert($arr);
                // 写入客资表
                $cData['order_number'] = $order_sn;
                $cData['c_end_day'] = $time;
                $cData['last_trackday'] = $time;

                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('crm_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;
                }
                $cData['update_time'] = date('Y-m-d H:i:s');

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

                if($cData['is_success']){
                    //如果是爆破活动，修改对应的爆破表数据
                    if($info['is_act'] == 2){
                        db('crm_c_swap_customer')->where('customer_number',$info['customer_number'])->update(['is_success'=>$cData['is_success']]);
                    }
                }
                history_log($cData, [], $data['customer_id'], session('staff_id'), session('staff_name'));
                //追踪记录
                $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('CrmCSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$data['customer_id'],null);
                //修改追踪时间
                $time = date('Y-m-d H:i:s',time());
                if(empty($info['c_start_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                    );
                }
                db('CrmCCustomerinfo')->where('id',$data['customer_id'])->update($arr);
                getSalesTracking($data['customer_id']);
                //修改进客信息
                /*if($into_id){
                    db('crm_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']          = $customerInfo['customer_cource'] ? $customerInfo['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'] = $customerInfo['consultation_type'] ? $customerInfo['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('crm_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('crm_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'] = $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;
                }
                $cData['update_time'] = date('Y-m-d H:i:s');

                db('crm_c_customerinfo')->where('id', $data['customer_id'])->update($cData);

                $info = db('CrmCCustomerinfo')->where('id',$data['customer_id'])->find();
                if($cData['is_success']){
                    //如果是爆破活动，修改对应的爆破表数据
                    if($info['is_act'] == 2){
                        db('crm_c_swap_customer')->where('customer_number',$info['customer_number'])->update(['is_success'=>$cData['is_success']]);
                    }
                }
                //追踪记录
                $params['customer_id'] = $data['customer_id'];
                $params['c_unique'] = $customerInfo['c_unique'];
                $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('CrmCSalestrackinginfo')->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('CrmCCustomerinfo')->where('id',$data['customer_id'])->update($arr);
                getSalesTracking($data['customer_id']);
                //修改进客信息
                /*if($into_id){
                    db('crm_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());
        }
        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('crm_c_call_registration')->where('shop_code',session('shop_code'))->where('customer_id','null')->field('id,customer_name,audio_path,customer_sex,customer_tel,consultation_type,customer_intention,op_signinfo,customer_cource,customer_channel,access_model,customer_remark,tel_alltime,dj_staff')->order('id desc')->select();
            $count = db('crm_c_call_registration')->where('shop_code',session('shop_code'))->where('customer_id','null')->order('id desc')->count();
        }else{
            $res = db('crm_c_call_registration')->where('dj_staff_id',session('staff_id'))->where('customer_id','null')->field('id,customer_name,audio_path,customer_sex,customer_tel,consultation_type,customer_intention,op_signinfo,customer_cource,customer_channel,access_model,customer_remark,tel_alltime,dj_staff')->order('id desc')->select();
            $count = db('crm_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 json($result);
    }
    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('crm_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') ? session('belong_shop_code') : $info['shop_code'];;
        $param['add_shop_name'] = session('belong_shop_name') ? session('belong_shop_name') : $info['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'];
        $djInfo = getStaffInfoById($info['dj_staff_id']);
        $param['dj_department_id']  = $djInfo['department_id'] ? $djInfo['department_id'] : null;
        $param['dj_department_name']= $djInfo['department_name'] ? $djInfo['department_name'] : null;
        $param['customer_type'] = 1;

        db()->startTrans();
        try{
            $res = $this->addCustomer_child($param);
            if(empty($res)){
                return $returnData = array('code' => 500,'msg' =>'转客资失败','data'=>$res['data']);
            }
            if($res['code'] == 201){
                return json($res);
            }
            if (is_array($res) && $res['code'] != 200) {
                $returnData = array('code' => $res['code'],'msg' =>'转客资失败','data'=>$res['data']);
                return json($returnData);
            } else {
                db('crm_c_call_registration')->where('id', $ord_id)->update(['customer_id' => $res['customer_id']]);
                $customerinfo = db('crm_c_customerinfo')->where('id',$res['customer_id'])->find();
                //追踪记录
                $params['customer_id'] = $res['customer_id'];
                $params['c_unique'] = $customerinfo['c_unique'];
                $params['customer_name'] = $customerinfo['customer_name'];
                $params['customer_tel'] = $customerinfo['customer_tel'];
                $params['customer_number'] = $customerinfo['customer_number'];
                $params['customer_intention'] = $customerinfo['customer_intention'];
                $params['consultation_type'] = $customerinfo['consultation_type'];
                $params['audio_path'] = $info['audio_path'];
                $params['sales_remark'] = '转客资：'.$param['customer_remark'];
                $params['sales_day'] = date('Y-m-d H:i:s',time());
                $params['sales_staff'] = session('staff_name');
                $params['sales_staff_id'] = session('staff_id');
                $params['sales_staff_number'] = session('staff_number');
                $params['shop_name'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('crm_c_salestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$res['customer_id'],null);
                db()->commit();
                $returnData = array('code' => 200,'msg' =>'转客资成功','data'=>'','customer_id'=>$res['customer_id']);
                return json($returnData);
            }
        }catch (\Exception $e){
            db()->rollback();
            return array('code'=>100,'msg'=>'转客资失败','data'=>$e->getMessage());
        }
    }
    function delNewCall($id){
        db()->startTrans();
        $res = db('crm_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('crm_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('crm_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('crm_s_channel')->where($findSql)->where('channel_name','in',explode(',',$trench))->order('order_sort asc')->where($where)->select();
            }else{
                $channel = db('crm_s_channel')->where($where)->where($findSql)->order('order_sort asc')->select();
            }

            //print_r(db()->getLastSql());die;
            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'];
                    }
                }
            }
        }
        // var_dump($channel);die;
        return $channel;
    }
    //获取二级渠道补充
    public function getErChannel($shop_code, $brandclass_id){
        
        $brandclass_id = $brandclass_id ? $brandclass_id : session('brandclass_id');
        if(empty($shop_code)) $shop_code = session('shop_code');
       
        if(!cache('erChannel_'.$shop_code.'_'.$brandclass_id)){
            $findSql = ' FIND_IN_SET("'.$shop_code.'",share_shops) ';
            $channel = db('crm_s_channel')->where($findSql)->order('order_sort')->group("channel_info_id")->select();
            cache('erChannel_'.$shop_code.'_'.$brandclass_id,$channel);
        }else{
            $channel = cache('erChannel_'.$shop_code.'_'.$brandclass_id);
        }

        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('crm_c_customerinfo')
                ->where($where)
                ->where('yjd_day', 'null')
                ->where('jr_day', 'between time', [$three_days_ago, $today])
                ->count('id');
            // 没有订单
            $countO = db('crm_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('crm_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('crm_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('crm_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('crm_c_customerinfo')->where('id',$param['customer_id'])->find();
        db()->startTrans();
        try{
            //修改订单表
            db('crm_c_customer_order')->where('order_sn',$param['old_order_sn'])->update($data);
            //修改客资表
            $cusInfo['order_number'] = $data['order_sn'];
            $cusInfo['update_time']  = $time;
            db('crm_c_customerinfo')->where('id',$param['customer_id'])->update($cusInfo);
            //修改流水表
            //当修改单号时更新原来的流水单号
            if($data['order_sn'] != $param['old_order_sn']){
                db('crm_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);
            exit;
        }

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

                // 向上一级发信息  PC消息
                $reject_staff = db_config('reject_staff_'.session('shop_code'));
                if ($reject_staff) {
                    $rejectInfo = getStaffInfoById($reject_staff);
                    $receive_id = $reject_staff;
                    $receive_name = $rejectInfo['staffname'];
                }else{
                    // 向上一级发信息  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']       = '您有一笔客资被驳回，ID：'.$cInfo['id'].'；姓名：'.$cInfo['customer_name'].'；电话：'.$cInfo['customer_tel'].'；渠道名称：'.$cInfo['customer_channel'].'。驳回理由：'.$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;
                    $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,is_fp,sales_staff,is_valid,sign_name,c_star_day,is_status,is_success,c_from';
        }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,c_from';
        }
        
        if(config('search_use_full_text_index')){
            $searchTel = implode(' ', $tel);
            $res = db('crm_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)
            ->field($field)
            ->select();
        }else{
            $searchTel = "'".implode("','", $tel)."'";
            $res = db('crm_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 crm_c_customer_contact where contact in('.$searchTel.'))')
            ->where('brandclass_id',session('brandclass_id'))
            ->where('is_status',1)
            ->field($field)
            ->select();
        }
        $result['sql'] = db()->getlastsql();;
        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 ($v['c_from'] == 1) {
                    $res[$k]['c_from'] = 'CRM';
                }else if($v['c_from'] == 2){
                    $res[$k]['c_from'] = 'ERP';
                }else{
                    $res[$k]['c_from'] = '未知';
                }
            }
        }

        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('crm_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){
                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 = input();
        $reason = cache('unValidReason');
        if(empty($reason)){
            $url = '5af3fe7a0a668';
            // if($data){
                // $res = sx_call($url,$data);
            // }else{
                $res = sx_call($url);
            // }
            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('crm_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('crm_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('crm_c_customerinfo')->where('id', $cid)->field('is_valid,customer_name,customer_number,customer_tel,customer_sex,dj_staff_id,dj_staff,sales_staff_id,sales_staff')->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('crm_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('crm_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('crm_c_customerinfo')->where('id', $param['cid'])->update($param);

        //如果标记预约，存入pool表
        //查询再约提前时间
        $adv = db('crm_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('crm_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('crm_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('crm_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 [];
        // }
        $mc = new \app\common\lib\mcInterface();
        $detail = $mc->getBrand($data);
        if ($detail === false) {
            $detail = [];
        }
        return $detail;
    }
    //短信记录
    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('crm_c_send_message_log')
                ->where("receive_id",$param['id'])
                ->order('send_time desc')
                ->select();
        }else{
            $info = db('crm_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('crm_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('crm_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('crm_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);
        //     }
        // }
        $mc = new \app\common\lib\mcInterface();
        $detail = $mc->getBrand($data);
        if ($detail === false) {
            $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')
            ->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')
            ->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')
            ->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')
            ->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')
            ->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){
        $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')
            ->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')->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.package_name,o.targetdate,o.consumption_type,o.acceptor_address,o.total_money,o.payment_money,o.nopayment_money,o.ordertopic,o.ordernote,p.currentfc,p.phototype,p.photodate,p.phototime,p.photostate,p.cameraman,p.dresser,p.mentor_a,p.photonote,p.photobase,p.id,p.id as photoid,p.shop_code,p.communication_date,p.communication_state,p.communication_man,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('CrmSMessageTemplateinfo')->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('crm_c_customerinfo')->where('id', $cid)->field('id,customer_name,customer_tel,customer_channel,customer_number,dj_staff_id,dj_staff, sales_staff_id,sales_staff,c_unique')->find();
        if(check_right('menu1517278844') || session('staff_id') == $cInfo['dj_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('crm_c_customerinfo')->where('id', $cid)->update($data);
                // 写入追踪表
                $dataValid = [
                    'gtType'            => '4',
                    'c_unique'       => $cInfo['c_unique'],
                    'customer_id'       => $cid,
                    'customer_name'     => $cInfo['customer_name'],
                    'customer_number'   => $cInfo['customer_number'],
                    'sales_day'         => date('Y-m-d H:i:s'),
                    'sales_staff'       => session('staff_name'),
                    'sales_staff_id'    => session('staff_id'),
                    'sales_staff_number'=> session('staff_number'),
                    'shop_name'         => session('shop_name'),
                    'shop_code'         => session('shop_code'),
                    'sales_remark'      => '客资反驳回：'.$send_msg,
                ];
                db('crm_c_salestrackinginfo')->insert($dataValid);
                getSalesTracking($cid);

                // 向下一级发信息  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']       = '您有一笔客资被反驳回，ID：'.$cInfo['id'].'；姓名：'.$cInfo['customer_name'].'；手机：'.$cInfo['customer_tel'].'；渠道名称：'.$cInfo['customer_channel'].'。请确认。';
                    $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('crm_s_channel')->where('id',$channel_id)->where('shop_code',$data['shop_code'])->find();

            $res = db('crm_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('crm_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('crm_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('crm_s_channel_cost')->insert($ins);

                    db('crm_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('crm_c_customerinfo')->where('id',$param['id'])->update($data);
            //追踪记录
            $params['customer_id'] = $param['id'];
            $params['c_unique'] = $info['c_unique'];
            $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('CrmCSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$param['id'],null);
            //修改追踪时间
            $time = date('Y-m-d H:i:s',time());
            if(empty($info['c_start_day'])){
                $arr = array(
                    'c_star_day' => $time,
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }else{
                $arr = array(
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }
            db('CrmCCustomerinfo')->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('crm_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('crm_c_customerinfo')->where('id',$id)->update($data);
            //追踪记录
            $params['customer_id'] = $id;
            $params['c_unique'] = $info['c_unique'];
            $params['customer_name'] = $info['customer_name'];
            $params['customer_number'] = $info['customer_number'];
            $params['sales_remark'] = '标记有效';
            $params['sales_day'] = date('Y-m-d H:i:s',time());
            $params['sales_staff'] = session('staff_name');
            $params['sales_staff_id'] = session('staff_id');
            $params['sales_staff_number'] = session('staff_number');
            $params['shop_name'] = session('shop_name');
            $params['shop_code'] = session('shop_code');
            db('CrmCSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$id,null);
            //修改追踪时间
            $time = date('Y-m-d H:i:s',time());
            if(empty($info['c_start_day'])){
                $arr = array(
                    'c_star_day' => $time,
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }else{
                $arr = array(
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }
            db('CrmCCustomerinfo')->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('crm_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'] = 1;
                $md5_k = substr(md5($info['id'].session('staff_id').config('SX_AUTH_KEY')),8,16);
                $messageD['operation'] = '[{"button":"查看详情","url":"/crm/Customer/customerList?k='.$md5_k.'&id='.$info['id'].'"}]';
                $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('crm_c_message')->field('send_title')->group('send_title')->select();
            cache('send_title',$temp);
        }
        return $temp;
    }
    //消息 删除
    public function delSendTitle($id,$sum){
        $temp = db('crm_c_message')->where('id','in',$id)->delete();
        if ($temp) {
            action_log(date("Y-m-d H:i:s",time()).session('staff_name')."删除消息".$sum."条",db('crm_c_message')->getLastSql(),session('staff_id'),session('staff_id'),'','crm','Customer','getAllMsgDel');
            return true;
        }else{
            return false;
        }
    }
    //手机端根据权限获取客资录入或提报数量
    public function appGetCustomerNumber($where){
        $count = db('crm_c_customerinfo')->where($where)->count();
        return $count;
    }
    //客资分配  搜索 业绩数 2020-08-04
    public function newCustomerNum($params) {
        if(is_string($params['staff_id']) && strpos($params['staff_id'],',')){
            $staff_id = explode(',',$params['staff_id']);
            $res = db('crm_c_customerinfo')
                ->where('jr_day', 'between time', [$params['start_day'], $params['end_day']])
                ->where('is_status', 1)
                ->where('c_from', 1)
                ->where('shop_code', $params['shop_code'])
                ->where('sales_staff_id','in', $staff_id)
                ->group("sales_staff_id")
                ->column("count(id)","sales_staff_id");
        }else{
            $res = db('crm_c_customerinfo')
                ->where('jr_day', 'between time', [$params['start_day'], $params['end_day']])
                ->where('is_status', 1)
                ->where('c_from', 1)
                ->where('shop_code', $params['shop_code'])
                ->column("count(id)","sales_staff_id");
        }
        // echo db()->getLastSql();
        return $res;
    }
    //客资分配  搜索 有效客资 2020-08-04
    public function validCustomerNumber($params) {
        if(is_string($params['staff_id']) && strpos($params['staff_id'],',')){
            $staff_id = explode(',',$params['staff_id']);
            $res = db('crm_c_customerinfo')
                ->where('yx_day', 'between time', [$params['start_day'], $params['end_day']])
                ->where('is_valid',1)
                ->where('is_status', 1)
                ->where('c_from', 1)
                ->where('shop_code', $params['shop_code'])
                ->where('sales_staff_id','in', $staff_id)
                ->group("sales_staff_id")
                ->column("count(id)","sales_staff_id");
        }else{
            $res = db('crm_c_customerinfo')
                ->where('yx_day', 'between time', [$params['start_day'], $params['end_day']])
                ->where('is_valid',1)
                ->where('is_status', 1)
                ->where('c_from', 1)
                ->where('shop_code', $params['shop_code'])
                ->column("count(id)","sales_staff_id");
        }
        // echo db()->getLastSql();
        return $res;
    }
    //客资分配  搜索 进店 2020-08-04
    public function actualIntoCustomerNumber($params) {
        if(is_string($params['staff_id']) && strpos($params['staff_id'],',')){
            $staff_id = explode(',',$params['staff_id']);
            $res = db('crm_c_customerinfo')
                ->where('syjd_day', 'between time', [$params['start_day'], $params['end_day']])
                ->where('is_intostore','in',[2, 3])
                ->where('is_status', 1)
                ->where('c_from', 1)
                ->where('shop_code', $params['shop_code'])
                ->where('sales_staff_id','in', $staff_id)
                ->group("sales_staff_id")
                ->column("count(id)","sales_staff_id");
        }else{
            $res = db('crm_c_customerinfo')
                ->where('syjd_day', 'between time', [$params['start_day'], $params['end_day']])
                ->where('is_intostore','in',[2, 3])
                ->where('is_status', 1)
                ->where('c_from', 1)
                ->where('shop_code', $params['shop_code'])
                ->column("count(id)","sales_staff_id");
        }
        // echo db()->getLastSql();
        return $res;
    }
    //客资分配  搜索 订单 2020-08-04
    public function orderNumber($params) {
        if(is_string($params['staff_id']) && strpos($params['staff_id'],',')){
            $staff_id = explode(',',$params['staff_id']);
            $res = db('crm_c_customerinfo')
                ->where('order_start_time', 'between time', [$params['start_day'], $params['end_day']])
                ->where('is_success', 1)
                ->where('is_status', 1)
                ->where('c_from', 1)
                ->where('shop_code', $params['shop_code'])
                ->where('sales_staff_id','in', $staff_id)
                ->group("sales_staff_id")
                ->column("count(id)","sales_staff_id");
        }else{
            $res = db('crm_c_customerinfo')
                ->where('order_start_time', 'between time', [$params['start_day'], $params['end_day']])
                ->where('is_success', 1)
                ->where('is_status', 1)
                ->where('c_from', 1)
                ->where('shop_code', $params['shop_code'])
                ->column("count(id)","sales_staff_id");
        }
        // echo db()->getLastSql();
        return $res;
    }
    // 美团=分配给网销的美团客资的数量
    public function getMtCus($params) {
        $start= date('Y-m-d 00:00:00', strtotime($params['start_day']));
        $end  = date('Y-m-d 23:59:59', strtotime($params['end_day']));

        $where['c.jr_day'] = ['between',[$start,$end]];
        $where['c.is_status']= 1;
        $where['c.c_from']   = 1;
        $where['c.is_fp']    = 1;
        $where['c.brandclass_id'] = session('brandclass_id');

        $where['c.shop_code'] = trim($params['shop_code']);
        if ($params['staff_id']) {
            $staff_id = explode(',',$params['staff_id']);
            $where['c.sales_staff_id'] = ['in',$staff_id];
        }
        $res = db('crm_c_customerinfo')->alias('c')
            ->join('crm_s_channel ch','c.customer_channel_id=ch.id','left')
            ->where($where)
            ->where('ch.channel_info_name','美团')
            ->group('c.sales_staff_id')
            ->column('count(c.id)','sales_staff_id');

        return $res;
    }
    // 朋友圈+小红书=分配给网销的朋友圈渠道和小红书渠道的客资汇总
    public function getPxCus($params) {
        $start= date('Y-m-d 00:00:00', strtotime($params['start_day']));
        $end  = date('Y-m-d 23:59:59', strtotime($params['end_day']));

        $where['c.jr_day'] = ['between',[$start,$end]];
        $where['c.is_status']= 1;
        $where['c.c_from']   = 1;
        $where['c.is_fp']    = 1;
        $where['c.brandclass_id'] = session('brandclass_id');

        $where['c.shop_code'] = trim($params['shop_code']);
        if ($params['staff_id']) {
            $staff_id = explode(',',$params['staff_id']);
            $where['c.sales_staff_id'] = ['in',$staff_id];
        }
        $res = db('crm_c_customerinfo')->alias('c')
            ->join('crm_s_channel ch','c.customer_channel_id=ch.id','left')
            ->where($where)
            ->where('ch.channel_info_name','in',['朋友圈','小红书'])
            ->group('c.sales_staff_id')
            ->column('count(c.id)','sales_staff_id');

        return $res;
    }
    // 抖音=分配给网销的抖音渠道客资数量
    public function getDyCus($params) {
        $start= date('Y-m-d 00:00:00', strtotime($params['start_day']));
        $end  = date('Y-m-d 23:59:59', strtotime($params['end_day']));

        $where['c.jr_day'] = ['between',[$start,$end]];
        $where['c.is_status']= 1;
        $where['c.c_from']   = 1;
        $where['c.is_fp']    = 1;
        $where['c.brandclass_id'] = session('brandclass_id');

        $where['c.shop_code'] = trim($params['shop_code']);
        if ($params['staff_id']) {
            $staff_id = explode(',',$params['staff_id']);
            $where['c.sales_staff_id'] = ['in',$staff_id];
        }
        $res = db('crm_c_customerinfo')->alias('c')
            ->join('crm_s_channel ch','c.customer_channel_id=ch.id','left')
            ->where($where)
            ->where('ch.channel_info_name','抖音')
            ->group('c.sales_staff_id')
            ->column('count(c.id)','sales_staff_id');

        return $res;
    }
    // 处理微信状态
    public function setWxStatus($param){
        $cid = (int)$param['cid'];
        $wxstatus = (int)$param['wxstatus'];
        $cInfo = db('crm_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'] = $param['staffInfo']['staff_name'].'通过扫描二维码，复制了微信号，微信状态由：未标记，修改为：待通过';
                        $upCInfo['wechat_status']  = $wxstatus;
                    }else{
                        $insCInfo['sales_remark'] = $param['staffInfo']['staff_name'].'通过扫描二维码，复制了微信号';
                    }
                }else if ($wxstatus=='2') {
                    $insCInfo['sales_remark'] = $param['staffInfo']['staff_name'].'，将微信状态由：'.getWxStatus($cInfo['wechat_status']).'，修改为：已加上';
                    $upCInfo['add_friend_time']= $now;
                    $upCInfo['wechat_status']  = $wxstatus;
                }else if ($wxstatus=='3') {
                    $insCInfo['sales_remark'] = $param['staffInfo']['staff_name'].'，将微信状态由：'.getWxStatus($cInfo['wechat_status']).'，修改为：未加上';
                    $upCInfo['wechat_status']  = $wxstatus;
                }

                // 更新客资表 
                db('crm_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['c_unique'] = $cInfo['c_unique'];
                $insCInfo['sales_day'] = $now;
                $insCInfo['sales_staff'] = $param['staffInfo']['staff_name'];
                $insCInfo['sales_staff_id'] = $param['staffInfo']['staff_id'];
                $insCInfo['sales_staff_number'] = $param['staffInfo']['staff_number'];
                
                $insCInfo['step_name'] = $cInfo['step_name'];
                $insCInfo['shop_name'] = $param['staffInfo']['shop_code'];
                $insCInfo['shop_code'] = $param['staffInfo']['shop_name'];
                db('crm_c_salestrackinginfo')->insert($insCInfo);
                getSalesTracking($cid);
                // 记录日志
                history_log('微信状态：'.getWxStatus($wxstatus), '微信状态：'.getWxStatus($cInfo['wechat_status']),$cid, $param['staffInfo']['staff_id'], $param['staffInfo']['staff_name']);
                db()->commit();
            } catch (\Exception $e) {
                db()->rollback();
                $return['code'] = 100;
                $return['msg']  = '操作失败：'.$e->getMessage();
            }
        }
        
        return $return;
    }


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

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

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

            for($i = 0; $i < $value['timecount']; $i++){
                $setData[] = [
                    'setTime' => $value['pctime'],
                    'setArea' => $value['area']==""?"全部":$value['area']
                ];
            }
        }
        unset($pc_set);
        //已排程数据
        $pc_list = db('c_customerphoto')->alias('p')
            ->join('c_customerinfo c','c.customerid = p.customerid', 'left')
            ->join('c_customerorder o','o.customerid = c.customerid', 'left')
            ->where('p.photodate',$photodate)
            ->field('c.customerid,c.mname,c.wname,c.bbname,c.wphone,c.mphone,c.cssname,c.area,o.orderId,o.package_name,o.targetdate,o.consumption_type,o.acceptor_address,o.total_money,o.payment_money,o.nopayment_money,o.ordertopic,o.ordernote,p.currentfc,p.phototype,p.photodate,p.phototime,p.photostate,p.cameraman,p.dresser,p.mentor_a,p.photonote,p.photobase,p.id,p.id as photoid,p.shop_code,p.communication_date,p.communication_state,p.communication_man,p.shop_name,p.shop_code,c.customer_channel')
            ->order('p.phototime')
            ->select();
        // echo db()->getLastSql();exit;
        //占位数据
        $zd_list = db('c_customerphotozd')
            ->alias('zd')
            ->join('c_customerphoto p','zd.photoid = p.id','left')
            ->join('c_customerinfo c','c.customerid = p.customerid', 'left')
            ->join('c_customerorder o','o.customerid = c.customerid', 'left')
            ->where('zddel=""')
            ->where('zd.shop_code',$shop_code)
            ->where('zd.photodate',$photodate)
            ->field('zd.photodate,zd.phototime,zd.zdtype as phototype,c.customerid,c.mname,c.wname,c.bbname,c.wphone,c.mphone,c.cssname,c.area,o.orderId,o.package_name,o.targetdate,o.consumption_type,o.acceptor_address,o.total_money,o.payment_money,o.nopayment_money,o.ordertopic,o.ordernote,p.currentfc,p.photostate,p.cameraman,p.dresser,p.mentor_a,p.photonote,p.photobase,p.id,p.id as photoid,p.shop_code,p.communication_date,p.communication_state,p.communication_man,p.shop_name,p.shop_code,c.customer_channel')
            ->order('phototime')
            ->select();
        $pc_list = array_merge($pc_list,$zd_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){

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


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

        //改期数据
        $strwhere = "c.shop_code = '".$shop_code."' and  c.photodate = '".$photodate."'";
        $sql = "select  ''as ss,a.customerid,a.mname,a.wname,a.bbname,a.wphone,a.mphone,a.area,
                a.weddingdate, a.customer_channel, b.orderid, b.targetdate, b.consumption_type,
                b.package_name, b.total_money, b.payment_money, b.nopayment_money, b.storeconsuitant1, b.storeconsuitant2, b.storeconsuitant3, b.shop_name as ordershop_name,
                b.ordernote, b.ordertopic, b.paizhaocount, b.rucecount, b.jingxiucount, c.phototype, c.photodate, c.phototime,
                case c.photostate when 0 then '全未拍' when 1 then '未拍完' when 2 then '已拍完' else '' end as photostate, c.cameraman, c.mentor_a,
                c.dresser, c.photonote, c.photobase, c.shop_code, c.shop_name, c.photocount, c.locationcount, indoordresscount,c.Interiorcount, c.paikongstaff, c.paikongtime,
                c.currentfc,p.id as photoid, b.bargain_money, b.supplementary_money, b.nextphotodate, c.yxphotodaystart, c.yxphotodayend, c.callphotomark,c.gqremark,c.qgman,c.gqtime,c.todian
                ,p.photodate as newphotoday ,p.cameraman,p.dresser,p.mentor_a,b.order_type_name,c.dqiseffect,'' as gqtype,c.id as gqid
                from c_customerinfo a join c_customerorder b on a.customerid = b.customerid
                join c_customerphotogq c on b.orderId = c.orderId
                join c_customerphoto p on b.orderId=p.orderId and c.currentfc=p.currentfc and p.islast=1
                where blankoutannal <> 1 and " .$strwhere. "  order by b.targetdate";

        $pc_list = db()->query($sql);

        return $pc_list;
    }
    
    /*
     * 2021.03.11
     * 客资解除订单功能
     */
    public function relieveOrder($id){
        $order = db('c_customerorder')->field("id,crm_customer_id,crm_customer_number,crm_c_unique,crm_order_type,crm_into_id,crm_visit_id,orderId as order_number")->where('id',$id)->find();
        if (!$order) {
            $return['code'] = 100;
            $return['msg']  = '查询订单信息失败！';
            $return['data'] = json_encode($id);
            return $return;
        }

        $return['code'] = 200;
        $return['msg']  = '解除订单成功';

        db()->startTrans();
        try {
            $new = date("Y-m-d H:i:s");
            //crm_into_id : crm  进客表（crm_c_customer_intostore）id
            if ($order['crm_into_id'] && $order['crm_into_id'] > 0) {
                db('crm_c_customer_intostore')->where('id',$order['crm_into_id'])->update(['is_success'=>2,'update_time'=>$new]);
            }

            //crm_visit_id : 预约上门id（crm_l_pc_log）
            if ($order['crm_visit_id'] && $order['crm_visit_id'] > 0) {
                db('crm_l_pc_log')->where('id',$order['crm_visit_id'])->update(['status'=>3]);
            }

            //crm_c_customerinfo
            $c_customerorder = db("c_customerorder")->field("id,orderyouxiaodate,targetdate")->where(["crm_customer_id"=>$order['crm_customer_id'],"id"=>['<>',$id]])->order("orderyouxiaodate asc")->select();
            
            if (count($c_customerorder) > 0) {
                foreach ($c_customerorder as $key => $value) {
                    if (strlen($value['orderyouxiaodate']) > 0) {
                        $orderyouxiaodate[] = $value['orderyouxiaodate'];
                    }
                }
                $c_customerorders = arraySort($c_customerorder,'targetdate',SORT_ASC);
                $targetdate = substr($c_customerorders[0]['targetdate'], 0,4)."-".substr($c_customerorders[0]['targetdate'], 4,2)."-".substr($c_customerorders[0]['targetdate'], 6,2);
                if (isset($orderyouxiaodate)) {
                    //orderyouxiaodate有效时间 有1个或多个 有效值 的情况
                    db('crm_c_customerinfo')->where('id',$order['crm_customer_id'])->update(['order_start_time'=>date("Y-m-d H:i:s",strtotime($targetdate)),'order_day'=>date("Y-m-d H:i:s",strtotime($orderyouxiaodate[0])),'update_time'=>$new]);
                }else{
                    //orderyouxiaodate有效时间 有1个或多个数据  没有效值 的情况
                    db('crm_c_customerinfo')->where('id',$order['crm_customer_id'])->update(['is_success'=>3,'order_start_time'=>date("Y-m-d H:i:s",strtotime($targetdate)),'order_day'=>null,'update_time'=>$new]);
                }
            }else{
                //没有订单数据
                db('crm_c_customerinfo')->where('id',$order['crm_customer_id'])->update(['is_success'=>2,'order_start_time'=>null,'order_day'=>null,'update_time'=>$new]);
            }


            //订单表
            db('c_customerorder')->where('id',$id)->update(['crm_customer_id'=>null,'crm_customer_number'=>null,'crm_c_unique'=>null,'crm_order_type'=>null,'crm_into_id'=>null,'crm_visit_id'=>null]);

            // 记录日志
            history_log('客资解除订单功能 c_customerorder.id：'.$id, $order,$order['crm_customer_id'], session('staff_id'), session('staff_name'));
            db()->commit();
        } catch (\Exception $e) {
            db()->rollback();
            $return['code'] = 100;
            $return['msg']  = '解除订单失败：'.$e->getMessage();
        }
        return $return;
    }

    /*
     * 2021.06.16
     * 客资绑定订单功能
     */
    public function bindingOrder($params){
        $id = $params['id'];
        $crm_customer_id = $params['crm_customer_id'];
        $order = db('c_customerorder')->where('id',$id)->find();
        if (!$order) {
            $return['code'] = 100;
            $return['msg']  = '查询订单信息失败！';
            $return['data'] = json_encode($id);
            return $return;
        }

        $return['code'] = 200;
        $return['msg']  = '绑定订单成功';

        $customer_number = db('crm_c_customerinfo')->where('id',$crm_customer_id)->value('customer_number');

        db()->startTrans();
        try {
            $new = date("Y-m-d H:i:s");
            $target = substr($order['targetdate'], 0,4)."-".substr($order['targetdate'], 4,2)."-".substr($order['targetdate'], 6,2);
            /*
            //crm_into_id : crm  进客表（crm_c_customer_intostore）id
            if ($order['crm_into_id'] && $order['crm_into_id'] > 0) {
                db('crm_c_customer_intostore')->where('id',$order['crm_into_id'])->update(['is_success'=>2,'update_time'=>$new]);
            }

            //crm_visit_id : 预约上门id（crm_l_pc_log）
            if ($order['crm_visit_id'] && $order['crm_visit_id'] > 0) {
                db('crm_l_pc_log')->where('id',$order['crm_visit_id'])->update(['status'=>3]);
            }*/

            if (isset($order['orderyouxiaodate'])) {
                $is_success = 1;
            }else{
                $is_success = 3;
            }

            //crm_c_customerinfo
            $c_customerorder = db("c_customerorder")->field("id,orderyouxiaodate,targetdate")->where(["crm_customer_id"=>$crm_customer_id,"id"=>['<>',$id]])->order("orderyouxiaodate asc")->select();
            
            if (count($c_customerorder) > 0) {
                foreach ($c_customerorder as $key => $value) {
                    if (strlen($value['orderyouxiaodate']) > 0) {
                        $orderyouxiaodate[] = $value['orderyouxiaodate'];
                    }
                }
                $c_customerorders = arraySort($c_customerorder,'targetdate',SORT_ASC);
                $targetdate = substr($c_customerorders[0]['targetdate'], 0,4)."-".substr($c_customerorders[0]['targetdate'], 4,2)."-".substr($c_customerorders[0]['targetdate'], 6,2);
                if (isset($orderyouxiaodate)) {
                    //orderyouxiaodate有效时间 有1个或多个 有效值 的情况
                    $is_success = 1;
                    $orderyouxiao = date("Y-m-d H:i:s",strtotime($orderyouxiaodate[0]));
                    if ($$orderyouxiao > $order['orderyouxiaodate']) {
                        $order['orderyouxiaodate'] = $orderyouxiao;
                    }
                }
            }

            db('crm_c_customerinfo')->where('id',$crm_customer_id)->update(['is_success'=>$is_success,'order_start_time'=>date("Y-m-d H:i:s",strtotime($target)),'order_day'=>$order['orderyouxiaodate']?:null,'update_time'=>$new]);


            //订单表
            db('c_customerorder')->where('id',$id)->update(['crm_customer_id'=>$crm_customer_id,'crm_customer_number'=>$customer_number,'crm_order_type'=>1]);

            // 记录日志
            history_log('客资绑定订单功能 c_customerorder.id：'.$id, $order,$crm_customer_id, session('staff_id'), session('staff_name'));
            db()->commit();
        } catch (\Exception $e) {
            db()->rollback();
            $return['code'] = 100;
            $return['msg']  = '绑定订单失败：'.$e->getMessage();
        }
        return $return;
    }

    /**
     * 对重复客资进行列新
     * 
     * @param  [type] $oldCustomer [description]
     * @param  [type] $newCustomer [description]
     * @return [type]              [description]
     */
    public function saveRepeatCustomer($oldCustomer,$newCustomer,$opip,$opname,$opid){
        $data = [];
        $logOld = '';
        $logNew = '';
        $oldCustomer = db('crm_c_customerinfo')->find($oldCustomer['id']);
        if($newCustomer['baby_name'] && $oldCustomer['baby_name'] != $newCustomer['baby_name']){
            $data['baby_name'] = $newCustomer['baby_name'];
            $logOld .= '宝宝性名：'.$oldCustomer['baby_name'];
            $logNew .= '宝宝性名：'.$newCustomer['baby_name'];
        }
        if($newCustomer['baby_sex'] && $oldCustomer['baby_sex'] != $newCustomer['baby_sex']){
            $data['baby_sex'] = $newCustomer['baby_sex'];
            $logOld .= '宝宝性名：'.$oldCustomer['baby_sex'];
            $logNew .= '宝宝性名：'.$newCustomer['baby_sex'];
        }
        if($newCustomer['baby_address'] && $oldCustomer['baby_address'] != $newCustomer['baby_address']){
            $data['baby_address'] = $newCustomer['baby_address'];
            $logOld .= '出生医院：'.$oldCustomer['baby_address'];
            $logNew .= '出生医院：'.$newCustomer['baby_address'];
        }
        if($newCustomer['baby_birthday'] && $oldCustomer['baby_birthday'] != $newCustomer['baby_birthday']){
            $data['baby_birthday'] = $newCustomer['baby_birthday'];
            $logOld .= '宝宝生日：'.$oldCustomer['baby_birthday'];
            $logNew .= '宝宝生日：'.$newCustomer['baby_birthday'];
        }
        if($newCustomer['ready_baby_day'] && $oldCustomer['ready_baby_day'] != $newCustomer['ready_baby_day']){
            $data['ready_baby_day'] = $newCustomer['ready_baby_day'];
            $logOld .= '预产期：'.$oldCustomer['ready_baby_day'];
            $logNew .= '预产期：'.$newCustomer['ready_baby_day'];
        }
        if($newCustomer['customer_name'] && $oldCustomer['customer_name'] != $newCustomer['customer_name']){
            $data['customer_name'] = $newCustomer['customer_name'];
            $logOld .= '妈妈姓名：'.$oldCustomer['customer_name'];
            $logNew .= '妈妈姓名：'.$newCustomer['customer_name'];
        }
        if($newCustomer['customer_tel'] && $oldCustomer['customer_tel'] != $newCustomer['customer_tel']){
            $data['customer_tel'] = $newCustomer['customer_tel'];
            $logOld .= '妈妈电话：'.$oldCustomer['customer_tel'];
            $logNew .= '妈妈电话：'.$newCustomer['customer_tel'];
        }
        if($newCustomer['customer_wechat'] && $oldCustomer['customer_wechat'] != $newCustomer['customer_wechat']){
            $data['customer_wechat'] = $newCustomer['customer_wechat'];
            $logOld .= '妈妈微信：'.$oldCustomer['customer_wechat'];
            $logNew .= '妈妈微信：'.$newCustomer['customer_wechat'];
        }
        if($newCustomer['customer_qq'] && $oldCustomer['customer_qq'] != $newCustomer['customer_qq']){
            $data['customer_qq'] = $newCustomer['customer_qq'];
            $logOld .= '妈妈QQ：'.$oldCustomer['customer_qq'];
            $logNew .= '妈妈QQ：'.$newCustomer['customer_qq'];
        }
        if($newCustomer['customer_weibo'] && $oldCustomer['customer_weibo'] != $newCustomer['customer_weibo']){
            $data['customer_weibo'] = $newCustomer['customer_weibo'];
            $logOld .= '妈妈微博：'.$oldCustomer['customer_weibo'];
            $logNew .= '妈妈微博：'.$newCustomer['customer_weibo'];
        }
        if($newCustomer['customer_idnumber'] && $oldCustomer['customer_idnumber'] != $newCustomer['customer_idnumber']){
            $data['customer_idnumber'] = $newCustomer['customer_idnumber'];
            $logOld .= '妈妈证件号：'.$oldCustomer['customer_idnumber'];
            $logNew .= '妈妈证件号：'.$newCustomer['customer_idnumber'];
        }
        if($newCustomer['mate_name'] && $oldCustomer['mate_name'] != $newCustomer['mate_name']){
            $data['mate_name'] = $newCustomer['mate_name'];
            $logOld .= '爸爸姓名：'.$oldCustomer['mate_name'];
            $logNew .= '爸爸姓名：'.$newCustomer['mate_name'];
        }
        if($newCustomer['mate_tel'] && $oldCustomer['mate_tel'] != $newCustomer['mate_tel']){
            $data['mate_tel'] = $newCustomer['mate_tel'];
            $logOld .= '爸爸电话：'.$oldCustomer['mate_tel'];
            $logNew .= '爸爸电话：'.$newCustomer['mate_tel'];
        }
        if($newCustomer['mate_wechat'] && $oldCustomer['mate_wechat'] != $newCustomer['mate_wechat']){
            $data['mate_wechat'] = $newCustomer['mate_wechat'];
            $logOld .= '爸爸微信：'.$oldCustomer['mate_wechat'];
            $logNew .= '爸爸微信：'.$newCustomer['mate_wechat'];
        }
        if($newCustomer['mate_qq'] && $oldCustomer['mate_qq'] != $newCustomer['mate_qq']){
            $data['mate_qq'] = $newCustomer['mate_qq'];
            $logOld .= '爸爸QQ：'.$oldCustomer['mate_qq'];
            $logNew .= '爸爸QQ：'.$newCustomer['mate_qq'];
        }
        if($newCustomer['mate_weibo'] && $oldCustomer['mate_weibo'] != $newCustomer['mate_weibo']){
            $data['mate_weibo'] = $newCustomer['mate_weibo'];
            $logOld .= '爸爸微博：'.$oldCustomer['mate_weibo'];
            $logNew .= '爸爸微博：'.$newCustomer['mate_weibo'];
        }
        if($newCustomer['mate_idnumber'] && $oldCustomer['mate_idnumber'] != $newCustomer['mate_idnumber']){
            $data['mate_idnumber'] = $newCustomer['mate_idnumber'];
            $logOld .= '爸爸证件号：'.$oldCustomer['mate_idnumber'];
            $logNew .= '爸爸证件号：'.$newCustomer['mate_idnumber'];
        }
        if($newCustomer['customer_address'] && $oldCustomer['customer_address'] != $newCustomer['customer_address']){
            $data['customer_address'] = $newCustomer['customer_address'];
            $logOld .= '地址：'.$oldCustomer['customer_address'];
            $logNew .= '地址：'.$newCustomer['customer_address'];
        }
        if($newCustomer['customer_key'] && $oldCustomer['customer_key'] != $newCustomer['customer_key']){
            $data['customer_key'] = $newCustomer['customer_key'];
            $logOld .= '关键字：'.$oldCustomer['customer_key'];
            $logNew .= '关键字：'.$newCustomer['customer_key'];
        }
        db('crm_c_customerinfo')->where('id',$oldCustomer['id'])->update($data);
        $log = [
            'module'=>'crm',
            'controller'=>'customer',
            'action'=>'editcustomer',
            'old_data'=>$logOld,
            'data'=>$logNew,
            'customer_id'=>$oldCustomer['id'],
            'ip'=>$opip,
            'staff_name'=>$opname,
            'staff_id'=>$opid,
            'create_time'=>date('Y-m-d H:i:s'),
        ];
        db('crm_action_log','db_logs')->insert($log);
    }

    //通话记录
    public function getCallList($param){
        // if($param['customer_tel']) $phone[] = $param['customer_tel'];
        $info = db('osip_table_calllog','db_call')
            ->where("uufrom",$param['customer_tel'])
            ->whereOr('uuto',$param['customer_tel'])
            ->order('uuid desc')
            ->select();
        if (count($info) > 0) {
            $call_man = db('crm_s_call_man')->column("staff_name","user");
            foreach ($info as $key => $value) {
                if (strlen($value['uufrom']) != 11 && $call_man[$value['uufrom']]) {
                    $info[$key]['uufrom'] = $call_man[$value['uufrom']];
                }
                if (strlen($value['uuto']) != 11 && $call_man[$value['uuto']]) {
                    $info[$key]['uuto'] = $call_man[$value['uuto']];
                }
                if ($value['uuestablishedlength'] > 0) {
                    $info[$key]['url'] = "http://192.168.8.248:8833/osip_playwave.cpc?guid=".$value['uuguid'];
                }else{
                    $info[$key]['url'] = '';
                }
                $info[$key]['uuestablishedtime_str'] = $value['uuestablishedtime_str'] == '1970-01-01 08:00:00' ? '' : $value['uuestablishedtime_str'];
                $info[$key]['uufinishedtime_str'] = $value['uufinishedtime_str'] == '1970-01-01 08:00:00' ? '' : $value['uufinishedtime_str'];
                // $info[$key]['uuestablishedlength'] = $value['uuestablishedlength'] > 0 ? SToHis($value['uuestablishedlength']) : 0;
            }
        }
        return $info;
    }

}