<template>
  <ele-page>
    <!-- 搜索表单 -->
    <config-search @search="reload" />

    <ele-tabs
      type="tag"
      v-model="configGroup"
      :items="groupItems"
      @tabChange="reload()"
    />

    <ele-card :body-style="{ paddingTop: '8px' }">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        :show-overflow-tooltip="true"
        v-model:selections="selections"
        :highlight-current-row="true"
        :pagination="false"
        cache-key="systemRoleTable"
        :load-on-created="false"
        height="66vh"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <template #toolbar>
          <el-button
            type="primary"
            class="ele-btn-icon"
            :icon="PlusOutlined"
            @click="openEdit()"
          >
            添加
          </el-button>
        </template>
        <template #action="{ row }">
          <template v-if="['tabs', 'tabs_item', 'collapse', 'card'].indexOf(row.type) != -1">
            <el-link
              type="primary"
              underline="never"
              @click="openEdit(null, row)"
              >添加子项</el-link
            >
            <el-divider direction="vertical" />
          </template>
          <el-link type="primary" underline="never" @click="openEdit(row)">
            修改
          </el-link>
          <template v-if="row.group != 'system'">
            <el-divider direction="vertical" />
            <el-link type="danger" underline="never" @click="remove(row)">
              删除
            </el-link>
          </template>
          <el-divider direction="vertical" />
          <el-link type="primary" underline="never" @click="openLog(row)" title="查看配置变更日志记录">
            日志
          </el-link>
        </template>
        <template #status="{ row }">
          <el-switch
            size="small"
            :model-value="row.status === 1"
            @change="(checked: boolean) => editStatus(checked, row)"
          />
        </template>
        <template #type="{ row }">
          <span :title="row.type">{{ getItemLabel(row.type) }}</span>
        </template>
        <template #sort="{ row }">
         <el-input-number :controls="false" v-model="row.sort" @update:modelValue="(sort)=>updateSort(row.id, row.sort)" :min="1" :max="9999" style="width: 100%;"></el-input-number>
        </template>
      </ele-pro-table>
    </ele-card>
    <!-- 编辑弹窗 -->
    <config-edit
      v-model="showEdit"
      :data="current"
      :parent="parent"
      @done="reload"
      :group="configGroup"
    />
  </ele-page>
</template>

<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { ElMessageBox } from 'element-plus';
  import {EleMessage, toTree} from 'ele-admin-plus';
  import type { EleProTable } from 'ele-admin-plus';
  import type {
    DatasourceFunction,
    Columns
  } from 'ele-admin-plus/es/ele-pro-table/types';
  import { PlusOutlined } from '@/components/icons';
  import ConfigSearch from './components/config-search.vue';
  import ConfigEdit from './components/config-edit.vue';
  import type { Config, ConfigParam } from '@/api/system/config/model';
  import {
    listConfigs,
    updateConfigStatus,
    removeConfigs,
    updateConfigSort
  } from '@/api/system/config';
  import { getSysConfig } from '@/utils/sys-config';
  import { ItemType, getItemLabel } from '@/enum/config-item-type.ts';

  defineOptions({ name: 'SystemConfig' });

  /** 表格实例 */
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);

  /** 表格列配置 */
  const columns = ref<Columns>([
    {
      type: 'index',
      columnKey: 'index',
      width: 50,
      align: 'center'
    },
    {
      prop: 'title',
      label: '标题',
      minWidth: 120
    },
    {
      prop: 'name',
      label: '名称',
      minWidth: 120
    },
    {
      prop: 'type',
      slot: 'type',
      label: '类型',
      width: 120
    },
    {
      prop: 'status',
      label: '状态',
      width: 90,
      align: 'center',
      slot: 'status',
      formatter: (row) => (row.status == 0 ? '正常' : '冻结')
    },
    {
      prop: 'sort',
      slot: 'sort',
      label: '排序',
      align: 'center',
      width: 140
    },
    {
      prop: 'comments',
      label: '备注',
      minWidth: 140
    },
    {
      columnKey: 'action',
      label: '操作',
      width: 280,
      align: 'right' /* ,
      fixed: 'right' */,
      slot: 'action',
      hideInPrint: true,
      hideInExport: true
    }
  ]);

  /** 表格选中数据 */
  const selections = ref<Config[]>([]);

  /** 当前编辑数据 */
  const current = ref<Config | null>(null);

  const parent = ref<Config | null>(null);

  /** 是否显示编辑弹窗 */
  const showEdit = ref(false);

  /** 表格数据源 */
  const datasource: DatasourceFunction = async ({ pages, where, orders }) => {
    const data = await listConfigs({
      ...where,
      ...orders,
      ...pages,
      group: configGroup.value,
      limit: 999
    });
    return toTree({
      data,
      idField: 'id',
      parentIdField: 'pid'
    });
  };

  /** 搜索 */
  const reload = (where?: ConfigParam) => {
    selections.value = [];
    tableRef.value?.reload?.({ page: 1, where });
  };

  /** 打开编辑弹窗 */
  const openEdit = (row?: Config, parentRow?: Config) => {
    current.value = row ?? null;
    showEdit.value = true;
    parent.value = parentRow;
  };
  const showLog = ref(false);
  const openLog = (row?:Config)=>{
    current.value = row ?? null;
    showLog.value = true;
  }
  /** 删除单个 */
  const remove = (row?: Config) => {
    const rows = row == null ? selections.value : [row];
    if (!rows.length) {
      EleMessage.error({ message: '请至少选择一条数据', plain: true });
      return;
    }
    ElMessageBox.confirm(
      '确定要删除“' + rows.map((d) => d.roleName).join(', ') + '”吗?',
      '系统提示',
      { type: 'warning', draggable: true }
    )
      .then(() => {
        const loading = EleMessage.loading({
          message: '请求中..',
          plain: true
        });
        removeConfigs(rows.map((d) => d.id))
          .then((msg) => {
            loading.close();
            EleMessage.success({ message: msg, plain: true });
            reload();
          })
          .catch((e) => {
            loading.close();
            EleMessage.error({ message: e.message, plain: true });
          });
      })
      .catch(() => {});
  };

  const updateSort = (id, sort) => {
    updateConfigSort(id, sort).then(()=>{
      EleMessage.success("更新成功");
    });
  }
  /** 修改配置状态 */
  const editStatus = (checked: boolean, row: Config) => {
    const status = checked ? 1 : 0;
    updateConfigStatus(row.id, status)
      .then((msg) => {
        row.status = status;
        EleMessage.success({ message: msg, plain: true });
      })
      .catch((e) => {
        EleMessage.error({ message: e.message, plain: true });
      });
  };

  const groupItems = ref([]);
  const configGroup = ref('');
  onMounted(async () => {
    // 配置分组
    const group = [];
    const { valueData } = await getSysConfig('config_group');
    for (const name in valueData) {
      group.push({ name: name, label: valueData[name] });
    }
    groupItems.value = group;
    if (group.length > 0) {
      configGroup.value = group[0].name;
    }
    reload();
  });
</script>
