<!--
 * @Author: xiejiang
 * @Date: 2024-11-11 09:38:40
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-11 23:23:32
 * @Description: 系统字典-管理子集
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
-->
<template>
  <div class="bg-white p-[12px] h-full">
    <Back />
    <main class="m-auto max-w-[1012px]">
      <!-- 基本信息 -->
      <PageTitle title="基本信息" class="mb-[24px] mt-[12px]" />
      <div class="flex flex-wrap" v-loading="detailLoading">
        <DetailTable label="字典大类" :value="dataInfo.categoryName" />
        <DetailTable label="字典名称" :value="dataInfo.dictName" />
        <DetailTable label="字典编码" :value="dataInfo.dictCode" />
        <DetailTable label="字典属性">
          <div class="flex flex-wrap">
            <span
              v-for="v in dictionarys"
              :key="v.value"
              :class="'dictionary ' + dictionaryAttributeTxt(dataInfo[v.value] ? v.allow : v.noAllow)?.class"
            >
              {{ dictionaryAttributeTxt(dataInfo[v.value] ? v.allow : v.noAllow)?.label }}
            </span>
          </div>
        </DetailTable>
        <DetailTable label="字典说明" width="100%" :value="dataInfo.remark" />
      </div>
      <PageTitle title="枚举值" class="my-[24px]" />
      <t-table
        :data="tableData"
        :columns="columns"
        :loading="loading"
        max-height="400px"
        @page-change="onPageChange"
        :pagination="pagination.total > 10 ? pagination : undefined"
      >
        <!-- 保留自定义列插槽 -->
        <template v-for="(_, name) in $slots" #[name]="scope">
          <slot :name="name" v-bind="scope" />
        </template>
        <template v-for="col in columns" #[soltName(col)]="{ row }" :key="col.colKey">
          <template v-if="col.colKey != 'operation'">
            <div class="cell-content">{{ row[col.colKey as string] || '-' }}</div>
          </template>
        </template>
      </t-table>
      <div class="table-add">
        <span class="cursor-pointer text-[var(--td-brand-color)]" @click="handleAdd">+ 新增 </span>
      </div>
    </main>

    <!-- 新增编辑枚举值 -->
    <DictionarySubsetEdit ref="dictionarySubsetEditRef" @success="resetPageData" />
  </div>
</template>

<script setup lang="tsx" name="dictionary-subset">
import { useRoute } from 'vue-router'
import { MessagePlugin, PrimaryTableCol, PaginationProps } from 'tdesign-vue-next'
import { ArrowDownIcon, ArrowUpIcon } from 'tdesign-icons-vue-next'
import { useBasic } from '@/hooks/useBasic'
import MessageBox from '@/utils/messageBox'
import { soltName } from '@/utils'
import { dictionaryAttributeTxt } from '@/utils/status'
import { ResDictionary } from '@/api/interface/dectionory'
import {
  getGetDictDataInfo,
  getGetDictDataList,
  dectionoryPostSort,
  postRemoveDictData
} from '@/api/modules/dectionory'
import DictionarySubsetEdit from './page/dictionary-subset-edit.vue'

const { setBreadcrumb } = useBasic()
const route = useRoute()

const dataInfo = ref<ResDictionary>({
  categoryName: '',
  dictName: '',
  dictCode: '',
  remark: '',
  dictId: '',
  isAllowAddsub: 0,
  isAllowDelete: 0
})

const tableData = ref<ResDictionary[]>([])

const dictionarys = [
  {
    value: 'isAllowAddsub',
    allow: 3,
    noAllow: 4
  },
  {
    value: 'isAllowDelete',
    allow: 5,
    noAllow: 6
  },
  {
    value: 'isAllowEdit',
    allow: 1,
    noAllow: 2
  }
]

const detailLoading = ref(false)
// 查询子集详情
const getData = () => {
  detailLoading.value = true
  getGetDictDataInfo({ dictId: route.query.dictId as string })
    .then(res => {
      dataInfo.value = res.data
    })
    .finally(() => {
      detailLoading.value = false
    })
}

// 查询子集列表
const loading = ref(false)
const pagination = ref({
  page: 1,
  limit: 10,
  total: 0
})
// 表格columns配置
const columns: PrimaryTableCol[] = [
  {
    title: '序号',
    colKey: 'serial-number',
    width: 70
  },
  { title: '值名称', colKey: 'valueName' },
  { title: '值编码', colKey: 'dataCode' },
  { title: '备注', colKey: 'remark' },
  {
    title: '快速排序',
    colKey: 'sort',
    width: 88,
    cell: (h, { row }: { row: any }) => {
      return (
        <div class='flex items-center text-[var(--td-brand-color)]'>
          <operate-btn
            content=''
            class='ico-btn'
            disabled={row.isFirst ? true : false}
            onClick={handleSort(row, false)}
          >
            <ArrowUpIcon />
          </operate-btn>
          <operate-btn content='' class='ico-btn' disabled={row.isLast ? true : false} onClick={handleSort(row, true)}>
            <ArrowDownIcon />
          </operate-btn>
        </div>
      )
    }
  },
  {
    title: '操作',
    colKey: 'operation',
    width: 150,
    cell: (h, { row }: { row: any }) => {
      return (
        <div class='flex items-center'>
          <operate-btn content='编辑' class='mr-[8px]' onClick={handleEdit(row)}></operate-btn>
          <operate-btn content='删除' onClick={handleDel(row)}></operate-btn>
        </div>
      )
    }
  }
]

const dictionarySubsetEditRef = ref()

// 编辑
const handleEdit = (row: ResDictionary) => () => {
  dictionarySubsetEditRef.value?.open(row)
}
// 新增
const handleAdd = () => {
  dictionarySubsetEditRef.value?.open({ dictId: route.query.dictId })
}

const resetPageData = () => {
  pagination.value.page = 1
  GetDictDataList()
}

// 表格分页
const onPageChange = (val: PaginationProps) => {
  pagination.value.page = val.current as number
  pagination.value.limit = val.pageSize as number
  GetDictDataList()
}

// 删除
const handleDel = (row: ResDictionary) => () => {
  const dialog = MessageBox(3, {
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定', loading: true } })
      postRemoveDictData({
        dictDataId: row?.dictDataId
      })
        .then(() => {
          GetDictDataList()
          MessagePlugin.success('操作成功')
          dialog.hide()
        })
        .catch(() => {
          MessagePlugin.error('操作失败')
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定', loading: false } })
        })
    }
  })
}

// 排序
const handleSort = (row: ResDictionary, isUp: boolean) => () => {
  const sort = isUp ? (row?.sort ?? 0) - 1 : (row?.sort ?? 0) + 1
  dectionoryPostSort({ dictDataId: row.dictDataId as string, newSortNum: sort }).then(() => {
    MessagePlugin.success('排序成功')
    GetDictDataList()
  })
}

// 获取枚举数据列表
const GetDictDataList = () => {
  loading.value = true
  getGetDictDataList({ dictId: route.query.dictId as string })
    .then(res => {
      tableData.value = res.data || []
      pagination.value.total = res?.recordsFiltered as number
    })
    .finally(() => {
      loading.value = false
    })
}

onMounted(() => {
  setBreadcrumb([
    {
      title: '系统配置'
    },
    {
      title: '系统字典',
      name: 'dictionary'
    },
    {
      title: '管理子集'
    }
  ])
  getData()
  GetDictDataList()
})
</script>

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

.table-add {
  width: 100%;
  padding: 13px;
  height: 42px;
  box-sizing: border-box;
  background: var(--td-brand-color-1);
}

:deep(.ico-btn) {
  padding: 0;
}
</style>
