<template>
  <ResizePageWrapper>
    <template #resizeLeft>
      <BasicTree
        :title="t('流程监控状态')"
        :clickRowToExpand="true"
        :treeData="treeData"
        :fieldNames="{ key: 'id', title: 'name' }"
        @select="handleSelect"
        :selectedKeys="selectedKeys"
      />
    </template>

    <template #resizeRight>
      <BasicTable @register="registerTable">
        <template #status="{ record }">
          <Tag color="warning" v-if="record.status == ProcessMonitorStatus.SUSPENDED">{{
            t('挂起')
          }}</Tag>
          <Tag color="processing" v-if="record.status == ProcessMonitorStatus.ACTIVE">{{
            t('活动中')
          }}</Tag>
          <Tag color="success" v-if="record.status == ProcessMonitorStatus.COMPLETED">{{
            t('完成')
          }}</Tag>
          <Tag color="error" v-if="record.status == ProcessMonitorStatus.INTERNALLY_TERMINATED">{{
            t('内部终止')
          }}</Tag>
        </template>
        <template #currentProgress="{ record }">
          <a-progress
            v-if="record.currentProgress"
            :percent="record.currentProgress"
            size="small"
          />
        </template>
        <template #action="{ record }">
          <TableAction
            :actions="[
              {
                auth: 'monitor:view',
                label: '查看',
                onClick: handleView.bind(null, record),
              },
              {
                auth: 'monitor:appointedAuditor',
                label: '指派审核人',
                onClick: approveUser.bind(null, record),
                ifShow: data.type === 0,
              },
              {
                auth: 'monitor:pending',
                label: record.status === ProcessMonitorStatus.SUSPENDED ? '恢复' : '挂起',
                onClick: setSuspended.bind(null, record),
                ifShow: data.type === 0,
              },
              {
                auth: 'monitor:termination',
                label: '终止',
                onClick: terminateProcess.bind(null, record),
                ifShow: data.type === 0,
              },
              {
                auth: 'monitor:change',
                label: '变更',
                onClick: changeNode.bind(null, record),
                ifShow: data.type === 0,
              },
              {
                label: '删除',
                auth: 'monitor:delete',
                color: 'error',
                popConfirm: {
                  title: t('是否确认删除'),
                  confirm: deleteFlow.bind(null, record),
                },
                ifShow: data.type === 0,
              },
            ]"
          />
        </template>
      </BasicTable>
    </template>
    <!-- 指派审核人 -->
    <ApproveProcessMonitorUser
      v-if="data.approvedUserVisible"
      :taskId="taskIdProcess"
      :schemaId="schemaIdProcess"
      :title="approvedUserTitle"
      @close="
        () => {
          data.approvedUserVisible = false;
          reload();
        }
      "
    />
    <MonitorChange
      :processId="processIdProcess"
      :taskId="taskIdProcess"
      v-if="data.changeNodeVisible"
      @close="nodeModalClose"
      @success="nodeModalSuccess"
    />
    <LookProcess
      v-if="visibleLookProcess"
      :visible="visibleLookProcess"
      :taskId="taskIdProcess"
      :processId="processIdProcess"
      @close="visibleLookProcess = false"
    />
  </ResizePageWrapper>
</template>

<script lang="ts" setup>
  import { createVNode, reactive, ref, computed } from 'vue';
  import { BasicTree } from '/@/components/Tree';
  // import { PageWrapper } from '/@/components/Page';
  import { ResizePageWrapper } from '/@/components/Page';
  import LookProcess from './components/LookProcess.vue';
  import ApproveProcessMonitorUser from './components/flow/ApproveProcessMonitorUser.vue';
  import MonitorChange from './components/MonitorChange.vue';
  import {
    deleteWorkflow,
    getProcessMonitorPage,
    postSetSuspended,
    cancelProcess,
  } from '/@/api/workflow/monitor';
  import { Modal } from 'ant-design-vue';
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
  import { notification, Tag } from 'ant-design-vue';
  import { ProcessMonitorStatus } from '/@/enums/workflowEnum';
  import { BasicTable, useTable, FormSchema, BasicColumn, TableAction } from '/@/components/Table';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  const configColumns: BasicColumn[] = [
    {
      title: t('流水号'),
      dataIndex: 'serialNumber',
      sorter: {
        multiple: 1,
      },
      width: 70,
      resizable: true,
    },
    {
      title: t('任务'),
      dataIndex: 'currentTaskName',
      width: 120,
      sorter: {
        multiple: 2,
      },
      resizable: true,
    },
    {
      title: t('标题'),
      dataIndex: 'schemaName',
      width: 120,
      sorter: {
        multiple: 3,
      },
      resizable: true,
    },
    {
      title: t('状态'),
      dataIndex: 'status',
      width: 100,
      sorter: {
        multiple: 4,
      },
      resizable: true,
      slots: { customRender: 'status' },
    },
    // {
    //   title: '状态详情',
    //   dataIndex: 'statusMessage',
    // },
    {
      title: t('当前进度'),
      dataIndex: 'currentProgress',
      resizable: true,
      slots: { customRender: 'currentProgress' },
    },
    {
      title: t('发起人'),
      dataIndex: 'originator',
      resizable: true,
    },
    {
      title: t('时间'),
      width: 160,
      dataIndex: 'createDate',
      resizable: true,
    },
  ];
  const searchFormSchema: FormSchema[] = [
    {
      field: 'keyword',
      label: t('关键字'),
      component: 'Input',
      colProps: { span: 8 },
      componentProps: {
        placeholder: t('请输入关键字'),
      },
    },
    {
      field: 'searchDate',
      label: t('时间范围'),
      component: 'RangePicker',
      colProps: { span: 8 },
    },
  ];

  const treeData = [
    {
      key: 0,
      id: 0,
      name: t('未完成'),
      icon: 'ant-design:profile-outlined',
    },
    {
      key: 1,
      id: 1,
      name: t('已完成'),
      icon: 'ant-design:profile-outlined',
    },
  ];

  const actionColumn = computed(() => {
    return {
      width: data.type === 0 ? 320 : 80,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
      fixed: undefined,
    };
  });
  const selectedKeys = ref([0]);
  const [registerTable, { reload }] = useTable({
    title: t('流程监控列表'),
    api: getProcessMonitorPage,
    rowKey: 'processId',
    columns: configColumns,
    formConfig: {
      rowProps: {
        gutter: 16,
      },
      schemas: searchFormSchema,
      fieldMapToTime: [['searchDate', ['startTime', 'endTime'], 'YYYY-MM-DD', true]],
      showResetButton: false,
    },
    beforeFetch: (params) => {
      //发送请求默认新增  左边树结构所选机构id
      return { ...params, type: data.type };
    },
    useSearchForm: true,
    showTableSetting: true,
    striped: false,
    pagination: {
      pageSize: 18,
    },
    tableSetting: {
      size: false,
    },
    actionColumn,
  });
  let data: {
    type: number;
    approvedUserVisible: boolean;
    changeNodeVisible: boolean;
  } = reactive({
    type: 0,
    approvedUserVisible: false,
    changeNodeVisible: false,
  });
  const visibleLookProcess = ref(false);
  const taskIdProcess = ref('');
  const processIdProcess = ref('');
  const schemaIdProcess = ref('');

  const approvedUserTitle = ref(t('任务'));

  async function setSuspended(record) {
    let res = await postSetSuspended(record.processId);
    if (res) {
      reload();
      notification.open({
        type: 'success',
        message: record.status === ProcessMonitorStatus.SUSPENDED ? '恢复' : '挂起',
        description: t('成功'),
      });
    }
  }
  function deleteFlow(record) {
    Modal.confirm({
      title: t('提示'),
      icon: createVNode(ExclamationCircleOutlined),
      content: t('请确认是否删除该流程？删除后无法进行恢复。'),
      okText: t('确定'),
      okType: 'danger',
      cancelText: t('取消'),
      onOk() {
        if (record.processId) {
          deleteWorkflow(record.processId).then((res) => {
            if (res) {
              reload();
              notification.open({
                type: 'success',
                message: t('删除成功'),
                description: t('成功'),
              });
            }
          });
        }
      },
      onCancel() {},
    });
  }
  function handleSelect(_, e) {
    data.type = e.node.key;
    selectedKeys.value = [e.node.key];
    reload();
  }
  function approveUser(record) {
    schemaIdProcess.value = record.schemaId;
    taskIdProcess.value = record.taskId;
    approvedUserTitle.value = t('任务-') + record.schemaName + '-' + record.currentTaskName;
    data.approvedUserVisible = true;
  }

  function terminateProcess(record) {
    Modal.confirm({
      title: t('提示'),
      icon: createVNode(ExclamationCircleOutlined),
      content: '终止流程会直接结束该流程，请确认是否继续？',
      okText: t('确定'),
      okType: 'danger',
      cancelText: t('取消'),
      onOk() {
        if (record.processId) {
          cancelProcess(record.processId).then((res) => {
            if (res) {
              reload();
              notification.open({
                type: 'success',
                message: t('终止成功'),
                description: t('成功'),
              });
            }
          });
        }
      },
      onCancel() {},
    });
  }

  function changeNode(record) {
    taskIdProcess.value = record.taskId;
    processIdProcess.value = record.processId;
    data.changeNodeVisible = true;
  }

  function nodeModalClose() {
    data.changeNodeVisible = false;
  }

  function nodeModalSuccess() {
    data.changeNodeVisible = false;
    reload();
  }

  const handleView = (record) => {
    visibleLookProcess.value = true;
    taskIdProcess.value = record.taskId;
    processIdProcess.value = record.processId;
  };
</script>
