<template>
  <div class="page">
    <el-card shadow="never">
      <el-form :model="tableData.param" ref="queryRef" inline label-width="68px">
        <el-form-item label="参数名称" prop="configName">
          <el-input v-model="tableData.param.configName" placeholder="请输入参数名称" clearable @keyup.enter.native="dataList" />
        </el-form-item>
        <el-form-item label="系统内置" prop="configType">
          <el-select v-model="tableData.param.configType" placeholder="系统内置" clearable style="width: 100px">
            <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" class="ml10" @click="dataList">
            <el-icon>
              <ele-Search />
            </el-icon>
            查询
          </el-button>
          <el-button @click="resetQuery(queryRef)">
            <el-icon>
              <ele-Refresh />
            </el-icon>
            重置
          </el-button>
          <el-button type="primary" class="ml10" @click="onOpenAddDic" v-auth="'add'">
            <el-icon>
              <ele-FolderAdd />
            </el-icon>
            新增参数
          </el-button>
          <el-button type="info" class="ml10" @click="onRowDel()" v-auth="'del'">
            <el-icon>
              <ele-Delete />
            </el-icon>
            删除参数
          </el-button>
        </el-form-item>
      </el-form>
      <!-- 字典切换 -->
      <el-tabs v-model="tableData.param.moduleClassify" @tab-change="dataList">
        <el-tab-pane v-for="dict in tabDataList" :label="dict.dictLabel" :name="dict.dictValue"></el-tab-pane>
      </el-tabs>
      <el-table :data="tableData.data" style="width: 100%" @selection-change="handleSelectionChange" v-loading="tableData.loading">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" v-col="'configId'" align="center" prop="configId" width="100" />
        <el-table-column label="参数名称" v-col="'configName'" prop="configName" show-overflow-tooltip />
        <el-table-column label="参数键名" v-col="'configKey'" prop="configKey" show-overflow-tooltip />
        <el-table-column label="参数键值" v-col="'configValue'" prop="configValue" />
        <el-table-column label="备注" prop="remark" v-col="'remark'" show-overflow-tooltip />
        <!-- <el-table-column label="创建时间" prop="createdAt" width="180" align="center" /> -->
        <el-table-column label="系统内置" v-col="'configType'" align="center" prop="configType" width="100">
          <template #default="{ row }">
            {{ row.configType ? '是' : '否' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" v-col="'handle'" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" text type="warning" @click="onOpenEditDic(scope.row)" v-auth="'edit'">修改</el-button>
            <el-button size="small" text type="info" @click="onRowDel(scope.row)" v-auth="'del'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="tableData.total > 0" :total="tableData.total" v-model:page="tableData.param.pageNum" v-model:limit="tableData.param.pageSize" @pagination="dataList" />
    </el-card>
    <EditConfig ref="editDicRef" @dataList="dataList" :sysYesNoOptions="sys_yes_no" />
  </div>
</template>

<script lang="ts">
import { toRefs, reactive, onMounted, ref, defineComponent, unref, getCurrentInstance } from 'vue';
import { ElMessageBox, ElMessage, FormInstance } from 'element-plus';
import EditConfig from '/@/views/system/config/component/editConfig.vue';
import api from '/@/api/system';

// 定义接口来定义对象的类型
interface TableDataRow {
  configId: number;
  configName: string;
  configKey: string;
  configValue: string;
  configType: number;
  remark: string;
  createdAt: string;
  moduleClassify: string;
}
interface TableDataState {
  ids: number[];
  tableData: {
    data: Array<TableDataRow>;
    total: number;
    loading: boolean;
    param: {
      pageNum: number;
      pageSize: number;
      configName: string;
      configKey: string;
      configType: string;
      dateRange: string[];
      moduleClassify: string;
    };
  };
}

export default defineComponent({
  name: 'apiV1SystemDictDataList',
  components: { EditConfig },
  setup() {
    const { proxy } = getCurrentInstance() as any;
    const addDicRef = ref();
    const editDicRef = ref();
    const queryRef = ref();
    const { sys_yes_no } = proxy.useDict('sys_yes_no');
    const tabDataList = ref([{ dictLabel: '全部', dictValue: '' }]);
    const state = reactive<TableDataState>({
      ids: [],
      tableData: {
        data: [],
        total: 0,
        loading: false,
        param: {
          dateRange: [],
          pageNum: 1,
          pageSize: 20,
          configName: '',
          configKey: '',
          configType: '',
          moduleClassify: '',// 字典分类
        },
      },
    });
    // 页面加载时
    onMounted(() => {
      initTableData();
    });
    // 初始化表格数据
    const initTableData = () => {
      dictList();
    };
    const dataList = () => {
      state.tableData.loading = true;
      api.config
        .getList(state.tableData.param)
        .then((res: any) => {
          state.tableData.data = res.list;
          state.tableData.total = res.total;
        })
        .finally(() => (state.tableData.loading = false));
    };
    // 打开新增字典弹窗
    const onOpenAddDic = () => {
      editDicRef.value.openDialog();
    };
    // 打开修改字典弹窗
    const onOpenEditDic = (row: TableDataRow) => {
      editDicRef.value.openDialog(row);
    };
    // 删除字典
    const onRowDel = (row?: TableDataRow) => {
      let msg = '你确定要删除所选数据？';
      let ids: number[] = [];
      if (row) {
        msg = `此操作将永久删除用户：“${row.configName}”，是否继续?`;
        ids = [row.configId];
      } else {
        ids = state.ids;
      }
      if (ids.length === 0) {
        ElMessage.error('请选择要删除的数据。');
        return;
      }
      ElMessageBox.confirm(msg, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          api.config.del(ids).then(() => {
            ElMessage.success('删除成功');
            dataList();
          });
        })
        .catch(() => { });
    };
    /** 重置按钮操作 */
    const resetQuery = (formEl: FormInstance | undefined) => {
      if (!formEl) return;
      formEl.resetFields();
      dataList();
    };
    // 多选框选中数据
    const handleSelectionChange = (selection: TableDataRow[]) => {
      state.ids = selection.map((item) => item.configId);
    };
    // 参数系统内置字典翻译
    const typeFormat = (row: TableDataRow) => {
      return proxy.selectDictLabel(unref(sys_yes_no), row.configType);
    };
    // 获取字典列表
    const dictList = () => {
      state.tableData.loading = true;
      api.dict.getDataList({ dictType: 'param_class_type', status: 1, pageNum: 1, pageSize: 50, defaultValue: '' })
        .then((res: any) => {
          tabDataList.value = tabDataList.value.concat(res.list);
          dataList();
        }).finally(() => (state.tableData.loading = false));
    };
    return {
      addDicRef,
      editDicRef,
      queryRef,
      sys_yes_no,
      tabDataList,
      onOpenAddDic,
      onOpenEditDic,
      onRowDel,
      dataList,
      resetQuery,
      handleSelectionChange,
      ...toRefs(state),
    };
  },
});
</script>
