<?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\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Repair extends Command{

    protected function configure()
    {
        $this->setName('repair')->setDescription('Suxuan system service: Repair ');
        $this->addArgument('method');
    }
    
    protected function execute(Input $input, Output $output)
    {
        if($input->getArgument('method')){
            //指定执行某个方法，未来要增加方法，不需要再指定method，直接运行时，输入函数名即可
            $method = $input->getArgument('method');
            if(!method_exists($this, $method)){
                throw new \Exception("方法：".$method."不存在，请重试。", 1);
                die;
            }else{
                $this->$method();
            }
        }else{
            throw new \Exception("请在命令行后面输入要执行的修复方法，如：php think repair test", 1);
            die;
        }

    }
    public function test(){
        echo '当前是测试方法，请增加对应具体实现方法，并更改调用的命令。'."\r\n";
        echo '演示个进度条效果：'."\r\n";
        $a = new progressTools(1,2,[134]);
        $total = 0;
        while (1==1) {
            $num = rand(0,10);
            $total +=  $num;
            $total = $total>134?134:$total;
            $a->updateProgressValue(0,$total);
            sleep(1);
            if($total == 134) break;
        }
        $total = 0;
        $b = new progressTools(1);
        while (1==1) {
            $num = rand(0,10);
            $total +=  $num;
            $total = $total>134?134:$total;
            $percent = sprintf("%.2d",100*$total/134);
            $b->updateProgressValue(0,$percent);
            sleep(1);
            if($total == 134) break;
        }
        $c = new progressTools(3);
        $aa = $bb = $cc = 0;
        while (1==1) {
            $numa = rand(0,10);
            $aa +=  $numa;
            $numb = rand(0,10);
            $bb +=  $numb;
            $numc = rand(0,10);
            $cc +=  $numc;
            $aa = $aa>134?134:$aa;
            $bb = $bb>134?134:$bb;
            $cc = $cc>134?134:$cc;
            $paa = sprintf("%.2d",100*$aa/134);
            $pbb = sprintf("%.2d",100*$bb/134);
            $pcc = sprintf("%.2d",100*$cc/134);
            $c->updateProgressValue(0,$paa);
            $c->updateProgressValue(1,$pbb);
            $c->updateProgressValue(2,$pcc);
            sleep(1);
            if($aa == 134 && $bb == 134 && $cc == 134) break;
        }
    }
    /**
     * 修复客资表客资编号重复问题，执行完此程序后，会把所有客资表客资编号重复的客资拉到临时表：crm_c_customerinfo_prepar
     * 字段为：cid old_number new_number orderid
     * 然后自动生成不重复的new_number 再从订单表内抓取订单，当订单的shop_code 网销门市，手机号全相同时，与当前客资匹配
     * 如果没匹配上，会把此old_number下的所有未区配上的订单，写入日志：log/repair.log的最后。需手动处理。
     * 本方法执行完成后，除了未匹配上的订单需要手动处理外，还需要执行以下语句，正式修复：
    ---- 修复客资表：
    update 
    crm_c_customerinfo_prepar p 
    left join crm_c_customerinfo c on c.id = p.cid
    set c.customer_number= p.new_number
    --修复订单表：
    update 
    crm_c_customerinfo_prepar p 
    left join c_customerorder o on find_in_set(o.orderId , p.orderid)
    set o.crm_customer_number = p.new_number
    where p.orderid is not null 
    建议晚上执行。
     *
     * 
     * @return [type] [description]
     */
    public function rebuidCustomerNumber(){
        echo "````````````````````````````````````````\r\n";
        echo '`开始修复客资表客资编号重复数据'."\r\n";
        echo "````````````````````````````````````````\r\n";
        echo "是否继续？输入y或yes继续，其它键退出。";
        $str = trim(trim(fgets(STDIN),"\n"),"\r");
        if(strtolower($str) != 'y' && strtolower($str) != 'yes'){
            echo "........再见.......\r\n";
            die;
        }
        echo "检查临时表\r\n";
        try{
            // var_dump($this->tableExist('crm_c_customerinfo_prepar'));
            if(!$this->tableExist('crm_c_customerinfo_prepar')){
                echo "未检测到临时表，开始创建临时表\r\n";
                $sql = '
                    CREATE TABLE `crm_c_customerinfo_prepar` (
                      `cid` int(11) DEFAULT NULL,
                      `old_number` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
                      `new_number` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
                      `orderid` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL
                    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
                ';
                db()->execute($sql);
                echo "创建临时表完成\r\n";
            }
            ///*
            echo "临时表导入数据中...\r\n";
            $sql0 = 'TRUNCATE TABLE crm_c_customerinfo_prepar';
            db()->execute($sql0);
            $sql1 = 'insert  into crm_c_customerinfo_prepar (cid,old_number)
            select c.id,c.customer_number from (
                select 
                count(*) cnt,customer_number
                from crm_c_customerinfo 
                where customer_number is not null
                group by customer_number
                having cnt >1
            ) a left join crm_c_customerinfo  c on c.customer_number = a.customer_number
            ';
            db()->execute($sql1);
            //*/
            $count = db('crm_c_customerinfo_prepar p')
                        ->where('p.new_number is null')
                         ->count();
            echo "临时表导入数据完成,待处理数量：$count \r\n";
            $allNumber = [];
            $allOrder = [];
            $progress = new progressTools(1,2,[$count]);
            $doing = 0;
            $this->log('开始修复',true);
            while (1==1) {
                $list = db('crm_c_customerinfo_prepar p')
                        ->join('crm_c_customerinfo c','c.id = p.cid')
                        ->field('p.*,c.id,c.shop_code,c.sales_staff,c.customer_tel,c.dj_day,c.c_unique')
                        ->where('p.new_number is null')
                        ->limit(100)
                        ->select();
                if(empty($list)){
                    break;
                }
                $this->log('获取列表：'.db()->getLastSql());
                //生成编号
                
                $newData = [];
                foreach ($list as $key => $value) {
                    $this->log('100条开始执行');
                    $dj_day = date('Y-m-d',strtotime($value['dj_day']));
                    if(!$allNumber[$dj_day]){
                        $allNumber[$dj_day] = db('crm_c_customerinfo')->where('dj_day','like',"$dj_day%")->where('c_from',1)->order(' customer_number desc')->column('customer_number');
                        $this->log('查询'.$dj_day.'当前所有客资编号：'.db()->getLastSql());
                    }
                    $index = (int)substr($allNumber[$dj_day][0], -6);
                    $new_number = date('Ymd',strtotime($value['dj_day'])).sprintf('%06s', ++$index);
                    $i = 0;
                    while (in_array($new_number, $allNumber[$dj_day])) {
                        $i++;
                        $new_number = date('Ymd',strtotime($value['dj_day'])).sprintf('%06s', ++$index);
                        if($i > 3000){
                            throw new Exception("生成新编号出错：".$dj_day, 1);
                            die;
                        }
                    }
                    array_unshift($allNumber[$dj_day],$new_number);
                    // $allNumber[$dj_day][] = $new_number;
                    $newData['new_number'] = $new_number;
                    $this->log('开始匹配订单：');
                    if(!array_key_exists($value['old_number'], $allOrder)){
                        $allOrder[$value['old_number']] = db('c_customerorder o')
                                                        ->field('o.orderId,o.crm_c_unique,o.shop_code,o.storeconsuitant2,i.wphone')
                                                        ->join('c_customerinfo i','i.customerid = o.customerid','left')
                                                        ->where('crm_customer_number',$value['old_number'])
                                                        ->select();
                        $this->log('查询编号：'.$value['old_number'].'的所有订单：'.db()->getLastSql());
                    }
                    foreach ($allOrder[$value['old_number']] as $korder=>$order) {
                        if(
                            // $order['shop_code'] == trim($value['shop_code']) 
                            $order['crm_c_unique'] == trim($value['c_unique']) 
                           // && trim($order['storeconsuitant2']) == trim($value['sales_staff'])
                            && trim($order['wphone']) == trim($value['customer_tel'])
                        ){
                            $this->log('批配到了订单：'.$order['orderId'].';客资编号：'.$value['old_number']);
                            $newData['orderid'][] = $order['orderId'];
                            unset($allOrder[$value['old_number']][$korder]);
                            //break;
                        }
                    }
                    if(!empty($newData['orderid'])){
                        $newData['orderid'] = implode(',',$newData['orderid']);
                    }
                    $this->log('开始更新临时表数据');
                    db('crm_c_customerinfo_prepar')->where('cid',$value['cid'])->update($newData);
                    unset($newData);
                    $this->log('临时表数据更新完成。'.db()->getLastSql());
                    $doing++;
                    // $percent = floor(100*$doing/$count);
                    // $progress->updateProgressValue(0,$percent);
                    $progress->updateProgressValue(0,$doing);
                }
            }
            $this->log('数据全部处理完毕，统计未配匹到订单：');
            $logorder = "";
            foreach ($allOrder as $key => $value) {
                foreach ($value as $order) {
                    $logorder .= $key."\t".$order['orderId']."\r\n";
                }
            }
            if($logorder){
                $this->log("\r\n".$logorder);
            }
        }catch(\Exception $e){
            echo "操作异常报错：".$e->getMessage()."\r\n";
            echo ".......修复终止......\r\n";
            die;
        }
        echo ".......全部执行完毕......\r\n";

    }
    public function tableExist($table){
        $sql = "show tables;";
        $res = db()->master()->query($sql);
        foreach($res as $value){
            if(array_search($table, $value)){
                return true;
            }
        }
        return false;
    }
    public function log($value='',$clean = false)
    {
        if($clean) file_put_contents(ROOT_PATH.'/runtime/log/repair.log','');
        file_put_contents(ROOT_PATH.'/runtime/log/repair.log',microtime(true).'>--<'. $value.PHP_EOL, FILE_APPEND);
    }
    
    // 重写
    public function shiftFiels(){
        $this->log(date('Y-m-d H:i:s').'：开始......');
        // 我的签名
        // $sign = input('get.sign');
        // if ($sign != 'ericLee') {
        //     echo 'sign error';
        //     exit;
        // }
        $insertStr = "INSERT INTO `temp_order` (`customer_id`,`order_valid`,`earnest_money`,`order_fact`,`two_pin_fact`,`customer_name`,`order_sn`,`order_type`,`consultation_type`,`customer_orderaddress`,`order_amount`,`two_pin_amount`,`order_note`,`create_time`,`target_time`,`shop_code`,`shop_name`,`brandclass`,`brandclass_id`,`is_success`,`order_start_time`,`order_day`,`fact_money`,`totalpay_money`,`order_number`) VALUES ";
        file_put_contents(ROOT_PATH.'/runtime/log/insertStr.log', $insertStr, FILE_APPEND);
        
        $insertDetailStr = "INSERT INTO `temp_detail` (`order_sn`,`pay_time`,`order_fact`,`pay_type`) VALUES ";
        file_put_contents(ROOT_PATH.'/runtime/log/insertDetailStr.log', $insertDetailStr, FILE_APPEND);
        

        $brandclass = '时尚经典事业部';
        // ignore_user_abort(); // 后台运行
        set_time_limit(0);      // 取消脚本运行时间的超时上限
        $tCInfo = db('crm_t_c_info');
        $all = $tCInfo->where('is_deal', '0')->limit(500)->select();
        $count = count($all);
        if (!$all) {
            $this->log('全部处理完毕');
            exit;
        }
        // 批量执行明细表数组
        $inDetail = [];
        // var_dump($count);
        // exit;
        while($count>0) {
            $this->log(date('Y-m-d H:i:s').'：本次循环，一共('.count($all).')条');
            foreach ($all as $key => $value) {

                $this->log(date('Y-m-d H:i:s').'：本次循环，第('.$key.')条');
                // 联系方式数组
                $contact = [];
                // 如果女手机号 或者 男手机号存在
                if ($value['wphone'] || $value['mphone']) {
                    if ($value['wphone']) {
                        array_push($contact,$value['wphone']);
                    }
                    if ($value['mphone']) {
                        array_push($contact,$value['mphone']);
                    }

                    $tContact = db('crm_temp_contact');
                    $double = $tContact->where('brandclass', $brandclass)
                        ->where('contact', 'in', $contact)
                        ->group('c_id')
                        ->field('c_id')
                        ->select();
                    $tInfo = db('crm_temp_info');
                    if(count($double) > 1){
                        $tCInfo->where('id', $value['id'])->update(['is_deal'=>json_encode($double)]);
                        continue;
                    }elseif (count($double) == 1) {
                        $cid = $double[0]['c_id'];
                        $tInfo = db('crm_temp_info');

                        $existId = $tInfo->where('is_status', 1)
                            ->where('brandclass_id', $value['brandclass_id'])
                            ->where('id', $cid)
                            ->field('id,customer_number,order_start_time')
                            ->find();

                        if (!$existId) {
                            $existId = 0;
                        }
                    }else{
                        $existId = 0;
                    }
                    unset($double);
                }
                // 如果两个都不存在，更新状态，跳出本次循环
                else{
                    $tCInfo->where('id', $value['id'])->update(['is_deal'=>'x']);
                    continue;
                }
                // 处理 订单明细
                $tODetail = db('crm_t_o_detail');
                $orderDetail = $tODetail->where('order_sn', $value['order_sn'])->field('pay_time,pay_money,type')->select();
                unset($tODetail);
                $order_fact = 0;
                $two_pin_fact = 0;
                $pay_time = 0;
                foreach ($orderDetail as $k => $v) {
                    $detail = [
                        'order_sn'  => "'".$value['order_sn']."'",
                        'pay_time'  => $v['pay_time'] ? "'".date('Y-m-d', strtotime($v['pay_time']))."'" : 'null',
                        'order_fact'=> $v['pay_money'],
                        'pay_type'  => $v['type'],
                    ];
                    $inDetailStr[] = "(".implode(',',$detail).")";

                    // 计算一销收款 
                    if ($v['type'] == 1) {
                        $order_fact += $v['pay_money'];
                        // 当收款大于订单总额的 30% 订单有效  除了旅拍 （旅拍的有效标准是 实收 1000）
                        if ($value['order_amount'] * 0.3 <= $order_fact) {
                        // if ($order_fact >= 1000) {
                            $is_success = 1;
                            $order_valid = 2;
                            $earnest_money = 0;
                            
                            if (!$pay_time) {
                                $pay_time = $v['pay_time'];
                            }
                        }
                        // 订单无效
                        else{
                            $is_success    = 3;
                            $order_valid   = 1;
                            $earnest_money = $order_fact;
                            $order_fact    = 0;
                        }
                    }
                    // 计算二销收款
                    else if ($v['type'] == 2) {
                        $two_pin_fact += $v['pay_money'];
                    }
                }

                // $this->log(date('Y-m-d H:i:s').'：处理订单明细');
                unset($orderDetail);
                // $this->log(date('Y-m-d H:i:s').'：准备处理客资');
                // 如果两个都不存在 
                if ($existId === 0) {
                    $this->log(date('Y-m-d H:i:s').'：录入新客资-->');
                    if ($value['wphone']) {
                        $cUpData['customer_tel']    = $value['wphone'];
                        $cUpData['customer_name']   = $value['wname'];
                        $cUpData['customer_wechat'] = $value['wwechat'];
                        $cUpData['customer_sex']    = '女';
                        $cUpData['mate_name']       = $value['mname'];
                        $cUpData['mate_tel']        = $value['mphone'];
                        $cUpData['mate_wechat']     = $value['mwechat'];
                        $cUpData['mate_sex']        = '男';
                    }else{
                        $cUpData['customer_tel']    = $value['mphone'];
                        $cUpData['customer_name']   = $value['mname'];
                        $cUpData['customer_wechat'] = $value['mwechat'];
                        $cUpData['customer_sex']    = '男';
                        $cUpData['mate_name']       = $value['wname'];
                        $cUpData['mate_tel']        = $value['wphone'];
                        $cUpData['mate_wechat']     = $value['wwechat'];
                        $cUpData['mate_sex']        = '女';
                    }
                    // 客资表中 关于订单的字段 
                    $cUpData['is_success']        = $is_success;
                    $cUpData['order_start_time']  = $value['target_time'] ? date('Y-m-d H:i:s', strtotime($value['target_time'])) : null;
                    $cUpData['order_day']         = $pay_time ? date('Y-m-d H:i:s', strtotime($pay_time)) : null;
                    $cUpData['order_type']        = 2;
                    $cUpData['fact_money']        = $order_fact+$two_pin_fact;
                    $cUpData['totalpay_money']    = $value['order_amount']+$value['two_pin_amount'];
                    $cUpData['order_number']      = $value['order_sn'];

                    // 客资基本信息
                    $customer_number = str_shuffle(strtotime($value['target_time']).generate_code());
                    $cUpData['customer_number']   = $customer_number;
                    $cUpData['dj_staff']          = $value['staff_name'];
                    $cUpData['dj_day']            = $value['target_time'] ? date('Y-m-d H:i:s', strtotime($value['target_time'])) : null;
                    $cUpData['create_time']       = $value['target_time'] ? date('Y-m-d H:i:s', strtotime($value['target_time'])) : null;
                    $cUpData['consultation_type'] = $value['consultation_type'];
                    $cUpData['customer_cource']   = $value['customer_cource'];
                    $cUpData['customer_area']     = $value['customer_area'];
                    $cUpData['marry_day']         = $value['marry_day'] ? date('Y-m-d H:i:s',strtotime($value['marry_day'])) : null;
                    $cUpData['baby_birthday']     = $value['baby_birthday'] ? date('Y-m-d H:i:s',strtotime($value['baby_birthday'])) : null;
                    $cUpData['shop_code']         = $value['shop_code'];
                    $cUpData['shop_name']         = $value['shop_name'];
                    $cUpData['brandclass_id']     = $value['brandclass_id'];
                    $cUpData['brandclass']        = $brandclass;
                    $cUpData['is_status']         = 1;
                    $cUpData['c_from']            = 2;
                    
                    $cid = $tInfo->insertGetId($cUpData);
                    
                    // 联系方式，插入联系方式表
                    $contact=array_unique($contact);
                    $contactList = [];
                    foreach ($contact as $k => $v) {
                        $contactList[$k]['c_id']       = $cid;
                        $contactList[$k]['contact']    = $v;
                        $contactList[$k]['brandclass'] = $brandclass;
                    }

                    $tContact->insertAll($contactList);

                    unset($contact);
                    unset($contactList);

                    // 更新t_c_info 数据
                    $tUpData['is_deal'] = 1;
                    $tUpData['customer_number'] = $customer_number;
                }else{
                    $cid = $existId['id'];
                    $customer_number = $existId['customer_number'];

                    // 更新t_c_info 数据
                    $tUpData['is_deal'] = json_encode($cid);
                    $tUpData['customer_number'] = $customer_number;
                }

                // 准备写入订单表的数据
                $oData = [
                    'customer_id'          => $cid,
                    'order_valid'          => $order_valid ? $order_valid : 1,
                    'earnest_money'        => $earnest_money ? $earnest_money : 0,
                    'order_fact'           => $order_fact ? $order_fact : 0,
                    'two_pin_fact'         => $two_pin_fact ? $two_pin_fact : 0,
                    'customer_name'        => $value['wname'] ? "'".$value['wname']."'" : "'".$value['mname']."'",
                    'order_sn'             => "'".$value['order_sn']."'",
                    'order_type'           => 2,
                    'consultation_type'    => "'".$value['consultation_type']."'",
                    'customer_orderaddress'=> "'".$value['customer_orderaddress']."'",
                    'order_amount'         => $value['order_amount'],
                    'two_pin_amount'       => $value['two_pin_amount'],
                    'order_note'           => "'".$value['order_note']."'",
                    'create_time'          => $value['create_time'] ? "'".date('Y-m-d H:i:s', strtotime($value['create_time']))."'" : 'null',
                    'target_time'          => $value['target_time'] ? "'".date('Y-m-d H:i:s', strtotime($value['target_time']))."'" : 'null',
                    'shop_code'            => "'".$value['shop_code']."'",
                    'shop_name'            => "'".$value['shop_name']."'",
                    'brandclass'           => "'".$brandclass."'",
                    'brandclass_id'        => $value['brandclass_id'],
                    'is_success'           => $is_success ? $is_success : 2,
                    'order_start_time'     => $value['target_time'] ? "'".date('Y-m-d H:i:s', strtotime($value['target_time']))."'" : 'null',
                    'order_day'            => $pay_time ? "'".date('Y-m-d H:i:s', strtotime($pay_time))."'" : 'null',
                    'fact_money'           => $order_fact+$two_pin_fact+$earnest_money,
                    'totalpay_money'       => $value['order_amount']+$value['two_pin_amount'],
                    'order_number'         => "'".$value['order_sn']."'",
                ];
                $str = "(".implode(',',$oData).")";
                $inOrderStr[] = $str;

                $tCInfo->where('id', $value['id'])->update($tUpData);

                unset($oData);
                unset($tUpData);
            }
            // 订单insert语句
            file_put_contents(ROOT_PATH.'/runtime/log/insertStr.log', implode(',', $inOrderStr).';'.PHP_EOL.$insertStr, FILE_APPEND);
            file_put_contents(ROOT_PATH.'/runtime/log/insertDetailStr.log', implode(',', $inDetailStr).';'.PHP_EOL.$insertDetailStr, FILE_APPEND);
            unset($inOrderStr);
            unset($inDetailStr);
            unset($all);
            // unset($tCInfo);
            // unset($tContact);
            // unset($tInfo);
            $this->log(date('Y-m-d H:i:s').'：处理完一批，然后开始处理下一次循环。');
            $all = db('crm_t_c_info')->where('is_deal', '0')->limit(1000)->select();
            $count = count($all);
        }
    }

    // 重写
    // public function shiftFiels(){
    //     // file_put_contents(ROOT_PATH.'/runtime/log/repair.log', date('Y-m-d H:i:s').'：开始......'.PHP_EOL, FILE_APPEND);
    //     $this->log(date('Y-m-d H:i:s').'：开始......');
    //     // 我的签名
    //     // $sign = input('get.sign');
    //     // if ($sign != 'ericLee') {
    //     //     echo 'sign error';
    //     //     exit;
    //     // }
    //     $brandclass = '时尚经典事业部';
    //     // ignore_user_abort(); // 后台运行
    //     set_time_limit(0);      // 取消脚本运行时间的超时上限
    //     $all = db('t_c_info')->where('is_deal', '0')->limit(5)->select();

    //     if (!$all) {
    //         $this->log('全部处理完毕');
    //         exit;
    //     }
    //     // 批量执行明细表数组
    //     $inDetail = [];

    //     $this->log(date('Y-m-d H:i:s').'：本次循环，一共('.count($all).')条');
    //     foreach ($all as $key => $value) {
    //         $this->log(date('Y-m-d H:i:s').'：本次循环，第('.$key.')条');
    //         // 联系方式数组
    //         $contact = [];
    //         // 如果女手机号 或者 男手机号存在
    //         if ($value['wphone'] || $value['mphone']) {
    //             if ($value['wphone']) {
    //                 array_push($contact,$value['wphone']);
    //             }
    //             if ($value['mphone']) {
    //                 array_push($contact,$value['mphone']);
    //             }
                
    //             $double = db('temp_contact')
    //                 ->where('brandclass', $brandclass)
    //                 ->where('contact', 'in', $contact)
    //                 ->group('c_id')
    //                 ->field('c_id')
    //                 ->select();
    //             $this->log(date('Y-m-d H:i:s').'：查询判重1.1-->'.db()->getLastSql());
    //             $this->log(date('Y-m-d H:i:s').'：查询判重1.2-->'.json_encode($double));

    //             if(count($double) > 1){
    //                 $this->log(date('Y-m-d H:i:s').'：两个以上');
    //                 db('t_c_info')->where('id', $value['id'])->update(['is_deal'=>json_encode($double)]);
    //                 continue;
    //             }elseif (count($double) == 1) {
    //                 $cid = $double[0]['c_id'];
    //                 $existId = db('temp_info')
    //                     ->where('is_status', 1)
    //                     ->where('brandclass_id', $value['brandclass_id'])
    //                     ->where('id', $cid)
    //                     ->field('id,customer_number,order_start_time')
    //                     ->find();
    //                 $this->log(date('Y-m-d H:i:s').'：查询客资1.1-->'.db()->getLastSql());
    //                 $this->log(date('Y-m-d H:i:s').'：查询客资1.2-->'.json_encode($existId));
    //                 if (!$existId) {
    //                     $existId = 0;
    //                 }
    //             }else{
    //                 $existId = 0;
    //                 $this->log(date('Y-m-d H:i:s').'：查询判重2，没有重复客资');
    //             }
    //             unset($double);
    //             // $this->log(date('Y-m-d H:i:s').'：查询判重2->'.json_encode($existId));
    //         }
    //         // exit;
    //         // 如果两个都不存在，更新状态，跳出本次循环
    //         else{
    //             db('t_c_info')->where('id', $value['id'])->update(['is_deal'=>'x']);
    //             $this->log(date('Y-m-d H:i:s').'：男女手机号都不存在，不处理，跳到下一条');
    //             // file_put_contents(ROOT_PATH.'/runtime/log/repair.log', date('Y-m-d H:i:s').'男女手机号都不存在，不处理，跳到下一条'.PHP_EOL, FILE_APPEND);
    //             continue;
    //         }
    //         // 处理 订单明细
    //         $orderDetail = db('t_o_detail')->where('order_sn', $value['order_sn'])->field('pay_time,pay_money,type')->select();
    //         $this->log(date('Y-m-d H:i:s').'：查询订单明细');
    //         $order_fact = 0;
    //         $two_pin_fact = 0;
    //         $pay_time = 0;
    //         foreach ($orderDetail as $k => $v) {
    //             $detail = [
    //                 'order_sn'  => $value['order_sn'],
    //                 'pay_time'  => $v['pay_time'] ? date('Y-m-d', strtotime($v['pay_time'])) : null,
    //                 'order_fact'=> $v['pay_money'],
    //                 'pay_type'  => $v['type'],
    //             ];
    //             $inDetail[] = $detail;
    //             // 计算一销收款 
    //             if ($v['type'] == 1) {
    //                 $order_fact += $v['pay_money'];
    //                 // 当收款大于订单总额的 30% 订单有效  除了旅拍 （旅拍的有效标准是 实收 1000）
    //                 if ($value['order_amount'] * 0.3 >= $order_fact) {
    //                 // if ($order_fact >= 1000) {
    //                     $is_success = 1;
    //                     $order_valid = 2;
    //                     $earnest_money = 0;
                        
    //                     if (!$pay_time) {
    //                         $pay_time = $v['pay_time'];
    //                     }
    //                 }
    //                 // 订单无效
    //                 else{
    //                     $is_success = 3;
    //                     $order_fact = 0;
    //                     $order_valid = 1;
    //                     $earnest_money = $order_fact;
    //                 }
    //             }
    //             // 计算二销收款
    //             else if ($v['type'] == 2) {
    //                 $two_pin_fact += $v['pay_money'];
    //             }
    //         }
    //         // $this->log(date('Y-m-d H:i:s').'：处理订单明细');
    //         unset($orderDetail);
    //         // $this->log(date('Y-m-d H:i:s').'：准备处理客资');
    //         // 如果两个都不存在 
    //         if ($existId === 0) {
    //             $this->log(date('Y-m-d H:i:s').'：录入新客资-->');
    //             if ($value['wphone']) {
    //                 $cUpData['customer_tel']    = $value['wphone'];
    //                 $cUpData['customer_name']   = $value['wname'];
    //                 $cUpData['customer_wechat'] = $value['wwechat'];
    //                 $cUpData['customer_sex']    = '女';
    //                 $cUpData['mate_name']       = $value['mname'];
    //                 $cUpData['mate_tel']        = $value['mphone'];
    //                 $cUpData['mate_wechat']     = $value['mwechat'];
    //                 $cUpData['mate_sex']        = '男';
    //             }else{
    //                 $cUpData['customer_tel']    = $value['mphone'];
    //                 $cUpData['customer_name']   = $value['mname'];
    //                 $cUpData['customer_wechat'] = $value['mwechat'];
    //                 $cUpData['customer_sex']    = '男';
    //                 $cUpData['mate_name']       = $value['wname'];
    //                 $cUpData['mate_tel']        = $value['wphone'];
    //                 $cUpData['mate_wechat']     = $value['wwechat'];
    //                 $cUpData['mate_sex']        = '女';
    //             }
    //             // 客资表中 关于订单的字段 
    //             $cUpData['is_success']        = $is_success;
    //             $cUpData['order_start_time']  = $value['target_time'] ? date('Y-m-d H:i:s', strtotime($value['target_time'])) : null;
    //             $cUpData['order_day']         = $pay_time ? date('Y-m-d H:i:s', strtotime($pay_time)) : null;
    //             $cUpData['order_type']        = 2;
    //             $cUpData['fact_money']        = $order_fact+$two_pin_fact;
    //             $cUpData['totalpay_money']    = $value['order_amount']+$value['two_pin_amount'];
    //             $cUpData['order_number']      = $value['order_sn'];

    //             // 客资基本信息
    //             $customer_number = str_shuffle(strtotime($value['target_time']).generate_code());
    //             $cUpData['customer_number']   = $customer_number;
    //             $cUpData['dj_staff']          = $value['staff_name'];
    //             $cUpData['dj_day']            = $value['target_time'] ? date('Y-m-d H:i:s', strtotime($value['target_time'])) : null;
    //             $cUpData['create_time']       = $value['target_time'] ? date('Y-m-d H:i:s', strtotime($value['target_time'])) : null;
    //             $cUpData['consultation_type'] = $value['consultation_type'];
    //             $cUpData['customer_cource']   = $value['customer_cource'];
    //             $cUpData['customer_area']     = $value['customer_area'];
    //             $cUpData['marry_day']         = $value['marry_day'] ? date('Y-m-d H:i:s',strtotime($value['marry_day'])) : null;
    //             $cUpData['baby_birthday']     = $value['baby_birthday'] ? date('Y-m-d H:i:s',strtotime($value['baby_birthday'])) : null;
    //             $cUpData['shop_code']         = $value['shop_code'];
    //             $cUpData['shop_name']         = $value['shop_name'];
    //             $cUpData['brandclass_id']     = $value['brandclass_id'];
    //             $cUpData['brandclass']        = $brandclass;
    //             $cUpData['is_status']         = 1;
    //             $cUpData['c_from']            = 2;
    //             $this->log(date('Y-m-d H:i:s').'：录入客资start'.json_encode($cUpData));
    //             $cid = db('temp_info')->insertGetId($cUpData);
    //             $this->log(date('Y-m-d H:i:s').'：录入客资end');
    //             // 联系方式，插入联系方式表
    //             $contact=array_unique($contact);
    //             $contactList = [];
    //             foreach ($contact as $k => $v) {
    //                 $contactList[$k]['c_id']       = $cid;
    //                 $contactList[$k]['contact']    = $v;
    //                 $contactList[$k]['brandclass'] = $brandclass;
    //             }
    //             $this->log(date('Y-m-d H:i:s').'：录入联系方式'.json_encode($contactList));
    //             db('temp_contact')->insertAll($contactList);
    //             $this->log(date('Y-m-d H:i:s').'：联系方式表');
    //             unset($contact);
    //             unset($contactList);

    //             // 更新t_c_info 数据
    //             $tUpData['is_deal'] = 1;
    //             $tUpData['customer_number'] = $customer_number;
    //         }
    //         // 如果其中一个存在，就算存在  如果女士信息存在，按女士信息处理了
    //         else{
    //             $this->log(date('Y-m-d H:i:s').'：更新客资-->'.json_encode($existId));
    //             // 当前订单时间
    //             $target_time = $value['target_time'] ? date('Y-m-d H:i:s', strtotime($value['target_time'])) : null;

    //             //if ($wInfo) {
    //                 $cid = $existId['id'];
    //                 $customer_number = $existId['customer_number'];
    //                 // 如果该订单时间大于 客资表中的 订单时间，更新客资表的 订单信息 
    //                 if ($existId['order_start_time'] < $target_time) {
    //                     // 客资表中 关于订单的字段 
    //                     $cUpData['is_success']        = $is_success;
    //                     $cUpData['order_start_time']  = $target_time;
    //                     $cUpData['order_day']         = $pay_time ? date('Y-m-d H:i:s', strtotime($pay_time)) : null;
    //                     $cUpData['order_type']        = 2;
    //                     $cUpData['fact_money']        = $order_fact+$two_pin_fact;
    //                     $cUpData['totalpay_money']    = $value['order_amount']+$value['two_pin_amount'];
    //                     $cUpData['order_number']      = $value['order_sn'];
    //                     // 更新客资
    //                     $this->log(date('Y-m-d H:i:s').'：更新客资start'.json_encode($cUpData));
    //                     db('temp_info')->where('id', $cid)->update($cUpData);
    //                     $this->log(date('Y-m-d H:i:s').'：更新客资end');
    //                 }
    //             // }else{
    //             //     $cid = $mInfo['id'];
    //             //     $customer_number = $mInfo['customer_number'];
    //             //     // 如果该订单时间大于 客资表中的 订单时间，更新客资表的 订单信息 
    //             //     if ($mInfo['order_start_time'] < $target_time) {
    //             //         // 客资表中 关于订单的字段 
    //             //         $cUpData['is_success']        = $is_success;
    //             //         $cUpData['order_start_time']  = $target_time;
    //             //         $cUpData['order_day']         = $pay_time ? date('Y-m-d H:i:s', strtotime($pay_time)) : null;
    //             //         $cUpData['order_type']        = 2;
    //             //         $cUpData['fact_money']        = $order_fact+$two_pin_fact;
    //             //         $cUpData['totalpay_money']    = $value['order_amount']+$value['two_pin_amount'];
    //             //         $cUpData['order_number']      = $value['order_sn'];
    //             //         // 更新客资
    //             //         db('temp_info')->where('id', $cid)->update($cUpData);
    //             //     }
    //             // }

    //             // 更新t_c_info 数据
    //             $tUpData['is_deal'] = json_encode($cid);
    //             $tUpData['customer_number'] = $customer_number;
    //         }

    //         // 准备写入订单表的数据
    //         $oData = [
    //             'customer_id'          => $cid,
    //             'order_valid'          => $order_valid,
    //             'earnest_money'        => $earnest_money,
    //             'order_fact'           => $order_fact,
    //             'two_pin_fact'         => $two_pin_fact,
    //             'customer_name'        => $value['wname'] ? "'".$value['wname']."'" : "'".$value['mname']."'",
    //             'order_sn'             => "'".$value['order_sn']."'",
    //             'order_type'           => 2,
    //             'consultation_type'    => $value['consultation_type'],
    //             'customer_orderaddress'=> "'".$value['customer_orderaddress']."'",
    //             'order_amount'         => $value['order_amount'],
    //             'two_pin_amount'       => $value['two_pin_amount'],
    //             'order_note'           => "'".$value['order_note']."'",
    //             'create_time'          => $value['create_time'] ? "'".date('Y-m-d H:i:s', strtotime($value['create_time']))."'" : null,
    //             'target_time'          => $value['target_time'] ? "'".date('Y-m-d H:i:s', strtotime($value['target_time']))."'" : null,
    //             'shop_code'            => "'".$value['shop_code']."'",
    //             'shop_name'            => "'".$value['shop_name']."'",
    //             'brandclass'           => "'".$brandclass."'",
    //             'brandclass_id'        => $value['brandclass_id'],
    //         ];

    //         $insertStr[] = "(".implode(',',$oData).")";
    //         var_dump($insertStr);
    //         exit;
    //         // 插入订单表
    //         // $this->log(date('Y-m-d H:i:s').'：插入订单-->'.json_encode($oData));
    //         // db('temp_order')->insert($oData);
    //         // $this->log(date('Y-m-d H:i:s').'：插入订单');
    //         // 更新t_c_info 表
    //         db('t_c_info')->where('id', $value['id'])->update($tUpData);
    //         $this->log(date('Y-m-d H:i:s').'：更新erp表');
    //         unset($oData);
    //         unset($cUpData);
    //         unset($tUpData);
    //         // file_put_contents(ROOT_PATH.'/runtime/log/repair.log', date('Y-m-d H:i:s').'：处理完一个，循环处理下一个......'.PHP_EOL, FILE_APPEND);
    //     }
    //     var_dump($insertStr);
    //     exit;
    //     // 订单insert语句
    //     file_put_contents(ROOT_PATH.'/runtime/log/insertStr.log', explode(',', $insertStr), FILE_APPEND);
    //     // 明细insert语句
    //     // file_put_contents(ROOT_PATH.'/runtime/log/repair.log', '--》'.PHP_EOL, FILE_APPEND);
    //     // 录入明细
    //     // db('temp_detail')->insertAll($inDetail);
    //     unset($inDetail);
    //     // $this->log(date('Y-m-d H:i:s').'：处理所有订单的明细');
    //     // var_dump($inDetail);
    //     // exit;
    //     unset($all);
    //     $this->log(date('Y-m-d H:i:s').'：处理完一批，然后开始处理下一次循环。');
    //     // exit;
    //     // sleep(3);
    //     $this->shiftFiels();
    // }
}
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";
    }
}