<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

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 ExcelImportSync extends Controller {
    protected $importHeader = [];
    public function cus_import_sync($data){
        $customer = [];
        $fail_array =[];
        $this->log('import_sync_import_sync_begin--eid-'.$data['eid']);

        $file_url=$data['file_url'];
        if(!$file_url){
            $fileData=db('c_excel_import')->where('id',$data['eid'])->find();
            $file_url=$fileData['file_url'];
        }

        if(empty($file_url)){
            $this->log('import_sync_import_sync没有获取到文件地址');
            db('c_excel_import')->where(array('id'=>$data['eid']))->update(array('status'=>1));
            return false;
        }
        $this->log('import_sync_准备读取文件'.date('Y-m-d H:i:s',time()));
        $objReader =\PHPExcel_IOFactory::createReader('Excel2007');
        $obj_PHPExcel =$objReader->load($file_url, $encode = 'utf-8');  //加载文件内容,编码utf-8
        $array=$obj_PHPExcel->getsheet(0)->toArray();   //转换为数组格式
        $excel_array = [];
        foreach($array as $k=>$v){
            if($v[0] != '' && $v[0] != null){
                $excel_array[] = $v;
            }
        }
        $first=reset($excel_array);
        array_shift($excel_array);
        $all_number=count($excel_array);
        $this->log('import_sync_总数据量'.$all_number);
        if(!$excel_array){
            $this->log('import_sync_没有读取到文件数据');
            db('c_excel_import')->where(array('id'=>$data['eid']))->update(array('status'=>1));
            return false;
        }
        $this->log('import_sync_导入人员信息--->'.json_encode($data['staff']));
        $shop = controller('crm/Customer','lib')->get_shop(['shop_code'=>$data['staff']['shop_code']]);
        $this->log('import_sync_导入店面类型--->'.$shop[0]['shop_type']);
        if($shop[0]['shop_type'] == 2){
            $title=import_header_child();//标准表头格式
        }else{
            $title=import_header();//标准表头格式
        }

        $header=array();
        foreach($title as $key => $val){
            foreach($first as $k => $v){
                if($first[$k]==$title[$key]){
                    $header[$key]=$k;
                    $this->importHeader[$key] = $v;
                }
            }
        }
        $this->log('import_sync_表头--》》'.json_encode($header));
        // var_dump($header);exit;
        $now_xh_num=1;//当前foreach循环次数
        $num=1;//本次foreach处理成功数据条数
        $contact=array();//用于文件数据中排重的联系方式
        $sump = getSumptionType(['brandclass_id'=>$data['staff']['brandclass_id']]);
        $sumption = array_column($sump,'id','consumption_name');

        foreach($excel_array as $k=>$v) {

            $import=cache('import_excel_'.$data['eid']);//处理到第几行（从0开始）
            // $name = str_replace(array("/r/n", "/r", "/n", " ", "　"), "", trim(addslashes($v[$header['customer_name']])));
            if($import&&$k<=$import){
                continue;
            }
            // elseif(strlen($name) == 0){//为空行时跳出
                // continue;
            // }
            else{
                if($shop[0]['shop_type'] == 2){//儿童
                    $tmpName = trim(addslashes($v[$header['baby_name']]));
                    preg_match_all('/[\w\x{4e00}-\x{9fa5}]+/u',$tmpName,$newname);
                    $trueName = $newname && $newname[0]?implode('',$newname[0]):'';
                    $customer[$k]['baby_name']     = $trueName;
                    // $customer[$k]['baby_name']     = trim(addslashes($v[$header['baby_name']]));
                    $customer[$k]['baby_sex']      = trim(addslashes($v[$header['baby_sex']]));
                    $customer[$k]['baby_birthday'] = $v[$header['baby_birthday']] ? date('Y-m-d',strtotime($v[$header['baby_birthday']])) : NULL;
                    $customer[$k]['mate_name']     = trim(addslashes($v[$header['mate_name']]));
                    $customer[$k]['mate_tel']      = trim(addslashes($v[$header['mate_tel']]));
                    $customer[$k]['customer_sex']  = '女';
                    $customer[$k]['mate_sex']      = '男';
                    $customer[$k]['ready_baby_day']= $v[$header['ready_baby_day']] ? date('Y-m-d',strtotime($v[$header['ready_baby_day']])) : NULL;
                }else{
                    $customer[$k]['customer_sex']  = trim(addslashes($v[$header['customer_sex']]));
                }
                $tmpName = trim(addslashes($v[$header['customer_name']]));
                preg_match_all('/[\w\x{4e00}-\x{9fa5}]+/u',$tmpName,$newname);
                $trueName = $newname && $newname[0]?implode('',$newname[0]):'';
                $customer[$k]['customer_name']     = $trueName;
                // $customer[$k]['customer_name']     = trim(addslashes($v[$header['customer_name']]));
                $customer[$k]['customer_tel']      = trim(addslashes($v[$header['customer_tel']]));
                $tmpName = trim(addslashes($v[$header['customer_wechat']]));
                preg_match_all('/[\w\x{4e00}-\x{9fa5}]+/u',$tmpName,$newname);
                $trueName = $newname && $newname[0]?implode('',$newname[0]):'';
                $customer[$k]['customer_wechat']     = $trueName;
                // $customer[$k]['customer_wechat']   = trim(addslashes($v[$header['customer_wechat']]));
                $customer[$k]['customer_qq']       = trim(addslashes($v[$header['customer_qq']]));
                $customer[$k]['customer_weibo']    = trim(addslashes($v[$header['customer_weibo']]));
                $customer[$k]['province']          = trim(addslashes($v[$header['province']]));
                $customer[$k]['city']              = trim(addslashes($v[$header['city']]));
                $customer[$k]['county']            = trim(addslashes($v[$header['county']]));
                $customer[$k]['customer_address']  = trim(addslashes($v[$header['customer_address']]));
                $customer[$k]['customer_type']     = trim(addslashes($v[$header['customer_type']]));
                $customer[$k]['introducer_name'] = trim(addslashes($v[$header['introducer_name']]));//介绍人
                $customer[$k]['customer_channel']  = trim(addslashes($v[$header['customer_channel']]));
                $customer[$k]['channel_plan_number']  = trim(addslashes($v[$header['channel_plan_number']]));
                $customer[$k]['access_model']      = trim(addslashes($v[$header['access_model']]));
                $customer[$k]['consultation_type'] = trim(addslashes($v[$header['consultation_type']]));
                $customer[$k]['customer_cource']   = trim(addslashes($v[$header['customer_cource']]));
                $customer[$k]['customer_area']     = trim(addslashes($v[$header['customer_area']]));
                $customer[$k]['customer_intention']= trim(addslashes($v[$header['customer_intention']]));
                $customer[$k]['consulation_shop']  = trim(addslashes($v[$header['consulation_shop']]));
                $customer[$k]['sales_staff']       = trim(addslashes($v[$header['sales_staff']]));
                $customer[$k]['customer_remark']   = trim(addslashes($v[$header['customer_remark']]));
                $customer[$k]['customer_key']      = trim(addslashes($v[$header['customer_key']]));
                $customer[$k]['introduce_staff_name'] = trim(addslashes($v[$header['introduce_staff_name']]));
                $customer[$k]['customer_orderaddress']= trim(addslashes($v[$header['customer_orderaddress']]));
                $customer[$k]['customer_label']= trim(addslashes($v[$header['customer_label']]));
                // 导入 hm
                // $customer[$k]['dj_staff']    = $v[$header['dj_staff']] ? addslashes($v[$header['dj_staff']]) : '';
                // $customer[$k]['dj_staff_id'] = $v[$header['dj_staff_id']] ? addslashes($v[$header['dj_staff_id']]) : 0;
                // $customer[$k]['dj_day']      = $v[$header['dj_day']] ? addslashes($v[$header['dj_day']]) : null;

                // $customer[$k]['fp_staff']    = $v[$header['dj_staff']] ? addslashes($v[$header['dj_staff']]) : '';
                // $customer[$k]['fp_staff_id'] = $v[$header['dj_staff_id']] ? addslashes($v[$header['dj_staff_id']]) : 0;
                // $customer[$k]['fp_day']      = $v[$header['fp_day']] ? addslashes($v[$header['fp_day']]) : null;
                // $customer[$k]['jr_day']      = $v[$header['jr_day']] ? addslashes($v[$header['jr_day']]) : null;

                // $customer[$k]['add_shop_code'] = $v[$header['add_shop_code']] ? addslashes($v[$header['add_shop_code']]) : '';
                // $customer[$k]['add_shop_name'] = $v[$header['add_shop_name']] ? addslashes($v[$header['add_shop_name']]) : '';

                // $customer[$k]['brandclass']    = $v[$header['brandclass']] ? addslashes($v[$header['brandclass']]) : '';
                // $customer[$k]['brandclass_id'] = $v[$header['brandclass_id']] ? addslashes($v[$header['brandclass_id']]) : 0;

                // $customer[$k]['is_valid']    = $v[$header['is_valid']] ? addslashes($v[$header['is_valid']]) : 2;

                // $customer[$k]['yx_day']      = $v[$header['yx_day']] ? addslashes($v[$header['yx_day']]) : date('Y-m-d H:i:s',time());

                // $customer[$k]['yjd_day']       = $v[$header['yjd_day']] ? addslashes($v[$header['yjd_day']]) : null;
                // $customer[$k]['is_intostore']  = addslashes($v[$header['is_intostore']]) ? addslashes($v[$header['is_intostore']]) : 1;
                // $customer[$k]['syjd_day']      = $v[$header['syjd_day']] ? addslashes($v[$header['syjd_day']]) : null;
                // $customer[$k]['c_star_day']    = $v[$header['c_star_day']] ? addslashes($v[$header['c_star_day']]) : null;

                //$this->log('import_sync_本条数据===》》》'.json_encode($customer)."\n\r");

                if(empty($fileData)){
                    $fileData=db('c_excel_import')->where('id',$data['eid'])->find();
                }
                if(!$customer[$k]){
                    unset($customer[$k]);
                    if($k==count($excel_array)-1){
                        $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                        return false;
                    }else{
                        continue;
                    }
                }
                /* if($shop[0]['shop_type'] == 2){//儿童
                    if(empty($customer[$k]['baby_name'])){
                        $customer[$k]['error']='没有填写宝宝姓名';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }

                }*/
                $lrMust = db_config('lr_must_'.$data['staff']['brandclass_id']);
                $lrMust = explode(',',trim($lrMust,','));
                $this->log('import_sync_-------必选项-->>'.json_encode($lrMust));
                if($shop[0]['shop_type'] == 2) {//儿童
                    if(in_array('baby_birthday',$lrMust)){
                        if ($customer[$k]['baby_birthday']) {
                            // $baby_birthday = date('Y-m-d', strtotime($customer[$k]['baby_birthday']));
                            if ($customer[$k]['baby_birthday'] == '1970-01-01') {
                                $customer[$k]['error']='宝宝生日填写有误，请按照正确格式填写。';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                        }
                    }
                }
                if(in_array('customer_channel',$lrMust)){
                    if(empty($customer[$k]['customer_channel'])){
                        //$this->log('import_sync_第'.$now_xh_num.'次循环，第'.$num.'条，没有‘来源渠道’。----文件第'.$k.'行');
                        $customer[$k]['error']='没有填写渠道名称';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }
                if(empty($customer[$k]['customer_name'])){
                    $customer[$k]['error']='没有填写客资姓名';
                    array_push($fail_array,$customer[$k]);
                    unset($customer[$k]);
                    if($k==count($excel_array)-1){
                        $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                        return false;
                    }else{
                        continue;
                    }
                }
                if(in_array('customer_sex',$lrMust)){
                    if(empty($customer[$k]['customer_sex'])){
                        $customer[$k]['error']='没有填写性别';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }
                if(in_array('customer_intention',$lrMust)){
                    if(empty($customer[$k]['customer_intention'])){
                        $customer[$k]['error']='没有填写客户意向';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }
                if(in_array('customer_cource',$lrMust)){
                    if(empty($customer[$k]['customer_cource'])){
                        $customer[$k]['error']='没有填写客户来源';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }else{
                    //没有来源，给个默认，如果默认也没有，就是空了。
                    if(empty($customer[$k]['customer_cource'])){
                        $source=controller("crm/Customer","lib")->source();
                        $cusTypeId = $customer[$k]['customer_type'] == '转介绍'?2:3;
                        foreach ($source as $vsource) {
                            if($vsource['type_id'] == $cusTypeId || $vsource['type_id'] == 0){
                                // $customer[$k]['customer_cource_id'] = $vsource['id'];
                                $customer[$k]['customer_cource'] = $vsource['cus_name'];
                                break;
                            }
                        }
                    }
                }
                if(in_array('province',$lrMust)){
                    if(empty($customer[$k]['province'])){
                        $customer[$k]['error']='没有填写省份';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }
                if(in_array('city',$lrMust)){
                    if(empty($customer[$k]['city'])){
                        $customer[$k]['error']='没有填写市';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }
                if(in_array('consulation_shop',$lrMust)){
                    if(empty($customer[$k]['consulation_shop'])){
                        $customer[$k]['error']='没有填写意向店面';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }
                if(in_array('sales_staff_id',$lrMust)){
                    if(empty($customer[$k]['sales_staff'])){
                        $customer[$k]['error']='没有填写追踪人';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }
                if(in_array('customer_remark',$lrMust)){
                    if(empty($customer[$k]['customer_remark'])){
                        $customer[$k]['error']='没有填写客资备注';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }


                if(in_array('consultation_type',$lrMust)){
                    if(empty($customer[$k]['consultation_type'])){
                        $customer[$k]['error']='没有填写消费类型';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }

                if(in_array('access_model',$lrMust)){
                    if(empty($customer[$k]['access_model'])){
                        //$this->log('import_sync_第'.$now_xh_num.'次循环，第'.$num.'条，没有‘获取方式’。----文件第'.$k.'行');
                        $customer[$k]['error']='没有填写获取方式';
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }
                }
                if($customer[$k]['customer_wechat']||$customer[$k]['customer_qq']||$customer[$k]['customer_tel']){
                    //手机号存在
                    if(!empty($customer[$k]['customer_tel'])){
                        if(!preg_match("/^1[3|4|5|6|7|8|9][0-9]{9}$/", $customer[$k]['customer_tel'])){//手机号格式
                            //$this->log('import_sync_第'.$now_xh_num.'次循环，第'.$num.'条，手机号格式错误。----文件第'.$k.'行');
                            $customer[$k]['error']='手机号格式错误';
                            array_push($fail_array,$customer[$k]);
                            unset($customer[$k]);
                            if($k==count($excel_array)-1){
                                $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                return false;
                            }else{
                                continue;
                            }
                        }else{
                            if(in_array($customer[$k]['customer_tel'],$contact)){
                                //$this->log('import_sync_第'.$now_xh_num.'次循环，第'.$num.'条，文件中手机号重复。----文件第'.$k.'行');
                                $customer[$k]['error']='此条客资已重复';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                        }
                    }

                    if(!empty($customer[$k]['customer_wechat'])){
                        // if(preg_match('/[\x{4e00}-\x{9fa5}]/u',$customer[$k]['customer_wechat'])>0){
                        //     //$this->log('import_sync_第'.$now_xh_num.'次循环，第'.$num.'条，微信格式错误。----文件第'.$k.'行');
                        //     $customer[$k]['error']='微信号输入错误';
                        //     array_push($fail_array,$customer[$k]);
                        //     unset($customer[$k]);
                        //     if($k==count($excel_array)-1){
                        //         $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                        //         return false;
                        //     }else{
                        //         continue;
                        //     }
                        // }else{
                            if(in_array($customer[$k]['customer_wechat'],$contact)){
                                //$this->log('import_sync_第'.$now_xh_num.'次循环，第'.$num.'条，文件中微信重复。----文件第'.$k.'行');
                                $customer[$k]['error']='此条客资已重复';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                        // }
                    }

                    if(!empty($customer[$k]['customer_qq'])){
                        // if(preg_match('/[\x{4e00}-\x{9fa5}]/u', $customer[$k]['customer_qq'])>0){
                        //     //$this->log('import_sync_第'.$now_xh_num.'次循环，第'.$num.'条，qq格式错误。----文件第'.$k.'行');
                        //     $customer[$k]['error']='QQ号输入错误';
                        //     array_push($fail_array,$customer[$k]);
                        //     unset($customer[$k]);
                        //     if($k==count($excel_array)-1){
                        //         $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                        //         return false;
                        //     }else{
                        //         continue;
                        //     }
                        // }else{
                            if(in_array($customer[$k]['customer_qq'],$contact)){
                                //$this->log('import_sync_第'.$now_xh_num.'次循环，第'.$num.'条，文件中qq重复。----文件第'.$k.'行');
                                $customer[$k]['error']='此条客资已重复';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                        // }
                    }

                    $arr=controller('crm/Customer','lib')->isRepeat($data['staff']['brandclass'],$customer[$k]['customer_tel'],$customer[$k]['customer_wechat'],$customer[$k]['customer_qq'],$customer[$k]['mate_tel'],0,$sumption[$customer[$k]['consultation_type']],$data['staff']['add_shop_code']);
                    $this->log('排重返回结果:'.$customer[$k]['customer_tel'].'--'.json_encode($arr));
                    if($arr['code'] == 201){
                        $this->log('第'.$now_xh_num.'次循环，第'.$num.'条，数据库中已经存在此联系方式。----文件第'.$k.'行');
                        if($arr['data']['customer_tel'] == $customer[$k]['customer_tel']){
                            $customer[$k]['error']='系统内已存在此手机号';
                        }elseif($arr['data']['customer_wechat'] == $customer[$k]['customer_wechat']){
                            $customer[$k]['error']='系统内已存在此微信号';
                        }elseif($arr['data']['customer_qq'] == $customer[$k]['customer_qq']){
                            $customer[$k]['error']='系统内已存在此QQ';
                        }else{
                            $customer[$k]['error']='系统内已存在此客资';
                        }

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

                        if ($arr['data']['sales_staff']) {
                            //重复提醒
                            // $notice = db_config('cus_repeat_notice');
                            // if($notice){
                                $message['send_type']      = 1;
                                $message['send_title']     = '拦截提醒';
                                $message['send_msg']       = $sales_remark;
                                $message['customer_id']    = $arr['data']['id'];
                                $message['receive_id']     = $arr['data']['sales_staff_id'];
                                $message['receive_name']   = $arr['data']['sales_staff'];
                                $message['receive_status'] = 0;
                                $message['operation_type'] = 1;
                                $message['operation']      = [];
                                $message['time_out']       = 240;
                                sendSystemMessage($message);
                            // }
                        }
                        $lanjieCount = db('c_customer_from')->where('cid',$arr['data']['id'])->count();
                        if ($lanjieCount) {
                            db('c_customer_from')->where('cid',$arr['data']['id'])->setInc('lanjie_num',1);
                        }else{
                            $lanjieData['cid'] = $arr['data']['id'];
                            $lanjieData['lanjie_num'] = 1;
                            db('c_customer_from')->insert($lanjieData);
                        }
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$k]);
                        if($k==count($excel_array)-1){
                            $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            return false;
                        }else{
                            continue;
                        }
                    }else{

                        $conditions=array();
                        if($customer[$k]['customer_channel'])    $conditions['customer_channel']=$customer[$k]['customer_channel'];
                        if($customer[$k]['consultation_type'])   $conditions['consultation_type']=$customer[$k]['consultation_type'];
                        if($customer[$k]['access_model'])         $conditions['access_model']=$customer[$k]['access_model'];
                        if($customer[$k]['customer_cource'])     $conditions['customer_cource']=$customer[$k]['customer_cource'];
                        if($customer[$k]['customer_intention'])  $conditions['customer_intention']=$customer[$k]['customer_intention'];
                        if($customer[$k]['customer_area'])        $conditions['customer_area']=$customer[$k]['customer_area'];
                        //if($customer[$k]['customer_region'])      $conditions['customer_region']=$customer[$k]['customer_region'];
                        if($customer[$k]['customer_orderaddress'])  $conditions['customer_orderaddress']=$customer[$k]['customer_orderaddress'];
                        if($customer[$k]['consulation_shop'])     $conditions['consulation_shop']=$customer[$k]['consulation_shop'];
                        if($customer[$k]['province'])              $conditions['province']=$customer[$k]['province'];
                        if($customer[$k]['city'])                   $conditions['city']=$customer[$k]['city'];
                        if($customer[$k]['county'])                 $conditions['county']=$customer[$k]['county'];
                        if($customer[$k]['sales_staff'])           $conditions['sales_staff']=$customer[$k]['sales_staff'];
                        $conditions['brandclass_id']=$data['staff']['brandclass_id'];
                        $all_id=controller('crm/Customer','lib')->get_set_id($conditions,$data['staff']['add_shop_code'],$data['staff']['shop_code']);
                        // $this->log('import_sync_all_id:'.json_encode($all_id));
                        if(!empty($all_id)){

                            if($customer[$k]['customer_channel']&&empty($all_id['customer_channel_id'])){
                                $customer[$k]['error']='渠道名称填写有误';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }

                            if($customer[$k]['consultation_type']&&empty($all_id['consultation_type_id'])){
                                $customer[$k]['error']='消费类型填写有误';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                            if($customer[$k]['access_model']&&empty($all_id['access_model_id'])){
                                $customer[$k]['error']='获取方式填写有误';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                            if($customer[$k]['customer_cource']&&empty($all_id['customer_cource_id'])){
                                $customer[$k]['error']='客户来源填写有误';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                            if($customer[$k]['customer_intention']&&empty($all_id['customer_intention_id'])){
                                $customer[$k]['error']='客户意向填写有误';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                            if($customer[$k]['customer_area']&&empty($all_id['customer_area_id'])){
                                $customer[$k]['error']='客户分区填写有误';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                            // if($customer[$k]['customer_region']&&empty($all_id['customer_region_id'])){
                            //     $customer[$k]['error']='客户地域填写有误';
                            //     array_push($fail_array,$customer[$k]);
                            //     unset($customer[$k]);
                            //     if($k==count($excel_array)-1){
                            //         $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                            //         return false;
                            //     }else{
                            //         continue;
                            //     }
                            // }
                            if($customer[$k]['customer_orderaddress']&&empty($all_id['customer_orderaddress_id'])){
                                $customer[$k]['error']='接单点填写有误';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                            if($customer[$k]['consulation_shop']&&empty($all_id['consulation_shop_code'])){
                                $customer[$k]['error']='意向店面填写有误';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                            if($customer[$k]['province']&&empty($all_id['province_id'])){
                                $customer[$k]['error']='省填写有误'.$all_id['province_id'];
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                            if($customer[$k]['city']&&empty($all_id['city_id'])){
                                $customer[$k]['error']='市填写有误'.$all_id['city_id'];
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                            if($customer[$k]['county']&&empty($all_id['county_id'])){
                                $customer[$k]['error']='区填写有误'.$all_id['county_id'];
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }
                            if($customer[$k]['sales_staff']&&empty($all_id['sales_staff_id'])){
                                $customer[$k]['error']='追踪人填写有误';
                                array_push($fail_array,$customer[$k]);
                                unset($customer[$k]);
                                if($k==count($excel_array)-1){
                                    $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                    return false;
                                }else{
                                    continue;
                                }
                            }

                            $customer[$k]['customer_channel_id']=$all_id['customer_channel_id'];
                            $customer[$k]['consultation_type_id']=$all_id['consultation_type_id'];
                            $customer[$k]['access_model_id']=$all_id['access_model_id'];
                            $customer[$k]['customer_cource_id']=$all_id['customer_cource_id'];
                            $customer[$k]['customer_intention_id']=$all_id['customer_intention_id'];
                            $customer[$k]['customer_area_id']=$all_id['customer_area_id'];
                            $customer[$k]['customer_orderaddress_id']=$all_id['customer_orderaddress_id'];
                            $customer[$k]['consulation_shop_code']=$all_id['consulation_shop_code'];
                            $customer[$k]['customer_region_id']=$all_id['customer_region_id'];
                            $customer[$k]['province_id']=$all_id['province_id'];
                            $customer[$k]['customer_region_id']=$all_id['customer_region_id'];
                            $customer[$k]['customer_region']=$all_id['customer_region'];
                            $customer[$k]['city_id']=$all_id['city_id'];
                            $customer[$k]['county_id']=$all_id['county_id'];
                            $customer[$k]['sales_staff_id']=$all_id['sales_staff_id'];
                            $customer[$k]['sales_staff_number']=$all_id['sales_staff_number'];

                            $dj = getStaffInfoById($data['staff']['staff_id']);
                            if ($customer[$k]['sales_staff_id']) {
                                $customer[$k]['is_fp']  = 1;
                                $sales = getStaffInfoById($all_id['sales_staff_id']);
                                $this->log('import_sync_部门--指定追踪人部门信息--'.json_encode($sales));
                                $customer[$k]['sales_department_id']  = $sales['department_id'];
                                $customer[$k]['sales_department_name']  = $sales['department_name'];
                                $customer[$k]['fp_department_id']  = $dj['department_id'];
                                $customer[$k]['fp_department_name']  = $dj['department_name'];
                                $customer[$k]['fp_staff']=$data['staff']['staff_name'];
                                $customer[$k]['fp_staff_id']=$data['staff']['staff_id'];
                                $customer[$k]['fp_staff_number']=$data['staff']['staff_number'];

                                if (!$customer[$k]['fp_day']) {
                                    $customer[$k]['fp_day'] = date('Y-m-d H:i:s');
                                }
                                if (!$customer[$k]['jr_day']) {
                                    $customer[$k]['jr_day'] = date('Y-m-d H:i:s');
                                }

                            }else{
                                $customer[$k]['sales_department_id']  = null;
                                $customer[$k]['is_fp']  = 2;
                                $customer[$k]['fp_staff']='';
                                $customer[$k]['fp_staff_id']=null;
                                $customer[$k]['fp_staff_number']='';
                                $customer[$k]['fp_day'] = null;
                                $customer[$k]['jr_day'] = null;
                            }

                        }else{
                            $customer[$k]['error']='请检查您的信息是否填写有误';
                            array_push($fail_array,$customer[$k]);
                            unset($customer[$k]);
                            if($k==count($excel_array)-1){
                                $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                                return false;
                            }else{
                                continue;
                            }
                        }

                        if(!empty($customer[$k]['customer_tel'])){
                            $customer[$k]['tel_staff_id']=$data['staff']['staff_id'];
                            $customer[$k]['tel_staff']=$data['staff']['staff_name'];
                            $customer[$k]['tel_time']=date('Y-m-d H:i:s',time());
                            $customer[$k]['is_first_tel']=1;
                            array_push($contact,$customer[$k]['customer_tel']);
                        }else{
                            $customer[$k]['tel_staff_id'] = null;
                            $customer[$k]['tel_staff'] = '';
                            $customer[$k]['tel_time'] = null;
                            $customer[$k]['is_first_tel'] = null;

                        }
                        if(!empty($customer[$k]['customer_wechat'])){
                            $customer[$k]['wechat_staff_id']=$data['staff']['staff_id'];
                            $customer[$k]['wechat_staff']=$data['staff']['staff_name'];
                            $customer[$k]['wechat_time']=date('Y-m-d H:i:s',time());
                            $customer[$k]['is_first_wechat']=1;
                            array_push($contact,$customer[$k]['customer_wechat']);
                        }else{
                            $customer[$k]['wechat_staff_id'] = null;
                            $customer[$k]['wechat_staff'] = '';
                            $customer[$k]['wechat_time'] = null;
                            $customer[$k]['is_first_wechat'] = null;
                        }
                        if(!empty($customer[$k]['customer_qq'])){
                            $customer[$k]['qq_staff_id']=$data['staff']['staff_id'];
                            $customer[$k]['qq_staff']=$data['staff']['staff_name'];
                            $customer[$k]['qq_time']=date('Y-m-d H:i:s',time());
                            $customer[$k]['is_first_qq']=1;
                            array_push($contact,$customer[$k]['customer_qq']);
                        }else{
                            $customer[$k]['qq_staff_id'] = null;
                            $customer[$k]['qq_staff'] = '';
                            $customer[$k]['qq_time'] = null;
                            $customer[$k]['is_first_qq']=null;
                        }

                        //$this->log('import_sync_第'.$now_xh_num.'次循环，第'.$num.'条，----文件第'.$k.'行，排重联系方式数组现在为'.json_encode($contact));

                        $customer[$k]['eid'] = replaceSpecialChar($data['eid']);
                        $customer[$k]['customer_number'] = str_shuffle(time().generate_code());
                        $customer[$k]['customer_type']= $customer[$k]['customer_type']=='转介绍'?2:1;
                        $customer[$k]['creator_day'] = date('Y-m-d H:i:s',time());

                        if(!$customer[$k]['yx_day']){
                            $customer[$k]['yx_day']=date('Y-m-d H:i:s',time());
                        }

                        if (trim(addslashes($v[$header['dj_day']]))) {
                            $customer[$k]['dj_day'] = date('Y-m-d H:i:s',strtotime(trim(addslashes($v[$header['dj_day']]))));
                        }else{
                            $customer[$k]['dj_day'] = date('Y-m-d H:i:s',time());
                        }
                        $this->log('import_sync_本次导入的data----》》》'.json_encode($v));
                        //获取时间 create_time
                        if (trim(addslashes($v[$header['create_time']]))) {
                            $customer[$k]['create_time'] = date('Y-m-d H:i:s',strtotime(trim(addslashes($v[$header['create_time']]))));
                        }else{
                            $customer[$k]['create_time'] = date('Y-m-d H:i:s',time());
                        }

                        if (!$customer[$k]['dj_staff']) {
                            $this->log('import_sync_部门--指定登记人部门id--'.$dj['department_id']);
                            $customer[$k]['dj_department_id']=$dj['department_id'];
                            $customer[$k]['dj_department_name']=$dj['department_name'];
                            $customer[$k]['dj_staff']=$data['staff']['staff_name'];
                            $customer[$k]['dj_staff_id']=$data['staff']['staff_id'];
                            $customer[$k]['dj_staff_number']=$data['staff']['staff_number'];
                            $customer[$k]['brandclass']=$data['staff']['brandclass'];
                            $customer[$k]['brandclass_id']=$data['staff']['brandclass_id'];
                            $customer[$k]['add_shop_code']=$data['staff']['add_shop_code'];
                            $customer[$k]['add_shop_name']=$data['staff']['add_shop_name'];
                        }
                        $customer[$k]['shop_name']=$data['staff']['shop_name'];
                        $customer[$k]['shop_code']=$data['staff']['shop_code'];
                        if($customer[$k]['customer_type'] == 2){
                            $customer[$k]['customer_channel_id'] = $dj['department_id'];
                            $customer[$k]['customer_channel'] = $dj['department_name'];
                            $customer[$k]['zjs_from'] = 2;//转介绍类型 :   1:老顾客转介绍;2:员工亲友转介绍
                            $this->log('import_sync_转介绍导入--'.json_encode($customer[$k]));
                        }else{
                            $customer[$k]['zjs_from'] = 0;//转介绍类型 :   1:老顾客转介绍;2:员工亲友转介绍
                        }
                        // $customer[$k]['brandclass']=$data['staff']['brandclass'];
                        // $customer[$k]['brandclass_id']=$data['staff']['brandclass_id'];
                        // $customer[$k]['add_shop_code']=$data['staff']['add_shop_code'];
                        // $customer[$k]['add_shop_name']=$data['staff']['add_shop_name'];

                        if($fileData['is_sk']==1 && !$customer[$k]['sales_staff_id']){
                            $sklist = controller("crm/Customer", "lib")->sklist($data['staff']['add_shop_code'].','.$data['staff']['shop_code'],24);
                            $rand = rand(0,count($sklist)-1);
                            $arr = $sklist[$rand];
                            if(!empty($arr)){
                                $customer[$k]['is_sk']=1;
                                $customer[$k]['sk_staff_id'] = $arr['id'];
                                $customer[$k]['sk_staff'] = $arr['staffname'];
                            }else{
                                $customer[$k]['is_sk']=2;
                                $customer[$k]['sk_staff_id'] = null;
                                $customer[$k]['sk_staff'] = null;
                            }
                        }else{
                            $customer[$k]['is_sk']=2;
                            $customer[$k]['sk_staff_id'] = null;
                            $customer[$k]['sk_staff'] = null;
                        }
                        //$this->log('import_sync_---获取客资信息over---');
                    }
                }else{
                    $this->log('import_sync_第'.$now_xh_num.'次循环，第'.$num.'条，没有联系方式----文件第'.$k.'行，excel总行数：'.count($excel_array)).'>>>'.json_encode($customer);
                    $customer[$k]['error']='没有联系方式';
                    array_push($fail_array,$customer[$k]);
                    unset($customer[$k]);
                    if($k==count($excel_array)-1){
                        $this->last_import($all_number,$customer,$fail_array,$fileData,$data,$contact);
                        return false;
                    }else{
                        continue;
                    }

                }

                if($num>=200||$k==count($excel_array)-1){

                    //$this->log('import_sync_本条数据--------->'.json_encode($customer));
                    //将costomer数组类数据进行入库
                    //将错误数组写入excel
                    //将excel_import表更新已处理和错误数量
                    $res=$this->doImport($all_number,$customer,$fail_array,$fileData,$data,$contact);
                    //doImport($customer,$fail_array,$fileData,$data,$contact);
                    if($res===false){
                        $this->log('import_sync_导入数据执行失败');
                        return false;
                    }else{
                        if($customer[$k]['customer_tel']){
                            history_log(['customer_tel'=>$customer[$k]['customer_tel']],[],$res,$customer[$k]['dj_staff_id'],$customer[$k]['dj_staff'],'crm','Customer','editCustomerTel');
                        }
                        unset ($customer,$contact);
                        cache('import_excel_'.$data['eid'],$k);
                        $num=1;
                        $this->log('import_sync_本次导入的eid----》》》'.$data['eid']);
                        if($k==count($excel_array)-1){
                            unset($all_number);
                            if(count($fail_array)>0){
                                $fail_file['fail_array']=$fail_array;
                                $fail_file['eid']=$data['eid'];
                                $fail_url=controller("crm/Customer","lib")->cusFailFile($fail_file,$this->importHeader);
                                $this->log('import_sync_最后一次导入成功后生成错误文件'.$fail_url);
                            }
                            db('c_excel_import')->where(array('id'=>$data['eid']))->update(array('status'=>1,'fail_file_url'=>$fail_url));
                            $this->log('import_sync_进统计队列之前的data====>>>'.json_encode($data));
                            $this->historyList($data);//数据统计队列
                            if($fileData['is_sk']!=1 && empty($customer[$k]['sales_staff'])){
                                $this->fpList($data);//分配队列
                            }
                        }
                    }
                    $now_xh_num++;
                    continue;
                }else{
                    $num++;
                    //unset($conditions);
                    //unset($all_id);
                }
            }
        }
    }

    /*将costomer数组类数据进行入库
     *将错误数组写入excel
     * 将excel_import表更新已处理和错误数量
     * $all_number     文件总数量
     * $customer       已处理成功数据
     * $failCustomer   过滤失败数据
     * $fileData       文件信息
     * $data           队列输入的数据
     * $contact        已处理成功数据的联系方式（一维数组）
     */

    function doImport($all_number,$customer,$failCustomer,$fileData,$data,$contact){
       // $this->log(json_encode($customer));
        /*$contactAll=array();
        $contact=array_unique($contact);
        foreach($contact as $k =>$v){
            $contactAll[$k]['contact']=$v;
            $contactAll[$k]['brandclass']=$data['staff']['brandclass'];
        }*/
        db()->startTrans();//开启事务
        try{
            if(count($customer)>0){
                $aa = db('c_customerinfo')->insertAll($customer);
                $this->log('import_sync_====执行添加====');
                //$fileData=db('c_excel_import')->where('id',$data['eid'])->find();
                //$import_number=$fileData['import_number']+count($customer);
                //通过eid查询导入的客资id,插入到排重表
                $eInfo = db('c_customerinfo')->where('eid',$data['eid'])->master()->field(('id,eid,customer_name,customer_tel,customer_wechat,customer_qq,brandclass,dj_staff_id,add_shop_code,add_shop_name,shop_code,shop_name,dj_staff,sales_staff,brandclass_id,sales_staff_id'))->order('id desc')->limit(count($customer))->select();
                foreach($eInfo as $kk=>$vv){
                    $model = db_config('is_send_sms_'.$vv['add_shop_code']);
                    $msgUser = db_config('sms_'.$vv['add_shop_code']);
                    $this->log('import_sync_====此客资是否可以发短信===='.$model);
                    if($vv['customer_tel'] && $msgUser && $model){
                        $send_msg = db('s_message_templateinfo')->where('id',$model)->value('mtemplate_content');
                        preg_match("/(?:\{)(.*)(?:\})/i",$send_msg, $name);
                        preg_match("/(?:\[)(.*)(?:\])/i",$send_msg, $sex);
                        if($vv['customer_sex'] == '男'){
                            $m = '先生';
                        }elseif($vv['customer_sex'] == '女'){
                            $m = '女士';
                        }else{
                            $m = '';
                        }
                        //字符串替换
                        $send_msg1 = str_replace($name[0],$vv['customer_name'],$send_msg);
                        $msg = str_replace($sex[0],$m,$send_msg1);
                        $this->log('import_sync_====发现短信内容===='.$msg);
                        $data1 = array(
                            'send_id' => $vv['dj_staff_id'],
                            'send_name'=>'素玄科技',
                            'send_content'=>$msg,
                            'model_id'=>$model,
                            'send_time'=>date('Y-m-d H:i:s',time()),
                            'receive_id'=>$vv['id'],
                            'receive_name'=>$vv['customer_name'],
                            'receive_phone'=>$vv['customer_tel']
                        );
                        //调用短信接口
                        $url = '5a17b86088f1a';
                        $da = array(
                            'mobile' => $vv['customer_tel'],
                            'content' =>$msg,
                            'send_config' =>$msgUser,
                        );
                        $res = sx_call($url,$da);
                        if($res['code'] == 200){
                            db('CSendMessageLog')->insert($data1);

                        }
                        $this->log('import_sync_本次短信已发送--->'.$vv['id'].'--'.$vv['customer_tel']);
                    }
                }

                $this->log('import_sync_本次导入客资--->'.json_encode($eInfo));
                $date = date('Y-m-d H:i:s');
                $contactAll=array();
                $cid = [];
                $fpLog = [];
                foreach($eInfo as $k =>$v){
                    $cid[$k]['cid'] = $v['id'];
                    //查询有无追踪人，有的话记录追踪日志
                    if($v['sales_staff_id']){
                        $fpLog[$k]['cid']              = $v['id'];
                        $fpLog[$k]['eid']              = $v['eid'];
                        $fpLog[$k]['fp_model']         = 3;
                        $fpLog[$k]['fp_status']        = 1;
                        $fpLog[$k]['fp_time']          = $date;
                        $fpLog[$k]['jr_time']          = $date;
                        $fpLog[$k]['fp_staff_id']      = $v['dj_staff_id'];
                        $fpLog[$k]['fp_staff_name']    = $v['dj_staff'];
                        $fpLog[$k]['fp_shop_code']     = $v['add_shop_code'];
                        $fpLog[$k]['fp_shop_name']     = $v['add_shop_name'];
                        $fpLog[$k]['fp_brandclass_id'] = $v['brandclass_id'];
                        $fpLog[$k]['jr_staff_id']      = $v['sales_staff_id'];
                        $fpLog[$k]['jr_staff_name']    = $v['sales_staff'];
                        $fpLog[$k]['jr_shop_code']     = $v['shop_code'];
                        $fpLog[$k]['jr_shop_name']     = $v['shop_name'];
                    }
                    $temp = [];
                    if(!empty(trim($v['customer_tel']))){
                        $temp['c_id']=$v['id'];
                        $temp['contact']=trim($v['customer_tel']);
                        $temp['brandclass']=trim($v['brandclass']);
                        $contactAll[] = $temp;
                    }
                    if(!empty(trim($v['customer_wechat']))){
                        $temp['c_id']=$v['id'];
                        $temp['contact']=trim($v['customer_wechat']);
                        $temp['brandclass']=trim($v['brandclass']);
                        $contactAll[] = $temp;
                    }
                    if(!empty(trim($v['customer_qq']))){
                        $temp['c_id']=$v['id'];
                        $temp['contact']=trim($v['customer_qq']);
                        $temp['brandclass']=trim($v['brandclass']);
                        $contactAll[] = $temp;
                    }
                }
                $arr = array_unset_tt($contactAll,'contact');
                $this->log('import_sync_====排重后数组,准备插入排重表===='.json_encode($arr));
                $contactAll = array_values($arr);
                $this->log('import_sync_====插入排重表内容===='.json_encode($contactAll));
                $res = db('c_customer_contact')->insertAll($contactAll);
                $this->log('import_sync_====插入排重表结果===='.$res);
                $this->log('import_sync_上次导入成功数'.$fileData['import_number'].'--本次导入成功-'.count($customer));
                db('c_excel_import')->where('id',$data['eid'])->setInc('import_number',count($customer));//新增成功数据量
                $this->log('import_sync_====修改成功数量sql===='.db()->getLastSql());
                db('c_excel_import')->where(array('id'=>$data['eid']))->update(array('status'=>2,'all_number'=>$all_number,'fail_number'=>count($failCustomer)));
                $this->log('import_sync_====修改全部导入数量sql===='.db()->getLastSql());
                //把cid存入from表
                db('c_customer_from')->insertAll($cid);
                //插入分配日志
                db('l_fp_logs')->insertAll($fpLog);
                //把此次导入的信息存入pool表
                $pool['msg'] = $data['eid'];
                $pool['count'] = 0;
                $pool['pool_type'] = 10;
                $pool['fp_time_out'] = time();
                $pool['create_time'] = date('Y-m-d H:i:s');
                db('c_fp_pool')->insert($pool);
            }else{
                if(count($failCustomer)>0){
                    db('c_excel_import')->where(array('id'=>$data['eid']))->update(array('status'=>2,'all_number'=>$all_number,'fail_number'=>count($failCustomer)));
                    $this->log('import_sync_====修改失败导入数量sql===='.db()->getLastSql());
                }
            }
            //db('c_excel_import')->where('id',$eid)->inc(array('import_number'=>count($customer),'fail_number'=>count($failCustomer)))->update(array('status'=>2));
            db()->commit();
            return true;
        }catch (\Exception $e){
            db()->rollback();
            db('c_excel_import')->where(array('id'=>$data['eid']))->update(array('status'=>3,'import_fail'=>count($failCustomer)));
            $this->log($e->getMessage().'===import_sync_====执行失败更新失败数量sql===='.db()->getLastSql());
            return false;
        }
    }

    /*最后一次循环入库后，生成错误文件 改变文件状态
      * $all_number     文件总数量
     * $customer       已处理成功数据
     * $fail_array   过滤失败数据
     * $fileData       文件信息
     * $data           队列输入的数据
     * $contact        已处理成功数据的联系方式（一维数组）
     */
    function last_import($all_number,$customer,$fail_array,$fileData,$data,$contact){
        $this->log("***最后一次入库方法，最后一条是错误信息时，走这里的逻辑");
        $this->log("***最后一次入库数据".json_encode($customer));
        if(empty($customer)){
            try{
                unset ($customer,$contact,$all_number);
                //cache('import_excel_'.$data['eid'],null);
                if(count($fail_array)>0){
                    $fail_file['fail_array']=$fail_array;
                    $fail_file['eid']=$fileData['id'];
                    $fail_url=controller("crm/Customer","lib")->cusFailFile($fail_file,$this->importHeader);
                }

                $this->log('import_sync_生成错误文件'.$fail_url);
                db('c_excel_import')->where(array('id'=>$fileData['id']))->update(array('status'=>1,'fail_file_url'=>$fail_url,'fail_number'=>count($fail_array)));
                $this->historyList($data);//数据统计队列
                if($fileData['is_sk']!=1){
                    $this->fpList($data);//分配队列
                }
            }catch(\Exception $e){
                $this->log("生成错误文件数据出错：".$e->getMessage()."\r\n".$e->getTraceAsString());
            }
            return false;
        }else{
            $res=$this->doImport($all_number,$customer,$fail_array,$fileData,$data,$contact);
            //unset($conditions);
            //unset($all_id);
            if($res===false){
                $this->log('import_sync_导入数据执行失败');
                return false;
            }else{
                unset ($customer,$contact,$all_number);
                //cache('import_excel_'.$data['eid'],null);
                if(count($fail_array)>0){
                    $fail_file['fail_array']=$fail_array;
                    $fail_file['eid']=$fileData['id'];
                    $fail_url=controller("crm/Customer","lib")->cusFailFile($fail_file,$this->importHeader);
                }

                $this->log('import_sync_生成错误文件'.$fail_url);
                db('c_excel_import')->where(array('id'=>$fileData['id']))->update(array('status'=>1,'fail_file_url'=>$fail_url));
                $this->historyList($data);//数据统计队列
                if($fileData['is_sk']!=1){
                    $this->fpList($data);//分配队列
                }
                return false;
            }
        }
        return false;
    }

    //分配队列
    function fpList($data){
        $sysconfig = db_config('fp_switch_'.$data['staff']['shop_code']);
        if($sysconfig==1){
            // 系统分配队列
            $this->log('import_sync_start fpCustomerList');
            $listName_fp = 'fpCustomerList';
            $message_fp['type']=2;
            $message_fp['eid']=$data['eid'];
            $message_fp['receive'] = '-1';
            $message_fp['body']    = '';
            $message_fp['staff_id']= $data['staff']['staff_id'];
            $message_fp['shop_code']= $data['staff']['shop_code'];
            $this->log('import_sync_导入的客资进入分配队列---->'.json_encode($message_fp));
            push_list($listName_fp, $message_fp);
            $this->log('import_sync_push fpcustomerlist over....');
        }
    }

    //数据统计
    function historyList($data){
        // 数据统计队列
        $listName= 'historyDataList';
        $cinfo   = [];
        $message = array(
            // 数据统计类型（1：单条；2：批量导入）
            'type'       => 2,
            // 批量导入的客资的eid
            'eid'        => $data['eid'],
            'staff_id'   => $data['staff']['staff_id'],
            'identity'   => 'record',
            'cinfo'      => $cinfo,
            'old_data'   => array(),
            'new_data'   => $data,
            'controller' => 'Customer',
            'action'     => 'addCustomer',
        );
        push_list($listName,$message);
    }
    function log($str){
       if(config('app_debug')){
            file_put_contents(LOG_PATH.date('Ym').DS."syncImport-".date('Ymd').".log",'【'.date('Y-m-d H:i:s').'】'.$str.PHP_EOL,FILE_APPEND );
       }
    }
}  
