<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/5/005
 * Time: 9:50
 */

namespace backend\controllers;

use backend\models\Config;

class ConfigController extends BaseController
{
    const EVENT_CMD_DEL = 'del';

    /**
     * 获取配置详情
     */
    public function actionGetConfig()
    {
        $cache = \Yii::$app->cache;
        $config = $cache->get('config');
        if ($config == null) {
            $config = Config::findOne(1);
            $cache->set('config', $config, 86400);
        }
        return $this->outJson(1, $config);
    }
    
    /**
     * 更新配置
     */
    public function actionUpdate()
    {
        $request = \Yii::$app->request->getBodyParams();
        $config = Config::findOne(1);
        $config->setAttributes($request, false);
        if ($config->save()) {
            $cache = \Yii::$app->cache;
            $cache->set('config', Config::findOne(1));
        }
        $configModel = new Config();
        // 事件的绑定
        $this->on(self::EVENT_CMD_DEL, [$configModel, 'updateEvent']);
        // 事件的触发
        $this->trigger(self::EVENT_CMD_DEL);
        
        return $this->outJson(1, $config, '操作成功');
    }

    /**
     * 清除缓存
     */
    public function actionClearCache()
    {
        $cache = \Yii::$app->cache;
        $cache->flush();

        $config = Config::findOne(1);
        $cache->set('CacheDepositJob', false);
        $cache->set('CacheVolumeJob', false);
        $cache->set('CommissionJobRun', false);
        $cache->set('CommissionJobRunTime', $config->commission_deal_time);
        $cache->set('config', $config);
        return $this->outJson(1, $cache, '操作成功');
    }
}