<?php
/**
 * Created by PhpStorm.
 * User: leo
 * Date: 2018/2/24
 * Time: 下午12:48
 */

namespace backendApi\modules\v1\controllers;

use backendApi\modules\v1\models\Admin;
use backendApi\modules\v1\models\AdminCountry;
use backendApi\modules\v1\models\AdminRole;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\LoggerTool;
use common\models\Countries;
use common\models\Currency;
use common\models\CurrencyConversions;
use common\models\DecRole;
use common\models\forms\ConfigForm;
use common\models\forms\ConfigPeriodForm;
use common\models\forms\CurrenciesConversionsForm;
use common\models\forms\DecLevelForm;
use common\models\forms\DecRoleForm;
use common\models\forms\FreeTemplateForm;
use common\models\forms\RegTypeForm;
use common\models\forms\DeclarationLevelForm;
use common\models\forms\EmployLevelForm;
use common\models\forms\OcrApiForm;
use common\models\forms\SmsApiForm;
use common\models\forms\SmsTemplateForm;
use common\models\forms\WithdrawLevelForm;
use common\models\FreeTemplate;
use common\models\OcrApi;
use common\models\RegType;
use common\models\DeclarationLevel;
use common\models\EmployLevel;
use common\models\SmsApi;
use common\models\SmsTemplate;
use common\models\WithdrawLevel;
use Yii;
use common\models\Config;
use yii\base\Exception;
use yii\helpers\Json;
use yii\web\HttpException;

class ConfigController extends BaseController {
    public $modelClass = Config::class;

    public $currencyModelClass = Currency::class;

    public $currencyConversionsModelClass = CurrencyConversions::class;

    public $freeTemplateModelClass = FreeTemplate::class;
    public $countiesModelClass = Countries::class;

    public function behaviors() {
        return parent::behaviors();
    }

    /**
     * 站点设置
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBase() {
        // 获取priod的相关配置参数
        $configs = Config::find()->where("TYPE='base'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();

        $form = new ConfigForm();
        if (Yii::$app->request->post() && $form->load(Yii::$app->request->post(), '')) {
            if ($form->updateBase()) {
                Config::updateToCache();
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 422);
            }
        }
        foreach ($configs as $key => $config) {
            if ($config['OPTIONS']) {
                $configs[$key]['OPTIONS'] = Json::decode($config['OPTIONS']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_SWITCH) {
                $configs[$key]['VALUE'] = boolval($config['VALUE']);
            }
            $configs[$key]['TITLE'] = Yii::t('ctx', $config['LANGUAGE_KEY']);
        }
        return static::notice($configs);
    }

    /**
     * 奖金相关配置
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBonusOpt() {
        $configs = Config::find()->where("TYPE='bonus'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        foreach ($configs as $key => $config) {
            if ($config['OPTIONS']) {
                $configs[$key]['OPTIONS'] = Json::decode($config['OPTIONS']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_SWITCH) {
                $configs[$key]['VALUE'] = boolval($config['VALUE']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_SELECT_MULTIPLE) {
                $configs[$key]['VALUE'] = explode(',', $config['VALUE']);
            }
            if($config['INPUT_TYPE'] == Config::INPUT_TYPE_TABLE) {
                $configs[$key]['VALUE'] = Json::decode($config['VALUE']);
            }
            $configs[$key]['TITLE'] = $config['LANGUAGE_KEY'] ? Yii::t('ctx', $config['LANGUAGE_KEY']) : $config['TITLE'];
        }

        return static::notice(['config' => $configs]);
    }

    /**
     * 基本奖金设置
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBonus() {
        $form = new ConfigForm();
        if (Yii::$app->request->post() && $form->load(Yii::$app->request->post(), '')) {
            if ($form->updateBonus()) {
                Config::updateToCache();
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 422);
            }
        }
    }

    /**
     * 修改会员级别相关的奖金配置
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBonusDecLevel() {
        $form = new DeclarationLevelForm();
        if (Yii::$app->request->post() && $form->load(Yii::$app->request->post(), '')) {
            if ($form->updateBonus()) {
                DeclarationLevel::updateToCache();
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 422);
            }
        }
    }

    /**
     * 修改奖金聘级相关的奖金配置
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionBonusEmpLevel() {
        $form = new EmployLevelForm();
        if (Yii::$app->request->post() && $form->load(Yii::$app->request->post(), '')) {
            if ($form->updateBonus()) {
                Cache::updateEmpLevelConfig();
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 422);
            }
        }
    }

    /**
     * 更新封期参数
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionPeriod() {
        $form = new ConfigPeriodForm();
        if (Yii::$app->request->post() && $form->load(Yii::$app->request->post(), '')) {
            if ($form->update()) {
                Config::updateToCache();
                // Log::adminHandle('更新封期参数', 1);
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 422);
            }
        }
        // 获取priod的相关配置参数
        $configs = Config::find()->where("TYPE='period'")->indexBy('CONFIG_NAME')->orderBy('SORT ASC')->asArray()->all();
        foreach ($configs as $key => $config) {
            if ($config['OPTIONS']) {
                $configs[$key]['OPTIONS'] = Json::decode($config['OPTIONS']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_SWITCH) {
                $configs[$key]['VALUE'] = boolval($config['VALUE']);
            }
            $configs[$key]['TITLE'] = Yii::t('ctx', $config['LANGUAGE_KEY']);
        }
        return static::notice($configs);
    }


    /**
     * 接口设置
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionApiOpt(){
        return static::notice('1');
    }

    /**
     *  查看OcrApi接口
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionOcrApi() {
        $condition = '';
        $params = [];
        $data = OcrApi::lists($condition, $params, [
            'select' => 'OA.*,ADMC.ADMIN_NAME CREATE_ADMIN_NAME,ADMU.ADMIN_NAME UPDATE_ADMIN_NAME',
            'from' => OcrApi::tableName() . ' AS OA',
            'join' => [
                ['LEFT JOIN', Admin::tableName() . ' AS ADMC', 'ADMC.ID=OA.CREATE_ADMIN'],
                ['LEFT JOIN', Admin::tableName() . ' AS ADMU', 'ADMU.ID=OA.UPDATE_ADMIN'],
            ],
            'orderBy' => 'OA.CREATED_AT ASC',
        ]);
        return static::notice($data);
    }


    /**
     * 修改OcrApi接口
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionOcrApiEdit() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return static::edit(OcrApiForm::class, Yii::t('ctx', 'successfully'), null, null, null, function () {
                OcrApi::updateToCache();
                // Log::adminHandle('编辑OCRAPI参数配置', 1);
            });
        }
        $oneData = OcrApi::find()->where('ID=:ID', [':ID' => $id])->asArray()->one();
        if ($oneData['CONFIG']) {
            $oneData['CONFIG'] = Json::decode($oneData['CONFIG']);
        }
        // 获取可供编辑的字段
        $oneData['apiType'] = '百度OCR';
        $oneData['CONFIGS'] = \common\helpers\ocr\OcrApi::apiConfigs($oneData['API_NAME']);

        return static::notice($oneData);
    }

    /**
     * 短信接口查看
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionSmsApi() {
        $condition = '';
        $params = [];
        $data = SmsApi::lists($condition, $params, [
            'select' => 'OA.*,ADMC.ADMIN_NAME CREATE_ADMIN_NAME,ADMU.ADMIN_NAME UPDATE_ADMIN_NAME',
            'from' => SmsApi::tableName() . ' AS OA',
            'join' => [
                ['LEFT JOIN', Admin::tableName() . ' AS ADMC', 'ADMC.ID=OA.CREATE_ADMIN'],
                ['LEFT JOIN', Admin::tableName() . ' AS ADMU', 'ADMU.ID=OA.UPDATE_ADMIN'],
            ],
            'orderBy' => 'OA.CREATED_AT ASC',
        ]);
        return static::notice($data);
    }

    /**
     * 短信接口编辑
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionSmsApiEdit() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return static::edit(SmsApiForm::class, Yii::t('ctx', 'successfully'), null, null, null, function () {
                SmsApi::updateToCache();
                // Log::adminHandle('编辑SMSAPI参数配置', 1);
            });
        }
        $oneData = SmsApi::find()->where('ID=:ID', [':ID' => $id])->asArray()->one();
        if ($oneData['CONFIG']) {
            $oneData['CONFIG'] = Json::decode($oneData['CONFIG']);
        }
        $oneData['apiType'] = '短信接口';
        // 获取可供编辑的字段
        $oneData['CONFIGS'] = \common\libs\api\sms\SmsApi::apiConfigs($oneData['API_NAME']);

        return static::notice($oneData);
    }

    /**
     * 短信配置
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionSms() {
        // 获取priod的相关配置参数
        $configs = Config::find()->where("TYPE='sms'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        $form = new ConfigForm();
        if (Yii::$app->request->post() && $form->load(Yii::$app->request->post(), '')) {
            if ($form->updateSms()) {
                Config::updateToCache();
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 422);
            }
        }
        foreach ($configs as $key => $config) {
            if ($config['OPTIONS']) {
                $configs[$key]['OPTIONS'] = Json::decode($config['OPTIONS']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_SWITCH) {
                $configs[$key]['VALUE'] = boolval($config['VALUE']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_SELECT) {
                $configs[$key]['VALUE'] = explode(",",$config['VALUE']);
            }
        }
        return static::notice($configs);
    }

    /**
     * 转账配置
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionTransfer() {
        // 获取priod的相关配置参数
        $configs = Config::find()->where("TYPE='transfer'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        $form = new ConfigForm();
        if (Yii::$app->request->post() && $form->load(Yii::$app->request->post(), '')) {
            if ($form->updateTransfer()) {
                Config::updateToCache();
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 422);
            }
        }
        foreach ($configs as $key => $config) {
            if ($config['OPTIONS']) {
                $configs[$key]['OPTIONS'] = Json::decode($config['OPTIONS']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_SWITCH) {
                $configs[$key]['VALUE'] = boolval($config['VALUE']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_TABLE) {
                $configs[$key]['VALUE'] = Json::decode($config['VALUE']);
            }
            $configs[$key]['TITLE'] = Yii::t('ctx', $config['LANGUAGE_KEY']);
        }
        return static::notice($configs);
    }

    /**
     * 分数配置
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionScore() {
        // 获取priod的相关配置参数
        $configs = Config::find()->where("TYPE='score'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        $form = new ConfigForm();
        if (Yii::$app->request->post() && $form->load(Yii::$app->request->post(), '')) {
            if ($form->updateScore()) {
                Config::updateToCache();
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 422);
            }
        }
        foreach ($configs as $key => $config) {
            if ($config['OPTIONS']) {
                $configs[$key]['OPTIONS'] = Json::decode($config['OPTIONS']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_SWITCH) {
                $configs[$key]['VALUE'] = boolval($config['VALUE']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_TABLE) {
                $configs[$key]['VALUE'] = Json::decode($config['VALUE']);
            }
            $configs[$key]['TITLE'] = Yii::t('ctx', $config['LANGUAGE_KEY']);
        }
        return static::notice($configs);
    }

    /**
     * 其他配置
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionOther() {
        // 获取priod的相关配置参数
        $configs = Config::find()->where("TYPE='other'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        $form = new ConfigForm();
        if (Yii::$app->request->post() && $form->load(Yii::$app->request->post(), '')) {
            if ($form->updateOther()) {
                Config::updateToCache();
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($form->getErrors()), 422);
            }
        }

        if (Yii::$app->request->post()) {
            $postData = Yii::$app->request->post();
            $transaction = Yii::$app->db->beginTransaction();
            try {
                foreach ($configs as $key => $value) {
                    if (array_key_exists($key, $postData)) {
                        if (!$postData[$key]) $postData[$key] = 0;
                        Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
                    }
                }
                Config::updateToCache();
                $transaction->commit();
            } catch (Exception $e) {
                $transaction->rollBack();
                return static::notice(Yii::t('ctx', 'failed'));
            }
            // Log::adminHandle('更新其他配置参数', 1);
            return static::notice(Yii::t('ctx', 'successfully'));
        }
        foreach ($configs as $key => $config) {
            if ($config['OPTIONS']) {
                $configs[$key]['OPTIONS'] = Json::decode($config['OPTIONS']);
            }
            if ($config['INPUT_TYPE'] == Config::INPUT_TYPE_SWITCH) {
                $configs[$key]['VALUE'] = boolval($config['VALUE']);
            }
            $configs[$key]['TITLE'] = Yii::t('ctx', $config['LANGUAGE_KEY']);
        }
        return static::notice($configs);
    }

    /**
     *  查看报单级别
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDecLevel() {
        $data = Cache::getDecLevelConfig();
        return static::notice(['list' => $data]);
    }

    public function actionMonthLimit() {
        if (Yii::$app->request->isPost) {
            $postData = Yii::$app->request->post();
            $month = $postData['month'];
            $ret = Config::updateAll(['VALUE' => $month, 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => 'observePeriodLimit']);
            if ($ret) {
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Yii::t('ctx', 'failed'));
            }
        }
        $data = Config::find()
        ->where("CONFIG_NAME='observePeriodLimit'")
        ->asArray()
        ->one();

        $isSwitchUpgrade = Config::find()
        ->where("CONFIG_NAME='isOpenUpgrade'")
        ->asArray()
        ->one();

        return static::notice([
            'observe' => $data,
            'isOpenUpgrade' => $isSwitchUpgrade
        ]);
    }

    // 开关会员升级单功能
    public function actionOpenUpgrade() {
        if (Yii::$app->request->isPost) {
            $postData = Yii::$app->request->post();
            $isOpen = $postData['isOpen'];
            $ret = Config::updateAll(
                ['VALUE' => $isOpen, 'UPDATED_AT' => Date::nowTime()], 
                "CONFIG_NAME=:CONFIG_NAME", 
                [':CONFIG_NAME' => 'isOpenUpgrade']
            );
            if ($ret) {
                $msg = $isOpen == 1 ? Yii::t('ctx', 'on') : Yii::t('ctx', 'off');
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Yii::t('ctx', 'failed'));
            }
        }
        return static::notice(Yii::t('ctx', 'illegalRequest'), 405);
    }

    /**
     *  查看报单中心级别
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDecRole() {
        $data = Cache::getDecRoleConfig();
        return static::notice(['list' => $data]);
    }

    /**
     * 修改报单中心级别
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDecRoleEdit() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return static::edit(DecRoleForm::class, Yii::t('ctx', 'successfully'), null, null, null, function () {
                DecRole::updateToCache();
            });
        }
        $oneData = DecRole::find()->where('ID=:ID', [':ID' => $id])->asArray()->one();
        return static::notice($oneData);
    }

    /**
     * 添加会员级别
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDecLevelAdd() {
        if (Yii::$app->request->isPost) {
            return static::edit(DecLevelForm::class, Yii::t('ctx', 'successfully'), null, null, null, function () {
                DeclarationLevel::updateToCache();
            });
        }
        return static::notice(Yii::t('ctx', 'illegalRequest'), 405);
    }

    /**
     * 修改会员级别
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDecLevelEdit() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return static::edit(DecLevelForm::class, Yii::t('ctx', 'successfully'), null, null, null, function () {
                DeclarationLevel::updateToCache();
            });
        }
        $oneData = DeclarationLevel::find()->where('ID=:ID', [':ID' => $id])->asArray()->one();
        return static::notice($oneData);
    }

    /**
     * 删除会员级别
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionDecLevelDelete() {
        return static::delete(DeclarationLevel::class, '', function ($selected) {
            DeclarationLevel::updateToCache();
        });
    }

    /**
     *  查看会员聘级
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionEmpLevel() {
        $data = EmployLevel::lists('', [], [
            'select' => 'E.*, ME.LEVEL_NAME AS MIN_EMPLOY_LEVEL_NAME',
            'from' => EmployLevel::tableName() . ' AS E',
            'join' => [
                ['LEFT JOIN', EmployLevel::tableName() . ' AS ME', 'ME.ID=E.MIN_EMPLOY_LEVEL']
            ],
            'orderBy' => 'E.SORT ASC, E.CREATED_AT ASC'
        ]);
        return static::notice($data);
    }

    /**
     * 添加会员聘级
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionEmpLevelAdd() {
        if (Yii::$app->request->isPost) {
            return static::edit(EmployLevelForm::class, Yii::t('ctx', 'successfully'), null, null, null, function () {
                EmployLevel::updateToCache();
            });
        }
        // 获取所有聘级，以供选择
        $allLevel = EmployLevel::find()->where('1=1')->orderBy('SORT ASC')->asArray()->all();
        return static::notice($allLevel);
    }

    /**
     * 修改聘级
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionEmpLevelEdit() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return static::edit(EmployLevelForm::class, Yii::t('ctx', 'successfully'), null, null, null, function () {
                EmployLevel::updateToCache();
                // Log::adminHandle('编辑会员聘级', 1);
            });
        }
        $oneData = EmployLevel::find()->where('ID=:ID', [':ID' => $id])->asArray()->one();
        // 获取所有聘级，以供选择
        $allLevel = EmployLevel::find()->where('1=1')->orderBy('SORT ASC')->asArray()->all();
        $oneData['allLevel'] = $allLevel;
        return static::notice($oneData);
    }

    /**
     * 删除聘级
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionEmpLevelDelete() {
        return static::delete(EmployLevel::class, '', function ($selected) {
            EmployLevel::updateToCache();
            // Log::adminHandle('删除会员聘级', 1);
        });
    }

    /**
     * 查看短信模板
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionSmsTemplate() {
        $data = SmsTemplate::lists('', [], ['orderBy' => 'CREATED_AT ASC']);
        return static::notice($data);
    }

    /**
     * 编辑短信模板
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionSmsTemplateEdit() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return parent::edit(SmsTemplateForm::class, Yii::t('ctx', 'successfully'), null, null, null, function () {
                SmsTemplate::updateDecToCache();
                SmsTemplate::updateEmpToCache();
                // Log::adminHandle('编辑短信模板', 1);
            });
        }
        $oneData = SmsTemplate::find()->where('ID=:ID', [':ID' => $id])->asArray()->one();
        return static::notice(['oneData' => $oneData]);
    }

    /**
     * 提现金额等级
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawLevel() {
        $data = WithdrawLevel::lists('', [], ['orderBy' => 'MIN_AMOUNT ASC']);
        return static::notice($data);
    }

    /**
     * 添加提现金额等级
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawLevelAdd() {
        if (Yii::$app->request->isPost) {
            return static::edit(WithdrawLevelForm::class, Yii::t('ctx', 'successfully'), null, null, null, function () {
                WithdrawLevel::updateToCache();
                // Log::adminHandle('添加提现金额等级', 1);
            });
        }
    }

    /**
     * 修改提现金额等级
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawLevelEdit() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            return static::edit(WithdrawLevelForm::class, Yii::t('ctx', 'successfully'), null, null, null, function () {
                WithdrawLevel::updateToCache();
                // Log::adminHandle('编辑提现金额等级', 1);
            });
        }
        $oneData = WithdrawLevel::find()->where('ID=:ID', [':ID' => $id])->asArray()->one();
        return static::notice($oneData);
    }

    /**
     * 删除提现金额等级
     * @return mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\HttpException
     */
    public function actionWithdrawLevelDelete() {
        return static::delete(WithdrawLevel::class, '', function ($selected) {
            WithdrawLevel::updateToCache();
        });
    }

    /**
     * 注册类型
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRegType() {
        $data = RegType::lists('', [], [
            'orderBy' => 'SORT ASC, CREATED_AT ASC'
        ]);
        return static::notice($data);
    }

    /**
     * 获取注册类型
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRegTypeGet() {
        $id = Yii::$app->request->get('id');
        $regType = RegType::findOneAsArray('ID=:ID', [':ID' => $id]);
        if (!$regType) {
            return static::notice(Yii::t('ctx', 'dataNotExists'), 400);
        }
        return static::notice(['id' => $regType['ID'], 'typeName' => $regType['TYPE_NAME'], 'isPact' => $regType['IS_PACT'], 'monthAmount' => $regType['MONTH_LIMIT_AMOUNT'], 'yearAmount' => $regType['YEAR_LIMIT_AMOUNT'], 'remark' => $regType['REMARK']]);
    }


    /**
     * 修改注册类型
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionRegTypeEdit() {
        $id = Yii::$app->request->get('id');
        if (Yii::$app->request->isPost) {
            $formModel = new RegTypeForm();
            $formModel->scenario = 'edit';
            $formModel->id = $id;
            if ($formModel->load(Yii::$app->request->post(), '') && $result = $formModel->edit()) {
                // Log::adminHandle('修改注册类型，ID为：' . $result['ID']);
                return static::notice(Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
        return static::notice(Yii::t('ctx', 'illegalRequest'), 405);
    }

    /**
     * 获取服务协议
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionPactGet() {
        $path = \Yii::getAlias('@common/runtime/datas/pact.php');
        if (!file_exists($path)) {
            $oneData = '';
        } else {
            $oneData = include $path;
        }
        return static::notice($oneData);
    }

    /**
     * 获取服务协议
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\web\HttpException
     */
    public function actionPactEdit() {
        $path = \Yii::getAlias('@common/runtime/datas/pact.php');
        $post = Yii::$app->request->post();
        if (!isset($post['CONTENT']) || empty($post['CONTENT'])) {
            return static::notice('请输入协议内容', 400);
        }
        $now = Date::nowTime();
        $data = [
            'UPDATED_AT' => $now,
            'CONTENT' => addslashes($post['CONTENT']),
            'ADM_NAME' => \Yii::$app->user->id,
        ];
        // Log::adminHandle('更新服务协议');
        $date = \Yii::$app->formatter->asDatetime($now);
        $content = "<?php" . PHP_EOL . "/**
 * 配置文件
 * @date {$date}
 */" . PHP_EOL;
        $content .= "return ";
        $content .= var_export($data, true);
        $content .= ";";
        file_put_contents($path, $content, LOCK_EX);
        return static::notice(Yii::t('ctx', 'successfully'));
    }

    public function actionCurrencies()
    {
        // 国家
        $countries = Cache::getCountries();
        // 货币
        $currencies = $this->currencyModelClass::getFromCache();
        // 汇率
        $currencyConversion = $this->currencyConversionsModelClass::getFromCache();

        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
        if (!$isSuper) {
            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
            $adminCountry = AdminCountry::getCountry($adminId);

            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
            $countries = array_values($countries);
        }

        $countriesCurrencyIds = array_column($countries, 'LOCAL_CURRENCY_ID');
        $currencyConversion = array_filter($currencyConversion, fn($item) => in_array($item['TO_CURRENCY_ID'], $countriesCurrencyIds));
        $currencyConversion = array_values($currencyConversion);
        $currencyConversion = array_column($currencyConversion, null, 'TO_CURRENCY_ID');

        $currencies = array_filter($currencies, fn($item) => in_array($item['ID'], $countriesCurrencyIds));
        $currencies = array_values($currencies);

        foreach ($currencies as &$currency) {
            $currency['PRODUCT_RATE'] = $currencyConversion[$currency['ID']]['PRODUCT_RATE'] ?? 0;
            $currency['BONUSES_RATE'] = $currencyConversion[$currency['ID']]['BONUSES_RATE'] ?? 0;
        }

        return static::notice(['data' => $currencies]);
    }

    /**
     * @throws \yii\db\Exception
     * @throws HttpException
     */
    public function actionSetCurrenciesConversions()
    {
        if (\Yii::$app->request->isPost) {
            $formModel = new CurrenciesConversionsForm();
            $formModel->scenario = 'setCurrenciesConversions';
            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->setCurrenciesConversions()) {
                // 更新缓存
                $this->currencyConversionsModelClass::updateToCache();

                return static::notice(\Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);

            }
        }

        return static::notice(\Yii::t('ctx', 'illegalRequest'));
    }

    public function actionTransportation()
    {
        // 国家列表
        $countries = $this->countiesModelClass::getFromCache();
        // 运费列表
        $transportation = $this->freeTemplateModelClass::getFromCache();

        $isSuper = AdminRole::isSuperAdmin(\Yii::$app->getUser()->getUserInfo()['roleId']);
        if (!$isSuper) {
            $adminId = Yii::$app->getUser()->getUserInfo()['id'];
            $adminCountry = AdminCountry::getCountry($adminId);

            $countries = array_filter($countries, fn($country) => in_array($country['ID'], $adminCountry));
            $countries = array_values($countries);
            $countriesId = array_column($countries, 'ID');

            $transportation = array_filter($transportation, fn($item) => in_array($item['country_id'], $countriesId));
            $transportation = array_values($transportation);
        }

        $transportation = array_column($transportation, NULL, 'country_id');

        foreach ($countries as &$country) {
            $country['freight'] = $transportation[$country['ID']]['freight'] ?? 0;
            $country['free_shipping'] = $transportation[$country['ID']]['free_shipping'] ?? 0;
            $country['currency'] = $this->currencyModelClass::getById($country['LOCAL_CURRENCY_ID']);
        }

        return static::notice(['data' => $countries]);
    }

    public function actionSetTransportation()
    {
        if (\Yii::$app->request->isPost) {
            $formModel = new FreeTemplateForm();
            $formModel->scenario = 'setTransportation';
            if ($formModel->load(\Yii::$app->request->post(), '') && $formModel->setTransportation()) {
                // 更新缓存
                $this->modelClass::updateToCache();

                return static::notice(\Yii::t('ctx', 'successfully'));
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);

            }
        }

        return static::notice(\Yii::t('ctx', 'illegalRequest'));
    }
}