<template>
  <div>
    <Title>
      <template v-slot:titleName>异常事件列表</template>
      <template v-slot:titleContent></template>
      <template v-slot:titleOperate>
      </template>
    </Title>

     <!--搜索条件-->
     <div class="form-container">
         <AbQueryForm :formModel="queryFromModel" :fieldConfigs="queryFromData" :span="6" :criteriaShowNumber="8" :queryCriteriaOffset=[15,2] 
         :queryEvent="queryLogsEvent">
         </AbQueryForm>
     </div>
    <!--列表-->
    <div class="table-container" v-loading="tableloading">
      <vxe-grid ref="tableRef" v-bind="tableOptions">
        <template #tools_toolbar>
        </template>
        <template #state="{ row }">
          <el-text type="danger" v-if="row.state === -1">失败</el-text>
          <el-text type="success" v-else-if="row.state === 1">成功</el-text>
          <el-text v-else>待处理</el-text>
        </template>
        <template #information="{ row }">
          <ClickCopy :content="row.information" ></ClickCopy>
        </template>
        <template #operate="{ row }">
          <el-link type="primary"  :underline="false" @click="dialogFormShow(row)" title="详情"><el-icon size="20"><Document /></el-icon></el-link>
          &nbsp;
          <el-link v-if="row.state!==1" type="primary" @click="sendRetryAbnormalEvent(row.code)"  :underline="false"  title="重试">重试</el-link>
        </template>
      </vxe-grid>
    </div>
  </div>
  

  <!--重试记录-->
  <el-dialog v-model="dialogFormVisible" width="90%" :title="currentTableRow.describes+'('+currentTableRow.businessCode+')'" >
      <vxe-grid v-if="dialogFormVisible" ref="detailtableRef" v-bind="detailTableOptions" :data="detailTableData" >
        <template #tools_toolbar>
        </template>
        <template #requestData="{ row }">
          <ClickCopy :content="row.requestData" ></ClickCopy>
        </template>
        <template #responseData="{ row }">
          <ClickCopy :content="row.responseData" ></ClickCopy>
        </template>
        <template #error="{ row }">
          <ClickCopy :content="row.error" ></ClickCopy>
        </template>
      </vxe-grid>
  </el-dialog> 

</template>
  

<script lang="ts">
export default { name: "abnormalEvent" }
</script>
<script setup lang="ts">
import XEUtils from 'xe-utils'
import Title from "@/framework/components/Title/index.vue";
import { queryAbnormalEvents,retryAbnormalEvent,queryAbnormalEventLogs,queryBusinessDicts,querySubsystems } from '@/subsystem/api/sms/abnormal.ts'

import { useQueryParamsHandle,useTableQueryReload } from '@/framework/hooks/useVxeTableHandle'
import { gridDefaultProps } from '@/framework/utils/standard/vxe.ts'
import AbQueryForm from "@/framework/components/standard/FormDynamic/abQueryForm.vue";
import ClickCopy from "@/framework/components/standard/ClickCopy/index.vue";
import { handleSelectData } from '@/framework/utils/standard/dataHandleUtil.ts'

const tableloading=ref(false)
/**查询表单 */
const queryFromModel = ref({})
const queryFromData = reactive([
  { name: "操作时间", type: "datetimerange", key: "crtTime", 
    value: ref<[String, String]>([XEUtils.toDateString(XEUtils.getWhatDay (new Date(), -7), 'yyyy-MM-dd 00:00:00'), XEUtils.toDateString(new Date(), 'yyyy-MM-dd 23:59:59')])
  },
  { name: "状态", type: "select", key: "state",value:"0", listData: [{ value: '0', label: '待处理' }, { value: '1', label: '成功' },{ value: '-1', label: '失败' },]},
  { name: "微服务", type: "select", key: "subsystem",value:"", },
  {name: "业务类型", type: "select", key: "businessType", value:''},
  { name: "业务码", type: "input", key: "businessCode" ,value:""},
  
])
const queryLogsEvent = () => {
   useTableQueryReload(tableRef.value)
}

/**表格初始化 */
const tableRef = ref<VxeGridInstance>()//表格对象
const tableOptions = reactive<VxeGridProps>(gridDefaultProps({
  params: reactive<VxeTableParam>({
    clientPage: false, //是否客户端分页
  }),
  rowConfig: {keyField: 'id'},//自定义行数据唯一主键的字段名
  pagerConfig: { enabled: true, pageSize: 10, pageSizes: [10, 20, 50, 100] },//分页配置
  toolbarConfig: { export: false, custom: true, slots: {  tools: 'tools_toolbar' },  },//工具栏配置
  exportConfig: { type: 'xlsx', types: ['xlsx'], modes: ['all'] },
  proxyConfig: {
    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
    props: { result: 'data', total: 'total' },// 对应响应结果，按照后台服务PageResult对象配置
    ajax: {
      // 接收 Promise 对象
      query: ({ page, sorts, filters }) => {
         const params={
          startdate:'',enddate:'',
          subsystem:queryFromModel.value.subsystem,
          businessType:queryFromModel.value.businessType,
          businessCode:queryFromModel.value.businessCode,
          state:queryFromModel.value.state,
          }

         if(''!=queryFromModel.crtTime){
            params.startdate=XEUtils.toDateString(queryFromModel.value.crtTime[0], 'yyyy-MM-dd HH:mm:ss')
            params.enddate=XEUtils.toDateString(queryFromModel.value.crtTime[1], 'yyyy-MM-dd HH:mm:ss')
         }
         const queryParams = useQueryParamsHandle(params, page, sorts, filters)//请求参数处理
         return queryAbnormalEvents(queryParams) //服务端分页查询
      },
    }
  },
  columns: [
   { type: 'seq', title: '序号',align:'center',width:'50px'},
  //  { field: 'tenant', title: '租户号'  ,align:'center',width:'80px',},
   { field: 'code', title: '事件编码',visible:false,},
   { field: 'subsystem', title: '微服务',},
   { field: 'businessType',title: '业务类型' },
   { field: 'businessCode',title: '业务码' ,},
   { field: 'describes',title: '描述' , },
   { field: 'information',title: '消息数据', slots: {default: 'information'},},
   { field: 'crtDate', title: '创建时间',},
   { field: 'handleUrl',title: '处理接口地址',visible:false},
   { field: 'state',title: '处理状态' , slots: {default: 'state'}, },
   { field: 'retryCount', title: '重试次数'},
   { field: 'updDate',title: '修改时间' , visible:false,},
   { field: 'completeDate',title: '完成时间' ,visible:false,},
   { field: '', title: '操作',slots: {default: 'operate'},align:'center',minWidth:'5%'},//操作类居中显示 
  ]
}))

/**重试记录表格初始化 */
const currentTableRow=ref({})
const dialogFormVisible=ref(false)
const detailFilterName = ref('')
const detailTableData = ref([])
const detailtableRef = ref<VxeGridInstance>()//表详情表格对象
const detailTableOptions = reactive<VxeGridProps>(gridDefaultProps({
  params: reactive<VxeTableParam>({
    clientPage: true, //是否客户端分页
    tableDataCache: detailTableData, //表格数据缓存
    filterNameRef: detailFilterName, //表内搜索引用
    searchProps: ['name','columntype','defaultvalue','description'],//需要检索列的key
  }),
  toolbarConfig: { custom: true, slots: { tools: 'tools_toolbar' }, },//工具栏配置
  proxyConfig: {
    seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
    sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
    filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
    props: { result: 'data', total: 'total' },// 对应响应结果，按照后台服务PageResult对象配置
    ajax: {
      // 接收 Promise 对象
      query: ({ page, sorts, filters }) => {
         const params={code:currentTableRow.value.code}
         return queryAbnormalEventLogs(params) //服务端分页查询
      },
    }
  },
  columns: [
    { type: 'seq', title: '序号', width:'50px'},
    { field: 'requestUrl', title: '请求地址', },
    { field: 'requestData', title: '请求数据', slots: {default: 'requestData'},  },
    { field: 'responseData', title: '请求结果', slots: {default: 'responseData'},   },
    { field: 'error', title: '错误信息', slots: {default: 'error'},},
    { field: 'crtdate', title: '创建时间',},
  ]
}))
const dialogFormShow = (row) => {
    dialogFormVisible.value=true
    currentTableRow.value=row
    detailTableData.value=row.fields
}

const  sendRetryAbnormalEvent= (code) => {
  tableloading.value=true
  retryAbnormalEvent({code:code}).then((data: any) => {
    useTableQueryReload(tableRef.value)
    ElMessage({message: '操作成功',type: 'success',})
  }).finally(() => {
    tableloading.value=false
  });
}


onMounted(() => {
  /**加载下拉框数据 */
  queryBusinessDicts().then((data: any) => {
    let arrays=handleSelectData(data,false)
    queryFromData[3].listData=arrays
    queryFromData[3].value=arrays[0].value
  })
  querySubsystems().then((data: any) => {
    let arrays=handleSelectData(data,false)
    queryFromData[2].listData=arrays
    queryFromData[2].value=arrays[0].value
  })


});

</script>

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