<!--
 * @Author: xiejiang
 * @Date: 2024-11-11 09:38:40
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-11 20:20:12
 * @Description: 系统字典
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
-->
<template>
  <div class="h-full dictionary">
    <PageContainer
      :filter-conditions="filterConditions"
      :table-data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @search-change="handleSearch"
      @on-search="onSearch"
      @clear="handleClear(true)"
      @page-change="handlePage"
    >
      <template #header-left>
        <SearchWithButton
          :loading="loading"
          placeholder="搜索字典大类，字典名称"
          v-model="categoryNameOrDictName"
          @on-search="handleSearch(searchParams)"
          @clear="handleClear(null)"
      /></template>

      <template #header-right>
        <div class="flex items-center justify-end gap-2">
          <t-button theme="primary" @click="handelEdit(null)">
            <template #icon><AddIcon /></template>
            新增字典</t-button
          >
        </div>
      </template>

      <template #operation="{ row }">
        <operate-btn v-if="row.status != '2'" content="启用" @click="handelStatus(row, 2)"> </operate-btn>
        <operate-btn v-if="row.isAllowEdit || row.status == '1'" content="编辑" @click="handelEdit(row)"> </operate-btn>
        <operate-btn v-if="row.isAllowAddsub || row.status == '1'" content="管理子集" @click="handelSubset(row)">
        </operate-btn>
        <operate-btn v-if="row.status == '2'" content="停用" @click="handelStatus(row, 1)"> </operate-btn>
        <operate-btn v-if="row.isAllowDelete || row.status == '1'" content="删除" @click="handelDel(row)"></operate-btn>
      </template>
    </PageContainer>

    <!-- 编辑新增字典 -->
    <DictionaryEdit ref="dictionaryEditRef" @success="handleSearch(searchParams)" />
  </div>
</template>

<script setup lang="tsx" name="dictionary">
import { useRouter } from 'vue-router'
import { PrimaryTableCol, MessagePlugin } from 'tdesign-vue-next'
import type { filterItemProp } from '@/components/PageFilters/interface/index'
import type { Pagination } from '@/components/PageContainer/interface/index'
import { statusTxt, dictionaryAttributes, dictionaryAttributeTxt } from '@/utils/status'
import { useBasic } from '@/hooks/useBasic'
import MessageBox from '@/utils/messageBox'
import { ResDictionary } from '@/api/interface/dectionory'
import {
  getDectionoryList,
  postEnableDictionary,
  postDisableDictionary,
  postRemoveDictionary
} from '@/api/modules/dectionory'
import DictionaryEdit from './page/dictionary-edit.vue'

defineOptions({
  name: 'dictionary'
})

const { setBreadcrumb } = useBasic()
const router = useRouter()

// 初始加载
onMounted(() => {
  setBreadcrumb([
    {
      title: '系统配置'
    },
    {
      title: '系统字典'
    }
  ])
  getData()
})

onActivated(() => {
  getData()
})

const dictionaryEditRef = ref()

// 加载状态
const loading = ref(false)
// 分页配置
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0
})

const categoryNameOrDictName = ref('')

// 筛选项配置，type类型参考pageFilters组件下的ts定义
const filterConditions = computed<filterItemProp[]>(() => [
  {
    label: '字典属性',
    prop: 'type',
    type: 'select',
    selectData: dictionaryAttributes
  },
  {
    label: '字典状态',
    prop: 'status',
    type: 'select',
    selectData: [
      { label: '编辑中', value: 1 },
      { label: '启用', value: 2 },
      { label: '停用', value: 3 }
    ]
  }
])

// 表格columns配置
const columns: PrimaryTableCol[] = [
  {
    title: '序号',
    colKey: 'serial-number',
    width: 70
  },
  { title: '字典大类', colKey: 'categoryName' },
  { title: '字典名称', colKey: 'dictName' },
  { title: '字典编码', colKey: 'dictCode' },
  { title: '字典说明', colKey: 'remark' },
  {
    title: '字典属性',
    colKey: 'attribute',
    width: 320,
    cell: (h, { row }: { row: any }) => {
      const attributes = attributeTxt(row)
      return (
        <div>
          {attributes.map(item => (
            <span class={'dictionary ' + dictionaryAttributeTxt(item)?.class}>
              {dictionaryAttributeTxt(item)?.label}
            </span>
          ))}
        </div>
      )
    }
  },
  {
    title: '字典状态',
    colKey: 'status',
    cell: (h, { row }) => {
      return (
        <div class='flex items-center'>
          <div class={'dot ' + statusTxt(Number(row.status))?.class}></div>
          <span class={statusTxt(Number(row.status))?.class}>{statusTxt(Number(row.status))?.title}</span>
        </div>
      )
    }
  },
  {
    title: '添加人',
    colKey: 'inputUserName',
    width: 120,
    cell: (h, { row }) => {
      return (
        <div class='flex items-center justify-between'>
          <t-tooltip content={row.inputUserName}>
            <div class={row.inputUserDelFlag ? 'w-[calc(100%-58px)] ellipsis' : ''}>
              <span>{row.inputUserName || '-'}</span>
            </div>
          </t-tooltip>
          {row.inputUserDelFlag ? <span class='inputUserName-del'>已删除</span> : ''}
        </div>
      )
    }
  },
  { title: '添加时间', colKey: 'inputTime' },
  { title: '操作', colKey: 'operation', fixed: 'right', width: 230 }
]

// 表格数据，自行规范ts
const tableData = ref<ResDictionary[]>([])

// 获取表格数据接口
const getData = () => {
  loading.value = true
  let filterConditions = { ...searchParams.value }
  const types = [
    { isAllowEdit: 1 },
    { isAllowEdit: 0 },
    { isAllowAddsub: 1 },
    { isAllowAddsub: 0 },
    { isAllowDelete: 1 },
    { isAllowDelete: 0 }
  ]
  filterConditions = { ...filterConditions, ...types[filterConditions.type - 1] }

  const postData = {
    ...pagination.value,
    ...filterConditions,
    categoryNameOrDictName: categoryNameOrDictName.value
  }
  getDectionoryList(postData)
    .then(res => {
      tableData.value = res.data
      pagination.value.total = res?.recordsFiltered as number
    })
    .finally(() => {
      loading.value = false
    })
}

// 处理字典属性
function attributeTxt(row: ResDictionary): number[] {
  return [row.isAllowEdit ? 1 : 2, row.isAllowAddsub ? 3 : 4, row.isAllowDelete ? 5 : 6]
}

const searchParams = ref<Record<string, any>>({}) // 搜索筛选

// 处理搜索条件
const handleSearch = (params: Record<string, any>) => {
  pagination.value.page = 1
  searchParams.value = params
  getData()
}

const onSearch = (params: Record<string, any>) => {
  searchParams.value = params
}
// 清空搜索条件
const handleClear = (flge: boolean | null) => {
  if (flge) {
    searchParams.value = {}
  }
  categoryNameOrDictName.value = ''
  pagination.value.page = 1
  getData()
}

// 处理分页
const handlePage = (pageInfo: Pagination) => {
  pagination.value = { ...pagination.value, ...pageInfo }
  getData()
}

const handelEdit = (row: ResDictionary | null) => {
  dictionaryEditRef.value?.open(row)
}

// 管理子集
const handelSubset = (row: ResDictionary) => {
  router.push({
    name: 'dictionary-subset',
    query: {
      dictId: row?.dictId
    }
  })
}

// 状态
const handelStatus = (row: ResDictionary, status: number) => {
  const submit = status == 1 ? postDisableDictionary : postEnableDictionary
  const dialog = MessageBox(status, {
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定', loading: true } })
      submit({
        dictId: row?.dictId
      })
        .then(() => {
          getData()
          MessagePlugin.success('操作成功')
          dialog.hide()
        })
        .catch(() => {
          MessagePlugin.error('操作失败')
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定', loading: false } })
        })
    }
  })
}

// 删除
const handelDel = (row: ResDictionary) => {
  const status = row.isExistsSub ? 4 : 5
  const dialog = MessageBox(status, {
    confirmBtn: status == 4 ? null : '确定删除',
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定删除', loading: true } })
      postRemoveDictionary({
        dictId: row?.dictId
      })
        .then(() => {
          getData()
          MessagePlugin.success('操作成功')
          dialog.hide()
        })
        .catch(() => {
          MessagePlugin.error('操作失败')
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定删除', loading: false } })
        })
    }
  })
}
</script>

<style lang="less" scoped>
@import './comm.less';
</style>
