<?php


namespace frontend\modules\api\controllers;


use common\components\AjaxException;
use common\models\AccidentCases;
use common\models\AccidentCasesScore;
use common\services\AccidentCasesRelateToDictionaryService;
use common\services\AccidentCasesDimensionService;
use common\services\AccidentCasesScoreConfigService;
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\services\EventOverviewService;
use common\services\EventSourceDataService;
use common\services\MailService;
use common\services\OperationalAdjustmentsDimensionService;
use common\services\OperationalAdjustmentsRelateToRulesPointsService;
use common\services\OperationalAdjustmentsService;
use common\services\UserService;
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 AccidentCasesController extends BaseAdminController
{
    /**
     * 案例列表
     * @param int $current
     * @param int $page
     * @return Response
     * @throws AjaxException
     */
    public function actionList(int $current = 1, int $page = 10)
    {
        $query = CaseService::getCaseQuery()
            ->limit($page)
            ->offset(($current - 1) * $page);
        //排序
        $this->initSequence($query);
        //主要筛选条件
        $query = $this->addConditionToQuery("title", $query, true);
        $query = $this->addConditionToQuery("status", $query);
        // * @property int $status 状态 0-待提交 1-已发布  2已提交 3已审核 4驳回
        $userRoleAuth = UserService::getUserRoleAuth($this->userInfo);
        //--基础是查看已审核和已发布的 ["status" => [1, 3]]
        //判断用户是否有创建的权限 有的话可以查看自己创建的 ["create_by" => $this->userInfo->username ]
        //判断用户是否有审核权限 有的话可以查看 没有指定审核人的["check_list"=>"[]"] 指定与自己相关的 从指定审核人表里面查找 ["check_list"=>]
        if ($userRoleAuth->isSuperAdmin) {
            $query = $query->andWhere(["status" => [0, 1, 2, 3, 4]]);
        } else if ($userRoleAuth->caseAdd && $userRoleAuth->caseCheck) {
            $query = $query->andWhere(["or", ["status" => [1, 3]], ["create_by" => $this->userInfo->username], ["status" => [2], "check_list" => "[]"], ["and", ["status" => [2]], ["like", "check_list", $this->userInfo->username]]]);
        } else if ($userRoleAuth->caseAdd) {
            $query = $query->andWhere(["or", ["status" => [1, 3]], ["create_by" => $this->userInfo->username]]);
        } else if ($userRoleAuth->caseCheck) {
//            $idList = $userRoleAuth->caseCheck;
//            $query = $query->andWhere(["or", ["status" => [1, 3]], ["check_list" => "[]"], ["id" => $idList]]);
            $query = $query->andWhere(["or", ["status" => [1, 3]], ["status" => [2], "check_list" => "[]"], ["and", ["status" => [2]], ["like", "check_list", $this->userInfo->username]]]);
        } else {
            $query = $query->andWhere(["status" => [1, 3]]);
        }
        //组合数据
        $dataInfo = CaseService::dealWithList($query->all());
        //待审核案例置顶
        if ($current == 1) {
            $data['total'] = $query->count();
            $newData = [];
            $top = CaseService::dealWithList($query->andWhere(["status" => 2])->all());
            if ($top == []) {
                $newData = $dataInfo;
            } else {
                $topIds = [];
                foreach ($top as $value) {
                    $topIds[] = $value->id;
                    $newData[] = $value;
                }
                foreach ($dataInfo as $value) {
                    if (!in_array($value->id, $topIds)) {
                        $newData[] = $value;
                    }
                }
            }
            $data['data'] = $newData;
        } else {
            $data['data'] = $dataInfo;
            $data['total'] = $query->count();
        }
        return $this->asJson($data);
    }

    /**
     * 案例添加
     * @return Response
     * @throws InvalidConfigException
     * @throws Throwable
     */
    public function actionAdd(): Response
    {
        $userRoleAuth = UserService::getUserRoleAuth($this->userInfo);
        if (!$userRoleAuth->caseAdd) {
            /**
             * in_array("/accident-cases/add", $rules)
             * && in_array("/accident-cases/commit", $rules)
             * && in_array("/accident-cases/update", $rules)
             * && in_array("/accident-cases/delete", $rules)
             */
            return $this->returnError("权限不足：" . '/accident-cases/add' . "/accident-cases/commit" . "/accident-cases/cancel" . "/accident-cases/update" . "/accident-cases/delete");
        }
        $allParam = $this->getAllParams();
        unset($allParam['adminLogModel']);
        unset($allParam['adminLogId']);
        $post = DealWithPostData::changePostDataArrayToJson($allParam);
        $model = new AccidentCases($post);
        $origin = AdminLogService::getOrigin($model, $this->getAllParams(), true);
        $model->update_time = date("Y-m-d H:i:s");
        $model->status = 0;
        //开启事务
        Yii::$app->db->transaction(function () use ($model) {
            //添加派生关系
            CaseService::deriveByAccidentCasesModel($model);
            $model->create_by = $this->userInfo->username;
            $model->create_name = $this->userInfo->name;
            if (!$model->save()) {
                throw new Exception($model->getErrorSummary(true)[0]);
            }
            //将案例与字典表的关系保存
            AccidentCasesRelateToDictionaryService::add($model);
            //生成评分数据
            AccidentCasesScoreService::initScore($model->id);
        });
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $model->id, $model->title, $this->getAllParams());
        //返回数据
        return $this->asJson();
    }

    /**
     * 上架案例
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws InvalidConfigException
     */
    public function actionPublish($id)
    {
        $model = CaseService::getCaseById($id);
        $userRoleAuth = UserService::getUserRoleAuth($this->userInfo);
        if ($userRoleAuth->caseCheck) {
            if ($model->check_list == "[]" || str_contains($model->check_list, $this->userInfo->username)) {
                if ($model->status != 3) {
                    return $this->returnError("只能上架已审核的案例");
                }
            } else {
                if (!$userRoleAuth->isSuperAdmin) {
                    return $this->returnError("只能由" . $model->check_name_list . "上架");
                }
            }
        }
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        $model->status = 1;
        $model->check_remark = $this->getParams("check_remark") ?? "";
        $model->save();
        //返回数据
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $model->id, $model->title, $this->getAllParams());
        return $this->asJson();
    }

    /**
     * 下架案例
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws InvalidConfigException
     */
    public function actionRevoke($id)
    {
        $model = CaseService::getCaseById($id);
        if ($model->status != 1) {
            return $this->returnError("只能下架已上架的案例");
        }
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        $model->status = 3;
        $model->check_remark = $this->getParams("check_remark") ?? "";
        $model->save();
        //返回数据
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $model->id, $model->title, $this->getAllParams());
        return $this->asJson();
    }

    /**
     * 拒绝案例
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws InvalidConfigException
     */
    public function actionRefuse($id)
    {
        $model = CaseService::getCaseById($id);
        $userRoleAuth = UserService::getUserRoleAuth($this->userInfo);
        if ($userRoleAuth->caseCheck) {
            if ($model->check_list == "[]" || str_contains($model->check_list, $this->userInfo->username)) {
                if ($model->status != 2 && $model->status != 3) {
                    return $this->returnError("只能退回已提交和已审核的案例");
                }
            } else {
                if (!$userRoleAuth->isSuperAdmin) {
                    return $this->returnError("只能由" . $model->check_name_list . "退回");
                }
            }
        }
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        $model->status = 4;
        $model->check_remark = $this->getParams("check_remark") ?? "";
        $model->check_by = $this->userInfo->username;
        $model->check_name = $this->userInfo->name ?? "系统管理员";
        $model->save();
        //发送信息
        MailService::sendRefuseMail($model, $model->check_remark);
        //历史
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $model->id, $model->title, $this->getAllParams());
        return $this->asJson();
    }

    /**
     * 提交案例
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws InvalidConfigException
     */
    public function actionCommit($id): Response
    {
        $model = CaseService::getCaseById($id);
        $userRoleAuth = UserService::getUserRoleAuth($this->userInfo);
        if (!$userRoleAuth->isSuperAdmin) {
            if ($model->create_by != $this->userInfo->username) {
                return $this->returnError("只能提交自己创建的案例");
            }
        }
        if ($model->status != 0 && $model->status != 4) {
            return $this->returnError("只能提交待审核或已退回的案例");
        }
        $params = $this->getAllParams();
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        $model->status = 2;
        $model->check_list = json_encode($params["check_people"]);
        CaseService::setCheckNameList($model, $params["check_people"]);
        $model->create_remark = $params["check_remark"];
        $model->save();
        //发送信息
        MailService::sendCommitMail($model, $model->create_remark);
        //返回数据
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $model->id, $model->title, $this->getAllParams());
        return $this->asJson();
    }

    /**
     * 取消提交案例
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws InvalidConfigException
     */
    public function actionCancel($id)
    {
        $model = CaseService::getCaseById($id);
        $userRoleAuth = UserService::getUserRoleAuth($this->userInfo);
        if (!$userRoleAuth->isSuperAdmin) {
            if ($model->create_by != $this->userInfo->username) {
                return $this->returnError("只能取消提交自己创建的案例");
            }
        }
        if ($model->status != 2) {
            return $this->returnError("只能取消审核中的案例");
        }
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        $model->status = 0;
        $model->create_remark = $this->getParams("check_remark") ?? "";
        $model->save();
        //返回数据
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $model->id, $model->title, $this->getAllParams());
        return $this->asJson();
    }

    /**
     * 通过案例
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws InvalidConfigException
     */
    public function actionPass($id)
    {
        //通过以后自动上架
        $model = CaseService::getCaseById($id);
        $userRoleAuth = UserService::getUserRoleAuth($this->userInfo);
        if ($userRoleAuth->caseCheck) {
            if ($model->check_list == "[]" || str_contains($model->check_list, $this->userInfo->username)) {
                if ($model->status != 2) {
                    return $this->returnError("只能通过审核中的案例");
                }
            } else {
                if (!$userRoleAuth->isSuperAdmin) {
                    return $this->returnError("只能由" . $model->check_name_list . "通过");
                }
            }
        }
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        $model->check_remark = $this->getParams("check_remark") ?? "";
        $model->status = 3;
        $model->check_by = $this->userInfo->username;
        $model->check_name = $this->userInfo->name ?? "系统管理员";
        $model->save();
        //返回数据
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $model->id, $model->title, $this->getAllParams());
        return $this->asJson();
    }

    /**
     * 案例修改
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws InvalidConfigException
     * @throws Throwable
     */
    public function actionUpdate($id)
    {
        //status 0 2 3 4可以修改
        $model = CaseService::checkIsPublish($id, $this->userInfo);
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        $totalScore = isset(Yii::$app->request->post()["totalScore"]) ? Yii::$app->request->post()["totalScore"] : null;
        //通过setBodyParams来修改Yii::$app->request->post()返回值
        Yii::$app->request->setBodyParams(DealWithPostData::changePostDataArrayToJson(Yii::$app->request->post()));
        $this->setAttributeFromGetAndPost($model);
        //开启事务
        Yii::$app->db->transaction(function () use ($model, $totalScore) {
            //添加派生关系
            CaseService::deriveByAccidentCasesModel($model);
            $model->update_time = date("Y-m-d H:i:s");
            $model->status = 0;
            if (!$model->save()) {
                throw new Exception($model->getErrorSummary(true)[0]);
            }
            //将案例与字典表的关系更新
            AccidentCasesRelateToDictionaryService::update($model);
            //修改评价
//            AccidentCasesScoreService::updateByTotalScore($model->id, $totalScore);
        });
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $model->id, $model->title, $this->getAllParams());
        //返回数据
        return $this->asJson();
    }

    /**
     * 评价总评价评语 评价结果
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws InvalidConfigException
     */
    public function actionUpdateTotalScore($id)
    {
        if (AccidentCasesScoreConfigService::getAccidentCasesScoreConfigUpdate()) {
            throw new AjaxException("打分配置正在更新中，请稍后打分！");
        }
        $case = $accidentModel = CaseService::checkIsPublish($id, $this->userInfo);
        $totalScore = isset(Yii::$app->request->post()["totalScore"]) ? Yii::$app->request->post()["totalScore"] : null;
        //修改评价
        $model = AccidentCasesScore::findOne(["accident_id" => $accidentModel->id, "category" => 1]);
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        if ($totalScore) {
            if (isset($totalScore["content"])) {
                $model->content = $totalScore["content"];
            }
            if (isset($totalScore["content_two"])) {
                $model->content_two = $totalScore["content_two"];
            }
        }
        $model->save();
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $case->id, $case->title, $this->getAllParams());
        return $this->asJson();
    }

    /**
     * 案例删除
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws Throwable
     */
    public function actionDelete($id)
    {
        $model = CaseService::checkIsPublish($id, $this->userInfo);
        $userRoleAuth = UserService::getUserRoleAuth($this->userInfo);
        if (!$userRoleAuth->isSuperAdmin) {
            if ($model->create_by != $this->userInfo->username) {
                return $this->returnError("只能删除自己创建的案例");
            }
        }
        if ($model->status != 0 && $model->status != 4) {
            return $this->returnError("只能删除待审核或已退回的案例");
        }
        $model->delete_time = time();
        //开启事务
        Yii::$app->db->transaction(function () use ($model, $id) {
            if (!$model->save()) {
                throw new Exception($model->getErrorSummary(true)[0]);
            }
            //将案例与字典表的关系删除
            AccidentCasesRelateToDictionaryService::delete($model);
            //删除原始资料和缓存数据
            EventSourceDataService::deleteByAccidentCasesId($id);
            //删除评价打分
            AccidentCasesScoreService::deleteByAccidentCasesId($id);
            //删除总评价维度
            AccidentCasesDimensionService::deleteByAccidentCasesId($id);
            //将与案例相关的 事件概览、应急处置和运营调整 删除
            //删除应急处置 删除应急处置与规章表的关系  删除应急处置评价维度
            $EmergencyResponseIdList = array_column(EmergencyResponseService::getEmergencyResponseQuery()->andWhere(["accident_id" => $id])->select("accident_id")->all(), "accident_id");
            EmergencyResponseService::deleteByAccidentCasesId($id);
            EmergencyResponseDimensionService::deleteByAccidentId($id);
            EmergencyResponseRelateToRulesPointsService::deleteByEmergencyResponseId($EmergencyResponseIdList);
            //删除事件概览
            EventOverviewService::deleteByAccidentCasesId($id);
            //删除运营调整 删除运营调整与规章表的关系  删除评价维度
            $OperationalAdjustmentsIdList = array_column(OperationalAdjustmentsService::getQuery()->andWhere(["accident_id" => $id])->select("accident_id")->all(), "accident_id");
            OperationalAdjustmentsService::deleteByAccidentCasesId($id);
            OperationalAdjustmentsDimensionService::deleteByAccidentId($id);
            OperationalAdjustmentsRelateToRulesPointsService::deleteByOperationalAdjustmentsId($OperationalAdjustmentsIdList);
        });
        //返回数据
        $origin = AdminLogService::getOrigin($model, $this->getAllParams());
        AdminLogService::saveLogWithUpdateHistory($origin, $model, $model->id, $model->title, $this->getAllParams());
        return $this->asJson();
    }

    /**
     * 案例学习
     * @return Response
     * @throws InvalidConfigException
     */
    public function actionStudy($id)
    {
        $this->getParams("id");
        CaseService::study($id,$this->userInfo);
        return $this->asJson();
    }
}