<?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\OrderStandard;
use common\models\OrderStandardGoods;
use common\models\Period;
use common\models\User;
use common\models\UserInfo;
use Yii;
use yii\base\Exception;

class ExcelOrderStandardForm 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',
    ];

    /**
     * 导入excel数据
     * @param $excelData
     * @param $orderMonth
     * @param $payType
     * @return bool
     * @throws \yii\db\Exception
     */
    public function run($excelData,$orderMonth,$payType) {
        if( !$excelData ) return false;
        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']) ) continue;

            //判断商城订单是表中是否已经存在该订单
            $one = OrderStandard::find()->select(["USER_ID", "SN", "ORDER_AMOUNT", "PV", "PAY_AMOUNT", "PAY_PV"])->where('SN=:SN', ['SN' => $formatOrderGoodsData['ORDER_SN']])->asArray()->one();
            if ($one) {
                OrderStandard::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']
                ]);
            } 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,
                    'DELIVERY_STATUS' => $formatOrderData['DELIVERY_STATUS'] === '已发货' ? 1 : 0,
                    'CALC_MONTH' => $this->_getCalcMonth($orderMonth),
                ]);
                OrderStandard::insertOne($orderShopInsertData);
            }
            $goodsInsertData[] = array_merge($formatOrderGoodsData, [
                'CALC_MONTH' => $this->_getCalcMonth($orderMonth),
                'PAY_TYPE' => $payType,
            ]);
            unset($formatOrderData, $formatOrderGoodsData, $everyData);

        }

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

        return true;
    }

    /**
     * 检测导入状态
     * @param $orderMonth
     */
    public function checkStatus($orderMonth) {
        //清空已经导入的数据
        $this->_clearPeriodOrder($orderMonth);
    }

    protected function _clearPeriodOrder($orderMonth) {
        OrderStandard::pageDeleteAll("CALC_MONTH=".$this->_getCalcMonth($orderMonth));
        OrderStandardGoods::pageDeleteAll("CALC_MONTH=".$this->_getCalcMonth($orderMonth));
    }

    protected function _getCalcMonth($orderMonth) {
        return date('Ym', strtotime($orderMonth.'-01'));
    }

    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;
    }

    public function finished($orderMonth) {
        return true;
    }



}