<template> 
    <ifbp-page id="designer">
        <ifbp-breadcrumb name="设计器"></ifbp-breadcrumb>
        <ifbp-main-area id="designer-content">
            <div id="designer-nav">
               <el-col>
                <el-tabs>
                    <el-tab-pane label="系统">
                        <el-tree
                            :data="systemData"
                            :props="systemProps"
                            accordion
                            @node-dblclick="sysDblclick"
                            @node-click="sysNodeClick"
                        ></el-tree>
                    </el-tab-pane>
                    <el-tab-pane label="业务">
                        <el-tree
                        :data="busData"
                        :props="busProps"
                        accordion
                        @node-dblclick="busDblclick"
                        @node-click="busNodeClick"
                        @node-expand="busExpandClick"></el-tree>
                    </el-tab-pane>
                </el-tabs>
            </el-col> 
            </div>
            <div class="fr" style="width:80%;">
                <div id="editor" type="text/plain" ref="ue"></div>
            </div>
        </ifbp-main-area>
        <ifbp-footer>
            <!-- <el-button type="default" class="fr" @click="backInfo">返回</el-button> -->
            <el-button type="primary" @click="save">保存</el-button>
        </ifbp-footer>
    </ifbp-page> 
</template> 

<script>
import '../../../static/Ueditor/ueditor.config.js';
import '../../../static/Ueditor/ueditor.all.js'; 
import '../../../static/Ueditor/ueditor.parse.js';
import '../../../static/Ueditor/lang/zh-cn/zh-cn.js'; 
export default {
  data(){
    return{
      busClickData:'',
      busClickNode: '',
      sysClickData:'',
      sysClickNode: '',
      systemData: [],
      systemProps:{
          label:'label',
          children: 'children'
      },
      busData:[],
      busProps:{
          label:'label',
          children: 'children'
      },
      orginalTpl:'',
      Ueditor: {},
      title:'',
      associatedProcesses:'',//关联流程
      processes: '',//流程的数据
    }
  },
  methods:{
      scroll(){
        // e.preventDefault();
        // e = window.event || e;
        if($('#designer').length > 0) {
        const mainTop = $('#designer-content').offset().top;
        // console.log("editor offset",mainTop);
        const $fixedDom = $('#designer-nav');
        var topHight = 60; 
        if(mainTop >= topHight) {
          $fixedDom.removeClass('fixed');
        }
        if(mainTop < topHight) {
          $fixedDom.addClass('fixed');
        }
      }
      },
      sysNodeClick(data,node){
          this.sysClickData = data;
          this.sysClickNode = node;
      },
      sysDblclick(){
          var data = this.sysClickData;
          if(data.isProperty === true){
              this.Ueditor.execCommand("inserthtml",'"["+ name+"]"');
          }
      },
      // 点击参照增加下级
      busNodeClick(data,node,comp){
          this.busClickData = data;
          this.busClickNode = node;
          if(data.datatypestyle === '305'){
              if(node.childNodes.length === 0){
              this.$http({
                  url:'/ifbp-app-sm-infoset-web/scene/queryRefEntityPropertyList',
                  method: 'post',
                  headers: {
                    "Content-Type": "application/json"
                  },
                  data: data.datatype
              }).then((res) => {
                  if(res.data.success === true){
                    var resData = JSON.parse(JSON.stringify(res.data.data));
                    resData.forEach((v) => {
                      this.$set(v,'label',v.displayname);
                    });
                    this.$set(data,'children',resData);
                  }
              }).catch(() => {
                  this.$message({
                      type: 'error',
                      message: '请求出错'
                  });
              });
            }
          }
      },
      busExpandClick(data,node){
          if(node.level === 2){
              node.childNodes.forEach((v) => {
                  if(v.data.datatypestyle === '305'){
                      v.isLeaf = false;
                  }
              });
          } else if(node.level === 3){
              node.childNodes.forEach((v) => {
                  if(v.data.datatypestyle === '302'){
                      v.isLeaf = false;
                  }
              });
          }
          if(data.datatypestyle === '305' || data.datatypestyle === '302'){
              if(node.childNodes.length === 0){
              this.$http({
                  url:'/ifbp-app-sm-infoset-web/scene/queryRefEntityPropertyList',
                  method: 'post',
                  headers: {
                    "Content-Type": "application/json"
                  },
                  data: data.datatype
              }).then((res) => {
                if(res.data.success === true){
                var resData = JSON.parse(JSON.stringify(res.data.data));
                var childNodes = [];
                node.isLeaf = false;
                node.expanded = true;
                  resData.forEach((v,index) => {
                    this.$set(v,'label',v.displayname);
                    node.childNodes.push({
                        checked: false,
                        childNodes: [],
                        data: v,
                        expanded: false,
                        id: 2222 + index ,
                        indeterminate: false,
                        isLeaf: true,
                        level: node.level + 1,
                        loaded: false,
                        loading: false,
                        parent: node,
                        store: [],
                        text: '',
                        visible: true,
                        icon: '',
                        key: undefined,
                        label: v.label
                    });            
                });
                  
                }
              }).catch(() => {
                  this.$message({
                      type: 'error',
                      message: '请求出错'
                  });
              });
            }
          }
      },
      busDblclick(){
          var data = this.busClickData;
          var node = this.busClickNode;
          var name,keyname,pName,pKeyname,ppName,ppKeyname;
          name = node.data.name;
          keyname = node.data.label;
          pName = node.parent.data.name;
          pKeyname = node.parent.data.label;
          ppName = node.parent.parent.data.name;
          ppKeyname = node.parent.parent.data.label;        
          if(node.level < 2){
              name = '';
              keyname = '';
          }
          if(node.level === 3){
              if(node.parent.data.primary === true){
                name = name;
                keyname = keyname;
              } else{
                name = pName+'.'+name;
                keyname = pKeyname + '.' + keyname;
              }
          } else if(node.level === 4){
              if(node.parent.parent.data.primary === true){
                name = pName+'.'+name;
                keyname = pKeyname+'.'+keyname;
              } else {
                name = ppName + '.' + pName+'.'+name;
                keyname = ppKeyname + '.' + pKeyname+'.'+keyname;
              }
          }       
          var addHtml = '<a class="getKeyValue" title="'+ name+'">['+keyname+']</a>';
          // 增加的span标签和class是为了后端提取拖拽的关键字
          if(data.datatypestyle !== undefined && data.datatypestyle !== '305' && data.datatypestyle !== '302'){
              this.Ueditor.execCommand("inserthtml",addHtml);
          }
      },
      getBus(){
        const self = this;
        var currentTpl = JSON.parse(window.localStorage.getItem('currentTpl'));
        this.orginalTpl = JSON.parse(JSON.stringify(currentTpl));
        // window.localStorage.clear();
        var submitData = {
            id: currentTpl.pk_pubscene
        };
        this.$http({
            url: '/ifbp-app-sm-infoset-web/scene/queryPubSceneMsgSetting',
            method:'post',
            data: submitData,
            dataType: 'json'
        }).then((res) => {
            if(res.data.success === true) {
                self.busData.push(res.data.data);
            } else if(res.data.success === false){
                self.$message({
                    message: "请求出错",
                    type: 'error'
                });
                }
        }).catch(() => {
            self.$message({
                message: '请求出错',
                type: 'error'
            });
        });
        },
        save(){
            const self = this;
            if(this.Ueditor.hasContents()){
                // var datas = self.Ueditor.getAllHtml();
                // var meta = '<meta http-equiv="content-type" content="text/html;charset=utf-8">';
                // console.log('data',data);
                // if(datas.indexOf(meta) == -1){
                //     var contentData =data.substring(0,6) + meta +data.substring(12);
                // } else {
                //     var data ='<html><head><meta>' + datas.split('<meta>')[0];
                // }
                var contentData = self.Ueditor.getContent();
                var template = {
                        pk_print_template: self.orginalTpl.pk_print_template,
                        content: contentData
                };
                this.$http({
                    url: '/ifbp-print/rest/printTemplate/updateContent',
                    method:'post',
                    data: template,
                }).then((res) => {
                    if(res.data.success === true) {
                        self.$message(res.data.msg);
                        this.$router.push('/printTemplate');
                    } else if(res.data.success === false){
                        self.$message({
                            message: "请求出错",
                            type: 'error'
                        });
                        }
                }).catch(() => {
                    self.$message({
                        message: '请求出错',
                        type: 'error'
                    });
                });
        }
        },
        backInfo(){
            this.$router.push('/printTemplate');
        },
        // 鼠标移到变量上的时候选中整个变量
        selectVariable(){
            var pattern = /\[(.)*\]/;
            var range = this.Ueditor.selection.getRange();
            var str = range.startContainer.data;
            if(pattern.test(str)){
                range=range.selectNode(range.startContainer);
                range.adjustmentBoundary();
                range.select();
            }
        },
        // 单击变量的时候选中整个变量
        selectVariableByClick(){
            var pattern = /\[(.)*\]/;
            var range = this.Ueditor.selection.getRange();
            var str = range.startContainer.data;
            if(pattern.test(str)){
                range=range.selectNode(range.startContainer);
                range.adjustmentBoundary();
                range.select();
            }
        },
  },
  created(){
      this.getBus();
  },
  mounted(){
    const self = this;
    document.getElementById('main-right').addEventListener("scroll",self.scroll);
    var ueditor = new UE.ui.Editor();
    this.Ueditor = ueditor;
    this.Ueditor.render('editor');
    // this.Ueditor = UE.getEditor('editor');
    this.Ueditor.addListener("ready", function() {
        if(self.orginalTpl.template_content){
            self.Ueditor.setContent(self.orginalTpl.template_content); // 确保UE加载完成后，放入内容。
        } else {
            self.Ueditor.setContent('');
        }
        self.Ueditor.addListener('click',self.selectVariableByClick);
        self.Ueditor.addListener('keyup',self.selectVariable);
        
      });
    
  },
  destroyed(){
    this.Ueditor.destroy();
    document.getElementById('main-right').removeEventListener('scroll',this.scroll);
    this.Ueditor.removeListener('click',self.selectVariableByClick);
    this.Ueditor.removeListener('keyup',self.selectVariable);
   },
}
</script> 
<style scope>
#designer-nav{
    width: 18%;
}
.fixed{
    position: fixed;
    height: 78%;
    overflow: auto;
    top: 80px;
    left: 30px;
}
</style>
