<?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 {

    protected  $bClass  = '费司摄影';
    protected  $bClassId= '3';
    protected  $logName= '_repair.log';
    protected  $logPath= 'repair';
    public function repairCusOrder(){
        set_time_limit(0);
        // 所有的订单
        $allOrder = db('z_erp_c_customerorder')->alias('o')
            ->join('z_erp_c_customerinfo c','c.customerid=o.customerid','left')
            ->field('o.orderId,o.customerid,o.order_type,o.package_name,o.targetdate,o.storeconsuitant1,o.storeconsuitant2,o.total_money,o.payment_money,o.nopayment_money,o.supplementary_money,o.bargain_money,o.yixiaopaid_money,o.erxiaopaid_money,o.payoervedate,o.firstpaydate,o.ordernote,o.shop_code,o.shop_name,o.create_time,o.blankoutannal,o.is_effective,o.is_effectiveday,c.mphone,c.wphone,c.cssname')
            ->select();
        // 循环所有的订单
        foreach ($allOrder as $k => $v) {
            textlog('开始处理第'.$k.'个订单，单号：'.$v['orderId'],$this->logName,$this->logPath);
            db()->startTrans();
            try {
                $cusOrder=db('c_customer_order_copy')->where('order_sn',$v['orderId'])->field('id,customer_id')->find();
                // --- 修复客资数据 --- //
                $upCus['is_intostore'] = 2;
                $upCus['customer_cource'] = $v['cssname'];
                // if ($v['storeconsuitant2']) {
                //     # code...
                // }
                // 有效单
                if ($v['is_effective']==1) {
                    $upCus['is_success']= 1;
                    $upCus['order_day'] = date('Y-m-d H:i:s',strtotime($v['is_effectiveday']));

                    $upOrder['order_valid']= 2;
                    $upOrder['valid_time'] = date('Y-m-d H:i:s',strtotime($v['is_effectiveday']));
                }else{
                    $upCus['is_success']= 3;
                    $upCus['order_day'] = NULL;

                    $upOrder['order_valid']= 1;
                    $upOrder['valid_time'] = NULL;
                }
                $upCus['order_number'] = $v['orderId'];
                $upCus['order_start_time'] = date('Y-m-d H:i:s',strtotime($v['targetdate']));
                $upCus['fact_money'] = $v['payment_money'];
                $upCus['totalpay_money'] = $v['total_money'];
                // 客资里已经有订单了  修复订单数据
                if ($cusOrder) {
                    textlog('已存在订单：'.$v['orderId'],$this->logName,$this->logPath);
                    textlog('更新客资数据：'.json_encode($upCus),$this->logName,$this->logPath);
                    // 更新客资
                    db('c_customerinfo_copy')->where('id',$cusOrder['customer_id'])->update($upCus);
                    // --- 修复订单数据 --- //
                    // 作废单
                    if ($v['blankoutannal']==1) {
                        $upOrder['refund']= 2;
                    }
                    $upOrder['target_time']= date('Y-m-d H:i:s',strtotime($v['targetdate']));
                    $upOrder['create_time']= date('Y-m-d H:i:s',strtotime($v['create_time']));
                    // 有效单
                    
                    $upOrder['order_fact']    = $v['yixiaopaid_money'];
                    $upOrder['order_amount']  = $v['bargain_money'];
                    $upOrder['two_pin_fact']  = $v['erxiaopaid_money'];
                    $upOrder['two_pin_amount']= $v['supplementary_money'];
                    db('c_customer_order_copy')->where('id',$cusOrder['id'])->update($upOrder);
                    textlog('更新订单数据：'.json_encode($upOrder),$this->logName,$this->logPath);
                }
                // 客资里还没有订单  查询erp的客资手机号，在根据手机号查crm客资，并补充订单
                else{
                    textlog('不存在订单，新增订单：'.$v['orderId'],$this->logName,$this->logPath);
                    textlog('更新客资数据：'.json_encode($upCus),$this->logName,$this->logPath);
                    // 更新客资
                    db('c_customerinfo_copy')->where('id',$cusInfo['id'])->update($upCus);
                    // textlog('订单手机号：'.json_encode($twoPhone),$this->logName,$this->logPath);
                    if ($v['wphone'] && $v['mphone']) {
                        $sql = 'customer_tel='.$v['mphone'].' OR customer_tel='.$v['wphone'];
                    }else{
                        if ($v['mphone']) {
                            $sql = 'customer_tel='.$v['mphone'];
                        }
                        if ($v['wphone']) {
                            $sql = 'customer_tel='.$v['wphone'];
                        }
                    }
                    // 根据erp 订单的手机号查客资
                    $cusInfo = db('c_customerinfo_copy')->where($sql)->field('id,customer_name,customer_channel,customer_channel_id,shop_code,shop_name')->find();
                    // echo db()->getLastSql();
                    // var_dump($cusInfo);
                    textlog('查询客资：'.json_encode($cusInfo),$this->logName,$this->logPath);
                    if (!$cusInfo) {
                        db()->rollback();
                        textlog('订单未找到客资，语句：'.db()->getLastSql().'==>单号：'.$v['orderId'],$this->logName,$this->logPath);
                        continue;
                    }
                    $insOrder['customer_id'] = $cusInfo['id'];
                    $insOrder['customer_name'] = $cusInfo['customer_name'];
                    $insOrder['customer_channel_id'] = $cusInfo['customer_channel_id'];
                    $insOrder['customer_channel'] = $cusInfo['customer_channel'];
                    $insOrder['order_valid'] = $upOrder['order_valid'];
                    $insOrder['valid_time']  = $upOrder['valid_time'];
                    $insOrder['target_time'] = date('Y-m-d H:i:s',strtotime($v['targetdate']));
                    $insOrder['order_sn']    = $v['orderId'];
                    $insOrder['order_fact']    = $v['yixiaopaid_money'];
                    $insOrder['order_amount']  = $v['bargain_money'];
                    $insOrder['two_pin_fact']  = $v['erxiaopaid_money'];
                    $insOrder['two_pin_amount']= $v['supplementary_money'];
                    $insOrder['consultation_type'] = '';
                    $insOrder['create_time'] = date('Y-m-d H:i:s',strtotime($v['create_time']));
                    $insOrder['shop_code'] = $cusInfo['shop_code'];;
                    $insOrder['shop_name'] = $cusInfo['shop_name'];;
                    $insOrder['order_note'] = $v['ordernote'];
                    $insOrder['brandclass'] = $this->bClass;
                    $insOrder['brandclass_id'] = $this->bClassId;
                    db('c_customer_order_copy')->insert($insOrder);
                    textlog('插入订单信息：'.json_encode($insOrder),$this->logName,$this->logPath);
                }
                // 清空原有收款 同步erp收款记录
                db('c_order_detail')->where('order_sn',$v['orderId'])->delete();
                $payInfo = db('z_erp_c_paymentcontent')
                    ->where('orderId',$v['orderId'])
                    ->field('paymentdate,paymenttime,payment_money,suoshu')
                    ->select();
                $insertPay = [];
                foreach ($payInfo as $pk => $pv) {
                    $temp['pay_time'] = date('Y-m-d',strtotime($pv['paymentdate']));
                    $temp['create_time'] = date('Y-m-d',strtotime($pv['create_time']));
                    $temp['order_fact'] = $pv['payment_money'];
                    if ($pv['suoshu']=='前期款'||$pv['suoshu']=='前期补款') {
                        $temp['pay_type'] = 1;
                    }else{
                        $temp['pay_type'] = 2;
                    }
                    array_push($insertPay, $temp);
                    unset($temp);
                }
                db('c_order_detail')->insertAll($insertPay);
                db()->commit();
            } catch (\Exception $e) {
                db()->rollback();
                textlog($v['orderId'].'处理出现错误'.$e->getMessage(),$this->logName,$this->logPath);
                continue;
            }
        }
        die;
    }

    public function index(){
        $brandclassInfo= controller('index/Customer','lib')->getBrandClassInfo($brandclass_id);
        var_dump($brandclassInfo);
        die;
        $v['customerid'] = 'e243a1c6-317d-43fb-a274-f68c9a8ff82f';
        $twoPhone = db('z_erp_c_customerinfo')->where('customerid',$v['customerid'])->field('mphone','wphone')->find();
        if ($twoPhone['wphone'] && $twoPhone['mphone']) {
            $sql = 'customer_tel='.$twoPhone['mphone'].' OR customer_tel='.$twoPhone['wphone'];
        }else{
            if ($twoPhone['mphone']) {
                $sql = 'customer_tel='.$twoPhone['mphone'];
            }
            if ($twoPhone['wphone']) {
                $sql = 'customer_tel='.$twoPhone['wphone'];
            }
        }
        
        $cusInfo = db('c_customerinfo')->where($sql)->field('id,customer_name,customer_channel,customer_channel_id,shop_code,shop_name')->find();
        // echo db()->getLastSql();
        // var_dump($cusInfo);
        if (!$cusInfo) {
            # code...
        }
        die;



        $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();
        echo db()->getLastSql();
    }
    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;
     * */
}
