<?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('crm_c_excel_import')->where('id',$data['eid'])->find();
            $file_url=$fileData['file_url'];
        }

        if(empty($file_url)){
            $this->log('import_sync_import_sync没有获取到文件地址');
            db('crm_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('crm_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();//标准表头格式
        // }

        $title=import_header_child();//标准表头格式

        $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();//用于文件数据中排重的联系方式
        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{
                $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]['ready_baby_day'] = $v[$header['ready_baby_day']] ? date('Y-m-d',strtotime($v[$header['ready_baby_day']])) : NULL;
                $customer[$k]['customer_name']  = trim(addslashes($v[$header['customer_name']]));
                $customer[$k]['customer_tel']   = trim(addslashes($v[$header['customer_tel']]));
                $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]['mate_name']      = trim(addslashes($v[$header['mate_name']]));
                $customer[$k]['mate_tel']       = trim(addslashes($v[$header['mate_tel']]));

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

                if(empty($fileData)){
                    $fileData=db('crm_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(!$customer[$k]['customer_tel'] && !$customer[$k]['customer_wechat']){
                    $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]['baby_birthday'] && !$customer[$k]['ready_baby_day']){
                    $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_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 ($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 ($customer[$k]['ready_baby_day']) {
                    if ($customer[$k]['ready_baby_day'] == '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;
                        }
                    }
                }
                
                $lrMust = db_config('lr_must_'.$data['staff']['brandclass_id']);
                $lrMust = explode(',',trim($lrMust,','));
                if($data['staff']['shop_code'] == 'TSYX13' && !in_array('access_model',$lrMust)){
                    $lrMust[] = 'access_model';
                }
                // $this->log('import_sync_-------必选项-->>'.json_encode($lrMust));
                
                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_tel']||$customer[$k]['mate_wechat']||$customer[$k]['mate_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(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]['mate_tel'])){
                        if(!preg_match("/^1[3|4|5|6|7|8|9][0-9]{9}$/", $customer[$k]['mate_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]['mate_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]['mate_wechat'])){
                        if(in_array($customer[$k]['mate_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;
                            }
                        }
                    }
                    // 组织结构
                    $orz = [
                        'add_shop_code'=> $data['staff']['add_shop_code'],
                        'shop_code'    => $data['staff']['shop_code'],
                    ];
                    // 联系方式
                    $con = [
                        'customer_tel'   => $customer[$k]['customer_tel'],
                        'customer_wechat'=> $customer[$k]['customer_wechat'],
                        'mate_tel'       => $customer[$k]['mate_tel'],
                        'mate_wechat'    => $customer[$k]['mate_wechat'],
                        'customer_qq'    => $customer[$k]['customer_qq'],
                        'consultation_type_id'    => $customer[$k]['consultation_type_id'],
                    ];
                    // 其他排重条件
                    $other = [
                        'channel' => $customer[$k]['customer_channel'],
                    ];
                    $arr = controller('crm/Customer','lib')->isRepeat($orz,$con,$other,0);
                    unset($orz,$con,$other);
                    // $orz['add_shop_code'] = $data['staff']['add_shop_code'];
                    // $orz['shop_code'] = $data['staff']['shop_code'];
                    // $arr=controller('crm/Customer','lib')->isRepeat($data['staff']['brandclass'],$customer[$k]['customer_tel'],$customer[$k]['customer_wechat'],'',$customer[$k]['mate_tel'],0,$customer[$k]['mate_wechat'],$customer[$k]['customer_channel'],$orz);
                    

                    // $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']['mate_tel'] == $customer[$k]['mate_tel']){
                            $customer[$k]['error']='系统内已存在此父亲手机';
                        }elseif($arr['data']['mate_wechat'] == $customer[$k]['mate_wechat']){
                            $customer[$k]['error']='系统内已存在此父亲微信';
                        }else{
                            $customer[$k]['error']='系统内已存在此客资';
                        }
                        array_push($fail_array,$customer[$k]);
                        dealMain($arr['c_unique'],$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'];

                            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]['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]['mete_tel'])){
                            array_push($contact,$customer[$k]['mete_tel']);
                        }

                        if(!empty($customer[$k]['mate_wechat'])){
                            array_push($contact,$customer[$k]['mate_wechat']);
                        }

                        //$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());
                        $customer[$k]['create_time'] = 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 (!$customer[$k]['dj_day']) {
                            $customer[$k]['dj_day'] = date('Y-m-d H:i:s',time());
                        }

                        $dj = getStaffInfoById($data['staff']['staff_id']);
                        if (!$customer[$k]['dj_staff']) {
                            $this->log('import_sync_部门--指定登记人部门id--'.$dj['department_id']);
                            $customer[$k]['dj_department_id']=$dj['department_id'];
                            $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('crm_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){
                foreach ($customer as $key => $value) {
                    $mainRes = dealMain('', $value);
                    if ($mainRes['code'] == 200) {
                        $customer[$key]['c_unique'] = $mainRes['c_unique'];
                    }else{
                        $customer[$k]['error'] = '生成客户信息失败'.$mainRes['err'];
                        array_push($fail_array,$customer[$k]);
                        unset($customer[$key]);
                    }
                }
                // var_dump($customer);exit;
                $aa = db('crm_c_customerinfo')->insertAll($customer);
                $this->log('import_sync_====执行添加====');
                //$fileData=db('crm_c_excel_import')->where('id',$data['eid'])->find();
                //$import_number=$fileData['import_number']+count($customer);
                //通过eid查询导入的客资id,插入到排重表
                $eInfo = db('crm_c_customerinfo')->where('eid',$data['eid'])->master()->field('id,eid,c_unique,baby_name,baby_sex,baby_birthday,ready_baby_day,customer_name,customer_tel,customer_wechat,mate_name,mate_tel,customer_channel,consultation_type,customer_cource,consulation_shop,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){
                    // 记录一次获取日志
                    $logStr = '新增一次获取。宝宝姓名：'.$vv['baby_name'].'；宝宝性别：'.$vv['baby_sex'].'；宝宝生日：'.$vv['baby_birthday'].'；预产期：'.$vv['ready_baby_day'].'；妈妈姓名：'.$vv['customer_name'].'；妈妈电话：'.$vv['customer_tel'].'；妈妈微信：'.$vv['customer_wechat'].'；爸爸姓名：'.$vv['mate_name'].'；爸爸手机：'.$vv['mate_tel'].'；渠道名称：'.$vv['customer_channel'].'；消费类型：'.$vv['consultation_type'].'；客户来源：'.$vv['customer_cource'].'；意向店面：'.$vv['consulation_shop'].'；登记人：'.$vv['dj_staff'].'；追踪人：'.$vv['sales_staff'].'；录入店面：'.$vv['add_shop_name'].'；归属店面：'.$vv['shop_name'].'；';
                    history_log($logStr,$vv,$vv['id'],$vv['dj_staff_id'],$vv['dj_staff'],'crm','Customer','excelImportSync');

                    $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('crm_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('crm_c_send_message_log')->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['c_unique']        = trim($v['c_unique']);
                        $temp['customer_channel']= trim($v['customer_channel']);
                        $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['c_unique']        = trim($v['c_unique']);
                        $temp['customer_channel']= trim($v['customer_channel']);
                        $temp['contact']         =trim($v['customer_wechat']);
                        $temp['brandclass']      =trim($v['brandclass']);
                        $contactAll[] = $temp;
                    }
                    if(!empty(trim($v['mate_tel']))){
                        $temp['c_id']            =$v['id'];
                        $temp['c_unique']        = trim($v['c_unique']);
                        $temp['customer_channel']= trim($v['customer_channel']);
                        $temp['contact']         =trim($v['mate_tel']);
                        $temp['brandclass']      =trim($v['brandclass']);
                        $contactAll[] = $temp;
                    }
                    if(!empty(trim($v['mate_wechat']))){
                        $temp['c_id']            = $v['id'];
                        $temp['c_unique']        = trim($v['c_unique']);
                        $temp['customer_channel']= trim($v['customer_channel']);
                        $temp['contact']         = trim($v['mate_wechat']);
                        $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('crm_c_customer_contact')->insertAll($contactAll);
                // $this->log('import_sync_====插入排重表结果===='.$res);
                // $this->log('import_sync_上次导入成功数'.$fileData['import_number'].'--本次导入成功-'.count($customer));
                db('crm_c_excel_import')->where('id',$data['eid'])->setInc('import_number',count($customer));//新增成功数据量
                // $this->log('import_sync_====修改成功数量sql===='.db()->getLastSql());
                db('crm_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('crm_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('crm_c_fp_pool')->insert($pool);
            }else{
                if(count($failCustomer)>0){
                    db('crm_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('crm_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('crm_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('crm_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('crm_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 );
       }
    }
}  
