<?php


namespace frontend\modules\api\controllers;


use common\components\AjaxException;
use common\models\AccidentCasesScore;
use common\models\AccidentCasesScoreConfig;
use common\services\AccidentCasesScoreConfigService;
use common\services\AccidentCasesScoreService;
use frontend\modules\api\components\BaseAdminController;
use Yii;
use yii\db\Exception;
use yii\web\Response;

class AccidentCasesScoreConfigController extends BaseAdminController
{
    /**
     * 评价打分显示配置
     * @return Response
     */
    public function actionInfo()
    {
        $id = 1;
        $AccidentCasesScoreConfig = AccidentCasesScoreConfig::findOne($id);
        //组合数据
        $data['data'] = json_decode($AccidentCasesScoreConfig->content, true);
        return $this->asJson($data);
    }

    /**
     * 评价打分显示配置修改
     * @return Response
     * @throws AjaxException
     * @throws Exception
     */
    public function actionUpdate()
    {
        //方法不超时
        set_time_limit(0);
        //数据
        $data = Yii::$app->request->post()["data"];
        //验证权重数据是否错误
        foreach (AccidentCasesScoreService::$quanzhongConfig as $configKey => $configValue) {
            if (!isset($data[$configKey]) || $data[$configKey] <= 0) {
                throw new AjaxException("打分权重未配置或者权重小于等于0！");
            }
        }
        //修改数据
        $id = 1;
        $AccidentCasesScoreConfig = AccidentCasesScoreConfig::findOne($id);
        $AccidentCasesScoreConfig->content = json_encode($data, true);
        $AccidentCasesScoreConfig->update_time = time();
        $AccidentCasesScoreConfig->save();
        //根据权重将总分数据重新计算
        AccidentCasesScoreConfigService::setAccidentCasesScoreConfigUpdate();
        $needUpdateAccidentCasesScore = AccidentCasesScoreService::calculateTotalScoreAll();
        if ($needUpdateAccidentCasesScore != []) {
            $sql = $this->batchUpdate(AccidentCasesScore::tableName(), "id", "score", $needUpdateAccidentCasesScore, true);
            Yii::$app->db->createCommand($sql)->execute();
        }
        AccidentCasesScoreConfigService::clearAccidentCasesScoreConfigUpdate();
        return $this->asJson();
    }
}