<template>
  <div v-if="show">
    <vue-bpmn @save="btnSave" :defKey="defKey" :modelData="modelData" :processStatus="processStatus" :operateType="operateType"
      :key="new Date().getTime()" />
  </div>
</template>
<script>
import { Message } from 'element-ui'
import VueBpmn from '@/components/VueBpmn'

  export default {
    name: 'FlowableModelEdit',
    components: {VueBpmn},
    props: {
      defId: String,
      defKey: String,
      operateType:String,
      processStatus: String,
      designPattern: String,
      flowData: Object
    },
    data() {
      return {
        id: '',
        modelData: {
          id: '',
          defId: '',
          bpmnXml: '',
          defKey: '',
          key: '',
          name: '',
          typeId: '',
          typeName: '',
          desc: '',
          designer: 'BPMNJS',
          designPattern: 'normal',
        },
        show: false,
        designPattern: this.designPattern,
      }
    },
    created() {
      this.getModelData()
    },
    methods: {
      getModelData() {
        if (this.defId) {
          this.$http
            .get('${bpmModel}/flow/def/v1/webDefDesign?defId=' + this.defId)
            .then(({data}) => {
              this.modelData = data
              this.modelData.id = data.defId
              this.modelData.defId = data.defId
              this.modelData.designer = 'BPMNJS'
              this.modelData.bpmnXml = this.replace2BpmnDefinitions(data.bpmnXml)
              this.modelData.key = data.defKey
              this.modelData.category = data.typeId
              this.modelData.designPattern = data.designPattern || 'normal'
              this.show = true
            })
        } else {
          if (this.flowData) {
            this.modelData.typeId = this.flowData.categoryId
            this.modelData.typeName = this.flowData.categoryName
            this.modelData.name = this.flowData.name
            this.modelData.desc = this.flowData.desc
            this.modelData.defKey = this.flowData.alias
            this.modelData.key = this.flowData.alias
          }
          this.show = true
        }
      },
      replace2BpmnDefinitions(xml) {
        var reg = new RegExp(/ext:definitions/, 'g')
        xml = xml.replace(reg, 'bpmn:definitions')
        return xml
      },
      btnSave(params,cb) {
        const xmlStr = params.defaultBpmDefinition.bpmnXml
        const myregexp = /\s{1}id="(.*?)"\s{1}/g
        let result = [],
          match = null
        // 通过正则提取流程xml中的id
        while ((match = myregexp.exec(xmlStr))) {
          if (match[1]) {
            result.push(match[1])
          }
        }
        result = result.sort()
        const errorIdAry = []
        for (var i = 0; i < result.length; i++) {
          // 判断id是否重复
          if (result[i] == result[i + 1]) {
            errorIdAry.push(result[i])
          }
        }
        if (errorIdAry.length > 0) {
          this.$message({
            message: `以下节点ID：【${errorIdAry.join(
              ','
            )}】重复（流程key和节点ID也不能重复），无法发布该流程。`,
            type: 'error',
          })
          return
        }
        //保存时，删除defaultBpmDefinition中的多余的key属性
        if(params.defaultBpmDefinition.hasOwnProperty('key')){
          this.$delete(params.defaultBpmDefinition,'key')
        }
        let dataParam = _.cloneDeep(params)
        delete dataParam.defaultBpmDefinition.modelId
        this.$http
          .post('${bpmModel}/flow/def/v1/webDefSave', dataParam)
          .then((msg, data) => {
            if (msg.data.state) {
              Message.success(params.isdeploy ? '发布成功' : '保存成功')
              cb()
              this.modelData.defId = msg.data.value
              setTimeout(() => {
                this.receiveMsg(params.isdeploy)
              }, 2000)
            }
          })
      },
      receiveMsg(param) {
        let type = ''
        if (['true',true].includes(param)) {
          type = 'flowDesignPublishSuccess'
        }
        if (['false',false].includes(param)) {
          type = 'flowDesignSaveSuccess'
        }
        switch (type) {
          case 'flowDesignFullscreen':
            this.toggle()
            break
          case 'flowDesignPublishSuccess':
            this.$emit('def-deploy-success', this.modelData.defId)
            break
          case 'flowDesignSaveSuccess':
            this.$emit('switch-config-refresh')
            break
        }
      },
      toggle() {
        if (!screenfull.isEnabled) {
          this.$message({
            message: '不支持全屏',
            type: 'warning',
          })
          return false
        }
        screenfull.toggle(this.$el)
        this.fullscreen = !this.fullscreen
      },
    }
  }
</script>
