<template>
  <cacp-search-layout>
    <template #search>
      <cacp-search-panel-layout
        :model="query"
        ref="formRef"
        label-width="auto"
        label-position="left"
        :gutter="30"
        :colSpan="6"
      >
        <el-form-item label="关键字" prop="searchKey">
          <el-input v-model="query.searchKey"></el-input>
        </el-form-item>
        <el-form-item label="收发标志" prop="type">
          <el-select v-model="query.type">
            <el-option :value="false" label="发送"></el-option>
            <el-option :value="true" label="接收"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="消息状态" prop="flag">
          <el-select v-model="query.flag">
            <el-option value="WAITING" label="WAITING"></el-option>
            <el-option value="COMPLETED" label="COMPLETED"></el-option>
            <el-option value="ERROR" label="ERROR"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用消息Id">
          <el-input v-model="query.appMsgId"></el-input>
        </el-form-item>
        <el-form-item label="消息类型">
          <el-input v-model="query.messageType"></el-input>
        </el-form-item>
        <el-form-item label="业务Id">
          <el-input v-model="query.bizId"></el-input>
        </el-form-item>

        <el-form-item label="最后日期">
          <el-date-picker type="date" value-format="YYYY-MM-DD" v-model="query.beginDate" placeholder="" />
        </el-form-item>
        <el-form-item label="到">
          <el-date-picker type="date" value-format="YYYY-MM-DD" v-model="query.endDate" placeholder="" />
        </el-form-item>

        <template #buttonGroup>
          <el-button type="primary" @click="loadData">查询</el-button>
        </template>
      </cacp-search-panel-layout>
    </template>
    <cacp-complex-table
      :actions="tableActions"
      :loading="loading"
      :data="tableData"
      :pagination="tablePagination"
      @on-page-change="onPageChange"
      @on-size-change="onSizeChange"
      stripe
    >
      <template #title>
        <div class="title">消息列表</div>
      </template>
      <el-table-column label="应用消息Id" prop="appMsgId" width="130"></el-table-column>
      <el-table-column label="消息Id" prop="messageId" width="130"></el-table-column>
      <el-table-column label="消息类型" prop="messageType" width="130"></el-table-column>
      <el-table-column label="业务Id" prop="bizId" width="130"></el-table-column>
      <el-table-column label="重试次数" prop="retryCount" width="110"></el-table-column>
      <el-table-column label="完成标志" prop="completed" width="130"></el-table-column>
      <el-table-column label="最后时间" prop="lastTime" min-width="160"></el-table-column>
    </cacp-complex-table>
  </cacp-search-layout>

  <message-detail
    :visible="visible"
    :mode="mode"
    :app-msg-id="info.appMsgId"
    :flag="previousValue.flag"
    :type="previousValue.type"
    @on-close="onClose"
  ></message-detail>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'

import config from '@/config'
import {
  SuccessResultCode,
  type TableAction,
  type HeaiMessageInfo,
  type HeaiMessageQueryInfo,
  useLoading,
  useOperModal,
  useComplexTable
} from '@cacp/ui'
import * as apis from '@/apis/heai'
import { usePrevious } from '@/hooks/previous'
import { initMessage } from './types'

import MessageDetail from './HeaiMessageDetail.vue'

const { loading, setLoading } = useLoading(false)
const { mode, visible, info, setOperModal, clearOperModal } = useOperModal(initMessage)
const { tableData, tablePagination, setPagination, setPageIndex, setPageSizes } = useComplexTable(config)
const tableActions: Array<TableAction> = [
  {
    key: 'show',
    type: 'default',
    limit: 'one',
    icon: 'View',
    tooltip: '查看',
    onclick: onShow
  },
  {
    key: 'update',
    type: 'warning',
    limit: 'one',
    icon: 'Edit',
    tooltip: '修改',
    onclick: onUpdate
  },
  {
    key: 'towaiting',
    type: 'danger',
    limit: 'one',
    icon: 'Back',
    tooltip: '移动到待处理',
    disabled: () => previousValue.value.flag === 'WAITING',
    onclick: onToWaiting
  },
  {
    key: 'tocomplete',
    type: 'danger',
    limit: 'one',
    icon: 'ArrowRight',
    tooltip: '移动到完成',
    disabled: () => previousValue.value.flag !== 'WAITING',
    onclick: onToComplete
  },
  {
    key: 'toerror',
    type: 'danger',
    limit: 'one',
    icon: 'DArrowRight',
    tooltip: '移动到错误',
    disabled: () => previousValue.value.flag !== 'WAITING',
    onclick: onToError
  }
]

const query = ref<HeaiMessageQueryInfo>({
  type: true,
  flag: 'WAITING',
  appMsgId: '',
  messageType: '',
  bizId: '',
  searchKey: '',
  beginDate: dayjs().startOf('month').format('YYYY-MM-DD'),
  endDate: dayjs().format('YYYY-MM-DD'),
  pageIndex: tablePagination.currentPage,
  pageSize: tablePagination.pageSize
})
const { previousValue } = usePrevious(query)

onMounted(async () => {})

async function loadData() {
  setLoading(true)
  query.value = { ...query.value }
  const res = await apis.queryMessagePage(query.value)
  if (res.code === SuccessResultCode && res.data) {
    setPagination(res.data)
  }
  setLoading(false)
}

function onShow(info: HeaiMessageInfo) {
  setOperModal('show', true, info)
}
function onUpdate(info: HeaiMessageInfo) {
  setOperModal('update', true, info)
}

async function onToWaiting(info: HeaiMessageInfo) {
  const res = await apis.transferWaiting(info.appMsgId, previousValue.value.type, previousValue.value.flag)
  if (res.code === SuccessResultCode) {
    ElMessage.success('移动成功')
    query.value.pageIndex = 1
    await loadData()
  }
}
async function onToComplete(info: HeaiMessageInfo) {
  const res = await apis.transferCmplete(info.appMsgId, previousValue.value.type)
  if (res.code === SuccessResultCode) {
    ElMessage.success('移动成功')
    query.value.pageIndex = 1
    await loadData()
  }
}
async function onToError(info: HeaiMessageInfo) {
  const res = await apis.transferError(info.appMsgId)
  if (res.code === SuccessResultCode) {
    ElMessage.success('移动成功')
    query.value.pageIndex = 1
    await loadData()
  }
}

function onClose() {
  clearOperModal()
}

async function onPageChange(currentPage: number) {
  query.value.pageIndex = currentPage
  setPageIndex(currentPage)
  await loadData()
}

async function onSizeChange(size: number) {
  setPageSizes(size)
  query.value.pageSize = size
  await loadData()
}
</script>

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