<?php
/**
 * 醉唐风订单修复
 * CRM 基本模块
 * 默认接口方法，此方法内定议基础框架所需要的方法，用于验证模块合法性，模块版本，对接基础架构中需要的方法
 *
 * ============================================================================
 * 版权所有 2017北京素玄科技，并保留所有权利。
 *
 * 网站地址: http://www.suxuantech.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经允许的情况下，您不能对本系统代码做任何修改 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * 如有修改需求，请联系素玄科技有限公司：contact@suxuantech.cn
 * ============================================================================
 * $Author: songdemei<songdemei@suxuantech.cn> 2017-10-17 $
 */
namespace app\crm\controller;
use think\Controller;

class Test extends controller {
    public function index(){
        ini_set('memory_limit','10240M');
        set_time_limit(0);
        $start = time();
        echo "start...".$start."\r\n";
        $this->log('订单修复日期------2018-12-01---->');
        $this->log('订单修复------开始---->');
        $error = [];
        $erpinfo = db('c_customerorder','sx_erp')->alias('o')->join('c_customerinfo c','c.customerid=o.customerid','left')->where('o.create_time','between',['2018-12-01','2018-12-02'])->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();
        $this->log('需修复订单数量---------->'.count($erpinfo));
        $del = db('c_order_detail')->where('order_sn','in',array_column($erpinfo,'orderId'))->delete();
        $this->log('已删除的流水数据数量---------->'.count($del));
        $i = 1;
        $time = date('Y-m-d H:i:s');
        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;
            //查询客资表
            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();
            }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();
            }

            $data = [];
            $cdata = [];
            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'] = $targetdate;
                    }
                }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'] = $targetdate;
                        }
                    }
                }

                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($cusInfo['is_success'] != 1 && $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'] = $time;
                    $data['customer_id'] = $cusInfo['id'];
                    $data['customer_name'] = $cusInfo['customer_name'];

                    $data['earnest_money'] = $cdata['is_success'] != 1 ? $v['yixiaopaid_money'] : 0.00;
                    //一销
                    $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($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'] = $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();
                    }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 H:i:s',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 H:i:s',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));
                        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{//未找到客资
                $error[$k]['customer_name'] = $v['wname'];
                $error[$k]['customer_tel'] = $v['wphone'];
                $error[$k]['order_sn'] = $v['orderId'];
                $error[$k]['fact_money'] = $v['payment_money'];
                $error[$k]['totalpay_money'] = $v['total_money'];
                $error[$k]['order_start_time'] = $v['create_time'];
                $error[$k]['order_day'] = date('Y-m-d H:i:s',strtotime($v['targetdate']));
                $error[$k]['type'] = 1;//错误码：1:没有对应客资；2：没有对应订单；3：没有对应流水
                $this->log("第 $i 次循环------无对应客资----错误信息---->".json_encode($error[$k]));
            }
            $i++;
        }
        db()->startTrans();
        try{
            $er_sql = db('c_order_temp')->insertAll($error);//有误的订单信息
            $this->log("--最后----无对应客资----插入错误订单信息数量---->".$er_sql);
            db()->commit();
            echo 'success'.time()-$start;
        }catch (\Exception $e){
            db()->rollback();
            $this->log("--最后----无对应客资----插入错误订单信息数量---->".$e->getMessage());
            echo 'error'.$e->getMessage();
        }
    }
    function log($str){
        if(config('app_debug')){
            file_put_contents(LOG_PATH.date('Ym').DS."orderRepair-".date('YmdH').".log",'【'.date('Y-m-d H:i:s').'】'.$str.PHP_EOL,FILE_APPEND );
        }
    }
    /*----执行错误信息表------
    DROP TABLE IF EXISTS `c_error`;
CREATE TABLE `c_error` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `order_sn` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `error` text COLLATE utf8_unicode_ci,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=83 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    ---未找到对应客资或订单表----
     DROP TABLE IF EXISTS `c_order_temp`;
CREATE TABLE `c_order_temp` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `order_sn` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `customer_name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `customer_tel` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `customer_number` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `fact_money` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `totalpay_money` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `order_start_time` datetime DEFAULT NULL,
  `order_day` datetime DEFAULT NULL,
  `type` tinyint(2) DEFAULT '0' COMMENT '//错误码：1:没有对应客资；2：没有对应订单；3：没有对应流水',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=523 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
     * */
}
