<template>
    <md-layout style="height:100%;">
        <md-page slot="master" title="业务类型"  show-footer="false">
        <el-tree
          :data="treeData" :props="defaultProps"
          style="height: 400px;overflow: auto;"
          accordion
          :highlight-current="true"
          @current-change="handleAppChange"
        >
        </el-tree>

        </md-page>
        <md-page slot="detail" title="" show-footer="false" :title="currentTitle">
          <el-button type="primary" @click="add" slot="toolbar">新增</el-button>
          <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"
              :width="column.width"
              v-if="column.display"
              >
            </el-table-column>
            <el-table-column
              label="操作"
              >
              <template scope="scope">
                <i class="el-icon-delete" type="primary" @click="deleteRow(scope.row)" title="删除"></i>
                <i class="el-icon-menu" type="primary" @click="openDesigner(scope.row)" title="设计模板"></i>
              </template>
            </el-table-column>
          </el-table>
  <el-dialog title="创建UI模板" :modal="false" v-model="dialogVisible">
    <div style="font-size: 0px;">
      <!--
      <div id="authApp-tpl-tree">
        <el-tree
        :data="tplTree"
        style="height: 400px;overflow: auto;"
        accordion
        :highlight-current="true"
        @current-change="handleTplChange"
        :props="{label:'name',children:'forms'}"
        >
        </el-tree>
      </div>
        -->
      <div id="authApp-dialog-form">
        <el-form :model="dialogForm" label-width="100px" :rules="rules" ref="editForm">
          <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>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>
  </el-dialog>
        </md-page>
    </md-layout>

</template>


<script>
// import  MdLayout from '../../test/mdlayout.vue'
// import  MdPage from '../../test/mdpage.vue'
export default {
  // components:{
  //   MdLayout,
  //   MdPage
  // },
  data(){
    return {
      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:'模板名称不能为空'}],
        nexuskey:[{required:true,message:'模板标识不能为空'}]
      },
      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'
        }
    };
  },
  watch:{
    //TODO后面需要调整接口，自动组织树型结构
    currentProduct: function(product){
      var oThis = this;
      this.$http({
        url:'/ifbp-app-sm/buz/product/'+ product +'/models'
      }).then((res) => {
        oThis.treeData = [];
        if(res.data.success === true) {
          var modules = res.data.data;
          for (var i=0; i< modules.length; i++){
            var module = modules[i];
            oThis.treeData.push(module);
            module.label = module.name;
            module.children = [{
              label:'合同',
              code: '111'
            }];
            // this.$http({
            //   url:'/ifbp-app-sm/buz/product/'+product+'/module/'+module.mid+'/buzitypes'
            // }).then((res2) =>{
            //   if(res.data.success === true) {
            //     module.children = res.data.data;
            //   }else{
            //     oThis.$message.error('请求失败');
            //   }
            // }).catch((e)=>{

            // })
          }
        } else {
          oThis.$message.error('请求失败');
        }
      }).catch((e) => {
        console.log(e);
        oThis.$message.error('请求出错');
      });

    }
  },
  methods:{
    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;
        } 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 );
    },
    handleAppChange(treeItem) {
      if(!treeItem.children) {
        this.currentApp = treeItem;
        this.currentTitle = treeItem.label;
        this.$http({
          url:'/ifbp-app-sm/sm/uitemplate/getByFunnode?funNode=' + treeItem.code,
          method: 'get'
          // data:{
          //   funNode:treeItem.code
          // }
        }).then((res) => {
          this.tableData = 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.resetForm();
        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) {
      console.log(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() {
      // debugger;
      var oThis = this;
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$http({
            url: '/wbalone/uitemplatenexusbase/createUitemplate',
            method: 'post',
            data: {
              nexuskey: this.dialogForm.nexuskey,
              funnode: this.currentApp.code,
              pkMetaData: this.dialogForm.md_metadata,
              tempFormName: this.dialogForm.tempform_name,
              formData:this.dialogForm.formData,
            }
          }).then((res) => {
            oThis.handleAppChange(oThis.currentApp);
            if(res.data.status === 1) {
            //   console.log(res);
              this.dialogVisible = false;
              res.data.data.type = 'UI模板';
              oThis.handleAppChange(oThis.currentApp);
            //   this.tableData.push(res.data.data);
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(() => {
            this.$message.error('请求失败');
          });

        }
      });
    },
    cancel() {
      this.dialogVisible = false;
    },
    resetForm() {
      Object.keys(this.dialogForm).forEach((key) => {
        this.dialogForm[key] = '';
      });
      // debugger;
      this.dialogForm.formData={};
      this.dialogForm.formData.form = {};
      this.dialogForm.formData.form.pkMetadata='';
      this.dialogForm.formData.form.pkClass='';
      this.dialogForm.formData.form.sysflag = '';
      this.dialogForm.formData.form.name = '';

    }
  },
  created(){
    this.request();
  }
};
</script>

<style scoped>
#appTplAuth-container {
  padding: 15px;
  font-size: 0px;
}

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

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

#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>
