<?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\User;
use common\components\Redis;
use common\helpers\Cache;
use common\helpers\Date;
use common\helpers\Form;
use common\helpers\Log;
use common\helpers\Tool;
use common\models\CalcBonus;
use common\models\DecRole;
use common\models\forms\ClearDataForm;
use common\models\forms\ConfigBonusForm;
use common\models\forms\ConfigForm;
use common\models\forms\ConfigPeriodForm;
use common\models\forms\DecLevelForm;
use common\models\forms\DecRoleForm;
use common\models\forms\RegTypeForm;
use common\models\forms\DeclarationLevelForm;
use common\models\forms\EmployLevelForm;
use common\models\FlowBonus;
use common\models\forms\OcrApiForm;
use common\models\forms\SmsApiForm;
use common\models\forms\SmsTemplateForm;
use common\models\forms\WithdrawLevelForm;
use common\models\OcrApi;
use common\models\PerfCompany;
use common\models\PerfMonth;
use common\models\Period;
use common\models\ReconsumePool;
use common\models\RegType;
use common\models\DeclarationLevel;
use common\models\EmployLevel;
use common\models\SmsApi;
use common\models\SmsTemplate;
use common\models\UserBonus;
use common\models\UserClose;
use common\models\UserInfo;
use common\models\UserNetwork;
use common\models\UserRelation;
use common\models\BaiduRegion;
use common\models\Region;
use common\models\WithdrawLevel;
use Yii;
use common\models\Config;
use yii\base\Exception;
use yii\helpers\Json;

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

    public function behaviors() {
        $behaviors = parent::behaviors();
        //$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
        return $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('更新站点设置成功');
            } 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']);
            }
        }
        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']);
            }
        }
        // 获取会员报单级别的相关参数
        $decLevel = DeclarationLevel::find()->orderBy('SORT ASC')->asArray()->all();
        // 获取会员聘级相关参数
        // $empLevel = EmployLevel::getAllDataWithNumIndex();
        $result = [
            'config' => $configs,
            'decLevel' => $decLevel,
            // 'empLevel' => $empLevel,
        ];
        return static::notice($result);
    }

    /**
     * 基本奖金设置
     * @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('更新奖金配置成功');
            } 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('更新级别奖金配置成功');
            } 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('更新聘级奖金配置成功');
            } 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('期数已开始更新');
            } 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']);
            }
        }
        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, 'OcrApi配置成功', 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, 'SmsApi配置成功', 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('更新短信配置成功');
            } 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('更新转账配置成功');
            } 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']);
            }
        }
        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('更新分数配置成功');
            } 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']);
            }
        }
        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('更新其他配置成功');
            } 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('配置更新失败，请重试');
            }
            // Log::adminHandle('更新其他配置参数', 1);
            return static::notice('配置更新成功');
        }
        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']);
            }
        }
        return static::notice($configs);
    }

    /**
     *  查看报单级别
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDecLevel() {
        $data = DeclarationLevel::lists('', [], [
            'orderBy' => 'SORT ASC, CREATED_AT ASC'
        ]);
        return static::notice($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('更新观察期成功');
            } else {
                return static::notice('更新观察期失败，请重试');
            }
        }
        $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) {
                Cache::updateSystemConfig();
                $msg = $isOpen == 1 ? '开启' : '关闭';
                return static::notice("$msg,操作成功");
            } else {
                return static::notice('操作失败，请重试');
            }
        }
        return static::notice('非法请求');
    }

    /**
     *  查看报单中心级别
     * @return mixed
     * @throws \yii\web\HttpException
     */
    public function actionDecRole() {
        $data = DecRole::lists('', [], [
            'orderBy' => 'SORT ASC'
        ]);
        return static::notice($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, '报单中心级别修改成功', 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, '会员级别添加成功', null, null, null, function () {
                DeclarationLevel::updateToCache();
                // Log::adminHandle('添加会员级别', 1);
            });
        }
        return static::notice('非发请求', 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, '会员级别修改成功', null, null, null, function () {
                DeclarationLevel::updateToCache();
                // Log::adminHandle('编辑报单级别参数', 1);
            });
        }
        $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();
            // Log::adminHandle('删除报单级别', 1);
        });
    }

    /**
     *  查看会员聘级
     * @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, '会员聘级添加成功', null, null, null, function () {
                EmployLevel::updateToCache();
                // Log::adminHandle('添加会员聘级', 1);
            });
        }
        // 获取所有聘级，以供选择
        $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, '会员聘级修改成功', 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, '短信模板编辑成功', 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, '提现金额等级添加成功', 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, '提现金额等级修改成功', 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('数据不存在', 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('修改注册类型成功');
            } else {
                return static::notice(Form::formatErrorsForApi($formModel->getErrors()), 400);
            }
        }
        return static::notice('非法请求', 400);
    }

    /**
     * 获取服务协议
     * @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('更新服务协议成功');
    }

    /**
     * 获取当前在线用户
     * @return mixed
     * @throws \yii\base\InvalidConfigException
     * @throws \yii\web\HttpException
     */
    public function actionUserOnline() {
        $params = Yii::$app->request->get();
        $page = $params['page'];
        $pageSize = $params['pageSize'];
        $redisKey = $params['filterStatus'] == 1 ? 'user:timeOut' : 'admin:timeOut';
        $redisKeyUserInfo = 'user:baseInfo';

        $tokens = Yii::$app->tokenRedis->hgetall($redisKey);
        $timeOut = Yii::$app->params['operationTimeOut'];
        $currentTime = time();
        $user_info = [];
        if($tokens && is_array($tokens)){
            foreach($tokens as $k=>$v){
                //判断是否是hash的key
                $last_time = Yii::$app->tokenRedis->hget($redisKey,$v);
                if($last_time && ( $currentTime - $last_time < $timeOut )){
                    if( $params['filterStatus'] == 1){
                        $user_data = json_decode(Yii::$app->tokenRedis->hget($redisKeyUserInfo,$v),true);
                        $user_info['list'][$k]['ID'] = $user_data['USER_NAME'];
                        $user_info['list'][$k]['REAL_NAME'] = $user_data['REAL_NAME'];
                        $user_info['list'][$k]['UPDATE_TIME'] = date('Y-m-d H:i:s',$last_time);
                    } else {
                        $user_data = User::find()->where(['ID'=>$v])->asArray()->one();
                        $user_info['list'][$k]['ID'] = $user_data['ADMIN_NAME'];
                        $user_info['list'][$k]['REAL_NAME'] = $user_data['REAL_NAME'];
                        $user_info['list'][$k]['UPDATE_TIME'] = date('Y-m-d H:i:s',$last_time);
                    }

                }
            }
        }
        if($user_info){
            $user_info['list'] = array_values($user_info['list']);
            $totalCount = count($user_info['list']);
            $limit = ($page - 1) * $pageSize;
            array_multisort(array_column($user_info['list'],'UPDATE_TIME'), SORT_DESC,$user_info['list']);
            $user_info['list'] = array_slice($user_info['list'],$limit,$pageSize);
            $user_info['totalCount'] = $totalCount;
            $user_info['pageSize'] = $pageSize;
        }
        return static::notice($user_info);
    }

    public static function actionInitRegionXls() {
        BaiduRegion::deleteAll();
        BaiduRegion::importXls(0,1000);
        return static::notice('导入成功');
    }

    public static function actionRegion() {
        // 开始查找bd区划，先找县级和以上
//        $bdProv = BaiduRegion::_getBdProv();
//        foreach ($bdProv as $prov) {
//
//        }

        $bdCity = BaiduRegion::_getBdCity();
        print_r("检查新增地市".PHP_EOL);
        foreach ($bdCity as $city) {
            $p = BaiduRegion::_checkInNc($city['CITY_CODE']);
            if (!$p) {
                print_r($city['CITY_NAME'].'找不到，添加'.PHP_EOL);
//                print_r($city);
                if(BaiduRegion::addNcRegion($region_code=$city['CITY_CODE'], $region_name=$city['CITY_NAME'], $pid=$city['PROV_CODE'], $deep=3)){
                    print_r("添加成功".PHP_EOL);
                }else{
                    $regionM = Region::findOne(["REGION_CODE"=>$city['CITY_CODE']]);
                    $regionM->STATUS = 1;
                    $regionM->save();
                    print_r("启用成功".PHP_EOL);
                }
            }
        }

        $bdCounty = BaiduRegion::_getBdCounty();
//        print_r("检查新增县".PHP_EOL);
        foreach ($bdCounty as $county) {
            $p = BaiduRegion::_checkInNc($county['COUNTY_CODE']);
            if (!$p){
                print_r($county['COUNTY_NAME'].' 区县找不到，添加'.PHP_EOL);
//                print_r($county);
                if(BaiduRegion::addNcRegion($region_code=$county['COUNTY_CODE'], $region_name=$county['COUNTY_NAME'], $pid=$county['CITY_CODE'], $deep=4)){
//                    print_r("添加成功".PHP_EOL);
                }else{
                    $regionM = Region::findOne(["REGION_CODE"=>$county['COUNTY_CODE']]);
                    $regionM->STATUS = 1;
                    $regionM->save();
//                    print_r("启用成功".PHP_EOL);
                }
            }
        }

        $bdTown = BaiduRegion::_getBdTown(); // 只取省直辖县，直筒子市的乡镇
        print_r("检查新增地乡镇".PHP_EOL);
        foreach ($bdTown as $town) {
            $p = BaiduRegion::_checkInNc($town['TOWN_CODE']);
//            print_r($p);
            if (!$p) {
                print_r($town['TOWN_CODE'].$town['TOWN_NAME'].' 镇 找不到，添加'.PHP_EOL);
//                print_r($town);
                if(BaiduRegion::addNcRegion($region_code=$town['TOWN_CODE'], $region_name=$town['TOWN_NAME'], $pid=$town['COUNTY_CODE'], $deep=5)){
//                    print_r("添加成功".PHP_EOL);
                }else{
                    $regionM = Region::findOne(["REGION_CODE"=>$town['TOWN_CODE']]);
                    $regionM->STATUS = 1;
                    $regionM->save();
//                    print_r("启用成功".PHP_EOL);
                }
            }
        }

        $ncAllRegion = BaiduRegion::_getAllNcRegion();

        foreach ($ncAllRegion as $ncRegi) {
            if(strlen($ncRegi['REGION_CODE'])==9){
                $model = Region::findOne(["REGION_CODE"=>$ncRegi['REGION_CODE'], "STATUS"=>1]);
                $model->DEEP = 5;
                $model->save();
                $ncRegi['DEEP'] = 5;
            }
            $t = BaiduRegion::_checkInBd($ncRegi['REGION_CODE'], $ncRegi['REGION_NAME'], $ncRegi['PID'], $ncRegi['DEEP']);
            if(!$t){
//                print_r($ncRegi['REGION_CODE'].$ncRegi['REGION_NAME']." 在百度没有，标记删除".$ncRegi['DEEP'].PHP_EOL);
                $regionM = Region::findOne(["REGION_CODE"=>$ncRegi['REGION_CODE'], "STATUS"=>1]);
                $regionM->STATUS = '0';
                $regionM->save();
            } else {
                if($t['REGION_NAME']!=$ncRegi['REGION_NAME']) {
//                    print_r($ncRegi['REGION_CODE'] . $ncRegi['REGION_NAME'] . " 更名，需修改" . PHP_EOL);
                    $regionM = Region::findOne(["REGION_CODE"=>$ncRegi['REGION_CODE'], "STATUS"=>1]);
                    $regionM->REGION_NAME = $t['REGION_NAME'];
                    $regionM->save();
                }
                if($t['PID']!=$ncRegi['PID']){
//                    print_r($ncRegi['REGION_CODE'] . $ncRegi['REGION_NAME'] . " 上级".$ncRegi['PID']."需修改". $t['PID'] . PHP_EOL);
                    $regionM = Region::findOne(["REGION_CODE"=>$ncRegi['REGION_CODE'], "STATUS"=>1]);
                    $regionM->PID = $t['PID'];
                    $regionM->save();
                }
            }
        }

        return static::notice('更新成功');
    }

    public function actionRegionJs() {
        $ncProv = BaiduRegion::_getAllNcProv();
//        print_r($ncProv);

        $prov_list = [];
        $ar_region_array = [
            '86' => $prov_list
        ];

        foreach ($ncProv as $prov) {
            $ar_region_array['86'][$prov['REGION_CODE']] = $prov['REGION_NAME'];
            $ar_region_array[$prov['REGION_CODE']] = [];
        }

        // 普通地市，直筒子市
        $ncCity = BaiduRegion::_getAllNcCity();
        foreach($ncCity as $city){
            $ar_region_array[$city['PID']][$city['REGION_CODE']] = $city['REGION_NAME'];
            $ncCounty = BaiduRegion::_getAllNcCountyByCity($city['REGION_CODE']);
            foreach ($ncCounty as $county) {
                $ar_region_array[$city['REGION_CODE']][$county['REGION_CODE']] = $county['REGION_NAME'];
            }
        }

        // 直辖县级市
        $ncHighCounty = BaiduRegion::_getAllNcCounty();
        foreach ($ncHighCounty as $county) {
            $ar_region_array[$county['PID']][$county['REGION_CODE']] = $county['REGION_NAME'];
            $ncTown = BaiduRegion::_getAllNcTownByCity($county['REGION_CODE']);
            foreach ($ncTown as $town) {
                $ar_region_array[$county['REGION_CODE']][$town['REGION_CODE']] = $town['REGION_NAME'];
            }
        }

        $ar_region_data = json_encode($ar_region_array,JSON_UNESCAPED_UNICODE);
        $str = (string)$ar_region_data;
        $str = "const AR_REGION_DATA = ".$str;

        file_put_contents("/Volumes/HDD/workshop/old/ar.upload.ming/cdn/jsdata/ar_region_data.js", $str);

        return static::notice('生成JS成功');
    }

    public function actionRenewRegionCache() {
        if(Region::updateToCache()){
            return static::notice('刷新成功');
        } else {
            return static::notice('刷新失败');
        }
    }

}
