<template>
  <div class="main-box">
    <div class="table-box">
      <ProTable
        ref="proTable"
        :columns="columns"
        :request-api="getTableList"
        :init-param="initParam"
        :search-col="{ xs: 1, sm: 1, md: 2, lg: 3, xl: 3 }"
      >
        <!-- 表格 header 按钮 -->
        <template #tableHeader>
          <el-button v-auth="['system:dict:add']" type="primary" :icon="CirclePlus" @click="openDialog()">新增</el-button>
          <el-button v-auth="['system:dict:refresh']" type="danger" plain icon="Refresh" @click="refreshCache">
            刷新缓存
          </el-button>
        </template>
        <!-- 字典类型 -->
        <template #dictType="scope">
          <router-link :to="`/system/dictData/${scope.row.dictId}?dictType=${scope.row.dictType}`">
            {{ scope.row.dictType }}
          </router-link>
        </template>
        <!-- 表格操作 -->
        <template #operation="scope">
          <template v-if="!scope.row.admin">
            <el-button v-auth="['system:dict:edit']" type="primary" link :icon="EditPen" @click="openDialog(scope.row)">
              编辑
            </el-button>
            <el-button v-auth="['system:dict:remove']" type="primary" link :icon="Delete" @click="deleteAccount(scope.row)">
              删除
            </el-button>
          </template>
        </template>
      </ProTable>
      <DictDialog ref="dialogRef" />
    </div>
  </div>
</template>
<script setup lang="ts" name="dictManage">
import { ref, reactive, getCurrentInstance, onActivated } from "vue";
import { onBeforeRouteLeave } from "vue-router";
import { ElMessage } from "element-plus";
import { Dict } from "@/api/interface";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import DictDialog from "./components/DictDialog.vue";
import { getDictOptions } from "@/api/modules/common";
import { getDictList, deleteDict, refreshDict } from "@/api/modules/system/dict";
import { CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({});

// 表格配置项
const columns = reactive<ColumnProps<Dict.ResDictList>[]>([
  { prop: "dictId", label: "字典编号", width: 100 },
  { prop: "dictName", label: "字典名称", search: { el: "input" } },
  { prop: "dictType", label: "字典类型", search: { el: "input" } },
  {
    prop: "status",
    label: "状态",
    enum: () => getDictOptions("sys_normal_disable"),
    search: { el: "select" },
    fieldNames: { label: "dictLabel", value: "dictValue" }
  },
  { prop: "remark", label: "备注" },

  { prop: "createTime", label: "创建时间", search: { el: "date-range-picker", custom: true } },
  { prop: "operation", label: "操作", width: 330, fixed: "right" }
]);

const proxy = getCurrentInstance()?.proxy;
const keepAlive = useKeepAliveStore();
// const { returnValue } = useType();

onBeforeRouteLeave(to => {
  // 只有二级页面，才缓存
  if (to.name === "dictData") {
    keepAlive.addKeepAliveName(proxy?.$options.name as string);
  } else {
    keepAlive.removeKeepAliveName(proxy?.$options.name as string);
  }
});

onActivated(() => {
  proTable.value?.getTableList();
});
// 分页列表获取数据
const getTableList = (params: Dict.ReqDictParams) => {
  if (params.createTime) {
    const [beginTime, endTime] = params.createTime;
    params.params = {
      beginTime,
      endTime
    };
    delete params.createTime;
  }
  return getDictList(params);
};

// 删除
const deleteAccount = async (params: Dict.ResDictList) => {
  await useHandleData(deleteDict, [params.dictId], `删除字典【${params.dictName}】`);
  proTable.value?.getTableList();
};

// 刷新缓存
const refreshCache = async () => {
  await refreshDict();
  ElMessage.success("刷新成功");
};

// 打开 drawer(新增、查看、编辑)
const dialogRef = ref<InstanceType<typeof DictDialog> | null>(null);
const openDialog = (row?: Dict.ResDictList) => {
  dialogRef.value?.open(row).then(proTable.value?.getTableList);
};
</script>
