<template>
  <div>
    <BasicTable @register="registerTable">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'disable'">
          <Tag :color="formatDictColor(disableOptions, record.disable)">
            {{ formatDictValue(disableOptions, record.disable) }}
          </Tag>
        </template>
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                auth: ['sys:org:edit'],
                icon: 'icon-edit|iconfont',
                tooltip: '编辑',
                onClick: handleEdit.bind(null, record),
              },
              {
                auth: ['sys:org:remove'],
                icon: 'icon-delete|iconfont',
                tooltip: '删除',
                color: 'error',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: handleDelete.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
      <template #toolbar>
        <a-button
          type="primary"
          @click="handleCreate"
          v-auth="['sys:org:add']"
          preIcon="icon-plus|iconfont"
          >新增</a-button
        >
      </template>
    </BasicTable>
    <FormModal @register="registerModal" @success="handleSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { nextTick, onBeforeMount, ref, watch } 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 { sysOrgQueryPage, sysOrgRemove } from '/@/api/sys/sysOrgApi';
  import { listDictModel } from '/@/api/common';
  import { formatDictColor, formatDictValue } from '/@/utils';

  const emit = defineEmits(['refresh-tree']);

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

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

  const { createMessage } = useMessage();
  const [registerModal, { openModal }] = useModal();
  const [registerTable, { reload }] = useTable({
    title: '部门列表',
    api: sysOrgQueryPage,
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      autoSubmitOnEnter: true,
      baseColProps: { xs: 24, sm: 12, md: 12, lg: 12, xl: 8 },
      resetButtonOptions: {
        preIcon: 'icon-delete|iconfont',
      },
      submitButtonOptions: {
        preIcon: 'icon-search|iconfont',
      },
    },
    showIndexColumn: false,
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    actionColumn: {
      auth: ['sys:org:edit', 'sys:org:remove'],
      width: 80,
      title: '操作',
      dataIndex: 'action',
    },
    beforeFetch: handleBeforeFetch,
    afterFetch: handleAfterFetch,
  });

  // 新增按钮事件
  function handleCreate() {
    const record = {
      parentId: props.nodeId,
    };
    openModal(true, {
      record,
      isUpdate: false,
    });
  }

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

  // 删除按钮事件
  async function handleDelete(record: Recordable) {
    console.log(record);
    await sysOrgRemove([record.id]);
    createMessage.success('删除成功！');
    emit('refresh-tree', record.parentId === '0' ? undefined : record.parentId);
    // 表格刷新，在refresh-tree事件之后，执行
    // await reload();
  }

  // 弹窗回调事件
  function handleSuccess({ isUpdate, values }) {
    console.log(isUpdate);
    console.log(values);
    emit('refresh-tree', values.parentId);
    // 表格刷新，在refresh-tree事件之后，执行
    // reload();
  }

  // 表格请求之前，对参数进行处理
  function handleBeforeFetch(params) {
    return { ...params, parentId: !props.nodeId ? '0' : props.nodeId };
  }

  function handleAfterFetch(data) {
    const res = data.map(ele => {
      ele.children = null;
      return ele;
    });
    return res;
  }

  // 刷新表格
  function refresh() {
    reload();
  }

  watch(
    () => props.nodeId,
    () => {
      nextTick(() => {
        reload();
      });
    },
  );

  // 暴露内部方法
  defineExpose({ refresh });
</script>
