<template>
  <div class="start-process">
    <flow-form
      ref="startProcessForm"
      :key="defId"
      :form="form"
      :data.sync="data"
      :def-id="defId"
      :permission="permission"
      :record-data="recordData"
      @formTypeChange="handleFormTypeChange"
      :businessKey="businessKey"
      :flowObject.sync="flowObject"
    />
    <!-- 底部操作按钮 -->
    <start-button-group
      class="bottom-btn"
      :class="{ 'app-model-start': isFromApplicationModule }"
      :start-button-list="startButtonList"
      :approval-form-data="data"
      :data="data"
      :before-click="handleBeforeClick"
      :main-def-id="mainDefId"
      :form-type="formType"
      :formKey="form && form.formKey ? form.formKey : ''"
      :flowObject="flowObject"
    />
  </div>
</template>

<script>
  import { mapActions, mapState } from 'vuex'
  import StartButtonGroup from './newMatter/StartButtonGroup'
  import {
    getProcessFormAndBo,
    getMainByDefIdOrKey,
    checkStartRight,
  } from '@/api/process'
  import FlowForm from './form/FlowForm.vue'
  const { Base64 } = require('js-base64')

  export default {
    name: 'StartProcess',
    components: {
      StartButtonGroup,
      FlowForm,
    },
    provide() {
      return {
        headerData: {},
        nodeId: '',
        data: this.data,
        instId: this.proInstId,
      }
    },
    data() {
      return {
        flowObject: {},
        startButtonList: [],
        form: null,
        formType: null,
        data: null,
        permission: null,
        mainDefId: '',
      }
    },
    computed: {
      ...mapState('user', ['userInfo']),
      ...mapState('matter', ['isFromApplicationModule']),
      defId() {
        return this.$route.query.defId || this.mainDefId
      },
      businessKey() {
        return this.$route.query.businessKey
      },
      proInstId() {
        return this.$route.query.instId
      },
      copyInstId() {
        return this.$route.query.copyInstId
      },
      recordData() {
        return {
          defId: this.defId,
        }
      },
      userId() {
        return this.userInfo?.user?.userId
      },
    },
    watch: {
      defId: {
        handler(val) {
          if (!this.defId && this.$route.query.flowKey) {
            getMainByDefIdOrKey('', this.$route.query.flowKey).then((resp) => {
              this.mainDefId = resp['defId']
            })
          }
          this.initData()
        },
        immediate: true,
      },
    },
    methods: {
      ...mapActions('process', ['getFlowKey']),
      ...mapState('routes', ['fullScreenState']),
      handleFormTypeChange(type) {
        this.formType = type
      },
      initData() {
        if (!this.defId) {
          return
        }
        const { leaderId } = this.$route.query
        // 判断发起权限
        checkStartRight(this.userId, this.defId, leaderId || '').then(
          (response) => {
            if (response.state) {
              if (response.value) {
                this.getFormAndBoData()
                this.getFlowKey({ defId: this.defId })
              } else {
                this.$message({
                  type: 'error',
                  message: '您没有该流程的发起权限',
                  duration: 1500,
                  onClose: () => {
                    if (
                      this.fullScreenState &&
                      typeof this.fullScreenState !== 'function'
                    ) {
                      this.$router.go(-1)
                    } else {
                      this.$tabs.close()
                    }
                  },
                })
              }
            } else {
              this.$message.error(
                response.message ? response.message : '判断流程发起权限时出错'
              )
            }
          }
        )
      },
      handlerJs(diyJs) {
        this.$nextTick(() => {
          const userInfo = this.userInfo
          const currentUser = userInfo?.user
          let data = this.data
          let _this = this
          const $ = require('jquery')
          eval(diyJs)
        })
      },
      //流程启动时获取bo和表单
      getFormAndBoData() {
        let params = {}
        if (this.proInstId) {
          // 我的草稿进入发起页面
          params = { defId: this.defId, proInstId: this.proInstId }
        } else if (this.copyInstId) {
          // 流程复制进入发起页面
          params = { defId: this.defId, copyInstId: this.copyInstId }
        } else {
          // 常规发起
          params = { defId: this.defId }
        }
        getProcessFormAndBo(params).then((res) => {
          if (res.resultMsg === 'formEmpty') {
            this.$message.warning('该流程尚未配置表单')
          }
          this.startButtonList = res?.buttons
          this.form = res?.form

          this.data = res?.data
          //复制流程时，需要把版本号去掉
          if (this.copyInstId) {
            Object.keys(this.data).forEach((key) => {
              delete this.data[key].form_data_rev_
            })
          }
          this.permission =
            res && res.permission ? JSON.parse(res.permission) : null

          this.getParametersData()
          //处理表单的js脚本
          res.form && res.form.diyJs && this.handlerJs(res.form.diyJs)
          this.$nextTick(() => {
            if (res.form.formCss) {
              let style = document.createElement('style')
              style.id = 'online-form-addStyle'
              style.type = 'text/css'
              style.innerHTML = `div[name='online-form'] ${res.form.formCss}`
              document.head.appendChild(style)
            }
          })
        })
      },
      getParametersData() {
        if (this.$route.query.data) {
          let param = JSON.parse(Base64.decode(this.$route.query.data))

          Object.keys(this.data).forEach((boDefAlias) => {
            for (let key in param) {
              this.data[boDefAlias][key] = param[key]
            }
          })
        }
      },
      handleBeforeClick(alias) {
        // 启动流程前校验表单
        if (alias == 'startFlow' || alias == 'saveDraft') {
          return this.$refs.startProcessForm
            .getData(true)
            .then(() => {
              return true
            })
            .catch(() => {
              return false
            })
        }
        return true
      },
    },
    beforeDestroy() {
      if (
        document.getElementById('online-form-addStyle') &&
        document.getElementsByTagName('head') &&
        document.getElementsByTagName('head').item(0)
      ) {
        document
          .getElementsByTagName('head')
          .item(0)
          .removeChild(document.getElementById('online-form-addStyle'))
      }
    },
  }
</script>
<style lang="scss" scoped>
  .start-process {
    border: 1px solid $base-border-color;
    border-radius: 2px;
    height: 100%;
    background: $base-color-white;
    box-sizing: border-box;
    min-height: calc(100vh - 60px - 48px - 24px * 2) !important;
    .form-container {
      height: calc(100% - 80px);
      padding-bottom: 0;
      overflow: auto;
      -ms-overflow-style: none;
      overflow: -moz-scrollbars-none;
    }
    ::-webkit-scrollbar {
      width: 0;
      background-color: transparent;
    }
    .bottom-btn {
      // border-top: 1px solid $base-border-color;
      height: 80px;
      line-height: 80px;
      text-align: center;
      box-shadow: 0px -2px 6px rgba(149, 149, 149, 0.16);
      position: flex;
      bottom: $base-content-margin;
      width: 100%;
    }
    .app-model-start {
      width: 100%;
      bottom: 0;
    }
  }
  .horizontal-container {
    .start-process {
      .bottom-btn {
        width: 92%;
        background: var(--background);
        bottom: 0;
      }
    }
  }
  .is-collapse-main {
    .start-process {
      .bottom-btn {
        width: calc(
          100% - #{$base-left-menu-width-min} - #{$base-content-margin}* 2
        );
      }
    }
  }
  .mobile {
    .is-collapse-main {
      .start-process {
        .bottom-btn {
          width: calc(100% - #{$base-content-margin}* 2);
        }
      }
    }
  }
  .el-textarea__inner {
    &::-webkit-scrollbar {
      width: 13px !important;
      background-color: transparent;
    }
  }
</style>
