<template>
  <PageWrapper :class="prefixCls">
    <a-spin :spinning="spinning" style="width: 100%; height: 100%">
      <div class="btn-box">
        <a-button type="primary" @click="confimReading" class="ml-2" v-if="props.isRead == 1"
          >确认阅读
        </a-button>
        <a-button type="primary" @click="closePage" class="ml-2" danger>关闭 </a-button>
      </div>

      <div class="maper-container" v-if="mapConfig?.isShowMap">
        <MapboxMap
          :caseno="casenoValue"
          :countyname="
            props.auditData && props.auditData.countyname ? props.auditData.countyname : ''
          "
          :mapConfig="mapConfig"
          :geomsList="geomsList"
          @handlerDrawComplete="handlerDrawComplete"
          @mapOnLoad="onMapboxLoad"
          ref="MapboxComponent"
        />
      </div>

      <div
        id="form-container"
        @mousemove="onFormContainerMouseOver"
        style="position: relative"
        :class="mapConfig?.isShowMap ? 'form-container' : ''"
      >
        <a-layout>
          <a-layout>
            <a-layout-content v-if="false">
              <a-tabs
                v-model:activeKey="activeName"
                tabPosition="bottom"
                @change="changeActive"
                type="card"
              >
                <a-tab-pane
                  key="form"
                  :tab="
                    designerData.formCurrentNode.formTitle
                      ? designerData.formCurrentNode.formTitle
                      : '表单信息'
                  "
                  v-if="formVisble"
                >
                  <div id="process-form-container">
                    <ImagePreview
                      style="width: 100%; height:"
                      v-if="isShowImagePreview"
                      :globalImagePreviewUrl="globalImagePreviewUrl"
                      :globalImagePreviewList="globalImagePreviewList"
                      @closeImagePreview="closeImagePreview"
                    />

                    <FormViewer
                      ref="formBoxRef"
                      :formConfig="formConfig"
                      :processId="designerData.process.id"
                      :formVerison="designerData.formCurrentNode.formVerison"
                      :formRelationId="designerData.formCurrentNode.formRelationId"
                      :instanceInfo="designerData.process.instanceInfo"
                      :noSubmit="noSubmit"
                      @getFormSuccess="getFormSuccess"
                      v-if="formVisble"
                    />
                  </div>
                </a-tab-pane>
                <a-tab-pane
                  key="form"
                  :tab="
                    designerData.formCurrentNode.formTitle
                      ? designerData.formCurrentNode.formTitle
                      : '系统表单信息'
                  "
                  v-if="formUrlVisble"
                >
                  <AsyncComponent ref="pcForm" />
                </a-tab-pane>
                <a-tab-pane key="flow" tab="流程模板" force-render v-if="false">
                  <div class="process-design" style="display: flex; height: calc(100vh - 350px)">
                    <process-viewer
                      v-if="processVisble"
                      :key="`designer-${id}`"
                      :events="['element.click']"
                      @element-click="elementClick"
                      :xml="flowContent"
                      :flowViewer="flowViewer"
                    />
                  </div>
                </a-tab-pane>
                <a-tab-pane key="record" tab="操作记录" force-render v-if="false">
                  <div
                    :style="'padding:10px 0 40px 0;overflow:auto; height:' + designerData.height"
                  >
                    <a-timeline>
                      <a-timeline-item
                        v-for="(item, index) in designerData.logs"
                        :key="index"
                        :color="item.type"
                      >
                        <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>
                  </div>
                </a-tab-pane>
              </a-tabs>
            </a-layout-content>
            <a-layout-content>
              <div id="process-form-container">
                <ImagePreview
                  style="width: 100%; height:"
                  v-if="isShowImagePreview"
                  :globalImagePreviewUrl="globalImagePreviewUrl"
                  :globalImagePreviewList="globalImagePreviewList"
                  @closeImagePreview="closeImagePreview"
                />

                <FormViewer
                  ref="formBoxRef"
                  :formConfig="formConfig"
                  :processId="designerData.process.id"
                  :formVerison="designerData.formCurrentNode.formVerison"
                  :formRelationId="designerData.formCurrentNode.formRelationId"
                  :instanceInfo="designerData.process.instanceInfo"
                  :noSubmit="noSubmit"
                  @getFormSuccess="getFormSuccess"
                  v-if="formVisble"
                />
              </div>
              <AsyncComponent ref="pcForm" v-if="formUrlVisble" />
            </a-layout-content>
            <div :style="footerStyle">
              <a-tabs v-if="props.isRead == 0" v-model:activeKey="auditName">
                <a-tab-pane key="audit" :tab="auditTitleVal">
                  <div class="approval-column">
                    <a-form
                      ref="formRef"
                      :rules="rules"
                      :model="formData"
                      size="small"
                      labelAlign="left"
                      :label-col="2"
                      :wrapper-col="22"
                    >
                      <!-- <a-form-item :label="auditNameVal" /> -->
                      <!-- <div style="margin-bottom: 20px">某某【退回】 ： {{ backDescription }}</div> -->
                      <a-form-item :label="auditNameVal">
                        <a-textarea
                          v-model:value="formData.des"
                          placeholder="请输入"
                          :auto-size="{ minRows: 2, maxRows: 8 }"
                        />
                      </a-form-item>
                      <a-form-item
                        label=""
                        :class="btnVisble ? 'l-task-btns' : 'l-task-btns btn-hidden'"
                        v-if="formVisble"
                      >
                        <a-button
                          v-for="(btn, index) in designerData.taskBtns"
                          :key="index"
                          :color="btn.type"
                          :type="btn.type ? btn.type : 'primary'"
                          @click="handleBtnClick(btn)"
                          >{{ btn.name }}</a-button
                        >
                      </a-form-item>
                    </a-form>
                    <!-- <auditInfo :data="designerData.userLogs" /> -->
                  </div>
                </a-tab-pane>
                <a-tab-pane key="record" tab="流转信息" force-render>
                  <div :style="'padding:10px 0 40px 0;overflow:auto; height:220px'">
                    <a-timeline>
                      <a-timeline-item
                        v-for="(item, index) in designerData.logs"
                        :key="index"
                        :color="item.type"
                      >
                        <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>
                  </div>
                </a-tab-pane>
              </a-tabs>
            </div>
          </a-layout>
        </a-layout>
      </div>
      <!-- 节点记录信息 -->
      <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"
              :color="item.type"
            >
              <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>
      <a-modal
        v-model:open="rejectOpen"
        width="50%"
        title="驳回节点选择"
        @ok="rejectHandleOk"
        :destroyOnClose="true"
      >
        <div class="l-from-body">
          <a-form
            ref="rejectFormRef"
            :model="reject"
            labelAlign="left"
            :label-col="rejectLabelCol"
            :wrapper-col="rejectWrapperCol"
            :rules="rejectRules"
          >
            <a-form-item label="驳回到" name="nextId">
              <a-select
                v-model:value="reject.nextId"
                placeholder="驳回节点选择"
                :field-names="{ label: 'unitName', value: 'unitId' }"
                :options="rejectRelations"
              />
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </a-spin>
  </PageWrapper>
</template>

<script lang="ts" setup>
  import { ref, reactive, onBeforeMount, watch, defineAsyncComponent } from 'vue';
  import { ProcessViewer } from '@/components/ProcessViewer';
  import { PageWrapper } from '@/components/Page';
  import { createAgain, signAudit, audit, ReadFlow } from '@/api/sys/WFProcess';
  import { getBPMNTask } from '@/api/sys/WFTask';
  import { getGeom } from '@/api/sys/layerManagement';
  import { dateFormat } from '@/utils/base';
  import { flowStore } from '@/store/modules/flow';
  import { functionsaveForm, LoadFormScheme } from '@/api/demo/formScheme';
  import { FormViewer } from '@/components/FormViewer';
  import { storeToRefs } from 'pinia';
  import ImagePreview from '@/components/Upload/src/components/image_preview.vue';
  import { userFormFileStore } from '@/store/modules/formFileUrl';
  import { getConfig } from '@/api/sys/layerManagement';
  import { getLoadCaseImgList } from '@/api/tiankongdi';

  import {
    designerDataType,
    logsType,
    taskBtnsType,
    currentNodeObject,
    nodeUsersType,
  } from './processModel';
  import { auditInfo } from './page';
  import { IFormConfig } from '@/views/demo/form-design/typings/v-form-component';
  import { useMessage } from '@/hooks/web/useMessage';
  import { buildGUID } from '@/utils/uuid';
  import { settings } from 'nprogress';
  import { flowCodeName } from '@/views/demo/workflow/flowcode';

  const MapboxMap = defineAsyncComponent(() => import('@/components/MapboxMaps/MapComponent.vue'));
  const spinning = ref(false);
  let quickClick: any = null;
  const goClick = ref(true);
  const geomsList = ref();
  const mapConfig = ref({ isShowMap: false });
  const MapboxComponent = ref();
  const { createMessage, createConfirm } = useMessage();
  const formBoxRef = ref<any>();
  const emit = defineEmits(['closeModel']);
  const keyValue = ref('');
  const rejectLabelCol = { span: 5 };
  const rejectWrapperCol = { span: 17 };
  const flowWfDataStore = flowStore();
  const prefixCls = 'preview-box';
  const flowContent = ref('');
  const flowViewer = ref({});
  const formRef = ref();
  const labelCol = { span: 1 };
  const wrapperCol = { span: 22 };
  const infoOpen = ref(true);
  const formVisble = ref(false);
  const formUrlVisble = ref(false);
  const processVisble = ref(false);
  const AsyncComponent = ref();
  const pcForm = ref();
  const reject = ref({
    nextId: '',
  });
  const rejectFormRef = ref();
  const rejectRules = reactive({
    nextId: [{ required: true, message: '请选择驳回节点', trigger: 'blur' }],
  });
  const rejectRelations = ref([]);
  const props = defineProps({
    processId: String,
    taskId: String,
    type: String,
    isRead: String,
    auditData: Object,
  });

  const casenoValue = () => {
    if (props.auditData && props.auditData.case_no) {
      return props.auditData.case_no;
    } else if (props.auditData && props.auditData.caseno) {
      return props.auditData.caseno;
    } else {
      return '';
    }
  };
  const formData = ref({
    des: '',
  });
  const rules: any = ref({
    des: [{ required: true, message: '请填写审批意见', trigger: 'blur' }],
  });
  const backDescription = ref('退回描述');

  if (props.type == 4) {
    rules.value = {};
  }
  const btnVisble = ref(true);
  // 表单数据
  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 - 350 + '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: [],
    isCreateAgain: props.type == 4 ? true : false,
    selectRejectNodeVisible: false,
    selectSignVisible: false,
    formCurrentNode: {},
  });
  const activeName = ref('form');
  const auditName = ref('audit');
  const auditTitleVal = ref('审批栏');
  const auditNameVal = ref('审批意见');
  const rejectOpen = ref(false);
  const footerStyle = ref({
    height: '220px',
    width: mapConfig.value.isShowMap ? '100%' : '60%',
    overFlow: 'auto',
    color: '#fff',
    backgroundColor: '#ffffff',
    zIndex: '123',
    padding: '0px 100px',
    position: 'fixed',
    bottom: '0px',
    right: '0px',
  });
  const noSubmit = ref<string[]>([])

  function changeActive(activeKey) {
    if (activeKey == 'flow') {
      processVisble.value = true;
    }
  }
  function elementClick(element: { id: string | number }) {
    if (element) {
      designerData.nodeLogs = designerData.nodeMap[element.id] || [];
      infoOpen.value = true;
    } else {
      designerData.nodeLogs = [];
    }
  }

  const imageList = ref([]);
  async function getCaseImgList() {
    imageList.value = await getLoadCaseImgList({
      caseid: props.processId,
      category: flowCodeName(designerData.process.schemeCode),
    });
    if (MapboxComponent.value) {
      MapboxComponent.value.handlerLoadPictureAzimuth(imageList.value);
    }
  }

  async function getTaskInfo() {
    rejectRelations.value = [];
    let query: any = {
      id: props.taskId,
    };
    let data = await getBPMNTask(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 map = new Map();
    const newArr = data.logs.filter((v) => !map.has(v.unitId) && map.set(v.unitId, v));
    // taskType == 1审核任务 7单任务
    rejectRelations.value = newArr.filter((item) => item.taskType == 1 || item.taskType == 7);

    const auditNode = wfData.find((t) => t.id == data.task.unitId);
    if (auditNode.auditTitle) {
      auditTitleVal.value = auditNode.auditTitle;
    }
    if (designerData.isCreateAgain) {
      auditNameVal.value = '备注';
    } else {
      if (auditNode.auditName) {
        auditNameVal.value = auditNode.auditName;
      }
    }

    let currentNode;

    let currentMapNode = wfData.find((t) => t.type == 'bpmn:StartEvent');

    // mapConfig.value = currentMapNode.mapConfig;
    if (auditNode.isInherit) {
      currentNode = wfData.find((t) => t.type == 'bpmn:StartEvent');
      // mapConfig.value = currentNode.mapConfig;

      footerStyle.value.width = mapConfig.value?.isShowMap ? '100%' : '60%';
      if (mapConfig.value?.isShowMap) {
      }
    } else {
      currentNode = auditNode;
      let currentMapNode = wfData.find((t) => t.type == 'bpmn:StartEvent');
      // mapConfig.value = currentMapNode.mapConfig;
      footerStyle.value.width = mapConfig.value?.isShowMap ? '100%' : '60%';
    }

    getConfig({ code: 'mapsetting' }).then((res) => {
      mapConfig.value = JSON.parse(res.codeValue);
    });

    if (currentNode.authFields.length > 0) {
      formVisble.value = true;
    } else if (currentNode.formUrl) {
      // 有PC系统表单时
      formUrlVisble.value = true;
      let url = '../../../' + currentNode.formUrl + '.vue';
      // AsyncComponent.value = defineAsyncComponent(() => import(url));
      AsyncComponent.value = defineAsyncComponent({
        // 加载函数
        loader: () => import(url),
        // 展示加载组件前的延迟时间，默认为200ms,注：这里如果设置的时间过短，会有闪烁的效果
        delay: 200,
        // 如果提供了一个timeout时间限制，并且超时了，也会展示这里的报错组件
        // 设置加载超时时间为3000毫秒
        timeout: 3000,
        onError: function () {
          createMessage.error('无法加载系统表单，请查看流程配置是否正确!');
        },
      });
    } else {
      activeName.value = 'flow';
      processVisble.value = true;
    }
    designerData.formCurrentNode = currentNode;
    formConfig.value = currentNode.authFields;
    if (props.isRead == 0) {
      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: task.unitName.replace('待', '正在'),
            time: `当前-创建时间:${dateFormat(task.createDate)}`,
            type: 'blue',
            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: 'blue',
            taskType: task.type,
          };
          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: 'blue',
              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: task.unitName.replace('待', '正在'),
            time: `当前-创建时间:${dateFormat(task.createDate)}`,
            type: 'blue',
            taskType: task.type,
          };
          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.reverse();
    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: 'gray',
          taskType: log.taskType,
        });

        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: 'gray',
          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,
          });
          // }
        }
      },
    );
    // taskType == 1审核任务 7单任务
    designerData.logs = res.filter((item) => item.taskType == 1 || item.taskType == 7);
    designerData.nodeMap = nodeMap;
    designerData.userLogs = userLogs.sort(function (a, b) {
      return b.time < a.time ? -1 : 1;
    });
  }
  async function validateForm() {
    let res = await formRef.value
      .validate()
      .then(() => {
        return true;
      })
      .catch(() => {
        return false;
      });
    return res;
  }
  function getBtns() {
    const wfData = flowWfDataStore.getWfData;
    designerData.wfData = wfData;
    const currentNode: currentNodeObject =
      wfData.find((t) => t.id == designerData.task.unitId) || {};
    designerData.currentNode = currentNode;
    // 设置审核按钮
    const btns: taskBtnsType[] = [];
    if (currentNode.type == 'bpmn:StartEvent') {
      btns.push({
        code: 'hc_create',
        name: '提交',
        type: '',
      });
    } else {
      currentNode.btnlist.forEach((btn: taskBtnsType) => {
        if (btn.hidden == false) {
          if (btn.code == 'agree') {
            btn.type = '';
          } else if (btn.code == 'disagree') {
            btn.type = 'error';
          }
          btns.push(btn);
        }
      });

      if (currentNode.isAddSign) {
        btns.push({
          code: 'hc_sign',
          name: '加签',
          type: 'success',
        });
      }

      if (currentNode.isTransfer) {
        btns.push({
          code: 'hc_transfer',
          name: '转移',
          type: 'success',
        });
      }
    }
    designerData.taskBtns = btns;
  }
  async function handleBtnClick(btn) {
    if (goClick.value) {
      goClick.value = false;
      quickClick = setTimeout(() => {
        goClick.value = true;
      }, 1000);
    } else {
      return;
    }
    const instanceInfo = designerData.process.instanceInfo;
    // 验证审批栏必填项
    // const data = await validateForm();
    // if (!data) {
    //   return;
    // }
    // 有表单先提交表单数据
    if (btn.name == '同意') {
      createConfirm({
        iconType: 'info',
        title: btn.name,
        content: '确定要' + btn.name + '吗？',
        onOk: () => {
          confimBtnClick(btn);
        },
        onCancel: () => {
          console.log('不确定');
        },
      });
    } else if (btn.code == 'disagree') {
      if (!formData.value.des) {
        createMessage.warning('请填写驳回意见');
        btnVisble.value = true;
        return false;
      } else {
        confimBtnClick(btn);
      }
    } else {
      // btnVisble.value = false;
      confimBtnClick(btn);
    }
  }
  async function confimBtnClick(btn) {
    const instanceInfo = designerData.process.instanceInfo;

    if (formVisble.value) {
      var querys = {
        schemeId: designerData.formCurrentNode.formVerison,
        isUpdate: true,
        pkey: instanceInfo.pkey,
        pkeyValue: instanceInfo.pkeyValue,
      };
      await formBoxRef.value
        .getForm()
        .then(async (res) => {
          console.log(res);
          if (!res) {
            console.log('无语无语');
            createMessage.error('请检查表单必填项');
            btnVisble.value = true;
            return false;
          } else {
            res[designerData.formCurrentNode.formRelationId] = instanceInfo.pkeyValue;
            for (var item in res) {
              if (res[item] == undefined) {
                res[item] = '';
                if (item.search('_input_guid') != -1) {
                  res[item] = buildGUID();
                }
              }
            }
            console.log('审核提交');
            setTimeout(async () => {
              // 将不提交的数据过滤掉
              let resultQuery = {}
              Object.keys(res).forEach(key => {
                if(!noSubmit.value.includes(key)){
                  resultQuery[key] = res[key]
                }
              })
              querys.data = JSON.stringify(resultQuery);
              spinning.value = true;
              const formValue = await functionsaveForm(querys);
              spinning.value = false;
              if (formValue) {
                if (btn.code == 'zancun') {
                  createMessage.success('暂存成功');
                  return;
                }
                handleSubmit(btn);
              }
            }, 100);
          }
        })
        .catch((error) => {
          spinning.value = false;
          console.log(error);
          activeName.value = 'form';
          return;
        });
    } else if (formUrlVisble.value) {
      //有系统表单，先存系统表单
      const funName = btn.code;
      const res = await pcForm.value[funName]();
      handleSubmit(btn);
    } else {
      handleSubmit(btn);
    }
  }
  async function handleSubmit(btn) {
    const currentBtn = btn;
    designerData.currentBtn = currentBtn;
    let res: any;
    switch (btn.code) {
      case 'hc_create':
        try {
          spinning.value = true;
          res = await createAgain({
            processId: props.processId,
            des: `重新提交${formData.value.des ? '-' : ''}${formData.value.des}`,
          });
          spinning.value = false;
        } catch (e) {
          spinning.value = false;
          console.log(e);
        }
        break;
      case 'hc_sign':
        designerData.tUserType = 2;
        designerData.selectTUserVisible = true;
        break;
      case 'hc_transfer':
        designerData.tUserType = 1;
        designerData.selectTUserVisible = true;
        break;
      default:
        if (designerData.task.type == 6) {
          // 加签审核
          try {
            spinning.value = true;
            res = await signAudit(props.taskId, {
              code: btn.code,
              name: btn.name,
              des: formData.value.des,
            });
            spinning.value = false;
          } catch (e) {
            spinning.value = false;
            console.log(e);
          }
        } else {
          if (designerData.currentNode.rejectType == '2' && btn.code == 'disagree') {
            designerData.selectRejectNodeVisible = true;
            rejectOpen.value = true;
            return;
          }

          if (btn.isSign) {
            // 加载签章数据
            // const stampList = await this.$awaitWraper(apiStamp.getList(this.loginInfo.f_UserId));
            // if (stampList && stampList.length > 0) {
            //   designerData.stampList = stampList;
            //   designerData.selectSignVisible = true;
            //   return;
            // }
          }
          res = await auditFun();
        }
        break;
    }
    // if (res) {
    //   closePage();
    //   return createMessage.success('成功');
    // } else {
    //   return createMessage.error('失败');
    // }
  }
  async function auditFun() {
    btnVisble.value = false;
    // 获取接下来节点审核人
    if (designerData.currentBtn.isNextAuditor) {
      spinning.value = true;
      const res = await getLoadNextAuditors({
        processId: props.processId,
        nodeId: designerData.currentNode.id,
      });
      spinning.value = false;
      const nodeUserMap = res.data.data;
      const nodeUsers: nodeUsersType[] = [];
      for (let key in nodeUserMap) {
        const nodeUserItem = nodeUserMap[key];
        if (nodeUserItem.length > 1) {
          nodeUsers.push({
            name: designerData.wfData.find((t) => t.id == key).name,
            id: key,
            options: nodeUserItem.map((t: { id: any; name: any }) => {
              return { value: t.id, label: t.name };
            }),
          });
        }
      }

      designerData.nodeUsers = nodeUsers;

      if (designerData.nodeUsers.length > 0) {
        designerData.selectUsersVisible = true;
        return;
      }
    }
    spinning.value = true;
    const data = await audit(props.taskId, {
      code: designerData.currentBtn.code,
      name: designerData.currentBtn.name,
      des: formData.value.des,
    });
    spinning.value = false;
    if (data) {
      btnVisble.value = false;
      closePage();
      return createMessage.success('成功');
    } else {
      btnVisble.value = true;
      return createMessage.error('失败');
    }
  }
  function closePage() {
    emit('closeModel');
    // tabStore.closeTabByKey(
    //   '/dashboard/task_audit_preview/detail?processId=' +
    //     processId +
    //     '&taskId=' +
    //     taskId +
    //     '&type=' +
    //     type +
    //     '&isRead=' +
    //     isRead,
    //   router,
    // );
  }
  async function confimReading() {
    const data = await ReadFlow(props.taskId);
    if (data) {
      closePage();
      return createMessage.success('成功');
    } else {
      return createMessage.error('失败');
    }
  }

  const chooseLayer = ref<string>('');
  const geomfield = ref<string>('');

  function findValue(obj, targetKey) {
    for (var key in obj) {
      if (typeof obj[key] === 'object') {
        // 如果当前值是对象，则递归调用findValue
        var result = findValue(obj[key], targetKey);
        if (result !== undefined && result == 'MapGeom') {
          return result;
        }
      } else if (key === targetKey && obj[key] == 'MapGeom') {
        // 如果当前键等于目标键，则返回对应的值
        chooseLayer.value = obj['mapSetData'].chooseLayer;
        geomfield.value = obj['field'];
        return obj[key];
      }
    }
  }

  function getFormSuccess(formData) {
    if (mapConfig.value.isShowMap) {
      handlerShowGeomtrys(designerData.formCurrentNode, formData);
      getCaseImgList();
    }
  }

  async function handlerShowGeomtrys(currentNode, formData) {
    findValue(currentNode.authFields, 'component');
    let layer: string = chooseLayer.value;
    if (!layer) {
      createMessage.error('图斑未绑定图层服务！');
      return;
    }
    let geomfiledValue = geomfield.value;
    let gids = '';
    try {
      geomfiledValue = geomfiledValue.toLowerCase();
      gids = formData[geomfiledValue];
      console.log('gidssss', gids);
      // 根据ids获取图斑
      if (gids) {
        try {
          let getGeomPrams = {
            TableName: layer,
            FieldName: 'gid',
            FieldValue: gids?.split(','),
            page: 1,
            limit: 999,
            key: null,
          };
          getGeom(getGeomPrams).then((res) => {
            let geoms = [];
            if (res) {
              if (res.items?.length > 0) {
                res.items.forEach((item, index) => {
                  let geom = {
                    key: item.gid,
                    mapgeom: item.geometry,
                  };
                  geoms.push(geom);
                });
              }
              geomsList.value = geoms;
              // MapboxComponent.value.handlerDraw(status,mapgemoList.value, false);
              MapboxComponent.value.handlerDraw('Details', geoms, false);
            } else {
              geomsList.value = null;
              createMessage.error('当前数据没有图斑！');
            }
          });
        } catch (e) {
          createMessage.error('当前数据没有图斑！');
        }
      } else {
        createMessage.error('当前数据没有图斑！');
      }
    } catch {
      createMessage.error('获取图斑数据失败！');
    }
  }

  function onMapboxLoad() {}
  // 驳回到指定节点
  async function rejectHandleOk() {
    let res = await rejectFormRef.value
      .validate()
      .then(() => {
        return true;
      })
      .catch((error) => {
        return false;
      });
    if (res) {
      spinning.value = true;
      const data = await audit(props.taskId, {
        code: designerData.currentBtn.code,
        name: designerData.currentBtn.name,
        des: formData.value.des,
        NextId: reject.value.nextId,
      });
      spinning.value = false;
      if (data) {
        closePage();
        rejectOpen.value = false;
        btnVisble.value = false;
        return createMessage.success('成功');
      } else {
        btnVisble.value = true;
        return createMessage.error('失败');
      }
    }
  }

  // 图片预览
  const isShowImagePreview = ref<Boolean>(false);
  const closeImagePreview = () => {
    isShowImagePreview.value = false;
  };
  const globalImagePreviewUrl = ref<String>();
  const globalImagePreviewList = ref([]);

  const formFileStore = userFormFileStore();
  const formFileState = storeToRefs(formFileStore);

  watch(formFileState.url, (newValue, oldValue) => {
    const regex = /([^/\\]+)(?=\.[^/\\]*$|$)/;
    const match = newValue.match(regex);
    if (match) {
      MapboxComponent.value.handlerCurrentImageChange(match[1]);
    }

    // MapboxComponent.value.handlerCurrentImageChange(formFileState.url.value)
    // globalImagePreviewList.value = formFileState.urlList;
    // isShowImagePreview.value = true;
    // globalImagePreviewUrl.value = newValue;
  });

  onBeforeMount(() => {
    getTaskInfo();
    // 表单附件和图片组件 历史举证功能获取专题和ID 在进入审核时将数据放到session
    sessionStorage.setItem('SelectOtherId', props.processId);
    if (props.auditData && props.auditData.processcode) {
      sessionStorage.setItem('SelectOtherZhuantiCode', props.auditData.processcode);
    }
  });

  function onFormContainerMouseOver(event) {}
</script>
<style lang="less" scoped>
  :deep(.ant-spin-nested-loading) {
    height: 100%;
    .ant-spin-container {
      height: 100%;
    }
  }
  ::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: 0px;
    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;
      display: none;
    }
  }
  ::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 {
    visibility: visible;
    .ant-btn {
      margin: 0;
      margin-top: 8px;
      margin-right: 8px;
    }
  }
  .l-task-btns.btn-hidden {
    visibility: hidden;
  }

  ::v-deep .ant-modal-footer {
    display: none !important;
    height: 0px !important;
  }
  ::v-deep .ant-layout-footer {
    padding: 0px 20px !important;
    overflow: auto !important;
  }

  .form-container {
    float: left;
    width: 60%;
  }
  .maper-container {
    float: left;
    width: 40%;
    padding: 20px;
    height: 100%;
  }

  .l-from-body {
    padding: 10px 30px;
  }

  #process-form-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
    float: left;
    position: relative;
    ::deep(.ant-image-preview-root) {
      position: absolute;
    }
    :deep(.ant-image-preview-wrap) {
      position: absolute;
      .ant-image-preview {
        .ant-image-preview-content {
          .ant-image-preview-body {
            .ant-image-preview-switch-left {
              position: absolute;
            }
            .ant-image-preview-switch-right {
              position: absolute;
            }
          }
        }
      }
    }
    :deep(.ant-image-preview-mask) {
      position: absolute;
    }
    ::deep(.ant-image-preview-switch-left) {
      position: absolute;
    }

    :deep(.ant-image-preview-operations-wrapper) {
      height: 100%;
      position: absolute;
      .ant-image-preview-operations {
        position: absolute;
        top: 0;
        width: 100%;
        .ant-image-preview-operations-operation {
          // flex:1;
        }
      }
      .ant-image-preview-operations-operation:nth-last-child(1) {
        display: none;
      }
      .ant-image-preview-operations-operation:nth-last-child(2) {
        display: none;
      }
    }
  }
  #form-container {
    position: relative;
    height: 100%;
    :deep(.ant-image-preview-wrap) {
      position: absolute;
    }
    :deep(.ant-image-preview-mask) {
      position: absolute;
    }
    :deep(.ant-image-preview-switch-left) {
      position: absolute;
    }
    :deep(.ant-image-preview-switch-right) {
      position: absolute;
    }
    :deep(.ant-image-preview-operations-wrapper) {
      height: 100%;
      position: absolute;
      .ant-image-preview-operations {
        position: absolute;
        top: 0;
        width: 100%;
        .ant-image-preview-operations-operation {
          // flex:1;
        }
      }
      .ant-image-preview-operations-operation:nth-last-child(1) {
        display: none;
      }
      .ant-image-preview-operations-operation:nth-last-child(2) {
        display: none;
      }
    }
  }
</style>
