<?php

/*
*数据修复类，用于定期执行
*/

namespace app\crm\lib;
use think\Controller;
use app\common\lib\redisQueue;
/*
 * 命令
 * /usr/local/php/bin/php think repairintostore
 * win:进入项目目录后执行d:\suxuantech\bin\php\php.exe think repairintostore
 * */
class Repair extends Controller {
    public function juzi(){
        $date = date('Y-m-1');
        $sql1 = <<<EOF
select 
c.id,c.syjd_day
,g.id gid,g.is_intostore gintostore,g.syjd_day gsyjd_day
from sx_crm.c_customerinfo  c 
left join sx_erp.c_guestinfo g on g.from_index = c.customer_number 
and g.is_intostore = 1

where 
c.is_intostore in (2,3,5) and 
c.syjd_day >= '$date' 
and c.c_from = 1 and (c.is_success = 2 or order_type =2)
and date_format(c.syjd_day,'%Y-%m') <> date_format(g.syjd_day,'%Y-%m')
EOF;
        $res  = db()->query($sql1);
        $i = 0;
        foreach ($res as  $value) {
            $i++;
            $sqlup = 'update c_customerinfo set syjd_day = \''.$value['gsyjd_day'].'\' where id = '.$value['id'];
            $log['customer_id'] = $value['id'];
            $log['data'] = '进店数据数据修复，修复进店时间，原进店时间：'.$value['syjd_day'].'，新时间：'.$value['gsyjd_day'];
            $log['create_time'] = date('Y-m-d H:i:s');
            $log['module'] = 'index';
            $log['controller'] = 'Command';
            $log['action'] = 'Repair';
            try{
                db()->startTrans();
                db('c_customerinfo')->execute($sqlup);
                //db('CSalestrackinginfo')->insert($log);
                common_log($log,'action_log');
                db()->commit();
            }catch(\Exception $e){
                db()->rollback();
                $this->log('SQL1修复数据出错：'.$e->getMessage().';数据：'.db()->getLastSql(),1);
            }
            unset($log);
        }
        
       $this->log('SQL1执行结束,总计更新：'.$i,1);

        $sql2 = <<<EOF
select 
c.id,c.syjd_day
,g.id gid,g.is_intostore gintostore,g.syjd_day gsyjd_day

from sx_erp.c_guestinfo g 
left join sx_crm.c_customerinfo c force index(all_time) on g.from_index = c.customer_number 
where g.is_intostore = 1 and g.syjd_day >= '$date'  
and g.customer_from = 'CRM'
and 
c.is_intostore in (1,4)

EOF;

        $res2  = db()->query($sql2);
        $i = 0;
        foreach ($res2 as  $value) {
            $i++;
            $sqlup = 'update c_customerinfo set is_intostore = 2, syjd_day = \''.$value['gsyjd_day'].'\' where id = '.$value['id'];
            $log['customer_id'] = $value['id'];
            $log['data'] = '进店数据数据修复，修复进店时间+进店状态，原进店时间：'.$value['syjd_day'].'，新时间：'.$value['gsyjd_day'];
            $log['old_data'] = json_decode($value);
            $log['create_time'] = date('Y-m-d H:i:s');
            $log['module'] = 'index';
            $log['controller'] = 'Command';
            $log['action'] = 'Repair';
            try{
                db()->startTrans();
                db('c_customerinfo')->execute($sqlup);
                //db('CSalestrackinginfo')->insert($log);
                common_log($log,'action_log');
                db()->commit();
            }catch(\Exception $e){
                db()->rollback();
                $this->log('SQL2修复数据出错：'.$e->getMessage().';数据：'.db()->getLastSql(),1);
            }
            unset($log);
        }
        
       $this->log('SQL2执行结束,总计更新：'.$i,1);

 $sql3= <<<EOF
 select o.orderid,o.is_effective,date_format(o.is_effectiveday,'%Y-%m-%d')  is_effective ,c.id,c.customer_number,c.order_number,c.order_day,c.is_success
 from 
 sx_erp.c_customerorder o 
 left join sx_crm.c_customerinfo c on c.order_number = o.orderid
 where o.is_effective = 1 and o.is_effectiveday is not null and o.is_effectiveday <> ''
 and c.id is not null and   date_format(o.is_effectiveday,'%Y-%m-%d') <> date_format(c.order_day,'%Y-%m-%d')
EOF;

        $res3  = db()->query($sql3);
        $i = 0;
        foreach ($res3 as  $value) {
            $i++;
            $newOrderday = $value['is_effective'].' '.substr($value['order_day'], 11);

            $sqlup = 'update c_customerinfo set order_day = \''.$newOrderday.'\' where id = '.$value['id'];
            $log['customer_id'] = $value['id'];
            $log['data'] = '订单有效时间修复，修复订单有效时间，原有效时间：'.$value['order_day'].'，新时间：'.$newOrderday;
            $log['old_data'] = json_decode($value);
            $log['create_time'] = date('Y-m-d H:i:s');
            $log['module'] = 'index';
            $log['controller'] = 'Command';
            $log['action'] = 'Repair';
            try{
                db()->startTrans();
                db('c_customerinfo')->execute($sqlup);
                //db('CSalestrackinginfo')->insert($log);
                common_log($log,'action_log');
                db()->commit();
            }catch(\Exception $e){
                db()->rollback();
                $this->log('SQL3修复数据出错：'.$e->getMessage().';数据：'.db()->getLastSql(),1);
            }
            unset($log);
        }
        
       $this->log('SQL3执行结束,总计更新：'.$i,1);
       $sql4 = <<<EOF
       UPDATE sx_erp.c_customerinfo a join sx_erp.c_guestinfo b on a.customer_from_index=b.from_index
set a.customer_channel=b.customer_channel
where a.customer_channel='' and b.customer_channel<>'';
EOF;
        try{
            db()->startTrans();
            $res = db()->execute($sql4);
            //db('CSalestrackinginfo')->insert($log);
            db()->commit();
        }catch(\Exception $e){
            db()->rollback();
            $this->log('SQL4修复数据出错：'.$e->getMessage().';数据：'.db()->getLastSql(),1);
        }
        $this->log('SQL4执行结束,总计更新：'.$res,1);
        $sql5 = <<<EOF
        update sx_erp.c_customerinfo c  
left join sx_crm.c_customerinfo cc on cc.customer_number = c.customer_from_index 
set c.customer_channel = cc.customer_channel
where cc.id is not null and c.customer_channel = '' and cc.c_from =1 and cc.customer_channel <> ''
EOF;
        try{
            db()->startTrans();
            $res = db()->execute($sql5);
            //db('CSalestrackinginfo')->insert($log);
            db()->commit();
        }catch(\Exception $e){
            db()->rollback();
            $this->log('SQL5修复数据出错：'.$e->getMessage().';数据：'.db()->getLastSql(),1);
        }
        $this->log('SQL5执行结束,总计更新：'.$res,1);
    }
    function laise(){
        $start = time();
        echo "start...".$start."\r\n";
        $this->log('订单修复日期------2019-09-10---->');
        $this->log('订单修复------开始---->');
        $error = [];


//        $erpinfo = db('c_customerorder_temp')->alias('o')->join('c_customerinfo_temp c','c.customerid=o.customerid','left')->where('o.create_time','between',['2019-03-25','2019-03-31'])->field('o.id,o.orderId,o.targetdate,o.create_time,o.order_type,c.weddingdate,c.bbithdate,c.wbirthday,c.mbirthday,c.consultation_type,c.area,c.cssname,storeconsuitant1,storeconsuitant2,o.total_money,o.payment_money,o.bargain_money,o.supplementary_money,o.consumption_type,o.payoervedate,o.ordernote,o.yixiaopaid_money,o.erxiaopaid_money,o.validdate,c.wname,c.wphone,c.wwechat,c.mwechat,c.mname,c.wphone,c.customer_from_index,c.shop_code,c.shop_name,c.brandid')->select();
        $erpinfo = db('c_customerorder_temp')->alias('o')->join('c_customerinfo_temp c','c.customerid=o.customerid','left')->where('o.create_time','between',['2019-09-10 00:00:00','2019-10-15 20:30'])->field('o.id,o.orderId,o.targetdate,o.create_time,o.order_type,storeconsuitant2,o.total_money,o.payment_money,o.bargain_money,o.supplementary_money,o.consumption_type,o.payoervedate,o.ordernote,o.yixiaopaid_money,o.erxiaopaid_money,o.validdate,c.wname,c.wphone,c.mname,c.wphone,c.customer_from_index,c.shop_code,c.shop_name,c.brandid')->select();
        /*$corder = db('c_customer_order')->where('order_sn','in',array_column($erpinfo,'orderId'))->field('id,order_sn')->select();
        $corders = array_column($corder,'order_sn');
        foreach ($erpinfo as $key=>$val) {
            if(in_array($val['orderId'],$corders)){
                unset($erpinfo[$key]);
            }
        }*/

        $this->log('需修复订单数量---------->'.count($erpinfo));
        $i = 1;
        $time = date('Y-m-d H:i:s');
        $logs = [];
        foreach($erpinfo as $k=>$v){
            $targetdate = substr($v['targetdate'],0,4).'-'.substr($v['targetdate'],4,2).'-'.substr($v['targetdate'],6,2).' 00:00:00';
            $validdate = $v['validdate'] ? substr($v['validdate'],0,4).'-'.substr($v['validdate'],4,2).'-'.substr($v['validdate'],6,2).' 00:00:00' : $targetdate;
            $syjd_day = $v['create_time'];
            //查询客资表
            if($v['customer_from_index']){
                $cusInfo = db('c_customerinfo')->where('customer_number',$v['customer_from_index'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
            }elseif($v['wphone']){
                $cusInfo = db('c_customerinfo')->where('customer_tel',$v['wphone'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
                if(empty($cusInfo)){
                    $cusInfo = db('c_customerinfo')->where('mate_tel',$v['wphone'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
                }
            }elseif($v['mphone']){
                $cusInfo = db('c_customerinfo')->where('customer_tel',$v['mphone'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
                if(empty($cusInfo)){
                    $cusInfo = db('c_customerinfo')->where('mate_tel',$v['mphone'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
                }
            }

            $data = [];
            $cdata = [];
            $binfo = getAllBrand();
            if(!empty($cusInfo)){
                $this->log("第 $i 次循环------有对应客资---->");
                //线上订单 500进店
                if($cusInfo['order_type'] == 1){
                    if($v['payment_money'] >= 500 && $cusInfo['is_intostore'] != 2){
                        $cdata['is_intostore'] = 2;
                        $cdata['syjd_day'] = $syjd_day;
                    }
                }else{
                    //线下订单 交钱就算进店
                    if($cusInfo['is_intostore'] != 2 && $v['payment_money'] > 0){
                        $cdata['is_intostore'] = 2;
                        if($cusInfo['is_intostore'] != 5 || empty($cusInfo['syjd_day'])){
                            $cdata['syjd_day'] = $syjd_day;
                        }
                    }
                }

                if($v['orderId'] != $cusInfo['order_number']){
                    $cdata['order_number'] = $v['orderId'];
                }
                if($v['total_money'] != $cusInfo['totalpay_money']){
                    $cdata['totalpay_money'] = $v['total_money'];
                }
                if($v['payment_money'] != $cusInfo['fact_money']){
                    $cdata['fact_money'] = $v['payment_money'];
                }
                if($v['payment_money'] >= 99){
                    $cdata['is_success'] = 1;
                    $cdata['order_day'] = $validdate ? $validdate : $targetdate;
                }elseif($v['payment_money'] > 0 && $v['payment_money'] < 99){
                    $cdata['is_success'] = 3;
                }else{
                    $cdata['is_success'] = 2;
                }
                if(date('YmdHis',strtotime($cusInfo['order_start_time'])) != date('YmdHis',strtotime($v['create_time']))){
                    $cdata['order_start_time'] = $targetdate;
                }
                //查询订单表
                $order = db('c_customer_order')->where('order_sn',$v['orderId'])->find();
                if(empty($order)){
                    $this->log("第 $i 次循环------无对应订单--创建订单-->");
                    $time = date('Y-m-d H:i:s',time());
                    //创建订单
                    $data['shop_code'] = $v['shop_code'];
                    $data['shop_name'] = $v['shop_name'];
                    $data['target_time'] = $targetdate ? $targetdate : $time;

                    $data['create_time'] = $v['create_time'];
                    $data['customer_id'] = $cusInfo['id'];
                    $data['customer_name'] = $cusInfo['customer_name'];

                    $data['earnest_money'] = $cdata['is_success'] == 1 ? 0.00 : $v['yixiaopaid_money'];
                    //一销
                    $data['order_fact'] = $cdata['is_success'] == 1 ? $v['yixiaopaid_money'] : 0.00;
                    $data['order_amount'] = $v['bargain_money'] ? $v['bargain_money'] : 0.00;
                    //二销
                    $data['two_pin_fact'] = $v['erxiaopaid_money'] ? $v['erxiaopaid_money'] : 0.00;
                    $data['two_pin_amount'] = $v['supplementary_money'] ? $v['supplementary_money'] : 0.00;

                    $data['consultation_type'] = $v['consumption_type'];
                    $data['order_note'] = $v['ordernote'];
                    $data['order_sn'] = $v['orderId'];
                    $data['order_type'] = 1;
                    $data['brandclass_id'] = $v['brandid'];
                    $binfo = getAllBrand();
                    $data['brandclass'] = $binfo[$v['brandid']]['brandclass'];
                    $data['order_valid'] = $cdata['is_success'] == 1 ? 2 : 1;
                    $this->log("第 $i 次循环------无对应订单--创建订单数据-->".json_encode($data));
                    db()->startTrans();
                    try{
                        $res = db('c_customer_order')->insert($data);
                        $this->log("第 $i 次循环------无对应订单--创建订单结果-->".$res);
                        if($v['yixiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d H:i:s',strtotime($v['payoervedate'])) : $validdate;
                            $detail['order_valid'] = $data['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['yixiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 1;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------无对应订单--需要插入一销流水信息-->".json_encode($detail));
                        }
                        if($v['erxiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d H:i:s',strtotime($v['payoervedate'])) : $validdate;
                            $detail['order_valid'] = $data['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['erxiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 2;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------无对应订单--需要插入二销销流水信息-->".json_encode($detail));
                        }


                        db('c_customerinfo')->where('id',$cusInfo['id'])->update($cdata);//修改客资信息
                        $this->log("第 $i 次循环------无对应订单--需要修改的客资信息-->".json_encode($cdata));
                        db()->commit();
                        $ll =  '系统修复：创建订单：'.$v['orderId'].'一销实收：'.$data['order_fact'].'，一销套系：'. $data['order_amount'].',二销实收'.$data['two_pin_fact'].',二销套系：'.$data['two_pin_amount'].',订单时间：'.$data['target_time'];
                        $logs[] = [
                            'module'     => 'crm',
                            'controller' => 'repair',
                            'action'     => 'system',
                            'old_data'   => '',
                            'data'       => $ll,
                            'customer_id'=> $cusInfo['id'],
                            'staff_name' => 'system',
                            'staff_id'   => -1,
                            'ip'         => get_client_ip(),
                            'create_time'=> $time,
                        ];
                    }catch (\Exception $e){
                        db()->rollback();
                        //记录失败订单
                        $fail['order_sn'] = $v['orderId'];
                        $fail['error'] = $e->getMessage();
                        db('c_error')->insert($fail);
                        $this->log("第 $i 次循环------无对应订单--执行失败-->".json_encode($fail));
                    }
                }else{
                    //订单表有数据就查看数据对不对
                    $odata = [];
                    if($order['customer_id'] != $cusInfo['id']){
                        $odata['customer_id'] = $cusInfo['id'];
                    }
                    if($order['order_sn'] != $v['orderId']){
                        $odata['order_sn'] = $v['orderId'];
                    }

                    if($v['bargain_money'] != $order['order_amount']){
                        $odata['order_amount'] = $v['bargain_money'] ? $v['bargain_money'] : 0.00;
                    }
                    if($v['supplementary_money'] != $order['two_pin_amount']){
                        $odata['two_pin_amount'] = $v['supplementary_money'] ? $v['supplementary_money'] : 0.00;
                    }
                    if($v['yixiaopaid_money'] != $order['order_fact']){
                        $odata['order_fact'] = $v['yixiaopaid_money'] ? $v['yixiaopaid_money'] : 0.00;
                    }
                    if($v['erxiaopaid_money'] != $order['two_pin_fact']){
                        $odata['two_pin_fact'] = $v['erxiaopaid_money'] ? $v['erxiaopaid_money'] : 0.00;
                    }
                    if($v['payment_money'] >= 99){
                        $odata['order_valid'] = 2;
                        $odata['earnest_money'] = 0.00;
                        $cdata['is_success'] = 1;
                        if(empty($cusInfo['order_day'])){
                            $cdata['order_day'] = $validdate ? $validdate : $targetdate;
                        }
                    }elseif($v['payment_money'] > 0 && $v['payment_money'] < 99){
                        $odata['order_valid'] = 1;
                        $cdata['is_success'] = 3;
                        if(empty($cusInfo['order_day'])){
                            $cdata['order_start_time'] = $targetdate;
                        }
                    }else{
                        $odata['order_valid'] = 1;
                        if(empty($cusInfo['order_day'])){
                            $cdata['order_start_time'] = $targetdate;
                        }
                    }
                    db()->startTrans();
                    try{
                        if(!empty($odata)){
                            $this->log("第 $i 次循环------有对应订单--需要修改订单信息-->".json_encode($odata));
                            db('c_customer_order')->where('id',$order['id'])->update($odata);
                        }
                        if($v['yixiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d',strtotime($v['payoervedate'])): $validdate;
                            $detail['order_valid'] = $odata['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['yixiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 1;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------有对应订单--需要插入一销流水信息-->".json_encode($detail));
                        }
                        if($v['erxiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d',strtotime($v['payoervedate'])): $validdate;
                            $detail['order_valid'] = $odata['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['erxiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 2;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------有对应订单--需要插入二销销流水信息-->".json_encode($detail));
                        }

                        db('c_customerinfo')->where('id',$cusInfo['id'])->update($cdata);//修改客资信息
                        $this->log("第 $i 次循环------有对应订单--需要修改的客资信息-->".json_encode($cdata));
                        $ll = '系统修复：修复客资ID：'.$cusInfo['id'].'，修复订单，流水：'.$v['orderId'].'一销实收：'.$odata['order_fact'].'，一销套系：'. $odata['order_amount'].',二销实收'.$odata['two_pin_fact'].',二销套系：'.$odata['two_pin_amount'].',订单时间：'.$odata['target_time'];
                        $logs[] = [
                            'module'     => 'crm',
                            'controller' => 'repair',
                            'action'     => 'system',
                            'old_data'   => '',
                            'data'       => $ll,
                            'customer_id'=> $cusInfo['id'],
                            'staff_name' => 'system',
                            'staff_id'   => -1,
                            'ip'         => get_client_ip(),
                            'create_time'=> $time,
                        ];
                        db()->commit();
                    }catch (\Exception $e){
                        db()->rollback();
                        //记录失败订单
                        $fail['order_sn'] = $v['orderId'];
                        $fail['error'] = $e->getMessage();
                        db('c_error')->insert($fail);
                        $this->log("第 $i 次循环------有对应订单--修改订单和流水信息执行失败-->".json_encode($fail));
                    }
                }
            }else{//未找到客资  创建客资 erp未存登记人id 所以crm只有登记人名字，没有id，追踪人同样
                $newdata = [
                    'brandclass_id'        => $v['brandid'],
                    'brandclass'           => $binfo[$v['brandid']]['brandclass'],
                    'shop_code'            => $v['shop_code'],
                    'shop_name'            => $v['shop_name'],
                    'add_shop_code'        => $v['shop_code'],
                    'add_shop_name'        => $v['shop_name'],
                    'customer_number'      => $v['customer_from_index'] ? $v['customer_from_index'] : str_shuffle(time().generate_code()),
                    'customer_name'        => $v['wname'],
                    'customer_tel'         => $v['wphone'],
                    'customer_wechat'      => $v['wwechat'],
                    'customer_sex'         => '女',
                    'mate_name'            => $v['mname'],
                    'mate_tel'             => $v['mphone'],
                    'mate_wechat'          => $v['mwechat'],
                    'mate_sex'             => '男',
                    'marry_day'            => $v['weddingdate'] ? date('Y-m-d H:i:s', strtotime($v['weddingdate'])) : NULL,
                    'ready_baby_day'       => $v['bbithdate']?date('Y-m-d H:i:s',strtotime($v['bbithdate'])):NULL,
                    'consultation_type_id' => NULL,
                    'consultation_type'    => $v['consultation_type'],
                    'customer_area_id'     => NULL,
                    'customer_area'        => $v['area'],
                    'customer_cource_id'   => NULL,
                    'customer_cource'      => $v['cssname'],
                    'c_from'               => 2,
                    'is_intostore'         => 2,
                    'is_success'           => $v['yixiaopaid_money']>= 99 ? 1 : 3,
                    'syjd_day'             => $v['create_time']?$v['create_time']:null,
                    'creator_day'          => $v['create_time'],
                    'create_time'          => $v['create_time'],
                    'dj_day'               => $v['create_time'],
                    'dj_staff'             => $v['storeconsuitant1'],
                    'dj_staff_id'          => NULL,
                    'dj_staff_number'      => NULL,
                    'is_fp'                => 1,
                    'sales_staff'          => $v['storeconsuitant2'],
                    'sales_staff_id'       => NULL,
                    'sales_staff_number'   => NULL,
                    'is_first_tel'         => 1,
                    'customer_type'        => 1,
                    'consulation_shop_code'=> $v['shop_code'],
                    'consulation_shop'     => $v['shop_name'],
                    'reception_id'         => NULL,
                    'reception_name'       => $v['storeconsuitant1'] ? $v['storeconsuitant1'] : NULL,
                    'order_start_time'     => $v['create_time']?$v['create_time']:$time,
                    'is_valid'             => 1,
                    'yx_day'               => $v['create_time']?$v['create_time']:$time,
                    'customer_birthday'    => $v['wbirthday'] ? date('Y-m-d H:i:s', strtotime($v['wbirthday'])) : NULL,
                    'mate_birthday'        => $v['mbirthday'] ? date('Y-m-d H:i:s', strtotime($v['mbirthday'])) : NULL,
                ];
                //这条客资所有联系方式
                $contact=array();
                $contactList=array();
                if($newdata['customer_tel']){
                    array_push($contact,$newdata['customer_tel']);
                }
                if($newdata['customer_wechat']){
                    array_push($contact,$newdata['customer_wechat']);
                }
                if($newdata['mate_wechat']){
                    array_push($contact,$newdata['mate_wechat']);
                }
                if($data['mate_tel']){
                    array_push($contact,$newdata['mate_tel']);
                }
                $contact=array_unique($contact);
                //创建订单
                $data['shop_code'] = $v['shop_code'];
                $data['shop_name'] = $v['shop_name'];
                $data['target_time'] = $targetdate ? $targetdate : $time;

                $data['create_time'] = $v['create_time'];
                $data['customer_name'] = $v['wname'];

                $data['earnest_money'] = $v['yixiaopaid_money'] < 99 ? $v['yixiaopaid_money'] : 0.00;
                //一销
                $data['order_fact'] =   $v['yixiaopaid_money'] >= 99 ? $v['yixiaopaid_money'] : 0.00;
                $data['order_amount'] = $v['bargain_money'] ? $v['bargain_money'] : 0.00;
                //二销
                $data['two_pin_fact'] = $v['erxiaopaid_money'] ? $v['erxiaopaid_money'] : 0.00;
                $data['two_pin_amount'] = $v['supplementary_money'] ? $v['supplementary_money'] : 0.00;

                $data['consultation_type'] = $v['consumption_type'];
                $data['order_note'] = $v['ordernote'];
                $data['order_sn'] = $v['orderId'];
                $data['order_type'] = 1;
                $data['brandclass_id'] = $v['brandid'];
                $data['brandclass'] = $binfo[$v['brandid']]['brandclass'];
                $data['order_valid'] = $v['yixiaopaid_money']>= 99 ? 2 : 1;
                try{
                    $id = db('c_customerinfo')->insertGetId($newdata);//插入客资信息
                    $this->log("第 $i 次循环------无对应客资--需要创建的客资ID-->".$id);

                    foreach($contact as $kkk => $vvv){
                        $contactList[$kkk]['c_id']=$id;
                        $contactList[$kkk]['contact']=$vvv;
                        $contactList[$kkk]['brandclass']=$newdata['brandclass'];
                    }
                    db('c_customer_contact')->insertAll($contactList);

                    $data['customer_id'] = $id;
                    $res = db('c_customer_order')->insert($data);

                    $this->log("第 $i 次循环------无对应客资--创建订单-->".json_encode($data));
                    if($data['yixiaopaid_money']>0){
                        //插入流水表
                        $detail['order_sn'] = $v['orderId'];
                        $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d H:i:s',strtotime($v['payoervedate'])) : $validdate;
                        $detail['order_valid'] = $data['order_valid'];
                        $detail['order_type'] = 1;
                        $detail['order_fact'] = $v['yixiaopaid_money'];
                        $detail['create_time'] = $v['create_time'];
                        $detail['pay_type'] = 1;
                        controller('crm/Customer','lib')->insert_order_detail($detail);
                        $this->log("第 $i 次循环------无对应客资--需要插入一销流水信息-->".json_encode($detail));
                    }
                    if($v['erxiaopaid_money']>0){
                        //插入流水表
                        $detail['order_sn'] = $v['orderId'];
                        $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d H:i:s',strtotime($v['payoervedate'])) : $validdate;
                        $detail['order_valid'] = $data['order_valid'];
                        $detail['order_type'] = 1;
                        $detail['order_fact'] = $v['erxiaopaid_money'];
                        $detail['create_time'] = $v['create_time'];
                        $detail['pay_type'] = 2;
                        controller('crm/Customer','lib')->insert_order_detail($detail);
                        $this->log("第 $i 次循环------无对应客资--需要插入二销销流水信息-->".json_encode($detail));
                    }
                    $ll =  '系统修复：创建客资ID：'.$id.'，创建订单，流水：'.$v['orderId'].'一销实收：'.$data['order_fact'].'，一销套系：'. $data['order_amount'].',二销实收'.$data['two_pin_fact'].',二销套系：'.$data['two_pin_amount'].',订单时间：'.$data['target_time'];
                    $logs[] = [
                        'module'     => 'crm',
                        'controller' => 'repair',
                        'action'     => 'system',
                        'old_data'   => '',
                        'data'       => $ll,
                        'customer_id'=> $id,
                        'staff_name' => 'system',
                        'staff_id'   => -1,
                        'ip'         => get_client_ip(),
                        'create_time'=> $time,
                    ];
                    db()->commit();
                }catch (\Exception $ex){
                    db()->rollback();
                    $fail['order_sn'] = $v['orderId'];
                    $fail['error'] = $ex->getMessage();
                    db('c_error')->insert($fail);
                    $this->log("第 $i 次循环------无对应客资--执行失败-->".json_encode($fail));
                }
            }
            $i++;
        }
        db()->startTrans();
        try{
            db('action_log','db_logs')->insertAll($logs);
            db()->commit();
            echo 'success'.time()-$start;
        }catch (\Exception $e){
            db()->rollback();
            $this->log("--最后--------插入错误信息报错:---->".$e->getMessage());
            echo 'error'.$e->getMessage();
        }
    }
    function tcdj(){
        $start = time();
        echo "start...".$start."\r\n";
        $this->log('天长地久订单修复------开始---->');
        $error = [];


//        $erpinfo = db('c_customerorder_temp')->alias('o')->join('c_customerinfo_temp c','c.customerid=o.customerid','left')->where('o.create_time','between',['2019-03-25','2019-03-31'])->field('o.id,o.orderId,o.targetdate,o.create_time,o.order_type,c.weddingdate,c.bbithdate,c.wbirthday,c.mbirthday,c.consultation_type,c.area,c.cssname,storeconsuitant1,storeconsuitant2,o.total_money,o.payment_money,o.bargain_money,o.supplementary_money,o.consumption_type,o.payoervedate,o.ordernote,o.yixiaopaid_money,o.erxiaopaid_money,o.payoervedate,c.wname,c.wphone,c.wwechat,c.mwechat,c.mname,c.wphone,c.customer_from_index,c.shop_code,c.shop_name,c.brandid')->select();
        $erpinfo = db('c_customerorder_erp')->alias('o')->join('c_customerinfo_erp c','c.customerid=o.customerid','left')->where('o.targetdate','>=','20191001')->field('o.id,o.orderId,o.targetdate,o.create_time,o.order_type,storeconsuitant2,o.total_money,o.payment_money,o.bargain_money,o.supplementary_money,o.consumption_type,o.payoervedate,o.ordernote,o.yixiaopaid_money,o.erxiaopaid_money,o.payoervedate,c.wname,c.wphone,c.mname,c.wphone,c.customer_from_index,c.shop_code,c.shop_name,c.brandid')->select();

        $this->log('需修复订单数量---------->'.count($erpinfo));
        $i = 1;
        $time = date('Y-m-d H:i:s');
        $logs = [];
        foreach($erpinfo as $k=>$v){
            $targetdate = substr($v['targetdate'],0,4).'-'.substr($v['targetdate'],4,2).'-'.substr($v['targetdate'],6,2).' 00:00:00';
            $payoervedate = $v['payoervedate'] ? substr($v['payoervedate'],0,4).'-'.substr($v['payoervedate'],4,2).'-'.substr($v['payoervedate'],6,2).' 00:00:00' : $targetdate;
            $syjd_day = $v['create_time'];
            //查询客资表
            $cusInfo = db('c_customerinfo')->where('order_number',$v['orderId'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
            if(!empty($cusInfo)){
                $this->log("第 $i 次循环---".$v['orderId']."---crm有对应订单，不用修复---->");
            }else{
                if($v['wphone']){
                    $cusInfo = db('c_customerinfo')->where('customer_tel',$v['wphone'])->where('dj_day','<',$targetdate)->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->order('id desc')->limit(1)->find();
                    if(empty($cusInfo)){
                        $cusInfo = db('c_customerinfo')->where('mate_tel',$v['wphone'])->where('dj_day','<',$targetdate)->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->order('id desc')->limit(1)->find();
                    }
                }elseif($v['mphone']){
                    $cusInfo = db('c_customerinfo')->where('customer_tel',$v['mphone'])->where('dj_day','<',$targetdate)->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->order('id desc')->limit(1)->find();
                    if(empty($cusInfo)){
                        $cusInfo = db('c_customerinfo')->where('mate_tel',$v['mphone'])->where('dj_day','<',$targetdate)->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->order('id desc')->limit(1)->find();
                    }
                }


            $data = [];
            $cdata = [];
            if(!empty($cusInfo)){
                $this->log("第 $i 次循环------有对应客资---->");
                //线上订单 500进店

                $cdata['is_intostore'] = 2;
                $cdata['syjd_day'] = $syjd_day;


                if($v['orderId'] != $cusInfo['order_number']){
                    $cdata['order_number'] = $v['orderId'];
                }
                if($v['total_money'] != $cusInfo['totalpay_money']){
                    $cdata['totalpay_money'] = $v['total_money'];
                }
                if($v['payment_money'] != $cusInfo['fact_money']){
                    $cdata['fact_money'] = $v['payment_money'];
                }
                if($v['payment_money'] >= 100){
                    $cdata['is_success'] = 1;
                    $cdata['order_day'] = $payoervedate ? $payoervedate : $targetdate;
                }elseif($v['payment_money'] > 0 && $v['payment_money'] < 100){
                    $cdata['is_success'] = 3;
                }else{
                    $cdata['is_success'] = 2;
                }
                if(date('YmdHis',strtotime($cusInfo['order_start_time'])) != date('YmdHis',strtotime($v['create_time']))){
                    $cdata['order_start_time'] = $targetdate;
                }
                //查询订单表
                $order = db('c_customer_order')->where('order_sn',$v['orderId'])->find();
                if(empty($order)){
                    $this->log("第 $i 次循环------无对应订单--创建订单-->");
                    $time = date('Y-m-d H:i:s',time());
                    //创建订单
                    $data['shop_code'] = $v['shop_code'];
                    $data['shop_name'] = $v['shop_name'];
                    $data['target_time'] = $targetdate ? $targetdate : $time;

                    $data['create_time'] = $v['create_time'];
                    $data['customer_id'] = $cusInfo['id'];
                    $data['customer_name'] = $cusInfo['customer_name'];

                    $data['earnest_money'] = $cdata['is_success'] == 1 ? 0.00 : $v['yixiaopaid_money'];
                    //一销
                    $data['order_fact'] = $cdata['is_success'] == 1 ? $v['yixiaopaid_money'] : 0.00;
                    $data['order_amount'] = $v['bargain_money'] ? $v['bargain_money'] : 0.00;
                    //二销
                    $data['two_pin_fact'] = $v['erxiaopaid_money'] ? $v['erxiaopaid_money'] : 0.00;
                    $data['two_pin_amount'] = $v['supplementary_money'] ? $v['supplementary_money'] : 0.00;

                    $data['consultation_type'] = $v['consumption_type'];
                    $data['order_note'] = $v['ordernote'];
                    $data['order_sn'] = $v['orderId'];
                    $data['order_type'] = 1;
                    $data['brandclass_id'] = $v['brandid'];
                    $binfo = getAllBrand();
                    $data['brandclass'] = $binfo[$v['brandid']]['brandclass'];
                    $data['order_valid'] = $cdata['is_success'] == 1 ? 2 : 1;
                    $this->log("第 $i 次循环------无对应订单--创建订单数据-->".json_encode($data));
                    db()->startTrans();
                    try{
                        $res = db('c_customer_order')->insert($data);
                        $this->log("第 $i 次循环------无对应订单--创建订单结果-->".$res);
                        if($v['yixiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d H:i:s',strtotime($v['payoervedate'])) : $payoervedate;
                            $detail['order_valid'] = $data['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['yixiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 1;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------无对应订单--需要插入一销流水信息-->".json_encode($detail));
                        }
                        if($v['erxiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d H:i:s',strtotime($v['payoervedate'])) : $payoervedate;
                            $detail['order_valid'] = $data['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['erxiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 2;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------无对应订单--需要插入二销销流水信息-->".json_encode($detail));
                        }


                        db('c_customerinfo')->where('id',$cusInfo['id'])->update($cdata);//修改客资信息
                        $this->log("第 $i 次循环------无对应订单--需要修改的客资信息-->".json_encode($cdata));
                        db()->commit();
                        $ll =  '系统修复：创建订单：'.$v['orderId'].'一销实收：'.$data['order_fact'].'，一销套系：'. $data['order_amount'].',二销实收'.$data['two_pin_fact'].',二销套系：'.$data['two_pin_amount'].',订单时间：'.$data['target_time'];
                        $logs[] = [
                            'module'     => 'crm',
                            'controller' => 'repair',
                            'action'     => 'system',
                            'old_data'   => '',
                            'data'       => $ll,
                            'customer_id'=> $cusInfo['id'],
                            'staff_name' => 'system',
                            'staff_id'   => -1,
                            'ip'         => get_client_ip(),
                            'create_time'=> $time,
                        ];
                    }catch (\Exception $e){
                        db()->rollback();
                        //记录失败订单
                        $fail['order_sn'] = $v['orderId'];
                        $fail['error'] = $e->getMessage();
                        db('c_error')->insert($fail);
                        $this->log("第 $i 次循环------无对应订单--执行失败-->".json_encode($fail));
                    }
                }else{
                    //订单表有数据就查看数据对不对
                    $odata = [];
                    if($order['customer_id'] != $cusInfo['id']){
                        $odata['customer_id'] = $cusInfo['id'];
                    }
                    if($order['order_sn'] != $v['orderId']){
                        $odata['order_sn'] = $v['orderId'];
                    }

                    if($v['bargain_money'] != $order['order_amount']){
                        $odata['order_amount'] = $v['bargain_money'] ? $v['bargain_money'] : 0.00;
                    }
                    if($v['supplementary_money'] != $order['two_pin_amount']){
                        $odata['two_pin_amount'] = $v['supplementary_money'] ? $v['supplementary_money'] : 0.00;
                    }
                    if($v['yixiaopaid_money'] != $order['order_fact']){
                        $odata['order_fact'] = $v['yixiaopaid_money'] ? $v['yixiaopaid_money'] : 0.00;
                    }
                    if($v['erxiaopaid_money'] != $order['two_pin_fact']){
                        $odata['two_pin_fact'] = $v['erxiaopaid_money'] ? $v['erxiaopaid_money'] : 0.00;
                    }
                    if($v['payment_money'] >= 100){
                        $odata['order_valid'] = 2;
                        $odata['earnest_money'] = 0.00;
                        $cdata['is_success'] = 1;
                        if(empty($cusInfo['order_day'])){
                            $cdata['order_day'] = $payoervedate ? $payoervedate : $targetdate;
                        }
                    }elseif($v['payment_money'] > 0 && $v['payment_money'] < 100){
                        $odata['order_valid'] = 1;
                        $cdata['is_success'] = 3;
                        if(empty($cusInfo['order_day'])){
                            $cdata['order_start_time'] = $targetdate;
                        }
                    }else{
                        $odata['order_valid'] = 1;
                        if(empty($cusInfo['order_day'])){
                            $cdata['order_start_time'] = $targetdate;
                        }
                    }
                    db()->startTrans();
                    try{
                        if(!empty($odata)){
                            $this->log("第 $i 次循环------有对应订单--需要修改订单信息-->".json_encode($odata));
                            db('c_customer_order')->where('id',$order['id'])->update($odata);
                        }
                        if($v['yixiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d',strtotime($v['payoervedate'])): $payoervedate;
                            $detail['order_valid'] = $odata['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['yixiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 1;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------有对应订单--需要插入一销流水信息-->".json_encode($detail));
                        }
                        if($v['erxiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d',strtotime($v['payoervedate'])): $payoervedate;
                            $detail['order_valid'] = $odata['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['erxiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 2;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------有对应订单--需要插入二销销流水信息-->".json_encode($detail));
                        }

                        db('c_customerinfo')->where('id',$cusInfo['id'])->update($cdata);//修改客资信息
                        $this->log("第 $i 次循环------有对应订单--需要修改的客资信息-->".json_encode($cdata));
                        $ll = '系统修复：修复客资ID：'.$cusInfo['id'].'，修复订单，流水：'.$v['orderId'].'一销实收：'.$odata['order_fact'].'，一销套系：'. $odata['order_amount'].',二销实收'.$odata['two_pin_fact'].',二销套系：'.$odata['two_pin_amount'].',订单时间：'.$odata['target_time'];
                        $logs[] = [
                            'module'     => 'crm',
                            'controller' => 'repair',
                            'action'     => 'system',
                            'old_data'   => '',
                            'data'       => $ll,
                            'customer_id'=> $cusInfo['id'],
                            'staff_name' => 'system',
                            'staff_id'   => -1,
                            'ip'         => get_client_ip(),
                            'create_time'=> $time,
                        ];
                        db()->commit();
                    }catch (\Exception $e){
                        db()->rollback();
                        //记录失败订单
                        $fail['order_sn'] = $v['orderId'];
                        $fail['error'] = $e->getMessage();
                        db('c_error')->insert($fail);
                        $this->log("第 $i 次循环------有对应订单--修改订单和流水信息执行失败-->".json_encode($fail));
                    }
                }
            }
            }
            $i++;
        }
        db()->startTrans();
        try{
            db('action_log','db_logs')->insertAll($logs);
            db()->commit();
            echo 'success'.time()-$start;
        }catch (\Exception $e){
            db()->rollback();
            $this->log("--最后--------插入错误信息报错:---->".$e->getMessage());
            echo 'error'.$e->getMessage();
        }
    }
    function jsj(){
        $start = time();
        echo "start...".$start."\r\n";
        $this->log('订单修复日期------2019-10-24---->');
        $this->log('订单修复------开始---->');
        $error = [];


//        $erpinfo = db('c_customerorder_temp')->alias('o')->join('c_customerinfo_temp c','c.customerid=o.customerid','left')->where('o.create_time','between',['2019-03-25','2019-03-31'])->field('o.id,o.orderId,o.targetdate,o.create_time,o.order_type,c.weddingdate,c.bbithdate,c.wbirthday,c.mbirthday,c.consultation_type,c.area,c.cssname,storeconsuitant1,storeconsuitant2,o.total_money,o.payment_money,o.bargain_money,o.supplementary_money,o.consumption_type,o.payoervedate,o.ordernote,o.yixiaopaid_money,o.erxiaopaid_money,o.validdate,c.wname,c.wphone,c.wwechat,c.mwechat,c.mname,c.wphone,c.customer_from_index,c.shop_code,c.shop_name,c.brandid')->select();
        $erpinfo = db('c_customerorder')->alias('o')->join('c_customerinfo_temp c','c.customerid=o.customerid','left')->where('o.create_time','between',['2019-10-24 00:00:00','2019-10-24 23:59:59'])->field('o.id,o.orderId,o.targetdate,o.create_time,o.order_type,storeconsuitant2,o.total_money,o.payment_money,o.bargain_money,o.supplementary_money,o.consumption_type,o.payoervedate,o.ordernote,o.yixiaopaid_money,o.erxiaopaid_money,o.payoervedate,c.wname,c.wphone,c.mname,c.wphone,c.customer_from_index,c.shop_code,c.shop_name,c.brandid')->select();
        /*$corder = db('c_customer_order')->where('order_sn','in',array_column($erpinfo,'orderId'))->field('id,order_sn')->select();
        $corders = array_column($corder,'order_sn');
        foreach ($erpinfo as $key=>$val) {
            if(in_array($val['orderId'],$corders)){
                unset($erpinfo[$key]);
            }
        }*/

        $this->log('需修复订单数量---------->'.count($erpinfo));
        $i = 1;
        $time = date('Y-m-d H:i:s');
        $logs = [];
        foreach($erpinfo as $k=>$v){
            $targetdate = substr($v['targetdate'],0,4).'-'.substr($v['targetdate'],4,2).'-'.substr($v['targetdate'],6,2).' 00:00:00';
            $validdate = $v['payoervedate'] ? substr($v['payoervedate'],0,4).'-'.substr($v['payoervedate'],4,2).'-'.substr($v['payoervedate'],6,2).' 00:00:00' : $targetdate;
            $syjd_day = $v['create_time'];
            //查询客资表
            if($v['customer_from_index']){
                $cusInfo = db('c_customerinfo')->where('customer_number',$v['customer_from_index'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
            }elseif($v['wphone']){
                $cusInfo = db('c_customerinfo')->where('customer_tel',$v['wphone'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
                if(empty($cusInfo)){
                    $cusInfo = db('c_customerinfo')->where('mate_tel',$v['wphone'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
                }
            }elseif($v['mphone']){
                $cusInfo = db('c_customerinfo')->where('customer_tel',$v['mphone'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
                if(empty($cusInfo)){
                    $cusInfo = db('c_customerinfo')->where('mate_tel',$v['mphone'])->field('id,customer_number,customer_name,customer_tel,is_success,fact_money,totalpay_money,order_start_time,order_day,sales_staff_id,sales_staff,sales_staff_number')->find();
                }
            }

            $data = [];
            $cdata = [];
            $binfo = getAllBrand();
            if(!empty($cusInfo)){
                $this->log("第 $i 次循环------有对应客资---->");
                //线上订单 500进店
                if($cusInfo['order_type'] == 1){
                    if($v['payment_money'] >= 1 && $cusInfo['is_intostore'] != 2){
                        $cdata['is_intostore'] = 2;
                        $cdata['syjd_day'] = $syjd_day;
                    }
                }else{
                    //线下订单 交钱就算进店
                    if($cusInfo['is_intostore'] != 2 && $v['payment_money'] > 0){
                        $cdata['is_intostore'] = 2;
                        if($cusInfo['is_intostore'] != 5 || empty($cusInfo['syjd_day'])){
                            $cdata['syjd_day'] = $syjd_day;
                        }
                    }
                }

                if($v['orderId'] != $cusInfo['order_number']){
                    $cdata['order_number'] = $v['orderId'];
                }
                if($v['total_money'] != $cusInfo['totalpay_money']){
                    $cdata['totalpay_money'] = $v['total_money'];
                }
                if($v['payment_money'] != $cusInfo['fact_money']){
                    $cdata['fact_money'] = $v['payment_money'];
                }
                if($v['payment_money'] >= 1){
                    $cdata['is_success'] = 1;
                    $cdata['order_day'] = $validdate ? $validdate : $targetdate;
                }elseif($v['payment_money'] > 0 && $v['payment_money'] < 1){
                    $cdata['is_success'] = 3;
                }else{
                    $cdata['is_success'] = 2;
                }
                if(date('YmdHis',strtotime($cusInfo['order_start_time'])) != date('YmdHis',strtotime($v['create_time']))){
                    $cdata['order_start_time'] = $targetdate;
                }
                //查询订单表
                $order = db('c_customer_order')->where('order_sn',$v['orderId'])->find();
                if(empty($order)){
                    $this->log("第 $i 次循环------无对应订单--创建订单-->");
                    $time = date('Y-m-d H:i:s',time());
                    //创建订单
                    $data['shop_code'] = $v['shop_code'];
                    $data['shop_name'] = $v['shop_name'];
                    $data['target_time'] = $targetdate ? $targetdate : $time;

                    $data['create_time'] = $v['create_time'];
                    $data['customer_id'] = $cusInfo['id'];
                    $data['customer_name'] = $cusInfo['customer_name'];

                    $data['earnest_money'] = $cdata['is_success'] == 1 ? 0.00 : $v['yixiaopaid_money'];
                    //一销
                    $data['order_fact'] = $cdata['is_success'] == 1 ? $v['yixiaopaid_money'] : 0.00;
                    $data['order_amount'] = $v['bargain_money'] ? $v['bargain_money'] : 0.00;
                    //二销
                    $data['two_pin_fact'] = $v['erxiaopaid_money'] ? $v['erxiaopaid_money'] : 0.00;
                    $data['two_pin_amount'] = $v['supplementary_money'] ? $v['supplementary_money'] : 0.00;

                    $data['consultation_type'] = $v['consumption_type'];
                    $data['order_note'] = $v['ordernote'];
                    $data['order_sn'] = $v['orderId'];
                    $data['order_type'] = 1;
                    $data['brandclass_id'] = $v['brandid'];
                    $binfo = getAllBrand();
                    $data['brandclass'] = $binfo[$v['brandid']]['brandclass'];
                    $data['order_valid'] = $cdata['is_success'] == 1 ? 2 : 1;
                    $this->log("第 $i 次循环------无对应订单--创建订单数据-->".json_encode($data));
                    db()->startTrans();
                    try{
                        $res = db('c_customer_order')->insert($data);
                        $this->log("第 $i 次循环------无对应订单--创建订单结果-->".$res);
                        if($v['yixiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d H:i:s',strtotime($v['payoervedate'])) : $validdate;
                            $detail['order_valid'] = $data['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['yixiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 1;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------无对应订单--需要插入一销流水信息-->".json_encode($detail));
                        }
                        if($v['erxiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d H:i:s',strtotime($v['payoervedate'])) : $validdate;
                            $detail['order_valid'] = $data['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['erxiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 2;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------无对应订单--需要插入二销销流水信息-->".json_encode($detail));
                        }


                        db('c_customerinfo')->where('id',$cusInfo['id'])->update($cdata);//修改客资信息
                        $this->log("第 $i 次循环------无对应订单--需要修改的客资信息-->".json_encode($cdata));
                        db()->commit();
                        $ll =  '系统修复：创建订单：'.$v['orderId'].'一销实收：'.$data['order_fact'].'，一销套系：'. $data['order_amount'].',二销实收'.$data['two_pin_fact'].',二销套系：'.$data['two_pin_amount'].',订单时间：'.$data['target_time'];
                        $logs[] = [
                            'module'     => 'crm',
                            'controller' => 'repair',
                            'action'     => 'system',
                            'old_data'   => '',
                            'data'       => $ll,
                            'customer_id'=> $cusInfo['id'],
                            'staff_name' => 'system',
                            'staff_id'   => -1,
                            'ip'         => get_client_ip(),
                            'create_time'=> $time,
                        ];
                    }catch (\Exception $e){
                        db()->rollback();
                        //记录失败订单
                        $fail['order_sn'] = $v['orderId'];
                        $fail['error'] = $e->getMessage();
                        db('c_error')->insert($fail);
                        $this->log("第 $i 次循环------无对应订单--执行失败-->".json_encode($fail));
                    }
                }else{
                    //订单表有数据就查看数据对不对
                    $odata = [];
                    if($order['customer_id'] != $cusInfo['id']){
                        $odata['customer_id'] = $cusInfo['id'];
                    }
                    if($order['order_sn'] != $v['orderId']){
                        $odata['order_sn'] = $v['orderId'];
                    }

                    if($v['bargain_money'] != $order['order_amount']){
                        $odata['order_amount'] = $v['bargain_money'] ? $v['bargain_money'] : 0.00;
                    }
                    if($v['supplementary_money'] != $order['two_pin_amount']){
                        $odata['two_pin_amount'] = $v['supplementary_money'] ? $v['supplementary_money'] : 0.00;
                    }
                    if($v['yixiaopaid_money'] != $order['order_fact']){
                        $odata['order_fact'] = $v['yixiaopaid_money'] ? $v['yixiaopaid_money'] : 0.00;
                    }
                    if($v['erxiaopaid_money'] != $order['two_pin_fact']){
                        $odata['two_pin_fact'] = $v['erxiaopaid_money'] ? $v['erxiaopaid_money'] : 0.00;
                    }
                    if($v['payment_money'] >= 1){
                        $odata['order_valid'] = 2;
                        $odata['earnest_money'] = 0.00;
                        $cdata['is_success'] = 1;
                        if(empty($cusInfo['order_day'])){
                            $cdata['order_day'] = $validdate ? $validdate : $targetdate;
                        }
                    }elseif($v['payment_money'] > 0 && $v['payment_money'] < 1){
                        $odata['order_valid'] = 1;
                        $cdata['is_success'] = 3;
                        if(empty($cusInfo['order_day'])){
                            $cdata['order_start_time'] = $targetdate;
                        }
                    }else{
                        $odata['order_valid'] = 1;
                        if(empty($cusInfo['order_day'])){
                            $cdata['order_start_time'] = $targetdate;
                        }
                    }
                    db()->startTrans();
                    try{
                        if(!empty($odata)){
                            $this->log("第 $i 次循环------有对应订单--需要修改订单信息-->".json_encode($odata));
                            db('c_customer_order')->where('id',$order['id'])->update($odata);
                        }
                        if($v['yixiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d',strtotime($v['payoervedate'])): $validdate;
                            $detail['order_valid'] = $odata['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['yixiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 1;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------有对应订单--需要插入一销流水信息-->".json_encode($detail));
                        }
                        if($v['erxiaopaid_money']>0){
                            //插入流水表
                            $detail['order_sn'] = $v['orderId'];
                            $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d',strtotime($v['payoervedate'])): $validdate;
                            $detail['order_valid'] = $odata['order_valid'];
                            $detail['order_type'] = $cusInfo['order_type'] ? $cusInfo['order_type'] : 1;
                            $detail['order_fact'] = $v['erxiaopaid_money'];
                            $detail['create_time'] = $v['create_time'];
                            $detail['pay_type'] = 2;
                            controller('crm/Customer','lib')->insert_order_detail($detail);
                            $this->log("第 $i 次循环------有对应订单--需要插入二销销流水信息-->".json_encode($detail));
                        }

                        db('c_customerinfo')->where('id',$cusInfo['id'])->update($cdata);//修改客资信息
                        $this->log("第 $i 次循环------有对应订单--需要修改的客资信息-->".json_encode($cdata));
                        $ll = '系统修复：修复客资ID：'.$cusInfo['id'].'，修复订单，流水：'.$v['orderId'].'一销实收：'.$odata['order_fact'].'，一销套系：'. $odata['order_amount'].',二销实收'.$odata['two_pin_fact'].',二销套系：'.$odata['two_pin_amount'].',订单时间：'.$odata['target_time'];
                        $logs[] = [
                            'module'     => 'crm',
                            'controller' => 'repair',
                            'action'     => 'system',
                            'old_data'   => '',
                            'data'       => $ll,
                            'customer_id'=> $cusInfo['id'],
                            'staff_name' => 'system',
                            'staff_id'   => -1,
                            'ip'         => get_client_ip(),
                            'create_time'=> $time,
                        ];
                        db()->commit();
                    }catch (\Exception $e){
                        db()->rollback();
                        //记录失败订单
                        $fail['order_sn'] = $v['orderId'];
                        $fail['error'] = $e->getMessage();
                        db('c_error')->insert($fail);
                        $this->log("第 $i 次循环------有对应订单--修改订单和流水信息执行失败-->".json_encode($fail));
                    }
                }
            }else{//未找到客资  创建客资 erp未存登记人id 所以crm只有登记人名字，没有id，追踪人同样
                $newdata = [
                    'brandclass_id'        => $v['brandid'],
                    'brandclass'           => $binfo[$v['brandid']]['brandclass'],
                    'shop_code'            => $v['shop_code'],
                    'shop_name'            => $v['shop_name'],
                    'add_shop_code'        => $v['shop_code'],
                    'add_shop_name'        => $v['shop_name'],
                    'customer_number'      => $v['customer_from_index'] ? $v['customer_from_index'] : str_shuffle(time().generate_code()),
                    'customer_name'        => $v['wname'],
                    'customer_tel'         => $v['wphone'],
                    'customer_wechat'      => $v['wwechat'],
                    'customer_sex'         => '女',
                    'mate_name'            => $v['mname'],
                    'mate_tel'             => $v['mphone'],
                    'mate_wechat'          => $v['mwechat'],
                    'mate_sex'             => '男',
                    'marry_day'            => $v['weddingdate'] ? date('Y-m-d H:i:s', strtotime($v['weddingdate'])) : NULL,
                    'ready_baby_day'       => $v['bbithdate']?date('Y-m-d H:i:s',strtotime($v['bbithdate'])):NULL,
                    'consultation_type_id' => NULL,
                    'consultation_type'    => $v['consultation_type'],
                    'customer_area_id'     => NULL,
                    'customer_area'        => $v['area'],
                    'customer_cource_id'   => NULL,
                    'customer_cource'      => $v['cssname'],
                    'c_from'               => 2,
                    'is_intostore'         => 2,
                    'is_success'           => $v['yixiaopaid_money']>= 1 ? 1 : 3,
                    'syjd_day'             => $v['create_time']?$v['create_time']:null,
                    'creator_day'          => $v['create_time'],
                    'create_time'          => $v['create_time'],
                    'dj_day'               => $v['create_time'],
                    'dj_staff'             => $v['storeconsuitant1'],
                    'dj_staff_id'          => NULL,
                    'dj_staff_number'      => NULL,
                    'is_fp'                => 1,
                    'sales_staff'          => $v['storeconsuitant2'],
                    'sales_staff_id'       => NULL,
                    'sales_staff_number'   => NULL,
                    'is_first_tel'         => 1,
                    'customer_type'        => 1,
                    'consulation_shop_code'=> $v['shop_code'],
                    'consulation_shop'     => $v['shop_name'],
                    'reception_id'         => NULL,
                    'reception_name'       => $v['storeconsuitant1'] ? $v['storeconsuitant1'] : NULL,
                    'order_start_time'     => $v['create_time']?$v['create_time']:$time,
                    'is_valid'             => 1,
                    'yx_day'               => $v['create_time']?$v['create_time']:$time,
                    'customer_birthday'    => $v['wbirthday'] ? date('Y-m-d H:i:s', strtotime($v['wbirthday'])) : NULL,
                    'mate_birthday'        => $v['mbirthday'] ? date('Y-m-d H:i:s', strtotime($v['mbirthday'])) : NULL,
                ];
                //这条客资所有联系方式
                $contact=array();
                $contactList=array();
                if($newdata['customer_tel']){
                    array_push($contact,$newdata['customer_tel']);
                }
                if($newdata['customer_wechat']){
                    array_push($contact,$newdata['customer_wechat']);
                }
                if($newdata['mate_wechat']){
                    array_push($contact,$newdata['mate_wechat']);
                }
                if($data['mate_tel']){
                    array_push($contact,$newdata['mate_tel']);
                }
                $contact=array_unique($contact);
                //创建订单
                $data['shop_code'] = $v['shop_code'];
                $data['shop_name'] = $v['shop_name'];
                $data['target_time'] = $targetdate ? $targetdate : $time;

                $data['create_time'] = $v['create_time'];
                $data['customer_name'] = $v['wname'];

                $data['earnest_money'] = $v['yixiaopaid_money'] < 1 ? $v['yixiaopaid_money'] : 0.00;
                //一销
                $data['order_fact'] =   $v['yixiaopaid_money'] >= 1 ? $v['yixiaopaid_money'] : 0.00;
                $data['order_amount'] = $v['bargain_money'] ? $v['bargain_money'] : 0.00;
                //二销
                $data['two_pin_fact'] = $v['erxiaopaid_money'] ? $v['erxiaopaid_money'] : 0.00;
                $data['two_pin_amount'] = $v['supplementary_money'] ? $v['supplementary_money'] : 0.00;

                $data['consultation_type'] = $v['consumption_type'];
                $data['order_note'] = $v['ordernote'];
                $data['order_sn'] = $v['orderId'];
                $data['order_type'] = 1;
                $data['brandclass_id'] = $v['brandid'];
                $data['brandclass'] = $binfo[$v['brandid']]['brandclass'];
                $data['order_valid'] = $v['yixiaopaid_money']>= 1 ? 2 : 1;
                try{
                    $id = db('c_customerinfo')->insertGetId($newdata);//插入客资信息
                    $this->log("第 $i 次循环------无对应客资--需要创建的客资ID-->".$id);

                    foreach($contact as $kkk => $vvv){
                        $contactList[$kkk]['c_id']=$id;
                        $contactList[$kkk]['contact']=$vvv;
                        $contactList[$kkk]['brandclass']=$newdata['brandclass'];
                    }
                    db('c_customer_contact')->insertAll($contactList);

                    $data['customer_id'] = $id;
                    $res = db('c_customer_order')->insert($data);

                    $this->log("第 $i 次循环------无对应客资--创建订单-->".json_encode($data));
                    if($data['yixiaopaid_money']>0){
                        //插入流水表
                        $detail['order_sn'] = $v['orderId'];
                        $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d H:i:s',strtotime($v['payoervedate'])) : $validdate;
                        $detail['order_valid'] = $data['order_valid'];
                        $detail['order_type'] = 1;
                        $detail['order_fact'] = $v['yixiaopaid_money'];
                        $detail['create_time'] = $v['create_time'];
                        $detail['pay_type'] = 1;
                        controller('crm/Customer','lib')->insert_order_detail($detail);
                        $this->log("第 $i 次循环------无对应客资--需要插入一销流水信息-->".json_encode($detail));
                    }
                    if($v['erxiaopaid_money']>0){
                        //插入流水表
                        $detail['order_sn'] = $v['orderId'];
                        $detail['pay_time'] = $v['payoervedate'] ? date('Y-m-d H:i:s',strtotime($v['payoervedate'])) : $validdate;
                        $detail['order_valid'] = $data['order_valid'];
                        $detail['order_type'] = 1;
                        $detail['order_fact'] = $v['erxiaopaid_money'];
                        $detail['create_time'] = $v['create_time'];
                        $detail['pay_type'] = 2;
                        controller('crm/Customer','lib')->insert_order_detail($detail);
                        $this->log("第 $i 次循环------无对应客资--需要插入二销销流水信息-->".json_encode($detail));
                    }
                    $ll =  '系统修复：创建客资ID：'.$id.'，创建订单，流水：'.$v['orderId'].'一销实收：'.$data['order_fact'].'，一销套系：'. $data['order_amount'].',二销实收'.$data['two_pin_fact'].',二销套系：'.$data['two_pin_amount'].',订单时间：'.$data['target_time'];
                    $logs[] = [
                        'module'     => 'crm',
                        'controller' => 'repair',
                        'action'     => 'system',
                        'old_data'   => '',
                        'data'       => $ll,
                        'customer_id'=> $id,
                        'staff_name' => 'system',
                        'staff_id'   => -1,
                        'ip'         => get_client_ip(),
                        'create_time'=> $time,
                    ];
                    db()->commit();
                }catch (\Exception $ex){
                    db()->rollback();
                    $fail['order_sn'] = $v['orderId'];
                    $fail['error'] = $ex->getMessage();
                    db('c_error')->insert($fail);
                    $this->log("第 $i 次循环------无对应客资--执行失败-->".json_encode($fail));
                }
            }
            $i++;
        }
        db()->startTrans();
        try{
            db('action_log','db_logs')->insertAll($logs);
            db()->commit();
            echo 'success'.time()-$start;
        }catch (\Exception $e){
            db()->rollback();
            $this->log("--最后--------插入错误信息报错:---->".$e->getMessage());
            echo 'error'.$e->getMessage();
        }
    }
    function log($str,$file=1){
        if(config('app_debug')){
            if (strtoupper(substr(php_uname(),0,3)) == 'WIN') {
                $str = iconv("UTF-8","GB2312//IGNORE",$str);
            }
            $logFile = LOG_PATH.'repair_log-'.date('Y-m').'.log';
            if($file){
                file_put_contents($logFile, date('Y-m-d H:i:s').$str."\r\n",FILE_APPEND);
            }else{
                echo date('Y-m-d H:i:s').$str."\r\n";
            }
        }
    }
}