<template>
  <div class="containers" ref="content" v-loading="vLoading">
    <div class="topButtonGroup">
      <div class="head-left">流程建模</div>
      <div class="head-right">
        <el-button
          type="primary"
          size="mini"
          @click="save()"
          ref="save"
          :disabled="saveObj.appId == null || buttonDisabled"
        >
          保存
        </el-button>
        <!-- <a ref="saveSvg" href="javascript:" class="el-button el-button--primary el-button--mini is-disabled" title="download as SVG image">SVG image</a> -->
        <!-- <a ref="saveDiagram" class="el-button el-button--primary el-button--mini is-disabled"
          href="javascript:"  style="text-decoration: none;"
          title="导出" >导出</a> -->
        <!--<el-button type="primary" size="mini"  @click="release()" :disabled="saveObj.appId==null||buttonDisabledByProDefId">发布</el-button>-->
        <el-button
          type="primary"
          size="mini"
          @click="_export()"
          :disabled="buttonDisabledByProDefId"
        >
          导出
        </el-button>
        <el-button
          size="mini"
          @click="_VVersion()"
          :disabled="buttonDisabledByProDefId"
        >
          查看版本
        </el-button>
        <el-button size="mini" @click="_chooseFlow()">选择流程</el-button>
      </div>
    </div>
    <div class="canvas" ref="canvas"></div>
    <div id="js-properties-panel" class="panel"></div>
    <el-dialog
      :title="store.state.dialogVisible.title"
      :visible.sync="store.state.dialogVisible.show"
      width="80%"
      top="3vh"
      class="el-dialog-lcpz"
      v-if="store.state.dialogVisible.show"
    >
      <div class="dialog-content" style="height: 600px;">
        <iframe
          :src="store.state.dialogVisible.dialogIfromeSrc"
          frameborder="0"
          width="100%"
          height="100%"
        ></iframe>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// 引入相关的依赖
// import BpmnViewer from 'bpmn-js'
//import BpmnModeler from 'bpmn-js/lib/Modeler'
import BpmnModeler from '../../public/js/bpmn-js/lib/Modeler'
//import propertiesPanelModule1 from 'bpmn-js-properties-panel'
import propertiesPanelModule from '../../bpmn-js/propertiesPanel'
//import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda'
//import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda'
import customTranslate from '../../bpmn-js/customTranslate/customTranslate'
import propertiesProviderModule from '../../bpmn-js/provider/magic'
//import magicModdleDescriptor from '../../bpmn-js/descriptors/magic.json';
//import CustomModeler from '../custom-modeler';
import colors from '../../bpmn-js/colors'

export default {
  data() {
    return {
      // bpmn建模器
      bpmnModeler: null,
      container: null,
      canvas: null,
      //bpmn图表数据
      xmlStr: null,
      processName: '',
      saveObj: {
        //svgXml:null,
        flow_xml: null,
        name: null,
        key: null,
        appId: 'DEMO_SYS',
      },
      buttonDisabled: true,
      bpmnXmlStr: '',
      procDefId: '',
      dialogVisible: false,
      dialogIfromeSrc: '',
      buttonDisabledByProDefId: true,
      vLoading: false,
    }
  },
  created() {
    // 设置接收消息方法
    window.addEventListener('message', this.handleMessage)
    this.saveObj.appId = 'DEMO_SYS'
    //this.getUrlKey('appId');
    // = 'common-service'
    if (
      this.getUrlKey('procDefKey') === '' ||
      this.getUrlKey('procDefKey') === 'undefined' ||
      this.getUrlKey('procDefKey') === null
    ) {
      this.saveObj.key = this.getUrlKey('key')
    } else {
      this.saveObj.key = this.getUrlKey('procDefKey')
    }
    //this.saveObj.key = this.getUrlKey('key')
    // 'testFlow004_devpf'
    this.store.state.dialogVisible.appId = this.getUrlKey('appId')
    // this.getUrlKey('appId')
    this.saveObj.name = this.getUrlKey('formName')
    // this.getUrlKey('formName')
    this.store.state.dialogVisible.formId = this.getUrlKey('formId')
    // this.getUrlKey('formId')
    // "1567501907497gdd7C8bJm0ujImCDuul5dg307"
    this.store.state.dialogVisible.formCode = this.getUrlKey('key')
    // this.getUrlKey('key')
    this.store.state.dialogVisible.modelId = this.getUrlKey('modelId')
    // this.getUrlKey('modelId')
    // e2df599a-7a61-484e-80a2-5916561c2916
    if (
      this.getUrlKey('procDefKey') === '' ||
      this.getUrlKey('procDefKey') === 'undefined'
    ) {
      this.store.state.dialogVisible.procDefKey = this.getUrlKey('key')
    } else {
      this.store.state.dialogVisible.procDefKey = this.getUrlKey('procDefKey')
    }

    // console.log('22222222'+this.store.state.dialogVisible.procDefKey)
    let processId =
      this.saveObj.key == null
        ? 'Process_' + this.randomString(8)
        : this.saveObj.key
    this.bpmnXmlStr =
      '<?xml version="1.0" encoding="UTF-8"?>\n' +
      '<definitions xmlns="http://www.omg.org/spec/BPMN/20100524/MODEL" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:bpmndi="http://www.omg.org/spec/BPMN/20100524/DI" xmlns:omgdc="http://www.omg.org/spec/DD/20100524/DC" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:activiti="http://activiti.org/bpmn" targetNamespace="http://www.activiti.org/test">\n' +
      '  <process id="' +
      processId +
      '" name="' +
      this.saveObj.name +
      '" isExecutable="true">\n' +
      '    <startEvent id="sid-46588EAA-38B7-4FBC-80DD-46A5EFE26CFA" />\n' +
      '  </process>\n' +
      '  <bpmndi:BPMNDiagram id="BPMNDiagram_demo_zdhta6966633366">\n' +
      '    <bpmndi:BPMNPlane id="BPMNPlane_demo_zdhta6966633366" bpmnElement="demo_zdhta6966633366">\n' +
      '      <bpmndi:BPMNShape id="BPMNShape_sid-46588EAA-38B7-4FBC-80DD-46A5EFE26CFA" bpmnElement="sid-46588EAA-38B7-4FBC-80DD-46A5EFE26CFA">\n' +
      '        <omgdc:Bounds x="298" y="101" width="30" height="30" />\n' +
      '      </bpmndi:BPMNShape>\n' +
      '    </bpmndi:BPMNPlane>\n' +
      '  </bpmndi:BPMNDiagram>\n' +
      '</definitions>'
  },
  methods: {
    createNewDiagram() {
      // 将字符串转换成图显示出来
      //console.log(this.bpmnXmlStr)
      this.bpmnModeler.importXML(this.bpmnXmlStr, function (err) {
        if (err) {
          console.error(err)
        }
      })
    },
    getUrlKey: function (name) {
      return (
        decodeURIComponent(
          (new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(
            location.href,
          ) || ['', ''])[1].replace(/\+/g, '%20'),
        ) || null
      )
    },
    //导出
    _export() {
      let url =
        this.$get_bpmn_manage_url() +
        '/procDefMgr/exportProcessAllFile.do?resourceType=xml&procDefIds=' +
        this.procDefId +
        '&exportall=1'
      window.open(url)
      //console.log('http://222.244.147.65:8089/ebpm-process-manage/procDefMgr/exportProcessAllFile.do?resourceType=xml&procDefIds='+this.procDefId+'&exportall=1');
    },
    _VVersion() {
      //let _dialogIfrome= this.$refs.dialogIfrome;
      //http://222.244.147.65:8089/ebpm-process-manage/procDefMgr/getHistoryProcessDefModel.do?procDefId=jzsp_cgfssbbgzs:1:b74fc3bf-808d-11e5-8675-005056b627a1
      this.store.state.dialogVisible.dialogIfromeSrc =
        this.$get_bpmn_manage_url() +
        '/procDefMgr/getHistoryProcessDefModel.do?procDefId=' +
        this.procDefId
      this.store.state.dialogVisible.show = true
      this.store.state.dialogVisible.title = '查看版本'
    },
    _chooseFlow() {
      this.store.state.dialogVisible.dialogIfromeSrc =
        this.$get_bpmn_manage_url() +
        '/procDefModelMgr/model/list.do?appId=' +
        this.saveObj.appId
      this.store.state.dialogVisible.show = true
      this.store.state.dialogVisible.title = '选择流程'
    },
    // 下载为SVG格式,done是个函数，调用的时候传入的
    saveSVG(done) {
      // 把传入的done再传给bpmn原型的saveSVG函数调用
      this.bpmnModeler.saveSVG(done)
    },
    // 下载为SVG格式,done是个函数，调用的时候传入的
    saveDiagram(done) {
      // 把传入的done再传给bpmn原型的saveXML函数调用
      this.bpmnModeler.saveXML({ format: true }, function (err, xml) {
        done(err, xml)
      })
    },
    // 当图发生改变的时候会调用这个函数，这个data就是图的xml
    setEncoded(link, name, data) {
      // 把xml转换为URI，下载要用到的
      const encodedData = encodeURIComponent(data)
      // 获取到图的xml，保存就是把这个xml提交给后台
      this.xmlStr = data
      // 下载图的具体操作,改变a的属性，className令a标签可点击，href令能下载，download是下载的文件的名字
      if (data) {
        link.className = 'el-button el-button--primary el-button--mini '
        link.href = 'data:application/bpmn20-xml;charset=UTF-8,' + encodedData
        link.download = name
      }
    },
    release() {
      let _this = this
      let url =
        this.$get_bpmn_manage_url() +
        '/procDefMgr/releaseProcess.do?' +
        'procDefId=' +
        this.procDefId
      _this.vLoading = true
      this.$axios
        .get(url)
        .then(function (res) {
          console.log(res)
          _this.vLoading = false
          _this.$message.success(res.data)
        })
        .catch(function (error) {
          console.log(error)
          _this.$message.warning('操作失败!')
          _this.vLoading = false
        })
    },

    save() {
      let _this = this
      let url =
        this.$get_bpmn_manage_url() +
        '/procDefModelMgr/deployCascodeUpdate.do'
      let _saveObj = this.saveObj
      //console.log(_saveObj);

      for (let property in _saveObj) {
        //console.log(_saveObj[property]);
        if (_saveObj[property] == null) {
          this.$message.error(
            '流程的' + (property == 'name' ? '名称' : property) + '不能为空',
          )
          return
        }
      }
      _this.vLoading = true
      this.$axios
        .post(url, _saveObj)
        .then(function (res) {
          _this.vLoading = false
          _this.procDefId = res.data.procDefId
          if (res.data.procDefId != '') {
            _this.buttonDisabledByProDefId = false
          }
          if (
            _this.store.state.dialogVisible.procDefId == '' ||
            _this.store.state.dialogVisible.procDefId == undefined
          ) {
            console.log(window)
            window.parent.location.reload()
          }
          _this.store.state.dialogVisible.procDefId = res.data.procDefId
          _this.$message.success(res.data.msg)
        })
        .catch(function (error) {
          console.log(error)
          _this.buttonDisabledByProDefId = true
          _this.$message.warning('操作失败!')
          _this.vLoading = false
        })
    },
    randomString(length) {
      var chars = [
        '0',
        '1',
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'I',
        'J',
        'K',
        'L',
        'M',
        'N',
        'O',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
      ]
      var result = ''
      for (var i = length; i > 0; --i) {
        result += chars[Math.floor(Math.random() * chars.length)]
      }
      return result
    },
    // 接受子信息
    handleMessage(event) {
      const self = this
      const data = event.data

      switch (data.cmd) {
        case 'flow':
          self.judge('flow', data.params.procDefKey)
          break
      }
    },
    judge(type, value) {
      window.parent.parent.postMessage(
        {
          cmd: 'flow',
          params: { procDefKey: value },
        },
        '*',
      )
    },
  },
  mounted() {

    this.vLoading = true
    let customTranslateModule = {
      translate: ['value', customTranslate],
    }

    // 获取到属性ref为“content”的dom节点
    this.container = this.$refs.content
    // 获取到属性ref为“canvas”的dom节点
    const canvas = this.$refs.canvas
    // 建模，官方文档这里讲的很详细
    let options = {
      container: canvas,
      // 添加控制板
      propertiesPanel: {
        parent: '#js-properties-panel',
      },
      additionalModules: [
        // 右边的工具栏
        propertiesProviderModule,

        // 左边工具栏以及节点
        propertiesPanelModule,
        // PropertiesPanel,
        //汉字转换模块
        customTranslateModule,
        //颜色
        colors,
      ],
      keyboard: {
        bindTo: window,
      },
      //moddleExtensions: {
      //  camunda: magicModdleDescriptor
      //}
    }
    this.bpmnModeler = new BpmnModeler(options)
    //console.log(modeker);
    // 下载画图
    let _this = this
    // 给图绑定事件，当图有发生改变就会触发这个事件
    this.bpmnModeler.on('commandStack.changed', function () {
      //_this.saveSVG(function (err, svg) {
      //_this.setEncoded(downloadSvgLink, 'diagram.xml', err ? null : svg)
      // _this.saveObj.svgXml = svg;
      //})

      _this.saveDiagram(function (err, xml) {
        _this.saveObj.flow_xml = xml
        //_this.setEncoded(downloadLink, 'diagram.bpmn', err ? null : xml)
      })
      _this.buttonDisabled = false
      //console.log(_this.bpmnModeler);
      //获取图表的id和name,(暂时不确定有没有其它好办法)
      _this.saveObj.key = _this.bpmnModeler._definitions.rootElements[0].id
      _this.saveObj.name = _this.bpmnModeler._definitions.rootElements[0].name
    })
    let openProcessUrl =
      this.$get_bpmn_manage_url() +
      '/procDefModelMgr/openProcess.do?key=' +
      this.saveObj.key +
      '&appId=' +
      this.saveObj.appId
    if (this.saveObj.appId == null) {
      _this.$message.warning('appId参数异常!')
    }
    this.$axios
      .get(openProcessUrl)
      .then(function (res) {
        if (res.data.flow_xml != '') {
          _this.bpmnXmlStr = res.data.flow_xml
          _this.procDefId = res.data.procDefId
          if (res.data.procDefId != '') {
            _this.buttonDisabledByProDefId = false
          }
          _this.store.state.dialogVisible.procDefId = res.data.procDefId
        }
        console.log('验证遮罩')
        _this.createNewDiagram(_this.bpmnModeler)
        _this.vLoading = false
        //console.log(res);
      })
      .catch(function (error) {
        console.log(error)
        _this.buttonDisabledByProDefId = true
        _this.createNewDiagram(_this.bpmnModeler)
        _this.vLoading = false
      })

    /** let imgs= document.getElementsByClassName("bjs-powered-by");
    for(let i = 0;i<imgs.length;i++){
      imgs[i].style.display = 'none';
    }**/
  },
}
</script>

<style lang="scss">
/*左边工具栏以及编辑节点的样式*/
@import '../../node_modules/bpmn-js/dist/assets/diagram-js.css';
@import '../../node_modules/bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
@import '../../node_modules/bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css';
@import '../../node_modules/bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';
/*右边工具栏样式*/
@import '../../node_modules/bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css';
@import '../../bpmn-js/colors/vendor/diagram-js.css';
@import '../../bpmn-js/colors/vendor/colors/color-picker.css';
@import '../../bpmn-js/colors/vendor/bpmn-font/css/bpmn-embedded.css';

/*左边工具栏以及编辑节点的样式*/
/*右边工具栏样式*/
/*左边工具栏以及编辑节点的样式*/
/*右边工具栏样式*/
* {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}
.containers {
  position: absolute;
  background-color: #ffffff;
  width: 99%;
  height: calc(100% - 16px);
}
.canvas {
  width: calc(100% - 258px);
  height: calc(100% - 48px);
}
.topButtonGroup {
  text-align: left;
  width: 100%;
  background: #f3f5fb;
  color: #333;
  padding: 10px;
  height: 48px;
  border: 1px solid #e6e9ed;
}
.bpp-properties-group {
  padding: 10px 15px 10px 15px;
}
.bpp-properties-entry {
  margin-bottom: 15px;
}
.bpp-properties-panel label {
  color: #333;
  font-size: 14px;
}
.bpp-properties-panel {
  background-color: #fff;
}
.bpp-properties-group > .group-label {
  display: none !important;
}
.el-dialog__wrapper.el-dialog-lcpz .el-dialog__body {
  padding: 4px 20px;
}
ul.bpp-properties-tabs-links > li > a {
  border: 1px solid #e6e9ed;
}
ul.bpp-properties-tabs-links > li.bpp-active a {
  padding-bottom: 4px;
  border-top: 2px solid #409eff;
  background: #fff;
}
.bpp-properties-tab-bar {
  border-bottom: 1px solid #e6e9ed;
  background: #fafafa;
}
.bpp-properties-header + .bpp-properties-tab-bar {
  margin-top: -10px;
}
.bpp-properties-header {
  padding: 15px;
  padding-bottom: 5px;
  background: #fafafa;
}
.panel {
  position: absolute;
  right: 0;
  top: 0;
  width: 300px;
}
#js-properties-panel {
  position: absolute;
  top: 48px;
  bottom: 0;
  right: 0;
  width: 260px;
  z-index: 10;
  border: 1px solid #e6e9ed !important;
  overflow: auto;
  border-top: 0 !important;
}
#js-properties-panel:empty {
  display: none;
}
#js-properties-panel > .djs-properties-panel {
  padding-bottom: 70px;
  min-height: 100%;
}
.containers .djs-palette {
  left: 0;
  top: 0;
  height: calc(100% - 20px);
  border-color: #e6e9ed;
  border-top: 0 !important;
}
.afterText::after {
  content: attr(title);
  font-size: 12px;
}
</style>

<style>
html,
body {
  margin: 0;
  padding: 0;
}
body .containers {
  width: 100%;
  height: 100%;
  background: #f9fafe;
}
body .containers .topButtonGroup {
  background: #fff;
  border: 0;
  display: table;
  width: 100%;
  position: absolute;
  box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.05);
  z-index: 9;
}
body .containers .topButtonGroup .head-left {
  display: table-cell;
  vertical-align: middle;
  color: #333;
  font-size: 16px;
}
body .containers .topButtonGroup .head-right {
  display: table-cell;
  vertical-align: middle;
  text-align: right;
}
body .containers .topButtonGroup .head-right .el-button.el-button--primary {
  background: #233984;
  border-color: #233984;
  color: #fff;
}
body .containers .topButtonGroup .head-right .el-button.el-button--default {
  color: #333;
  background: #fff;
  border-color: #d9d9d9;
}
body .containers .topButtonGroup .head-right .el-button.is-disabled {
  background: #f0f0f0 !important;
  border-color: #d9d9d9 !important;
  color: #999 !important;
}
body .containers .canvas {
  margin-top: 48px;
}
body .containers .canvas .djs-overlay-context-pad {
  top: -50px !important;
  left: -50px !important;
}
body .containers .canvas .djs-context-pad.open {
  background: #fff;
  border: 0;
  box-shadow: 0px 2px 2px rgb(0 0 0 / 5%);
  position: absolute;
  z-index: 9;
  display: flex;
}
body .containers .canvas .djs-context-pad .group {
  display: flex;
}
body .containers .canvas .djs-context-pad .group .entry {
  margin: 5px 10px;
  border-radius: 0;
  font-size: 18px;
  line-height: 22px;
  text-align: center;
}
body .containers .canvas .djs-context-pad .group .entry:before {
  line-height: 22px;
}
body .containers .canvas .djs-context-pad .group .entry:hover {
  background: #f0f0f0;
}
body .containers .canvas .bjs-container .djs-container .djs-palette {
  box-shadow: 2px 0px 4px rgba(0, 0, 0, 0.1);
  background: #fff;
  border: none;
  height: 100%;
  width: 180px;
}
body .containers .canvas .bjs-container .djs-container .djs-palette .entry,
body
  .containers
  .canvas
  .bjs-container
  .djs-container
  .djs-palette
  .djs-palette-toggle {
  width: 180px;
  height: 50px;
  line-height: 50px;
  cursor: default;
  text-align: left;
  padding: 0 0 0 16px;
}
body
  .containers
  .canvas
  .bjs-container
  .djs-container
  .djs-palette
  [class^='bpmn-icon-']:before,
body
  .containers
  .canvas
  .bjs-container
  .djs-container
  .djs-palette
  [class*=' bpmn-icon-']:before {
  font-size: 24px;
  line-height: 50px;
  float: left;
}
body
  .containers
  .canvas
  .bjs-container
  .djs-container
  .djs-palette
  .afterText::after {
  content: attr(title);
  font-size: 12px;
  line-height: 50px;
  display: inline-block;
  float: left;
  padding: 0 0 0 8px;
}
body .containers .canvas .bjs-container .djs-container .djs-palette .separator {
  margin: 5px 0;
  padding-top: 0;
  border: none;
  border-bottom: solid 1px #eeee;
  clear: both;
}
body .containers #js-properties-panel {
  z-index: 2;
  background: #fff;
  border: 0;
  box-shadow: -2px 0px 4px rgb(0 0 0 / 10%);
}
body .containers #js-properties-panel .bpp-properties-header {
  padding: 0;
  background: #fff;
}
body
  .containers
  #js-properties-panel
  .bpp-properties-header
  + .bpp-properties-tab-bar {
  margin-top: 0;
}
body .containers #js-properties-panel .bpp-properties-tab-bar {
  background: #fff;
  border-bottom: 1px solid #eee;
  height: 49px;
}
body
  .containers
  #js-properties-panel
  .bpp-properties-tab-bar
  ul.bpp-properties-tabs-links {
  margin: 0;
}
body
  .containers
  #js-properties-panel
  .bpp-properties-tab-bar
  ul.bpp-properties-tabs-links
  > li {
  margin: 0;
}
body
  .containers
  #js-properties-panel
  .bpp-properties-tab-bar
  ul.bpp-properties-tabs-links
  > li
  > a {
  border: 0;
  padding: 0 10px;
  line-height: 46px;
  border-bottom: 2px solid transparent;
  color: #666;
  font-size: 15px;
}
body
  .containers
  #js-properties-panel
  .bpp-properties-tab-bar
  ul.bpp-properties-tabs-links
  > li.bpp-active
  a {
  border-bottom-color: #333;
  color: #333;
}
body .containers .bpp-properties-panel input,
body .containers .bpp-properties-panel button,
body .containers .bpp-properties-panel textarea,
body .containers .bpp-properties-panel [contenteditable] {
  height: 40px;
  line-height: 38px;
  padding: 0 10px;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
}
body .containers .bpp-properties-panel label {
  color: #333;
  font-size: 14px;
  font-weight: normal;
  line-height: 24px;
  margin-bottom: 5px;
}
body .containers .bpp-properties-entry {
  margin-bottom: 24px;
}
</style>
