<?php
namespace common\models\forms;

use common\helpers\Date;
use common\helpers\snowflake\SnowFake;
use common\models\ExcelOrderShop;
use common\models\OrderGoodsShop;
use common\models\OrderShop;
use common\models\Period;
use common\models\User;
use common\models\UserInfo;
use Yii;
use yii\base\Exception;

class ExcelOrderShopForm extends \common\components\ActiveRecord
{
    CONST EXCEL_ORDER_SHOP_FIELD = [
        '会员编号' => 'USER_NAME',
//        '报单中心' => 'DEC_USER_NAME',
//        '订单号' => 'ORDER_SN',
        '订单状态' => 'STATUS',
        '收货人' => 'CONSIGNEE',
        '联系方式1' => 'MOBILE',
        '省' => 'PROVINCE',
        '市' => 'CITY',
        '区' => 'COUNTY',
        '详细地址' => 'ADDRESS',
        '期数' => 'PERIOD_NUM',
        '订单类型' => 'ORDER_TYPE',
        '创建时间' => 'CREATED_AT',
        '支付时间' => 'PAY_AT',
        '发货时间' => 'DELIVERY_AT',
        '运费' => 'FREIGHT',
        '快递公司' => 'EXPRESS_COMPANY',
        '快递单号' => 'ORDER_TRACK_NO',
        '发货方式' => 'EXPRESS_TYPE',
        '会员备注' => 'FRONT_REMARK',
        '发货仓' => 'WAREHOUSE',
        '发货状态' => 'DELIVERY_STATUS',
    ];

    CONST EXCEL_ORDER_SHOP_GOODS_FIELD = [
        '订单号' => 'ORDER_SN',
//        '订单状态' => 'STATUS',
        '存货编码' => 'SKU_CODE',
        '存货名称' => 'GOODS_TITLE',
        '数量' => 'BUY_NUMS',
        '商品单价' => 'PRICE',
        '商品金额' => 'REAL_PRICE',
        '商品PV' => 'PV',
        'PV合计' => 'REAL_PV',
        '期数' => 'PERIOD_NUM',
    ];

    private $_isSentMaxPeriodNum = 0;

    /**
     * 初始化最小未挂网的期数
     */
    public function initNoClosedMinPeriodNum() {
        $periodModel = Period::instance();
        $this->_isSentMaxPeriodNum = $periodModel->getMaxIsSentPeriodNum();
    }


    /**
     * 导入excel数据
     * @param $excelData
     * @param $orderDay
     * @param $payType
     * @return bool
     * @throws \yii\db\Exception
     */
    public function run($excelData,$orderDay,$payType) {
        if( !$excelData ) return false;
        $this->initNoClosedMinPeriodNum();

        foreach ($excelData as $everyData) {
            if( !$everyData ) continue;

            $formatOrderData = [];
            $formatOrderGoodsData = [];
            foreach ($everyData as $key => $value) {
                if(isset(self::EXCEL_ORDER_SHOP_FIELD[$key])) {
                    $formatOrderData[self::EXCEL_ORDER_SHOP_FIELD[$key]] = $value;
                }

                if(isset(self::EXCEL_ORDER_SHOP_GOODS_FIELD[$key])) {
                    $formatOrderGoodsData[self::EXCEL_ORDER_SHOP_GOODS_FIELD[$key]] = $value;
                }
            }

            if( !isset($formatOrderGoodsData['ORDER_SN']) ) {
                throw new \Exception('缺少订单编号字段');
            }

            if ( !isset($formatOrderData['PERIOD_NUM']) ) {
                throw new \Exception('缺少期数字段');
            }

            if ( $formatOrderData['PERIOD_NUM'] <= $this->_isSentMaxPeriodNum ) {
                throw new \Exception(sprintf('不可以导入已经挂网期数【%s】的数据', $formatOrderData['PERIOD_NUM']));
            }

            //判断商城订单是表中是否已经存在该订单
            $one = OrderShop::find()->select(["USER_ID", "PERIOD_NUM", "SN", "ORDER_AMOUNT", "PV", "PAY_AMOUNT", "PAY_PV"])->where('SN=:SN', ['SN' => $formatOrderGoodsData['ORDER_SN']])->asArray()->one();
            if ($one) {

                if ( $one['PERIOD_NUM'] != $formatOrderData['PERIOD_NUM'] ) {
                    throw new \Exception(sprintf('订单号【%s】重复不可以导入', $formatOrderGoodsData['ORDER_SN']));
                }

                OrderShop::updateAllCounters([
                    'ORDER_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
                    'PV' => $formatOrderGoodsData['REAL_PV'],
                    'PAY_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
                    'PAY_PV' => $formatOrderGoodsData['REAL_PV'],
                ], 'SN=:SN', [
                    'SN' => $formatOrderGoodsData['ORDER_SN']
                ]);

                //会员状态激活
                $amount = $one['ORDER_AMOUNT'] + $formatOrderGoodsData['REAL_PRICE'];
                if ($amount >= 300) {
                    $userStatus = User::find()->select(["ID", "STATUS"])->where('ID=:ID', ['ID' => $one['USER_ID']])->asArray()->one();
                    if ($userStatus && $userStatus['STATUS'] == 0) {
                        User::updateAll(['STATUS' => 1], 'ID=:ID', ['ID' => $one['USER_ID']]);
                    }
                }
                unset($amount, $userStatus);

            } else {
                $userInfoArr = UserInfo::findOneAsArray('USER_NAME=:USER_NAME', [':USER_NAME' => $formatOrderData['USER_NAME']], 'USER_ID');
                if (!isset($userInfoArr['USER_ID']) || !$userInfoArr['USER_ID']) {
//                    echo $formatOrderData['USER_NAME'] . PHP_EOL;
                    continue;
                }

                //insertOrderShop
                $orderShopInsertData = array_merge($formatOrderData, [
                    'ID' => SnowFake::instance()->generateId(),
                    'SN' => $formatOrderGoodsData['ORDER_SN'],
                    'USER_ID' => $userInfoArr['USER_ID'],
                    'ORDER_TYPE' => 'FX',
                    'ORDER_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
                    'PV' => $formatOrderGoodsData['REAL_PV'],
                    'PAY_AMOUNT' => $formatOrderGoodsData['REAL_PRICE'],
                    'PAY_PV' => $formatOrderGoodsData['REAL_PV'],
                    'PAY_AT' => strtotime(self::excelTime($formatOrderData['PAY_AT'])),
                    'DELIVERY_AT' => strtotime(self::excelTime($formatOrderData['DELIVERY_AT'])),
                    'CREATED_AT' => strtotime(self::excelTime($formatOrderData['CREATED_AT'])),
                    'CREATE_USER' => $formatOrderData['USER_NAME'],
                    'PAY_TYPE' => $payType,//@todo
                    'STATUS' => 1,
                    'P_CALC_MONTH' => self::excelTime($formatOrderData['CREATED_AT'],'Y-m-d'),
                    'DELIVERY_STATUS' => $formatOrderData['DELIVERY_STATUS'] === '已发货' ? 1 : 0,
                    'ORDER_DAY' => $orderDay,
                ]);
                OrderShop::insertOne($orderShopInsertData);

                //会员状态激活
                if ($orderShopInsertData['ORDER_AMOUNT'] >= 300) {
                    $userStatus = User::find()->select(["ID", "STATUS"])->where('ID=:ID', ['ID' => $userInfoArr['USER_ID']])->asArray()->one();
                    if ($userStatus && $userStatus['STATUS'] == 0) {
                        User::updateAll(['STATUS' => 1], 'ID=:ID', ['ID' => $userInfoArr['USER_ID']]);
                    }
                }

                unset($orderShopInsertData, $userInfoArr, $userStatus);
            }
            $goodsInsertData[] = array_merge($formatOrderGoodsData, [
                'ORDER_DAY' => $orderDay,
                'PAY_TYPE' => $payType,
                'P_CALC_MONTH' => self::excelTime($formatOrderData['CREATED_AT'],'Y-m-d')
            ]);
            unset($formatOrderData, $formatOrderGoodsData, $everyData);

        }

        if( isset($goodsInsertData) && $goodsInsertData ) OrderGoodsShop::batchInsert($goodsInsertData);
        unset($newStartRow, $goodsInsertData,$decGoodsInsertData);

        return true;
    }

    /**
     * 检测导入状态
     * @param $orderDay
     * @param $orderType
     * @throws Exception
     * @throws \yii\db\Exception
     */
    public function checkStatus($orderDay,$orderType) {
//        if( !$periodNum ) {
//            throw new Exception('期数不能为空');
//        }
        $periodData = Period::getPeriodFromTime(strtotime($orderDay));
        if(!$periodData){
            throw new Exception('期数有误');
        }
        $periodNum = $periodData['PERIOD_NUM'];
        //检查是否已经导入过了
        //$excelPeriodData = ExcelOrderShop::find()->where('PERIOD_NUM=:PERIOD_NUM', [':PERIOD_NUM'=>$periodNum])->asArray()->one();
        if($orderType=='cash'){
            $ot = 'FX';
        }else{
            $ot = 'PT';
        }
        $excelPeriodData = ExcelOrderShop::find()->where("ORDER_DAY=:ORDER_DAY AND ORDER_TYPE=:ORDER_TYPE", [':ORDER_DAY'=>$orderDay,':ORDER_TYPE'=>$ot])->asArray()->one();
        if( !$excelPeriodData ) {
            ExcelOrderShop::insertOne(
                [
                    'ID' => SnowFake::instance()->generateId(),
                    'PERIOD_NUM' => $periodNum,
                    'ORDER_DAY' => $orderDay,
                    'ORDER_TYPE' => $ot,
                    'STATUS' => 0,
                    'CREATED_AT' => Date::nowTime(),
                ]
            );
        }
//            if( $excelPeriodData['STATUS'] == 1 ) {
//                throw new Exception(sprintf('%s订单已经导入过了，不可以重复导入', $orderDay));
//            }


        //清空已经导入的数据
        $this->_clearPeriodOrder($orderDay,$orderType);
    }

    protected function _clearPeriodOrder($orderDay,$orderType) {
        OrderShop::pageDeleteAll("ORDER_DAY='".$orderDay."' and PAY_TYPE='".$orderType."'");
        OrderGoodsShop::pageDeleteAll("ORDER_DAY='".$orderDay."' and PAY_TYPE='".$orderType."'");
    }

    public function finished($orderDay,$orderType) {
        if( !$orderDay ) return false;

        if($orderType=='cash'){
            $ot = 'FX';
        }else{
            $ot = 'PT';
        }
        ExcelOrderShop::updateAll(['STATUS' => 1], "ORDER_DAY=:ORDER_DAY AND ORDER_TYPE=:ORDER_TYPE", [':ORDER_DAY'=>$orderDay,':ORDER_TYPE'=>$ot]);
        return true;
    }

    public function excelTime($orderDay,$format='Y-m-d H:i:s') {
        if(is_numeric($orderDay)){
            $t1 = intval(($orderDay - 25569) * 3600 * 24);
            $orderDay=gmdate($format,$t1);
        }
        return $orderDay;
    }



}