<?php


namespace common\services;


use common\models\AccidentCasesUpdateHistory;
use common\models\AdminLog;
use common\models\BaseUser;

class AdminLogService
{
    public static array $ignoreList = [
        "/admin-log/list",
        "/admin-log/detail",
        "/admin-log/url-title",
        "/admin-log/staff-list",
        "/mail/get-unread-messages-number",
        "/accident-cases/study",
    ];

    public static array $ignoreContentList = [
        "/basic/rules-add-batch",
        "/user/add-batch",
    ];

    public static array $staffTitle = [
        "/login/index",
        "/user/logout",
        "/accident-cases/add",
        "/accident-cases/update",
        "/accident-cases/update-total-score",
        "/emergency-response/add",
        "/emergency-response/update",
        "/emergency-response/delete",
        "/operational-adjustments/add",
        "/operational-adjustments/update",
        "/operational-adjustments/delete",
        "/event-overview/add",
        "/event-overview/update",
        "/event-overview/delete",
        "/event-source-data/add",
        "/event-source-data/delete",
        "/accident-cases-score/update",
        "/accident-cases-dimension/update",
        "/operational-adjustments-dimension/update",
        "/emergency-response-dimension/update",
        "/case/detail",
        "/case/list-new",
        "/accident-cases/delete",
        "/accident-cases/publish",
        "/accident-cases/cancel",
        "/accident-cases/revoke",
        "/accident-cases/refuse",
        "/accident-cases/commit",
        "/accident-cases/pass"
    ];

    public static array $title = [
        "/accident-cases/list" => "案例列表",
        "/accident-cases/add" => "案例添加",
        "/accident-cases/update" => "案例修改",
        "/accident-cases/update-total-score" => "案例评语修改",
        "/accident-cases/delete" => "案例删除",
        "/accident-cases/publish" => "案例上架",
        "/accident-cases/revoke" => "案例下架",
        "/accident-cases/pass" => "案例通过",
        "/accident-cases/refuse" => "案例驳回",
        "/accident-cases/commit" => "案例提交",
        "/accident-cases/cancel" => "案例撤回",
        "/accident-cases-dimension/update" => "评价维度修改",
        "/accident-cases-focus/list" => "关注列表",
        "/accident-cases-focus/add" => "添加关注",
        "/accident-cases-focus/cancel" => "取消关注",
        "/accident-cases-score-config/info" => "评价打分显示配置",
        "/accident-cases-score-config/update" => "评价打分显示配置修改",
        "/accident-cases-score/update" => "评价打分",
        "/basic/rules-show-list" => "规则需要展示的列表",
        "/basic/rules-get-by-id" => "规则需要展示的列表",
        "/basic/rules-get-by-case-id" => "根据案例ID展示规章",
        "/basic/rules-and-points-by-event-id" => "通过应急处置ID或者运营调整ID查找规章",
        "/basic/rules-list" => "规则列表",
        "/basic/rules-add" => "规章添加",
        "/basic/rules-add-batch" => "从excel批量导入规章",
        "/basic/rules-update" => "规章修改",
        "/basic/rules-delete" => "规章删除",
        "/basic/rules-list-category" => "规章列表",
        "/basic/rules-points-list-by-id" => "规章知识点列表",
        "/basic/rules-points-add" => "规章知识点添加",
        "/basic/rules-points-update" => "规章知识点更新",
        "/basic/rules-points-delete-by-id" => "规章知识点删除",
        "/case/search-history" => "搜索历史",
        "/case/recommend" => "推荐案例",
        "/case/list-new" => "案例搜索",
        "/case/detail" => "案例详情",
        "/case/compare" => "案例对比",
        "/case-manage/check" => "查询案例是否重名",
        "/dictionary/list" => "字典对象数据",
        "/dictionary/list-category" => "字典分类列表",
        "/dictionary/list-category-name" => "字典分类列表",
        "/dictionary/list-all" => "字典列表",
        "/dictionary/all" => "字典列表",
        "/dictionary/add" => "字典添加",
        "/dictionary/update" => "字典修改",
        "/emergency-response/list" => "应急处置列表",
        "/emergency-response/add" => "应急处置添加",
        "/emergency-response/update" => "应急处置修改",
        "/emergency-response/delete" => "应急处置删除",
        "/emergency-response-dimension/update" => "评价维度修改",
        "/event-overview/list" => "事件概览列表",
        "/event-overview/add" => "事件概览添加",
        "/event-overview/update" => "事件概览修改",
        "/event-overview/delete" => "事件概览删除",
        "/event-source-data/list" => "原始资料列表",
        "/event-source-data/add" => "原始资料添加",
        "/event-source-data/delete" => "原始资料删除",
        "/login/index" => "登录",
        "/login/check-username" => "校验昵称",
        "/login/x5Login" => "x5登录",
        "/operational-adjustments/list" => "运营调整列表",
        "/operational-adjustments/add" => "添加运营调整",
        "/operational-adjustments/update" => "运营调整修改",
        "/operational-adjustments/delete" => "运营调整删除",
        "/operational-adjustments-dimension/update" => "评价维度修改",
        "/permission/route" => "路由列表",
        "/permission/route-refresh" => "刷新路由",
        "/permission/route-list" => "读取路由",
        "/permission/route-update" => "路由修改",
        "/permission/role" => "角色列表",
        "/permission/roles-list" => "角色合集",
        "/permission/role-add" => "角色新增",
        "/permission/role-update" => "角色资料和权限修改",
        "/search-config/info" => "高级搜索显示配置",
        "/search-config/update" => "高级搜索显示配置修改",
        "/system/department-list" => "部门列表",
        "/system/department-add" => "部门添加",
        "/system/department-update" => "部门修改",
        "/system/job-list" => "岗位列表",
        "/system/job-add" => "岗位添加",
        "/system/job-update" => "岗位修改",
        "/system/roles-list" => "类型列表",
        "/upload/user-avatar" => "上传头像",
        "/upload/case-avatar" => "头像上传",
        "/user/list" => "用户列表",
        "/user/info" => "用户信息",
        "/user/add" => "用户添加",
        "/user/user-update" => "用户修改",
        "/user/add-batch" => "从excel批量导入",
        "/user/check" => "用户名查重",
        "/user/change-info" => "修改资料",
        "/user/save-avatar" => "保存头像",
        "/user/logout" => "登出",
        "/util/time-feature" => "时间特征查询",
    ];

    public static function saveLog(BaseUser $userInfo, $url, $params)
    {
        if (in_array($url, self::$ignoreList)) {
            return 0;
        }
        $content = "excel批量导入不保存参数";
        if (!in_array($url, self::$ignoreContentList)) {
            $content = is_array($params) && count($params) == 0 ? json_encode(['default' => '无请求参数'], JSON_UNESCAPED_UNICODE) : json_encode($params, JSON_UNESCAPED_UNICODE);
        }
        $AdminLog = new AdminLog();
        $AdminLog->uid = $userInfo->id;
        $AdminLog->role_name = $userInfo->roleName;
        $AdminLog->username = $userInfo->username;
        $AdminLog->name = $userInfo->realName;
        $AdminLog->url = $url;
        $AdminLog->ip = $_SERVER["REMOTE_ADDR"];
        $AdminLog->title = self::$title[$url] ?? $url; // 等价 isset(self::$title[$url]) ? self::$title[$url] : $url  网址：https://wiki.php.net/rfc/isset_ternary
        $AdminLog->content = $content;
        $AdminLog->create_time = date("Y-m-d H:i:s");
        $AdminLog->history_id = 0;
        $AdminLog->save();
        return $AdminLog;
    }

    public static function saveLogWithUpdateHistory($origin, $model, $caseId, $caseTitle, $allParams): void
    {
        if (isset($allParams["adminLogId"])) {
            /** @var  $adminLogModel AdminLog */
            $adminLogModel = $allParams["adminLogModel"];
            $history = new AccidentCasesUpdateHistory();
            $history->admin_log_id = $allParams["adminLogId"];
            $history->uid = $adminLogModel->uid;
            $history->name = $adminLogModel->name;
            $history->role_name = $adminLogModel->role_name;
            $history->username = $adminLogModel->username;
            $history->url = $adminLogModel->url;
            $history->title = $adminLogModel->title;
            $history->case_id = $caseId;
            $history->case_title = $caseTitle;
            $history->content = $adminLogModel->content;
            $history->ip = $adminLogModel->ip;
            $history->create_time = $adminLogModel->create_time;
            $history->origin = $origin;
            $history->current = self::dealWithModel($model);
            $history->save();
        }
    }

    public static function getOrigin($model, $allParams, $isCreate = false)
    {
        if ($isCreate) {
            return "";
        }
        //查询原始资料
        if (isset($allParams["adminLogId"])) {
            if ($model == "") {
                $new = "";
            } else {
                $new = clone $model;
            }
            return self::dealWithModel($new);
        }
        return "";
    }

    public static function dealWithModel($model)
    {
        if ($model == "") {
            return "";
        }
        if ($model->hasAttribute("source_data") && $model->source_data != "[]") {
            $sourceDataList = array_column(EventSourceDataService::getSourceDataListByAccidentId($model->accident_id), null, "id");
            self::dealWithSourceData($model, $sourceDataList);
        }
        return json_encode($model->getAttributes());
    }

    public static function dealWithSourceData($model, $sourceDataList)
    {
        $sourceDataIdList = json_decode($model->source_data, true);
        $sourceDataObj = [];
        foreach ($sourceDataIdList as $sourceDataId) {
            if (isset($sourceDataList[$sourceDataId])) {
                $sourceDataObj[] = $sourceDataList[$sourceDataId]->getAttributes();
            }
        }
        $model->source_data = $sourceDataObj;
    }
}