<?php

namespace common\services;

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

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

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

    /**
     * @param $allParams
     * @return void
     * @throws AjaxException
     * @throws Exception
     */
    public static function update($allParams, $userInfo)
    {
        /** @var OperationalAdjustmentsDimension $model */
        $model = self::getQuery()->andWhere(["operational_adjustments_id" => $allParams["operational_adjustments_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);
    }

    /**
     * @param $OperationalAdjustmentsId
     * @return OperationalAdjustmentsDimension[]
     */
    public static function getListByOperationalAdjustmentsId($OperationalAdjustmentsId): array
    {
        return self::getQuery()->andWhere(["operational_adjustments_id" => $OperationalAdjustmentsId])->all();
    }

    public static function deleteByOperationalAdjustmentsId($OperationalAdjustmentsId): void
    {
        OperationalAdjustmentsDimension::updateAll(["delete_time" => time()], ["operational_adjustments_id" => $OperationalAdjustmentsId]);
    }

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