<?php


namespace frontend\modules\api\controllers;


use common\components\AjaxException;
use common\models\EventSourceData;
use common\services\AdminLogService;
use common\services\CaseService;
use common\services\EventSourceDataService;
use common\util\Upload;
use frontend\modules\api\components\BaseAdminController;
use Yii;
use yii\base\InvalidConfigException;
use yii\db\Exception;
use yii\web\Response;

class EventSourceDataController extends BaseAdminController
{
    /**
     * 原始资料列表
     * @param int $accident_id
     * @return Response
     */
    public function actionList(int $accident_id)
    {
        $query = EventSourceDataService::getQueryByAccidentId($accident_id)->orderBy("update_time desc,id desc");
        //组合数据
        $data['data'] = $query->asArray()->all();
        return $this->asJson($data);
    }

    /**
     * 原始资料添加
     * @return Response
     * @throws AjaxException
     * @throws Exception
     * @throws InvalidConfigException
     */
    public function actionAdd()
    {
        set_time_limit(0);
        if (!$_FILES) {
            throw new AjaxException("文件获取失败！");
        }
        $post = Yii::$app->request->post();
        $case = CaseService::checkIsPublish($post["accident_id"], $this->userInfo);
        $model = new EventSourceData($post);
        $origin = AdminLogService::getOrigin($model, $this->getAllParams(), true);
        list($model->file_name, $model->url) = Upload::dealWithEventSourceDataFile($model->accident_id);
        $model->update_time = time();
        if (!$model->save()) {
            throw new Exception($model->getErrorSummary(true)[0]);
        }
        //清除缓存
        EventSourceDataService::clearSourceDataListByAccidentIdCacheData($model->accident_id);
        //返回数据
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $case->id, $case->title, $this->getAllParams());
        $data['data'] = $model->id;
        return $this->asJson($data);
    }

    /**
     * 原始资料删除
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws Exception
     * @throws InvalidConfigException
     */
    public function actionDelete($id)
    {

        //清除缓存
        $model = EventSourceDataService::getEventSourceDataById($id);
        $case = CaseService::checkIsPublish($model->accident_id, $this->userInfo);
        $model->delete_time = time();
        if (!$model->save()) {
            throw new Exception($model->getErrorSummary(true)[0]);
        }
        EventSourceDataService::clearSourceDataListByAccidentIdCacheData($model->accident_id);
        //返回数据
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $case->id, $case->title, $this->getAllParams());
        return $this->asJson();
    }
}