<template>
  <j-modal
    :title="title"
    :width="1400"
    :visible="visible"
    :footer="null"
    @cancel="handleCancel"
    cancelText="关闭"
  >
    <div class="business-process-list-modal">
      <BasicTable @register="registerTable">
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" />
        </template>
      </BasicTable>
    </div>
    <BpmPictureModal @register="registerBpmModal" />
  </j-modal>
</template>

<script lang="ts" setup>
  import { nextTick, ref } from 'vue';
  import { BasicColumn, BasicTable, TableAction, useTable } from '/@/components/Table';
  import JModal from '/@/components/Modal/src/JModal/JModal.vue';
  import { useModal } from '/@/components/Modal';
  import { columns } from './QueryProcessList.data';
  import { queryByBusinessId } from '/@/api/common/api';
  import { useMessage } from '/@/hooks/web/useMessage';

  interface OpenParams {
    businessId?: string;
    title?: string;
    columns?: BasicColumn[];
    onDeleteProcess?: (record: Recordable, reload: () => Promise<void>) => Promise<void>;
  }

  const title = ref('流程列表');
  const visible = ref(false);
  const currentBusinessId = ref('');
  const defaultColumns = columns;
  const { createMessage } = useMessage();
  const onDeleteProcessRef = ref<OpenParams['onDeleteProcess']>();
  const [registerBpmModal, { openModal: bpmPicModal }] = useModal();

  const [registerTable, { setColumns, setTableData, setLoading, clearSelectedRowKeys }] = useTable({
    rowKey: 'id',
    columns: columns,
    useSearchForm: false,
    canResize: false,
    pagination: false,
    showIndexColumn: true,
    bordered: true,
    actionColumn: {
      title: '操作',
      dataIndex: 'action',
      width: 180,
      fixed: 'right',
      slots: { customRender: 'action' },
    },
    scroll: {
      x: 3600,
    },
  });

  async function loadData() {
    if (!currentBusinessId.value) {
      setTableData([]);
      return;
    }

    setLoading(true);
    try {
      const res = await queryByBusinessId({ businessId: currentBusinessId.value });
      const list = Array.isArray(res?.result) ? res.result : [];
      setTableData(list);
      if (!list.length) {
        createMessage.warning(res?.message || '未查询到流程数据');
      }
    } catch (error) {
      setTableData([]);
    } finally {
      setLoading(false);
      clearSelectedRowKeys();
    }
  }

  async function open(params: OpenParams = {}) {
    currentBusinessId.value = params.businessId || '';
    title.value = params.title || '流程列表';
    onDeleteProcessRef.value = params.onDeleteProcess;
    visible.value = true;
    await nextTick();
    setColumns(params.columns?.length ? params.columns : defaultColumns);
    await loadData();
  }

  function handleCancel() {
    visible.value = false;
    currentBusinessId.value = '';
    onDeleteProcessRef.value = undefined;
    setColumns(defaultColumns);
    setTableData([]);
    clearSelectedRowKeys();
  }

  function handlePreviewPic(record) {
    bpmPicModal(true, {
      flowCode: record.flowCode,
      dataId: record.id,
    });
  }

  async function handleDeleteProcess(record) {
    if (typeof onDeleteProcessRef.value === 'function') {
      await onDeleteProcessRef.value(record, loadData);
    } else {
      createMessage.warning('未配置删除流程回调');
    }
  }

  function getTableAction(record) {
    const actions: any[] = [
      {
        label: '审批历史',
        onClick: handlePreviewPic.bind(null, record),
      },
    ];

    if (typeof onDeleteProcessRef.value === 'function') {
      actions.push({
        label: '删除流程',
        popConfirm: {
          title: '确定删除该流程吗？',
          confirm: handleDeleteProcess.bind(null, record),
          placement: 'topLeft',
        },
      });
    }

    return actions;
  }

  defineExpose({
    open,
  });
</script>

<style lang="less" scoped>
  .business-process-list-modal {
    :deep(.vben-basic-table) {
      padding: 0;
    }
  }
</style>
