<template>
  <ifbp-page>
    <ifbp-breadcrumb name="打印模板"></ifbp-breadcrumb>
    <!--search-->
    <ifbp-button-area>
      <el-button type="primary"  class="fl" v-if="!isAdd" @click="add">新增</el-button>
      <el-button type="primary" class="fl" v-if="!isEdit" @click="edit">修改</el-button>
      <el-button type="primary" class="fl" v-if="showBtn" style="margin-right: 20px;" @click="save">保存</el-button>
      <el-button type="primary" class="fl" v-if="showBtn" @click="cancel">取消</el-button>
      <el-button type="text" class="fr" v-if="!isAdd" @click="showSearch">
        高级搜索
        <i class="el-icon-arrow-down" v-if="this.isHide"></i>
        <i class="el-icon-arrow-up" v-if="!this.isHide"></i>
      </el-button>
      <el-button v-if="!isEdit" type="primary" class="fr" @click="goBackInfo">返回</el-button>
    </ifbp-button-area>

    <div id="advanced-search" :class="{hide: isHide}">
      <el-row>
        <el-col :span="2"><span class="search-label">编码:</span></el-col>
        <el-col :span="3">
          <el-input type="text" v-model="search_data.templatecode" placeholder="请输入编码"></el-input>
        </el-col>
        <el-col :span="2"><span class="search-label"> 名称:</span></el-col>
        <el-col :span="3">
          <el-input type="text" v-model="search_data.templatename" placeholder="请输入名称"></el-input>
        </el-col>
        <el-col :span="2"><span class="search-label"> 启用状态:</span></el-col>
        <el-col :span="4">
          <el-select id="s-state" v-model="search_data.enablestate">
            <el-option
              v-for="item in search_enablestate"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="2"><span class="search-label"> 打印类型:</span></el-col>
        <el-col :span="4">
          <el-select id="s-state" v-model="search_data.printtype">
            <el-option
              v-for="item in search_printTypeData"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <div class="fr">
          <el-button @click="search">搜索</el-button>
        </div>
      </el-row>
    </div>

    <div id="staff-detail" style="font-size: 0px;" v-show="!isAdd">
      <div id="app-container">
        <el-tree
          style="height: 400px;overflow: auto;"
          accordion
          :props="defaultProps"
          :load="loadNode"
          lazy
          :highlight-current="true"
          @current-change="handleAppChange"
        >
        </el-tree>
      </div>
      <div id="tpl-container" style="height: 400px; position:relative;">
        <el-table
        :max-height="400"
        :data="tableData"
        border
        style="width: 100%">
          <el-table-column
            v-for="column in tableColumn"
            :prop="column.prop"
            :label="column.title"
            v-if="column.display"
            ></el-table-column>
          <el-table-column
            prop="pubscene_name"
            label="模型视图"
            :filters="pubsceneFilters"
            :filter-method="filterPubscene"
            filter-placement="bottom-end">
            <template scope="scope">
            {{scope.row.pubscene_name}}
            </template>
          </el-table-column>
          <el-table-column
            v-for="column in tableColumn1"
            :prop="column.prop"
            :label="column.title"
            v-if="column.display"
            ></el-table-column>
          <el-table-column
            label="操作"
            width="140">
            <template scope="scope">
              <el-tooltip class="item" effect="dark" placement="top-start" content="设计">
                <i class="el-icon-setting" type="primary" @click="designerTpl(scope)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" placement="top-start" content="启用状态">
                <i class="el-icon-pt-tuichu" type="primary" @click="enabledTpl(scope)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" placement="top-start" content="查看">
                <i class="el-icon-search" type="primary" @click="checkTpl(scope)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" placement="top-start" content="查看">
                <i class="ifbp-icon-print" type="primary" @click="preview(scope.row)"></i>
              </el-tooltip>
              <!-- <el-tooltip class="item" effect="dark" placement="top-start" content="转换为Word">
                <i class="el-icon-upload" type="primary" @click="downloadToWord(scope.row)"></i>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" placement="top-start" content="转换为PDF">
                <i class="el-icon-document" type="primary" @click="downloadToPDF(scope.row)"></i>
              </el-tooltip> -->
              <!-- <el-tooltip class="item" effect="dark" placement="top-start" content="单据预览">
                <i class="el-icon-pt-chakan" type="primary" @click="prview(scope)"></i>
              </el-tooltip> -->
              <el-tooltip class="item" effect="dark" placement="top-start" content="删除">
                <i class="el-icon-delete" type="primary" @click="deleteTpl(scope)"></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <div id="edit-container" v-if="showTemplate">
      <div id="form-container">
        <el-form
          :model="currentTpl"
          label-width="100px"
          ref="currentTplForm"
          :rules="rules">
          <el-form-item label="业务类型：">
            <el-button v-model="currentTpl.code" type="text" v-if="!isEdit">{{currentTpl.bo_code}}</el-button>
            <el-button v-model="currentTpl.code" type="text" v-else>{{currentApp.name}}</el-button>
          </el-form-item>
          <el-form-item label="编码："
            prop="templatecode">
            <el-button type="text" v-model="currentTpl.templatecode" v-if="!isEdit">{{currentTpl.templatecode}}</el-button>
            <el-input v-model="currentTpl.templatecode" v-if="showTemplateCode">{{currentTpl.templatecode}}</el-input>
          </el-form-item>
          <el-form-item label="名称："
            prop="templatename">
            <el-button type="text" v-model="currentTpl.templatename" v-if="!isEdit">{{currentTpl.templatename}}</el-button>
            <el-input v-model="currentTpl.templatename" v-else>{{currentTpl.templatename}}</el-input>
          </el-form-item>
          <el-form-item label="模型视图："
            prop="pk_pubscene">
            <el-button type="text" v-model="currentTpl.pubscene_name" v-if="!isEdit">{{currentTpl.pubscene_name}}</el-button>
            <el-ref 
                    v-else
                    :is-muti-select="false"
                    :ref-code="'pubscence_ref'"
                    :field="'pk_pubscene'"
                    :template-value="currentTpl"
                    :query-params="queryParams"
                    width="300px"
                    :is-edit="true">
            </el-ref>
          </el-form-item>
          <el-form-item label="打印类型：">
            <el-button type="text" v-model="currentTpl.printtype" v-if="!isEdit">{{currentTpl.printtype}}</el-button>
            <el-select v-model="currentTpl.printtype" v-else>
              <el-option
                v-for="item in printTypeData"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="备注：">
            <el-button type="text" v-model="currentTpl.note" v-if="!isEdit">{{currentTpl.note}}</el-button>
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 5}"
            placeholder="请输入内容" v-model="currentTpl.note" v-else>{{currentTpl.note}}</el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
</ifbp-page>
</template>

<script>

export default {
  watch:{
    isAdd:function(){
      if(this.isAdd === true){
        this.showTemplateCode = true;
      } else {
        this.showTemplateCode = false;
      }
    },
    isEdit: function(){
      if(this.isEdit === false){
        this.showTemplateCode = false;
      } else {
        this.showTemplateCode = true;
      }
    }
  },
  data(){
    return {
      queryParams: {
        busitypecode: ''
      },
      currentScope: '',
      editTemplate: false,
      showTemplate: false,
      showTemplateCode: true,
      currentRowScope:'',
      pubsceneFilters:[],
      appClickData: '',//选中节点的数据
      treeData: [],
      tableData: [],
      tplTree: [],
      search_printTypeData: [
        {
          label: '全部',
          value: ''
        },
        {
          label:'标准（单据、套打等）',
          value:'1'
        },{
          label:'长文档（合同）',
          value: '2'
        }
      ],
      printTypeData: [
        {
          label:'标准（单据、套打等）',
          value:'1'
        },{
          label:'长文档（合同）',
          value: '2'
        }
      ],
      isHide: true,
      showBtn: false,
      isAdd: false,
      isEdit: true,
      search_data:{
        templatecode: '',
        templatename: '',
        printtype: '',
        enablestate: '',
      },
      search_enablestate:[
        {
          label: '全部',
          value: ''
        },
        {
          label:'启用',
          value:'2',
        },{
          label:'停用',
          value:'3',
        }
      ],
      currentTpl: {
        code: '',
        templatecode: '',
        templatename: '',
        pk_pubscene: '',
        pubscene_name: '',
        printtype: '',
        note: '',
      },
      defaultProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'leaf'
      },
      currentApp: '', //选中节点的数据
      tableColumn: [{
        title: '编码',
        prop: 'templatecode',
        display: true
      },{
        title: '名称',
        prop: 'templatename',
        display: true
      }],
      tableColumn1: [{
        title: '打印类型',
        prop: 'printtype',
        display: true
      },{
        title: '启用状态',
        prop: 'enablestate',
        display: true
      },{
        title: '创建时间',
        prop: 'createTimeForDisplay',
        display: true
      },{
        title: '创建人',
        prop: 'createby',
        display: true
      },{
        title: '修改时间',
        prop: 'modifyTimeForDisplay',
        display: true
      },{
        title: '修改人',
        prop: 'modifiedby',
        display: true
      }],
      rules:{
        templatecode:[
          { required: true, message: '请输入模板编码', trigger: 'blur' }
        ],
        templatename:[
          { required: true, message: '请输入模板名称', trigger: 'blur'}
        ],
        pk_pubscene:[
          { required: true, message: '请选择模型视图', trigger: 'change'}
        ]
      }
    };
  },
  methods:{
   
    // 高级搜索
    showSearch() {
      this.isHide = !this.isHide;
    },
    search(){
      const self = this;
      var template = {
        template: this.search_data
      };
      this.$http({
            url:'/ifbp-print/rest/printTemplate/searchPrint',
            method:'post',
            contentType: 'application/x-www-form-urlencoded',
            data: 'data='+ JSON.stringify(template)
          }).then((res) => {
            if(res.data.success === true && res.data.data.length !== 0){
              self.addType(res.data.data);
              self.tableData = res.data.data;
            } else if(res.data.success === true && res.data.data.length === 0){
              self.$message('未查询到相关数据');
              self.tableData = res.data.data;
            }
          }).catch((res) => {
            self.$message.error("请求失败");
          });
    },
    filterPubscene(value,row){
      return row.pubscene_name === value;
    },
    getPubscence(){
      var protocol = window.location.protocol;
      var host = window.location.host;
      const self = this;
        this.$http({
          url: '/uitemplate_web/iref_ctr/commonRefsearch',
          method:'post',
          // data:'refModelUrl=http://dev-ap.iservice.imfbp.com/ifbp-app-sm-infoset-web/infoset/pubscence_ref/'          
          data:'refModelUrl=' + protocol+'//' + host +'/ifbp-app-sm-infoset-web/infoset/pubscence_ref/'
        }).then((res) => {
          if(res.data.data) {
            var data = JSON.parse(JSON.stringify(res.data.data));
            data.forEach((value) => {
              self.$set(value,'text',value.refname);
              self.$set(value,'value',value.refname);
            });
            this.pubsceneFilters = data;

          } else {
            this.$message.error('获取模型视图失败');
          }
          this.search();
        }).catch(() => {
          this.$message.error('请求出错');
        });
    },
    loadNode(node, resolve){
      if(node.level === 0) {
        this.$http({
          url: '/ifbp-app-sm/buz/products'
        }).then((res) => {
          if(res.data.success === true) {
            resolve(res.data.data);
          } else {
            this.$message.error('请求失败');
          }
        }).catch(() => {
          this.$message.error('请求出错');
        });
      } else if(node.level === 1) {
        this.$http({
          url: '/ifbp-app-sm/buz/product/' + node.data.pid + '/models'
        }).then((res) => {
          if(res.data.success === true) {
            resolve(res.data.data);
          } else {
            this.$message.error('请求失败');
          }
        }).catch(() => {
          this.$message.error('请求出错');
        });
      } else if(node.level === 2) {
        this.$http({
          url: '/ifbp-app-sm/buz/product/' + node.data.pid + '/model/' + node.data.mid + '/buzitypes'
        }).then((res) => {
          if(res.data.success === true) {
            for(var i=0;i<res.data.data.length;i++) {
              res.data.data[i].leaf = true;
            }
            resolve(res.data.data);
          } else {
            this.$message.error('请求失败');
          }
        }).catch(() => {
          this.$message.error('请求出错');
        });
      }
    },
    handleAppChange(value) {
      if(value.leaf) {
        this.currentApp = value;
        this.currentTpl.code = value.code;
        this.$http({
          url: '/ifbp-print/rest/printCodeRelation/getRelationByCode?code='+ value.code,
          method: 'post'
        }).then((res) => {
          if(res.data.success === true) {
            this.addType(res.data.data);
            this.tableData = res.data.data;
          }else {
            this.$message.error('请求失败');
          }
        }).catch(() => {
          this.$message.error('请求失败');
        });
      } else {
        this.currentApp = '';
      }
    },
    // 时间戳转换为日期格式
    changeData(value){
      var date = new Date(value);
      var Y,M,D,h,m,s;
      Y = date.getFullYear() + '-';
      M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
      D = date.getDate() + ' ';
      h = date.getHours() + ':';
      m = date.getMinutes() + ':';
      s = date.getSeconds();
      return Y+M+D+h+m+s;
    },
    //转换时间，打印类型和启用状态
    addType(data) {
      data.forEach((v) => {
        if (v.createtime) {
          this.$set(v, 'createTimeForDisplay', this.changeData(v.createtime.time));
        }
        // var pubsceneFilters = JSON.parse(JSON.stringify(this.pubsceneFilters));
        this.pubsceneFilters.forEach((value) => {
          if(v.pk_pubscene === value.id){
            this.$set(v,'pubscene_name',value.refname);
          }
        });
        if(v.printtype === '1'){
          this.$set(v,'printtype','标准（单据、套打等）');
        } else if(v.printtype === '2'){
          this.$set(v,'printtype','长文档（合同）');
        }
        if(v.enablestate === '3'){
          this.$set(v,'enablestate','已停用');
        } else if(v.enablestate === '2'){
          this.$set(v,'enablestate','已启用');
        }
        if (v.modifiedtime) {
          this.$set(v, 'modifyTimeForDisplay', this.changeData(v.modifiedtime.time));
        }
      });
    },
    handleTplChange(value) {
      if(!value.forms) {
        this.currentTpl = value;
      } else {
        this.currentTpl = '';
      }
    },
    backInfo() {
      this.showTemplate = false;
      this.showBtn = false;
      this.isAdd = false;
      this.isEdit = true;
      this.showTemplateCode = false;
      this.$router.push('/appArea');
    },
     goBackInfo(){
      this.showTemplate = false;
      this.showBtn = false;
      this.isAdd = false;
      this.isEdit = true;
      this.showTemplateCode = false;
      this.editTemplate = false;
      this.currentTpl = {
                  code: '',
                  templateCode: '',
                  templateName: '',
                  templateScene: '',
                  templateDescription: ''
                };
      this.$router.push('/printTemplate');
    },
    save() {
      const self = this;
      var template = {};
      this.$refs.currentTplForm.validate((valid) => {
        var addTemplate = {
          template:{
            templatecode: self.currentTpl.templatecode,
            templatename: self.currentTpl.templatename,
            pk_printtemplatetype:"48a8206f-6759-431e-bf84-e973935e2fcc",
            bo_code: self.currentTpl.code,
            note: self.currentTpl.note,
            printtype: self.currentTpl.printtype,
            pk_pubscene: self.currentTpl.pk_pubscene,
            busiCode: self.currentApp.code,
            sceneCode: self.currentTpl.beanMap.pk_pubscene_ref[self.currentTpl.pk_pubscene].refcode
          }
        };
        var editTemplate = {
          template:{
            pk_print_template: self.currentRowScope.pk_print_template,
            templatename: self.currentTpl.templatename,
            note: self.currentTpl.note,
            printtype: self.currentTpl.printtype,
            pk_pubscene: self.currentTpl.pk_pubscene,
            busiCode: self.currentApp.code || self.currentTpl.bo_code,
            sceneCode: self.currentTpl.beanMap.pk_pubscene_ref[self.currentTpl.pk_pubscene].refcode || self.currentTpl.metadata_code
          }
        };
        if(self.editTemplate === false){
          template = addTemplate;
        } else if(self.editTemplate === true){
          template = editTemplate;
        }
        if(editTemplate.template.printtype === '标准（单据、套打等）'){
          editTemplate.template.printtype = '1';
        } else if(editTemplate.template.printtype === '长文档（合同）'){
          editTemplate.template.printtype = '2';
        }
        if(valid){
          this.$http({
            url:'/ifbp-print/rest/printTemplate/saveprint',
            method:'post',
            contentType: 'application/x-www-form-urlencoded',
            data: 'data='+ JSON.stringify(template)
          }).then((res) => {
            if(res.data.success === true){
              self.isAdd = false;
              self.showBtn = false;
              self.showTemplate = false;
              self.currentTpl = {
                  code: '',
                  templateCode: '',
                  templateName: '',
                  templateScene: '',
                  templateDescription: '',
                  printtype:'',
                };
                if(self.editTemplate === true){
                  self.editTemplate = false;
                  self.$set(self.tableData,self.currentScope.$index,JSON.parse(res.data.printVO));
                  self.addType(self.tableData);
                  self.$message({
                    type:'success',
                    message: '修改成功'
                  });
                } else{
                  self.tableData.push(JSON.parse(res.data.templateVO));
                  self.addType(self.tableData);
                  self.$message({
                    type: 'success',
                    message: '保存成功'
                  });
                }
            }else if(res.data.success === false){
              self.$message({
                type:'error',
                message: res.data.msg
              });
            }
          }).catch((res) => {
            this.$message.error('请求失败');
          });
        }
      })
    },
    add() {
      if(this.currentApp === '') {
        this.$message('请选择有效的业务类型');
      } else {
        this.queryParams.busitypecode = this.currentApp.code;
        this.isAdd = true;
        this.showBtn = true;
        this.isHide = true;
        this.showTemplateCode = true;
        this.showTemplate = true;
        this.editTemplate === false;
      }
    },
    edit() {
      this.isEdit = true;
      this.showBtn = true;
      this.showTemplateCode = false;
      this.editTemplate = true;
    },
    designerTpl(scope){
      if(scope.row.printtype === '标准（单据、套打等）'){
        var templateCode = scope.row.templatecode;
        var params = JSON.stringify({
          template: templateCode,
          tenantId: this.tenantId
        });
        var url = '/ifbp-print/static/html/iprint/preview.html?tenantId='+this.tenantId+'&template='+templateCode+'&printcode='+templateCode+'&serverUrl='+window.location.protocol+'//'+window.location.host+'/ifbp-print/rest/print/getdata&params='+params+'&sendType=2';
        window.open(url);
        // window.open('/print-demo/reomote/adddesign?tenantId=' + this.tenantId + '&printcode=' + scope.row.templatecode +'&encode=' + scope.row.templatename);
      } else if(scope.row.printtype === '长文档（合同）'){
        this.$router.push('/printTemplate/printDesigner');
        window.localStorage.setItem('currentTpl',JSON.stringify(scope.row));
      }
      // this.$router.push('/printTemplate/printDesigner');
      // window.localStorage.setItem('currentTpl',JSON.stringify(scope.row));
    },
    getCookie() {
        var reg = new RegExp("(^| )tenantid=([^;]*)(;|$)");
        var arr = document.cookie.match(reg);
        if (arr) {
          this.tenantId = arr[2];
        }
    },
    // prview(scope){
    //   var protocol = window.location.protocol;
    //   var host = window.location.host;
    //   let data = JSON.parse(JSON.stringify(scope.row));
    //   let params={"template":scope.row.templatecode,"tenantId":this.tenantId}
    //   if(scope.row.printtype === '标准（单据、套打等）'){
    //     window.open('/print-demo/template/preview?tenantId=' + this.tenantId + '&template='+scope.row.templatecode+'&printcode='+scope.row.templatecode +'&serverUrl='+protocol+'//'+host+'/print-demo/template/getdata&params='+params+'&sendType=2');
    //     // window.open('/print-demo/remote/preview?tenantId=' + this.tenantId + '&template='+scope.row.templatecode+'&printcode='+scope.row.templatecode +'&serverUrl=http://dev-ap.iservice.imfbp.com/print-demo/template/getdata&params={"template":"T1510362878602","tenantId":"sv3c1td6"}&sendType=2');
    //   } else if(scope.row.printtype === '长文档（合同）'){
    //     this.$message({
    //       type: 'error',
    //       message: '当前为长文档（合同）模板，不能预览，请选择转换为Word和PDF'
    //     });
    //     return;
    //   }
    // },
    checkTpl(scope){
      this.queryParams.busitypecode = scope.row.bo_code;
      const self = this;
      this.isEdit = false;
      this.isAdd = true;
      this.isHide = true;
      this.showTemplateCode = false;
      this.showTemplate = true;
      this.currentScope = scope;
      var beanMap = {
        "pk_pubscene_ref": {}
      };
      beanMap.pk_pubscene_ref[scope.row.pk_pubscene] = {
        name: scope.row.pubscene_name,
        id: scope.row.pk_pubscene
      };
      this.currentRowScope = JSON.parse(JSON.stringify(scope.row));
      this.currentTpl = JSON.parse(JSON.stringify(scope.row));
      this.$set(this.currentTpl,'beanMap',beanMap);
      var app = JSON.parse(JSON.stringify(scope.row));
      app.name = app.bo_code;
      if(!this.currentApp){
        this.currentApp = app;
      }
    },
    enabledTpl(scope){
      const self = this;
      var enablestate;
      var rowData = JSON.parse(JSON.stringify(scope.row));
        if(rowData.enablestate === '已停用'){
          enablestate='3';
        }
        if(rowData.enablestate === '已启用'){
          enablestate='2';
        }
      var template = {
        template:{
          pk_print_template: rowData.pk_print_template,
          pk_pubscene: rowData.pk_pubscene,
          enablestate: enablestate
        }
      };
      this.$http({
        url: '/ifbp-print/rest/printTemplate/updateEnablestate',
        method:'post',
        contentType: 'application/x-www-form-urlencoded',
        data: 'data='+ JSON.stringify(template)
      }).then((res) => {
        if(res.data.success === true) {
          self.$message(res.data.msg);
          if(enablestate === '2'){
            self.$set(scope.row,'enablestate','已停用');
          }
          if(enablestate === '3'){
            self.$set(scope.row,'enablestate','已启用');
          }
        } else{
          self.$message({
            type: 'error',
            message: res.data.errorMsg
        });
        }
      }).catch(() => {
        self.$message({
          type: 'error',
          message: '请求出错'
        });
      });
    },
    deleteTpl(scope){
      const self = this;
      this.$http({
        url: '/ifbp-print/rest/printTemplate/deleteprint?pk_print_template=' + scope.row.pk_print_template,
        method:'get',
      }).then((res) => {
        if(res.data.success === true) {
          self.tableData.splice(scope.$index,1);
          self.$message({
            type: 'success',
            message: '删除成功'
          });
        }
      }).catch(() => {
        self.$message({
          type: 'error',
          message: '删除失败'
        });
      });
    },
    requestTplTree() {
      this.$http({
        url: '/uitemplate_web/uitemplate_ctr/uitemplate_design_ctr/queryUITemplateList',
        method: 'post',
        contentType: 'application/x-www-form-urlencoded',
        data: 'data=' + encodeURIComponent('{"tenant_id":"","type":"sys"}')
      }).then((res) => {
        this.tplTree = res.data.formCategories;
      }).catch(() => {
        this.$message.error('请求失败');
      });
    },
    preview(row){
      if(row.printtype === '标准（单据、套打等）'){
        this.$message({
          type: 'error',
          message: '当前为标准（单据、套打等）模板，请选择长文本(合同)'
        });
        return;
      } else if(row.printtype === '长文档（合同）'){
        if(row.template_content){
          // 只返回启用模板
          // window.open('/ifbp-print/static/html/iprint/businessPreview.html?serverUrl='+window.location.protocol+'//'+window.location.hostname+'/ifbp-print/rest/printTemplate/replaceTemplateByGet&busicode='+row.bo_code+'&scenecode='+row.metadata_code+'&pk=wbalone10000000s2sx');
          // 是用元数据,返回模板编码
          window.open('/ifbp-print/static/html/iprint/businessPreview.html?serverUrl='+window.location.protocol+'//'+window.location.hostname+'/ifbp-print/rest/printTemplate/replaceTemplateByPk?pk_print_template='+row.pk_print_template+'&pk=wbalone10000000s2sx');
          // window.open('/ifbp-print/static/html/iprint/businessPreview.html?serverUrl=http://dev-ap.iservice.imfbp.com/ifbp-print/rest/printTemplate/replaceTemplateByPk?pk_print_template='+row.pk_print_template+'&pk=wbalone10000000s2sx');
          // 测试mydata,模板testKHGL4
          // var template = [{'id':'1234','num':'100','pname':'用户','childreninfo_id':[{'name':'张三','sex':'男'},{'name':'李四','sex':'女'},{'name':'王五','sex':'男'}]}];
          // window.open('/ifbp-print/static/html/iprint/businessPreview.html?serverUrl=http://dev-ap.iservice.imfbp.com/ifbp-print/rest/printTemplate/replaceTemplateByCodeAndMydata?pk_print_template='+row.pk_print_template+'&mydata='+encodeURIComponent(JSON.stringify(template)));
        } else {
          this.$message({
            type: 'error',
            message: '当前模板还没有内容，请添加内容'
          });
        }
      }
    },
    downloadToWord(row){
      let data = JSON.parse(JSON.stringify(row));
      if(row.printtype === '标准（单据、套打等）'){
        this.$message({
          type: 'error',
          message: '当前为标准（单据、套打等）模板，不能转换Word'
        });
        return;
      } else if(row.printtype === '长文档（合同）'){
        if(row.template_content){
          // var storage = window.localStorage;
          // storage.setItem('templatecode', row.templatecode);
          window.open('/print-demo/webapp/translate_to_word/translateword.html?pk_print_template='+row.pk_print_template+'&busicode='+row.bo_code+'&scenecode='+row.metadata_code+'&pk=wbalone10000000s2sx');
        } else {
          this.$message({
            type: 'error',
            message: '当前模板还没有内容，请添加内容'
          });
        }
      }
    },
    downloadToPDF(row){
      if(row.printtype === '标准（单据、套打等）'){
        this.$message({
          type: 'error',
          message: '当前为标准（单据、套打等）模板，不能转换PDF'
        });
        return;
      } else if(row.printtype === '长文档（合同）'){
        if(row.template_content){
          // var submitData ={
          //   pk_print_template: row.pk_print_template,
          //   busicode: row.bo_code,
          //   scenecode: row.metadata_code,
          //   pk: "wbalone10000000s2sx"
          // };
          window.open('/print-demo/webapp/translate_to_pdf/translatepdf.html?pdfUrl=/ifbp-print/rest/printTemplate/htmlToPDFLoopTemplate?pk_print_template='+row.pk_print_template+'&busicode='+row.bo_code+'&scenecode='+row.metadata_code+'&pk=wbalone10000000s2sx');          
          // this.$http({
          //   url: '/ifbp-print/rest/printTemplate/htmlToPDFLoopTemplate',
          //   method: 'post',
          //   data: submitData
          // }).then((res) => {
          //   debugger;
          //   if(res.data.success === 'true'){
          //     window.open('/print-demo/webapp/translate_to_pdf/translatepdf.html?pdfUrl=/ifbp-print/rest/printTemplate/PDFDownload?templateCode='+ row.pk_print_template);
          //   } else{
          //     this.$message({
          //       type: 'error',
          //       message: '转换PDF失败'
          //     });
          //   }
          // }).catch(() => {
          //   this.$message({
          //     type: 'error',
          //     message: '接口调用出错'
          //   });
          // });
        } else{
          this.$message({
            type: 'error',
            message: '当前模板还没有内容，请添加内容'
          });
        }
      }
    },
    deleteRow(row) {
      this.$confirm('确定删除关联?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: '/wbalone/uitemplatenexusbase/delete/' + row.pkNexus,
            method: 'post'
          }).then((res) => {
            this.tableData.splice(this.tableData.indexOf(row), 1);
            if(res.data.status === 1) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
            } else {
              this.$message({
                type: 'error',
                message: res.data.msg
              });
            }
          }).catch(() => {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          });

        });
    },
    closeDialog() {
    },
    confirm() {
      if (this.currentTpl.code === '') {
        this.$message('请选择有效的业务类型');
      } else {
        this.$http({
          url: '/wbalone/uitemplatenexusbase/create',
          method: 'post',
          data: {
            pkTemp: this.currentTpl.id,
            nexuskey: this.dialogForm.nexuskey,
            funnode: this.currentApp.code
          }
        }).then((res) => {
          if(res.data.status === 1) {
            this.dialogVisible = false;
            res.data.data.type = 'UI模板';
            this.tableData.push(res.data.data);
          } else {
            this.$message.error(res.data.message);
          }
        }).catch(() => {
          this.$message.error('请求失败');
        });
      }
    },
    cancel() {
      if(this.editTemplate === true){
        this.isEdit = false;
        this.showBtn = false;
      } else{
        this.isAdd = false;
        this.isEdit = true;
        this.showBtn = false;
        this.showTemplateCode = false;
        this.showTemplate = false;
        this.editTemplate = false;
        this.resetForm();
      }
    },
    resetForm() {
      Object.keys(this.currentTpl).forEach((key) => {
        this.currentTpl[key] = '';
      });
    },
    // request() {
    //   this.$http({
    //     url: '/ifbp-print/rest/bomanage/querybyapptetant'
    //   }).then((res) => {
    //     this.printTypeData = res.data;
    //   }).catch(() => {
    //     this.$message.error('请求失败');
    //   });
    // },
    
  },
  created(){
    this.getCookie();
    this.getPubscence();
    // this.request();
  }
};
</script>

<style scoped>
.printTemplate{
  padding: 20px;
}

#edit-container {
  margin-top: 20px;
  background: #ffffff;
  position: relative;
  padding: 0 20px;
  height: 400px;
}
#appTplAuth-container {
  padding: 15px;
  font-size: 0px;
}

#form-container {
  width: 40%;
  margin-left: 30%;
  padding-top: 50px;
}

#app-container {
  display: inline-block;
  width: calc(20% - 20px);
  font-size: 14px;
  vertical-align: top;
  margin-top: 20px;
  margin-right: 20px;
}

#tpl-container {
  display: inline-block;
  width: 80%;
  font-size: 14px;
  height: 400px;
  background-color: white;
  vertical-align: top;
  margin-top: 20px;
}

#authApp-tpl-tree {
  display: inline-block;
  width: calc(30% - 2px);
  font-size: 14px;
  vertical-align: top;
}

#authApp-dialog-form {
  display: inline-block;
  width: calc(70% - 2px);
  font-size: 14px;
  vertical-align: top;
}
</style>
<style>
.printTemplate .el-table .cell, .el-table th>div{
  padding: 0 5px;
}
</style>

