<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\LoggerTool;
use common\helpers\snowflake\PageSnowFake;
use common\libs\logging\operate\AdminOperate;
use common\models\Currency;
use common\models\CurrencyConversions;
use common\models\Period;
use common\models\ShopGoods;
use StatusEnum;
use Yii;
use yii\base\Exception;

/**
 * Login form
 */
class CurrenciesConversionsForm extends Model
{
    public $modelClass = CurrencyConversions::class;

    public $from_currency_id = Currency::USD; // 美元USD
    public $to_currency_id;
    public $product_rate;
    public $bonuses_rate;
    public $synchronize;

    private $period;

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

        $this->period = Period::instance();
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['from_currency_id', 'to_currency_id', 'product_rate', 'bonuses_rate'], 'required'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'from_currency_id' => 'From Currency Name', // 源汇率
            'to_currency_id' => 'To Currency Name', // 目标汇率
            'product_rate' => 'Product Rate', // 商品汇率
            'bonuses_rate' => 'Bonuses_rate Rate', // 奖金汇率
        ];
    }

    /**
     * 指定场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'setCurrenciesConversions' => ['from_currency_id', 'to_currency_id', 'product_rate', 'bonuses_rate'],
        ];

        return array_merge($parentScenarios, $customScenarios);
    }


    /**
     * 设置汇率.
     * @return true
     * @throws \yii\db\Exception
     */
    public function setCurrenciesConversions(): ?bool
    {
        if (!$this->validate()) {
            return null;
        }

        $postData = \Yii::$app->request->post();

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            // 删除原记录
            $this->modelClass::deleteOne($this->from_currency_id, $this->to_currency_id);
            // 添加新数据
            $model = new CurrencyConversions();
            $model->ID = PageSnowFake::instance()->generateId();
            $model->PERIOD_NUM = $this->period->getNowPeriodNum();
            $model->FROM_CURRENCY_ID = $this->from_currency_id;
            $model->TO_CURRENCY_ID = $this->to_currency_id;
            $model->PRODUCT_RATE = $this->product_rate;
            $model->BONUSES_RATE = $this->bonuses_rate;
            $model->CREATED_AT = date('Y-m-d H:i:s', Date::nowTime());
            $model->CREATED_BY = \Yii::$app->user->id;
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }

            // 选择商品汇率同步,更新商品属性
            if ($postData['synchronize']) {
                // 异步属性商品价格
                $taskKey = \Yii::$app->swooleAsyncTimer->asyncHandle('config/update-exchange-rate', ['currencyId' => $model->ID]);
                if($taskKey === false){
                    throw new \yii\db\Exception('请求异步服务器失败');
                }
            }

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('edit', $e->getMessage());
            return null;
        }

        return true;
    }
}
