<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="系统模块" prop="title">
          <el-input
            v-model="searchParams.title"
            placeholder="请输入系统模块"
            clearable
            style="width: 200px;"
            @keyup.enter.native="getList"
          />
        </el-form-item>
        <el-form-item label="操作名称" prop="operName">
          <el-input
            placeholder="请输入操作名称"
            v-model="searchParams.operName"
            style="width: 200px"
            clearable
            @keyup.enter.native="getList"
          ></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="businessType">
          <el-select
            v-model="searchParams.businessType"
            placeholder="操作类型"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in koiDicts.sys_oper_type"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="操作时间" prop="loginTime">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            value-format="YYYY-MM-DD HH:mm:ss"
            start-placeholder="开始日期"
            range-separator="至"
            end-placeholder="结束日期"
            style="width: 260px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" plain v-debounce="handleSearch">搜索</el-button>
          <el-button type="danger" icon="refresh" plain v-throttle="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5" v-auth="['system:role:delete']">
          <el-button type="danger" icon="delete" plain @click="handleBatchDelete()" :disabled="multiple">删除</el-button>
        </el-col>
<!--        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="getList"></KoiToolbar>-->
      </el-row>

      <div class="h-20px"></div>
      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        border
        :data="tableList"
        empty-text="暂时没有数据哟"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" prop="operId" width="70px" align="center" type="index"></el-table-column>
        <el-table-column label="操作人员[登录名/用户名]" prop="operName" width="200px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作类型" prop="sex" width="100px" align="center">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.sys_oper_type" :value="scope.row.businessType"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="系统类型" prop="title" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="请求方式" prop="requestMethod" width="100px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作状态" align="center" width="100px" prop="status">
          <template #default="scope">
            <KoiTag :tagOptions="koiDicts.sys_common_status" :value="scope.row.status"></KoiTag>
          </template>
        </el-table-column>
        <el-table-column label="操作IP" prop="operIp" width="200px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作地点" prop="operLocation" width="180px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作时间" prop="operTime" width="180px" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="{ row }">
            <el-tooltip content="删除" placement="top">
              <el-button
                type="danger"
                icon="Delete"
                circle
                plain
                @click="handleDelete(row)"
                v-auth="['monitor:operlog:remove']"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="查看" placement="top">
              <el-button
                type="primary"
                icon="View"
                circle
                plain
                @click="handleView(row)"
                v-auth="['monitor:operlog:query']"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <div class="h-20px"></div>
      <!-- 分页 -->
      <Pagination :queryParams="searchParams" :total="total" :getList="getList" />

      <KoiDialog ref="koiDialogRef" :title="title" top="6vh" :height="660" :width="800" :footerHidden="true">
        <template #content>
          <!-- 描述列表 -->
          <el-descriptions direction="vertical" :column="3" border>
            <el-descriptions-item label="操作模块">{{ form.title }}</el-descriptions-item>
            <el-descriptions-item label="登录信息">{{ form.operName }} / {{ form.operIp }} / {{ form.operLocation }}</el-descriptions-item>
            <el-descriptions-item label="请求方法">{{ form.methodName }}</el-descriptions-item>
            <el-descriptions-item label="请求地址">{{ form.operUrl }}</el-descriptions-item>
            <el-descriptions-item label="操作状态">
              <el-tag :type="form.status == '0' ? '' : form.status == '1' ? 'danger' : 'warning'">
                {{ form.status == "0" ? "操作成功" : "操作失败" }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="异常信息" v-if="form.status === 1">{{form.errorMsg }}</el-descriptions-item>
            <el-descriptions-item label="请求参数" :span="3">{{ form.operParam }}</el-descriptions-item>
            <el-descriptions-item label="返回数据" :span="3">{{ form.jsonResult }}</el-descriptions-item>
          </el-descriptions>
        </template>
      </KoiDialog>
    </KoiCard>
  </div>
</template>

<script setup lang="ts" name="operlog">
import { ref, onMounted, reactive } from "vue";
import { koiNoticeSuccess, koiNoticeError, koiMsgWarning, koiMsgBox, koiMsgInfo, koiMsgError } from "@/utils/koi.ts";
import { list, delOperlog } from "@/api/system/operlog/index.ts";
import {useKoiDict} from "@/hooks/dicts";

const { koiDicts } = useKoiDict(["sys_oper_type", "sys_common_status"])
// 表格加载动画Loading
const loading = ref(false);
// 是否显示搜索表单[默认显示]
const showSearch = ref<boolean>(true); // 默认显示搜索条件
// 表格数据
const tableList = ref<any>([]);

// 查询参数
const searchParams = reactive({
  pageNum: 1,
  pageSize: 15,
  title: '',
  operName: '',
  businessType: '',
  status: '',
  params: {
    beginTime: '',
    endTime: ''
  }
});
const total = ref<number>(0);
// 时间
const dateRange = ref([]);

/** 搜索 */
const handleSearch = () => {
  searchParams.pageNum = 1;
  getList();
};

/** 重置 */
const resetSearch = () => {
  dateRange.value = [];
  Object.assign(searchParams, {
    pageNum: 1,
    pageSize: 15,
    title: '',
    operName: '',
    businessType: '',
    status: '',
    params: {}
  })
  getList()
};

/** @current-change：点击分页组件页码发生变化：例如：切换第2、3页 OR 上一页 AND 下一页 OR 跳转某一页 */
/** @size-change：点击分页组件下拉选择条数发生变化：例如：选择10条/页、20条/页等 */
// 分页查询，@current-change AND @size-change都会触发分页，调用后端分页接口
/** 数据表格 */
const getList = async () => {
  loading.value = true
  if(dateRange.value.length) {
    console.log(dateRange.value)
    searchParams.params.beginTime = dateRange.value[0]
    searchParams.params.endTime = dateRange.value[1]
  }
  const res = await list(searchParams)
  tableList.value = res.rows;
  total.value = res.total;
  loading.value = false
};

onMounted(() => {
  // 获取表格数据
  getList()
});

const ids = ref([]); // 选择数组
const multiple = ref<boolean>(true); // 非多个禁用

/** 是否多选 */
const handleSelectionChange = (selection: any) => {
  // console.log(selection);
  ids.value = selection.map((item: any) => item.operId);
  multiple.value = !selection.length; // 多选
};

/** 删除 */
const handleDelete = (row: any) => {
  const id = row.operId;
  if (id == null || id == "") {
    koiMsgWarning("请选择需要删除的数据");
  }
  koiMsgBox("您确认需要删除操作名称[" + row.operName + "]么？")
    .then(async () => {
      delOper(id)
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};

const delOper = async (ids: any) => {
  const res = await delOperlog(ids)
  if(res.code === 200) {
    koiNoticeSuccess('删除成功')
    getList()
  } else {
    koiNoticeError('删除异常')
  }
}

/** 批量删除 */
const handleBatchDelete = () => {
  if (ids.value.length == 0) {
    koiMsgInfo("请选择需要删除的数据");
    return;
  }
  koiMsgBox("您确认需要进行批量删除么？")
    .then(async () => {
      const id = ids.value.join(",");
      delOper(id)
    })
    .catch(() => {
      koiMsgError("已取消");
    });
};

/** 查看 */
const handleView = async (row: any) => {
  // 重置表单
  resetForm();
  title.value = "描述列表";
  const detail = JSON.parse(JSON.stringify(row))
  form.value = detail
  koiDialogRef.value.koiOpen();
};

// 添加 OR 修改对话框Ref
const koiDialogRef = ref();
/** 打开Dialog操作 */
const title = ref("描述列表");

// form表单
let form = ref<any>({
  title: "",
  status: '',
  operName: "",
  operUrl: "",
  operIp: '',
  operLocation: '',
  operParam: '',
  jsonResult: '',
  operTime: '',
  errorMsg: ''
});

/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    title: "",
    status: '',
    operName: "",
    operUrl: "",
    operIp: '',
    operLocation: '',
    operParam: '',
    jsonResult: '',
    operTime: '',
    errorMsg: ''
  };
};
</script>

<style lang="scss" scoped></style>
