<template>
  <div class="selectuser" v-clickoutside="hideSelect">
    <Input
      v-model="selIndex.title"
      class="width-tab"
      readonly
      icon="md-person-add"
      :placeholder="placeholder"
      @on-focus="showSelectUser"
    />
    <div class="selu" style="z-index: 999" v-if="isSelectUser">
      <Row class="selu-head">
        <i-col span="24">{{ title }}</i-col>
      </Row>
      <Row class="selu-body">
        <i-col :span="level == 1 ? 24 : 14">
          <ul class="selu-depts scrollbar">
            <Select v-model="studySectionId" @on-change="studyChanged">
              <Option
                v-for="item in studyList"
                :key="item.studySectionId"
                :value="item.studySectionId"
              >
                {{ item.studySectionName }}
              </Option>
            </Select>
            <li
              v-for="(item, index) in depts"
              :key="index"
              :class="{ activedept: index == num }"
              @click="getUsers(item.nodeId, index)"
            >
              {{ item.title }}

              <Icon
                v-if="level == 1 && selIndex.nodeId != item.nodeId"
                type="md-arrow-round-forward"
                class="icon-teacher"
              ></Icon>
              <Icon
                v-if="level == 1 && selIndex.nodeId == item.nodeId"
                type="md-checkmark"
                class="icon-selteacher"
              ></Icon>
            </li>
          </ul>
        </i-col>
        <i-col v-if="level != 1" span="10" class="selu-col">
          <ul class="selu-teachers scrollbar">
            <li
              v-for="(item, index) in users"
              :key="index"
              inline
              :class="{ activeteacher: selIndex.uid == item.uid }"
              @click="selUser(item)"
            >
              {{ item.title }}
              <Icon
                v-if="selIndex.uid != item.uid"
                type="md-arrow-round-forward"
                class="icon-teacher"
              ></Icon>
              <Icon
                v-if="selIndex.uid == item.uid"
                type="md-checkmark"
                class="icon-selteacher"
              ></Icon>
            </li>
          </ul>
        </i-col>
      </Row>
      <Row class="selu-foot">
        <i-col span="24">
          <Button type="error" @click="clearAll">清空</Button>
          <Button
            type="info"
            @click="sureSelect"
            :style="{ 'margin-left': '10px' }"
            >确定</Button
          >
        </i-col>
      </Row>
    </div>
  </div>
</template>

<script>
const clickoutside = {
  // 初始化指令
  bind(el, binding, vnode) {
    function documentHandler(e) {
      // 这里判断点击的元素是否是本身，是本身，则返回
      if (el.contains(e.target)) {
        return false;
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数，此处binding.value就是handleClose方法
        binding.value(e);
      }
    }
    // 给当前元素绑定个私有变量，方便在unbind中可以解除事件监听
    el.__vueClickOutside__ = documentHandler;
    document.addEventListener("click", documentHandler);
  },
  update() {},
  unbind(el, binding) {
    // 解除事件监听
    document.removeEventListener("click", el.__vueClickOutside__);
    delete el.__vueClickOutside__;
  },
};

export default {
  name: "selectsingle",
  data() {
    return {
      isSelectUser: false,
      selectName: "", //输入框显示选中的用户
      searchName: "", //输入名称查询
      selIndex: {},
      depts: [], //部门列表
      selDept: "", //选中的部门
      users: [], //部门下的用户
      totals: 0,
      num: -1,
      config: JSON.parse(localStorage.getItem("config")),
      studyList: [],
      studySectionId: "0",
    };
  },
  props: {
    value: [Object, String, Array],

    placeholder: {
      type: String,
      default() {
        return "请选择";
      },
    },
    title: {
      type: String,
      default() {
        return "请选择";
      },
    },
    type: {
      type: String,
      default() {
        return "";
      },
    },
    level: {
      type: Number,
      default() {
        return 2;
      },
    },
  },
  created: function () {},
  directives: { clickoutside },
  methods: {
    init: function () {
      const self = this;
      self.totals = 0;
      self.getStudySection();
      self.selIndex = {};
      self.selectName = "";
      if (self.value) {
        self.selIndex = self.value;
      }
    },

    studyChanged() {
      this.getDepartment();
      this.getAllUsers();
    },
    getStudySection() {
      this.$axios({
        baseURL: this.config.basic,
        url: "studysections/list",
      }).then((res) => {
        if (res.code == 200) {
          this.studyList = res.data;
          if (this.studyList.length > 0) {
            if (this.studySectionId == "0") {
              this.studySectionId = this.studyList[0].studySectionId;
            }
          }
          this.getDepartment();
          this.getAllUsers();
        }
      });
    },
    getDepartment() {
        console.log(`type:${this.type}`)
      var self = this;
      if (this.type == "teacher") {
        this.$axios({
          baseURL: this.config.basic,
          url: `department/${this.studySectionId}`,
          method: "GET",
        }).then(function (res) {
          var list = res.data;
          var data = list.map((a) => {
            return {
              title: a.deptName,
              nodeId: a.deptId,
            };
          });
          self.depts = data;
        });
      } else if (this.type == "place") {
        this.$axios({
          baseURL: this.config.basic,
          url: `place/${this.studySectionId}`,
          method: "GET",
        }).then(function (res) {
          self.depts = res.data;
        });
      } else if (this.type == "grade") {
        this.$axios({
          baseURL: this.config.basic,
          url: `studysections/grade/${this.studySectionId}`,
          method: "GET",
        }).then(function (res) {
          self.depts = res.data;
        });
      }else if (this.type == "subject") {
        this.$axios({
          baseURL: this.config.basic,
          url: `studysections/subject/nomarl/${this.studySectionId}`,
          method: "GET",
        }).then(function (res) {
          self.depts = res.data;
        });
      }
    },
    searchUsers: function (self) {
      if (self.type == "teacher") {
        var params = {
          deptId: self.selDept,
          searchKey: self.searchName,
          studySectionId: self.studySectionId,
        };
        this.$axios({
          baseURL: this.config.basic,
          method: "POST",
          url: "teacher/ByCondition",
          data: params,
        }).then(function (res) {
          var list = res.data;
          var data = list.map((a) => {
            return {
              title: a.name,
              uid: a.uid,
            };
          });
          console.log(`info:${JSON.stringify(data)}`);
          self.users = data;
        });
      } else if (self.type == "place") {
        if (this.selDept && self.selDept.length > 0) {
          this.$axios({
            baseURL: this.config.basic,
            url: `place/room/${this.selDept}`,
            method: "GET",
          }).then((res) => {
            if (res.code == 200) {
              var list = res.data;
              var data = list.map((a) => {
                return {
                  title: a.roomName,
                  uid: a.roomId,
                };
              });
              console.log(`info:${JSON.stringify(data)}`);
              self.users = data;
            }
          });
        }
      }
    },
    getAllUsers: function () {
      const self = this;
      self.num = -1;
      self.selDept = "";
      self.searchUsers(self);
    },

    hideSelect() {
      (this.isSelectUser = false), (this.selIndex = {});
      if (this.value) {
        this.selIndex = this.value;
      }
    },
    showSelectUser: function () {
      this.isSelectUser = true;
      this.init();
    },

    getUsers: function (deptid, index) {
      const self = this;
      if (this.level == 1) {
        var model = this.depts[index];
        self.selIndex = model;
        return;
      }
      self.num = index;
      self.selDept = deptid;
      self.searchUsers(self);
    },
    queryUsers: function () {
      const self = this;
      self.searchUsers(self);
    },

    selUser: function (item) {
      if (this.type == "place") {
        this.selIndex = item;
      } else {
        this.selIndex = item;
      }
    },
    sureSelect: function () {
      this.$emit("input", this.selIndex); //点击确定触发父组件上自定义的事件
      this.$emit("sureSelect");
      this.isSelectUser = false;
    },
    clearAll: function () {
      this.selectName = "";
      this.searchName = "";
      this.selIndex = [];
      this.$emit("input", []);
    },
  },
  // watch: {
  //   value: function () {
  //     const self = this;
  //     self.selIndex = [];
  //     if (self.value) {
  //       self.selIndex = self.value;
  //     } else {
  //       self.selectName = "";
  //       self.searchName = "";
  //     }
  //   },
  // },
};
Array.prototype.remove = function (val) {
  var index = this.indexOf(val);
  if (index > -1) {
    this.splice(index, 1);
  }
};
</script>
<style>
.selectuser {
  position: relative;
}

.selu {
  position: absolute;
  top: 35px;
  left: 0;
  margin: 0 auto;
  width: 402px;
  height: 360px;
  border-radius: 4px;
  border: solid 1px #ccc;
  z-index: 999;
  background-color: #fff;
}

.selu-body {
  width: 400px;
  height: 260px;
  border-top: solid 1px #e4e4e4;
  border-bottom: solid 1px #e4e4e4;
}

.selu-foot {
  width: 400px;
  height: 50px;
  text-align: right;
  padding-right: 10px;
  padding-top: 8px;
}

.selu-depts.scrollbar {
  height: 221px;
  overflow-y: auto;
}
</style>
<style>
/* .width-tab {
  width: 200px;
} */

.selu-head {
  height: 50px;
  line-height: 50px;
  font-size: 14px;
  font-family: "Microsoft YaHei UI";
  padding-left: 10px;
}

.selu-body .selu-search {
  height: 37px;
  border-bottom: solid 1px #e4e4e4;
}

.selu-body .selu-col {
  border-left: solid 1px #e4e4e4;
  border-right: solid 1px #e4e4e4;
  height: 260px;
}

.selu-depts li,
.selu-teachers li {
  list-style-type: none;
  height: 37px;
  line-height: 37px;
  border-bottom: solid 1px #e4e4e4;
  padding-left: 10px;
  font-size: 14px;
  cursor: pointer;
  position: relative;
}

.icon-teacher,
.icon-selteacher {
  position: absolute;
  padding-top: 10px;
  left: 140px;
  color: #ccc;
}

.icon-selteacher {
  color: green;
}

.selu-depts li:hover,
.selu-teachers li:hover {
  background-color: #2d8cf0;
  color: #fff;
}

.selu-depts li:active,
.selu-teachers li:active {
  background-color: #2d8cf0;
  color: #fff;
}

.activedept {
  background-color: #2d8cf0;
  color: #fff;
}

.activeteacher {
  color: green;
}
</style>
<style>
.ivu-icon {
  cursor: pointer;
}

.selu-search .ivu-input {
  border: 0 !important;
  border: solid 0 white;
  height: 35px;
}

.selu-depts .ivu-badge {
  float: right;
  top: 8px;
  right: 10px;
  text-align: center;
}

.selu-depts .badge-alone {
  background: #2d8cf0 !important;
}

.selu-depts li.active .badge-alone {
  background: white !important;
  color: #333;
}

::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: #f5f5f5;
  border-radius: 10px;
}

::-webkit-scrollbar {
  width: 5px;
  border-radius: 10px;
  background-color: #ccc;
}

::-webkit-scrollbar-thumb {
  border-radius: 10px;
  background-color: #ccc;
}

.force-overflow {
  min-height: 260px;
}

.selu-teachers.scrollbar {
  height: 258px;
  overflow-y: auto;
}
</style>
