<?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 Testcustomer 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['app_id'] = config('app_id');
        $url = '59f2e9fb5f863';
        $res = sx_call($url,$params);
        //var_dump($res);die;
        if($res['code'] == 200){
            $loginRes = $this->setLoginEnv($res['data'],'pc','user_name',$params['five']);
            if($loginRes){
                //所有可查看店的岗位
                $info = $this->getPositions();
                if($info){
                    session('positions_'.session('staff_id'),$info);
                }
                $returnUrl = '/';
                if(session('return_url')){
                    $returnUrl = session('return_url');
                    session('return_url',null);
                }
                return [
                    'code'=>200,
                    'return_url'=>$returnUrl,
                ];
            }else{
                $res = array('code'=>101,'error'=>101,'msg'=>'登录失败，请重试。');
            }

        }else{
            if($res['code'] == 500){
                $res = array('code'=>500,'error'=>101,'msg'=>'此员工已离职');
            }else{
                $res = array('code'=>100,'error'=>101,'msg'=>'用户名或密码错误');
            }
        }
        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;
        }
        session();
        session('staff_id',$loginRes['staff_id']);
        session('staff_name',$loginRes['staffname']);
        session('staff_number',$loginRes['staffnumber']);
        session('session_id',$loginRes['session_id']);
        session('brandclass_id',$loginRes['brandclass_id']);
        session('brandclass',$loginRes['brandclass']);
        session('shop_name',$loginRes['shop_name']);
        session('shop_code',$loginRes['shop_code']);
        session('belong_shop_name',$loginRes['belong_shop_name']);
        session('belong_shop_code',$loginRes['belong_shop_code']);
        session('is_sk',$loginRes['is_sk']);
        session('shop_type',$loginRes['shop_type']);
        session('setkey',$loginRes['setkey']);
        session('main_work_type',$loginRes['main_work_type']);
        session('work_type',$loginRes['work_type']);
        session('department_name',$loginRes['department_name']);
        session('department_id',$loginRes['department_id']);
        session('position_code',$loginRes['position_code']);
        session('group_company_name',$loginRes['group_company_name']);
        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']);
        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']);
        }
        //操作session表
        $db = db('SSession');
        $staffInfo = $db->where(array('staff_id' => $loginRes['staff_id']))->find();

        $db->startTrans();
        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;
            $resdb = $db->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;
            $resdb = $db->insert($param);
        }
        if($resdb){
            $db->commit();
            return true;
        }else{
            $db->rollBack();
            return false;
        }
    }

    function update_status($status){
        // 取出员工信息
        $info = cache('staffInfo_'.cookie('staff_id'));
        // 赋值状态
        $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;
        // $param['status'] = $status;
        // $db = db('SSession');
        // $db->startTrans();
        // $res = $db->where(array('staff_id' => session('staff_id')))->update($param);
        // if($res){
        //     cookie('status',$status);
        //     $db->commit();
        //     return true;
        // }else{
        //     $db->rollBack();
        //     return false;
        // }
    }
    /*
     * 短消息
     * */
    public function message_list($type){
        $res = db('CMessage')->where('send_type',$type)->where('is_delete',0)->where('receive_id',session('staff_id'))->select();
        return $res;
    }
    /*
     * 通知
     * */
    public function notice_list(){
        return db('CMessage')->where('send_type',2)->where('is_delete',0)->where('receive_id',session('staff_id'))->select();
    }
    /*
     * 查看信息，通知
     */
    function update_message($id){
        $info = db('CMessage')->where('is_delete',0)->where('id',$id)->find();
        if($info && $info['read_status'] == 0){
            //修改状态，更新时间
            $data['read_status'] = 1;
            $data['read_time'] = date('Y-m-d H:i:s',time());
            db()->startTrans();
            $res = db('CMessage')->where('id',$id)->update($data);
            if($res === false){
                db()->rollBack();
                return false;
            }else{
                db()->commit();
                $info['read_status'] == 1;
                $info['read_time'] = $data['read_time'];
                return $info;
            }
        }else{
            return $info;
        }
    }
    function logOut($staffId){
        $staffId = cookie('staff_id');
        cache('staffInfo_'.$staffId,null);
        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);
        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);
        if( (time() - $info['active'] > 160) || ($info['status'] != 1) ){
            return false;
        }else{
            return true;
        }
    }
    function wx_login($param){
        $url = '5a029ee140dba';
        //$param['open_id'] = cookie('openId');
        $res = sx_call($url,$param);//openid和员工对应，调登录接口
        if($res['code'] == 200){
            //绑定openid成功与否无所谓，大不了再输一次密码
            // sx_call('5a2239cf24883', ['staffname'=>$param['staffname'],'password'=>$param['password'],'open_id'=>$param['open_id']]);
            $this->setLoginEnv($res['data'], 'WX', 'user_name', 0);

            $arr = array(
                'code' => 200,
                'msg' =>'',
                'data' =>  $param
            );
        }else {
            $arr = array(
                'code' => 100,
                'msg' =>'登录失败，请重试',
                'data' =>  $param
            );
        }
        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);
    }
    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){//管理员
            $res['sql']="add_shop_code = :add_shop_code OR shop_code =:belong_shop_code";
            $res['arr']['add_shop_code']=session('shop_code');
            $res['arr']['belong_shop_code']=session('shop_code');
        }else{//默认显示
            $res['sql']="dj_staff_id = :dj_staff_id or sales_staff_id = :sales_staff_id or sk_staff_id = :sk_staff_id";
            $res['arr']['dj_staff_id']=$info['id'];
            $res['arr']['sales_staff_id']=$info['id'];
            $res['arr']['sk_staff_id']=$info['id'];
        }

        // }
        return $res;
    }

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

        //$res = db('CCustomerinfo')->where('sales_staff_id',$staffId)->whereTime('fp_day',$where)->where('is_status',1)->count();
        /*       if(check_right('menu1512637269')){
                   $sql="shop_code = :shop_code";
                   $arr['shop_code']=session('shop_code');
               }else{
                   $sql="sales_staff_id = :sales_staff_id or dj_staff_id = :dj_staff_id";
                   $arr['sales_staff_id']=$staffId;
                   $arr['dj_staff_id']=$staffId;
               }
        */
        $arr=$this->get_sales_auth($info);
        $res = db('CCustomerinfo')->where($arr['sql'],$arr['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //有效进店
    public function validJD($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where('is_intostore',1)->where('is_valid',1)->where($res['sql'],$res['arr'])->whereTime('syjd_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //无效新单
    public function invalidOrder($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where('is_success',1)->where('is_valid',3)->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //营收
    public function fact($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->sum('fact_money');
        return $res;
    }
    //流失
    public function loss($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where($res['sql'],$res['arr'])->whereTime('loss_day',$where)->where('is_loss',1)->where('c_from',1)->count();
        return $res;
    }
    //花费
    function cost($info,$where){
        $res = db('s_channel_cost')->where('shop_code',$info['shop_code'])->whereTime('cost_date',$where)->sum('cost');
        return $res;
    }
    //有效订单
    function order_crm($staffId,$where){
        /*$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->orderNumber(array('start_day'=>$time[0],'end_day'=>$time[1],'staff_id'=>$staffId));
        //$res = db('CCustomerinfo')->where(array('sales_staff_id'=>$staffId,'is_success'=>1,'is_fp'=>1))->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where(array('is_success'=>1))->where($res['sql'],$res['arr'])->whereTime('order_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //订单
    public function sucOrder($info,$where){
        $res=$this->get_sales_auth($info);
        $res = db('CCustomerinfo')->where(array('is_success'=>1))->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //实际进店
    public function factIn($info,$where){
        $res=$this->get_sales_auth($info);
        $res = db('CCustomerinfo')->whereTime('syjd_day',$where)->where($res['sql'],$res['arr'])->where('is_status',1)->count();
        return $res;
    }
    //预约进店
    public function makeIn($info,$where){
        $res=$this->get_sales_auth($info);
        $res = db('CCustomerinfo')->whereTime('yjd_day',$where)->where($res['sql'],$res['arr'])->where('is_status',1)->count();
        return $res;
    }
    //待追踪
    function jdwd_crm($info,$where){
        //$res = db('CCustomerinfo')->where(array('sales_staff_id'=>$staffId,'c_star_day'=>null,'is_fp'=>1))->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where(array('c_star_day'=>null,'is_fp'=>1))->where($res['sql'],$res['arr'])->whereTime('jr_day',$where)->where('is_status',1)->where('c_from',1)->count();
        return $res;
    }
    //A客资
    function cus_a($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where('sign_name', 'like','A%')->where($res['sql'],$res['arr'])->whereTime('sign_time',$where)->where('is_status',1)->where('c_from',1)->count();
        return $res;
    }
    //待分配
    function fp_crm($staffId,$where){
        //$res = db('CCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_fp'=>2))->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where(array('is_fp'=>2))->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //获取到电话的客资数量
    public function getTelCount($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where('customer_tel|mate_tel','<>','')->where($res['sql'],$res['arr'])->whereTime('tel_time',$where)->whereTime('creator_day',$where)->where('is_status',1)->where('c_from',1)->count();
        return $res;
    }
    //获取到微信QQ的客资数量
    public function getQQCount($info,$where){
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where('customer_qq|customer_wechat','<>','')->where($res['sql'],$res['arr'])->whereTime('qq_time|wechat_time',$where)->whereTime('creator_day',$where)->where('is_status',1)->where('c_from',1)->count();
        return $res;
    }
    //追踪中
    function staff_id_crm($staffId,$where){
        //$res = db('CCustomerinfo')->where(array('sales_staff_id'=>$staffId,'is_valid'=>1,'is_fp'=>1))->where('c_star_day','<>','')->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where(array('is_valid'=>1,'is_fp'=>1))->where($res['sql'],$res['arr'])->where('c_star_day','<>',null)->whereTime('c_star_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //已预约
    function yuyue_crm($staffId,$where){
        //$res = db('CCustomerinfo')->where(array('sales_staff_id'=>$staffId))->where('yjd_day','<>','')->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where($res['sql'],$res['arr'])->where('yjd_day','<>','')->whereTime('creator_day',$where)->where('is_status',1)->count();
        // $res = db('c_day_number')->where(array('staff_id'=>$staffId))->whereTime('addtime',$where)->sum('yjd');
        return $res;
    }
    //进店未定
    function jdwd1_crm($staffId,$where){//进客+非进客-成单数
        // $res1 = db('c_day_number')->where(array('staff_id'=>$staffId))->whereTime('addtime',$where)->sum('syjd_jk');
        // $res2 = db('c_day_number')->where(array('staff_id'=>$staffId))->whereTime('addtime',$where)->sum('syjd_no_jk');
        // $res3 = db('c_day_number')->where(array('staff_id'=>$staffId))->whereTime('addtime',$where)->sum('orders');
        //$res = db('CCustomerinfo')->where(array('sales_staff_id'=>$staffId,'is_intostore'=>1,'is_success'=>2))->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where(array('is_intostore'=>1,'is_success'=>2))->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //进店(邀约)
    function jd_crm($info,$where){
        //$res = db('CCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_intostore'=>1))->whereTime('creator_day',$where)->count();
        $res=$this->get_sales_auth($info,$where);
        $res = db('CCustomerinfo')->where('is_intostore','in','2,3')->where($res['sql'],$res['arr'])->whereTime('syjd_day',$where)->where('is_status',1)->count();
        return $res;
    }
    //订单消费总额
    function xiaofei_amount($shop_code,$where){
        $res = db('c_customerinfo')->where('shop_code',$shop_code)->whereTime('creator_day',$where)->where('is_status',1)->sum('totalpay_money');
        return $res;
    }
    //实收总额
    function shishou_amount($shop_code,$where){
        /* $t = new Target();
         if($where == 'month'){
             $where = 'this_month';
         }elseif($where == 'last_month'){
             $where = 'last_month';
         }elseif($where == 'week'){
             $where = 'this_week';
         }elseif($where == 'last_week'){
             $where = 'last_week';
         }else{
             $where = 'this_month';
         }
         $time = getdateArea($where);*/
        // $res = $t->dealAmount(array('start_day'=>$time[0],'end_day'=>$time[1],'staff_id'=>$staffId,'staff_type'=>'sales_staff_id'));
        $res = db('c_customer_order')->where('shop_code',$shop_code)->whereTime('create_time',$where)->field('SUM(order_amount)')->find();
        return $res;
    }
    //沟通阶段和条数
    function get_seles_count($staff_id,$where){
        $r=$this->get_sales_auth($staff_id);
        $res = db('s_sales_routines')->where('shop_code',session('shop_code'))->order('id asc')->select();
        foreach($res as $k=>$v){
            $res[$k]['count'] = db('CCustomerinfo')
                ->where($r['sql'],$r['arr'])->whereTime('c_end_day',$where)->where('is_status',1)->where('seles_step',$v['step_stage'])
                ->count('id');
        }
        return $res;
    }
    //沟通总条数
    function get_total_count($staff_id,$times){
        $res=$this->get_sales_auth($staff_id);
        $count = db('CCustomerinfo')
            ->whereTime('c_end_day',$times)
            ->where('is_status',1)
            // ->where('sales_staff_id = :sales_staff_id and is_fp = :is_fp',['sales_staff_id'=>$staff_id,'is_fp'=>1])
            ->where($res['sql'],$res['arr'])
            // ->whereOr('dj_staff_id = :dj_staff_id',['dj_staff_id'=>$staff_id])
            ->count('id');
        return $count;
    }
    //无效
    function null_crm($staffId,$where){
        // $res = db('c_day_number')->where(array('staff_id'=>$staffId))->whereTime('addtime',$where)->sum('no_valid_customer');
        $res=$this->get_sales_auth($staffId);
        $res = db('CCustomerinfo')->where('is_valid',3)->where($res['sql'],$res['arr'])->whereTime('creator_day',$where)->where('is_status',1)->count('id');
        return $res;
    }

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

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

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

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

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

                $v['customer_type'] = $v['customer_type'] == 1 ? '新客资' : '转介绍';
                if(!check_right('menu1512998373')){
                    $v['customer_tel'] = !empty($v['customer_tel']) ? substr($v['customer_tel'], 0, 3).'****'.substr($v['customer_tel'], 7) : '';
                }
                $data['rows'][$k]['cell'] = array_values($v);
            }
            // foreach($res2 as $k=>$v){
            //     $data['rows'][$k]['id'] = array_values($v);
            // }
        }
        return $data;
    }
    //五维图
    function getHomeTu($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('SStaffAbility')->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();
        $info = $this->get_sales_auth($ret['data']);

        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);
            }
            /*switch($va){
                case 'newCustomerNum'://毛客资量
                    $dj_customer2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('creator_day',$times)->where('is_status',1)->count('id');
                    $res[$ke] = $dj_customer2;
                    break;
                case 'validCustomerNumber'://有效客资量
                    $valid_customer2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('creator_day',$times)->where('is_valid',1)->where('is_status',1)->count('id');
                    $res[$ke] = $valid_customer2;
                    break;
                case 'inviteIntoCustomerNumber'://邀约进店客资量
                    $yjd2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('creator_day',$times)->where('yjd_day','<>','')->count('id');
                    $res[$ke] = $yjd2;
                    break;
                case 'actualIntoCustomerNumber'://实际进店客资量
                    $syjd_jk2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('syjd_day',$times)->where('is_intostore',2)->count('id');
                    $res[$ke] = $syjd_jk2;
                    break;
                case 'orderNumber'://成交量
                    $order2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('order_day',$times)->where('is_success',1)->count('id');
                    $res[$ke] = $order2;
                    break;
                case 'telVisitNumber'://电访量
                    $res[$ke] = db('CCustomerinfo')->whereTime('c_end_day',$times)->where($info['sql'],$info['arr'])->sum('tel_visit_num');
                    break;
                case 'orderValueRate'://订单转化率 有效成单/有效
                    $valid = db('CCustomerinfo')->whereTime('creator_day',$times)->where('is_valid',1)->where($info['sql'],$info['arr'])->count('id');
                    $succ = db('CCustomerinfo')->whereTime('order_day',$times)->where(array('is_valid',1,'is_success'=>1))->count('id');
                    $res[$ke] = ($succ/$valid)*100;
                    break;
                case 'valueCustomerRate'://客资有效率
                    $valid_customer2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('creator_day',$times)->count('id');
                    $dj_customer2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('order_day',$times)->where('is_success',1)->count('id');
                    $res[$ke] = ($dj_customer2/$valid_customer2)*100;
                    break;
                case 'valueCustomerIntoRate'://客资进店率
                    $syjd_jk2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('creator_day',$times)->where('is_intostore',2)->count('id');
                    $valid_customer2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('syjd_day',$times)->count('id');
                    $res[$ke] = ($syjd_jk2/$valid_customer2)*100;
                    break;
                case 'valueCustomerconvertRate'://客资转换率
                    $order2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('creator_day',$times)->where('is_success',1)->count('id');
                    $dj_customer2 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('creator_day',$times)->count('id');
                    $res[$ke] = ($order2/$dj_customer2)*100;
                    break;
                case 'dealAmount'://成交金额
                    $res[$ke] = db('CCustomerinfo')->where('order_status',1)->where($info['sql'],$info['arr'])->whereTime('order_day',$times)->sum('totalpay_money');
                    break;
                case 'intoValueRate'://进店转换率
                    $is_intostore = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('creator_day',$times)->where('is_intostore','<>',1)->count('id');
                    $is_intostore1 = db('CCustomerinfo')->where($info['sql'],$info['arr'])->whereTime('syjd_day',$times)->where('is_valid',1)->count('id');
                    $res[$ke] = ($is_intostore/$is_intostore1)*100;
                    break;
            }*/
            $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){
        $year = date('Y',time());
        $month = date('m',time());
        if($shop['where'] == 'last month'){
            if($month == 1){
                $year = $year-1;
                $month = 12;
            }else{
                $month = $month-1;
            }
            //根据人员查目标
            $res = db('SKpiStaffgoal')->where(array('shop_code'=>$shop['info']['shop_code'],'year'=>$year,'month'=>$month))->where('staff_id',$shop['staff_id'])->where('flag','staff')->field('kpi_id,kpi_name,kpi_value,kpi_unit,channel_id,province_id,city_id')->limit(5)->order('order_sort asc')->select();
            if(empty($res)){
                //根据岗位查目标
                $res = db('SKpiStaffgoal')->where(array('shop_code'=>$shop['info']['shop_code'],'year'=>$year,'month'=>$month))->where('position_code',$shop['main_position_code'])->where('flag','position')->field('kpi_id,kpi_name,kpi_value,kpi_unit,channel_id,province_id,city_id')->limit(5)->order('order_sort asc')->select();
            }
        }else{
            $res = db('SKpiStaffgoal')->where(array('shop_code'=>$shop['info']['shop_code'],'year'=>$year,'month'=>$month))->where('staff_id',$shop['staff_id'])->where('flag','staff')->field('kpi_id,kpi_name,kpi_value,kpi_unit,channel_id,province_id,city_id')->limit(5)->order('order_sort asc')->select();
            if(empty($res)) {
                $res = db('SKpiStaffgoal')->where(array('shop_code' => $shop['info']['shop_code'], 'year' => $year, 'month' => $month))->where('position_code', $shop['main_position_code'])->where('flag', 'position')->field('kpi_id,kpi_name,kpi_value,kpi_unit,channel_id,province_id,city_id')->limit(5)->order('order_sort asc')->select();
            }
        }
        $time = getdateArea($shop['where']);
        $ret=$this->get_sales_auth($shop['info']);
        foreach($res as $ke=>$va){
            if($va['kpi_id'] == 'dealAmount'){
                $data = array(
                    'start_day' => $time[0],
                    'end_day' => $time[1],
                    'staff_id' => $shop['staff_id'],
                    'staff_type' => 'dj_staff_id'
                );
            }else{
                $data = array(
                    'start_day' => $time[0],
                    'end_day' => $time[1],
                    'shop_code' => $shop['shop_code'],
                    'staff_id' => $shop['staff_id'],
                    'channel_id'=>$va['channel_id'],
                    'province_id'=>$va['province_id'],
                    'city_id'=>$va['city_id'],
                );
            }

            $tar = new Target();
            $reach = $tar->$va['kpi_id']($data);
//            switch($va['kpi_id']) {
//                case 'newCustomerNum'://毛客资量
//                    $reach = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('creator_day', $shop['where'])->where('is_status',1)->where('is_status',1)->count('id');
//                    break;
//                case 'validCustomerNumber'://有效客资量
//                    $reach = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('yx_day', $shop['where'])->where('is_valid', 1)->where('is_status',1)->count('id');
//                    break;
//                case 'inviteIntoCustomerNumber'://邀约进店客资量
//                    $reach = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('yjd_day', $shop['where'])->where('is_status',1)->count('id');
//                    break;
//                case 'actualIntoCustomerNumber'://实际进店客资量
//                    $reach = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('syjd_day', $shop['where'])->where('is_intostore','<>',1)->where('is_status',1)->count('id');
//                    break;
//                case 'orderNumber'://成交量
//                    $reach = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('order_start_time', $shop['where'])->where('is_success', 1)->where('is_status',1)->count('id');
//                    break;
//                case 'telVisitNumber'://电访量
//                    $reach = db('c_salestrackinginfo')->whereTime('sales_day', $shop['where'])->where($ret['sql'],$ret['arr'])->where('gtType',1)->count('id');
//                    break;
//                case 'valueCustomerRate'://客资有效率
//                    $valid_customer2 = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('yx_day', $shop['where'])->where('is_status',1)->where('c_from', 1)->where('is_valid',1)->count('id');
//                    $dj_customer2 = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('dj_day', $shop['where'])->where('is_status',1)->count('id');
//                    $reach = ($dj_customer2 / $valid_customer2) * 100;
//                    break;
//                case 'valueCustomerIntoRate'://客资进店率
//                    $syjd_jk2 = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('syjd_day', $shop['where'])->where('is_intostore', 2)->where('is_status',1)->where('c_from', 1)->count('id');
//                    $valid_customer2 = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('yx_day', $shop['where'])->where('is_status',1)->where('is_valid',1)->where('c_from', 1)->count('id');
//                    $reach = ($syjd_jk2 / $valid_customer2) * 100;
//                    break;
//                case 'valueCustomerconvertRate'://客资转换率
//                    $order2 = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('yx_day', $shop['where'])->where('is_success', 1)->where('is_status',1)->where('is_valid',1)->where('c_from', 1)->count('id');
//                    $dj_customer2 = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('dj_day', $shop['where'])->where('is_status',1)->where('c_from', 1)->count('id');
//                    $reach = ($order2 / $dj_customer2) * 100;
//                    break;
//                case 'dealAmount'://成交金额
//                    $reach = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('order_start_time', $shop['where'])->where('is_status',1)->sum('fact_money');
//                    break;
//                case 'unvalidOrder'://无效新单
//                    $reach = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('order_start_time', $shop['where'])->where('is_status',1)->where('is_success',3)->count('id');
//                    break;
//                case 'ACustomerRate'://A客转化率
//                    //有效
//                    $yx = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('yx_day', $shop['where'])->where('is_valid', 1)->where('is_status',1)->where('c_from',1)->count('id');
//                    $a = db('CCustomerinfo')->where($ret['sql'],$ret['arr'])->whereTime('sign_time', $shop['where'])->where('sign_name', 'like', 'A%')->where('is_status',1)->count('id');
//                    $reach = ($yx / $a) * 100;
//                    break;
//            }
            $res[$ke]['reach'] = round($reach/$va['kpi_value'],2)*100;
        }
        return $res;
    }
    //实际收款
    function get_amount($staffId,$where){
        $res = db('CCustomerinfo')->where(array('dj_staff_id'=>$staffId,'is_intostore'=>1,'is_success'=>1,'Is_valid'=>1))->field('SUM(totalpay_money)')->find();
        action_log($staffId,'',$staffId['staff_id']);
        return $res['sum'];
    }

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

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

        return $detail;
    }

    //获取方式
    function accessModel($data)
    {
        $detail = session('accessModel');
        if(empty($detail)){
            $url = "59fd5f0792e10";
            $res = sx_call($url, $data);
            if ($res['code'] == 200) {
                $detail = $res['data'];
                session('accessModel', $detail);
            }
        }
        return $detail;
    }

    //客户意向
    function intention($data)
    {
        $detail = session('intention');
        if(empty($detail)){
        $url = "59fd5f6c1d340";
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $detail = $res['data'];
            session('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 = session('areaSet');
        if(empty($detail)){
        $url = "5a004e9c3e030";
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $detail = $res['data'];
            session('areaSet', $detail);
        }
    }
        return $detail;
    }
    //客户标记
    function markSet($data){
        /*$url="5a0c42f43e986";
        $res=sx_call($url,$data);
        if($res['code']==200){
            $detail=$res['data'];
        }*/
        //标记取前端的不是MC的
        $detail = db('s_markset')->where('shop_code',session('shop_code'))->select();
        return $detail;
    }
    //消费能力
    function capacity($data)
    {
        $detail = session('capacity');
        if(empty($detail)){
        $url = "5a0c43da3e99a";
        $res = sx_call($url, $data);
        if ($res['code'] == 200) {
            $detail = $res['data'];
            session('capacity', $detail);
        }
    }
        return $detail;
    }

    //消费类型
    function consumptionType($data)
    {
//        $detail = session('consumptionType');
//        if(empty($detail)){
//        $detail = db('s_consumptiontype')
//            ->where('is_delete',2)
//            ->where('brandclass_id',session('brandclass_id'))
//            ->select();
//        if(empty($detail)){
        $return = cache('consumptionType_'.session('brandclass_id'));
        if(empty($return)){
            $url = "59fd58574204a";
            $request = sx_call($url, ['brandclass_id'=>session('brandclass_id')]);
            if ($request['code'] == 200) {
                $return = $request['data'];
                cache('consumptionType_'.session('brandclass_id'), $return);
            }
        }

        return $return;
//        }

//    }
    }

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

    //人员
    function get_staff_list($data){
        $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);
            if($res['code']==200){
                $info=$res['data'];
//                session('consulation_shop',$info);
//            }
        }
        return $info;
    }


    //客资查询
    function customerSearch($data){
        $arr = [];
        $condition = [];
        $sql = " 1=1 ";
        if (!empty($data)) {
            if(session('is_dig') == 1){
                if($data['department_id'])       $sql .= " and 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 customer_number = :customer_number ";  $arr['customer_number']=$data['customer_number'];
            if($data['add_shop_code'])       $sql .= " and 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 province_id = '".$data['province_id']."' ";//$sql .= " and customer_number = :customer_number ";  $arr['customer_number']=$data['customer_number'];
            if($data['city_id'])       $sql .= " and city_id = '".$data['city_id']."' ";//$sql .= " and customer_number = :customer_number ";  $arr['customer_number']=$data['customer_number'];
            if($data['customer_number'])       $sql .= " and customer_number = '".$data['customer_number']."' ";//$sql .= " and customer_number = :customer_number ";  $arr['customer_number']=$data['customer_number'];
            if($data['customer_name'])         $sql .= " and customer_name like '%".$data['customer_name']."%' ";
            if($data['customer_tel'])          $sql .= " and customer_tel = '".$data['customer_tel']."' ";
            if($data['customer_wechat'])       $sql .= " and customer_wechat = '".$data['customer_wechat']."' ";
            if($data['customer_weibo'])        $sql .= " and customer_weibo = '".$data['customer_weibo']."' ";
            if($data['customer_qq'])            $sql .= " and customer_qq = '".$data['customer_qq']."' ";
            if($data['dj_staff_id'])            $sql .= " and dj_staff_id = '".$data['dj_staff_id']."' ";
            if($data['dj_staff_name'])          $sql .= " and dj_staff_name = '".$data['dj_staff_name']."' ";
            if($data['sk_staff_id'])            $sql .= " and sk_staff_id = '".$data['sk_staff_id']."' ";
            if($data['consultation_type_id'])  $sql .= " and consultation_type_id = '".$data['consultation_type_id']."' ";
            if($data['customer_intention_id']) $sql .= " and customer_intention_id = '".$data['customer_intention_id']."' ";
            if($data['is_success'])             $sql .= " and is_success = '".$data['is_success']."' ";
            if($data['customer_cource_id'])    $sql .= " and 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 sales_staff_id = '".$data['sales_staff_id']."' ";
            if($data['is_fp'])                   $sql .= " and is_fp = '".$data['is_fp']."' ";
            if($data['is_valid'])                $sql .= " and is_valid = '".$data['is_valid']."' ";
            if($data['is_success'])             $sql .= " and is_success = '".$data['is_success']."' ";
            if($data['brandclass'])             $sql .= " and brandclass = '".$data['brandclass']."' ";
            //if($data['op_signinfo_id'])        $sql .= " and op_signinfo_id = '".$data['op_signinfo_id']."' ";
            if($data['sign_id'])                $sql .= " and sign_id = '".$data['sign_id']."' ";
            if($data['more_like'])              $sql .= " and ( id=".intval($data['more_like'])." or customer_name like '%".trim($data['more_like'])."%' or customer_tel like '%".$data['more_like']."%' or customer_qq like '%".$data['more_like']."%' or customer_wechat like '%".$data['more_like']."%' or customer_weibo like '%".$data['more_like']."%' or mate_tel like '%".$data['more_like']."%') ";

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

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

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

            if($data['all_time']&&!empty($data['all_time'])){
                if($data['start_time'])      $sql .= " and ".$data['all_time']." BETWEEN '".$data['start_time']."' ";
                if($data['end_time'])        $sql .= " and '".date('Y-m-d',strtotime($data['end_time'])-86400)." 23:59:59' ";
            }else{
                // $sql .= ' and  dj_day BETWEEN "'.date('Y-m',time()).'-01"';
                $sql .= " and  dj_day  BETWEEN '".date('Y-m-01 00:00:00')."'";
                $sql .= " and  '".date('Y-m-d 23:59:59', time())."'";
                // $sql .= " and  '".date('Y-m',time()).'-'.(date('d'))." 23:59:59'";
            }

            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 {$k} in ($arr) ";
                }
            }

//            if($data['tab']&&$data['tab'] != 1){
//                $res = db('s_customer_tab')->where('id',$data['tab'])->find();
//                $info = json_decode($res['sql'],true);
//                $sql .= $info['where'];
//            }
            if($data['tab']&&$data['tab']==2){//待追踪
                $sql .= " and is_fp = 1 and c_star_day is null and is_intostore = 1 and is_valid in (1,2) and is_loss = 2 ";
            }elseif($data['tab']&&$data['tab']==3){//待分配
                $sql .= " and is_fp in (2,4) and is_already_sk = 1 ";
            }elseif($data['tab']&&$data['tab']==4){//追踪中
                $sql .= " and is_fp = 1 and is_loss=2 and c_star_day is not null and is_intostore = 1 and is_valid in (1,2) and is_success=2 ";
            }elseif($data['tab']&&$data['tab']==5){//成单
                $sql .= " and is_success in (1,3) ";
            }elseif($data['tab']&&$data['tab']==6){//进店未成单
                $sql .= " and is_success = 2 and is_intostore in (2,3) and is_loss = 2 ";
            }elseif($data['tab']&&$data['tab']==7){//流失
                $sql .= " and is_loss = 1 ";
            }elseif($data['tab']&&$data['tab']==8){//待筛客
                $sql .= " and is_sk = 1 and is_already_sk = 2 ";
            }elseif($data['tab']&&$data['tab']==9){//已筛客
                $sql .= " and is_sk = 1 and is_already_sk = 1 ";
            }
            //当日接收
            elseif($data['tab']&&($data['tab']==10)){
                $start = date('Y-m-d');
                $end   = date('Y-m-d', strtotime('+1 day'));
                $sql .= " and  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', strtotime('-3 day'));
                $end   = date('Y-m-d');
                $sql .= " and  last_trackday between '".$start."' and '".$end."'";
            }
            //、当日预进店
            elseif($data['tab']&&($data['tab']==12)){
                $start = date('Y-m-d');
                $end   = date('Y-m-d', strtotime('+1 day'));
                $sql .= " and yjd_day between '".$start."' and '".$end."'";
            }
            //有效客资
            elseif($data['tab']&&($data['tab']==13)){
                $sql .= " and  is_valid=1 ";
            }
            //无效客资
            elseif($data['tab']&&($data['tab']==14)){
                $sql .= " and  is_valid=1 ";
            }
            //待定客资
            elseif($data['tab']&&($data['tab']==15)){
                $sql .= " and  is_valid=3 ";
            }
            //驳回客资
            elseif($data['tab']&&($data['tab']==16)){
                $sql .= " and  is_valid=4 ";
            }
            //今日需追踪
            elseif($data['tab'] && ($data['tab'] == 17)){
                $start = date('Y-m-d');
                $end   = date('Y-m-d', strtotime('+1 day'));
                $sql .= " and (next_time between '".$start."' and '".$end."' or (c_star_day is null and is_fp=1)) ";
            }
        }
        $sql .= " and is_status = 1 ";
        // $sql .= " and is_status = 1 and is_act=1 ";
        return $sql;
    }

    //客资查询
    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'));
        $clumn = $str ? 'c.id,c.'.str_replace(',',',c.',$str) : 'c.id,c.customer_channel,c.sign_name,c.is_valid,c.customer_number,c.customer_name,c.customer_sex,c.customer_tel,c.customer_wechat,c.customer_weibo,c.customer_qq,c.city,c.marry_day,c.budget,c.consulation_shop,c.yjd_day,c.track_record,c.is_intostore,c.syjd_day,c.is_success,c.order_day,c.totalpay_money,c.loss_cause,c.customer_type,c.dj_day,c.create_time,c.is_fp,c.is_loss,c.dj_staff,s.sales_staff_name,c.sk_staff,c.introducer_name,c.introducer_tel,c.introducer_ordernum,c.introducer_type,c.tel_visit_num,c.last_trackday,c.consultation_type,c.customer_cource,c.customer_intention,c.access_model,c.customer_orderaddress,c.customer_area,c.brandclass,c.shop_name,c.add_shop_name';
        $join = [
            ['c_swap_customer s','c.customer_number=s.customer_number'],
        ];
        $customer = db('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;
        foreach($customer as $k=>$v){
            $v['customer_type'] = $v['customer_type'] == 1 ? '新客资' : '转介绍';
            $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['is_intostore'] = getIsIntostore($v['is_intostore']);
            $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']);
            $cus[$k]['id']=$v['id'];
            $cus[$k]['cell']=array_values($v);
        }
        $detail['rows']=$cus;
        $detail['userdata']['amount']=3320;
        $detail['userdata']['tax']=336;
        $detail['userdata']['total']=3320;
        $detail['userdata']['name']='Totals:';

        return $detail;
    }

    //获取客资数据
    function customerListData($data){

        $end_time=$data['end_time'];
        $data['end_time']=date("Y-m-d",strtotime("$end_time +1 day"));
        echo '-- 1 -- '.microtime(true).'<br />';
        $sql=$this->customerSearch($data);
        echo '-- 2 -- '.microtime(true).'<br />';
        if(check_right('menu1512637269')){
            switch (session('is_belong')){
                case '2':
                    $sql .= " and brandclass = '".session('brandclass')."' ";
                    break;
                case '3':
                    $sql .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                    break;
                case '4':
                    $sql .= " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                    break;
            }
        }else{
            if(strpos($data['type_info'],'sales_staff_id')===false){
                if(!$data['tab']||$data['tab']==1){//所有
                    $sql .= " and (dj_staff_id = '".session('staff_id')."' or (sales_staff_id = '".session('staff_id')."' and is_fp=1 ) or (sk_staff_id = '".session('staff_id')."')) ";
                }elseif($data['tab']&&$data['tab']==2){//待追踪
                    $sql .= " and sales_staff_id = '".session('staff_id')."' ";
                }elseif($data['tab']&&$data['tab']==3){//待分配
                    $sql .= " and shop_code = '".session('shop_code')."' ";
                }elseif($data['tab']&&$data['tab']==4){//追踪中
                    $sql .= " and (dj_staff_id = '".session('staff_id')."' or sales_staff_id = '".session('staff_id')."') ";
                }elseif($data['tab']&&$data['tab']==5){//已订单
                    $sql .= " and (dj_staff_id = '".session('staff_id')."' or sales_staff_id = '".session('staff_id')."') ";
                }elseif($data['tab']&&$data['tab']==6){//进店未成交
                    $sql .= " and (dj_staff_id = '".session('staff_id')."' or sales_staff_id = '".session('staff_id')."') ";
                }elseif($data['tab']&&$data['tab']==7){//流失
                    $sql .= " and (dj_staff_id = '".session('staff_id')."' or sales_staff_id = '".session('staff_id')."') ";
                }elseif($data['tab']&&($data['tab']==8)){//待筛客
                    $sql .= " and sk_staff_id = '".session('staff_id')."'  ";
                }elseif($data['tab']&&($data['tab']==9)){//、已筛客
                    $sql .= " and sk_staff_id = '".session('staff_id')."'  ";
                }elseif($data['tab']&&($data['tab']==10)){//、当日接收
                    $sql .= " and (dj_staff_id = '".session('staff_id')."' or (sales_staff_id = '".session('staff_id')."' and is_fp=1 ) ) ";
                }elseif($data['tab']&&($data['tab']==11)){//、三日内追踪
                    $sql .= " and (dj_staff_id = '".session('staff_id')."' or (sales_staff_id = '".session('staff_id')."' and is_fp=1 ) ) ";
                }elseif($data['tab']&&($data['tab']==12)){ //、当日预进店
                    $sql .= " and (dj_staff_id = '".session('staff_id')."' or (sales_staff_id = '".session('staff_id')."' and is_fp=1 ) ) ";
                }elseif($data['tab']&&($data['tab']==17)){ //今日需追踪
                    $sql .= " and (dj_staff_id = '".session('staff_id')."' or (sales_staff_id = '".session('staff_id').") ) ";
                }
            }
        }
        // if($data['tab']&&$data['tab'] != 1){
        //     $res = db('s_customer_tab')->where('id',$data['tab'])->find();
        //     $info = json_decode($res['sql'],true);
        //     $order = $info['order_by'];
        // }else{
        //     if(!$data['tab']||$data['tab']==1)          $order=" is_valid asc,dj_day desc ";
        // }
        $order = '';
        if($data['sidx']){
            $order .= ' '.$data['sidx'].' '.$data['sord'].',';
        }

//        if(!$data['tab']||$data['tab']==1)          $order .=" is_valid asc,dj_day desc ";
        if(!$data['tab']||$data['tab']==1)          $order .=" dj_day desc ";
        if($data['tab']&&$data['tab']==2)           $order .=" fp_day desc ";
        if($data['tab']&&$data['tab']==3)           $order .=" is_valid asc,dj_day desc ";
        if($data['tab']&&$data['tab']==4)           $order .=" last_trackday desc ";
        if($data['tab']&&$data['tab']==5)           $order .=" order_day desc ";
        if($data['tab']&&$data['tab']==6)           $order .=" syjd_day desc ";
        if($data['tab']&&$data['tab']==7)           $order .=" loss_day desc ";
        if($data['tab']&&($data['tab']==8))         $order .=" is_valid asc,dj_day desc ";
        if($data['tab']&&($data['tab']==9))         $order .=" sk_time desc ";

//        if($data['tab']&&($data['tab']==10))        $order .=" dj_day desc ";
//        if($data['tab']&&($data['tab']==11))        $order .=" c_star_day desc ";
        if($data['tab']&&($data['tab']==10))        $order .=" jr_day desc ";
        if($data['tab']&&($data['tab']==11))        $order .=" jr_day desc ";
        if($data['tab']&&($data['tab']==12))        $order .=" yjd_day desc ";
        if($data['tab']&&($data['tab']==17))        $order .=" next_time desc,jr_day desc ";

        $clumn = cache('colColumn_'.session('staff_id')) ? 'id,'.cache('colColumn_'.session('staff_id')) : 'id,customer_channel,sign_name,is_valid,op_signinfo,customer_number,customer_name,customer_sex,customer_tel,customer_wechat,customer_weibo,customer_qq,city,marry_day,budget,consulation_shop,next_time,yjd_action_day,yjd_day,customer_remark,track_record,is_intostore,is_urgent,syjd_day,is_success,order_number,order_day,totalpay_money,loss_cause,customer_type,dj_day,create_time,is_fp,is_loss,dj_staff,sales_staff,sk_staff,fp_staff,introducer_name,introducer_tel,introducer_ordernum,introducer_type,tel_visit_num,last_trackday,consultation_type,customer_cource,customer_intention,access_model,customer_orderaddress,customer_area,brandclass,shop_name,add_shop_name';

        $data['rows'] =  (int)$data['rows'] ? (int)$data['rows'] : 100;
        $data['page'] =  (int)$data['page'] ? (int)$data['page'] : 1;
//        if((int)$data['id']){
//            $sql = ' id='.(int)$data['id'];
//        }
echo '-- 3 -- '.microtime(true).'<br />';
        $customer=db('c_customerinfo')->where($sql)->count();
echo '-- SQL -- '.db()->getLastSql().'<br />';
echo '-- 4 -- '.microtime(true).'<br />';
        $customer1=db('c_customerinfo')->field($clumn)->where($sql)->limit($data['rows'])->page($data['page'])->ORDER($order)->select();
echo '-- SQL -- '.db()->getLastSql().'<br />';
//         $a=db()->getLastSql();print_r($a);die;
echo '-- 5 -- '.microtime(true).'<br />';
// exit;
        $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'];
        foreach($customer1 as $k=>$v){
            $v['customer_type'] = $v['customer_type'] == 1 ? '新客资' : '转介绍';
            $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_day'] = $v['order_day'] ? date('Y-m-d',strtotime($v['order_day'])) : '';
            $v['yjd_day'] = $v['yjd_day'] ? date('Y-m-d',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',strtotime($v['dj_day'])) : '';
            $v['create_time'] = $v['create_time'] ? date('Y-m-d',strtotime($v['create_time'])) : '';
            $v['marry_day'] = $v['marry_day'] ? date('Y-m-d',strtotime($v['marry_day'])) : '';
            $v['is_intostore'] = getIsIntostore($v['is_intostore']);
            $v['is_urgent'] = $v['is_urgent'] == 1 ? '是' : '否';
            $v['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']);
            $cus[$k]['id']=$v['id'];
            $cus[$k]['cell']=array_values($v);
        }
        $detail['rows']=$cus;
        $detail['userdata']['amount']=3320;
        $detail['userdata']['tax']=336;
        $detail['userdata']['total']=3320;
        $detail['userdata']['name']='Totals:';

        return $detail;
    }

    //客资数量
    function searchNum($data){
        $end_time=$data['end_time'];
        $data['end_time']=date("Y-m-d",strtotime("$end_time +1 day"));
        $sql=$this->customerSearch($data);
        $bp_sql=$this->customerSearch_bp($data);
//        if((int)$data['id']){
//            $sql = ' id='.(int)$data['id'];
//        }
        if(check_right('menu1512637269')){
            switch (session('is_belong')){
                case '1':
                    $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 =$sql16 = $sql17 = $sql;
                    break;
                case '2':
                    $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 =$sql16 = $sql17 = $sql . " and brandclass = '".session('brandclass')."' ";
                    break;
                case '3':
                    $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 =$sql16 = $sql17 = $sql . " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                    $bp_sql .= " and s.shop_code = '".session('shop_code')."'";
                    break;
                case '4':
                    $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 =$sql16 = $sql17 = $sql . " and (shop_code = '".session('shop_code')."' or add_shop_code = '".session('shop_code')."') ";
                    $bp_sql .= " and s.shop_code = '".session('shop_code')."'";
                    break;
            }
        }else{
            if(strpos($data['type_info'],'sales_staff_id')===false) {
                $sql1 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or (sales_staff_id = '" . session('staff_id') . "' and is_fp=1 ) or (sk_staff_id ='" . session('staff_id') . "')) ";
                $sql2 = $sql . " and sales_staff_id = '" . session('staff_id') . "' ";
                $sql3 = $sql . " and shop_code = '" . session('shop_code') . "' ";
                $sql4 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $sql5 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $sql6 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $sql7 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $sql8 = $sql . " and sk_staff_id = '" . session('staff_id') . "' ";
                $sql9 = $sql . " and sk_staff_id = '" . session('staff_id') . "' ";
                //$sql8= $sql . " and (dj_staff_id = '".session('staff_id')."' or sales_staff_id = '".session('staff_id')."') ";
                $sql10 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $sql11 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $sql12 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $sql13 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $sql14 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $sql15 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $sql16 = $sql . " and (dj_staff_id = '" . session('staff_id') . "' or sales_staff_id = '" . session('staff_id') . "') ";
                $bp_sql .= " and s.sales_staff_id = '" . session('staff_id') . "'";
            }else{
                $sql1 = $sql2 = $sql3 = $sql4 = $sql5 = $sql6 = $sql7 = $sql8 = $sql9 = $sql10 = $sql11 = $sql12 = $sql13 = $sql14 = $sql15 = $sql16 = $sql;
            }
        }

        $detail['all_crm'] = db('c_customerinfo')->where($sql1)->count();//所有客资
        // echo db()->getLastSql();exit;
//        $detail['no_traking']=db('c_customerinfo')->where(array('c_star_day'=>null,'is_fp'=>1,'is_loss'=>2,'is_intostore'=>1))->where($sql2)->count();//待追踪
        $detail['no_traking']=db('c_customerinfo')->where(array('c_star_day'=>null,'is_fp'=>1,'is_intostore'=>1,'is_loss'=>2,))->where('is_valid','in','1,2')->where($sql2)->count();//待追踪
        $detail['no_fp']=db('c_customerinfo')->where('is_fp','in','2,4')->where('is_already_sk',1)->where($sql3)->count();//待分配
        $detail['traking']=db('c_customerinfo')->where(array('is_loss'=>2,'is_fp'=>1,'is_intostore'=>1,'is_success'=>2))->where('is_valid','in','1,2')->where('c_star_day is not null')->where($sql4)->count();//追踪中
        $detail['crm_order']=db('c_customerinfo')->where('is_success','in','1,3')->where($sql5)->count();//已成单
        $detail['jdwd']=db('c_customerinfo')->where(array('is_success'=>2,'is_loss'=>2))->where('is_intostore','in','2,3')->where($sql6)->count();//进店未成单
        $detail['loss']=db('c_customerinfo')->where(array('is_loss'=>1))->where($sql7)->count();//不再追踪
        $detail['sk']=db('c_customerinfo')->where(array('is_sk'=>1,'is_already_sk'=>2))->where($sql8)->count();//筛客
        $detail['already_sk']=db('c_customerinfo')->where(array('is_sk'=>1,'is_already_sk'=>1))->where($sql9)->count();//已筛客

        // 今天 明天 3天前
        $today = date('Y-m-d');
        $end = date('Y-m-d', strtotime('+1 day'));
        $threeDaysAgo = date('Y-m-d', strtotime('-3 day'));
        // 今日接入
        $detail['today_receive'] = db('c_customerinfo')
            ->where('jr_day', 'between time', [$today, $end])
            ->where($sql10)
            ->count('id');
        // 三天内追踪
        $detail['three_tracking'] = db('c_customerinfo')
            ->where('last_trackday', 'between time', [$threeDaysAgo, $today])
            ->where($sql11)
            ->count('id');
        // 预计今日进店
        $detail['today_yjd']  = db('c_customerinfo')
            ->where('yjd_day', 'between time', [$today, $end])
            ->where($sql12)
            ->count('id');
        //爆破客资
        $join = [
            ['c_swap_customer s','c.customer_number=s.customer_number'],
        ];
        $detail['bp'] = db('c_customerinfo c')
            ->join($join)
            ->where($bp_sql)
            ->count('c.id');
        // 今日需追踪
        $tWhere = "  (next_time between '".$today."' and '".$end."' or (c_star_day is null and is_fp=1)) ";
        $detail['today_sales']  = db('c_customerinfo')
            ->where($sql17)
            ->where($tWhere)
            ->count('id');
//         echo db()->getLastSql();die;
        // $detail['valid_customer']=db('c_customerinfo')->where('is_valid',1)->where($sql13)->count();//有效客资
        // $detail['unvalid_customer']=db('c_customerinfo')->where('is_valid',2)->where($sql14)->count();//无效客资
        // $detail['daiding_customer']=db('c_customerinfo')->where('is_valid',3)->where($sql15)->count();//待定客资
        // $detail['bohui_customer']=db('c_customerinfo')->where('is_valid',4)->where($sql16)->count();//驳回客资
        // echo db()->getLastSql();die;
        //$detail['tel']=db('c_customerinfo')->where('tel_visit_num > 0')->where($sql8)->count();
        return $detail;
    }


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

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

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

        return $detail;
    }
    //客户地址模糊查询
    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('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){
        $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;
    }

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

        if(isset($data['sales_staff']) && !empty($data['sales_staff'])){
            $staff=$this->get_staff_list(array('staffname'=>$data['sales_staff'],'shop_code'=>$shop_code));
            $ids['sales_staff_id']=$staff[0]['id'];
            $ids['sales_staff_number']=$staff[0]['staffnumber'];
        }else{
            $ids['sales_staff_id']=null;
            $ids['sales_staff_number']='';

        }

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

        if($data['consultation_type']){
            if(!$consultation_type){
                $consultation_type=$this->consumptionType();
                cache('crm_consultation_type',$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'];
                }
            }
        }
        cache('ids',$ids);
        return $ids;
    }

    //验证手机号和名字重复
    function checkNameTel($param){
        $count = db("c_customerinfo")->where('customer_tel',$param['customer_tel'])->count();
        return $count;
    }
    //查询归属店是否筛客
    public function is_sk($belong_shop_code){
        $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));
        if($res['code'] == 200){
            return $res['data'];
        }else{
            return false;
        }
    }

    public function isRepeat($brandclass,$tel,$wechat,$qq,$mate_tel,$id=0){
        $brandclass = $brandclass ? $brandclass : session('brandclass');
        $array=array();

        if($tel){
            $contact[] = $tel;
        }
        if($qq){
            $contact[] = $qq;
        }
        if($wechat){
            $contact[] = $wechat;
        }
        if($mate_tel){
            $contact[] = $mate_tel;
        }
        if(!$contact){
            return array('code'=>201,'msg'=>'缺少联系方式','data'=>[]);
        }
        $sql1 = " 1=1 ";
        if($id){
            $sql1 .= ' and (c_id is null or c_id <> '.$id.') ';
        }
        $c_ids = db('c_customer_contact')->where($sql1)->where('contact','in',$contact)->where('brandclass',$brandclass)
            ->order('id desc')->column('c_id');
        if(empty($c_ids)){
            return array('code'=>200,'msg'=>''.db()->getLastSql(),'data'=>'');
        }else{
            foreach($c_ids as $k=>$c_id){
                if(!$c_id){
                    unset($c_ids[$k]);
                }
            }
            if(empty($c_ids)){
                return array('code'=>201,'msg'=>'客资有重复，但未找到客资编号','data'=>[]);
            }

            $sql = ' 1=1 ';
            //客资过期时间
            $key = 'brand_valid_date_'.md5($brandclass);
            $valid_date = cache('?'.$key);
            if(!$valid_date){
                $info = sx_call('5a3bbb5d0988d',['brandclass'=>$brandclass]);
                if($info['code'] == 200){
                    $valid_date = $info['data'][0]['valid_date'];
                    cache($key,$valid_date,1800);
                }else{
                    $valid_date = 60;
                }
            }else{
                $valid_date = cache($key);
            }
            $lastDate = date('Y-m-d H:i:s',time() - ($valid_date * 86400));
            $arr= db("c_customerinfo")
                ->field('id,customer_tel,customer_wechat,customer_qq,customer_weibo,customer_name,customer_number,mate_tel,dj_day,add_shop_name,dj_staff,sales_staff,shop_name,is_success,is_fp,is_valid,is_intostore,c_star_day')->where('id','in',$c_ids)->where('is_status',1)->where('dj_day','>',$lastDate)->where('is_success','<>',1)->master()->find();
            if($arr){
                return array('code'=>201,'msg'=>'','data'=>$arr);
            }else{
                return array('code'=>200,'msg'=>''.db()->getLastSql(),'data'=>''.json_encode($arr));
            }
            
        }
    }

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

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

    //客资录入
    function addCustomer($data){
        $data['customer_tel'] = trim($data['customer_tel']);
        $data['customer_wechat'] = trim(strip_tags($data['customer_wechat']));
        $data['customer_qq'] = trim($data['customer_qq']);
        $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_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']);

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

        }


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

        $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']);
        unset($data['img_record']);
        if($record['sales_remark']){
            $day = date('Y-m-d H:i', time());
            $remark = preg_replace('/<\s*img\s+[^>]*?src\s*=\s*(\'|\")(.*?)\\1[^>]*?\/?\s*>/i', '', $record['sales_remark']);
            $data['track_record'] ='<font color="#f08080">'.$day.'</font>&nbsp;'.$remark."<br/>";
        }
        $rep = controller('Customer', 'lib')->isRepeat($data['brandclass'], $data['customer_tel'],
            $data['customer_wechat'], $data['customer_qq']);

        if($rep['code'] == 201){
            $arr = $rep['data'];//$this->getCustomerInfo($rep['data']);
            $msg = "您 录入的客资信息重复，已存在的客资信息如下：<br/>";
                if($arr['sales_staff']){
                    $msg .= '客资提报人：'.$arr['dj_staff'].'<br/>';
                    $msg .= '客资提报人所属店面：'.$arr['add_shop_name'].'<br/>';
//                $msg .= '客资所属店面：'.$arr['shop_name'].'<br/>';
//                $msg .= '客资当前状态：'.getIsValidAttr($arr['is_valid']).'<br/>';
                    $sal = $arr['c_star_day'] ? '追踪中' : '待追踪';
//                $msg .= '是否分配：'.getIsFP($arr['is_fp']).'<br/>';
                    $msg .= '追踪状态：'.$sal.'<br/>';
                    $msg .= '追踪人：'.($arr['sales_staff']).'<br/>';
                    $msg .= '是否进店：'.getIsIntostore($arr['is_fp']).'<br/>';
                    $msg .= '是否成交：'.getIsSuccess($arr['is_success']).'<br/>';
                    $msg .= '客资录入时间：'.$arr['dj_day'].'<br/>';
                    $msg .= '请核对信息后再录入';
                    $returnData = array('code' => 201,'msg' =>$msg);
//                $returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].' ]的[ '.$arr['dj_staff'].' ]录入过，并且分配给了[ '.$arr['sales_staff'].' ]');
                }else{
                    $msg .= '客资提报人：'.$arr['dj_staff'].'<br/>';
                    $msg .= '客资提报人所属店面：'.$arr['add_shop_name'].'<br/>';
//                $msg .= '客资所属店面：'.$arr['shop_name'].'<br/>';
//                $msg .= '客资当前状态：'.getIsValidAttr($arr['is_valid']).'<br/>';
                    $msg .= '是否分配：'.getIsFP($arr['is_fp']).'<br/>';
                    $msg .= '是否进店：'.getIsIntostore($arr['is_fp']).'<br/>';
                    $msg .= '是否成交：'.getIsSuccess($arr['is_success']).'<br/>';
                    $msg .= '客资录入时间：'.$arr['dj_day'].'<br/>';
                    $msg .= '请核对信息后再录入';
                    $returnData = array('code' => 201,'msg' =>$msg);
//                $returnData = array('code' => 300,'msg' =>'此客资已在'.$arr['dj_day'].'由[ '.$arr['add_shop_name'].']的[ '.$arr['dj_staff'].' ]录入过，未进行分配');
                }
            return $returnData;
        }elseif ($rep['code'] != 200) {
            # code...
            $returnData = array('code' => 201,'msg' =>$rep['msg']);
            return $returnData;
        }
        db()->startTrans();//开启事务
        try {
            $data['customer_number'] = str_shuffle(time().generate_code());
            $res=db('CCustomerinfo')->insert($data);
            $customerId = db()->getLastInsID();
            foreach($contact as $k => $v){
                $contactList[$k]['c_id']=$customerId;
                $contactList[$k]['contact']=$v;
                $contactList[$k]['brandclass']=$data['brandclass'];
            }
            db('c_customer_contact')->insertAll($contactList);
            // $errId++;
            if($record['sales_remark']){
                //$customerInfo=db('CCustomerinfo')->field('customer_number,customer_name')->where('id',$customerId)->find();
                $record['gtType']=4;
                $record['customer_id']=$customerId;
                $record['customer_name']=$data['customer_name'];
                $record['customer_number']=$data['customer_number'];
                $record['sales_staff_id']=$data['dj_staff_id'];
                $record['sales_staff']=$data['dj_staff'];
                $record['sales_staff_number']=$data['dj_staff_number'];
                $record['shop_name']=$data['shop_name'];
                $record['shop_code']=$data['shop_code'];
                $record['sales_day']=date('Y-m-d H:i:s',time());
                if($data['shop_code'] == $data['add_shop_code']){
                    $record['sales_remark'] = 'PC录入-前端-'.$record['sales_remark'];
                }

                db('c_salestrackinginfo')->insert($record);
                getSalesTracking($customerId);
                // $errId++;
            }
            //发送短信
            if($sms_model && $is_send_msg){
                $send_msg = db('s_message_templateinfo')->where('id',$sms_model)->value('mtemplate_content');
                $sms = db_config('sms_'.session('shop_code'));
                $param = [
                    'ids' => $customerId,//客资id
                    'model_id' => $sms_model,//模板id
                    'send_msg' => $send_msg,//发送的模板内容
                    'send_config' => $sms,//短信账号
                ];
                $this->send_message($param);
            }

            db()->commit();
        } catch (Exception $e) {//1001001001
            db()->rollback();//回滚
            return false;
        }

        if($res!=false){
            // $staff_id, $staff_name, $staff_number, $shop_code,$identity, $cid, $old_data, $new_data
            // 数据统计队列
            $listName = 'historyDataList';
            $cinfo = [
                'id'    => $customerId,
                'dj_id' => $data['dj_staff_id'],
                'dj_day'=> $data['dj_day'],
            ];
            $message = array(
                // 数据统计类型（1：单条；2：批量导入）
                'type'       => 1,
                // 批量导入的客资的eid
                // 'eid'        => '',
                'staff_id'   => $data['dj_staff_id'],
                'identity'   => 'record',
                'cinfo'      => $cinfo,
                'old_data'   => array(),
                'new_data'   => $data,
                'controller' => 'Customer',
                'action'     => 'addCustomer',
            );
            push_list($listName,$message);
            // redisQueue::init()->rPush($listName, $message);
            // action_log($data,'',$customerId,$data['dj_staff_id'],$data['dj_staff']);
            // 如果提报人的工作类型是话务(21),分配给自己
            $staffinfo = getStaffInfoById(session('staff_id'));
            $workTypes = RECEIVE_WORK_TYPE;
            if ($staffinfo['work_type']) {
                $type = explode(',', $staffinfo['work_type']);
                array_push($type, $staffinfo['main_work_type']);
            }else{
                $type = $staffinfo['main_work_type'];
            }
            if (is_array($type)) {
                $is_in = in_array($workTypes, $type);
            }else{
                if ($workTypes == $type) {
                    $is_in = true;
                }else{
                    $is_in = false;
                }
            }
            // $work_type=explode(',',trim(session('main_work_type').','.session('work_type'),','));
            // if(in_array(RECEIVE_WORK_TYPE,$work_type)) {}       检验工作类型中有没有话务，其实可以这样更简单些的....
            if ($is_in) {
                // 分配  用数据
                $date = date('Y-m-d H:i:s');
                $dataN['sales_staff_id']    = session('staff_id');
                $dataN['sales_staff']       = session('staff_name');
                $dataN['sales_staff_number']= session('staff_number');
                $dataN['fp_day']            = $date;
                $dataN['is_fp']             = 1;
                $dataN['jr_day']            = $date;

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


    //筛客
    public function skCustomer($param){
        $has = $this->getCustomerInfo($param['id']);
        if (!$has) {
            $return = array('code' => 900,'msg' =>'用户数据不存在，请检查！');
        }
        //如果是筛客操作，增加筛客时间
        if($param['is_already_sk'] == 1){
            $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{
            db('c_customerinfo')->where('id',$param['id'])->update($param);

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

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

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

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

            if($param['is_valid'] == 1){
                //统计队列
                $listName = 'historyDataList';
                $cinfo = [
                    'id'     => $has['id'],
                    'dj_id'  => $has['dj_staff_id'],
                    'dj_day' => $has['dj_day'],
                    'sel_id' => $has['sk_staff_id'],
                    'sel_day'=> $has['sk_time'],
                ];
                $message = array(
                    'type'      => 1,
                    'staff_id'  => session('staff_id'),
                    'identity'  => 'sale',
                    'cinfo'     => $cinfo,
                    'old_data'  => $oldDateIn,
                    'new_data'  => $newDateIn,
                    'controller'=> 'Customer',
                    'action'    => 'customerInfo'
                );
                $pushStatus = push_list($listName, $message);

                if ($pushStatus) {
                    $sysconfig=db('c_sysconfig')->where('ckey','fp_switch_'.session('shop_code'))->find();
                    if($sysconfig['cvalue']==1){
                        // echo '2';
                        // 系统分配队列
                        $listName_fp = 'fpCustomerList';
                        $message_fp['receive']  = '-1';
                        $message_fp['body']     = $param['id'];
                        $message_fp['staff_id'] = $has['dj_staff_id'];
                        $message_fp['shop_code']= $has['shop_code'];
                        //redisQueue::init()->rPush($listName_fp, $message_fp);
                        push_list($listName_fp, $message_fp);
                    }
                    $return = array('code' => 1,'msg' => '筛客成功');
                }
            }
            action_log($param,'',$param['id'],session('staff_id'),session('staff_name'));
            db()->commit();
        }catch (\Exception $e){
            db()->rollback();
            $return = array('code' => 400,'msg' => '筛客失败');
        }




        return json($return);
    }

    //选择条件下的类型
    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_id"){//客资渠道
            $detail=$this->getChannel();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['channel_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']=="customer_area_id"){//客户分区
            $detail=$this->areaSet(array('shop_code'=>session('shop_code')));
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['area_name'];
            }
        }elseif($data['name']=="customer_region_id"){//客户地域
            $detail=$this->region(array('shop_code'=>session('shop_code')));
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['region_name'];
            }
        }elseif($data['name']=="op_signinfo_id"){
            $detail=$this->markSet();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['mark_name'];
            }
        }
        elseif($data['name']=="sales_staff_id"){
            if(session('is_belong')==1){
                $staff_list=$this->get_staff_lists();
            }elseif(session('is_belong')==2){
                $staff_list=$this->get_staff_lists(array('brandclass'=>session('brandclass')));
            }elseif(session('is_belong')==3||session('is_belong')==4){
                $staff_list=$this->get_staff_lists(array('shop_code'=>session('belong_shop_code')));
            }
            //$detail=controller("Customer","lib")->get_staff_list();
            foreach($staff_list as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['staffname'];
            }
        }elseif($data['name']=="op_signinfo"){
            $detail=controller('Customer','lib')->markSet();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $arr[$k]['name']=$v['mark_name'];
            }
        }elseif($data['name']=="sign_id"){
            $detail=controller('crm/Setting','lib')->gettrackingKmarkerList();
            foreach($detail as $k=>$v){
                $arr[$k]['id']=$v['id'];
                $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'];
            }
        }
        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']);
        }
    }

    //删除客资
    function delCustomer($ids){
        db()->startTrans();//开启事务
        try{
            $res=db('c_customerinfo')->where('id','in',implode(',',$ids))->update(['is_status' => '2']);
            $data=db('c_customerinfo')->field('customer_tel,customer_wechat,customer_qq,mate_tel')->where('id','in',implode(',',$ids))->select();
            /*$contact=array();
            foreach($data as $k => $v){
                if(!empty($v['customer_tel'])){
                    array_push($contact,$v['customer_tel']);
                }
                if(!empty($v['customer_wechat'])){
                    array_push($contact,$v['customer_wechat']);
                }
                if(!empty($v['customer_qq'])){
                    array_push($contact,$v['customer_qq']);
                }
                if(!empty($v['mate_tel'])){
                    array_push($contact,$v['mate_tel']);
                }
            }*/
            db('c_customer_contact')->where('c_id','in',implode(',',$ids))->delete();
            action_log($ids,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
            $returnData = array('code' => 1,'msg' =>'删除客资成功！','data'=>$ids);
            return json($returnData);
        }catch (\Exception $e){
            db()->rollback();
            $returnData = array('code' => 1000,'msg' =>'删除客资失败');
            return json($returnData);
        }

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

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


    //获取最新导入excel文件历史记录
    function new_list(){
        $excel=db('c_excel_import')->where(array('staff_id'=>session('staff_id')))->ORDER("addtime desc")->select();
        $this->success('成功','/',$excel);
    }

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

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

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

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

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

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


            $excel_file['file_name']=$file_name;
            $excel_file['file_url']=$file_url;
            $excel_file['staff_id']=session('staff_id');
            $excel_file['staff_name']=session('staff_name');
            $excel_file['addtime']=date('Y-m-d H:i:s',time());
            //$excel_file['all_number']=count($excel_array);
            unset($excel_array);
            //是否筛客
            $b_is_sk = controller("Customer", "lib")->is_sk(session('belong_shop_code'));
            if($b_is_sk ==1 || session('is_sk') == 1){
                $skList = controller("Customer", "lib")->sklist('',24);
                if(!empty($skList)){
                    $excel_file['is_sk']=1;//是否筛客
                }
            }

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


//            if($param['is_sk'] == 1){
//                $message['body']['sk']=array('is_sk'=>$param['is_sk'],'sk_staff_id'=>$param['sk_staff_id'],'sk_staff'=>$param['sk_staff']);
//            }
            $message['body']['file_url']=$file_url;
            $message['body']['eid']=$id;
            $message['body']['staff']=array('staff_id'=>session('staff_id'),'staff_name'=>session('staff_name'),'staff_number'=>session('staff_number'),'shop_name'=>session('belong_shop_name'),'shop_code'=>session('belong_shop_code'),'brandclass_id'=>session('brandclass_id'),'brandclass'=>session('brandclass'),'add_shop_code'=>session('shop_code'),'add_shop_name'=>session('shop_name'));
            //$message['body']['data']=$excel_array;
            //$message['body']['num']=$num;

            $dir='../application/data/excel/error';
            if (!is_dir($dir)){
                mkdir($dir);
            }

            if($res){
                $resutl=push_list("excelImportRedisList", $message);
                //redisQueue::init()->rPush('excelImportRedisList', $message);
                $this->success('客资文件上传成功',"/",$file_name);
            }
        } else {
            echo $file->getError();
        }
    }


    //生成错误文件
    function cusFailFile($fail_file){
        echo '1';
        $PHPExcel = new PHPExcel();
        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle('customer'); //给当前活动sheet设置名称

        $title=array('客户姓名','性别','手机号','微信','微博','QQ','省','市','区','详细地址','客户类型','渠道名称','获取方式','消费类型','客户来源','客户分区','客户意向','意向店面','接单点','追踪人','错误原因');

        // $title=array('客户姓名','性别','手机号','微信','微博','QQ','省','市','区','详细地址','客户类型','客户渠道','获取方式','消费类型','客户来源','客户分区','客户意向','意向店面','接单点','追踪人','登记人','录入员工id','登记日期','分配人','分配人id','分配日期','接入日期','录入员工部门code','录入员工部门名','事业部名', '事业部ID','是否有效','标记有效时间','预计进店日期','是否进店','实际进店日期','开始追踪日期','错误原因');

        $index = 1;
        // echo '2';
        for($i=0;$i<count($title);$i++){
            $range[$i] = controller("crm/Customer","lib")->stringFromColumnIndex($i);
            $PHPSheet->setCellValue($range[$i].$index, $title[$i]);
        }
        // echo '3';
        if(count($fail_file['fail_array'])>0){
            foreach($fail_file['fail_array'] as $k=>$v){
                $index++;
                foreach(array_values($v) as $kk=>$vv){
                    $PHPSheet->setCellValue("{$range[$kk]}{$index}",$vv);
                }
            }
        }
        // echo '4';
        $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');
        $file_url = ROOT_PATH . 'application' . DS . 'data'  . DS . 'excel';
        $file_name=$file_url."/error/".'error'.$fail_file['eid'].'.xlsx';
        // echo $file_name;
        $PHPWriter->save($file_name);
        return $file_name;
    }

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

        $PHPSheet = $PHPExcel->getActiveSheet();
        $PHPSheet->setTitle('customer'); //给当前活动sheet设置名称
        $index = 1;
        for($i=0;$i<count($title);$i++){
            $range[$i] = controller("crm/Customer","lib")->stringFromColumnIndex($i);
            $PHPSheet->setCellValue($range[$i].$index, $title[$i]);
        }
        // var_dump($data);
        // exit;
        if(count($data)>0){
            foreach($data as $k=>$v){
                if ($v['customer_type']) {
                    $v['customer_type'] = $v['customer_type']==1?'新客资':'转介绍';
                }
                if ($v['is_valid']) {
                    $v['is_valid'] = getIsValidAttr($v['is_valid']);
                }
                if ($v['is_intostore']) {
                    $v['is_intostore']=getIsIntostore($v['is_intostore']);
                }
                if ($v['is_fp']) {
                    $v['is_fp']=getIsFP($v['is_fp']);
                }
                if ($v['is_success']) {
                    $v['is_success']=getIsSuccess($v['is_success']);
                }
                if ($v['is_loss']) {
                    $v['is_loss']=getIsLoss($v['is_loss']);
                }
                if ($v['order_type'] == 1) {
                    $v['order_type']='线上';
                }elseif($v['order_type'] == 2){
                    $v['order_type']='线下';
                }
                if ($v['c_from'] == 1) {
                    $v['c_from']='CRM';
                }elseif($v['c_from'] == 2){
                    $v['c_from']='ERP';
                }
                if ($v['introducer_type']) {
                    $v['introducer_type']=getIntroducerType($v['introducer_type']);
                }
                if($v['track_record']){
                    $v['track_record'] = strip_tags($v['track_record']);
                }
                $index++;
                foreach(array_values($v) as $kk=>$vv){
                    $PHPSheet->setCellValue("{$range[$kk]}{$index}",$vv);
                }
            }
        }

        $PHPWriter = PHPExcel_IOFactory::createWriter($PHPExcel,'Excel2007');
        //header("Content-type:text/html;charset=utf-8");
        header('Content-type: application/vnd.ms-excel');//告诉浏览器输出07Excel文件
        header('Content-Disposition: attachment;filename='.$file);//告诉浏览器输出浏览器名称
        header("Content-Description: File Transfer");
        header('Cache-Control: max-age=0');//禁止缓存
        header("Content-Transfer-Encoding: binary"); //告诉浏览器，这是二进制文件
        $PHPWriter->save("php://output");
        exit;

    }

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

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

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

    }

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

        return $res;
    }
    /*
     * 插入手机归属地信息
     * tel : 男手机号
     * */
    public function insTelInfo($tel){
        //查询是否已有此手机号信息
        $info = $this->getTelInfo($tel);
        if(!empty($info)){
            return $info;
        }
//        $res = preg_match('/^1[3|4|5|6|7|8][0-9]{9}$/', $tel) ? true : false;
        //修改手机号时，查询归属地，区号等
        $telInfo = getData($tel);
        $arr = explode(' ',$telInfo);
        if($arr[1] == $arr[2]){
            $customerInfo['tel_belong'] = $arr[1];
        }else{
            $customerInfo['tel_belong'] = $arr[1].' '.$arr[2];
        }
        $customerInfo['tel_operator'] = $arr[3];
        $customerInfo['tel_area_code'] = $arr[5];
        //插入客资电话信息表
        db()->startTrans();
        if($customerInfo['tel_belong']){
            $id = db('c_customer_tel')->insertGetId(['customer_tel'=>$tel,'tel_belong'=>$customerInfo['tel_belong'],'tel_operator'=>$customerInfo['tel_operator'],'tel_area_code'=>$customerInfo['tel_area_code']]);
            if($id){
                db()->commit();
                return $customerInfo;
            }else{
                db()->rollback();
                return false;
            }
        }else{
            db()->rollback();
            return false;
        }
    }
    /*
     * 查询手机归属地信息
     * */
    public function getTelInfo($tel){
        $res = db('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('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';


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

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

        // 来源渠道
        $channelInfoUrl = '59fd5e729e5a8';
//        $allSet['channelInfo'] = self::callInterface($channelInfoUrl, $data);//mc设定
        $allSet['channelInfo'] = $this->getChannel();//crm设定
        // 客户来源
        $cussourceUrl = '59fd5ec462c88';
        $allSet['cussource'] = self::callInterface($cussourceUrl, $data);

        // 获取方式
        $accessModelUrl = '59fd5f0792e10';
        $allSet['accessModel'] = self::callInterface($accessModelUrl, $data);

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

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

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

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

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

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

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

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

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

//            $CustomerAllSet = json_encode($allSet);
        // 存缓存
//            $return = cache('CustomerAllSet'.$shop_code, $CustomerAllSet);
//            $return = $CustomerAllSet;
//        }
        return $allSet;
    }

    /**
     * 获取客资追踪记录，取c_salestrackinginfo表数据
     * @param  string $cNumber；customer的customer_number
     * @return array
     * @author Eric
     */
    public function getCustomerTrackInfos($cid){
        $where = array(
            'customer_id'  => $cid
        );
//        $trackInfo = cache('getCustomerTrackInfos'.$cid);
//        if(!$trackInfo){
        $trackInfo = db('c_salestrackinginfo')->where($where)->order('sales_day desc')->select();
        if(!check_right('menu1512998373')) {
            foreach ($trackInfo as $k => $v) {
                $trackInfo[$k]['customer_tel'] = !empty($v['customer_tel']) ? substr($v['customer_tel'], 0, 3) . '****' . substr($v['customer_tel'], 7) : '';
            }
        }
        foreach($trackInfo as $ke=>$va){
            $trackInfo[$ke]['tel_static'] = getTelResult($va['tel_static']);
        }
//            cache('getCustomerTrackInfos'.$cid,json_encode($trackInfo));
//        }
        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('action_log','db_logs')->where($where)->select();
        return $changeLogs;
    }

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

        return $changeLogs;
    }

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


    /**
     * 查看cache中是否存在对应规则及员工集合
     * @param  str    shop_code
     * @return array  rules 规则集合
     * @author Eric
     */
    public function getFpRuleStaffs($shop_code){
        $ruleStaffs = cache('fpRuleStaffs_'.$shop_code);
        if (!$ruleStaffs) {
            $rules  = controller("crm/Setting","lib")->getRule($shop_code);
            // echo json_encode($rules).'<br />';
            $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);
            }
            // 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']);
            // 员工是否在线
            $connect = $salf_not_online_is_fp ? true : self::getStaffOnlineStatus($value['id']);
            if (!$connect) {
                continue;
            }else{
                $memberOnline[$key] = $value;
            }
        }
        // var_dump($memberOnline);
        // exit;
        $memberOnline = my_sort($memberOnline, 'id');
        // echo 'memberOnline:'.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'],
        ];
        $next = $key+1;
        cache('fpCustomerP'.$rid, $next);
        cache('fpCustomerP-num-'.$rid, $num);
        return $sales_staff;
        // var_dump($next);
        // exit;
        // foreach ($staffs as $k => $v) {
        //     // $key 大于 $k 跳出循环
        //     if ($key > $k) {
        //         continue;
        //     }
        //     // 查看员工是否在线
        //     $connect = self::getStaffOnlineStatus($v['id']);
        //     // 如果员工不在线跳出循环
        //     if ($connect === false) {
        //         continue;
        //     }else{ // 如果员工在线记录员工信息，计算下一个要分配的key值 并存到缓存
        //         $next = $key+1;
        //         cache('fpCustomerP'.$rid, $next);
        //         $sales_staff = [
        //             'sales_staff_id'    => $v['id'],
        //             'sales_staff'       => $v['staffname'],
        //             'sales_staff_number'=> $v['staffnumber'],
        //         ];
        //         break;
        //     }
        // }
        // 返回要分配的员工信息
        return $sales_staff;
    }

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

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

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

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

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

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

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

        return $msgInfo;

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

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

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

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

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

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

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

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

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

        $message = '';
        $staffid = session('staff_id');
        while (!$message || $message['receive_id'] != $staffid) {
            $res = redisQueue::init()->subscribe($channel, $callback);
            // 监听频道超时
            if ($res === false) {
                return false;
            }
            $message = json_decode($res ,true);
        }
        $time = time();
        $message['time_out'] = $message['time_out']-$time;
        $message['operation']= json_decode($message['operation'], 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('CCustomerinfo')
                    ->where('is_status',1)
                    ->where('customer_name|customer_tel','like','%'.$param['search'].'%')
                    ->where($sql)
                    ->whereTime('dj_day',$time1)
                    ->order('id desc')
                    ->page($page,$limit)
                    ->select();

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

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

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

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

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

        return sprintf('%.2f',($succ/$jindian)*100);
    }
    //移动端客资名搜索
    public function customerNameSearch($name){
        $erp = is_install('sx_erp');
        if($erp){
            // 店面类型 （1：婚纱；2：儿童；3：旅拍；4：艺术；5：其他）
            $shop_type = session('shop_type');
            if ($shop_type == 2) {
                $shop_type = 1;
            }else{
                $shop_type = 0;
            }
            $addr = $erp['addr'];
            // 婚纱0，儿童1
            $url = $addr.'SX_CrmApi/Sel_CustomerOrderInfo?Token=^******^&CustomerType='.$shop_type.'&Customerinfo='.$name.'&Shop_code='.session('shop_code');
            // $url = $addr.'SX_CrmApi/Sel_CustomerOrderInfo?Token=^******^&CustomerType=0'.'&Customerinfo=黑&Shop_code=ZX002';
            $data = '';
            $res = requestERP($url, $data);
            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]['introducer_type'] = $v["order_type"] < 3 ? '新客' : ($v['order_type'] >= 3 and $v['order_type'] < 6 ? '现客' :($v['order_type'] >= 6 ? '老客' : '新客'));
                }
            }else{
                $res = array('Code'=>'300','Msg'=>'未查询到订单数据','Data'=>'');
            }
            return ($res);
        }else{
            $res = db('CCustomerinfo')
                ->where('customer_name|customer_tel|order_number','like','%'.$name.'%')
                ->where('order_number','<>','')
                ->where('add_shop_code',session('shop_code'))
                ->field('customer_name,customer_tel,order_number,introducer_type,customer_number,mate_tel')
                ->select();
            if(empty($res)){
                return array('Code'=>'300','Msg'=>'未查询到订单数据','Data'=>'');
            }else{
                foreach($res as $k=>$v){
                    $res[$k]['introducer_type'] = $v["introducer_type"] == 1 ? '新客' : ($v['introducer_type'] == 2 ? '现客' :($v['introducer_type'] >= 3 ? '老客' : '新客'));
                }
                return array('Code'=>'200','Msg'=>'查询成功','Data'=>$res);
            }
        }
    }
/*
 * PC端修改介绍人信息---start---
 * */
    public function editIntroducer($data){
        $param['introducer_name'] = $data['introducer_name'] ? trim($data['introducer_name']) : '';
        $param['introducer_tel'] = $data['introducer_tel'] ? trim($data['introducer_tel']) : '';
        $param['introducer_ordernum'] = $data['introducer_ordernum'] ? trim($data['introducer_ordernum']) : '';
        $param['introducer_number'] = $data['introducer_number'] ? trim($data['introducer_number']) : '';
        $param['introducer_type'] = $data['introducer_type'] ? trim($data['introducer_type']) : '';
        $param['id'] = $data['id'] ? intval($data['id']) : 0;
        if(empty($data['id'])){
            return array('code'=>'300','msg'=>'未获取到客资ID','data'=>'');
        }else{
            db()->startTrans();
            try{
                db('c_customerinfo')->where('id',$param['id'])->update($param);
                action_log($param,[],$param['id'],session('staff_id'),session('staff_name'));
                db()->commit();
                return array('code'=>'200','msg'=>'修改介绍人信息成功！','data'=>'');
            }catch (Exception $e){
                db()->rollback();
                return array('code'=>'300','msg'=>'修改介绍人信息失败！','data'=>$e->getMessage());
            }
        }
    }
/*
 * PC端修改介绍人信息---end---
 * */
    /*------------------------移动端方法------end------------------------*/
    //追踪标记
    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();
            $re = db('CCustomerinfo')->where('id', $param['id'])->update($param);
            if($re !== false){
                $info = $this->getCustomerInfo($param['id']);//客资信息
                // 录入record，筛客filter，销售sale
                if($param['is_success'] == 1){
                    $param['order_status'] = 1;
                    $param['order_valid'] = 2;
                }
                $listName = 'historyDataList';
                $oldDate = array(
                    'fp_staff_id'       => $info['fp_staff_id'],
                    'fp_staff'          => $info['fp_staff'],
                    'fp_staff_number'   => $info['fp_staff_number'],
                    'is_fp'             => $info['is_fp'],
                    'sales_staff_id'    => $info['sales_staff_id'],
                    'sales_staff'       => $info['sales_staff'],
                    'sales_staff_number'=> $info['sales_staff_number'],
                    'fp_day'            => $info['fp_day'],
                );
                $cinfo = [
                    'id'     => $info['id'],
                    'dj_id'  => $info['dj_staff_id'],
                    'dj_day' => $info['dj_day'],
                    'sel_id' => $info['sk_staff_id'],
                    'sel_day'=> $info['sk_time'],
                    'jr_id'  => $info['sales_staff_id'],
                    'jr_day' => $info['jr_day'],
                ];
                $message = array(
                    'type' => 1,
                    'staff_id'   => session('staff_id'),
                    'identity'   => 'sale',
                    'cinfo'      => $cinfo,
                    'old_data'   => $oldDate,
                    'new_data'   => $param,
                    'controller' => 'Customer',
                    'action'     => 'customerSign',
                );
                $r =  push_list($listName, $message);
                // redisQueue::init()->rPush($listName, $message);
                if($r){
                    action_log($param, '', $param['id'], session('staff_id'), session('staff_name'));
                    db()->commit();
                    $res = array('code'=>200,'msg'=>'标记成功');
                }else{
                    db()->rollback();
                    $res = array('code'=>103,'msg'=>'标记出错');
                }
            }else{
                db()->rollback();
                $res = array('code'=>104,'msg'=>'标记出错');
            }
        }else{
            $res = array('code'=>300,'msg'=>'ID未获取到');
        }
        return $res;
    }

    //不再追踪（不再追踪原因）
    public function notTraking($data){
        if($data['id']){
            $data['is_loss']=1;
            $data['loss_day']=date('Y-m-d H:i:s',time());
            if($data['loss_cause']){
                $data['loss_cause']=trim($data['loss_cause']);
            }else{
                unset($data['loss_cause']);
            }
            db()->startTrans();
            try{
                $result=db('c_customerinfo')->where('id',$data['id'])->update($data);
                action_log($data,'',$data['id'],session('staff_id'),session('staff_name'));
                db()->commit();
                $res = array('code'=>200,'msg'=>'操作成功');
            }catch (Exception $e){
                db()->rollback();
                $res = array('code'=>101,'msg'=>'操作失败');
            }
        }else{
            $res = array('code'=>102,'msg'=>'未获取到此条客资信息');
        }
        return $res;
    }

    //发送短信
    public function send_message($param){
        $customerInfos = $this->getCustomerInfos($param['ids']);
        $db = db('CSendMessageLog');
        $db->startTrans();
        try{
            preg_match("/(?:\{)(.*)(?:\})/i",$param['send_msg'], $name);
            preg_match("/(?:\[)(.*)(?:\])/i",$param['send_msg'], $sex);
            foreach($customerInfos as $k=>$v){
                if($v['customer_sex'] == '男'){
                    $m = '先生';
                }elseif($v['customer_sex'] == '女'){
                    $m = '女士';
                }else{
                    $m = '';
                }
                //字符串替换
                $send_msg1 = str_replace($name[0],$v['customer_name'],$param['send_msg']);
                $send_msg = str_replace($sex[0],$m,$send_msg1);

                $data = array(
                    'send_id' => session('staff_id'),
                    'send_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'=>$v['customer_name'],
                    'receive_phone'=>$v['customer_tel']
                );
                //调用短信接口
                $url = '5a17b86088f1a';
                $da = array(
                    'mobile' => $v['customer_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'=>'短信接口调用失败','code'=>100);
                }
                $db->insert($data);
            }
            action_log($param,'',0,session('staff_id'),session('staff_name'));
            db()->commit();
        }catch (Exception $e){
            $db->rollBack();
            return array('msg'=>'短信发送失败','code'=>100);
        }
        return array('msg'=>'短信发送成功','code'=>200);
    }
    //追踪添加
    public function addSalesTracking($param){

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

                db('CCustomerinfo')->where('id',$param['customer_id'])->update($arr);

                $listName = 'historyDataList';
                $cinfo = [
                    'id'     => $info['id'],
                    'dj_id'  => $info['dj_staff_id'],
                    'dj_day' => $info['dj_day'],
                    'sel_id' => $info['sk_staff_id'],
                    'sel_day'=> $info['sk_time'],
                    'jr_id'  => $info['sales_staff_id'],
                    'jr_day' => $info['jr_day'],
                ];
                $message = array(
                    'type' => 1,
                    'staff_id'   => session('staff_id'),
                    'identity'   => 'sale',
                    'cinfo'      => $cinfo,
                    'old_data'   => array(),
                    'new_data'   => array('tel_num'=>1),
                    'controller' => 'Customer',
                    'action'     => 'addSalesTracking',
                );
                $msg = push_list($listName, $message);
                // redisQueue::init()->rPush($listName, $message);
                if($msg === false){
                    db()->rollback();
                    return false;
                }
            }
            action_log($param,'',$param['customer_id'],session('staff_id'),session('staff_name'));
            db()->commit();
            return array('code'=>200,'id'=>$id,'data'=>$param);
        }catch (Exception $e){
            db()->rollBack();//回滚
            return false;
        }
    }
    //追踪修改
    public function editSalesTracking($param){
        $param['sales_remark'] = save_clips_to_file($param['sales_remark'],'upload/img/'.date('Ymd',time()));
        $param['sales_remark'] = DeleteHtml($param['sales_remark']);
        $info = $this->get_staff_info(array('staff_id'=>session('staff_id')));
        $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'] = $info['data']['staffnumber'];
        $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'];
        $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'];
        $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'];
        foreach($param as $k=>$v){
            if(empty($v) || $v == '请选择'){
                unset($param[$k]);
            }
        }
        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['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['noTrack']);
        unset($param['reject_reason']);
        unset($param['reason']);
        if(intval($param['id'])){//电访过后的修改
            db()->startTrans();//开启事务
            try{
                // print_r($param);die;
                $res = db('CSalestrackinginfo')->where('id',$param['id'])->update($param);
                cache('getCustomerTrackInfos'.$param['customer_id'],null);
                //修改追踪时间
                $time = date('Y-m-d H:i:s',time());
                $info = db('CCustomerinfo')->where('id',$param['customer_id'])->find();
                if(empty($info['c_star_day'])){
                    $arr = array(
                        'c_star_day' => $time,
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                        'seles_step' => $param['seles_step'],
                        'step_name' => $param['step_name'],
                        'consultation_type_id' => $consultation_type_id,
                        'customer_intention_id' => $customer_intention_id,
                        'consultation_type' => $param['consultation_type'],
                        'customer_intention' => $param['customer_intention'],
                        'sign_id' => $sign_id,
                        'sign_name' => $sign_name,
                        'sign_time' => $time,
                        'is_valid' => $data['is_valid'],
                        'yjd_day' => $data['yjd_day'],
                        'consulation_shop_code' => $data['consulation_shop_code'],
                        'consulation_shop' => $data['consulation_shop'],
                        'reception_id' => $data['reception_id'],
                        'reception_name' => $data['reception_name'],
                        'customer_sex' => $data['customer_sex'],
                        'customer_name' => $param['customer_name'],
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                        'seles_step' => $param['seles_step'],
                        'step_name' => $param['step_name'],
                        'consultation_type_id' => $consultation_type_id,
                        'customer_intention_id' => $customer_intention_id,
                        'consultation_type' => $param['consultation_type'],
                        'customer_intention' => $param['customer_intention'],
                        'sign_id' => $sign_id,
                        'sign_name' => $sign_name,
                        'sign_time' => $time,
                        'is_valid' => $data['is_valid'],
                        'yx_day' => $data['is_valid'] == 1 ? $time : null ,
                        'yjd_day' => $data['yjd_day'],
                        'consulation_shop_code' => $data['consulation_shop_code'],
                        'consulation_shop' => $data['consulation_shop'],
                        'reception_id' => $data['reception_id'],
                        'reception_name' => $data['reception_name'],
                        'customer_sex' => $data['customer_sex'],
                        'customer_name' => $param['customer_name'],
                    );
                }

                if($noTrack == 1){
                    array_push($arr,['is_loss'=>1,'loss_day'=>$time,'loss_cause'=>$param['sales_remark']]);
                }
                db('CCustomerinfo')->where('id',$param['customer_id'])->update($arr);

                if($data['is_valid'] == 4){
                    $result = $this->customerReject(['cid'=>$param['customer_id'],'send_msg'=>$param['sales_remark']]);
                    if($result['code'] != 200){
                        db()->rollback();
                        return array('code'=>300,'msg'=>$result['msg'],'data'=>$param);
                    }
                }
                //修改预约进店时间时再次插入一条追踪记录
                if($data['yjd_day'] && ($info['yjd_day'] != $data['yjd_day'])){
                    $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'],
                    );
                    $res = $this->customerYJD($yjd);
                    if($res['code'] != 200){
                        db()->rollback();
                        return array('code'=>100,'msg'=>$res['msg'],'data'=>'');
                    }
                }
                getSalesTracking($param['customer_id']);//获取最近三次追踪记录同步更新到客资表

                db()->commit();//提交事务
                return array('code'=>200,'msg'=>'追踪成功');
            }catch(Exception $e){
                db()->rollBack();//回滚
                return array('code'=>100,'msg'=>'追踪失败','data'=>$e->getMessage());
            }
        }else{//qq，微信聊天之后直接保存，没有通话时间，直接保存的
            db()->startTrans();
            try{
                //修改追踪时间
                $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,
                        'seles_step' => $param['seles_step'],
                        'step_name' => $param['step_name'],
                        'consultation_type_id' => $consultation_type_id,
                        'customer_intention_id' => $customer_intention_id,
                        'consultation_type' => $param['consultation_type'],
                        'customer_intention' => $param['customer_intention'],
                        'sign_id' => $sign_id,
                        'sign_name' => $sign_name,
                        'sign_time' => $time,
                        'yjd_day' => $data['yjd_day'],
                        'consulation_shop_code' => $data['consulation_shop_code'],
                        'consulation_shop' => $data['consulation_shop'],
                        'reception_id' => $data['reception_id'],
                        'reception_name' => $data['reception_name'],
                        'customer_sex' => $data['customer_sex'],
                        'customer_name' => $param['customer_name'],
                    );
                }else{
                    $arr = array(
                        'c_end_day' => $time,
                        'last_trackday' => $time,
                        'seles_step' => $param['seles_step'],
                        'step_name' => $param['step_name'],
                        'consultation_type_id' => $consultation_type_id,
                        'customer_intention_id' => $customer_intention_id,
                        'consultation_type' => $param['consultation_type'],
                        'customer_intention' => $param['customer_intention'],
                        'sign_id' => $sign_id,
                        'sign_name' => $sign_name,
                        'sign_time' => $time,
                        'yjd_day' => $data['yjd_day'],
                        'consulation_shop_code' => $data['consulation_shop_code'],
                        'consulation_shop' => $data['consulation_shop'],
                        'reception_id' => $data['reception_id'],
                        'reception_name' => $data['reception_name'],
                        'customer_sex' => $data['customer_sex'],
                        'customer_name' => $param['customer_name'],
                    );
                }
                if($info['is_valid'] != 1 && $data['is_valid'] == 1){
                    $arr['is_valid'] = 1;
                    $arr['yx_day'] = $time;
                }
                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)){
                        unset($arr[$k]);
                    }
                }

                if($noTrack == 2){
                    // $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]);
                    if($result['code'] != 200){
                        db()->rollback();
                        return array('code'=>300,'msg'=>$result['msg'],'data'=>'');
                    }
                }
                if($noTrack == 3 && $data['yjd_day'] && ($info['yjd_day'] != $data['yjd_day'])){
                    $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'],
                    );
                    $res = $this->customerYJD($yjd);
                    if($res['code'] != 200){
                        db()->rollback();
                        return array('code'=>100,'msg'=>$res['msg'],'data'=>'');
                    }
                }
                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']]);
                }
                if($noTrack == 1 || $noTrack == 4){
                    if($noTrack == 4){
                        $param['sales_remark'] = '不再追踪：'.$reason.'--'.$param['sales_remark'];
                    }
                    db('CSalestrackinginfo')->insertGetId($param);
                    db('c_customerinfo')->where('id',$param['customer_id'])->setInc('tel_visit_num');//电访量
                    cache('getCustomerTrackInfos'.$param['customer_id'],null);
                    getSalesTracking($param['customer_id']);//获取最近三次追踪记录同步更新到客资表
                    action_log($param,$info,$param['customer_id'],session('staff_id'),session('staff_name'));
                }

                db('CCustomerinfo')->where('id',$param['customer_id'])->update($arr);

                $listName = 'historyDataList';
                $cinfo = [
                    'id'     => $info['id'],
                    'dj_id'  => $info['dj_staff_id'],
                    'dj_day' => $info['dj_day'],
                    'sel_id' => $info['sk_staff_id'],
                    'sel_day'=> $info['sk_time'],
                    'jr_id'  => $info['sales_staff_id'],
                    'jr_day' => $info['jr_day'],
                ];
                $message = array(
                    'type' => 1,
                    'staff_id'   => session('staff_id'),
                    'identity'   => 'sale',
                    'cinfo'      => $cinfo,
                    'old_data'   => array(),
                    'new_data'   => array('tel_num'=>1),
                    'controller' => 'Customer',
                    'action'     => 'addSalesTracking',
                );
                $msg = push_list($listName, $message);
                // redisQueue::init()->rPush($listName, $message);
                if($msg === false){
                    db()->rollback();
                    // return false;
                    return array('code'=>300,'msg'=>'统计数据插入失败','data'=>$param);
                }

                db()->commit();
                return array('code'=>200,'msg'=>'追踪成功','data'=>'');
            }catch (Exception $e){
                db()->rollBack();//回滚
                return array('code'=>100,'msg'=>'追踪失败','data'=>$e->getMessage());
            }
        }



    }
    //新客资来电添加
    public function addNewCusCall($param){
        $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');
        foreach($param as $k=>$v){
            if(empty($v) || $v == '请选择'){
                unset($param[$k]);
            }
        }
        $db = db('CCallRegistration');
        $db->startTrans();
        $id = $db->insertGetId($param);
        if($id){
            $db->commit();
            return $id;
        }else{
            $db->rollback();
            return false;
        }
    }
    //老客资来电添加
    public function addOldCusCall($param){
        $info = $this->get_staff_info(array('staff_id'=>session('staff_id')));
        $c_info = $this->getCustomerInfo($param['customer_id']);
        $param['dj_staff'] = $info['data']['staffname'];
        $param['dj_staff_id'] = $info['data']['id'];
        $param['dj_staff_number'] = $info['data']['staffnumber'];
        $param['shop_name'] = $info['data']['shop_name'];
        $param['shop_code'] = $info['data']['shop_code'];
        $param['customer_sex'] = $c_info['customer_sex'];
        $param['customer_wechat'] = $c_info['customer_wechat'];
        $param['customer_weibo'] = $c_info['customer_weibo'];
        $param['customer_qq'] = $c_info['customer_qq'];
        $param['customer_address'] = $c_info['customer_address'];
        $param['customer_sex'] = $c_info['customer_sex'];
        $param['access_model'] = $c_info['access_model'];
        $param['customer_region'] = $c_info['customer_region'];
        $db = db('CCallRegistration');
        $db->startTrans();
        $id = $db->insertGetId($param);
        if($id){
            $db->commit();
            return $id;
        }else{
            $db->rollback();
            return false;
        }
    }

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

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

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

        // 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;
        }
        $customerInfo = db('c_customerinfo')
            ->where('id', $id)
            ->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,wedding_date,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($customerInfo['is_valid'] != 1){
//            return array('code'=>300,'msg'=>'不是有效客资，不能预约进店');
//        }
        if($data['yjd_day']){
            if($customerInfo['is_valid'] != 1){
                $data['is_valid'] = 1;
                $data['yx_day'] = date('Y-m-d H:i:s',time());
            }

            $yjd_day = date('Y-m-d',strtotime($data['yjd_day']));
            //如果标记预约，存入pool表
            //查询再约提前时间
            $adv = db('s_reminditemset')->where('id','remind3')->where('shop_code',session('shop_code'))->where('isopen',1)->field('advancehour')->find();
            if($adv['advancehour'] || $adv['advancehour'] == 0){
//                $adv = $adv['advancehour'] == 0 ? '今天' : $adv['advancehour'].'天后';
                $time = date('Y-m-d H:i:s',strtotime($data['yjd_day'])-86400*$adv['advancehour']);
                $message = array(
                    'customer_id' => $id,
                    'send_type'   => 1,
                    'send_title'  => '预约提醒',
                    'send_msg'    => '当前名为：【'.$customerInfo['customer_name'].'】的客资，'.date('Y-m-d',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()),
                );
            }

        }
        db()->startTrans();
        $is_erp = is_install('sx_erp');
        try{
            // $erp = false;
            if($is_erp){
                $erp = config('ext.app_config');

                $addr = $erp['sx_erp']['addr'];
                // 婚纱0，儿童1
                $url = $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_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"] = $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['wedding_date']) {
                    $wedding_date = date('Y-m-d',strtotime($customerInfo['wedding_date']));
                }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);
                // $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接口调用失败，请重试。');
                }else{
                    db('c_customerinfo')->where('id',$id)->update($data);
                    // newData oldData customer_id staff_id staff_name
                    $logData = [
                        'consulation_shop_code' => $customerInfo['consulation_shop_code'],
                        'consulation_shop'      => $customerInfo['consulation_shop'],
                        'yjd_day'               => $customerInfo['yjd_day'],
                        'intostore_note'        => $customerInfo['intostore_note'],
                        'reception_id'          => $customerInfo['reception_id'],
                        'reception_name'        => $customerInfo['reception_name'],
                    ];
                    action_log($param, $logData, $id, session('staff_id'), session('staff_name'));
                }

            }else{//未安装ERP
                db('c_customerinfo')->where('id',$id)->update($data);
                action_log($param,$customerInfo,$id,session('staff_id'),session('staff_name'));
            }

            //追踪记录
            $params['customer_id'] = $id;
            $params['sales_remark'] = '预约进店备注:'.$data['intostore_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('staffnumber');
            $params['shop_name'] = session('shop_name');
            $params['shop_code'] = session('shop_code');
            db('CSalestrackinginfo')->insert($params);
            cache('getCustomerTrackInfos'.$id,null);
            //修改追踪时间
            $info = $this->getCustomerInfo($id);//客资信息
            $time = date('Y-m-d H:i:s',time());
            if(empty($info['c_start_day'])){
                $arr = array(
                    'c_star_day' => $time,
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }else{
                $arr = array(
                    'c_end_day' => $time,
                    'last_trackday' => $time,
                );
            }
            db('CCustomerinfo')->where('id',$id)->update($arr);
            //修改客资为有效
            if($info['is_valid'] != 1 || empty($info['yx_day'])){
                $upd = array(
                    'is_valid' => 1,
                    'yx_day' => $time
                );
                db('CCustomerinfo')->where('id',$id)->update($upd);
            }
            //修改客资表近三次追踪记录
            getSalesTracking($id);

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

        if($param['order_fact'] && !$param['two_pin_fact']){
            $data['pay_type'] = 1;
            $data['order_fact'] = $param['order_fact'];
            return db('c_order_detail')->insertGetId($data);
        }elseif(!$param['order_fact'] && $param['two_pin_fact']){
            $data['pay_type'] = 2;
            $data['order_fact'] = $param['two_pin_fact'];
            return db('c_order_detail')->insertGetId($data);
        }elseif($param['order_fact'] && $param['two_pin_fact']){
            $data['pay_type'] = 1;
            $data['order_fact'] = $param['order_fact'];
            $id = db('c_order_detail')->insertGetId($data);
            if($id){
                $data['pay_type'] = 2;
                $data['order_fact'] = $param['two_pin_fact'];
                return db('c_order_detail')->insertGetId($data);
            }else{
                return false;
            }
        }else{
            return false;
        }
    }
    //转订单
    public function zhuanOrder($param){
        $time = date('Y-m-d H:i:s',time());
        if($param['target_time'] && $param['target_time']>$time){
            $arr = array('code'=>600,'msg'=>'开单时间不能大于当前时间','data'=>$param['target_time']);
            return $arr;
        }
        $consulation_shop_code = $param['consulation_shop_code'];
        $consulation_shop = $param['consulation_shop'];
        $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['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'];
        $reception_name = $param['reception_name'];
        // staffnumber
        $receptionInfo = getStaffInfoById($reception_id);

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

        // 订单有效标准 （order_rule） 1：实收款；2：占比
        if($brandclassInfo['order_rule'] == 1){
            if($param['order_fact']+$param['two_pin_fact'] >= $brandclassInfo['proportion']){
                $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'] = $param['order_fact'];
                $data['order_fact'] = 0;
                $data['two_pin_fact'] = $param['two_pin_fact'];
            }
        }else if($brandclassInfo['order_rule'] == 2){
            if( (($param['order_fact']+$param['two_pin_fact']) / $data['order_amount']) >= ($brandclassInfo['proportion']/100) ){
                $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'] = $param['order_fact'];
                $data['order_fact'] = 0;
                $data['two_pin_fact'] = $param['two_pin_fact'];
            }
        }else{
            if( (($param['order_fact']+$param['two_pin_fact']) / $data['order_amount']) >= ($brandclassInfo['proportion']/100) ){
                $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'] = $param['order_fact'];
                $data['order_fact'] = 0;
                $data['two_pin_fact'] = $param['two_pin_fact'];
            }
        }
        $customerInfo = db('c_customerinfo')
            ->where('id', $data['customer_id'])
            ->field('customer_number,customer_name,customer_tel,customer_wechat,customer_qq,customer_sex,consultation_type,customer_area,customer_birthday,customer_idtype,customer_idnumber,customer_cource,customer_intention,customer_orderaddress,customer_address,yjd_day,syjd_day,yp_day,wedding_date,mate_name,mate_sex,mate_tel,mate_wechat,mate_qq,mate_birthday,mate_idtype,mate_idnumber,intostore_note,consulation_shop,consulation_shop_code,brandclass_id,ready_baby_day,introducer_number,introducer_name,marry_day,baby_birthday,is_intostore,is_valid')
            ->find();
        // 是否安装erp
        $is_erp = is_install('sx_erp');
        if ($is_erp === false) {
            db()->startTrans();
            try {
                $order_sn = $data['order_sn'] ? trim($data['order_sn']) : 'sx_crm'.time().generate_code();
                $data['order_sn'] = $order_sn;
                $oid = db('c_customer_order')->insert($data);
                history_log($data, [], $data['customer_id'], session('staff_id'), session('staff_name'));
                //写入流水表
                $arr = array(
                    'order_sn' => $data['order_sn'],
                    'order_fact' => $param['order_fact'],
                    'two_pin_fact' => $data['two_pin_fact'],
                    'order_type' => $data['order_type'] ? $data['order_type'] : 2,
                    'order_valid' => $data['order_valid'],
                    'pay_time' => date('Y-m-d',time()),
                    'create_time' => date('Y-m-d H:i:s',time())
                );

                $this->insert_order_detail($arr);
                // db('c_order_detail')->insert($arr);
                // 写入客资表
                $cData['order_number'] = $order_sn;
                if($customerInfo['is_intostore'] != 2){
                    $cData['is_intostore']  = 2;//进店进客
                    $cData['syjd_day'] = $time;
                }elseif($customerInfo['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'];
                $cData['totalpay_money']   = $data['order_amount']+$data['two_pin_amount'];
                $cData['fact_money']       = $data['order_fact']+$data['two_pin_fact']+$data['earnest_money'];
                //修改客资为有效
                $info = db('c_customerinfo')->where('id',$data['customer_id'])->find();
                if($info['is_valid'] != 1 || empty($info['yx_day'])){
                    $cData['is_valid'] = 1;
                    $cData['yx_day'] = $time;
                }
                db('c_customerinfo')->where('id', $data['customer_id'])->update($cData);

                if($cData['is_success']){
                    //如果是爆破活动，修改对应的爆破表数据
                    if($info['is_act'] == 2){
                        db('c_swap_customer')->where('customer_number',$info['customer_number'])->update(['is_success'=>$cData['is_success']]);
                    }
                }
                history_log($cData, [], $data['customer_id'], session('staff_id'), session('staff_name'));
                //追踪记录
                $params['customer_id'] = $data['customer_id'];
                $params['sales_remark'] = '转订单';
                $params['sales_day'] = date('Y-m-d H:i:s',time());
                $params['sales_staff'] = session('staff_name');
                $params['sales_staff_id'] = session('staff_id');
                $params['sales_staff_number'] = session('staffnumber');
                $params['shop_name'] = session('shop_name');
                $params['shop_code'] = session('shop_code');
                db('CSalestrackinginfo')->insert($params);
                cache('getCustomerTrackInfos'.$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('CCustomerinfo')->where('id',$data['customer_id'])->update($arr);
                getSalesTracking($data['customer_id']);
                db()->commit();
                $arr = array('code'=>200,'msg'=>'转订单成功');
            } catch (Exception $e) {
                db()->rollback();
                $arr = array('code'=>100,'msg'=>'转订单失败','data'=>$e->getMessage());
            }
            return $arr;
        }

        // ----------  ERP接口数据  开始  -------- //
        // 店面类型 （1：婚纱；2：儿童；3：旅拍；4：艺术；5：其他）
        $s_shop_type = session('shop_type');
        if ($s_shop_type == 2) {
            $shop_type = 1;
        }else{
            $shop_type = 0;
        }

        $erp = config('ext.app_config');
        $addr = $erp['sx_erp']['addr'];
        // 婚纱0，儿童1
        $url = $addr.'SX_CrmApi/Add_CustomerOrderinfo?Token=^******^&CustomerType='.$shop_type;
        $dataErp = [];
        // 地址
        $dataErp['address']          = $customerInfo['customer_address'] ? $customerInfo['customer_address'] : '';
        // 客户来源
        $dataErp['cssname']          = $customerInfo['customer_cource'] ? $customerInfo['customer_cource'] : '';
        // 客户分区
        $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'] ? $data['order_note'] : '';
        // 宝宝姓名 目前客资表中没有
        $dataErp['bbname']           = $customerInfo['bbname'] ? $customerInfo['bbname'] : '';
        // 宝宝昵称 目前客资表中没有
        $dataErp['bnickname']        = $customerInfo['bnickname'] ? $customerInfo['bnickname'] : '';
        // 宝宝生日（阳历）
        $dataErp['bbithdate']        = $customerInfo['baby_birthday'] ? $customerInfo['baby_birthday'] : '';
        // 宝宝生日（阳历） 目前客资表中没有
        $dataErp['liunardate']       = $customerInfo['liunardate'] ? $customerInfo['liunardate'] : '';
        // 宝宝性别 目前客资表中没有
        $dataErp['bbsex']            = $customerInfo['bbsex'] ? $customerInfo['bbsex'] : '';
        // 宝宝生肖 目前客资表中没有
        $dataErp['bzodiac']          = $customerInfo['bzodiac'] ? $customerInfo['bzodiac'] : '';
        // 联系邮箱 目前客资表中没有
        $dataErp['email']            = $customerInfo['email'] ? $customerInfo['email'] : '';
        // 客户所属店面
        // $dataErp['shop_code']        = '';
        $dataErp['shop_code']        = $consulation_shop_code;
        // 客户所属店面
        $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']       = date('Ymd', strtotime($time));
        // 销售门市
        $dataErp['Storeconsuitant1'] = $reception_name ? $reception_name : '';
        // $dataErp['Storeconsuitant1'] = $receptionInfo['staffnumber'] ? $receptionInfo['staffnumber'] : '';
        // 网销门市 目前没有用
        $dataErp['Storeconsuitant2'] = '';
        // $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';
        // 事业部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;
        // 开启事务
        db()->startTrans();
        try {
            // 调 erp 接口
            $response = requestERP($url, $dataErp);
            // 写入订单表
            // $data['create_time'] = $time;
            // $oid = db('c_customer_order')->insertGetId($data);
            if ($response['Code'] != '200') {
                // if ($response['Code'] != '200' && $response['Code'] != '405') {
                // 存表
                // $next = time()+60;
                // $dataS = [
                //     'url'         => $url,                   // 请求url
                //     'data'        => $dataErp,               // 请求数据
                //     'call_time'   => $next,                  // 请求时间
                //     'type'        => 2,                      // 转订单（需要处理返回值）
                //     'cid'         => $data['customer_id'],   // 客资id
                //     'oid'         => $oid,                   // 订单id
                //     'create_time' => $time,                  // 创建时间
                // ];
                db()->rollback();
                $arr = array('code'=>300,'msg'=>'转订单失败,ERP请求有误');
                // db('c_erp_save')->insert($dataS);
            }else{
                $order_sn = $response['Data'];
                $data['order_sn'] = $order_sn;
                // db('c_customer_order')->where('id', $oid)->update($data);
                $oid = db('c_customer_order')->insert($data);

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

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


                if($customerInfo['is_intostore'] != 2){
                    $cData['is_intostore']  = 2;//进店进客
                    $cData['syjd_day'] = $time;
                }elseif($customerInfo['is_intostore'] == 2){
                    $cData['syjd_day'] = $customerInfo['syjd_day'] ? $customerInfo['syjd_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($info['yx_day'])){
                    $cData['is_valid'] = 1;
                    $cData['yx_day'] = $time;
                }
                db('c_customerinfo')->where('id', $data['customer_id'])->update($cData);


                history_log($cData, [], $data['customer_id'], session('staff_id'), session('staff_name'));

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

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

    }
    public function getCallInfo($id){
        return db('c_call_registration')->where('id',$id)->find();
    }
    //获取渠道补充
    public function getChannel($shop_code){
        $channel = session('channel');
        if(empty($channel)){
        if(empty($shop_code)) $shop_code = session('shop_code');
        $channel = db('s_channel')->where('shop_code',$shop_code)->order('order_sort')->select();
            session('channel',$channel);
        }
        return $channel;
    }

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                $cusInfo['is_success'] = 3;
                $cusInfo['order_day'] = null;
                $cusInfo['order_start_time'] = $order_start_time ? $order_start_time : $time;
                $cusInfo['totalpay_money'] = $param['order_amount']+$param['two_pin_amount'];
                $cusInfo['fact_money'] = $param['order_fact']+$param['two_pin_fact'];
            }
        }

        db()->startTrans();
        try{
            //修改订单表
            db('c_customer_order')->where('order_sn',$param['old_order_sn'])->update($data);
            //修改客资表
            $cusInfo['order_number'] = $data['order_sn'];
            db('c_customerinfo')->where('id',$param['customer_id'])->update($cusInfo);
            //修改流水表
            //当修改单号时更新原来的流水单号
            if($data['order_sn'] != $param['old_order_sn']){
                db('c_order_detail')->where('order_sn',$param['old_order_sn'])->update(['order_sn'=>$data['order_sn']]);
            }
            $dData['order_type'] = $orderInfo['order_type'];
            $dData['order_sn'] = $data['order_sn'];
            $this->insert_order_detail($dData);

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

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

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

                // 向上一级发信息  微信
                $content = [
                    'touser'       => $receive_id,
                    'template_id'  => OPENTM_BH,
                    'data'         => [
                        'first'=>[
                            'value'=> '您好，您有一笔客资被驳回',
                            'color'=> '#173177'
                        ],
                        'keyword1'=>[
                            'value'=> $cInfo['customer_name'].'('.$cInfo['customer_sex'].')',
                            'color'=> '#173177'
                        ],
                        'keyword2'=>[
                            'value'=> $cInfo['customer_tel'],
                            'color'=> '#173177'
                        ],
                        'keyword3'=>[
                            'value'=> $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) {
                    action_log(input('post.'), '', $cid, session('staff_id'), session('staff_name'));
                    db()->commit();
                    $return = ['msg'=>'已驳回给电商','code'=>200];
                }else{
                    db()->rollback();
                    $return = ['msg'=>'操作失败，请联系管理员','code'=>100];
                }
            } catch (Exception $e) {
                $return = ['msg'=>'操作失败，请联系管理员'.$e->getMessage(),'code'=>300];
                db()->rollback();
            };
        }else{
            $return = ['msg'=>'您不是当前客资的追踪人或筛客人或没有驳回权限','code'=>400];
        }
        return $return;
    }

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

        $result['code'] = 0;
        $result['msg'] = '';
        $res = [];
//        foreach($tel as $k=>$v){
//            if($v){
                $res = db('c_customerinfo')
                    ->where('customer_tel|mate_tel|customer_qq|customer_wechat','in',$tel)
                    ->where('brandclass_id',session('brandclass_id'))
                    ->where('is_status',1)
                    ->field('id,customer_name,customer_tel,mate_tel,customer_qq,customer_wechat,shop_name,add_shop_name,dj_staff,dj_day,sales_staff,is_valid,sign_name,c_star_day,is_status,is_success')
                    ->select();
                if(empty($res)){
                    foreach($res as $k=>$v){
                        $res[$k]['id'] = '';
                        $res[$k]['customer_name'] = '';
                        $res[$k]['customer_tel'] = $tel;
                        $res[$k]['shop_name'] = '';
                        $res[$k]['add_shop_name'] = '';
                        $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_valid'] = getIsValid($v['is_valid']);
                        $res[$k]['is_success'] = getIsSuccess($v['is_success']);
                        $res[$k]['track_status'] = $v['c_star_day'] ? '追踪中' : '待追踪';
//                        $res[$k]['is_status'] = $res['is_status'] == 1 ? '未删除' : '已删除';
                    }
                }
//            }
//        }
//        $res = db('c_customerinfo')
//            ->where('customer_tel','in',$tel)
//            ->limit($limit)
//            ->page($page)
//            ->field('id,customer_name,customer_tel,mate_tel,shop_name,add_shop_name,dj_staff,dj_day,sales_staff')
//            ->select();
        $count = db('c_customerinfo')->where('customer_tel','in',$tel)->count();
        if($res){
            $result['data'] = $res;
            $result['count'] = $count;
        }else{
            $result['data'] = array();
        }
        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']?$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'];
        $addr= $erp['addr'];
        $url = $addr.'SX_CrmApi/Sel_CustomerOrderList?Token=^******^&CustomerType='.$shopType;
        $url = $url.'&orderinfo='.$keyword.'&brandid='.$brandId.'&startdate='.$startDate.'&enddate='.$endDate;
        $dataErp = '[]';
        $response = requestERP($url, $dataErp);
        if($response['Code'] == 200){
            $numbers = [];
            foreach($response['Data'] as $k=>$v){//取出客资编号组成数组
                array_push($numbers,$v['customer_from_index']);
            }
            //查询符合的所有客资
            $cusInfo = db('c_customerinfo')->where('customer_number','in',$numbers)->column('customer_number,order_type,sales_staff,syjd_day,c_from','customer_number');

            foreach($response['Data'] as $k=>$v){
                if(empty($v['customer_from_index'])){
                    // $response['Data'][$k]['order_type'] = 1;
                    $response['Data'][$k]['sales_staff'] = '';
                    $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]['sales_staff'] = $cusInfo[$v['customer_from_index']]['sales_staff'];
                    $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';
            $res = sx_call($url,$data);
            if($res['code'] == 200){
                $reason = $res['data'];
                cache('unValidReason'.$reason);
            }else{
                $reason = array('code'=>100,'msg'=>'查询无效客资原因失败','data'=>'');
            }
        }
        return $reason;
    }
}