<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="deptPath"></el-table-column>
      <el-table-column label="代字" prop="snTitle"></el-table-column>
    </cacp-complex-table>

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

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

import { SuccessResultCode, type TableAction, useLoading, useOperModal } from '@cacp/ui'
import * as apis from '@/apis/form'
import { type DeptSn, initDeptSn } from './types'

import DeptSnDetail from './DeptSnDetail.vue'

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

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<DeptSn>>([])

onMounted(async () => {
  await initData()
})

async function initData() {
  setLoading(true)

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

  setLoading(false)
}

function onInsert() {
  setOperModal('insert', true, initDeptSn)
}
async function onDelete(info: DeptSn) {
  const res = await apis.deleteDeptSn(info.deptId)
  if (res.code === SuccessResultCode) {
    ElMessage.success('删除成功')
    await initData()
  }
}
function onShow(info: DeptSn) {
  setOperModal('show', true, info)
}

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

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