<template>
  <div>
    <BasicTable
      @register="registerTable"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @row-dbClick="handleRowDbClick"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'disable'">
          <Tag :color="formatDictColor(sysDisableType, record.disable)">
            {{ formatDictValue(sysDisableType, record.disable) }}
          </Tag>
        </template>
        <template v-if="column.key === 'dictType'">
          <Tag :color="formatDictColor(sysDictTypeOptions, record.dictType)">
            {{ formatDictValue(sysDictTypeOptions, record.dictType) }}
          </Tag>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                auth: ['sys:dict:edit'],
                icon: 'icon-edit|iconfont',
                tooltip: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                auth: ['sys:dict:remove'],
                icon: 'icon-delete|iconfont',
                tooltip: '删除',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
      <template #toolbar>
        <a-button
          v-auth="['sys:dict:add']"
          type="primary"
          @click="handleCreate"
          preIcon="icon-plus|iconfont"
          >新增</a-button
        >
      </template>
    </BasicTable>
    <FormModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { onBeforeMount, ref } from 'vue';
  import { Tag } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import FormModal from './FormModal.vue';
  import { columns, searchFormSchema } from './data';
  import { sysDictQueryPage, sysDictRemove } from '/@/api/sys/sysDictApi';
  import { formatDictColor, formatDictValue } from '/@/utils';
  import { listDictModel } from '/@/api/common';

  const emit = defineEmits(['dict-change']);

  const sysDictTypeOptions = ref([]);
  const sysDisableType = ref();
  onBeforeMount(async () => {
    const dictTypeStatus = await listDictModel({ dictCode: 'sys_dict_type' });
    sysDisableType.value = await listDictModel({ dictCode: 'sys_disable_type' });
    sysDictTypeOptions.value = dictTypeStatus || [];
  });

  const { createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload, getDataSource, getSelectRowKeys, setSelectedRowKeys }] = useTable(
    {
      title: '字典列表',
      api: sysDictQueryPage,
      rowKey: 'id',
      columns,
      rowSelection: { type: 'radio' },
      clickToRowSelect: true,
      formConfig: {
        labelWidth: 120,
        schemas: searchFormSchema,
        autoSubmitOnEnter: true,
        showAdvancedButton: false,
        baseColProps: { span: 12 },
        actionColOptions: {
          span: 24,
        },
        resetButtonOptions: {
          preIcon: 'icon-delete|iconfont',
        },
        submitButtonOptions: {
          preIcon: 'icon-search|iconfont',
        },
      },
      showIndexColumn: false,
      useSearchForm: true,
      showTableSetting: true,
      bordered: true,
      actionColumn: {
        auth: ['sys:dict:edit', 'sys:dict:remove'],
        width: 80,
        title: '操作',
        dataIndex: 'action',
      },
      afterFetch: handleAfterFetch,
    },
  );

  // 新增按钮事件
  function handleCreate() {
    openModal(true, {
      isUpdate: false,
    });
  }

  // 编辑按钮事件
  function handleEdit(record: Recordable) {
    console.log(record);
    openModal(true, {
      record,
      isUpdate: true,
    });
  }

  // 删除按钮事件
  async function handleDelete(record: Recordable) {
    console.log(record);
    await sysDictRemove([record.id]);
    createMessage.success('删除成功！');
    await reload();
    // after delete, select first row
    const list = getDataSource();
    if (list.length > 0) {
      setSelectedRowKeys([list[0].id]);
    } else {
      setSelectedRowKeys([]);
    }
    console.log('handleDelete');
    emitDictChange();
  }

  // 导出按钮事件
  // async function handleExport() {
  //   createConfirm({
  //     iconType: 'warning',
  //     title: '提示',
  //     content: '确认导出？',
  //     onOk: async () => {
  //       const params = getForm().getFieldsValue();
  //       const filepath = await exportList(params);
  //       downloadFile(filepath);
  //     },
  //   });
  // }

  // 弹窗回调事件
  async function handleSuccess({ isUpdate, values }) {
    console.log(isUpdate);
    console.log(values);
    await reload();
    if (isUpdate) {
      // after update, select updated row
      setSelectedRowKeys([values.id]);
    } else {
      // after create, select first row
      const list = getDataSource();
      if (list.length > 0) {
        setSelectedRowKeys([list[0].id]);
      } else {
        setSelectedRowKeys([]);
      }
    }
    console.log('handleSuccess', isUpdate ? 'update' : 'create');
    emitDictChange();
  }

  // 表格请求之后，对返回值进行处理
  function handleAfterFetch(data) {
    // after fetch, select first row
    if (data.length > 0) {
      setSelectedRowKeys([data[0].id]);
    } else {
      setSelectedRowKeys([]);
    }
    console.log('handleAfterFetch', data);
    emitDictChange();
  }

  // 表格行点击事件
  function handleRowClick(record: Recordable) {
    console.log('handleRowClick', record);
    setSelectedRowKeys([record.id]);
    emitDictChange();
  }

  // 表格行双击事件
  function handleRowDbClick(record: Recordable) {
    console.log('handleRowDbClick', record);
    setSelectedRowKeys([record.id]);
    emitDictChange();
  }

  // 表格行选中事件
  function handleSelectionChange({ keys, rows }) {
    console.log('handleSelectionChange', keys, rows);
    emitDictChange();
  }

  // 字典变化事件
  function emitDictChange() {
    const selectedKeys = getSelectRowKeys();
    console.log(selectedKeys);
    emit('dict-change', selectedKeys.length > 0 ? selectedKeys[0] : '');
  }
</script>
