<template>
  <div style="width: 100%;">
    <div class="el-input el-input--prefix el-input--suffix aws-org-input" :class="editable?'':'is-disabled'">
      <div class="el-input__inner aws-org-user-input" @click="openDialog" >
        <el-tag v-for="tag in dynamicTags" :closable="editable" size="small" :key="tag.index" @close="handleTagClose(tag)">
          {{tag.type == 'department' ? tag.name : tag.name}}
        </el-tag>
      </div>

      <span class="el-input__suffix">
        <span class="el-input__suffix-inner">
          <i class="aws-icon aws-book" @click="openDialog"></i>
        </span>
      </span>
    </div>

    <el-dialog v-dialogDrag title="组织架构" class="aws-org-dialog" :visible.sync="visible" width="400" center
      :close-on-click-modal="false" :before-close="beforeClose" :modal-append-to-body="true" :append-to-body="isDialog"
      :modal='modal' custom-class="sub-aws-org-dialog" >

      <el-row type="flex">
        <el-col :span="24">
          <el-autocomplete v-model="queryParams" class="input-with-select" :fetch-suggestions="querySearch"
            ref="autocompleteRef" @keyup.enter.native="enterSelect"
            placeholder="请输入内容" @select="handleSelect">
            <i class="el-icon-search el-input__icon" slot="suffix" @click="querySearch(queryParams)"></i>
            <template slot-scope="{ item }">
              <div class="el-autocomplete-name">{{ item.name }}</div>
              <div class="el-autocomplete-path">{{ item.path }}</div>
            </template>
          </el-autocomplete>
        </el-col>
      </el-row>
      <el-row type="flex" class="aws-org-row2">
        <el-col :span="ismuti ? 16 : 24" class="aws-org-row2-value">
          <!--  default-expand-all=false -->
          <el-tree ref="tree" class="org-tree" node-key="id" @check-change="handleNodeCheckChange"
            @node-click="handleNodeClick" highlight-current show-checkbox :default-expand-all=false
            :props="defaultProps" :lazy=true :load="loadAwsTree" :default-checked-keys="defaultCheckedIds"
            :default-expanded-keys="defaultExpandedIds" check-on-click-node expand-on-click-node>
            <span class="custom-tree-node" slot-scope="{ node, data }">
              <i class="aws-icon aws-department" v-if="data.type == 'department'">
              </i>
              <i class="aws-icon aws-user" v-if="data.type == 'user' && !data.ismanager">
              </i>
              <i class="aws-icon aws-admin" v-if="data.type == 'user' && data.ismanager">
              </i>
              {{ data.name }}
            </span>
          </el-tree>
        </el-col>
        <el-col :span="8" class="aws-org-row2-value org-tree el-tag-contain" >
          <div class="el-tag-wrap">
            <el-tag v-for="tag in dynamicTags" :key="tag.index" closable @close="handleTagClose(tag)">
              {{tag.type == 'department' ? tag.name : tag.name}}
            </el-tag>
          </div>
          <i class="el-icon-error my-clear" @click="clear"></i>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="warning" @click="submit" size="mini">确 定</el-button>
        <el-button @click="visible = false" type="info" plain size="mini">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
      if (this[i] == val) {
        return i;
      }
    }
    return -1;
  }
  Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
      this.splice(index, 1);
    }
  }
  Array.prototype.orgIndexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
      if (this[i].uid == val.uid) {
        return i;
      }
    }
    return -1;
  }
  Array.prototype.orghashpush = function(val) {
    var index = this.orgIndexOf(val);
    if (index == -1) {
      this.push(val);
    }
  }
  export default {
    name: 'aws-org',
    props: {
      ismuti: {
        type: Boolean,
        default: true,
        required: false
      },
      users: {
        type: Array,
        default: () => [],
        required: true
      },
      index: { //使用数组动态生成组件时，当前组件所处索引位置
        type: Number,
        default: null,
        required: false,
      },
      defaultCurOrg: {
        type: Boolean,
        default: true,
        required: false
      },
      modal: {
        type: Boolean,
        default: true,
        required: false
      },
      editable: {
        type: Boolean,
        default: true,
        required: false
      },
      isDialog: { //嵌套的 Dialog 必须指定该属性并赋值为 true
        type: Boolean,
        default: false,
        required: false
      },
      height: {
        type: Number,
        default: 28
      }
    },
    created() {

    },
    mounted() {
      if (this.defaultCurOrg) {
        this.loadDefaultExpandIds();
      }
    },
    methods: {

      loadDefaultExpandIds() {
        var params = {
          sid: this.sid,
          cmd: 'com.ls.apps.shr_api_tree_user_path_ids'
        }
        this.$http.post(this.url, params, {emulateJSON: true})
          .then(function(res) {
          var data = res.data;
          if(data.flag){
            let list = data.data || [];
            this.defaultCheckedIds = [];
            this.dynamicTags = [];
            this.defaultExpandedIds = [];
            this.users.forEach(item=>{
              if (item.uid && item.name) {
                list.push(item);
                this.defaultCheckedIds.push(item.uid);
                this.dynamicTags.push(item);
              }
            })
            list.forEach(item=>{
              this.defaultExpandedIds.push(item);
            })
          }else{
            console.log("loadDefaultExpandIds err",data.msg);
          }
        }, function(res) {
          console.log(res.status);
        });
      },
      querySearch: function(queryString, cb) {
        if (!queryString || queryString.trim().length == 0) {
          cb([]);
          return;
        }
        var params = {
          sid: this.sid,
          cmd: 'com.ls.apps.shr_api_tree_query_user',
          param: queryString
        }
        this.$http.post(this.url, params, {
          emulateJSON: true
        }).then(function(res) {
          var data = res.data;
          if (data.flag) {
            cb(data.data);
          } else {
            cb([]);
            console.log(data.msg);
          }
        }, function(res) {
          console.log(res.status);
        });
      },
      enterSelect(){
        let suggestions = this.$refs.autocompleteRef.suggestions || [];
        if(suggestions.length){
          this.handleSelect(suggestions[0]);
          this.$refs.autocompleteRef.activated = false;
        }
      },
      handleSelect: function(item) {
        this.$refs.tree.setChecked(item, true);
        this.dynamicTags.orghashpush(item);
        if (!this.ismuti && this.dynamicTags.length>1) {
          this.$refs.tree.setChecked(this.dynamicTags[0], false); // 上一个取消选中
          this.dynamicTags.remove(this.dynamicTags[0]);
        }
      },
      loadAwsTree: function(node, resolve) {
        var params = {
          sid: this.sid,
          cmd: 'com.ls.apps.shr_api_tree_aws_org',
        };
        if (node.level === 0) {
          params.id = '0';
        } else {
          params.id = node.data.id;
        }
        this.$http.post(this.url, params, {
          emulateJSON: true
        }).then(function(res) {
          var data = res.data;
          if (data.flag) {
            resolve(data.data);
          } else {
            resolve([]);
            console.log(data.msg);
          }
        }, function(res) {
          console.log(res.status);
        });
      },
      /**
       * [handleNodeCheckChange description]
       * @param  {[type]} data    节点所对应的对象
       * @param  {[type]} checked 节点本身是否被选中
       * @param  {[type]} children    节点的子树中是否有被选中的节点
       * @return {[type]}         [description]
       */
      handleNodeCheckChange: function(data, checked, children) {

        if (!children) {
          // 叶子
          if (checked) {
            if (data.type == 'user') {
              this.dynamicTags.orghashpush(data);
            }
            if (!this.ismuti && this.dynamicTags.length > 1) {
              let id = this.dynamicTags[0].uid || this.dynamicTags[0].id;
              this.$refs['tree'].setChecked(id, false); // 上一个取消选中
              this.dynamicTags.remove(this.dynamicTags[0]);
            }

          } else {
            this.dynamicTags.remove(data);
          }
        } else {
          // 非叶子
          // if (checked) {
          //   this.$refs['tree'].setChecked(data, false); // 上一个取消选中
          // }
        }
      },
      /**
       * [handleNodeClick description]
       * @param  {[type]} data 节点所对应的对象
       * @param  {[type]} node 节点对应的 Node
       * @param  {[type]} tree 节点组件本身
       * @return {[type]}      [description]
       */
      handleNodeClick: function(data, node, tree) {

      },
      handleTagClose: function(tag) {
        this.dynamicTags.remove(tag);
        if(this.$refs['tree']){
          this.$refs['tree'].setChecked(tag, false);
        }
      },
      openDialog: function() {
        if (!this.editable) {
          return;
        }
        this.visible = true;
        if (this.$refs.tree) {
          var nodes = this.$refs.tree.getCheckedNodes();
          if (nodes) {
            for (var i = 0; i < nodes.length; i++) {
              if (nodes[i].type == 'user') {
                this.dynamicTags.orghashpush(nodes[i]);
              }
            }
          }
        }
        if(!this.dynamicTags.length){
          this.$nextTick(()=>{
             this.$refs.tree.setCheckedKeys([]);
          })
        }

      },
      beforeClose: function(done) {
        this.$refs.tree.setCheckedKeys([]);
        done();
      },
      submit: function() {
        if (this.dynamicTags.length == 0) {
          this.$message({
            message: '请选择人员',
            type: 'error'
          });
          return;
        }
        this.visible = false;
      },
      clear: function() {
        this.dynamicTags = [];
        if (this.$refs.tree) {
          this.$refs.tree.setCheckedKeys([]);
        }
      },
    },
    computed: {
      sid(){
        return this.$common.getUrlParams('sid');
      },
      url() {
        if(process.env.envir === 'dev'){
          return '/portal/r/jd';
        }
        return this.$config.getDomain('awsUrl') + 'r/jd';;
      }
    },
    data: function() {
      return {
        visible: false,
        dynamicTags: [],
        queryParams: '',
        defaultCheckedIds: [],
        defaultExpandedIds: [],
        defaultProps: {
          children: 'children',
          label: function(data, node) {
            if (data.type == 'department') {
              return data.name;
            } else {
              return data.alias;
            }
          },
          isLeaf: function(data, node) {
            if (data.type == 'department') {
              return false;
            } else {
              return true;
            }
          }
        },
        selectedData: '',
      }
    },
    watch: {
      dynamicTags (newVal, oldVal) {
        let users = [];
        for (var i = 0; i < newVal.length; i++) {
          users.push({
            uid: newVal[i].uid,
            name: newVal[i].name,
            email: newVal[i].email,
            role: newVal[i].role,
            mobile: newVal[i].mobile,
          });
        }
        this.$emit('submit', users, this.index);
      },
      users(newVal){
        this.dynamicTags = newVal;
      },
    }

  }
</script>
<style type="text/css" lang="scss">

  .aws-org-dialog {
    overflow: hidden;
    .sub-aws-org-dialog {
      margin-top: 1vh!important;
    }
    .el-dialog__headerbtn {
      top: 10px;
    }
  }

  .aws-org-dialog .el-dialog__header {
    padding: 4px 10px !important;
  }

  .aws-org-dialog .el-dialog__body {
    padding: 6px 12px 6px !important;
  }

  .aws-org-dialog .el-dialog__footer {
    padding: 6px 6px 6px !important;
  }

  .aws-org-row2 {
    height: 400px;
  }

  .aws-org-row2-value {
    height: 100% !important;
    border: 1px solid #ebebeb;
    border-radius: 3px;
    transition: .2s;
  }

  .org-tree {
    overflow-y: auto;
    height: 100%;
  }

  .el-tag {
    margin: auto 4px;
  }

  .aws-icon {
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    display: inline-block;
    font-family: element-icons !important;
    width: 15px;
    height: 15px;
    margin-right: 6px;
    vertical-align: middle;
  }

  .aws-book {
    background-image: url('http://e.longsys.com/portal/lexar/resources/img/modules/system/address-book.png');
  }

  .aws-department {
    background-image: url('http://e.longsys.com/portal/lexar/resources/img/modules/system/org-1.gif');
  }

  .aws-user {
    background-image: url('http://e.longsys.com/portal/lexar/resources/img/modules/system/online_moderator.gif');
  }

  .aws-admin {
    background-image: url('http://e.longsys.com/portal/lexar/resources/img/modules/system/online_admin.gif');
  }

  .my-clear {
    color: red;
    position: absolute;
    right: 4px;
    bottom: 4px;
  }

  .input-with-select {
    width: 100%;
  }
  .el-autocomplete-suggestion li {
    overflow: unset;
  }
  .el-autocomplete-name {
    width: 20%;
    display: inline-block;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
  }

  .el-autocomplete-path {
    width: 80%;
    display: inline-block;
     overflow: hidden;
     text-overflow: ellipsis;
     white-space: nowrap;
     vertical-align: middle;
  }

  .aws-org-input {
    cursor: pointer;
  }
  .is-disabled.aws-org-input{
    cursor: not-allowed;
  }

  .aws-org-input .el-input__suffix {
    display: flex;
    align-items: center;
  }

  .aws-org-user-input {
    vertical-align: middle;
    padding-left: 0px !important;
    height: 28px;
    display: inline-flex;
    overflow-x: auto;
    overflow-y: hidden;
    // min-width: 202px;
  }

  .aws-org-user-input ::-webkit-scrollbar {
    width: 4px;
    height: 4px !important;
    scrollbar-arrow-color: red;

  }

  .aws-org-user-input::-webkit-scrollbar-thumb {
    /*滚动条里面小方块*/
    border-radius: 5px;
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: rgba(0, 0, 0, 0.2);
    scrollbar-arrow-color: red;
  }

  .aws-org-user-input::-webkit-scrollbar-track {
    /*滚动条里面轨道*/
    -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 0;
    background: rgba(0, 0, 0, 0.1);
  }

 .aws-org-user-input::-webkit-scrollbar {
      width: 1.3em;
      height: 0.5em;
      background-color: #fafafa;
  }
  .el-tag-contain {
    display: flex;
    .el-tag-wrap {
      display: flex;
      flex-direction: column;
      flex-wrap: wrap;

      .el-tag {
        margin: 2px;
      }

    }
  }
</style>
