<?php
namespace common\models\forms;

use backendApi\modules\v1\models\Admin;
use common\components\Model;
use common\helpers\Cache;
use common\helpers\Date;
use common\models\DeclarationPackage;
use yii\base\Exception;

/**
 * Login form
 */
class DecPackageForm extends Model
{
    public $selectedIds;
    public $id;
    public $packageName;
    public $packageNo;
    public $amount;
    public $amountStandard;
    public $amountPv;
    public $levelId;
    public $packageContent;
    public $status;
	public $storenums;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'packageName','packageNo', 'amount', 'amountPv', 'levelId','packageContent','status'], 'trim'],
            [['packageName','packageNo', 'amount', 'amountPv', 'levelId','packageContent','status', 'amountStandard'], 'required'],
            [['id'], 'required', 'on'=>'edit'],
            [['id'], 'exist', 'targetClass'=>DeclarationPackage::class, 'targetAttribute'=>'ID'],
            [['amount','amountPv'], 'price'],
            [['selectedIds'], 'isSelected'],
			[['storenums'],'number'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'selectedIds' => '套餐IDs',
            'id' => '套餐ID',
            'packageName' => '套餐名称',
            'packageNo' => '套餐编号',
            'amount' => '套餐金额',
            'amountStandard' => 'US price',
            'amountPv' => '套餐BV',
            'levelId' => '所属报单级别',
            'packageContent' => '套餐详情',
			'storenums' => '套餐库存',
        ];
    }

    /**
     * 指定场景
     * @return array
     */
    public function scenarios()
    {
        $parentScenarios =  parent::scenarios();
        $customScenarios = [
            'add' => ['packageName','packageNo','amount','amountPv','levelId', 'packageContent', 'amountStandard','storenums'],
            'edit' => ['id','packageName','packageNo','amount','amountPv', 'levelId', 'packageContent', 'amountStandard','storenums'],
            'changeStatus' => ['selectedIds', 'status'],
        ];
        return array_merge($parentScenarios, $customScenarios);
    }

    /**
     * 批量数据
     * @param $attributes
     */
    public function isSelected($attributes) {
        if (!$this->selectedIds) {
            $this->addError($attributes, 'A piece of data must be selected'); // 必须选择一条数据
        }
        if (!is_array($this->selectedIds)) {
            $this->selectedIds = [$this->selectedIds];
        }
    }

    /**
     * 编辑
     * @return DeclarationPackage|null|static
     */
    public function edit(){
        if(!$this->validate()){
            return null;
        }

        // 汇率：TODO：可优化为指定是否需要根据汇率生成
        $exchangeRate = floatval(Cache::getSystemConfig()['exchangeRate']['VALUE'] ?? 0);

        if($this->scenario == 'add'){
            $model = new DeclarationPackage();
            $model->CREATE_ADMIN = Admin::getAdminNameById(\Yii::$app->user->id);
            $model->CREATED_AT = Date::nowTime();
        } elseif($this->scenario == 'edit') {
            $model = DeclarationPackage::findOne(['ID'=>$this->id]);
            $model->UPDATE_ADMIN = Admin::getAdminNameById(\Yii::$app->user->id);
            $model->UPDATED_AT = Date::nowTime();
        } else {
            $this->addError('id', '提交场景不存在');
            return null;
        }
        $model->PACKAGE_NAME = $this->packageName;
        $model->PACKAGE_NO = $this->packageNo;
        $model->AMOUNT = $this->amount;
        $model->PV = $this->amountPv;
        $model->LEVEL_ID = $this->levelId;
        $model->PACKAGE_CONTENT = $this->packageContent;
        $model->AMOUNT_STANDARD = $this->amountStandard;
        $model->STORE_NUMS = $this->storenums;
        if($model->save()){
            return $model;
        } else {
            $this->addErrors($model->getErrors());
            return null;
        }
    }

    /**
     * 上下架
     * @return null|static
     * @throws \yii\db\Exception
     */
    public function changeStatus() {
        if (!$this->validate()) {
            return null;
        }
        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            foreach ($this->selectedIds as $select) {
                $oneGoods = DeclarationPackage::findOne(['ID' => $select]);
                //判断状态
                if (($msg = DeclarationPackage::chkAuditStatus($oneGoods->STATUS, $this->status)) != '') {
                    throw new Exception($msg);
                }
                $oneGoods->STATUS = $this->status;
                $oneGoods->UPDATED_AT = Date::nowTime();
                if (!$oneGoods->save()) {
                    throw new Exception(Form::formatErrorsForApi($oneGoods->getErrors()));
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            $this->addError('changeStatus', $e->getMessage());
            return null;
        }
        return ['status' => $this->status];
    }

}
