<?php


namespace frontend\modules\api\controllers;


use common\components\AjaxException;
use common\models\EmergencyResponse;
use common\services\AccidentCasesScoreService;
use common\services\AdminLogService;
use common\services\CaseService;
use common\services\EmergencyResponseDimensionService;
use common\services\EmergencyResponseRelateToRulesPointsService;
use common\services\EmergencyResponseService;
use common\util\DealWithPostData;
use frontend\modules\api\components\BaseAdminController;
use Throwable;
use Yii;
use yii\base\InvalidConfigException;
use yii\db\Exception;
use yii\web\Response;

class EmergencyResponseController extends BaseAdminController
{
    /**
     * 应急处置列表
     * @param int $accident_id
     * @return Response
     * @throws AjaxException
     */
    public function actionList(int $accident_id)
    {
        if (!$accident_id) {
            throw new AjaxException("accident_id不存在！");
        }
        $query = EmergencyResponseService::getEmergencyResponseQuery()->andWhere(["accident_id" => $accident_id]);
        //排序
        $this->initSequence($query, "start_time desc");
        //主要筛选条件
        $query = $this->addConditionToQuery("type_first", $query);
        //组合数据
        $list = EmergencyResponseService::dealWithList($query->all(), $accident_id);
        EmergencyResponseService::listAddDimension($list);
        $list = EmergencyResponseService::getEmergencyResponseObjList($list);
        $data['data'] = $list;
        list($data['scoreList'], $data['totalScore']) = AccidentCasesScoreService::getEmergencyResponseScore($accident_id);
        return $this->asJson($data);
    }

    /**
     * 应急处置添加
     * @return Response
     * @throws Exception
     * @throws Throwable
     */
    public function actionAdd()
    {
        $post = Yii::$app->request->post();
        $post = DealWithPostData::changePostDataArrayToJson($post);
        $case = CaseService::checkIsPublish($post["accident_id"], $this->userInfo);
        $param = [
            "accident_id" => $post["accident_id"],
            "assess" => $post["assess"],
            "assess_two" => $post["assess_two"],
            "content" => $post["content"],
            "important_content" => $post["important_content"],
            "is_important" => $post["is_important"] ? 1 : 0,
            "is_time_period" => isset($post["is_time_period"]) && $post["is_time_period"] ? 1 : 0,
            "end_time" => isset($post["end_time"]) && $post["end_time"] !== "" ? $post["end_time"] : 0,
            "rules" => $post["rules"],
            "source_data" => $post["source_data"],
            "start_time" => $post["start_time"],
            "type_first" => $post["type_first"],
            "type_fourth" => $post["type_fourth"],
            "type_second" => $post["type_second"],
            "type_third" => $post["type_third"],
        ];
        $model = new EmergencyResponse($param);
        $origin = AdminLogService::getOrigin($model, $this->getAllParams(), true);
        Yii::$app->db->transaction(function () use ($model) {
            if (!$model->save()) {
                throw new Exception($model->getErrorSummary(true)[0]);
            }
            //将应急处置与规章表的关系添加
            EmergencyResponseRelateToRulesPointsService::add($model);
            //评价维度表添加
            EmergencyResponseDimensionService::add($model);
        });
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $case->id, $case->title, $this->getAllParams());
        return $this->asJson();
    }

    /**
     * 应急处置修改
     * @param $id
     * @return Response
     * @throws InvalidConfigException
     * @throws Exception
     * @throws Throwable`
     */
    public function actionUpdate($id)
    {
        //通过setBodyParams来修改Yii::$app->request->post()返回值
        Yii::$app->request->setBodyParams(DealWithPostData::changePostDataArrayToJson(Yii::$app->request->post()));
        $model = EmergencyResponseService::getEmergencyResponseById($id);
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        $case = CaseService::checkIsPublish($model->accident_id, $this->userInfo);
        $this->setAttributeFromGetAndPost($model);
        Yii::$app->db->transaction(function () use ($model) {
            if (!$model->save()) {
                throw new Exception($model->getErrorSummary(true)[0]);
            }
            //将应急处置与规章表的关系更新
            EmergencyResponseRelateToRulesPointsService::update($model);
        });
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $case->id, $case->title, $this->getAllParams());
        return $this->asJson();
    }

    /**
     * 应急处置删除
     * @param $id
     * @return Response
     * @throws Exception
     * @throws Throwable
     */
    public function actionDelete($id)
    {
        $model = EmergencyResponseService::getEmergencyResponseById($id);
        $case = CaseService::checkIsPublish($model->accident_id, $this->userInfo);
        $model->delete_time = time();
        Yii::$app->db->transaction(function () use ($model) {
            if (!$model->save()) {
                throw new Exception($model->getErrorSummary(true)[0]);
            }
            //将应急处置与规章表的关系删除
            EmergencyResponseRelateToRulesPointsService::deleteByEmergencyResponseId($model->id);
            //删除评价维度
            EmergencyResponseDimensionService::deleteByEmergencyResponseId($model->id);
        });
        //返回数据
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $case->id, $case->title, $this->getAllParams());
        return $this->asJson();
    }
}