<template>
  <div class="cacp-pd-m" style="height: 100%">
    <cacp-complex-table
      class="cacp-pd-m cacp-search__content"
      :actions="tableActions"
      :secondary-colSpan="24"
      :data="list"
      :loading="loading"
      stripe
    >
      <template #title>
        <div class="title cacp-mb-m">消息类型列表</div>
      </template>
      <el-table-column label="应用代码" prop="appCode"></el-table-column>
      <el-table-column label="类型代码" prop="typeCode"></el-table-column>
      <el-table-column label="发送人" prop="senderId"></el-table-column>
      <el-table-column label="接收人" prop="receiverId"></el-table-column>
      <el-table-column label="通道" prop="channel"></el-table-column>
    </cacp-complex-table>

    <message-type-detail
      :visible="visible"
      :mode="mode"
      :info="info"
      @on-save="onSave"
      @on-close="onClose"
    ></message-type-detail>
  </div>
</template>

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

import { SuccessResultCode, type TableAction, type HeaiMessageTypeInfo, useLoading, useOperModal } from '@cacp/ui'
import * as apis from '@/apis/heai'
import { initMessageType } from './types'

import MessageTypeDetail from './HeaiMessageTypeDetail.vue'

const { loading, setLoading } = useLoading(false)
const { mode, visible, info, setOperModal, clearOperModal } = useOperModal(initMessageType)

const tableActions: Array<TableAction> = [
  {
    key: 'show',
    type: 'default',
    limit: 'one',
    text: '查看',
    onclick: onShow
  },
  {
    key: 'insert',
    type: 'primary',
    limit: 'none',
    position: 'left',
    text: '新建',
    onclick: onInsert
  },
  {
    key: 'delete',
    type: 'danger',
    limit: 'one',
    text: '删除',
    confirm: '确定要删除吗?',
    onclick: onDelete
  }
]

const list = ref<Array<HeaiMessageTypeInfo>>([])

onMounted(async () => {
  setLoading(true)

  const res = await apis.getMessageTypeList()
  if (res.code === SuccessResultCode && res.data) {
    list.value = res.data
  }

  setLoading(false)
})

function onInsert() {
  setOperModal('insert', true, initMessageType)
}
async function onDelete(info: HeaiMessageTypeInfo) {
  const res = await apis.deleteMessageType(info.typeCode)
  if (res.code === SuccessResultCode) {
    const idx = list.value.findIndex((item) => item.typeCode === info.typeCode)
    list.value.splice(idx, 1)
    ElMessage.success('删除成功')
  }
}
function onShow(info: HeaiMessageTypeInfo) {
  setOperModal('show', true, info)
}

async function onSave(info: HeaiMessageTypeInfo) {
  if (mode.value === 'insert') {
    const res = await apis.insertMessageType(info)
    if (res.code === SuccessResultCode) {
      list.value.push(info)
      ElMessage.success('保存成功')
      clearOperModal()
    }
  }
}
function onClose() {
  clearOperModal()
}
</script>

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