<template>
  <div class="approval-form">
    <div
      class="approval-form__content"
      :class="{ 'two-column-layout__content': currentShowDialogAlias }"
    >
      <el-row class="approval-form__top-row">
        <el-col :span="4">
          <i class="icon-task-back back-icon" @click="handleBack"></i>
          <span class="top-title">{{ $t('flowButton.ApprovalForm') }}</span>
        </el-col>
        <el-col :span="20" class="top-col">
          <el-button
            v-if="isShowCopyBtn"
            type="text"
            icon="el-icon-document-copy"
            @click="instanceCopy"
          >
            {{ $t('flowButton.Copy') }}
          </el-button>
          <el-button
            type="text"
            icon="icon-task-circulate"
            @click="handleCirculate"
          >
            {{ $t('flowButton.Circulate') }}
          </el-button>
          <el-button
            type="text"
            icon="icon-task-communicate"
            @click="handleCommunication"
          >
            {{ $t('flowButton.Communication') }}
          </el-button>
          <el-button type="text" icon="icon-task-follow" @click="handleFllow">
            {{ $t('flowButton.Tracking') }}
          </el-button>
          <el-button
            v-show="false"
            ref="printBtn"
            v-print="'#flow-form-container'"
            type="text"
            icon="icon-print"
          >
            {{ $t('flowButton.Print') }}
          </el-button>
          <el-button type="text" icon="icon-print" @click="showPrintDialog()">
            {{ $t('flowButton.Print') }}
          </el-button>
          <el-button
            v-show="false"
            ref="printBtn"
            v-print="'#flow-form-container'"
            type="text"
            icon="icon-print"
            @click="showPrintDialog"
          >
            {{ $t('flowButton.Print') }}
          </el-button>
          <el-button
            type="text"
            icon="icon-shenpiyuce"
            @click="showFigureDialog()"
          >
            <span class="predictButton">预测图</span>
          </el-button>
          <el-button
            type="text"
            icon="icon-task-flow-chart"
            @click="handleFlowChart"
          >
            {{ $t('flowButton.FlowChart') }}
          </el-button>
          <template v-if="!['circulate', 'delegate'].includes(from)">
            <el-button
              v-if="!taskId"
              type="text"
              icon="icon-task-reminders"
              @click="handleUrgent"
            >
              {{ $t('flowButton.Urgent') }}
            </el-button>
          </template>
          <el-button
            type="text"
            icon="icon-shujushitu1"
            @click="processInfoDialog"
          >
            {{ $t('flowButton.ProcessInfo') }}
          </el-button>
          <!-- <el-button
            v-if="!(approvalType == 'request' || approvalType == 'done')"
            type="text"
            icon="icon-task-deal-record"
            @click="previewProcessDialog"
          >
            流程预演
          </el-button> -->
        </el-col>
      </el-row>
      <flow-form
        ref="approvalFlowForm"
        :form="form"
        :data.sync="data"
        :inst-id="procInstId"
        :permission="permission"
        :is-dialog-model="isDialogModel"
        :record-data="recordData"
        :done-data-version="doneDataVersion"
        :node-options="nodeList"
        :current-select-node="currentSelectNode"
        :current-task-id="taskId"
        @getInstStatus="getInstStatus"
        @node-change="handleNodeChange"
        @updateHeaderData="updateHeaderData"
        @get-process-sponsor="getProcessSponsor"
      />
      <approval-button
        ref="approvalButton"
        :class="[
          currentShowDialogAlias ? 'hide-approval-btn' : 'show-approval-btn',
        ]"
        :node-type="nodeType"
        :form-key="formKey"
        :form-type="formType"
        :read-id="readId"
        :data.sync="data"
        :instance-status="instanceStatus"
        :process-inst-status="processInstStatus"
        :is-get-approval-button="Boolean(currentTaskId)"
        :before-click="handleBeforeClick"
        :dialog-before-click="(alias) => dialogClick('before', alias)"
        :dialog-after-click="(alias) => dialogClick('after', alias)"
        v-bind="$attrs"
        :opinion-field="opinionField"
        :append-opinion="appendOpinion"
        :current-node-info="currentNodeInfo"
        :node-id="nodeId"
        :proc-def-key="procDefKey"
        :approval-button-list="approvalButtonList"
        v-on="$listeners"
        @load-Data="loadData"
      ></approval-button>
    </div>
    <!-- 流程信息 -->
    <process-info
      :show.sync="isShowProcessInfo"
      :inst-id="procInstId"
      :is-get-approval-btn="Boolean(isGetApprovalBtn)"
      :is-show-urge-info="type != 'read' && !myReadType"
    ></process-info>

    <!-- 流程审批人和路径预演 -->
    <node-path
      ref="nodePath"
      :inst-id="procInstId"
      :node-id="nodeId"
      :form-data="data"
    />

    <!-- 催办记录 -->
    <urgent-record ref="urgentrecord" :inst-id="procInstId" />

    <!-- 处理记录 -->
    <process-record-dialog
      ref="processRecordDialog"
      :inst-id="procInstId"
      :task-id="taskId"
      :refer-opinion="referOpinion"
      :node-type="nodeType"
      :def-id="defId"
      :node-id="nodeId"
    />

    <!-- 催办 -->
    <task-urgent
      ref="taskUrgent"
      :def-id="defId"
      :subject="subject"
      :inst-id="procInstId"
    />
    <!-- 审批预测 -->
    <processForecast
      ref="processForecast"
      :inst-id="instId"
      :def-id="defId"
      :data="data"
      :node-id="nodeId"
      :header-data="headerData"
      :bpmn-inst-id="bpmnInstId"
    ></processForecast>
    <!-- 跟踪设置 -->
    <fllow-setting ref="fllowSetting" :def-id="defId" :inst-id="procInstId" />

    <!-- 沟通 -->
    <communication
      ref="communication"
      :def-id="defId"
      :inst-id="procInstId"
      :node-id="nodeId"
      :notice-id="noticeId"
      :is-get-approval-btn="Boolean(isGetApprovalBtn)"
      @submit-after="handleSubmitAfter"
    />

    <!-- 传阅 -->
    <circulate
      ref="circulate"
      :task-id="copyTaskId"
      :inst-id="procInstId"
      :node-id="nodeId"
      :notice-id="noticeId"
      :is-get-approval-btn="Boolean(isGetApprovalBtn)"
      @submit-after="handleSubmitAfter"
    />

    <!-- 流程图 -->
    <ht-flow-chart
      ref="flowChart"
      :inst-id="procInstId"
      :bpmn-inst-id="bpmnInstId"
    />

    <!-- 表单打印 -->
    <form-print
      v-if="form"
      ref="formPrint"
      :data="formPrintTemplateList"
      :form-data="data"
      :def-id="defId"
      :node-id="nodeId"
      :proc-inst-id="instId"
      :form-id="form.id"
      :refer-opinion="referOpinion"
      :node-type="nodeType"
      :task-id="taskId"
      :def-key="flowDefKey"
      :record-data="recordData"
      :form-key="formKey"
      :form="form"
      :instance-status="instanceStatus"
      @printCurForm="handleCurFormPrint"
      @loadTempalte="loadPrintTemplate"
    ></form-print>
  </div>
</template>

<script>
  import { mapActions, mapState, mapMutations } from 'vuex'

  import ApprovalButton from './components/ApprovalButton'

  import UrgentRecord from '@/views/matter/components/UrgentRecord'
  import ProcessRecordDialog from '@/components/flow/processRecordDialog'
  import Circulate from './components/Circulate'
  import TaskUrgent from './components/TaskUrgent'
  import FllowSetting from './components/FllowSetting'
  import Communication from './components/Communication'
  import FlowForm from './form/FlowForm.vue'
  import FormPrint from './print/FormPrint.vue'
  import processForecast from './processForecast/processForecast.vue'
  import NodePath from '@/components/flow/nodePath.vue'
  import ProcessInfo from '@/views/matter/components/ProcessInfo'

  import { getNotice, getFlowStatus, checkTaskAuth } from '@/api/flow'
  import {
    markTaskAsRead,
    getDoneByInstId,
    getDoneByInstIdAndAccount,
    setRead,
    getNoticeTodoReadById,
    getNodePrintTemplate,
  } from '@/api/process'
  import { getFormPrintList } from '@/api/form'

  import {
    processIsOver,
    getInstanceByInstId,
    getTaskDetailBo,
    getInstFormAndBO,
  } from '@/api/process'
  import { getFlowGlobalTemplate, getApprovalButtons } from '@/api/flow'
  import print from '@/assets/print'
  import { Base64 } from 'js-base64'

  export default {
    name: 'ApprovalForm',
    components: {
      ApprovalButton,
      UrgentRecord,
      ProcessRecordDialog,
      Circulate,
      TaskUrgent,
      FllowSetting,
      Communication,
      FlowForm,
      UrgentRecord,
      ProcessRecordDialog,
      TaskUrgent,
      FormPrint,
      NodePath,
      processForecast,
      ProcessInfo,
    },
    directives: {
      print,
    },
    provide() {
      return {
        headerData: this.headerData,
        nodeId: this.nodeId,
        data: this.data,
        instId: this.instId,
      }
    },
    props: {
      type: {
        type: String,
        default: '',
      },
      myReadType: Boolean,
      currentTaskId: {
        type: String,
        default: '',
      },
      currentInstId: {
        type: String,
        default: '',
      },
      currentLearderId: {
        type: String,
        default: '',
      },
    },
    data() {
      return {
        test: `同意qweqweq\r\n超级管理员 2021-10-11 19:11:57\n\n同意确认通过\n超级管理员 2021-10-11 19:13:43`,
        form: null,
        formKey: '',
        formType: '',
        data: null,
        permission: null,
        headerData: {
          id: '',
          creator: '',
          updateTime: '',
          procDefName: '',
          status: '',
          currentNode: '',
        },
        defId: '',
        execId: '',
        status: '',
        subject: '',
        bpmnInstId: '',
        instStatus: '',
        flowDefKey: '',
        copyTaskId: '',
        procInstId: '',

        // isOpen: false, //是否打开处理记录弹窗
        nodeId: '', //当前任务节点
        nodeType: '', //当前任务类型
        procDefKey: '', //流程名称

        jumpType: '',
        secretFree: '',
        referOpinion: true, //允许参考意见 (选择否，则审批时不允许参考同环节其他会签人员的意见)
        approvalArea: '', //审批区域显示的内容
        opinionField: '', //审批意见反填字段
        appendOpinion: false, //是否覆盖审批意见
        choiceExcutor: '',
        signatureField: '', //自动签章字段
        signatureCover: '', //自动签章是否覆盖

        showModifyRecord: false, // 是否显示表单修改记录
        processInstStatus: null, //流程实例状态
        instanceStatus: null, // 流程实例状态的信息
        printCurForm: false,
        formPrintTemplateList: [],
        isSkipStart: false, // 是否跳过第一个节点
        opinionMap: {},
        notice: null,
        dialogModeAutoApprovalTaskId: '', //弹窗模式自动获取下一条任务的任务id
        dialogModeAutoApprovalInstId: '', //弹窗模式自动获取下一条任务的实例id
        doneDataVersion: '',
        currentSelectNode: '', //当前选择节点
        nodeList: [], //审批节点
        currentNodeInfo: {},
        noticeId: this.$route.query.readId,
        isShowCopyBtn: false,
        isShowProcessInfo: false,
        showDialogAlias: '',
        approvalButtonList: [], //审批按钮
      }
    },
    computed: {
      ...mapState('process', ['bpmTask', 'curNodeDef']),
      ...mapState('user', ['userInfo']),
      ...mapState('matter', [
        'isFromApplicationModule',
        'currentShowDialogAlias',
      ]),
      ...mapState('routes', ['fullScreenState']),
      readId() {
        return this.$route.query.readId
      },
      dialogModeTaskId() {
        return this.dialogModeAutoApprovalTaskId || this.currentTaskId
      },
      dialogModeInstId() {
        return this.dialogModeAutoApprovalInstId || this.currentInstId
      },
      taskId() {
        return this.$route.query.taskId || this.dialogModeTaskId
      },
      instId() {
        return this.$route.query.instId || this.dialogModeInstId
      },
      leaderId() {
        return this.$route.query.leaderId || this.currentLearderId || 0
      },
      //来源
      from() {
        return this.$route.query.from
      },
      //是否获取审批按钮
      isGetApprovalBtn() {
        return this.$route.query.isGetApprovalBtn || this.currentTaskId
      },
      //是否是我的申请
      myApplication() {
        return this.$route.query.myApplication || false
      },
      //审批类型
      approvalType() {
        if (this.type) {
          return this.type
        } else if (this.$route.query && this.$route.query.type) {
          return this.$route.query.type
        }
        return ''
      },
      isDialogModel() {
        return this.currentTaskId ? true : false
      },
      isDialog() {
        // 是否弹框审批模式
        const isDialogModel = localStorage.getItem('isDialog')
        return (
          isDialogModel &&
          this.isDialogModel &&
          JSON.parse(isDialogModel) === true
        )
      },
      // 审批意见控件需要的参数处理记录参数
      recordData() {
        return {
          instId: this.instId,
          taskId: this.taskId,
          referOpinion: this.referOpinion,
          nodeType: this.nodeType,
          defId: this.defId,
          nodeId: this.nodeId,
          initFillData:
            this.notice &&
            this.notice.curNodeDef &&
            this.notice.curNodeDef.localProperties &&
            this.notice.curNodeDef.localProperties.initFillData,
        }
      },
      isUnRead() {
        return this.$route.query.isRead === '0'
      },
    },
    watch: {
      currentShowDialogAlias(val) {
        if (val) {
          if (val !== 'processInfo') {
            this.isShowProcessInfo = false
          }
        }
      },
    },
    created() {
      this.procInstId = this.instId
      this.copyTaskId = this.taskId
      this.initData()
      //发布一个加载数据的事件
      this.$baseEventBus.$on('approval-form-load-data', (data) => {
        if (data) {
          this.dialogModeAutoApprovalTaskId = data.taskId
          this.dialogModeAutoApprovalInstId = data.procInstId
        }
        this.initData()
      })
      this.setCurrentShowDialogAlias('')
    },
    methods: {
      ...mapMutations('matter', ['setCurrentShowDialogAlias']),
      ...mapActions({
        getApprovalButtonByTaskId: 'matter/getApprovalButtonByTaskId',
        getTaskIsLockStatus: 'matter/getTaskIsLockStatus',
        getFlowKey: 'process/getFlowKey',
        getTaskDetail: 'process/getTaskDetail',
      }),
      processInfoDialog() {
        this.showDialogAlias = 'processInfo'
        this.setCurrentShowDialogAlias('processInfo')
        this.isShowProcessInfo = true
      },
      previewProcessDialog() {
        this.$refs.nodePath.showNodePath(this.instId)
      },
      loadData() {
        this.initData()
      },
      async initData() {
        if (this.taskId) {
          if (!this.leaderId && !this.approvalType) {
            //验证当前用户是否有该任务处理权限
            const { value } = await checkTaskAuth(this.taskId)
            if (!value) {
              this.$message.warning('您没有执行该任务的权限！')
              this.$router.push(`/matter/myTask`)
              return
            }
          }
          const data = await getNotice(this.taskId).catch((err) => {
            window.location.href = '/front/matter/myTask'
          })
          this.notice = data
          this.procDefKey = this.notice.bpmTask.procDefKey
          this.getTaskDetail(data)
          this.handleTaskData(data)
          // 获取表单数据
          this.getTaskForm()
          this.markTaskAsReadByTaskId()
        } else {
          this.getNodePrintTemplateByInstIdAndNodeId()
          getInstanceByInstId(this.instId, (instData) => {
            this.handleInstData(instData)
          })
          // 获取实例表单
          this.getInstanceForm()
        }
        //获取审批按钮
        if (this.isGetApprovalBtn) {
          this.getApprovalButtonByTaskId()
          this.getTaskIsLockStatus({
            taskId: this.taskId,
            leaderId: this.leaderId,
          })
        }
        //获取flowKey根据procInstId
        this.getFlowKey({ procInstId: this.instId })
        this.getFlowStatusByInstIdAndTaskId()
        //标为已阅
        if (this.isUnRead) {
          setRead(this.readId).then((res) => {})
        }
      },
      getApprovalButtonByTaskId() {
        getApprovalButtons(
          {
            taskId: this.taskId,
            leaderId: this.leaderId,
          },
          (res) => {
            this.approvalButtonList = res?.buttons || []
          }
        )
      },

      handleTaskData(data) {
        const { bpmTask, curNodeDef } = data
        this.execId = bpmTask.execId
        this.status = bpmTask.status
        this.defId = bpmTask.procDefId
        this.subject = bpmTask.subject
        this.procInstId = bpmTask.procInstId
        this.bpmnInstId = bpmTask.bpmnInstId
        this.instStatus = bpmTask.instStatus
        this.flowDefKey = bpmTask.flowDefKey

        if (curNodeDef && curNodeDef.nodeProperties) {
          this.nodeId = curNodeDef.nodeId
          this.nodeType = curNodeDef.type
          const nodeProps =
            curNodeDef.nodeProperties[0] || curNodeDef.localProperties

          this.jumpType = nodeProps.jumpType
          this.secretFree = nodeProps.secretFree
          this.referOpinion = nodeProps.referOpinion
          this.opinionField = nodeProps.opinionField
          this.approvalArea = nodeProps.approvalArea
          this.appendOpinion = nodeProps.appendOpinion
          this.choiceExcutor = nodeProps.choiceExcutor
          this.signatureField = nodeProps.signatureField
          this.signatureCover = nodeProps.signatureCover
        }
      },
      handleInstData(data) {
        this.defId = data.procDefId
        this.subject = data.subject
        this.formKey = data.formKey
        this.bpmnInstId = data.bpmnInstId
        this.instStatus = data.instStatus
        this.approvalArea = 'processRecord'
        this.showModifyRecord = data.showModifyRecord
      },
      // 催办
      handleUrgent() {
        processIsOver(this.procInstId, (res) => {
          if (res.state) {
            this.$refs.taskUrgent.handleOpen()
          } else {
            this.$message.warning(res.message)
          }
        })
      },
      // 沟通
      handleCommunication() {
        this.showDialogAlias = 'communication'
        // this.setCurrentShowDialogAlias('communication')
        this.$refs.communication.handleOpen()
      },
      // 传阅
      handleCirculate() {
        this.showDialogAlias = 'circulate'
        // this.setCurrentShowDialogAlias('circulate')
        console.log('open')
        this.$refs.circulate.handleOpen()
      },
      // 跟踪设置
      handleFllow() {
        processIsOver(this.procInstId, (res) => {
          if (res.state) {
            this.$refs.fllowSetting.handleOpen()
          } else {
            this.$message.warning('流程已结束')
          }
        })
      },
      // 流程图
      handleFlowChart() {
        this.$refs.processForecast.handleOpen(
          this.instId,
          this.data,
          this.nodeId ? this.nodeId : this.headerData.nodeId,
          false,
          'flowChart'
        )
      },
      //处理记录信息
      processRecordDialog() {
        this.$refs.processRecordDialog.handleOpen() //父组件调用子组件方法
      },
      //催办记录
      urgentRecord() {
        this.$refs.urgentrecord.handleOpen() //父组件调用子组件方法
      },
      //预测图
      showFigureDialog() {
        this.$refs.processForecast.handleOpen(
          this.instId,
          this.data,
          this.nodeId ? this.nodeId : this.headerData.nodeId,
          false
        ) //父组件调用子组件方法
      },
      handleFormDetail(res) {
        if (res.state) {
          const { value } = res
          this.formKey = value?.form?.formKey
          this.formType = value?.form?.type
          this.form = value?.form
          this.data = value?.data
          this.permission =
            value && value.permission ? JSON.parse(value.permission) : null
          let diyJs = this.form?.diyJs
          diyJs && this.handlerJs(diyJs)
          this.$nextTick(() => {
            if (this.form.formCss) {
              let style = document.createElement('style')
              style.id = 'online-form-addStyle'
              style.type = 'text/css'
              style.innerHTML = `div[name='online-form'] ${this.form.formCss}`
              document.head.appendChild(style)
            }
          })
        }
      },
      handlerJs(diyJs) {
        this.$nextTick(() => {
          const userInfo = this.userInfo
          const currentUser = userInfo?.user
          let data = this.data
          let _this = this
          const $ = require('jquery')
          eval(diyJs)
        })
      },
      //获取任务详情
      getTaskForm() {
        getTaskDetailBo({
          taskId: this.taskId,
          leaderId: this.leaderId,
          reqParams: '',
          isDefAuthorize: this.$route.query.isDefAuthorize || '',
        }).then(
          (res) => this.handleFormDetail(res),
          (e) => {
            const { data } = e.response
            if (data && data.errorCode && data.errorCode == '5034') {
              this.$router.push(`/matter/myTask`)
            }
          }
        )
      },
      // 获取实例表单
      getInstanceForm() {
        const params = {
          querys: [
            {
              property: 'wfInst.id_',
              value: this.instId,
              group: 'typeId',
              operation: 'IN',
              relation: 'AND',
            },
          ],
        }
        if (this.from == 'received') {
          //当收到传阅时，需要增加传阅人参数，后端不能取当前用户
          getNoticeTodoReadById(this.readId).then((res) => {
            getDoneByInstIdAndAccount(params, res.ownerId).then((res) => {
              if (res.rows && res.rows.length > 0) {
                this.nodeList = res.rows.filter(
                  (item) => item.nodeType && item.nodeType !== 'END'
                )
              }
              this.getFormDataByInstId(res.rows)
            })
          })
        } else {
          getDoneByInstId(params).then((res) => {
            if (res.rows && res.rows.length > 0) {
              this.nodeList = res.rows.filter(
                (item) => item.nodeType && item.nodeType !== 'END'
              )
            }
            this.getFormDataByInstId(res.rows)
          })
        }
      },
      getFormDataByInstId(data) {
        if (data && data.length === 1 && data[0].opinionStatus === 'start') {
          this.isSkipStart = true
        }
        this.setOpinionMap(data)

        this.nodeId = this.$route.query.nodeId
        if (
          this.nodeId &&
          (this.from == 'received' || this.from == 'circulate') &&
          this.nodeList &&
          this.nodeList.length > 0
        ) {
          //传阅事项-我收到的 和我传阅的
          this.currentSelectNode = this.nodeId
          this.currentNodeInfo = this.nodeList.find(
            (item) => item.taskKey === this.nodeId
          )
        } else if (this.nodeList && this.nodeList.length > 0) {
          this.currentSelectNode = this.nodeList[0].taskKey
          this.currentNodeInfo = this.nodeList[0]
        } else if (data && data.length > 0) {
          this.currentSelectNode = data[0].taskKey
          this.currentNodeInfo = data[0]
        }
        this.getFormByNodeIdAndInstId()
      },
      getFormByNodeIdAndInstId() {
        getInstFormAndBO({
          instId: this.instId,
          getStartForm: this.isSkipStart,
          includData: true,
          myApplication: this.myApplication,
          nodeId: this.nodeId || this.currentSelectNode,
          isDefAuthorize: this.$route.query.isDefAuthorize || '',
        }).then((res) => {
          this.doneDataVersion = res.value.doneDataVersion
          if (this.myApplication) {
            //我的申请处理
            this.nodeId = res.value.form.nodeId
            this.currentSelectNode = res.value.form.nodeId
          }
          if (res.value.doneDataVersion === 'history') {
            const findCurrentForm = this.nodeList.find(
              (item) => item.taskKey === this.currentSelectNode
            )
            if (findCurrentForm && findCurrentForm.formData) {
              res.value.data = JSON.parse(
                Base64.decode(findCurrentForm.formData)
              )
            }
          }
          this.handleFormDetail(res)
        })
      },
      setOpinionMap(data) {
        data.forEach((item) => {
          const opinionStatusList = [
            'signRecoverCancel',
            'retracted',
            'start',
            'end',
            'awaiting_feedback',
            'copyto',
            'end_revoke',
            'start_commu',
            'awaiting_check',
            'copyto_reply',
            '',
          ]
          if (
            !opinionStatusList.includes(item.opinionStatus) &&
            this.opinionMap[item.taskKey]
          ) {
            if (item.opinionStatus === 'skip' && item.skipType !== 'first')
              return true
            if (item.formData) {
              item.formData = JSON.parse(Base64.decode(item.formData))
            }
            this.opinionMap[item.taskKey] = item
          }
        })
      },
      handleBeforeClick(alias) {
        // 启动流程前校验表单
        return this.$refs.approvalFlowForm
          .getData(true, alias ? alias + '-before' : '')
          .then(() => {
            return true
          })
          .catch(() => {
            return false
          })
      },
      dialogClick(type, alias) {
        if (this.form.type === 'FRAME') {
          const frm = document.querySelectorAll("[name='flowFrameForm']")[0]
          const frmControl = document.querySelectorAll("[name='iframeControl']")
          if (!frm && !frmControl) {
            this.$message.error('当前URL表单加载不正确。')
            return
          }
          const aliasSuffix = type === 'after' ? '-after' : '-submission'
          // 发送保存数据成功的的消息
          frm.contentWindow.postMessage(
            {
              messageName: 'saveData',
              alias: alias ? alias + aliasSuffix : '',
            },
            '*'
          )
        }
        // if (type === 'after') {
        //   // 客户场景，弹窗里用 iframe 嵌套表单审批页面，需求是 表单页处理完后需要通知进行 关闭弹窗
        //   window.parent && window.parent.postMessage('close', '*')
        // }
        return true
      },
      //进入审批页面时通过实例id和任务id获取流程状态
      getFlowStatusByInstIdAndTaskId() {
        const query = {
          instId: this.instId,
          taskId: this.taskId,
        }
        getFlowStatus(query, (res) => {
          this.processInstStatus = res
        })
      },
      handleSubmitAfter() {
        this.initData()
      },
      markTaskAsReadByTaskId() {
        markTaskAsRead(this.taskId)
      },
      handleBack() {
        if (this.isDialog) {
          this.$emit('close-dialog')
        } else {
          if (this.isFromApplicationModule || this.fullScreenState) {
            this.$router.go(-1)
          } else {
            this.$tabs.replace()
          }
        }
      },
      // 流程复制
      instanceCopy() {
        const this_ = this
        const { instId, defId } = this
        this.$confirm('使用当前数据发起新流程？', '提示')
          .then(() => {
            this_.$router.push(
              `/matter/startProcess?defId=${defId}&copyInstId=${instId}`
            )
          })
          .catch(() => {})
      },
      getInstStatus(data) {
        this.instanceStatus = data
      },
      showPrintDialog() {
        this.$refs['formPrint'].showDialog()
        // if (!this.formKey) {
        //   this.$watch('formKey', (newVal) => {
        //     newVal && this.$refs['formPrint'].showDialog()
        //   })
        // } else {
        //   this.$refs['formPrint'].showDialog()
        // }
      },
      loadPrintTemplate(params, cb) {
        const this_ = this
        let futures = [
          this.getFormPrintListByFormKey(),
          this.resolveNodePrintTemplate(),
          this.getFlowGlobalTemplate(),
        ]
        Promise.all(futures).then((resps) => {
          let rows = []
          resps.forEach((item) => {
            rows = rows.concat(item || [])
          })
          //去重
          const map = new Map()
          const rowsSet = rows.filter(
            (item) =>
              !item.fileId || (!map.has(item.fileId) && map.set(item.fileId, 1))
          )
          this_.$set(this_, 'formPrintTemplateList', rowsSet)
          cb && cb(!!rowsSet.length)
        })
      },
      getFlowGlobalTemplate() {
        return new Promise((resolve) => {
          getFlowGlobalTemplate(this.defId).then((resp) => {
            const templates = resp.value || []
            if (!templates.length) {
              resolve(templates)
            } else {
              let result = []
              templates.forEach((template) => {
                if (template.fileJson && template.fileJson != []) {
                  const file = JSON.parse(template.fileJson)[0]
                  let fileName = file.name
                  let extName =
                    fileName.split('.')[fileName.split('.').length - 1]
                  let printType = ''
                  if (extName == 'docx' || extName == 'doc') {
                    printType = 'word'
                  } else if (extName == 'xlsx' || extName == 'xls') {
                    printType = 'excel'
                  }
                  result.push({
                    fileId: file.id,
                    fileName: template.name,
                    name: template.desc,
                    printType,
                    createTime: template.createTime,
                    allowDownload: template.allowDownload,
                    allowPreview: template.allowPreview,
                    scriptStr: template.scriptStr,
                    templateId: template.id,
                  })
                }
              })
              resolve(result)
            }
          })
        })
      },
      getFormPrintListByFormKey() {
        const pageBean = {
          page: 1,
          pageSize: -1,
        }
        const param = {
          pageBean,
          querys: [
            {
              group: 'defaultQueryGroup',
              operation: 'EQUAL',
              relation: 'AND',
              property: 'formKey',
              value: this.formKey,
            },
          ],
        }
        return new Promise((resolve) => {
          getFormPrintList(param).then((resp) => {
            if (resp && resp.rows) {
              resolve(resp.rows)
            } else {
              resolve(new Array())
            }
          })
        })
      },
      resolveNodePrintTemplate() {
        return new Promise((resolve) => {
          if (
            this.curNodeDef &&
            this.curNodeDef.localProperties &&
            this.curNodeDef.localProperties.printTemplate
          ) {
            const printTemplate = JSON.parse(
              Base64.decode(this.curNodeDef.localProperties.printTemplate)
            )
            printTemplate.forEach((item) => {
              item['fileName'] = item['name']
            })
            resolve(printTemplate)
          } else {
            resolve([])
          }
        })
      },
      handleCurFormPrint() {
        this.$refs['printBtn'].$el.click()
      },
      handleNodeChange(key) {
        this.currentSelectNode = key
        this.nodeId = key
        this.currentNodeInfo =
          this.nodeList.find((item) => item.taskKey === key) || {}
        this.getFormByNodeIdAndInstId()
      },
      // 更新表单头部信息
      updateHeaderData(data) {
        this.headerData = data
      },
      getProcessSponsor(account) {
        this.isShowCopyBtn = account === this.userInfo.user.account
      },
      getNodePrintTemplateByInstIdAndNodeId() {
        const query = {
          instId: this.instId,
          nodeId: this.nodeId || this.$route.query.nodeId,
        }
        getNodePrintTemplate(query).then((res) => {
          if (res.state) {
            this.curNodeDef.localProperties =
              res.value && res.value.localProperties
          }
        })
      },
    },
    beforeDestroy() {
      if (
        document.getElementById('online-form-addStyle') &&
        document.getElementsByTagName('head') &&
        document.getElementsByTagName('head').item
      ) {
        document
          .getElementsByTagName('head')
          .item(0)
          .removeChild(document.getElementById('online-form-addStyle'))
      }
    },
  }
</script>

<style lang="scss" scoped>
  $top-btn-height: 48px;
  $top-btn-bg: #e6e6e6;
  $bottom-btn-height: 80px;
  .approval-form {
    // border: 1px solid $base-border-color;
    // border-radius: 2px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    height: 100%;
    overflow: hidden;
    // margin-bottom: $base-margin;
    background: $base-color-white;
    .approval-form__content {
      height: 100%;
      display: flex;
      flex-direction: column;
      .form-container {
        height: calc(100% - #{$top-btn-height} - #{$bottom-btn-height});
        overflow: auto;
        width: 100%;
        transition: width 0.5s;
      }
      .approval-buttons {
        display: flex;
        justify-content: center;
        height: $bottom-btn-height;
        line-height: $bottom-btn-height;
        box-shadow: 0px -2px 6px rgba(149, 149, 149, 0.16);
        position: fixed;
        z-index: 9;
        bottom: $base-content-margin;
        background: $base-color-white;
        width: calc(
          100% - #{$base-left-menu-width} - #{$base-content-margin}* 2
        );
      }
      .app-model {
        width: 100%;
        bottom: 0;
      }
    }
    .two-column-layout__content {
      .form-container {
        height: calc(100% - #{$top-btn-height});
        width: calc(100% - 380px);
      }
    }
    .approval-form__top-row {
      background: $base-color-white;
      height: $top-btn-height;
      line-height: $top-btn-height;
      padding: 0 32px;
      border-bottom: 1px solid $top-btn-bg;
      .top-col {
        margin-top: 8px;
        display: flex;
        justify-content: flex-end;
        ::v-deep {
          .el-button {
            font-size: 14px;
            padding-right: 14px;
            &:last-child {
              padding-right: 0;
            }
          }
          .el-button [class*='icon-'] + span {
            margin-left: 0;
          }
        }
      }
      .back-icon {
        color: var(--themeColor);
        cursor: pointer;
      }
      .top-title {
        font-size: $base-font-size-big;
        font-weight: bold;
        color: $base-dark-title-color;
        padding-left: 6px;
      }
    }
  }
  .horizontal-container {
    .approval-form {
      .approval-buttons {
        width: 92%;
        bottom: 0;
      }
    }
  }
  .is-collapse-main {
    .approval-form {
      .approval-buttons {
        width: calc(
          100% - #{$base-left-menu-width-min} - #{$base-content-margin}* 2
        );
      }
    }
  }
  .mobile {
    .is-collapse-main {
      .approval-form {
        .approval-buttons {
          width: calc(100% - #{$base-content-margin}* 2);
        }
      }
    }
  }
  .predictButton {
    line-height: 16px;
    height: 16px;
    margin-left: 3px;
  }
  .hide-approval-btn {
    animation: fadeOut 1s ease-in-out forwards;
  }
  .show-approval-btn {
    animation: fadeIn 0.3s ease-in-out forwards;
  }
  @keyframes fadeOut {
    0% {
      opacity: 1;
      transform: translateY(0);
    }
    100% {
      opacity: 0;
      transform: translateY(80px);
    }
  }

  @keyframes fadeIn {
    0% {
      opacity: 0;
      transform: translateY(80px);
    }
    100% {
      opacity: 1;
      transform: translateY(0);
    }
  }
  @media (max-width: 1360px) {
    .approval-form .two-column-layout__content .form-container {
      ::v-deep {
        .form-content {
          width: 730px;
          .status-wrap {
            margin-right: 16px;
          }
        }
      }
    }
  }
</style>
