<template>
   <div class="app-container">
      <basic-table
         ref="tableRef"
         :columns="columns"
         :search-columns="searchColumns"
         :query="queryList"
         row-key="dictId"
      >
         <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="danger"
                  plain
                  icon="Refresh"
                  @click="handleRefreshCache"
                  v-hasPermi="['system:dict:remove']"
               >刷新缓存</el-button>
            </el-col>
         </template>

         <template #col-dictType="{ row }">
            <a class="link-type" style="cursor:pointer" @click="handleViewData(row)">{{ row.dictType }}</a>
         </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="Operation" @click="handleDataList(row)" v-hasPermi="['system:dict:edit']">列表</el-button>
            <el-button link type="primary" icon="Delete" @click="handleDelete(row.dictId)" 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="dictRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="字典名称" prop="dictName">
               <el-input v-model="form.dictName" placeholder="请输入字典名称" />
            </el-form-item>
            <el-form-item prop="dictType">
               <el-input v-model="form.dictType" placeholder="请输入字典类型" />
               <template #label>
                 <span>
                   <el-tooltip content='数据存储中的Key值，如：sys_user_sex' placement="top">
                     <el-icon><question-filled /></el-icon>
                   </el-tooltip>
                   字典类型
                 </span>
               </template>
            </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>

      <dict-data-drawer v-model:visible="drawerVisible" :row="drawerRow" />
   </div>
</template>

<script setup name="Dict">
import DictDataDrawer from './detail'
import useDictStore from '@/store/modules/dict'
import { listType, getType, delType, addType, updateType, refreshCache } from "@/api/system/dict/type"

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

const tableRef = ref()
const open = ref(false)
const title = ref("")
const drawerVisible = ref(false)
const drawerRow = ref({})

// 搜索项配置
const searchColumns = [
  { label: "字典名称", prop: "dictName", component: "input", placeholder: "请输入字典名称", width: "240px" },
  { label: "字典类型", prop: "dictType", component: "input", placeholder: "请输入字典类型", width: "240px" },
  { label: "状态", prop: "status", component: "select", dict: "sys_normal_disable", placeholder: "字典状态", width: "240px" },
  { label: "创建时间", prop: "dateRange", component: "daterange", width: "320px" }
]

// 表格列配置
const columns = [
  { label: "字典编号", prop: "dictId", align: "center" },
  { label: "字典名称", prop: "dictName", align: "center" },
  { label: "字典类型", prop: "dictType", 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: 280, showInToolbar: false }
]

// 查询函数（BasicTable 调用，返回 { rows, total }）
function queryList(params) {
  const p = proxy.addDateRange({ ...params }, params.dateRange)
  delete p.dateRange
  return listType(p)
}

const data = reactive({
  form: {},
  rules: {
    dictName: [{ required: true, message: "字典名称不能为空", trigger: "blur" }],
    dictType: [{ required: true, message: "字典类型不能为空", trigger: "blur" }]
  }
})

const { form, rules } = toRefs(data)

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

/** 表单重置 */
function reset() {
  form.value = {
    dictId: undefined,
    dictName: undefined,
    dictType: undefined,
    status: "0",
    remark: undefined
  }
  proxy.resetForm("dictRef")
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "添加字典类型"
}

/** 字典数据抽屉 */
function handleViewData(row) {
  drawerRow.value = row
  drawerVisible.value = true
}

/** 字典数据列表页面 */
function handleDataList(row) {
  proxy.$tab.openPage("字典数据", '/system/dict-data/index/' + row.dictId)
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const dictId = row.dictId
  getType(dictId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改字典类型"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dictRef"].validate(valid => {
    if (valid) {
      if (form.value.dictId != undefined) {
        updateType(form.value).then(() => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          tableRef.value.refresh()
        })
      } else {
        addType(form.value).then(() => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          tableRef.value.refresh()
        })
      }
    }
  })
}

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

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

/** 刷新缓存按钮操作 */
function handleRefreshCache() {
  refreshCache().then(() => {
    proxy.$modal.msgSuccess("刷新成功")
    useDictStore().cleanDict()
  })
}
</script>
