<template>
   <div class="app-container">
      <basic-table
         ref="tableRef"
         :columns="columns"
         :search-columns="searchColumns"
         :query="queryList"
         row-key="configId"
      >
         <template #toolbar="{ selection, ids }">
            <el-col :span="1.5">
               <el-button
                  type="primary"
                  plain
                  icon="Plus"
                  @click="handleAdd"
                  v-hasPermi="['system:config: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:config: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:config:remove']"
               >删除</el-button>
            </el-col>
            <el-col :span="1.5">
               <el-button
                  type="warning"
                  plain
                  icon="Download"
                  @click="handleExport"
                  v-hasPermi="['system:config:export']"
               >导出</el-button>
            </el-col>
            <el-col :span="1.5">
               <el-button
                  type="danger"
                  plain
                  icon="Refresh"
                  @click="handleRefreshCache"
                  v-hasPermi="['system:config:remove']"
               >刷新缓存</el-button>
            </el-col>
         </template>

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

      <!-- 添加或修改参数配置对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body>
         <el-form ref="configRef" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="参数名称" prop="configName">
               <el-input v-model="form.configName" placeholder="请输入参数名称" />
            </el-form-item>
            <el-form-item label="参数键名" prop="configKey">
               <el-input v-model="form.configKey" placeholder="请输入参数键名" />
            </el-form-item>
            <el-form-item label="参数键值" prop="configValue">
               <el-input v-model="form.configValue" type="textarea" placeholder="请输入参数键值" />
            </el-form-item>
            <el-form-item label="系统内置" prop="configType">
               <el-radio-group v-model="form.configType">
                  <el-radio
                     v-for="dict in sys_yes_no"
                     :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-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="Config">
import { listConfig, getConfig, delConfig, addConfig, updateConfig, refreshCache } from "@/api/system/config"

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

const tableRef = ref()
const open = ref(false)
const title = ref("")

// 搜索项配置
const searchColumns = [
  { label: "参数名称", prop: "configName", component: "input", placeholder: "请输入参数名称", width: "240px" },
  { label: "参数键名", prop: "configKey", component: "input", placeholder: "请输入参数键名", width: "240px" },
  { label: "系统内置", prop: "configType", component: "select", dict: "sys_yes_no", placeholder: "系统内置", width: "240px" },
  { label: "创建时间", prop: "dateRange", component: "daterange", width: "320px" }
]

// 表格列配置
const columns = [
  { label: "参数主键", prop: "configId", align: "center" },
  { label: "参数名称", prop: "configName", align: "center" },
  { label: "参数键名", prop: "configKey", align: "center" },
  { label: "参数键值", prop: "configValue", align: "center" },
  { label: "系统内置", prop: "configType", align: "center", dict: "sys_yes_no" },
  { label: "备注", prop: "remark", align: "center" },
  { label: "创建时间", prop: "createTime", align: "center", width: 180, parseTime: true },
  { label: "操作", prop: "action", align: "center", width: 150, showInToolbar: false }
]

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

const data = reactive({
  form: {},
  rules: {
    configName: [{ required: true, message: "参数名称不能为空", trigger: "blur" }],
    configKey: [{ required: true, message: "参数键名不能为空", trigger: "blur" }],
    configValue: [{ required: true, message: "参数键值不能为空", trigger: "blur" }]
  }
})

const { form, rules } = toRefs(data)

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

/** 表单重置 */
function reset() {
  form.value = {
    configId: undefined,
    configName: undefined,
    configKey: undefined,
    configValue: undefined,
    configType: "Y",
    remark: undefined
  }
  proxy.resetForm("configRef")
}

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

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const configId = row.configId
  getConfig(configId).then(response => {
    form.value = response.data
    open.value = true
    title.value = "修改参数"
  })
}

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

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

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

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