<?php

namespace common\services;

use common\components\AjaxException;
use common\models\EmergencyResponse;
use common\models\EmergencyResponseDimension;
use common\models\OperationalAdjustmentsDimension;
use Yii;
use yii\db\ActiveQuery;
use yii\db\Exception;

class EmergencyResponseDimensionService
{
    public static function getQuery(): ActiveQuery
    {
        return EmergencyResponseDimension::find()->where(["delete_time" => 0]);
    }

    /**
     * @param $EmergencyResponseId
     * @return EmergencyResponseDimension[]
     */
    public static function getListByEmergencyResponseId($EmergencyResponseId): array
    {
        return self::getQuery()->andWhere(["emergency_response_id" => $EmergencyResponseId])->all();
    }

    public static function add(EmergencyResponse $EmergencyResponse)
    {
        $param = [
            "accident_id",
            "emergency_response_id",
            "content",
            "type",
            "update_time"
        ];
        $time = time();
        $paramData = [];
        foreach (AccidentCasesDimensionService::$typeList as $type) {
            $paramData[] = [
                "accident_id" => $EmergencyResponse->accident_id,
                "emergency_response_id" => $EmergencyResponse->id,
                "content" => "",
                "type" => $type,
                "update_time" => $time,
            ];
        }
        Yii::$app->db->createCommand()->batchInsert(EmergencyResponseDimension::tableName(), $param, $paramData)->execute();
    }

    /**
     * @param $allParams
     * @return void
     * @throws AjaxException
     * @throws Exception
     */
    public static function update($allParams, $userInfo)
    {
        /** @var EmergencyResponseDimension $model */
        $model = self::getQuery()->andWhere(["emergency_response_id" => $allParams["emergency_response_id"], "type" => $allParams["type"]])->one();
        if (!$model) {
            throw new AjaxException("该评价维度不存在！");
        }
        $origin = AdminLogService::getOrigin($model, $allParams);
        $case = CaseService::checkIsPublish($model->accident_id, $userInfo);
        $model->content = $allParams["content"];
        $model->status = $allParams["status"];
        $model->update_time = time();
        if (!$model->save()) {
            throw new Exception($model->getErrorSummary(true)[0]);
        }
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $case->id, $case->title, $allParams);
    }

    public static function deleteByEmergencyResponseId($EmergencyResponseId): void
    {
        EmergencyResponseDimension::updateAll(["delete_time" => 0], ["emergency_response_id" => $EmergencyResponseId]);
    }

    public static function deleteByAccidentId($AccidentId): void
    {
        OperationalAdjustmentsDimension::updateAll(["delete_time" => time()], ["accident_id" => $AccidentId]);
    }
}