<template>
  <cacp-search-layout>
    <template #search>
      <cacp-search-panel-layout
        :model="queryParams"
        ref="queryFormRef"
        label-position="left"
        label-width="auto"
        :gutter="30"
      >
      <el-form-item label="字典名称" prop="dictType">
        <el-select v-model="queryParams.dictType">
          <el-option
            style="width: 240px"
            v-for="item in typeOptions"
            :key="item.pkDictType"
            :label="item.dictName"
            :value="item.dictType"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="字典标签" prop="dictLabel">
        <el-input
          style="width: 240px"
          v-model="queryParams.dictLabel"
          placeholder="请输入字典标签"
          clearable
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="数据状态" clearable>
          <el-option
            style="width: 240px"
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
        <template #buttonGroup>
          <el-button type="primary" @click="onSearch">查询</el-button>
          <el-button type="info" @click="onReset">重置</el-button>
        </template>
      </cacp-search-panel-layout>
    </template>
    <cacp-complex-table
      :actions="actions"
      :data="tableData"
      :pagination="tablePagination"
      :actionsWidth="120"
      @selection-change="handleSelectionChange"
      @on-page-change="onPageChange"
      @on-size-change="onSizeChange"
      :loading="loading"
    >
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="字典编码" align="center" prop="dictCode" />-->
      <el-table-column label="字典标签" align="center" prop="dictLabel">
        <template #default="scope">
          <span v-if="(scope.row.listClass == '' || scope.row.listClass == 'default') && (scope.row.cssClass == '' || scope.row.cssClass == null)">{{ scope.row.dictLabel }}</span>
          <el-tag v-else :type="scope.row.listClass == 'primary' ? '' : scope.row.listClass" :class="scope.row.cssClass">{{ scope.row.dictLabel }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="字典键值" align="center" prop="dictValue" />
      <el-table-column label="字典排序" align="center" prop="dictSort" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ dayjs(scope.row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>
    </cacp-complex-table>
  </cacp-search-layout>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字典类型">
          <el-input v-model="form.dictType" :disabled="true" />
        </el-form-item>
        <el-form-item label="数据标签" prop="dictLabel">
          <el-input v-model="form.dictLabel" placeholder="请输入数据标签" />
        </el-form-item>
        <el-form-item label="数据键值" prop="dictValue">
          <el-input v-model="form.dictValue" placeholder="请输入数据键值" />
        </el-form-item>
        <el-form-item label="样式属性" prop="cssClass">
          <el-input v-model="form.cssClass" placeholder="请输入样式属性" />
        </el-form-item>
        <el-form-item label="显示排序" prop="dictSort">
          <el-input-number v-model="form.dictSort" controls-position="right" :min="0" />
        </el-form-item>
        <el-form-item label="回显样式" prop="listClass">
          <el-select v-model="form.listClass">
            <el-option
              v-for="item in listClassOptions"
              :key="item.value"
              :label="item.label + '(' + item.value + ')'"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElForm, ElMessageBox, ElMessage } from 'element-plus'
import type { FormRules, FormInstance } from 'element-plus'
import { listData, getData, delData, addData, updateData } from "@/apis/system/dictData"
import { optionselect as getDictOptionselect, getType, delType, updateType, addType } from '@/apis/system/dictType'
import { SuccessResultCode, type TableAction, useComplexTable, useLoading } from '@cacp/ui'
const { loading, setLoading } = useLoading()
const tableHooks = useComplexTable<DictDataInfo>(config)
const { tableData, tablePagination, setPagination, setPageIndex, setPageSizes } = tableHooks
import dayjs from 'dayjs'
import config from '@/config'
import type { DictDataInfo } from '@/types/system/dictData'
import type { AjaxResult } from '@/types/system/dictType'

// 路由和路由实例
const route = useRoute()
const router = useRouter()

// 字典数据
const sys_normal_disable = [
  { label: '正常', value: '0' },
  { label: '停用', value: '1' }
]
const getStatusTagType = (status: string) => {
  const typeMap: { [key: string]: any } = {
    '0': 'success', // 正常 - 绿色
    '1': 'danger'   // 停用 - 红色
  }
  return typeMap[status] || 'info'
}
// 新增方法：获取状态标签文本
const getStatusLabel = (status: string) => {
  const item = sys_normal_disable.find(item => item.value === status)
  return item ? item.label : status
}
// 数据标签回显样式
const listClassOptions = [
  { value: "default", label: "默认" },
  { value: "primary", label: "主要" },
  { value: "success", label: "成功" },
  { value: "info", label: "信息" },
  { value: "warning", label: "警告" },
  { value: "danger", label: "危险" }
]

const actions = <Array<TableAction>>[
  {
    key: '1',
    text: '新建',
    onclick: handleAdd,
    position: 'left',
    limit: 'none',
    type: 'primary',
  },
  {
    key: '2',
    text: '编辑',
    onclick: handleUpdate,
    limit: 'one',
    type: 'primary'
  },
  {
    key: '3',
    text: '删除',
    onclick: handleDelete,
    confirm: true,
    limit: 'one',
    type: 'primary'
  },
  {
    key: '4',
    text: '删除',
    onclick: handleDelete,
    confirm: true,
    limit: 'none',
    type: 'primary',
    position: 'left'
  },
  {
    key: '5',
    text: '关闭',
    type: 'primary',
    plain: true,
    onclick: handleClose,
    limit: 'none',
    position: 'left'
  },
]

// 表单接口
interface DictDataForm {
  dictCode?: number
  dictLabel?: string
  dictValue?: string
  dictType?: string
  cssClass?: string
  listClass?: string
  dictSort?: number
  status?: string
  remark?: string
}

// 查询参数接口
interface QueryParams {
  pageNum: number
  pageSize: number
  dictType?: string
  dictLabel?: string
  status?: string
}

// 字典类型选项接口
interface TypeOption {
  pkDictType: number
  dictName: string
  dictType: string
}

// 响应式数据
const ids = ref<number[]>([])
const single = ref(true)
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const dataList = ref<any[]>([])
const defaultDictType = ref("")
const title = ref('')
const open = ref(false)
const operBoo = ref(true)
const typeOptions = ref<TypeOption[]>([])

const queryParams = reactive<QueryParams>({
  pageNum: 1,
  pageSize: 10,
  dictType: undefined,
  dictLabel: undefined,
  status: undefined
})

const form = reactive<DictDataForm>({
  dictCode: undefined,
  dictLabel: undefined,
  dictValue: undefined,
  dictType: undefined,
  cssClass: undefined,
  listClass: 'default',
  dictSort: 0,
  status: "0",
  remark: undefined
})

// 表单引用
const queryFormRef = ref<FormInstance>()
const formRef = ref<FormInstance>()

// 表单验证规则
const rules = reactive<FormRules>({
  dictLabel: [
    { required: true, message: "数据标签不能为空", trigger: "blur" }
  ],
  dictValue: [
    { required: true, message: "数据键值不能为空", trigger: "blur" }
  ],
  dictSort: [
    { required: true, message: "数据顺序不能为空", trigger: "blur" }
  ]
})

// 监听选择变化
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map(item => item.dictCode)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 生命周期
onMounted(() => {
  const pkDictType = route.params && route.params.pkDictType as string
  getTypeDetail(Number(pkDictType))
  getTypeList()
})

// 方法
/** 查询字典类型详细 */
const getTypeDetail = (pkDictType: number) => {
  getType(pkDictType).then((response: any) => {
    queryParams.dictType = response.data.dictType
    defaultDictType.value = response.data.dictType
    getList()
  })
}

/** 查询字典类型列表 */
const getTypeList = () => {
  getDictOptionselect().then((response: any) => {
    typeOptions.value = response.data
  })
}

/** 查询字典数据列表 */
const getList = async() => {
  const query = { ...queryParams, pageIndex: tablePagination.currentPage, pageSize: tablePagination.pageSize }
  setLoading(true)
  const res = await listData(query)
  if (res.code == SuccessResultCode) {
    setPagination(res.data)
  }
  setLoading(false)
}

const cancel = () => {
  open.value = false
  reset()
}

const reset = () => {
  Object.assign(form, {
    dictCode: undefined,
    dictLabel: undefined,
    dictValue: undefined,
    cssClass: undefined,
    listClass: 'default',
    dictSort: 0,
    status: "0",
    remark: undefined
  })
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

function onSearch() {
  onPageChange(1)
}

function onReset() {
  formRef.value.resetFields()
  onPageChange(1)
}

function onPageChange(page: number) {
  setPageIndex(page)
  getList()
}
function onSizeChange(size: number) {
  setPageSizes(size)
  getList()
}

/** 返回按钮操作 */
function handleClose(){
  // 这里需要根据实际的路由管理方式调整
  router.push("/system-dictType")
}

function handleAdd (){
  reset()
  open.value = true
  title.value = "添加字典数据"
  form.dictType = queryParams.dictType
}

function handleUpdate(row: DictDataInfo){
  reset()
  const dictCode = row?.dictCode || ids.value[0]
  getData(dictCode).then((response: any) => {
    Object.assign(form, response.data)
    open.value = true
    title.value = "修改字典数据"
  })
}

function submitForm(){
  formRef.value.validate(async (isValid: boolean) => {
    if (isValid) {
      if (form.dictCode) {
        const res: AjaxResult<number> = await updateData(form)
        if(res.code == "200"){
          ElMessage.success("修改成功")
          open.value = false
          getList()
        } else {
          ElMessage.error(res.msg)
        }
      } else {
        const res: AjaxResult<number> = await addData(form)
        if(res.code == "200"){
          ElMessage.success("新增成功")
          open.value = false
          getList()
        } else {
          ElMessage.error(res.msg)
        }
      }
    }
  })
}

async function handleDelete (row?: DictDataInfo){
  const dictCodes = [row?.dictCode] || ids.value
    // 这里需要根据实际的 store 实现调整
    // useDictStore().removeDict(queryParams.dictType)
  const res = await delData(dictCodes)
  if (res.code == "200") {
    ElMessage.success("删除成功")
    onPageChange(1)
  } else {
    ElMessage.error(res.msg)
  }
}
</script>
