<template>
  <div style="margin-top: 16px">
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'color'">
          <Tag :color="record.color || '#000'">
            {{ record.color }}
          </Tag>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                auth: ['sys:dictItem:edit'],
                icon: 'icon-edit|iconfont',
                tooltip: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                auth: ['sys:dictItem:remove'],
                icon: 'icon-delete|iconfont',
                tooltip: '删除',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
      <template #toolbar>
        <a-button
          v-auth="['sys:dictItem:add']"
          v-show="!!dictId"
          type="primary"
          @click="handleCreate"
          preIcon="icon-plus|iconfont"
          >新增</a-button
        >
      </template>
    </BasicTable>
    <FormModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { Tag } from 'ant-design-vue';
  import { nextTick, onBeforeMount, ref, watch } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import FormModal from './FormModal.vue';
  import { columns, searchFormSchema } from './data';
  import { useMessage } from '/@/hooks/web/useMessage';

  import { sysDictItemQueryList, sysDictItemRemove } from '/@/api/sys/sysDictItemApi';
  import { listDictModel } from '/@/api/common';

  const props = defineProps({
    dictId: { type: String },
  });

  const sysStatusOptions = ref([]);
  onBeforeMount(async () => {
    sysStatusOptions.value = await listDictModel({ dictCode: 'sys_status' });
  });

  // const { createMessage, createConfirm } = useMessage();
  const { createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload }] = useTable({
    title: '字典项列表',
    titleHelpMessage: '请先选中字典，再操作字典项',
    api: sysDictItemQueryList,
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      resetButtonOptions: {
        preIcon: 'ant-design:delete-outlined',
      },
      submitButtonOptions: {
        preIcon: 'ant-design:search-outlined',
      },
    },
    immediate: false,
    showIndexColumn: false,
    useSearchForm: false,
    showTableSetting: true,
    bordered: true,
    actionColumn: {
      auth: ['sys:dictItem:edit', 'sys:dictItem:remove'],
      width: 80,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: handleBeforeFetch,
  });

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

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

  // 删除按钮事件
  async function handleDelete(record: Recordable) {
    console.log('🚀 ~ file: index.vue:141 ~ handleDelete ~ record', record);
    await sysDictItemRemove([record.id]);
    createMessage.success('删除成功！');
    await reload();
  }

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

  // 弹窗回调事件
  function handleSuccess({ isUpdate, values }) {
    console.log(isUpdate);
    console.log(values);
    reload();
  }

  // 表格请求之前，对参数进行处理
  function handleBeforeFetch(params) {
    return { ...params, dictId: props.dictId, orders: [{ field: 'sort', direction: 'ASC' }] };
  }

  watch(
    () => props.dictId,
    () => {
      nextTick(() => {
        reload();
      });
    },
  );
</script>
