<?php
namespace common\models\forms;

use common\components\Model;
use common\helpers\Date;
use common\libs\logging\operate\AdminOperate;
use common\models\Config;
use yii\db\Exception;
use yii\helpers\Json;

/**
 * Login form
 */
class ConfigForm extends Model
{
    const BONUS_TO_STRING_FIELD = [
        //共享奖
        'shareRecIncomeFrom',
        'shareIncomeFrom',
        //管理奖
        'parentOddIncomeFrom_0',
        'parentOddIncomeFrom_1',
        'parentOddIncomeFrom_2',
        'parentOddIncomeFrom_3',

        //共享奖-复消
        'fxShareRecIncomeFrom',
        'fxShareIncomeFrom',
        //管理奖
        'fxParentOddIncomeFrom_0',
        'fxParentOddIncomeFrom_1',
        'fxParentOddIncomeFrom_2',
        'fxParentOddIncomeFrom_3',
        //服务奖
        'decRoleBonusFrom',
    ];

    const BONUS_JSON_FIELD = [
        'jxStandard'
    ];

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

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            //[['postData'], 'required'],
        ];
    }

    public function attributeLabels()
    {
        return [
            //'postData' => '传入数据',
        ];
    }

    /**
     * 更新配置
     * @return bool|null
     * @throws Exception
     */
    public function updateBase(){
        if(!$this->validate()){
            return null;
        }
        $configs = Config::find()->where("TYPE='base'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        $configNames = [];
        foreach ($configs as $value){
            $configNames[] = $value['CONFIG_NAME'];
        }
        $beforeData = Config::getConfigByType('base');
        $this->adminOperateLogger->saveBeforeContent=$beforeData;
        $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]);
                }
            }
            $transaction->commit();
        } catch (Exception $e){
            $transaction->rollBack();
            $this->addError('updateBase', $e->getMessage());
            return null;
        }
        $afterData = Config::getConfigByType('base');
        // 关闭会员端,清空redis
        if (is_array($postData) && isset($postData['siteClose']) && $postData['siteClose'] === true) {
            \Yii::$app->redis->flushdb();
        }
        $this->adminOperateLogger->saveAfterContent=$afterData;
        unset($beforeData,$afterData);
        $this->adminOperateLogger->clean()->save([
            'optType' => '更新站点设置',
        ]);
        return true;
    }

    /**
     * 更新奖金配置
     * @return bool|null
     * @throws Exception
     */
    public function updateBonus(){
        if(!$this->validate()){
            return null;
        }
        $configs = Config::find()->where("TYPE='bonus'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        $configNames = [];
        foreach ($configs as $value){
            $configNames[] = $value['CONFIG_NAME'];
        }
        $beforeData = Config::getConfigByType('bonus');
        $this->adminOperateLogger->saveBeforeContent=$beforeData;
        $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;
                    if( in_array($key, self::BONUS_TO_STRING_FIELD) ) $postData[$key] = implode(",", $postData[$key]);
                    if( in_array($key, self::BONUS_JSON_FIELD) ) $postData[$key] = JSON::encode($postData[$key]);

                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
                }
            }
            $transaction->commit();
        } catch (Exception $e){
            $transaction->rollBack();
            $this->addError('updateBase', $e->getMessage());
            return null;
        }
        $afterData = Config::getConfigByType('bonus');
        $this->adminOperateLogger->saveAfterContent=$afterData;
        unset($beforeData,$afterData);
        $this->adminOperateLogger->clean()->save([
            'optType' => '更新奖金配置',
        ]);
        return true;
    }

    /**
     * 更新短信配置
     * @return bool|null
     * @throws Exception
     */
    public function updateSms(){
        if(!$this->validate()){
            return null;
        }
        $configs = Config::find()->where("TYPE='sms'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        $configNames = [];
        foreach ($configs as $value){
            $configNames[] = $value['CONFIG_NAME'];
        }
        $beforeData = Config::getConfigByType('sms');
        $this->adminOperateLogger->saveBeforeContent=$beforeData;
        $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;
                    if(is_array($postData[$key])) $postData[$key] = implode(",", $postData[$key]);
                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
                }
            }
            $transaction->commit();
        } catch (Exception $e){
            $transaction->rollBack();
            $this->addError('updateSms', $e->getMessage());
            return null;
        }
        $afterData = Config::getConfigByType('sms');
        $this->adminOperateLogger->saveAfterContent=$afterData;
        unset($beforeData,$afterData);
        $this->adminOperateLogger->clean()->save([
            'optType' => '更新短信配置',
        ]);
        return true;
    }

    /**
     * 更新转账配置
     * @return bool|null
     * @throws Exception
     */
    public function updateTransfer(){
        if(!$this->validate()){
            return null;
        }
        $configs = Config::find()->where("TYPE='transfer'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        $configNames = [];
        foreach ($configs as $value){
            $configNames[] = $value['CONFIG_NAME'];
        }
        $beforeData = Config::getConfigByType('transfer');
        $this->adminOperateLogger->saveBeforeContent=$beforeData;
        $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;
                    if(is_array($postData[$key])) $postData[$key] = Json::encode($postData[$key]);
                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
                }
            }
            $transaction->commit();
        } catch (Exception $e){
            $transaction->rollBack();
            $this->addError('updateTransfer', $e->getMessage());
            return null;
        }
        $afterData = Config::getConfigByType('transfer');
        $this->adminOperateLogger->saveAfterContent=$afterData;
        unset($beforeData,$afterData);
        $this->adminOperateLogger->clean()->save([
            'optType' => '更新转账配置',
        ]);
        return true;
    }

    /**
     * 更新分数配置
     * @return bool|null
     * @throws Exception
     */
    public function updateScore(){
        if(!$this->validate()){
            return null;
        }
        $configs = Config::find()->where("TYPE='score'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        $configNames = [];
        foreach ($configs as $value){
            $configNames[] = $value['CONFIG_NAME'];
        }
        $beforeData = Config::getConfigByType('score');
        $this->adminOperateLogger->saveBeforeContent=$beforeData;
        $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;
                    if(is_array($postData[$key])) $postData[$key] = Json::encode($postData[$key]);
                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
                }
            }
            $transaction->commit();
        } catch (Exception $e){
            $transaction->rollBack();
            $this->addError('updateScore', $e->getMessage());
            return null;
        }
        $afterData = Config::getConfigByType('score');
        $this->adminOperateLogger->saveAfterContent=$afterData;
        unset($beforeData,$afterData);
        $this->adminOperateLogger->clean()->save([
            'optType' => '更新分数配置',
        ]);
        return true;
    }

    /**
     * 更新其他配置
     * @return bool|null
     * @throws Exception
     */
    public function updateOther(){
        if(!$this->validate()){
            return null;
        }
        $configs = Config::find()->where("TYPE='other'")->orderBy('SORT ASC')->indexBy('CONFIG_NAME')->asArray()->all();
        $configNames = [];
        foreach ($configs as $value){
            $configNames[] = $value['CONFIG_NAME'];
        }
        $beforeData = Config::getConfigByType('other');
        $this->adminOperateLogger->saveBeforeContent=$beforeData;
        $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;
                    if(is_array($postData[$key])) $postData[$key] = implode(",", $postData[$key]);
                    Config::updateAll(['VALUE' => $postData[$key], 'UPDATED_AT' => Date::nowTime()], "CONFIG_NAME=:CONFIG_NAME", [':CONFIG_NAME' => $key]);
                }
            }
            $transaction->commit();
        } catch (Exception $e){
            $transaction->rollBack();
            $this->addError('updateOther', $e->getMessage());
            return null;
        }
        $afterData = Config::getConfigByType('other');
        $this->adminOperateLogger->saveAfterContent=$afterData;
        unset($beforeData,$afterData);
        $this->adminOperateLogger->clean()->save([
            'optType' => '更新其他配置',
        ]);
        return true;
    }
}
