<?php
namespace console\controllers;


use common\helpers\Cache;
use common\helpers\Excel;
use common\helpers\snowflake\SnowFake;
use common\helpers\user\Info;
use common\models\OrderGoodsShop;
use common\models\OrderShop;
use common\models\TmpOldNetwork;
use common\models\UserInfo;

/**
 * Class ImportOrderController
 * @package console\controllers
 */
class ImportOrderController extends BaseController
{
    const LIMIT = 1000;
    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',
    ];

    public function actionRun($fileName, $rowCount=1000, $startRow=1)
    {
        ini_set('memory_limit','512M');
        $pageCount = ceil($rowCount/self::LIMIT);
        $excel = new Excel();
        for($page=1;$page<=$pageCount;$page++) {
            $newStartRow = $startRow + self::LIMIT * ($page - 1);
            $result = $excel->pageImportDataByExcelFile($fileName, $rowCount, $newStartRow, self::LIMIT);

            $goodsInsertData = [];
            foreach ($result 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 = OrderShop::find()->select(["SN", "ORDER_AMOUNT", "PV", "PAY_AMOUNT", "PAY_PV"])->where('SN=:SN', ['SN'=>$formatOrderGoodsData['ORDER_SN']])->asArray()->one();
                if( $one ){
                    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']
                    ]);
                }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($formatOrderData['PAY_AT']),
                        'DELIVERY_AT' => strtotime($formatOrderData['DELIVERY_AT']),
                        'CREATED_AT' => strtotime($formatOrderData['CREATED_AT']),
                        'CREATE_USER' => $formatOrderData['USER_NAME'],
                        'PAY_TYPE' => 'cash',//@todo
                        'STATUS' => 1,
                        'P_CALC_MONTH' => date('Y-m-d', strtotime($formatOrderData['CREATED_AT'])),
                        'DELIVERY_STATUS' => $formatOrderData['DELIVERY_STATUS'] === '已发货' ? 1 : 0,

                    ]);
                    OrderShop::insertOne($orderShopInsertData);
                    unset($orderShopInsertData, $userInfoArr);
                }

                $goodsInsertData[] = array_merge($formatOrderGoodsData, [
                    'P_CALC_MONTH' => date('Y-m-d', strtotime($formatOrderData['CREATED_AT']))
                ]);
                unset($formatOrderData, $formatOrderGoodsData, $everyData);
            }

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

            echo sprintf("文件：【%s】页数：【%s】导入成功".PHP_EOL, $fileName, $page);
        }
    }




}