<?php
namespace app\crm\lib;
/**
 * 草莓卷数据转档工具实列类
 * 
 */
use think\Db;

class Caomeijuan
{
	/**
	 * 草莓卷内的此客户的公司ID
	 * @var integer
	 */
	private $companyId = 4050;
	private $brandclass = '天使印象事业部';
	private $brandclassId = 1;
	private $perSqlDataNum = 200;
	private $shopCode = 'TSYX13';
	private $shopName = '网销中心';
	private $con = '';
	public function init(){
    if(!$this->con){
        $DB = [
          'type'            => 'mysql',
          'hostname'=>'127.0.0.1',
          'username'=>'root',
          'database'=>'caomeijuan_chendou',
          'password'=>'123456',
        ];
        $this->con = @Db::connect($DB) or die("无法连接业务数据库");
    }
		  
	}
	/**
	 * 检测字典类的情况。
	 */
	public function  checkDict(){
		$this->init();
		$sqlsign = 'select c.id,cd.YXLEVEL 
					 FROM hm_crm_client_info c 
					left join hm_crm_client_detail cd on cd.KZID = c.KZID 
					where c.isdel =0  and c.COMPANYID = '.$this->companyId.'
					group by cd.YXLEVEL';
		$res = $this->con->query($sqlsign);
		echo "===========草莓卷客资标记字典=============\r\n";
		foreach ($res as $val) {
			echo $val['YXLEVEL']."\t\r\n";
		}
		echo "\r\n";

		$sqlconshop = 'select c.SHOPID,cd.SHOPNAME 
					 FROM hm_crm_client_info c 
					left join hm_crm_client_detail cd on cd.KZID = c.KZID 
					where c.isdel =0 and c.COMPANYID = '.$this->companyId.'
					group by c.SHOPID';
		$res = $this->con->query($sqlconshop);
		echo "===========草莓卷意向店面字典=============\r\n";
		foreach ($res as $val) {
			echo $val['SHOPID']."\t".$val['SHOPNAME']."\t\r\n";
		}
		echo "\r\n";
		$sqlsource = 'select c.SOURCEID,cs.srcname 
					 FROM hm_crm_client_info c 
					left join hm_crm_source cs on cs.ID = c.SOURCEID
					where c.isdel =0 and c.COMPANYID = '.$this->companyId.'
					group by c.SOURCEID';
		$res = $this->con->query($sqlsource);
		echo "===========草莓卷渠道字典=============\r\n";
		foreach ($res as $val) {
			echo $val['SOURCEID']."\t".$val['srcname']."\t\r\n";
		}
		echo "\r\n";

	}
  /**
    操作步骤：
    1.把CRM表的：crm_c_customer_contract、crm_c_customerinfo、crm_c_salestrackinginfo的表结构导入转档库内
    2.把CRM表的：crm_s_channel，crm_s_tracksign表的结构和数据导入转档库内
    3.把MC表的s_staffinfo表的结构和数据导入转档库内
    执行本类的：main转档客资主数据，方法：php think runtransdata caomeijuan main
    执行本类的：translog转档客资追踪记录数据，方法：php think runtransdata caomeijuan translog
    其中3里面的main和translog两个可同时开两个窗口执行，

    所有都执完了后，再执行下面的4
    4.执行最后一个方法：over 结束方法：php think runtransdata caomeijuan over
    重复导入时，需要执行以下语句
    truncate table crm_c_customer_contact;
    truncate table crm_c_customer_main;
    truncate table crm_c_customerinfo;
    truncate table crm_c_salestrackinginfo;
     */
  public function run(){
    
    $this->init();
    $this->main();
    $this->translog();
    $this->over();
  }
  function translog(){
    $this->init();
    $sqlTrans = 'select cl.yymemo,cl.createtime,cl.staffid,c.id,c.KZNAME,c.KZID from hm_crm_invitation_log cl left join hm_crm_client_info c on c.KZID = cl.KZID '." where cl.COMPANYID = $this->companyId";
          $count = $this->con->name('hm_crm_invitation_log')->where('COMPANYID',$this->companyId)->count();
          $process = new progressTools(1,2,[$count]);
          $page = 0;
          $allPage = ceil($count/$this->perSqlDataNum);
          if($this->test){
              $allPage = 5;//正式后删除，先做5次测试。
          }
          
          $this->log("开始追踪记录数据，待处理总数量：".$count);
          $i = 0;
          while($page < $allPage){
              $page++;
              $start = ($page - 1) * $this->perSqlDataNum;
              $sqlQuery = $sqlTrans . ' limit '.$start.','.$this->perSqlDataNum;
              $resTrans = $this->con->query($sqlQuery);
              $tmpValue = [];
              foreach ($resTrans as $key => $value) {
                if(!empty($tmpValue) && count($tmpValue) != count($dataTrans)){
                    $this->log('有不匹配的数据列，前一数据列：');
                    print_r($tmpValue);
                    $this->log('当前数据列：');
                    print_r($dataTrans);
                    die;
                }else{
                    $tmpValue = $dataTrans;
                }
                $i++;
                $process->updateProgressValue(0,$i);
                $dataTrans = [];
                $dataTrans['customer_id'] = 0;
                $dataTrans['customer_name'] = $value['KZNAME'];
                $dataTrans['customer_number'] = $value['KZID'];
                $dataTrans['sales_day'] = $value['createtime']?date('Y-m-d H:i:s',$value['createtime']):null;
                $dataTrans['sales_staff_id'] = $value['staffid'];
                $dataTrans['sales_remark'] = $value['yymemo'];
                $allData[] = $dataTrans;
                unset($dataTrans);
              }
              $this->con->name('crm_c_salestrackinginfo')->insertAll($allData);
              unset($dataTrans,$allData,$sqlQuery,$sqlCustomer,$tmpValue);
          }
  }
	function main()
	{
		$this->init();
    //先清库
    
		$sql = <<<EOF
            SELECT 
            cs.typeid,
            cs.srcname 渠道名称,
            c.id,c.letterid,c.KZID,
            c.CLASSID,c.STATUSID
            ,c.CREATETIME,c.KZNAME,c.KZPHONE,c.KZWECHAT,c.KZQQ,c.SEX 性别,c.SOURCEID
            ,c.COLLECTORID 提报人ID,
            cd.COLLECTORNAME 提报人姓名,
            c.PROMOTORID 筛客人ID,
            cd.PROMOTERNAME 筛客人姓名,
            c.APPOINTORID 追踪人,
            cd.APPOINTNAME 追踪人姓名,
            cd.memo 备注,
            c.TRACETIME 追踪时间,c.APPOINTTIME 预约进店时间,c.ACTUALTIME 实际进店时间,c.UPDATETIME,c.SHOPID 意向店面ID,
            cd.SHOPNAME 意向店面,
            c.RECEPTORID 门市接待ID ,
            cd.RECEPTORNAME 门市接待,
            #c.VALIDTIME  有效时间,
            c.COMESHOPTIME 首次到店时间,c.SUCCESSTIME 成交时间,cd.AMOUNT 套系金额,cd.STAYAMOUNT 已收金额
            ,c.RECEIVETIME 接收时间,
            #cd.OLDKZID 老客资ID,
            cd.OLDKZNAME 老客姓名 ,cd.OLDKZPHONE 老客手机 ,cd.ORDERIMG 订单图片,cd.TALKIMG 聊天图片地址
            ,c.LASTPUSHTIME 最后推送时间
            ,c.ALLOTTYPE 分配类型0手动1自动

            ,cd.YXLEVEL 客资标记,cd.YSRANGE 预算,
            #cd.MARRYMEMO 婚期,
            cd.MARRYTIME 结婚日期,
            #cd.YPMEMO 预拍,cd.YPTIME 预计拍摄日期,
            cd.ADDRESS,cd.MATENAME 配偶,cd.MATEPHONE 配偶手机,cd.MATEWECHAT 配偶微信,cd.MATEQQ 配偶QQ,
            #cd.BIRTHTIME 生日,cd.IDNUM 证件号,
            cd.INVALIDCODE 无效原因编号,cd.INVALIDLABEL 无效原因, cd.INVALIDMEMO 无效原因描述,cd.KEYWORD 关键词,c.isdel
            ,cd.adaddress ,cd.adid,cd.zxstyle,
            cr.content REMARK


            FROM hm_crm_client_info c
            left join hm_crm_client_detail cd on cd.KZID = c.KZID
            left join hm_crm_source cs on cs.ID = c.SOURCEID
            left join hm_crm_client_remark cr on cr.KZID = c.KZID
            where 
            c.isdel =0 and c.COMPANYID = $this->companyId
            #and c.KZID = '432730304795e4e1225df12b57c5ee91ca1c27'
            #and  c.ID in('','305005')
            #and  c.ID in('304795')
            #and c.letterid ='66HWHZ'
            #and cs.typeid > 3
            order by c.CREATETIME desc
EOF;
      $allSign = $this->con->name('crm_s_tracksign')->select();

      $count = $this->con->name('hm_crm_client_info')->where('isdel',0)->where('COMPANYID',$this->companyId)->count();
      $address = require_once('address.php');
      $process = new progressTools(1,2,[$count]);
      $page = 0;
      $allPage = ceil($count/$this->perSqlDataNum);
      if($this->test){
          $allPage = 5;//正式后删除，先做5次测试。
      }
      $this->log("开始处理客资主数据，待处理总数量：".$count);
      $i = 0;
      while($page < $allPage){
          $page++;
          $start = ($page - 1) * $this->perSqlDataNum;
          $sqlQuery = $sql . ' limit '.$start.','.$this->perSqlDataNum;
          $res = $this->con->query($sqlQuery);
      ///////////////客资主表信息
      ///
      $allData = [];
      $tmpValue = [];
      foreach ($res as $key => $value) {
          if(!empty($tmpValue) && count($tmpValue) != count($data)){
              $this->log('有不匹配的数据列，前一数据列：');
              print_r($tmpValue);
              $this->log('当前数据列：');
              print_r($data);
              die;
          }else{
              $tmpValue = $data;
          }
          $i++;
          $process->updateProgressValue(0,$i);
          $data = [];
          //基础客资信息
          $data['id'] = $value['id'];
          $data['customer_name'] = $value['KZNAME'];
          $data['customer_number'] = $value['KZID'];
          $data['customer_sex'] = $value['性别']==1?'女':($value['性别']==9?'':'男');
          $data['customer_tel'] = trim(str_replace(array("\r\n", "\r", "\n"), "", $value['KZPHONE']));
          $data['customer_wechat'] = trim(str_replace(array("\r\n", "\r", "\n"), "", $value['KZWECHAT']));
          $data['customer_qq'] = trim(str_replace(array("\r\n", "\r", "\n"), "", $value['KZQQ']));
          $data['mate_name'] = $value['配偶'];
          //$data['mate_sex'] = $value['性别0男1女9不详']==1?'女':($value['性别0男1女9不详']==9?'':'男');//原系统内配偶性别与客资性别是一个
          $data['mate_tel'] = $value['配偶手机'];
          $data['mate_wechat'] = $value['配偶微信'];
          $data['mate_qq'] = $value['配偶qq'];

          $data['consultation_type_id'] = 1;
          $data['consultation_type'] = '婚纱照';

         // $data['introducer_number'] = $value['老客资ID'];
          $data['introducer_name'] = $value['老客姓名'];
          $data['introducer_tel'] = $value['老客手机'];

          $data['budget'] = $value['预算'];
          $data['customer_birthday'] = $value['生日']?substr($value['生日'],0,10):'';
          /*
          if($value['筛客人ID']){
            $selStaff = $this->getStaffDB($value['筛客人姓名']);
            $data['sk_staff'] = $selStaff?$selStaff['staffname']:$value['筛客人姓名'];
            $data['sk_staff_id'] = $selStaff?$selStaff['id']:$value['筛客人ID'];
          }else{
            $data['sk_staff'] = null;
            $data['sk_staff_id'] = null;
          }*/
          $data['dj_day'] = $this->timeFormat($value['CREATETIME']);
          $data['create_time'] = $this->timeFormat($value['CREATETIME']);
          $data['update_time'] = $this->timeFormat($value['UPDATETIME']);
          $data['last_trackday'] = $data['update_time'];
          // $data['creator_day'] = $this->timeFormat($value['CREATETIME']);
          $data['yx_day'] = $this->timeFormat($value['有效时间']);
          $data['order_day'] = $this->timeFormat($value['成交时间']);
          $data['yp_day'] = $this->timeFormat($value['预计拍摄日期']);


          $data['customer_remark'] = $value['REMARK']?'推广首次备注：'.$value['REMARK'].'；客资备注：'.$value['备注']:$value['备注'];
          $data['is_valid'] =  2;//默认待定状态
          $data['is_loss'] = 2;
          $data['is_fp'] = 2;
          $data['is_success'] = 2;
          if($value['isdel'] == 1){
            $data['is_status'] = 0;
            $data['del_time'] = $this->timeFormat($value['UPDATETIME']);
          }else{
            $data['is_status'] = 1;
            $data['del_time'] = NULL;
          }
          /*
          $sign = [
            1=>['id'=>33,'sign'=>'A++'],
            2=>['id'=>34,'sign'=>'A'],
            3=>['id'=>35,'sign'=>'B'],
            4=>['id'=>36,'sign'=>'C'],
            5=>['id'=>37,'sign'=>'D'],
          ];
          */
          $data['customer_intention_id'] = $data['sign_id'] = null;
          $data['customer_intention'] = $data['sign_name'] = '';
          if($allSign){
              foreach ($allSign as $sign) {
                  if($sign['tracksign'] == $value['客资标记名称']){
                      $data['customer_intention_id'] = $data['sign_id'] = $sign['id'];
                      $data['customer_intention'] = $data['sign_name'] = $sign['tracksign'];

                  }
              }
          }
          /*
          //客资标记
          $data['sign_id'] = $sign[$value['客资标记']]['id'];
          $data['sign_name'] = $sign[$value['客资标记']]['sign'];

          //意向
          $data['customer_intention_id'] = $sign[$value['客资标记']]['id'];
          $data['customer_intention'] = $sign[$value['客资标记']]['sign'];
          */
          $data['brandclass'] = $this->brandclass;
          $data['brandclass_id'] = $this->brandclassId;
          $data['is_first_tel'] = ($data['customer_tel'] || $data['mate_tel'])?1:0;
          $data['customer_key'] = $value['关键词'];
          if($value['adid']){
            $data['channel_plan_number'] = $value['adid'];
          }else{
            $data['channel_plan_number'] = '';
          }
          if($value['adaddress']){
            $data['ad_page'] = $value['adaddress'];
          }else{
            $data['ad_page'] = '';
          }
          
          
          //处理客户地区及详细地址信息
          $data['province_id'] = 0;
          $data['province'] = '';
          $data['city_id'] = 0;
          $data['city'] = '';
          $data['county_id'] = 0;
          $data['county'] = '';
          $data['customer_address'] = '';

          $add = explode(',', $value['ADDRESS']);
          if($add[0]){
            foreach ($address['1'] as $k=>$v) {
                if(strpos($k,$add[0]) !== false){
                  $data['province_id'] = $v;
                  $data['province'] = $k;
                  break;
                }
            }
          }
          
          if($add[1]){
            foreach ($address['2'] as $k=>$v) {
                if(strpos($k,$add[1]) !== false){
                  $data['city_id'] = $v;
                  $data['city'] = $k;
                  break;
                }
            }
          }
          if($add[2]){
            foreach ($address['3'] as $k=>$v) {
                if(strpos($k,$add[2]) !== false){
                  $data['county_id'] = $v;
                  $data['county'] = $k;
                  break;
                }
            }
          }
          if($add[3]){
            $data['customer_address'] = $add[3];
          }
          /*
          //意向店面
          $shopList = [
            2025=>[
                'shop_name'=>'徐汇店',
                'shop_code'=>'JZ005',
            ],
            2026=>[
                'shop_name'=>'闵行总店',
                'shop_code'=>'JZ001',
            ],
            2027=>[
                'shop_name'=>'闵行总店',
                'shop_code'=>'JZ001',
            ],
            2503=>[
                'shop_name'=>'静安旗舰店',
                'shop_code'=>'JZ002',
            ],
            3758=>[
                'shop_name'=>'闵行总店',
                'shop_code'=>'JZ001',
            ],
            
          ];*/
          if($value['意向店面ID']){
              $data['consulation_shop_code'] = $this->shopCode;//$shopList[$value['意向店面ID']]['shop_code'];
              $data['consulation_shop'] = $this->shopName;//$shopList[$value['意向店面ID']]['shop_name'];
          }else{
            $data['consulation_shop_code'] = '';
            $data['consulation_shop'] = '';
          }

          //处理客资渠道、来源、客资类型等
          $data['customer_type'] = 1;
          $data['c_from'] = 1;
          $data['customer_cource_id'] = 1;
          $data['customer_cource'] = '电商';
          $data['customer_channel_id'] = 1;
          $data['customer_channel'] = '其他';
          // $data['shop_code'] = '';
          // $data['shop_name'] = '';
          // $data['add_shop_code'] = '';
          // $data['add_shop_name'] = '';
          $data['shop_code'] = $this->shopCode;
          $data['shop_name'] = $this->shopName;
          $data['add_shop_code'] = $this->shopCode;
          $data['add_shop_name'] = $this->shopName;
          $channel = $this->getChannelList($value['渠道名称']);
          if(!$channel){
              $channel = [
                'id'=>$value['SOURCEID'],
                'channel_name'=>$value['渠道名称'],
              ];
          }
          if($value['typeid'] == 1){
            //电商的客资
            
            $data['customer_channel_id'] = $channel['id'];
            $data['customer_channel'] = $channel['channel_name'];
            $data['customer_type'] = 1;
            $data['c_from'] = 1;
            $data['customer_cource_id'] = 1;
            $data['customer_cource'] = '电商';

          }
          if($value['typeid'] == 3 || $value['typeid'] == 2){
            //转介绍客资
            $data['customer_channel_id'] = $channel['id'];//待处理。。。
            $data['customer_channel'] = $channel['channel_name'];//待处理。。。

            $data['customer_type'] = 2;
            $data['c_from'] = 1;
            $data['customer_cource_id'] = 2;
            $data['customer_cource'] = '转介绍';
            $data['access_model_id'] = 3;
            $data['access_model'] = '老客户介绍';

            $data['shop_code'] = $this->shopCode;
            $data['shop_name'] = $this->shopName;

            //$data['add_shop_code'] = 'WX001';//待处理
            //$data['add_shop_name'] = '电商中心';//待处理

          }
          if($value['typeid'] > 3 ){
            //门店自然进客客资
            $data['customer_channel_id'] = 0;//待处理。。。
            $data['customer_channel'] = '';//待处理。。。
            $data['customer_cource_id'] = 7;
            $data['customer_cource'] = '自然进店';
            $data['customer_type'] = 1;
            $data['c_from'] = 2;
          }

          if(!$data['customer_cource_id']){
            $data['customer_cource_id'] = 8;
            $data['customer_cource'] = '其他';
            $data['c_from'] = 1;
            $data['customer_type'] = 1;
          }

          if($value['zxstyle'] == 1){
            $data['access_model_id'] = 1;
            $data['access_model'] = '对话咨询';
          }
          elseif ($value['zxstyle'] == 2){
            $data['access_model_id'] = 2;
            $data['access_model'] = '报名资询';
          }
          else{
            $data['access_model_id'] = 3;
            $data['access_model'] = '表单咨询';
          }
          /*
          //客户地域
          $regionList = [
            "黄浦区"=>"1",
            "徐汇区"=>"2",
            "长宁区"=>"3",
            "静安区"=>"4",
            "普陀区"=>"5",
            "虹口区"=>"6",
            "杨浦区"=>"7",
            "闵行区"=>"8",
            "宝山区"=>"9",
            "嘉定区"=>"10",
            "松江区"=>"12",
            "金山区"=>"13",
            "青浦区"=>"14",
            "奉贤区"=>"15",
            "崇明区"=>"16",
            "浦东新区"=> "11"
            ];
          if($regionList[$data['county']]){
            $data['customer_region_id'] = $regionList[$data['county']];
            $data['customer_region'] = $data['county'];
          }else{
            $data['customer_region_id'] = 0;
            $data['customer_region'] = '';
          }
          */
          //处理客资各种状态
          $classId = intval($value['CLASSID']);
          $statusId = intval($value['STATUSID']);
          $data['is_intostore'] = 1;//未进店
          $salesStaff = $this->getStaffDB($value['追踪人姓名']);
          $data['sales_staff_id'] = $salesStaff?$salesStaff['id']:$value['追踪人'];//追踪人，待处理。。。
          $data['sales_staff'] = $salesStaff?$salesStaff['staffname']:$value['追踪人姓名'];//追踪人，待处理。。。
          if ($data['customer_type'] == 2) {
          		 $data['customer_channel_id'] = $salesStaff['department_id'];
          		 $data['customer_channel'] = $salesStaff['department_name'];
          }


          $data['sales_staff_number'] = $salesStaff?$salesStaff['staffnumber']:'';
          $data['jr_day'] = null;
          $data['c_star_day'] = null;
          if($classId == 1 && ($statusId == 0 || $statusId == 98)){
              //待定
              $data['is_valid'] =  2;
          }else if($classId == 6){
              if($statusId == 5 || $statusId == 99){
                //无效
                $data['is_valid'] =  3;
              }else if($statusId == 4){
                //驳回
                $data['is_valid'] =  4;
              }else{
                //邀约流失-算有效
                $data['is_valid'] =  1;
                $data['is_intostore'] = 4;
              }
          }else{
            //其他全算有效
            $data['is_valid'] =  1;
          }
          $data['yjd_day'] = $data['syjd_day'] =  null;
          $data['intostore_note'] = '';
          if($value['预约进店时间']){
              $data['yjd_day'] = $this->timeFormat($value['预约进店时间']);
              $data['intostore_note'] = $value['备注'];
          }
          if($value['实际进店时间']){
              $data['syjd_day'] = $this->timeFormat($value['实际进店时间']);
              $data['is_intostore'] = 2;
          }
          $data['totalpay_money'] = $value['套系金额'];
          $data['fact_money'] = $value['已收金额'];
          $data['op_signinfo'] = '';
          $data['is_next'] = 2;
          $data['next_time'] = NULL;
          $data['yjd_action_day'] = NULL;
          if($value['接收时间']){
              $data['jr_day'] = $this->timeFormat($value['接收时间']);//接收时间
              $data['is_fp'] = 1;
              $data['c_star_day'] = $this->timeFormat($value['接收时间']);
          }
          
          $data['unvalid_id'] = $value['无效原因编号'];
          $data['unvalid_reason'] = $value['无效原因'];
         
          if($value['门市接待ID']){
              $receptionStaff = $this->getStaffDB($value['门市接待']);
              $data['reception_id'] = $receptionStaff?$receptionStaff['id']:$value['门市接待ID'];//门市接待人，待处理。。。
              $data['reception_name'] = $receptionStaff?$receptionStaff['staffname']:$value['门市接待'];//门市接待人，待处理。。。
          }else{
            $data['reception_id']  =0;
            $data['reception_name'] = '';
          }

          if($classId == 4){
            #已进店
            switch ($statusId) {
                case 39:
                  //非进客进店，即无效进店
                  $data['is_intostore'] = 3;
                break;
                case 33:
                  #进店保留--定金
                case 35:
                  #回门保留--定金
                  $data['is_success'] = 3;
                break;
                case 10:
                  #进店未成交
                  $data['is_intostore'] = 5;
                  $data['is_loss'] = 1;
                case 36:
                  #回门流失--进店未成交
                  $data['is_intostore'] = 5;
                  $data['is_loss'] = 1;
                break; 
            }
          }
          if($classId == 5){
              //已成交
              $data['is_success'] = 1;
              $data['totalpay_money'] = $value['套系金额'];
              $data['fact_money'] = $value['已收金额'];
          }
          
          $djStaff = $this->getStaffDB($value['提报人姓名']);
          $data['dj_staff'] = $djStaff?$djStaff['staffname']:$value['提报人姓名'];//录入人，待处理。。。
          $data['dj_staff_id'] = $djStaff?$djStaff['id']:$value['提报人ID'];//录入人，待处理。。。
          $allData[] = $data;
          //$customerId = $this->consx->name('c_customerinfo')->insertGetId($data);
          //



        }
        #######################客资主表一次结束
        $this->con->name('crm_c_customerinfo')->insertAll($allData);
        /*
        $sqlCustomer = $this->consx->name('c_customerinfo')->fetchSql()->insertAll($allData);
        $fileName = $this->sqlPath.DS.'c_customerinfo.sql';
        file_put_contents($fileName, $sqlCustomer.";\r\n",FILE_APPEND);
        $percent = sprintf('%.2f',($i/$count) * 100);
        $this->log("客资表数据完成：".$i.'/'.$count."【{$percent}%】");
		*/
        unset($data,$allData,$sqlQuery,$sqlCustomer);
      }//总while
      unset($sql,$address);
      $this->log('更新联系方式表-手机号');
      $this->con->query('insert into crm_c_customer_contact(c_id,contact,brandclass)select id,customer_tel,\''.$this->brandclass.'\' from crm_c_customerinfo where customer_tel is not null and customer_tel != \'\'');
      $this->log('更新联系方式表-微信号');
      $this->con->query('insert into crm_c_customer_contact(c_id,contact,brandclass)select id,customer_wechat,\''.$this->brandclass.'\' from crm_c_customerinfo where customer_wechat is not null and customer_wechat != \'\'');
      $this->log('更新联系方式表-QQ号');
      $this->con->query('insert into crm_c_customer_contact(c_id,contact,brandclass)select id,customer_qq,\''.$this->brandclass.'\' from crm_c_customerinfo where customer_qq is not null and customer_qq != \'\'');
      $this->log('更新联系方式表-渠道');

      die;
	}
  /**
   * 最后收尾工作
   * @return [type] [description]
   */
  public function over(){
      $this->init();
      $this->log('插入客资主表数据');
      $sql = 'insert into crm_c_customer_main(id,wname,wphone,wwechat,mname,mphone,mwechat,c_unique) select id,customer_name,customer_tel,customer_wechat,mate_name,mate_tel,mate_wechat,UUID() from crm_c_customerinfo';
      $this->con->query($sql);
      $this->log('更新客资表c_unique');
      $sql = 'update crm_c_customerinfo c left join crm_c_customer_main m on m.id = c.id set c.c_unique = m.c_unique';
      $this->con->query($sql);

      $this->log('更新客资追踪记录表c_unique');
      $sql = 'update crm_c_salestrackinginfo t left join crm_c_customerinfo c on c.id = t.customer_id set t.c_unique = c.c_unique';
      $this->con->query($sql);

      $this->log('更新客资排重表c_unique和渠道');
      $sql = 'update crm_c_customer_contact t left join crm_c_customerinfo c on c.id = t.c_id set t.c_unique = c.c_unique,t.customer_channel = c.customer_channel';
      $this->con->query($sql);

      $this->log('更新追踪记录和客资关系表');
      $sql = 'update crm_c_salestrackinginfo t left join crm_c_customerinfo c on c.customer_number = t.customer_number set t.customer_id = c.id where c.id is not null';
      $this->con->query($sql);
  }
	public function getStaffDB($name){
      static $allStaffs;
      if(!$allStaffs){
        $res = $this->con->name('s_staffinfo')->select();
          foreach ($res as  $value) {
            $allStaffs[$value['staffname']] = $value;
          }
      }
      return $allStaffs[$name];
    }
	public function timeFormat($timestamp){
        return $timestamp?date('Y-m-d H:i:s',$timestamp):NULL;
    }
	function is_windows(){
      return strtoupper(substr(PHP_OS,0,3))==='WIN'?true:false;
    }
    function log($t){//控制台输出
      //if($this->log){
        $t=date('Y-m-d H:i:s ').$this->thisStep.'/'.$this->step.' '.$t;
        $t .= "内存占用：".$this->getSystemMemory()."\r\n";
        if($this->is_windows()){
          fwrite(STDOUT, iconv('utf-8','gbk//IGNORE',$t));
        }else{
          fwrite(STDOUT, $t);
        }
      //}
    }
    function getSystemMemory(){
        $memory = memory_get_usage();
        $res = '';
        if($memory > 1073741824){
            $tmp = floor($memory/1073741824);
            $res .= $tmp.'G';
            $memory = $memory - ($tmp * 1073741824);
        }
        if($memory > 1048576){
            $tmp = floor($memory/1048576);
            $res .= $tmp.'M';
            $memory = $memory - ($tmp * 1048576);
        }
        if($memory > 1024){
            $res .= floor($memory/1024).'K';
        }
        return $res;
    }
    function getChannelList($name){
        static $allchannel;
        if(!$allchannel){
            $allchannel = $this->con->name('crm_s_channel')->select();
        }
        foreach ($allchannel as $key => $value) {
            if($value['channel_name'] == $name){
                return $value;
            }
        }
        return false;
    }
}


class progressTools{
    private $percentStatus;
    private $numberType;
    private $total = [];
    function __construct($processNumber=1,$numberType=1,$total=[]){
        for ($i=0; $i < $processNumber; $i++) { 
            $this->percentStatus[$i] = 0;
        }
        $this->numberType = $numberType;
        $this->total = $total;
        $this->outputProgress();
    }
    function outputProgress($clear = false)
    {
        if ($clear) {
            $number = count($this->percentStatus);
            for ($i=0; $i < $number; $i++) { 
                system("tput cuu1");
                system("tput el");
            }
        }
        foreach ($this->percentStatus as $key=>$value) {
            echo $this->buildLine($value,(int)$this->total[$key]) . "\n";
        }
    }
    function updateProgressValue($k, $value) {
        $this->percentStatus[$k] = $value;
        if($this->numberType == 1){
            if ($this->percentStatus[$k] >= 100) {
                $this->percentStatus[$k] = 100;
            }
        }
        $this->outputProgress(true);
    }
    function buildLine($percent,$total=0) {
        if($total > 0 && $this->numberType == 2){
            $now = $percent;
            $percent = floor(100*$now/$total);
        }
        $percent = $percent>100?100:$percent;
        $repeatTimes = 100;
        if ($percent > 0) {
            $hasColor = str_repeat('■', $percent);
        } else {
            $hasColor = '';
        }

        if ($repeatTimes - $percent > 0) {
            $noColor  = str_repeat(' ', $repeatTimes - $percent);
        } else {
            $noColor  = '';
        }

        $buffer      = sprintf("[{$hasColor}{$noColor}]");
        if($this->numberType == 2){
            $buffer .= "[$percent%]";
            $percentString = sprintf("[%-6s]", $now.'/'.$total);
        }else{
            if ($percent !== 100) {
                $percentString = sprintf("[   %-6s]", $percent . '%');
            } else {
                $percentString = sprintf("[    %-5s]", 'OK');;
            }
        }
        return $percentString . $buffer . "\r";
    }
}