<?php


namespace common\services;


use common\components\AjaxException;
use common\models\EventSourceData;
use Yii;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;

class EventSourceDataService
{
    public static $sourceDataListByAccidentIdCacheKey = "sourceDataListByAccidentId_";

    /**
     * @param $id
     * @return EventSourceData
     * @throws AjaxException
     */
    public static function getEventSourceDataById($id): EventSourceData
    {
        /** @var EventSourceData $EventOverview */
        $EventOverview = self::getQuery()->andWhere(["id" => $id])->one();
        if (!$EventOverview) {
            throw new AjaxException("该资料不存在！");
        }
        return $EventOverview;
    }

    /**
     * @return ActiveQuery
     */
    public static function getQuery(): ActiveQuery
    {
        return EventSourceData::find()->where(["delete_time" => 0]);
    }

    public static function getQueryByAccidentId($accidentId): ActiveQuery
    {
        return self::getQuery()->andWhere(["accident_id" => $accidentId]);
    }

    /**
     * @param $accidentId
     * @return ActiveRecord[]
     */
    public static function getSourceDataListByAccidentId($accidentId): array
    {
        $cache = Yii::$app->cache;
        return $cache->getOrSet(self::$sourceDataListByAccidentIdCacheKey . $accidentId, function () use ($accidentId) {
            return EventSourceDataService::getQueryByAccidentId($accidentId)->all();
        }, 1000);
    }

    public static function clearSourceDataListByAccidentIdCacheData($accidentId)
    {
        Yii::$app->cache->delete(self::$sourceDataListByAccidentIdCacheKey . $accidentId);
    }

    /**
     * 通过案例ID删除应急处置
     * @param $accident_id
     */
    public static function deleteByAccidentCasesId($accident_id): void
    {
        EventSourceData::updateAll(["delete_time" => time()], ["accident_id" => $accident_id]);
        //删除缓存
        self::clearSourceDataListByAccidentIdCacheData($accident_id);
    }
}