<?php
namespace common\models\forms;

use backendApi\modules\v1\models\Admin;
use common\helpers\Date;
use common\components\Model;
use common\helpers\LoggerTool;
use common\libs\logging\operate\AdminOperate;
use common\models\DecOrder;
use common\models\FlowExchangePoints;
use common\models\FlowGaragePoints;
use common\models\FlowReconsumePoints;
use common\models\FlowTourismPoints;
use common\models\FlowVillaPoints;
use common\models\FlowWallet;
use common\models\Order;
use common\models\OrderPeriodAdjust;
use common\models\Period;
use common\models\User;
use common\models\UserInfo;
use Yii;

/**
 * OrderPeriodAdjustForm form
 */
class OrderPeriodAdjustForm extends Model
{
    public $orderSn;
    public $modernPeriod;

    public $order;

    public function init() {
        parent::init();
        $this->adminOperateLogger = new AdminOperate([
            'fetchClass' => OrderPeriodAdjust::class,
        ]);
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['orderSn', 'modernPeriod'], 'trim'],
            [['orderSn', 'modernPeriod'], 'required'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'orderSn' => '订单号',
            'modernPeriod' => '调整后期数',
        ];
    }

    /**
     * 指定校验场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'orderPeriodAdjust' => ['orderSn', 'modernPeriod'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 校验之前
     * @return bool
     */
    public function beforeValidate()
    {
        $parentValidate = parent::beforeValidate();
        // 校验订单
        $this->order = Order::findOne(['SN' => $this->orderSn, 'IS_DELETE' => 0]);
        if (!$this->order) {
            $this->addError('orderSn', Yii::t('ctx', 'orderNotExist'));
            return false;
        }
        // 目前期数：已封期、未挂网可调整
        $period = Period::getInfoByPeriodNum($this->modernPeriod);
        if (!$period) {
            $this->addError('modernPeriod', Yii::t('ctx', 'invalidPcNo'));
            return false;
        }
        if ($period['IS_SENT'] == 1) {
            $this->addError('orderSn', Yii::t('ctx', 'orderHasBeenConnected'));
            return false;
        }

        return $parentValidate;
    }

    /**
     * @return bool|null
     */
    public function periodAdjust()
    {
        if (!$this->validate()) {
            return null;
        }

        $this->adminOperateLogger->saveBeforeContent = Order::findOneAsArray('SN=:SN', [':SN' => $this->orderSn]);

        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            // 调整订单期数
            Order::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'SN = :SN', [':SN' => $this->orderSn]);

            if ($this->order->ORDER_TYPE === 'ZC') {
                // 调整报单期数
                DecOrder::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
                // 调整会员的期数
                User::updateAll(['PERIOD_AT' => $this->modernPeriod], 'ID = :USER_ID', ['USER_ID' => $this->order->USER_ID]);
                UserInfo::updateAll(['HIGHEST_EMP_LV_PERIOD' => $this->modernPeriod], 'USER_ID = :USER_ID', ['USER_ID' => $this->order->USER_ID]);
            }

            // 调整流水的期数
            switch ($this->order->PAY_TYPE){
                case 'cash':
                    FlowWallet::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
                    break;
                case 'exchange':
                    FlowExchangePoints::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
                    break;
                case 'tourism_points':
                    FlowTourismPoints::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
                    break;
                case 'garage_points':
                    FlowGaragePoints::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
                    break;
                case 'villa_points':
                    FlowVillaPoints::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
                    break;
                case 'reconsume_points':
                    FlowReconsumePoints::updateAll(['PERIOD_NUM' => $this->modernPeriod], 'ORDER_SN = :ORDER_SN', ['ORDER_SN' => $this->orderSn]);
                    break;
                default:
                    break;
            }

            // 写入调整记录
            $orderModel = new OrderPeriodAdjust();
            $orderModel->ORDER_SN = $this->orderSn;
            //$orderModel->DEC_SN = $this->order->DEC_SN ?? '';
            $orderModel->ORIGIN_PERIOD = $this->order->PERIOD_NUM;
            $orderModel->MODERN_PERIOD = $this->modernPeriod;
            $orderModel->ADMIN_ID = Admin::getAdminNameById(\Yii::$app->user->id);
            $orderModel->CREATED_AT = Date::nowTime();
            if (!$orderModel->save()) {
                $this->addErrors($orderModel->getErrors());
                return false;
            }
            $transaction->commit();
        } catch(\Exception $e) {
            $transaction->rollBack();
            $this->addError('periodAdjust', $e->getMessage());
            return null;
        }

        $this->adminOperateLogger->saveAfterContent = Order::findOneAsArray('SN=:SN', [':SN' => $this->orderSn]);
        $this->adminOperateLogger->clean()->save([
            'optType' => '调整订单期数',
        ]);

        return true;
    }
}
