<template>
  <div :class="prefixCls">
    <ALayoutContent class="m-10">
      <h4 class="text-center text-lg pb-2">{{ state.formTitle }}</h4>
      <img class="process-status-img"
           :src="state.processImg"
           alt="流程状态"
      >
      <ATables v-model:activeKey="state.taskSelectedTab"
               class="bg-white"
               :tab-bar-style="{ 'padding-left': '13px' }"
      >
        <ATabPane key="formInfo">
          <template #tab>
            <span>
              <Icon icon="fa6-solid:file-lines"/>表单信息
            </span>
          </template>
          <!-- 动态表单:内置使用枇杷表单设计器(待更新为VUE3海豚表单设计器) -->
          <workflow-preview-form v-if="state.formType !== '2'"
                                 ref="formPreview"
                                 :task-form-data="state.taskFormData"
                                 :disabled="true"
          />
          <!-- 外置表单:内置使用用户自定义的vue页面,手动填写页面路径即可 -->
          <component :is="state.formPath"
                     v-if="state.formType === '2'"
                     ref="formPreview"
                     :form-read-only="state.formReadOnly"
                     :businessId="state.businessId"
                     :disabled="true"
          />
        </ATabPane>
        <ATabPane v-if="state.processInsId" key="processInfo">
          <template #tab>
            <span>
              <Icon icon="fa6-solid:money-bill-wheat"/>流程信息
            </span>
          </template>
          <WorkflowTimeLine :history-flow-change-list="state.historyFlowChangeList"/>
        </ATabPane>
        <ATabPane key="processChart" forceRender>
          <template #tab>
            <span>
              <Icon icon="fa-solid:image"/>流程图
            </span>
          </template>
          <WorkflowChartModel ref="workflowChart"/>
        </ATabPane>
        <ATabPane v-if="state.processInsId" key="flowRecord">
          <template #tab>
            <span>
              <Icon icon="fa6-solid:bars-progress"/>流转记录
            </span>
          </template>
          <WorkflowStep :history-flow-change-list="state.historyFlowChangeList"/>
        </ATabPane>
      </ATables>
    </ALayoutContent>
  </div>
</template>
<script lang="ts" setup>
  /**
   * 提供模板规范代码参考,请尽量保证编写代码风格跟模板规范代码一致
   * 采用vben-动态表格表单封装组件编写,采用 setup 写法
   * Copyright © 2023-2023 <a href="https://godolphinx.org">海豚生态开源社区</a> All rights reserved.
   * author wangxiang4
   */
  import { reactive, onActivated, unref, nextTick, ref } from 'vue';
  import { LayoutContent, Tabs } from 'ant-design-vue';
  import type { FormProperty } from '/@/api/platform/workflow/entity/formProperty';
  import type { Workflow } from '/@/api/platform/workflow/entity/workflow';
  import { useRouter } from 'vue-router';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { queryProcessStatus  } from '/@/api/platform/workflow/controller/process';
  import { useTabs } from '/@/hooks/web/useTabs';
  import { listHistoryFlowChange } from '/@/api/platform/workflow/controller/task';
  import WorkflowPreviewForm from './WorkflowPreviewForm.vue';
  import WorkflowChartModel from './WorkflowChartModel.vue';
  import WorkflowTimeLine from './WorkflowTimeLine.vue';
  import WorkflowStep from './workflowStep/index.vue';
  import { useDesign } from '/@/hooks/web/useDesign';
  import { useAppInject } from '/@/hooks/web/useAppInject';
  import agreeImg from '/@/assets/images/workflow/agree.png';
  import deletedImg from '/@/assets/images/workflow/deleted.png';
  import rejectImg from '/@/assets/images/workflow/reject.png';
  import revokeImg from '/@/assets/images/workflow/revoke.png';
  import stopImg from '/@/assets/images/workflow/stop.png';
  import waitingImg from '/@/assets/images/workflow/waiting.png';
  import { getHistoryFormTaskData } from '/@/api/platform/workflow/controller/form';

  /** 类型规范统一声明定义区域 */
  interface WindowState {
    // 流程表单标题
    formTitle: string;
    // 流程表单key
    formKey: string;
    // 表单类型(1:动态表单,2:外置表单)
    formType: string;
    // 外置表单路径
    formPath: string;
    // 外置表单是否只读
    formReadOnly: boolean;
    // 外置表单业务数据绑定ID
    businessId: string;
    // 动态表单字段配置数据
    taskFormData: FormProperty[];

    // 设置选择任务选项卡
    taskSelectedTab: string;
    // 流程任务定义key
    taskDefKey: string;

    // 流程定义ID
    processDefId: string;
    // 流程实例ID
    processInsId: string;
    // 流程定义Key
    processDefKey: string;
    // 流程状态图片
    processImg: string;

    // 历史流转信息
    historyFlowChangeList: Workflow[];
  }

  /** 通用变量统一声明区域 */
  const ALayoutContent = LayoutContent;
  const ATables = Tabs;
  const ATabPane = Tabs.TabPane;

  const { prefixCls } = useDesign('task-form-view');
  const { getIsMobile } = useAppInject();
  const state = reactive<WindowState>({
    formTitle: '',
    formKey: '',
    formType: '',
    formPath: '',
    formReadOnly: false,
    businessId: '',
    taskFormData: [],

    taskSelectedTab: 'formInfo',
    taskDefKey: '',

    processDefId: '',
    processInsId: '',
    processDefKey: '',
    processImg: waitingImg,

    historyFlowChangeList: [],
  });
  const { currentRoute, push } = useRouter();
  const { params, query } = unref(currentRoute);
  const { notification, createMessage, createConfirm } = useMessage();
  const { close } = useTabs();
  const formPreview = ref();
  const workflowChart = ref();
  onActivated(() => {
    handleInit();
    nextTick(async () => {
      // 初始化外置表单
      if (state.formType === '2') {
        if (state.formKey === '/404') {
          state.formPath = '';
          createMessage.info('没有关联流程表单!');
        } else {
          state.formPath = require('@/views' + state.formKey + '.vue').default;
        }
      // 初始化动态表单
      } else {
        state.taskFormData = await getHistoryFormTaskData({
          processInsId: state.processInsId,
          processDefId: state.processDefId,
          taskDefKey: state.taskDefKey
        });
        if (state.formKey === '/404') {
          formPreview.value.init('');
        } else {
          formPreview.value.init(state.formKey);
        }
      }
      // 获取历史任务流转列表
      if (state.processInsId) {
        const processDefinitionInfo = await queryProcessStatus(state.processInsId);
        switch (processDefinitionInfo.mesCode) {
          case '_workflow_process_waiting':
            state.processImg = waitingImg;
            break;
          case '_workflow_process_agree':
            state.processImg = agreeImg;
            break;
          case '_workflow_process_revoke':
            state.processImg = revokeImg;
            break;
          case '_workflow_process_reject':
            state.processImg = rejectImg;
            break;
          case '_workflow_process_stop':
            state.processImg = stopImg;
            break;
          case '_workflow_process_deleted':
            state.processImg = deletedImg;
            break;
        }
        state.historyFlowChangeList = await listHistoryFlowChange(state.processInsId);
      }
      workflowChart.value.init(state.processInsId, state.processDefId);
    });
  });

  function handleInit() {
    state.taskSelectedTab = 'formInfo';
    state.processDefId = query.processDefId as string;
    state.processInsId = query.processInsId as string;
    state.processDefKey = query.processDefKey as string;
    state.formType = query.formType as string;
    state.formKey = query.formKey as string;
    state.taskDefKey = query.taskDefKey as string;
    state.formTitle = query.formTitle as string;
    state.businessId = query.businessId as string;
    state.formReadOnly = query.formReadOnly === 'true';
  }

</script>
<style lang="less" scoped>
  @prefix-cls: ~'@{namespace}-task-form-view';

  .@{prefix-cls} {
    .process-status-img {
      height: 180px;
      position: absolute;
      z-index: @page-footer-z-index;
      top: 1px;
      right: 1px;
    }
  }

</style>
