<template>
   <div class="app-container">
      <basic-table
         ref="tableRef"
         :columns="columns"
         :search-columns="searchColumns"
         :query="queryList"
         :extra-params="extraParams"
         :auto-load="false"
         row-key="dictCode"
      >
         <template #toolbar="{ selection, ids }">
            <el-col :span="1.5">
               <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="handleAdd"
                  v-hasPermi="['system:dict:add']"
               >新增</el-button>
            </el-col>
            <el-col :span="1.5">
               <el-button
                  type="success"
                  plain
                  icon="Edit"
                  :disabled="selection.length !== 1"
                  @click="handleUpdate(selection[0])"
                  v-hasPermi="['system:dict:edit']"
               >修改</el-button>
            </el-col>
            <el-col :span="1.5">
               <el-button
                  type="danger"
                  plain
                  icon="Delete"
                  :disabled="!selection.length"
                  @click="handleDelete(ids)"
                  v-hasPermi="['system:dict:remove']"
               >删除</el-button>
            </el-col>
            <el-col :span="1.5">
               <el-button
                  type="warning"
                  plain
                  icon="Download"
                  @click="handleExport"
                  v-hasPermi="['system:dict:export']"
               >导出</el-button>
            </el-col>
            <el-col :span="1.5">
               <el-button
                  type="warning"
                  plain
                  icon="Close"
                  @click="handleClose"
               >关闭</el-button>
            </el-col>
         </template>

         <template #col-dictLabel="{ row }">
            <span v-if="(row.listClass == '' || row.listClass == 'default') && (row.cssClass == '' || row.cssClass == null)">{{ row.dictLabel }}</span>
            <el-tag v-else :type="row.listClass == 'primary' ? '' : row.listClass" :class="row.cssClass">{{ row.dictLabel }}</el-tag>
         </template>

         <template #col-action="{ row }">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['system:dict:edit']">修改</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(row.dictCode)" v-hasPermi="['system:dict:remove']">删除</el-button>
         </template>
      </basic-table>

      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
         <el-form ref="dataRef" :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-option>
               </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"
                     :value="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-input>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitForm">确 定</el-button>
               <el-button @click="cancel">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Data">
import useDictStore from '@/store/modules/dict'
import { getType } from "@/api/system/dict/type"
import { listData, getData, delData, addData, updateData } from "@/api/system/dict/data"

const { proxy } = getCurrentInstance()
const { sys_normal_disable } = useDict("sys_normal_disable")

const tableRef = ref()
const open = ref(false)
const title = ref("")
const route = useRoute()
// 上级字典类型（来自路由，固定参数，不随搜索重置）
const extraParams = reactive({ dictType: "" })
// 数据标签回显样式
const listClassOptions = ref([
  { value: "default", label: "默认" },
  { value: "primary", label: "主要" },
  { value: "success", label: "成功" },
  { value: "info", label: "信息" },
  { value: "warning", label: "警告" },
  { value: "danger", label: "危险" }
])

// 搜索项配置
const searchColumns = [
  { label: "字典标签", prop: "dictLabel", component: "input", placeholder: "请输入字典标签", width: "200px" },
  { label: "状态", prop: "status", component: "select", dict: "sys_normal_disable", placeholder: "数据状态", width: "200px" }
]

// 表格列配置
const columns = [
  { label: "字典编码", prop: "dictCode", align: "center" },
  { label: "字典标签", prop: "dictLabel", align: "center" },
  { label: "字典键值", prop: "dictValue", align: "center" },
  { label: "字典排序", prop: "dictSort", align: "center" },
  { label: "状态", prop: "status", align: "center", dict: "sys_normal_disable" },
  { label: "备注", prop: "remark", align: "center" },
  { label: "创建时间", prop: "createTime", align: "center", width: 180, parseTime: true },
  { label: "操作", prop: "action", align: "center", width: 160, showInToolbar: false }
]

// 查询函数（BasicTable 调用，返回 { rows, total }）
function queryList(params) {
  return listData(params)
}

const data = reactive({
  form: {},
  rules: {
    dictLabel: [{ required: true, message: "数据标签不能为空", trigger: "blur" }],
    dictValue: [{ required: true, message: "数据键值不能为空", trigger: "blur" }],
    dictSort: [{ required: true, message: "数据顺序不能为空", trigger: "blur" }]
  }
})

const { form, rules } = toRefs(data)

/** 查询字典类型详细（从路由参数获取上级 dictType） */
onMounted(() => {
  const dictId = route.params && route.params.dictId
  getType(dictId).then(response => {
    extraParams.dictType = response.data.dictType
    tableRef.value.reload()
  })
})

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    dictCode: undefined,
    dictLabel: undefined,
    dictValue: undefined,
    cssClass: undefined,
    listClass: "default",
    dictSort: 0,
    status: "0",
    remark: undefined
  }
  proxy.resetForm("dataRef")
}

/** 返回按钮操作 */
function handleClose() {
  const obj = { path: "/system/dict" }
  proxy.$tab.closeOpenPage(obj)
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加字典数据"
  form.value.dictType = extraParams.dictType
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const dictCode = row.dictCode
  getData(dictCode).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改字典数据"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dataRef"].validate(valid => {
    if (valid) {
      if (form.value.dictCode != undefined) {
        updateData(form.value).then(() => {
          useDictStore().removeDict(extraParams.dictType)
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          tableRef.value.refresh()
        })
      } else {
        addData(form.value).then(() => {
          useDictStore().removeDict(extraParams.dictType)
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          tableRef.value.refresh()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(dictCodes) {
  proxy.$modal.confirm('是否确认删除字典编码为"' + dictCodes + '"的数据项？').then(function() {
    return delData(dictCodes)
  }).then(() => {
    tableRef.value.refresh()
    proxy.$modal.msgSuccess("删除成功")
    useDictStore().removeDict(extraParams.dictType)
  }).catch(() => {})
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download("system/dict/data/export", {
    ...tableRef.value.getQueryParams()
  }, `dict_data_${new Date().getTime()}.xlsx`)
}
</script>
