<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-row :gutter="0">
              <el-form-item label="客户号" prop="customerNo" label-width="100px">
                <el-input v-model="queryParams.customerNo" placeholder="请输入客户号" clearable style="width: 180px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="子客户号" prop="subCustomerNo" label-width="100px">
                <el-input
                  v-model="queryParams.subCustomerNo"
                  placeholder="请输入子客户号"
                  clearable
                  style="width: 180px"
                  @keyup.enter="handleQuery"
                />
              </el-form-item>
              <el-form-item label="姓名" prop="name" label-width="100px">
                <el-input v-model="queryParams.name" placeholder="请输入姓名" clearable style="width: 180px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item label="证件类型" prop="identificationType" label-width="100px">
                <el-select v-model="queryParams.identificationType" placeholder="请选择证件类型" style="width: 180px" clearable>
                  <el-option v-for="dict in sys_id_type" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-row>
            <el-form-item label="证件号码" prop="identificationNumber" label-width="100px">
              <el-input
                v-model="queryParams.identificationNumber"
                placeholder="请输入证件号码"
                clearable
                style="width: 180px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="请求日期" prop="requestDate" label-width="100px">
              <el-date-picker
                v-model="queryParams.requestDate"
                clearable
                style="width: 180px"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择请求日期"
              />
            </el-form-item>
            <el-form-item label="系统" prop="system" label-width="100px">
              <el-select v-model="queryParams.system" placeholder="请选择系统" clearable style="width: 180px">
                <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="请求类型" prop="requestType" label-width="100px">
              <el-select v-model="queryParams.requestType" placeholder="请选择请求类型" clearable style="width: 180px">
                <el-option v-for="dict in request_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>

            <el-row>
              <el-form-item>
                <el-button type="primary" icon="Search" style="margin-left: 40px" @click="handleQuery">查询</el-button>
                <el-button icon="Refresh" style="margin-left: 50px" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="apiErrorLogList" @selection-change="handleSelectionChange">
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column v-if="false" label="错误日志ID" align="center" prop="errorId" />
        <el-table-column label="姓名" align="center" prop="name" />
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="出生日期" align="center" prop="birthday" >
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="证件类型" align="center" prop="identificationType">
          <template #default="scope">
            <dict-tag :options="sys_id_type" :value="scope.row.identificationType" />
          </template>
        </el-table-column>
        <el-table-column label="证件号码" align="center" prop="identificationNumber" />
        <el-table-column label="请求日期" align="center" prop="requestDate">
          <template #default="scope">
            <span>{{ parseTime(scope.row.requestDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="请求系统" align="center" prop="system">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.system" />
          </template>
        </el-table-column>
        <el-table-column label="证件类型" align="center" prop="requestType">
          <template #default="scope">
            <dict-tag :options="request_type" :value="scope.row.requestType" />
          </template>
        </el-table-column>
        <el-table-column label="请求报文" align="center" prop="requestParams" show-overflow-tooltip/>
        <el-table-column label="返回报文" align="center" prop="responseParams" show-overflow-tooltip/>
        <el-table-column label="错误信息" align="center" prop="errorMessage" show-overflow-tooltip/>
      </el-table>

      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="ApiErrorLog" lang="ts">
import { listApiErrorLog, getApiErrorLog, delApiErrorLog, addApiErrorLog, updateApiErrorLog } from '@/api/customer/apiErrorLog';
import { ApiErrorLogVO, ApiErrorLogQuery, ApiErrorLogForm } from '@/api/customer/apiErrorLog/types';
import { parseTime } from '../../../utils/ruoyi';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_id_type, sys_from_system, request_type, sys_user_sex } = toRefs<any>(
  proxy?.useDict('sys_id_type', 'sys_from_system', 'request_type', 'sys_user_sex')
);

const apiErrorLogList = ref<ApiErrorLogVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const apiErrorLogFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ApiErrorLogForm = {
  errorId: undefined,
  apiName: undefined,
  requestMethod: undefined,
  requestParams: undefined,
  responseParams: undefined,
  errorTime: undefined,
  errorCode: undefined,
  errorMessage: undefined,
  stackTrace: undefined,
  clientIp: undefined,
  userAgent: undefined,
  customerNo: undefined,
  subCustomerNo: undefined,
  name: undefined,
  identificationType: undefined,
  identificationNumber: undefined,
  requestDate: undefined,
  system: undefined,
  requestType: undefined,
  remarks: undefined
};
const data = reactive<PageData<ApiErrorLogForm, ApiErrorLogQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    apiName: undefined,
    requestMethod: undefined,
    requestParams: undefined,
    responseParams: undefined,
    errorTime: undefined,
    errorCode: undefined,
    errorMessage: undefined,
    stackTrace: undefined,
    clientIp: undefined,
    userAgent: undefined,
    customerNo: undefined,
    subCustomerNo: undefined,
    name: undefined,
    identificationType: undefined,
    identificationNumber: undefined,
    requestDate: undefined,
    system: undefined,
    requestType: undefined,
    remarks: undefined,
    params: {}
  },
  rules: {
    errorId: [{ required: true, message: '错误日志ID不能为空', trigger: 'blur' }],
    apiName: [{ required: true, message: '接口名称不能为空', trigger: 'blur' }],
    requestMethod: [{ required: true, message: '请求方法不能为空', trigger: 'blur' }],
    requestParams: [{ required: true, message: '请求参数不能为空', trigger: 'blur' }],
    responseParams: [{ required: true, message: '返回参数不能为空', trigger: 'blur' }],
    errorTime: [{ required: true, message: '出错时间不能为空', trigger: 'blur' }],
    errorCode: [{ required: true, message: '错误代码不能为空', trigger: 'blur' }],
    errorMessage: [{ required: true, message: '错误信息不能为空', trigger: 'blur' }],
    stackTrace: [{ required: true, message: '堆栈跟踪不能为空', trigger: 'blur' }],
    clientIp: [{ required: true, message: '客户端IP不能为空', trigger: 'blur' }],
    userAgent: [{ required: true, message: '用户代理不能为空', trigger: 'blur' }],
    customerNo: [{ required: true, message: '客户号不能为空', trigger: 'blur' }],
    subCustomerNo: [{ required: true, message: '子客户号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
    identificationType: [{ required: true, message: '证件类型不能为空', trigger: 'change' }],
    identificationNumber: [{ required: true, message: '证件号码不能为空', trigger: 'blur' }],
    requestDate: [{ required: true, message: '请求日期不能为空', trigger: 'blur' }],
    system: [{ required: true, message: '请求系统不能为空', trigger: 'blur' }],
    requestType: [{ required: true, message: '请求类型不能为空', trigger: 'change' }],
    remarks: [{ required: true, message: '备注不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询接口错误日志列表 */
const getList = async () => {
  loading.value = true;
  const res = await listApiErrorLog(queryParams.value);
  apiErrorLogList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  apiErrorLogFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ApiErrorLogVO[]) => {
  ids.value = selection.map((item) => item.errorId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加接口错误日志';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ApiErrorLogVO) => {
  reset();
  const _errorId = row?.errorId || ids.value[0];
  const res = await getApiErrorLog(_errorId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改接口错误日志';
};

/** 提交按钮 */
const submitForm = () => {
  apiErrorLogFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.errorId) {
        await updateApiErrorLog(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addApiErrorLog(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ApiErrorLogVO) => {
  const _errorIds = row?.errorId || ids.value;
  await proxy?.$modal.confirm('是否确认删除接口错误日志编号为"' + _errorIds + '"的数据项？').finally(() => (loading.value = false));
  await delApiErrorLog(_errorIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/apiErrorLog/export',
    {
      ...queryParams.value
    },
    `请求错误日志_${new Date().toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit',
      fractionalSecondDigits: 3,
      hour12: false
    })}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
