<template>
<div>
  <div class="title-header" style="padding: 20px 23px;">
    <h2 class="name">功能节点默认模板设置</h2>
  </div>
  <div id="action-container">
    <el-button @click="copy" type="primary" width="100" style="">复制</el-button>
    <el-button @click="alloc" type="primary" width="100" style="">分配</el-button>
    <el-button @click="design" type="primary" width="100" style="">设计</el-button>
  </div>
  <div id="tplAlloc-container">
    <div id="app-container">
      <el-tree
        accordion
        :props="defaultProps"
        :load="loadNode"
        lazy
        :highlight-current="true"
        @current-change="handleBoChange"
      ></el-tree>
    </div>
    <div id="tpl-container" style="position:relative;">
      <el-tree :data="tplTree" :highlight-current="true" @current-change="handleTplChange"
      :props="{label:'pkName', children: 'children'}">
      </el-tree>
    </div>
  </div>
  <el-dialog title="多角色和用户模板分配" v-model="dialogVisible">
    <div style="font-size: 0px;">
      <div id="tplAlloc-user-tree">
        <el-input placeholder="输入关键字过滤" v-model="filterText"></el-input>
        <el-tree class="userTree" ref="userTree" :data="userTree" :filter-node-method="filterFn" show-checkbox>
        </el-tree>
      </div>
      <div id='authApp-tranfer-container'>
        <el-button type="primary" style="width: 48px;display: block; margin: 0 auto 10px;" class="el-icon-d-arrow-right" @click="markSelect"></el-button>
        <el-button type="primary" style="width: 48px;display: block; margin: 0 auto;" class="el-icon-d-arrow-left" @click="markRemove"></el-button>
      </div>
      <div id="tplAlloc-selected-list">
        <el-tree class="selectedTree" ref="selectedTree" :data="selectedUsers" :show-checkbox="true">
        </el-tree>
      </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>
  <el-dialog title="复制模板" v-model="addDialogVisible">
    <el-form label-width="100">
      <el-form-item label="模板名称">
        <el-input v-model="tplName"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancelAdd">取 消</el-button>
      <el-button type="primary" @click="confirmAdd">确 定</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
export default {
  data() {
    return {
      tplTree: [],
      userTree: [{
        label:'用户',
        children: []
      },{
        label: '角色',
        children: []
      }],
      defaultProps: {
        children: 'children',
        label: 'name',
        isLeaf: 'leaf'
      },
      tplName: '',
      selectedUsers: [],
      filterText: '',
      currentBo: '',
      currentTpl: '',
      dialogVisible: false,
      addDialogVisible: false
    };
  },
  computed: {
    selectedKeys() {
      var selectedKeys = [];
      this.selectedUsers.forEach((user) => {
        selectedKeys.push(user.value);
      });
      return selectedKeys;
    }
  },
  methods: {
    request() {
      this.$http({
        url: '/wbalone/appMGT/findAllApps'
      }).then((res) => {
        if (res.data.status === 1) {
          this.boTree = res.data.data;
        } else {
          this.$message.error('请求失败');
        }
      }).catch(() => {
        this.$message.error('请求出错');
      });
    },
    loadNode(node, resolve){
      console.log(node);
      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('请求出错');
        });
      }
    },
    copy() {
      console.log(this.currentTpl);
      if(this.currentTpl) {
        this.tplName = this.currentTpl.pkName;
        this.addDialogVisible = true;
      }else{
        this.$message('请选择有效的模板节点进行复制');
      }
    },
    alloc() {
      var tmp;
      if(this.currentTpl && this.currentBo) {
        this.dialogVisible = true;
        Promise.all([this.$http({
          url: '/wbalone/roleMGT/listAll'
        }), this.$http({
          url: '/ifbp-app-sm/sm/user/findAll'
        })]).then((resArray) => {
          console.log(resArray);
          var roleRes = resArray[0];
          var userRes = resArray[1];
          if(roleRes.data.status === 1 && userRes.data.success === true) {
            roleRes.data.data.forEach((role) => {
              tmp = role;
              tmp.label = tmp.roleName;
              tmp.value = tmp.roleId;
              tmp.TYPEFORSUBMIT = 'role';
            });
            userRes.data.data.forEach((user) => {
              tmp = user;
              tmp.label = tmp.user_name;
              tmp.value = tmp.id;
              tmp.TYPEFORSUBMIT = 'user';
            });
            this.userTree = [{
              label:'用户',
              children: userRes.data.data
            },{
              label: '角色',
              children: roleRes.data.data
            }];
          } else {
            this.$message({
              type: 'error',
              message: '请求失败'
            });
          }
        });
      } else {
        this.$message('请选择有效的业务类型和模板节点');
      }
    },
    add() {
      //add
    },
    edit() {
      //edit
    },
    confirm() {
      var users = [];
      var roles = [];
      this.selectedUsers.forEach((item) => {
        if(item.TYPEFORSUBMIT === 'user') {
          users.push(item.value);
        } else {
          roles.push(item.value);
        }
      });
      this.$http({
        url: '/wbalone/ieoproleuitemplate/upDataRoleOrUserRelevanceToPkTemp',
        method: 'post',
        data: {
          userids: users,
          rolecodes: roles,
          funnode: this.currentBo,
          pktemp: this.currentTpl.pkTemp,
          nexuskey: this.currentTpl.nexuskey
        }
      }).then((res) => {
        if(res.data.status === 1) {
          this.dialogVisible = false;
          this.selectedUsers = [];
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg
          });
        }
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '新增失败'
        });
      });
    },
    cancel() {
      this.dialogVisible = false;
      this.selectedUsers = [];
    },
    design(){
      console.log(this.currentTplNode);
      if(this.currentTplNode.level === 2) {
        window.open('/uitemplate_web/index.html?pk_temp=' + this.currentTpl.pkTemp);
      }else if(this.currentTplNode.level === 1) {
        this.$message('系统模板不能设计');
      }else {
        this.$message('请选择有效的模板节点');
      }
    },
    confirmAdd() {
      var copyNode = JSON.parse(JSON.stringify(this.currentTpl));
      copyNode.pkName = this.tplName;
      delete copyNode.children;
      this.$http({
        url: '/wbalone/uitemplatenexusbase/copyUitemplate',
        method: 'post',
        data: {
          nexuskey: this.currentTpl.nexuskey,
          pkName: this.tplName,
          funnode: this.currentBo,
          pktemp: this.currentTpl.pkTemp,
        }
      }).then((res) => {
        if(res.data.status === 1) {
          this.addDialogVisible = false;
          this.tplName = '';
          for(var i=0;i<this.tplTree.length;i++) {
            if(this.tplTree[i].pkTemp === this.currentTpl.pkTemp) {
              var tmp = JSON.parse(JSON.stringify(this.tplTree[i]));
              tmp.children.push(copyNode);
              this.tplTree.splice(i, 1, tmp);
              break;
            }
          }
        } else {
          this.$message({
            type: 'error',
            message: res.data.msg
          });
        }
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '新增失败'
        });
      });
    },
    cancelAdd() {
      this.addDialogVisible = false;
      this.tplName = '';
    },
    markSelect() {
      var selected = this.$refs.userTree.getCheckedNodes(true);
      console.log(selected);
      this.selectedUsers = JSON.parse(JSON.stringify(selected));
      this.$refs.userTree.filter(this.filterText);
    },
    markRemove() {
      var removeItems = this.$refs.selectedTree.getCheckedNodes(true);
      console.log(removeItems);
      var result = [];
      var removeKeys = [];
      removeItems.forEach((item) => {
        removeKeys.push(item.value);
      });
      this.selectedUsers.forEach((user) => {
        if(removeKeys.indexOf(user.value) < 0) {
          result.push(user);
        }
      });
      this.selectedUsers = result;
      this.$refs.userTree.filter(this.filterText);
    },
    filterFn(val, data) {
      return this.searchFilter(val, data) && this.selectFilter(data);
    },
    searchFilter(value, data) {
      if(!value) {
        return true;
      }
      return data.label.indexOf(value) > -1;
    },
    selectFilter(data){
      return this.selectedKeys.indexOf(data.value) < 0;
    },
    handleBoChange(value, node) {
      console.log(value,node);
      if(value.code && node.level === 3){
        this.currentBo = value.code;
        this.$http({
          url: '/wbalone/ieoproleuitemplate/listByFunNode/' + this.currentBo
        }).then((res) => {
          if(res.data.msg === 'success') {
            this.tplTree = this.constructTree(res.data.data);
          } else {
            this.tplTree = [];
            this.$message({
              type: 'error',
              message: res.data.msg
            });
          }
        }).catch((e) => {
          console.log(e);
          this.tplTree = [];
          this.$message({
            type: 'error',
            message: '请求失败'
          });
        });
      }
    },
    handleTplChange(value, node) {
      console.log(value, node);
      this.currentTpl = value;
      this.currentTplNode = node;
    },
    constructTree(data) {
      var base = data.uitemplateNexusBaseList;
      var user = data.uitemplateNexusList;
      var tmp = {};
      base.forEach((tpl) => {
        tmp[tpl.nexuskey] = [];
      });
      user.forEach((tpl) => {
        if(Object.prototype.toString.call(tmp[tpl.nexuskey]) === "[object Array]") {
          tmp[tpl.nexuskey].push(tpl);
        }
      });
      for(var i=0;i<base.length;i++) {
        base[i].children = tmp[base[i].nexuskey];
      }
      return base;
    }
  },
  created() {
    //this.request();
  },
  watch: {
    filterText(val) {
      this.$refs.userTree.filter(val);
    }
  }
};
</script>

<style>
#tplAlloc-container .el-tree {
  height: 400px;
  overflow: auto;
}
#tplAlloc-user-tree .userTree .el-tree {
  height: 364px;
  overflow: auto;
}
#tplAlloc-selected-list .selectedTree .el-tree {
  height: 400px;
  overflow: auto;
}
#tplAlloc-user-tree .el-tree-node .el-tree-node__content .el-checkbox {
  display: none;
}
#tplAlloc-user-tree .el-tree-node .el-tree-node__children .el-tree-node__content .el-checkbox {
  display: inline;
}
</style>
<style scoped>
#tplAlloc-container {
  padding: 15px;
  font-size: 0px;
}

#action-container {
  padding: 10px;
  background-color: white;
  margin: 15px;
}

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

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

#tplAlloc-user-tree {
  display: inline-block;
  width: calc(50% - 100px);
  font-size: 14px;
  vertical-align: middle;
}

#authApp-tranfer-container {
  display: inline-block;
  width: 200px;
  vertical-align: middle;
  font-size: 14px;
  /* padding-left: 76px;
  padding-right: 76px; */
}

#tplAlloc-selected-list {
  display: inline-block;
  width: calc(50% - 100px);
  font-size: 14px;
  vertical-align: middle;
}
</style>
