<?php
namespace common\models\forms;

use common\helpers\Date;
use common\components\Model;
use common\helpers\Form;
use common\helpers\Tool;
use common\helpers\user\Info;
use common\libs\logging\operate\AdminOperate;
use common\models\Countries;
use common\models\CurrencyConversions;
use common\models\EmployLevel;
use common\models\HighestEmpLevelLog;
use common\models\Period;
use common\models\User;
use common\models\UserBonus;
use common\models\UserImmigrant;
use common\models\UserWallet;
use Yii;
use yii\base\Exception;

/**
 * Login form
 */
class ImmigrantForm extends Model
{
    public $userName;
    public $beforeCountryId;
    public $afterCountryId;
    public $periodNum;
    private $_userId;
    private $beforeCountry;
    private $afterCountry;

    public function init() {
        parent::init();
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['userName'], 'trim'],
            [['userName', 'afterCountryId'], 'required'],
            [['userName'], 'exist', 'targetClass' => User::class, 'targetAttribute' => 'USER_NAME'],
            [['userName'], 'isUser'],
            [['afterCountryId'], 'isAfterCountry'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'userName' => '会员编号',
            'beforeCountryId' => '移民前国家ID',
            'afterCountryId' => '移民后国家ID',
            'periodNum' => '期数',
        ];
    }

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

    /**
     * 赋值UserId并校验会员是否存在
     * @param $attribute
     */
    public function isUser($attribute){
        $this->_userId = Info::getUserIdByUserName($this->userName);
        if (!$this->_userId) {
            $this->addError($attribute, Yii::t('ctx', 'memberDoesNotExist'));
        }

        $this->beforeCountryId = Info::getUserCountryByUserId($this->_userId);
        $this->beforeCountry = Countries::getById($this->beforeCountryId);
    }

    public function isAfterCountry($attribute){
        $this->afterCountry = Countries::getById($this->afterCountryId);
        if (!$this->afterCountry) {
            $this->addError($attribute, Yii::t('ctx', 'countryDoesNotExist'));
        }
    }

    /**
     * 执行移民.
     */
    public function userImmigrant()
    {
        if (!$this->validate()) {
            return null;
        }

        $db = \Yii::$app->db;
        $transaction = $db->beginTransaction();
        try {
            // 移民记录
            $model = new UserImmigrant();
            $model->user_id = $this->_userId;
            $model->before_country_id = $this->beforeCountryId;
            $model->after_country_id = $this->afterCountryId;
            $model->period_num = Period::instance()->getNowPeriodNum();
            $model->created_by = \Yii::$app->user->id;
            if (!$model->save()) {
                throw new Exception(Form::formatErrorsForApi($model->getErrors()));
            }

            // 修改国家
            User::updateAll(['COUNTRY_ID' => $this->afterCountryId], 'ID=:USER_ID', [':USER_ID' => $this->_userId]);

            // 移民前汇率
            $beforeCurrency = CurrencyConversions::getToUSDRate($this->beforeCountry['LOCAL_CURRENCY_ID']);
            // 移民后汇率
            $afterCurrency = CurrencyConversions::getToUSDRate($this->afterCountry['LOCAL_CURRENCY_ID']);
            if (!$afterCurrency) {
                throw new Exception(Yii::t('app', 'currencyDoesNotExist'));
            }

            // 奖金账户余额转换(NG发放奖金为美元,所以不需要转换本地货币)
//            $userBonus = UserBonus::findOne(['USER_ID' => $this->_userId]);
//            if ($userBonus) {
//                foreach ($userBonus as $index => $bonus) {
//                    if ($index == 'ID' || $index == 'USER_ID') {
//                        continue;
//                    }
//
//                    $userBonus->$index = Tool::convertAmount($bonus, $beforeCurrency, $afterCurrency);
//                }
//                if (!$userBonus->save()) {
//                    $transaction->rollBack();
//                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
//                }
//            }

            // 现金钱包余额转换
            $userWallet = UserWallet::findOne(['USER_ID' => $this->_userId]);
            if ($userWallet && $userWallet->CASH > 0) {
                $userWallet->CASH = Tool::convertAmount($userWallet->CASH, $beforeCurrency, $afterCurrency);
                if (!$userWallet->save()) {
                    $transaction->rollBack();
                    throw new Exception(Form::formatErrorsForApi($model->getErrors()));
                }
            }

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

        return $model;
    }
}
