<template>
  <PageWrapper dense contentFullHeight contentClass="flex">
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleRefresh">
          <template #icon><Icon icon="ant-design:reload-outlined" /></template>
          {{ t('刷新') }}
        </a-button>

        <a-button type="primary" @click="handleAdd">
          <template #icon><Icon icon="ant-design:plus-outlined" /></template>
          {{ t('新增') }}
        </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'action'">
          <TableAction :actions="getActions(record)" />
        </template>
      </template>
    </BasicTable>

    <ProcessLayout class="wrap" v-if="visibleRef" @click.stop="">
      <template #title> {{ t('查看流程') }} </template>
      <template #close>
        <a-button type="primary" class="clean-icon" @click.stop="closeWorkflow">关闭</a-button>
      </template>
      <template #full>
        <LookTask v-if="visibleRef" :processId="processIdRef" />
      </template>
    </ProcessLayout>

    <LaunchProcess
      v-if="visibleLaunchProcessRef"
      :schemaId="schemaIdRef"
      :form-data="formDataRef"
      :form-id="formIdComputedRef"
      @close="visibleLaunchProcessRef = false"
    />

    <WorkflowApprovalProcess
      v-if="visibleApproveProcessRef"
      :taskId="taskIdRef"
      :processId="processIdRef"
      :schemaId="schemaIdRef"
      @close="visibleApproveProcessRef = false"
      :visible="visibleApproveProcessRef"
    />

    <AaaaModal @register="registerModal" @success="handleSuccess" />
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, ActionItem } from '/@/components/Table';
  import { getTable52930Page, deleteTable52930 } from '/@/api/bi/aaaa';
  import { PageWrapper } from '/@/components/Page';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useModal } from '/@/components/Modal';
  import ProcessLayout from '/@/views/workflow/task/components/flow/Layout.vue';
  import LookTask from '/@/views/workflow/task/components/flow/LookTask.vue';
  import LaunchProcess from '/@/views/workflow/task/components/LaunchProcess.vue';
  import WorkflowApprovalProcess from '/@/views/workflow/task/components/WorkflowApprovalProcess.vue';

  import AaaaModal from './components/AaaaModal.vue';

  import { searchFormSchema, columns } from './components/config';

  import Icon from '/@/components/Icon/index';
  import { useRouter } from 'vue-router';
  import { computed, ref } from 'vue';
  import { getFormExecuteWorkflow } from '/@/api/form/execute';

  const { notification } = useMessage();
  const { t } = useI18n();
  defineEmits(['register']);

  const visibleRef = ref(false);
  const processIdRef = ref(``);

  const visibleLaunchProcessRef = ref(false);
  const schemaIdRef = ref(``);
  const formDataRef = ref();

  const visibleApproveProcessRef = ref(false);
  const taskIdRef = ref(``);

  const { currentRoute } = useRouter();

  const formIdComputedRef = computed(() => currentRoute.value.meta.formId as string);

  const [registerModal, { openModal }] = useModal();

  const [registerTable, { reload }] = useTable({
    title: t('Aaaa列表'),
    api: getTable52930Page,
    rowKey: 'id',
    columns,
    formConfig: {
      labelWidth: 120,
      schemas: searchFormSchema,
      fieldMapToTime: [],
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选机构id
      return { ...params, FormId: formIdComputedRef.value, PK: 'id' };
    },
    useSearchForm: true,
    showTableSetting: true,
    bordered: true,
    actionColumn: {
      width: 210,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  function handleAdd() {
    openModal(true, {
      isUpdate: false,
    });
  }

  function handleEdit(record: Recordable) {
    openModal(true, {
      id: record.id,
      isUpdate: true,
    });
  }

  function handleViewWorkflow(record: Recordable) {
    if (record.workflowData) {
      visibleRef.value = true;
      processIdRef.value = record.workflowData.processId;
    }
  }

  async function handleLaunchProcess(record: Recordable) {
    if (record.workflowData) {
      // console.log(currentRoute.value, 'currentRoute.value');
      const result = await getFormExecuteWorkflow({
        formId: formIdComputedRef.value,
        id: record['id'],
      });

      visibleLaunchProcessRef.value = true;
      schemaIdRef.value = record.workflowData.schemaId;
      formDataRef.value = result;
    }
  }

  function handleApproveProcess(record: Recordable) {
    visibleApproveProcessRef.value = true;
    schemaIdRef.value = record.workflowData.schemaId;
    processIdRef.value = record.workflowData.processId;
    taskIdRef.value = record.workflowData.taskIds[0];
  }

  function getActions(record: Recordable): ActionItem[] {
    const actionsList: ActionItem[] = [
      {
        icon: 'ant-design:eye-outlined',
        label: t('查看'),
        onClick: handleView.bind(null, record),
      },
    ];
    //如果有工作流数据 默认需要在前面插入工作流相关按钮
    if (record.workflowData) {
      if (!record.workflowData.status) {
        actionsList.unshift({
          icon: 'ant-design:caret-right-outlined',
          label: t('发起流程'),
          onClick: handleLaunchProcess.bind(null, record),
        });

        actionsList.push({
          icon: 'ant-design:delete-outlined',
          label: t('删除'),
          popConfirm: {
            title: t('是否确认删除'),
            confirm: handleDelete.bind(null, record),
          },
        });
        actionsList.push({
          icon: 'ant-design:edit-outlined',
          label: t('编辑'),
          onClick: handleEdit.bind(null, record),
        });
      } else {
        //如果是本人需要审批的数据 就会有taskIds  所以需要修改绑定事件
        const act: ActionItem = {
          icon: 'ant-design:branches-outlined',
        };

        if (record.workflowData.taskIds) {
          act.label = t('查看流程(待审批)');
          act.onClick = handleApproveProcess.bind(null, record);
        } else {
          act.label =
            t('查看流程') +
            (record.workflowData.status === 'ACTIVE' ? t('(审批中)') : t('(已完成)'));
          act.onClick = handleViewWorkflow.bind(null, record);
        }
        actionsList.unshift(act);
      }
    }

    return actionsList;
  }
  function closeWorkflow() {
    visibleRef.value = false;
  }

  function handleDelete(record: Recordable) {
    deleteTable52930([record.id]).then((_) => {
      reload();
      notification.success({
        message: t('提示'),
        description: t('删除成功！'),
      }); //提示消息
    });
  }

  function handleRefresh() {
    reload();
  }

  function handleView() {}
  function handleSuccess() {
    reload();
  }
</script>
