<template>
  <div class="TemplateManagementNew">
  <!--  <Breadcrumb separator=">" class="breadcrumb">
        <BreadcrumbItem to="/TemplateManagementLists">模版管理</BreadcrumbItem>
        <BreadcrumbItem>{{$route.params.id != '-1'?'编辑模版':'新建模版'}}</BreadcrumbItem>

    </Breadcrumb> -->
    <!-- 预览状态 -->
    <div class="content" v-if="this.readOnly">
      <div class="tips" v-if="currentSteps === 2">
        <p>
          <span>单据类型:</span><span>{{data.businessTypeText}}</span>
        </p>
        <p>
          <span>模版名称:</span><span>{{data.name}}</span>
        </p>
        <p>
          <span>查询索引:</span><span>{{data.businessKey}}</span>
        </p>
        <p>
          <span>模版描述:</span><span>{{data.description}}</span>
        </p>
        <p>
          <span>自动处理:</span><span>{{data.autoClose?'开':'关'}}</span>
        </p>
        <p>
          <span>业务数据检查:</span><span>{{data.businessCheckUrl}}</span>
        </p>
      </div>
      <FlowChartComponent
        v-if="currentSteps === 2"
        :data="data"
        :currentSteps="2"
        :readOnly="readOnly"
        ref="component_2"
      >
      </FlowChartComponent>
      <p class="buttonGroups" v-if="currentSteps === 2">
        <Button type="primary" @click="close">关闭</Button>
      </p>
    </div>

    <!-- 编辑状态 -->
    <Steps :current="currentSteps" class="steps" v-if="!this.readOnly">
        <Step title="参数配置" ></Step>
        <Step title="流程设计器" ></Step>
        <Step title="保存发布模版" ></Step>
    </Steps>

    <div class="content" v-if="!this.readOnly">
      <keep-alive exclude="component_2" >
        <component
          :is="currentComponent"
          :ref="currentComponent"
          class="block"
          :editable="currentSteps === 1?true:false"
          :data="data"
          :currentSteps="currentSteps"
          :noFreshFlag="noFreshFlag"
          @dataChange="dataChange"
          >
        </component>
      </keep-alive>
      <p class="buttonGroups">
        <Button type="primary" v-if="currentSteps > 0" @click="previousSteps">上一步</Button>
        <Button type="primary" v-if="currentSteps < 2" @click="nextSteps">下一步</Button>
        <Button type="primary" v-if="(currentSteps === 2 && this.data.status !== 1)" @click="confirm(false)">保存</Button>
        <Button type="primary" v-if="(currentSteps === 2 && this.data.status !== 1)" @click="confirmAndPublish()">保存并发布</Button>
      </p>
    </div>
  </div>
</template>
<script>
import '@/utils/go'
import Vue from 'vue'
import ParameterConfiguration from '@/components/ParameterConfiguration'
import FlowChartComponent from '@/components/FlowChartComponent'
import FlowSuccess from '@/components/FlowSuccess'
import {  mapMutations } from 'vuex';
import { setTimeout } from 'timers';
import {
    getLoad,
    getCommit,
    getDuplicate,
    getPublish
  } from '@/api/modeler.js'
export default {
  name:'TemplateManagementNew',
  components:{ParameterConfiguration,FlowChartComponent,FlowSuccess},
  data () {
    return {
      currentSteps:0,
      currentComponent:null,
      imgBase:'',
      defaultData:{
        guiStyle:JSON.stringify({
          "class": "NewGraphLinksModel",
          "linkFromPortIdProperty": "fromPort",
          "linkToPortIdProperty": "toPort",
          "nodeDataArray": [
            {"key":-1, "category":"Start", "loc":"175 0", "text":"开始", "type": 1},
            {"key":0, "loc":"175 100", "text":"审批节点","type": 0, "category": 'Approval'},
            {"key":-2, "category":"End", "loc":"175 200", "text":"结束", "type": 2}
          ],
          "linkDataArray": [
            {"from":-1, "to":0, "fromPort":"B", "toPort":"T","key":0},
            {"from":0, "to":-2, "fromPort":"B", "toPort":"T","key":1}
          ]
        }),
        nodeMsg:[
          {"key":-1, "category":"Start", "loc":"175 0", "text":"开始", "name":"开始", "type": 1,"ruleList":[]},
          {"key":0, "loc":"175 100", "text":"审批节点",  "name":"审批节点", "category": 'Approval',"type": 0,"ruleList":[],"actServiceS":[],"actionConfig":[],"approvelList":[],"approverStyle":0},
          {"key":-2, "category":"End", "loc":"175 200", "text":"结束",  "name":"结束", "type": 2,"actionConfig":[{
              handleValue:null,
              extra_msg:{},
              handleType:31
            },
            {
              handleValue:'{}',
              extra_msg:{},
              handleType:41
            }]}
        ],
        pathMsg:[
          {"from":-1, "to":0, "fromPort":"B", "toPort":"T","ruleList":[],"key":0},
          {"from":0, "to":-2, "fromPort":"B", "toPort":"T","ruleList":[],"key":1}
        ],
        removeNode:[],
        removePath:[],
      },
      data:{
        guiStyle:JSON.stringify({
          "class": "NewGraphLinksModel",
          "linkFromPortIdProperty": "fromPort",
          "linkToPortIdProperty": "toPort",
          "nodeDataArray": [
            {"key":-1, "category":"Start", "loc":"175 0", "text":"开始", "type": 1},
            {"key":0, "loc":"175 100", "text":"审批节点","type": 0, "category": 'Approval'},
            {"key":-2, "category":"End", "loc":"175 200", "text":"结束", "type": 2}
          ],
          "linkDataArray": [
            {"from":-1, "to":0, "fromPort":"B", "toPort":"T","key":0},
            {"from":0, "to":-2, "fromPort":"B", "toPort":"T","key":1}
          ]
        }),
        nodeMsg:[
          {"key":-1, "category":"Start", "loc":"175 0", "text":"开始", "name":"开始", "type": 1,"ruleList":[]},
          {"key":0, "loc":"175 100", "text":"审批节点",  "name":"审批节点", "category": 'Approval',"type": 0,"ruleList":[],"actServiceS":[],"actionConfig":[],"approvelList":[],"approverStyle":0},
          {"key":-2, "category":"End", "loc":"175 200", "text":"结束",  "name":"结束", "type": 2,"actionConfig":[{
              handleValue:null,
              extra_msg:{},
              handleType:31
            },
            {
              handleValue:'{}',
              extra_msg:{},
              handleType:41
            }]}
        ],
        pathMsg:[
          {"from":-1, "to":0, "fromPort":"B", "toPort":"T","ruleList":[],"key":0},
          {"from":0, "to":-2, "fromPort":"B", "toPort":"T","ruleList":[],"key":1}
        ],
        removeNode:[],
        removePath:[],
        autoClose: true,
        moduleType: 0
      },
      noFreshFlag:false,

      readOnly:false,  //是否只读为预览模式
      //存放三步骤的数据


      defaultModuleType: null,  //暂存模版类型

    }
  },
  watch:{
    currentSteps (val) {
      // if(this.readOnly){
      //   return
      // }
      let componentName = `component_${val}`
      if(Vue.component(componentName) === undefined){
        if(val === 0 ){
          Vue.component(componentName,ParameterConfiguration)
        }else if(val === 1){
          Vue.component(componentName,FlowChartComponent)
        }else if(val === 2){
          Vue.component(componentName,FlowSuccess)
        }
      }
      this.currentComponent = componentName
    }
  },
  methods:{
    ...mapMutations(['currentChange']),
    getModuleInfo (id) {
      getLoad({id:id}).then((res) => {
        if(res.resultCode === 0){
          res.data.businessType = [{
            ID:res.data.businessType,
            Label:res.data.businessTypeName,
            val:res.data.businessTypeText
          }]
          res.data.businessNumber = [{
            ID:String(res.data.businessKeyId),
            Label:res.data.businessKey,
            val:res.data.businessKeyName
          }]
          this.data = res.data
          this.data.guiStyle = JSON.parse(res.data.guiStyle)
          this.data.moduleId = res.data.id
          this.$nextTick(() => {
            if(this.readOnly){
              this.currentSteps = 2
              this.noFreshFlag = false
            }else{
              this.$refs.component_1.init()
              this.noFreshFlag = false
            }
          })
        }else{
          this.$Modal.fcWarning({
            title:'警告',
            content:res.resultMsg,
            mask:true
          })
        }
      });
    },
    async nextSteps () {  //下一步
      if(await this.checkModuleName()){
        return false
      }

      if(this.currentSteps === 0 && (this.defaultModuleType != this.data.moduleType) && this.defaultModuleType !== null){
        this.$Modal.fcWarning({
          title:'警告',
          content:'您已修改模板类型/单据类型，这将导致下一步的流程设计器内所有设置恢复初始化，是否确定更改?',
          showCancel: true,
          mask: true,
          onOk: () => {
            this.defaultModuleType = this.data.moduleType
            this.data = Object.assign(this.data,JSON.parse(JSON.stringify(this.defaultData)))
            if(this.data.businessType && this.data.businessType.length > 0 && this.data.name){
              this.defaultModuleType = this.data.moduleType
              ++this.currentSteps
            }else{
              this.$Modal.fcWarning({
                title:'警告',
                content:'请填写必填项!',
                mask:true
              })
            }
          },
          onCancel: () => {
          }
        })
        return
      }
      if( this.data.name && (this.data.moduleType === 0?(this.data.businessType && this.data.businessType.length > 0):true) ){
        this.defaultModuleType = this.data.moduleType
        ++this.currentSteps
      }else{
        this.$Modal.fcWarning({
          title:'警告',
          content:'请填写必填项!',
          mask:true
        })
      }



    },
    async checkModuleName () {
      await new Promise((resolve, reject) => {
        let jsonObject = {
          ID:this.data.moduleId,
          NAME:this.data.name
        }
        getDuplicate(jsonObject).then(res => {
            if(res.resultCode !== 0){
              this.$Modal.fcWarning({
                title:'警告',
                content:res.resultMsg,
                mask:true
              })
              reject()
            }
            resolve(res)
        })
      })
    },
    previousSteps () {  //上一步
      --this.currentSteps
    },
    async confirm (flag) {  //确定

      return await new Promise((resolve,reject) => {

        var svg = this.data.myDisplay.makeImage({
                                          scale: 2
                                        });
        this.imgBase = svg.getAttribute('src')

        let nodeMsg = []
        Object.keys(this.data.nodeMsg).map(item => {
          nodeMsg.push(this.data.nodeMsg[item])
          return item
        })

        let pathMsg = []
        Object.keys(this.data.pathMsg).map(item => {
          pathMsg.push(this.data.pathMsg[item])
          return item
        })
        let jsonObject = {
          id:this.data.moduleId,
          name:this.data.name,
          description:this.data.description,
          GUI_STYLE:this.data.guiStyle,
          url:svg.getAttribute('src'),
          moduleType: this.data.moduleType,
          BUSINESS_TYPE:this.data.businessType?this.data.businessType[0].ID:null,
          BUSINESS_TYPE_NAME:this.data.businessType?this.data.businessType[0].Label:null,
          businessTypeText:this.data.businessType?this.data.businessType[0].val:null,
          businessKeyId:(this.data.businessNumber && this.data.businessNumber.length > 0)?this.data.businessNumber[0].ID:null,
          businessKey:(this.data.businessNumber && this.data.businessNumber.length > 0)?this.data.businessNumber[0].Label:null,
          businessKeyName:(this.data.businessNumber && this.data.businessNumber.length > 0)?this.data.businessNumber[0].val:null,
          autoClose:this.data.autoClose,
          businessCheckUrl:this.data.businessCheckUrl,
          nodeMsg: nodeMsg,
          pathMsg: pathMsg,
          removeNode: this.data.removeNode,
          removePath: this.data.removePath
        }
        getCommit(jsonObject).then(res => {
            if(res.resultCode === 0){
              // this.data = {
              //   guiStyle:{
              //     "class": "go.GraphLinksModel",
              //     "linkFromPortIdProperty": "fromPort",
              //     "linkToPortIdProperty": "toPort",
              //     "nodeDataArray": [],
              //     "linkDataArray": []
              //   }
              // }
              if(!flag){
                window.flag = true
                this.$router.push('/tool/activiti/modeler')
                this.currentChange({
                  path:'/tool/activiti/modeler'
                });
              }

              resolve(res)
            }else{
              this.$Modal.fcError({
                title:'错误',
                content:res.resultMsg,
                onOk: () => {
                }
              })
            }

        })
      })


    },
    async formatGuiStyle () {  //format整个流程图
      await new Promise((resolve) => {
        let startNode = {}  //获取开始节点
        this.data.guiStyle.nodeDataArray.map(item => {
          if(item.key === -1){
            startNode = item
          }
        })

        let startlink = {}
        //获取第一根线的数据
        this.data.guiStyle.linkDataArray.map(item => {
          if(item.from === -1){
            startlink = item
          }
        })

        //获取连线的正确排序
        let linkMap = []
        new Array(this.data.guiStyle.linkDataArray.length).fill(null).map(() => {
          this.data.guiStyle.linkDataArray.map(item => {
            if(linkMap.length === 0 && item.from === -1){
              linkMap.push(item)
            }
            if(linkMap.length > 0 && item.from === linkMap[linkMap.length-1].to){
              linkMap.push(item)
            }
          })
        })
        this.data.guiStyle.linkDataArray = linkMap


        //获取节点的正确顺序
        // let nodeMap = [startNode]
        this.data.guiStyle.nodeDataArray = this.data.guiStyle.linkDataArray.reduce((sum,item) => {
          sum.push(this.data.Diagram.model.findNodeDataForKey(item.to))
          return sum
        },[startNode])


        //将所有节点的x轴与开始节点对齐
        this.data.guiStyle.nodeDataArray.map((item,index) => {
          let loc = item.loc.split(' ')
          loc[0] = startNode.loc.split(' ')[0]
          loc[1] = Number(startNode.loc.split(' ')[1]) + index*80
          item.loc = loc.join(' ')
        })

        //将所有连线的x轴与开始节点对齐
        this.data.guiStyle.linkDataArray.map((item,index) => {
          item.points.j.map(temp => {
            temp.F = startlink.points.j[0].F
          })

          item.points.j.map((temp,j) => {
            if(index === 0){
              if(j !== item.points.j.length-1){
                temp.G = Number(this.data.guiStyle.nodeDataArray[index].loc.split(' ')[1])+20
              }else{
                temp.G = Number(this.data.guiStyle.nodeDataArray[index+1].loc.split(' ')[1])-20
              }
            }else if(index === this.data.guiStyle.linkDataArray.length - 1){
              if(j !== item.points.j.length-1){
                temp.G = Number(this.data.guiStyle.nodeDataArray[index].loc.split(' ')[1])+20
              }else{
                temp.G = Number(this.data.guiStyle.nodeDataArray[index+1].loc.split(' ')[1])-20
              }
            }else{
              if(j !== item.points.j.length-1){
                temp.G = Number(this.data.guiStyle.nodeDataArray[index].loc.split(' ')[1])+20
              }else{
                temp.G = Number(this.data.guiStyle.nodeDataArray[index+1].loc.split(' ')[1])-20
              }
            }

          })
        })

        this.data.Diagram.model = go.Model.fromJson(this.data.guiStyle)

        setTimeout(() => {
          resolve()
        },100)
      })
    },
    dataChange (data) {  //每一步中的数据变化
      this.data = Object.assign(this.data,data)
    },
    close () {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push('/tool/activiti/modeler')
      this.currentChange({
        path:'/tool/activiti/modeler'
      });
    },
    confirmAndPublish () {  //保存并发布
      this.confirm(true).then(res => {
        getPublish({id:res.data.id}).then((response) => {
          if(response.resultCode === 0){
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push('/tool/activiti/modeler')
            this.currentChange({
              path:'/tool/activiti/modeler'
            });
          }
        })
      })
    }
  },
  created () {
    Vue.component(`component_${this.currentSteps}`,Vue.extend(Object.assign({isKeepAliveModel:true},ParameterConfiguration)))
    this.currentComponent = `component_${this.currentSteps}`
    if(this.$route.params.flag === '1'){
      this.readOnly = true
      this.noFreshFlag = true
      this.currentSteps = 1
      this.getModuleInfo(this.$route.params.id)
      return
    }
    if(this.$route.params.id === undefined){  //新增

    }else{  //编辑
      this.noFreshFlag = true
      this.currentSteps = 1
      this.getModuleInfo(this.$route.params.id)
    }
  },
  beforeDestroy () {

  }
}
</script>
<style lang="scss" scoped>
.TemplateManagementNew{
  padding:16px;
  background: white;
  display: flex;
  height: calc(100vh - 100px);
  flex-direction: column;

  .breadcrumb{
    margin-bottom: 30px;
    font-size: 18px;
  }

  .steps{
    width: 75%;
    margin-left: 12.5%;
    margin-bottom: 30px;
  }

  .content{
    flex:1;
    border:1px solid rgba(220,222,226,1);
    display: flex;
    flex-direction: column;
    position: relative;
    // 预览tips
    .tips{
      width:260px;
      height:204px;
      background:rgba(236,236,236,1);
      padding: 16px;
      box-sizing: border-box;
      display: inline-block;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 99;
      >p{
        font-weight:400;
        color:rgba(52,52,52,1);
        line-height:16px;
        margin-bottom: 12px;
        display: flex;

        >span:first-child{
          margin-right: 8px;
          white-space: nowrap;
        }

        >span:last-child{
          word-break: break-all;
        }
      }
    }

    .block{
      flex: 1;
    }

    .buttonGroups{
      text-align: right;
      padding-bottom: 16px;

      button{
        margin-right: 10px;

        &:last-child{
          margin-right:16px;
        }
      }
    }
  }

  .burgeon-steps-item.burgeon-steps-status-finish .burgeon-steps-head-inner > .burgeon-steps-icon, .burgeon-steps-item.burgeon-steps-status-finish .burgeon-steps-head-inner span{
    color: white;
  }

  .burgeon-steps-item.burgeon-steps-status-finish .burgeon-steps-head-inner{
    border-color: #09A155;
    background: #09A155;
  }
}
</style>
