<template>
  <PageWrapper :class="prefixCls">
    <div class="btn-box">
      <a-button type="primary" :icon="h(SendOutlined)" @click="handleSubmit" class="ml-2"
        >发起流程
      </a-button>
      <!-- <a-button
        type="primary"
        @click="closePage"
        class="ml-2"
        danger
        >关闭
      </a-button> -->
    </div>
    <a-layout>
      <a-layout>
        <a-layout-content>
          <a-tabs v-model:activeKey="activeName" @change="changeActive">
            <a-tab-pane key="form" tab="表单信息" v-if="formVisble">
              <FormViewer
                ref="formBoxRef"
                :formConfig="formConfig"
                :processId="designerData.process.id"
                :formVerison="designerData.formCurrentNode.formVerison"
                :formRelationId="designerData.formCurrentNode.formRelationId"
                v-if="formVisble"
              />
            </a-tab-pane>
            <a-tab-pane key="flow" tab="流程模板" force-render>
              <div class="process-design" :style="'display: flex; height:' + designerData.height">
                <process-viewer
                  v-if="processVisble"
                  :key="`designer-${id}`"
                  :events="['element.click']"
                  @element-click="elementClick"
                  :xml="flowContent"
                  :flowViewer="flowViewer"
                />
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-layout-content>
        <a-layout-sider v-if="designerData.userLogs.length > 0">
          <a-tabs v-model:activeKey="auditName">
            <a-tab-pane key="audit" tab="审批信息">
              <div class="approval-info">
                <auditInfo :data="designerData.userLogs" />
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-layout-sider>
      </a-layout>
    </a-layout>

    <!-- 节点记录信息 -->
    <div class="info-box" v-if="designerData.nodeLogs.length > 0">
      <a-drawer v-model:open="infoOpen" class="custom-class" title="记录信息" placement="right">
        <a-timeline>
          <a-timeline-item v-for="(item, index) in designerData.nodeLogs" :key="index">
            <div class="title">{{ item.time }}</div>
            <a-card hoverable size="small">
              <div class="type-title">{{ item.name }}</div>
              <div class="content">
                <span class="link" v-for="(userName, index2) in item.userNames" :key="index2">{{
                  userName
                }}</span>
                {{ item.des }}
              </div>
            </a-card>
          </a-timeline-item>
        </a-timeline>
      </a-drawer>
    </div>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, reactive, onBeforeMount, h } from 'vue';
  import { SendOutlined } from '@ant-design/icons-vue';
  import { FormViewer } from '@/components/FormViewer';
  import { ProcessViewer } from '@/components/ProcessViewer';
  import { PageWrapper } from '@/components/Page';
  import { getBPMN, create } from '@/api/sys/WFProcess';
  import { IFormConfig } from '@/views/demo/form-design/typings/v-form-component';
  import { functionsaveForm } from '@/api/demo/formScheme';
  import { buildGUID } from '@/utils/uuid';
  import { dateFormat } from '@/utils/base';
  import { designerDataType, logsType } from './processModel';
  import { auditInfo } from './page';
  import { useMessage } from '@/hooks/web/useMessage';

  const emit = defineEmits(['closeModel']);
  const { createMessage } = useMessage();
  const props = defineProps({
    processId: String,
  });
  const prefixCls = 'preview-box';
  const flowContent = ref('');
  const flowViewer = ref({});
  const infoOpen = ref(true);
  const formBoxRef = ref<any>();
  const formVisble = ref(false);
  const processVisble = ref(false);
  // 表单数据
  const formConfig = ref<IFormConfig>({
    // 表单配置
    schemas: [],
    layout: 'horizontal',
    labelLayout: 'flex',
    labelWidth: 100,
    labelCol: {},
    wrapperCol: {},
    currentItem: {
      component: '',
      componentProps: {},
    },
    activeKey: 1,
  });
  const designerData: designerDataType = reactive({
    loading: false,
    xmlString: '',
    height: document.documentElement.clientHeight - 200.5 + 'px;',
    midVisible: false,
    isCustmerTitle: false,
    nodeUsers: [],
    selectUsersVisible: false,
    selectTUserVisible: false,
    tUserType: 1, // 1 转移 2 加签,
    isDraft: false,
    delegateUsers: [],
    task: {},
    process: {},
    logs: [], // 流程日志信息
    nodeMap: {}, // 需要处理的任务
    userLogs: [], // 人员日志信息
    nodeLogs: [],
    taskBtns: [],
    currentNode: {},
    stampList: [],
    currentBtn: {
      code: '',
      name: '',
      isNextAuditor: false,
    },
    wfData: [],
    selectRejectNodeVisible: false,
    selectSignVisible: false,
    formCurrentNode: {},
  });
  const activeName = ref('form');
  const auditName = ref('audit');
  function changeActive(activeKey) {
    if (activeKey == 'flow') {
      processVisble.value = true;
    } else {
      processVisble.value = false;
    }
  }
  function elementClick(element: { id: string | number }) {
    if (element) {
      designerData.nodeLogs = designerData.nodeMap[element.id] || [];
      infoOpen.value = true;
    } else {
      designerData.nodeLogs = [];
    }
  }
  async function getDetailInfo() {
    let query: any = {
      id: props.processId,
    };
    let data = await getBPMN(query);
    flowContent.value = data.flowContent;
    flowViewer.value = data.flowViewer;
    designerData.process = data.process;
    designerData.task = data.task;
    let content = JSON.parse(data.scheme.content);
    let wfData = content.wfData;
    const currentNode = wfData.find((t) => t.type == 'bpmn:StartEvent');
    if (currentNode.authFields.length > 0) {
      formVisble.value = true;
    } else {
      activeName.value = 'flow';
      processVisble.value = true;
    }
    designerData.formCurrentNode = currentNode;
    formConfig.value = currentNode.authFields;
    setLogsAndTasks(data.logs, data.tasks);
    // getBtns();
  }

  function setLogsAndTasks(logs: any[], tasks: any[]) {
    const res: logsType[] = [];
    const taskMap = {};
    const nodeMap = {};
    const userLogs: any[] = [];

    tasks.forEach(
      (task: {
        unitId: string | number;
        unitName: any;
        createDate: any;
        type: number;
        userId: any;
        userName: any;
      }) => {
        nodeMap[task.unitId] = nodeMap[task.unitId] || [
          {
            unitId: task.unitId,
            name: task.unitName,
            userIds: [],
            userNames: [],
            des: '正在审核',
            time: `当前-创建时间:${dateFormat(task.createDate)}`,
            type: 'primary',
            isFinish: false,
          },
        ];

        if (task.type == 2) {
          taskMap[task.unitId + task.type] = taskMap[task.unitId + task.type] || {
            unitId: task.unitId,
            name: task.unitName,
            userIds: [],
            userNames: [],
            des: '正在查阅',
            time: `当前-创建时间:${dateFormat(task.createDate)}`,
            type: 'primary',
          };
          taskMap[task.unitId + task.type].userIds.push(task.userId);
          taskMap[task.unitId + task.type].userNames.push(task.userName);

          if (nodeMap[task.unitId].length == 1) {
            nodeMap[task.unitId].push({
              unitId: task.unitId,
              name: task.unitName,
              userIds: [],
              userNames: [],
              des: '正在查阅',
              time: `当前-创建时间:${dateFormat(task.createDate)}`,
              type: 'primary',
              isFinish: true,
            });
          }
          nodeMap[task.unitId][1].userIds.push(task.userId);
          nodeMap[task.unitId][1].userNames.push(task.userName);
        } else {
          taskMap[task.unitId] = taskMap[task.unitId] || {
            unitId: task.unitId,
            name: task.unitName,
            userIds: [],
            userNames: [],
            des: '正在审核',
            time: `当前-创建时间:${dateFormat(task.createDate)}`,
            type: 'primary',
          };
          taskMap[task.unitId].userIds.push(task.userId);
          nodeMap[task.unitId][0].userIds.push(task.userId);
          taskMap[task.unitId].userNames.push(task.userName);
          nodeMap[task.unitId][0].userNames.push(task.userName);
        }
      },
    );

    for (let key in taskMap) {
      res.push(taskMap[key]);
    }

    for (let key in nodeMap) {
      nodeMap[key] = nodeMap[key].filter((t: { userIds: string | any[] }) => t.userIds.length > 0);
    }

    logs.forEach(
      (log: {
        unitId: string;
        unitName: any;
        userId: string;
        userName: string;
        des: string;
        operationName: string;
        createDate: any;
        taskType: number;
        operationCode: string;
        stampImg: any;
      }) => {
        res.push({
          unitId: log.unitId,
          name: log.unitName,
          userIds: [log.userId],
          userNames: [log.userName],
          des: log.des ? log.des : log.operationName,
          time: dateFormat(log.createDate),
          type: 'info',
        });

        nodeMap[log.unitId] = nodeMap[log.unitId] || [];
        nodeMap[log.unitId].push({
          unitId: log.unitId,
          name: log.unitName,
          userIds: [log.userId],
          userNames: [log.userName],
          time: dateFormat(log.createDate),
          des: log.des ? log.des : log.operationName,
          type: 'info',
          isFinish: true,
        });
        if (log.taskType == 1 && !['sign'].includes(log.operationCode)) {
          // 右侧显示审核记录
          // const userLogIndex = userLogs.findIndex((t) => t.id == log.unitId);
          // if (userLogIndex == -1) {
          userLogs.push({
            id: log.unitId,
            name: log.unitName,
            user: log.userName,
            time: dateFormat(log.createDate),
            des: log.des,
            img: log.stampImg,
          });
          // }
        }
      },
    );

    designerData.logs = res;
    designerData.nodeMap = nodeMap;
    designerData.userLogs = userLogs.sort(function (a, b) {
      return a.time < b.time ? -1 : 1;
    });
  }
  function handleSubmit() {
    var processId = designerData.process.id;
    var querys = {
      schemeId: designerData.formCurrentNode.formVerison,
      isUpdate: false,
      pkey: designerData.formCurrentNode.formRelationId,
      pkeyValue: processId,
    };
    // 有表单内容，先存表单信息
    if (formVisble.value) {
      if (!designerData.formCurrentNode.formRelationId) {
        return createMessage.error('请设置表单和流程关联字段');
      }
      formBoxRef.value
        .getForm()
        .then(async (res) => {
          res[designerData.formCurrentNode.formRelationId] = processId;
          for (var item in res) {
            if (res[item] == undefined) {
              res[item] = '';
              if (item.search('_input_guid') != -1) {
                res[item] = buildGUID();
              }
            }
          }
          querys.data = JSON.stringify(res);
          const formValue = await functionsaveForm(querys);
          if (formValue) {
            handleCreateFlow(processId);
          }
        })
        .catch((error) => {
          console.log(error);
          activeName.value = 'form';
          return;
        });
    } else {
      handleCreateFlow(processId);
    }
  }
  async function handleCreateFlow(processId) {
    var querys = {
      schemeCode: '',
      userId: designerData.process.userId,
      title: '',
      processId: processId,
    };
    const data = await create(querys);
    if (data) {
      closePreview();
      return createMessage.success('发起流程成功');
    } else {
      return createMessage.error('发起流程失败');
    }
  }
  function closePreview() {
    emit('closeModel');
  }
  // function closePage() {
  //   tabStore.closeTabByKey('/dashboard/task_look_preview/detail?processId=' + processId, router);
  // }

  onBeforeMount(() => {
    getDetailInfo();
  });
</script>
<style lang="less" scoped>
  ::v-deep .ant-tabs-nav-wrap {
    padding-left: 10px;
  }
  ::v-deep .ant-layout {
    height: 100%;
    background-color: @component-background;
  }
  ::v-deep .ant-layout-sider-children {
    border-left: 1px solid rgba(5, 5, 5, 0.06);
  }
  ::v-deep .ant-divider-vertical {
    height: 100%;
  }
  .info-box {
    display: inline-block;
    width: 300px;
    position: absolute;
    right: 0;
    margin-top: 40px;
  }

  .ant-timeline-item-content {
    .title {
      color: #909399;
      line-height: 1;
      margin-bottom: 8px;
      font-size: 13px;
    }

    .type-title {
      font-size: 12px;
      font-weight: bold;
      margin-bottom: 8px;
    }

    .link {
      color: #409eff;
    }
  }

  .preview-box {
    height: 100%;

    .btn-box {
      padding: 10px;
      justify-content: flex-end;
      display: flex;
    }
  }
  ::v-deep .vben-page-wrapper-content {
    height: 100%;
    margin: 0 0 0 16px;
  }
  .form-box {
    width: 480px;
  }

  .approval-column {
    padding: 10px;
  }
  ::v-deep .ant-layout .ant-layout-sider {
    padding-left: 10px;
    background-color: @component-background;
    flex: 0 0 360px !important;
    max-width: 360px !important;
    min-width: 360px !important;
    width: 360px !important;
  }
  ::v-deep .vben-page-wrapper .vben-page-wrapper-content {
    height: 98%;
  }
  .l-task-btns {
    .ant-btn {
      margin: 0;
      margin-top: 8px;
      margin-right: 8px;
    }
  }
</style>
