<template>
  <ifbp-page>
    <!-- 节点title -->
    <ifbp-breadcrumb name="UI模板管理"></ifbp-breadcrumb>
    <!-- 按钮区域 -->
    <ifbp-button-area>
      <div class="fl">
        <el-button type="primary" @click="add" slot="toolbar">新增</el-button>
      </div>
        <div class="fr">
          <!-- 查询模板组件 -->
          <ifbp-search 
            :template-code="searchCode"
            @search="handleSearch">
          </ifbp-search>
      </div>   
    </ifbp-button-area>
		<!-- 主体区域 -->
    <ifbp-main-area type="list">
      <div class="ifbp-btn-line">
        <div class="fl">
          <el-cascader
            v-if="treeTableTree && treeTableTree.length"
            ref="treeCascader"
            class="uiFilterCascader"
            expand-trigger="hover"
            popper-class="treeCascaderMenu"
            :change-on-select="false"
            :show-all-levels="true"
            :options="treeTableTree"
            v-model="selectedTreeNode"
            placeholder="业务类型"
            @change="handleTreeChange">
          </el-cascader>
        </div>
        <div class="fr">
          <ifbp-table-card-icon :show-table="showTable" @update:showTable="value => this.showTable = value">
          </ifbp-table-card-icon><i class="ifbp-icon-setting" :class='{"disabled":!showTable}' @click="showHeaderSetting" title="设置"></i>
        </div>
      </div>
      <el-table :data="tableData" border style="width: 100%" :table-show-menu="false" v-show="showTable" class="ui-table">
        <el-table-column
          v-for="column in tableColumn"
          :prop="column.prop"
          :label="column.title"
          align="right"
          v-if="column.display"
          >
        </el-table-column>
        <el-table-column
          label="操作"
          align="right"
          >
          <template scope="scope">
            <i class="ifbp-icon-delete" type="primary" @click="deleteRow(scope.row)" title="删除"></i>
            <i class="ifbp-icon-menu" type="primary" @click="openDesigner(scope.row)" title="设计模板"></i>
          </template>
        </el-table-column>
      </el-table>
      <!-- 卡片 -->
      <ifbp-ui-tpl-mgr-card
        v-show="!showTable"
        :card-data="cardData"
        @cardDeleteClick="deleteRow"
        @cardDesignerClick="openDesigner"
      ></ifbp-ui-tpl-mgr-card>
      <!-- <ul class="cardArea" v-if="cardData && cardData.length && !showTable">
        <li
          v-for="(column,index) in cardData"
        > 
          <div class="cardContent">
            <div class="mainArea">
              <div class="fl lArea">
                <span>{{column.funnode}}</span>
                <h3 :title="column.tempFormName">{{column.tempFormName}}</h3>
                <span>{{column.nexuskey}}</span>
              </div>
              <div class="rArea">
                <label></label>
                <i class="ifbp-icon-page"></i>
              </div>
            </div>
            <div class="btnArea">
              <i class="ifbp-icon-delete" @click='tabFn("delete",index)' title="删除"></i>
              <i class="ifbp-icon-menu" @click='tabFn("designer",index)' title="设计模板"></i>
            </div>
          </div>
        </li>
      </ul> -->
		</ifbp-main-area>
	  <el-dialog title="创建UI模板" 
      :modal="false" 
      :visible.sync="dialogVisible" 
      :before-close="cancel"
      >
        <div class="authApp-dialog-form">
          <el-form :model="dialogForm" label-width="100px" :rules="rules" ref="addForm">
            <el-form-item label="模板名称:" prop="tempform_name">
              <el-input v-model="dialogForm.tempform_name"></el-input>
            </el-form-item>
            <el-form-item label="模板标识:" prop="nexuskey">
              <el-input v-model="dialogForm.nexuskey"></el-input>
            </el-form-item>
            <el-form-item label="元数据:">
                <el-ref :is-muti-select="false"
                        :ref-code="'md_class_ref'"
                        :field="'md_metadata'"
                        :template-value="dialogForm"
                        @trigger="refChangFun"
                        width="300px"
                        :is-edit="true">
                </el-ref>
            </el-form-item>
            <!-- <template v-if="false">
            <el-form-item label="模板选择">
              <el-input v-model="dialogForm.a"></el-input>
            </el-form-item>
            <el-form-item label="所属模块">
              <el-input v-model="dialogForm.b"></el-input>
            </el-form-item>
            <el-form-item label="所属行业">
              <el-input v-model="dialogForm.pkIndustry"></el-input>
            </el-form-item>
            <el-form-item label="国家/地区">
              <el-input v-model="dialogForm.pkCountry"></el-input>
            </el-form-item>
            <el-form-item label="资产层次">
              <el-input v-model="dialogForm.layer"></el-input>
            </el-form-item>
          </template> -->
          </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
		</el-dialog>
    </ifbp-page>

</template>
<script>
import ifbpUiTplMgrCard from './ifbp-ui-tpl-mgr-card'
// import  MdLayout from '../../test/mdlayout.vue'
// import  MdPage from '../../test/mdpage.vue'
export default {
  components:{
    ifbpUiTplMgrCard
  },
  data(){
    return {
      // 查询模板传入参数
      searchCode: "UIMBGL",
      searchData: "",
      selectedTreeNode: [],
      selectedOptions: [],
      products:[],
      formData:{},
      currentProduct:"",
      currentTitle:"",
      treeData: [],
      tableData: [],
      tplTree: [],
      dialogForm: {
        tempform_name:'', // UI模板名称
        nexuskey: '',//节点标示
        md_metadata:'', //元数据主建
        pkIndustry: '',//所属行业
        pkCountry: '',//国家/地区
        layer: '',//资产层次
        formData:{
          "form":{
            // "pkMetadata":'',
            // "pkClass":'',
            // "sysflag":"Y",
            // "name":''
          }
        }
      },
      rules:{
        tempform_name:[{required:true,message:'模板名称不能为空', trigger: 'blur' }],
        nexuskey:[{required:true,message:'模板标识不能为空', trigger: 'blur' }]
      },
      currentApp: '',
      // currentTpl: '',
      dialogVisible: false,
      tableColumn: [{
        title: '业务类型',
        prop: 'funnode',
        display: true,
        width:100
      },{
        title: 'pk_temp',
        prop: 'pk_temp',
        display: true,
        width:350
      },{
        title: '模板名称',
        prop: 'tempFormName',
        display: true
      },{
        title: '模板标识',
        prop: 'nexuskey',
        display: true
      }],
      defaultProps: {
          children: 'children',
          label: 'name'
      },
      treeTableTree:[],
	  //搜索
	  isHide: true,
    searchStr: {
      name: ''
    },
    //卡片列表切换
    showTable: true,
    cardData:[]
  }
},
methods:{
  showSearch() {
    this.isHide = !this.isHide;
  },
  // 查询区点击搜索后的处理
  handleSearch(searchData) {
    if (!searchData) {
      return;
    }
    this.searchData = searchData;
    this.request();
  },
  search() {
    this.handleAppChange(this.currentApp);
  },
  refChangFun(type,data){
    if(type === 'change'){
      // console.log(data["md_metadata"]);
        this.dialogForm.formData.form.pkMetadata = data.value[0].pid;
        this.dialogForm.formData.form.pkClass = data.value[0].id;
        this.dialogForm.formData.form.sysflag = "Y";
        this.dialogForm.formData.form.name = this.dialogForm.tempform_name;
    }
  },
  request(){
    var oThis = this;
    this.$http({
      url:'/ifbp-app-sm/buz/display'
    }).then((res) => {
      if(res.data.success === true) {
        oThis.treeData = res.data.data;
      let fotmated = oThis.formatTreeLabel(oThis.treeData);
      oThis.treeTableTree=fotmated;
      } else {
        oThis.$message.error('请求失败');
      }
    }).catch((e) => {
      console.log(e);
      oThis.$message.error('请求出错');
    });
  },
  openDesigner(row){
    window.open('/uitemplate_web/index.html?pk_temp=' + row.pk_temp );
  },
  handleTreeChange(data){
    this.currentApp = data[data.length-1];
    this.handleAppChange(this.currentApp);
  },
  handleAppChange(treeItem) {
    //this.currentTitle = treeItem.label;
    this.$http({
      url:'/ifbp-app-sm/sm/uitemplate/getByFunnode?funNode=' + this.currentApp,
      method: 'get'
      // data:{
      //   funNode:treeItem.code
      // }
    }).then((res) => {
      this.tableData = res.data.data;
      this.cardData=res.data.data;
      // this.addType(this.tableData);
    }).catch(() => {
      this.$message.error('请求失败');
    });
    // else {
    //   this.currentApp = '';
    // }
  },
  // addType(data) {
  //   data.forEach((v) => {
  //     this.$set(v, 'type', 'UI模板');
  //   });
  // },
  // handleTplChange(value) {
  //   console.log(value);
  //   if(!value.forms) {
  //     this.currentTpl = value;
  //   } else {
  //     this.currentTpl = '';
  //   }
  // },
  add() {
    if(this.currentApp === '') {
      this.$message('请选择有效的磁贴节点');
    } else {
      this.dialogVisible = true;
      this.requestTplTree();
    }
  },
  requestTplTree() {
    this.$http({
      // url: '/uitemplate_web/uitemplate_ctr/uitemplate_design_ctr/queryUITemplateList',
      url: '/uitemplate_web/iref_ctr/blobRefClassSearch/',
      method: 'post',
      contentType: 'application/x-www-form-urlencoded',
      // data: 'data=' + encodeURIComponent('{"tenant_id":"","type":"sys"}')
      data:{
        refModelUrl:"http://125.35.5.124/uitemplate_web/mdref_grid_ctr/",
        refName:"%25E5%2585%2583%25E6%2595%25B0%25E6%258D%25AE",
        refCode:"metadata",
        cfgParam:{isMultiSelectedEnabled:false,pageUrl:"uitemplate_web",isCheckListEnabled:true},
        refClientPageInfo:{
          pageSize:50,
          currPageIndex:0
        }
      }
    }).then((res) => {
      this.tplTree = res.data.formCategories;
    }).catch(() => {
      this.$message.error('请求失败');
    });
  },
  deleteRow(row) {
    this.$confirm('确定删除关联?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$http({
          url: '/wbalone/uitemplatenexusbase/delete/' + row.pk_nexus,
          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() {
    console.log('close dialog');
  },
  confirm() {
    this.$refs.addForm.validate((valid) => {
      if (valid) {
        this.$http({
          url: '/wbalone/uitemplatenexusbase/createUitemplate',
          method: 'post',
          data: {
            nexuskey: this.dialogForm.nexuskey,
            funnode: this.currentApp,
            pkMetaData: this.dialogForm.md_metadata,
            tempFormName: this.dialogForm.tempform_name,
            formData:this.dialogForm.formData,
          }
        }).then((res) => {
          if(res.data.status === 1) {
            this.$refs['addForm'].resetFields();
            this.dialogVisible = false;
            this.handleAppChange(oThis.currentApp);
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(() => {
          this.$message.error('请求失败');
        });

      }
    });
  },
  cancel() {
    this.$refs['addForm'].resetFields();
    this.dialogVisible = false;
  },
  getRefData(data) {
    var refData;
    if (['RefTree', 'RefGridTree'].indexOf(this.refInfo.refUIType) > -1) {
      var map = {};
      var ids = [];
      var root = [];
      data.forEach(v => {
        ids.push(v.id);
      });
      data.forEach(v => {
        if (ids.indexOf(v.pid) > -1) {
          if (map[v.pid]) {
            map[v.pid].push(v);
          } else {
            map[v.pid] = [v];
          }
        } else {
          root.push(v);
        }
      });
      var setChild = function(node) {
        var tmp = node;
        if (map[tmp.id]) {
          tmp.children = map[tmp.id];
          tmp.children.forEach(v => {
            setChild(v);
          });
        }
      };
      root.forEach(v => {
        setChild(v);
      });
      refData = root;
    } else {
        refData = data;
    }
    return refData;
  },
  // 格式化树状参照的显示(code + name)
  formatTreeLabel(dataArr) {
    if (!Array.isArray(dataArr)) {
      return dataArr;
    }
    for (let i = 0; i < dataArr.length; i++) {
      let refObj = dataArr[i];
      if (Object.prototype.toString.call(refObj) !== '[object Object]') {
        continue;
      }
      refObj.label = refObj.name;
      refObj.value = refObj.code;
      if (refObj.children) {
        refObj.children = this.formatTreeLabel(refObj.children);
      }
    }
    return dataArr;
  },
  // 格式化标签显示名
  formatTreeTableTree(dataArr) {
    dataArr.forEach(node => {
      node.label = node.refcode ? node.refcode + ' ' + node.name : node.name;
      node.value = node.code;
    });
    return dataArr;
  },
  //设置表头
    showHeaderSetting(){
      if(this.showTable){
        //this.$refs.uiTplTableRef.setTransferVisible(true);
      }
    }
},
created(){
  this.request();
}
};
</script>
<style>
.authApp-dialog-form {
  display: inline-block;
  width: calc(70% - 2px);
  font-size: 14px;
  vertical-align: top;
}
.ui-table i{
  margin: 12px 0 0 8px;
  font-size: 18px;
  color:#727171;
}
.ui-table i:hover{
  cursor: pointer;
  color:#0089FA;
}
</style>