<template>
  <div class="contianer">
    <van-search
      v-model="searchVal"
      label="名称"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
      @cancel="onCancel"
      class="search"
    />
    <div class="main">
      <el-checkbox-group
        v-if="searchVal != ''"
        v-model="checkedUser"
        class="item"
        @change="handleCheckedSearchUserChange"
      >
        <el-checkbox
          size="medium"
          v-for="(item, index) in searchUsers"
          v-model="item.isChecked"
          :label="item.userId"
          :key="index"
          @change="item.isChecked = !item.isChecked"
        >
          <svgIcon
            icon-style="icon header-icon"
            icon-class="lianxiren2"
            style="margin-right: 2vw"
          />
          {{ item.fullname }}
        </el-checkbox>
      </el-checkbox-group>
      <el-checkbox-group
        v-else
        class="item"
        v-model="checkedUser"
        @change="handleCheckedUserChange"
      >
        <el-checkbox
          size="medium"
          v-for="(item, index) in userList"
          v-model="item.isChecked"
          :label="item.id"
          :key="index"
          @change="item.isChecked = !item.isChecked"
          class="itemCol"
        >
          <svgIcon
            v-if="item.userId"
            icon-style="icon header-icon"
            icon-class="lianxiren2"
            style="margin-right: 2vw"
          />
          <!-- <svgIcon v-if="!item.userId" icon-style="icon header-icon" icon-class="qunzu" style="margin-right:2vw;" /> -->
          {{ item.fullname }}
        </el-checkbox>

        <div
          class="childDept"
          v-for="(item, index) in childDept"
          :key="'z-' + index"
        >
          <div class="deptItem">
            <el-checkbox
              :isIndeterminate="true"
              style="border: none"
              v-model="item.isChecked"
              :label="item.id"
              :key="index"
              ><br
            /></el-checkbox>
            <div @click="toDeptUsersSelect(item)" class="itemText">
              <svgIcon
                icon-style="icon header-icon"
                icon-class="qunzu"
                style="margin-right: 2vw; margin-top: 0.3em"
              />
              <div class="flex">
                <div style="font-size: 14px">
                  {{ item.name }}
                </div>
                <van-icon name="arrow" size="16" />
              </div>
              <!-- <img
                style="width: 14px; height: 14px; margin-left: 40vw"
                src="/assets/img/meetingAppIconfontSvg/rightArrow.svg"
              /> -->
            </div>
          </div>
        </div>
      </el-checkbox-group>
    </div>
    <!-- <div class="okBtn">
      <div class="displayName">
        <div
          class="userNameItem"
          v-for="(item, index) in totalCheckedUsers"
          :key="index"
          @click="cancelCheckInbottom(item)"
        >
          <van-tag type="primary">{{ item.fullname }}</van-tag
          >&nbsp;
        </div>
      </div>
      <el-button style="float: right" type="primary" @click="handlerOk"
        >确定{{ totalNum() > 0 ? '(' + totalNum() + ')' : '' }}</el-button
      >
    </div> -->
  </div>
</template>
<script>
import {Message} from 'element-ui'
export default {
  data() {
    return {
      checkAll: [],
      checkedUser: [],
      deptList: [],
      userList: [],
      childUserList: [],
      totalUsers: [],
      searchUsers: [],
      users: [],
      deptUsers: [],
      isIndeterminate: [],
      value: [],
      isActive: [],
      deptIdList: [],
      childDept: [],
      isActive2: false,
      currentHandleCheckIndex: 0,
      isSearch: false,
      searchVal: '',
      beforeCheckLength: 0,
      beforeCheckList: [],
      totalCheckedUsers: [],
      beforeCheckedValue: [],
    }
  },
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      // 通过 `vm` 访问组件实例,将值传入fromPath
      vm.fromPath = from.path
      if (from.name == 'selDeptUsers') {
        console.log(to)
        // let deptUsers = to.query.deptUsers
        let deptUsers = JSON.parse(localStorage.getItem('deptUsers'))
        // console.log(deptUsers, 'deptUsers')
        // let deptId = to.query.deptId
        let deptId = JSON.parse(localStorage.getItem('deptId'))
        // if (deptUsers != undefined && deptId != undefined) {
        if (true) {
          //更新对于userid用户isChecked
          vm.childUserList.forEach((u) => {
            deptUsers.forEach((du) => {
              if (u.userId == du.userId) {
                u.isChecked = du.isChecked
              }
            })
          })
          console.log(vm.childUserList, 'vm.childUserList')
          //判断是否全选
          var isCheckAll = deptUsers.filter((item) => {
            return item.isChecked == true
          })
          // console.log(deptUsers.length,isCheckAll.length,'vm.value')
          if (deptUsers.length == isCheckAll.length) {
            vm.value.push(deptId)
            // console.log(vm.value,'vm.value')
            vm.deptList.forEach((item) => {
              if (item.id == deptId) {
                item.isChecked = true
              }
            })
            console.log(vm.deptList, 'vm.deptList')
          } else {
            let index = vm.value.indexOf(deptId)
            if (index != -1) vm.value.splice(index, 1)
          }
        }
        console.log(vm.userList, 'this.userList')
      }
    })
  },
  created() {
    let userList = this.$route.query.userList
    if (userList == undefined) {
      let deptUrl = `http://183.230.176.125:8896/api/org/v1/org/getOrgListByDemId?demId=1258608622670319616`
      this.$http.get(deptUrl).then((res) => {
        console.log(res, 'res')
        if (res.status == 200) {
          let totalDeptList = res.data
          this.deptList = totalDeptList
          totalDeptList.forEach((item) => {
            if (item.parentId != '0') {
              item.isChecked = false
              this.childDept.push(item)
            }
          })

          let url = `http://183.230.176.125:8896/api/user/v1/users/getOrgUserQuery`
          this.$http
            .post(url, {
              groupRelation: 'AND',
              groupTree: {},
              pageBean: {
                page: 1,
                pageSize: 100,
                showTotal: true,
              },
              params: {},
              querys: [
                {
                  property: 'ORG_ID_',
                  value: totalDeptList[0].id,
                  group: 'orgTree',
                  relation: 'AND',
                  operation: 'IN',
                },
              ],
              sorter: [],
            })
            .then((res) => {
              let userList = res.data.rows
              // console.log(res, 'res')
              if (res.status == 200) {
                userList.forEach((item) => {
                  item.isChecked = false
                  //  console.log(JSON.parse(totalDeptList[0]).id ,'totalDeptList[0].id')
                  this.userList.push(item)
                  this.totalUsers.push(item)
                })
                this.childDept.forEach((item) => {
                  // let dept = {
                  //   id: item.id,
                  //   fullname: item.name,
                  //   isChecked: false,
                  // }
                  // this.userList.push(dept)
                  this.$http
                    .post(url, {
                      groupRelation: 'AND',
                      groupTree: {},
                      pageBean: {
                        page: 1,
                        pageSize: 100,
                        showTotal: true,
                      },
                      params: {},
                      querys: [
                        {
                          property: 'ORG_ID_',
                          value: item.id,
                          group: 'orgTree',
                          relation: 'AND',
                          operation: 'IN',
                        },
                      ],
                      sorter: [],
                    })
                    .then((res) => {
                      let userList = res.data.rows

                      if (res.status == 200) {
                        userList.forEach((item2) => {
                          item2.isChecked = false
                          item2.department = [item.id]
                          //  console.log(JSON.parse(totalDeptList[0]).id ,'totalDeptList[0].id')
                          this.childUserList.push(item2)
                          this.totalUsers.push(item2)
                        })
                        // this.childUserList[index].forEach((e, i) => {
                        //   this.users.push(e.name)
                        // })
                      } else {
                        Message.error(res.data.errmsg)
                      }
                    })
                })
                // this.childUserList[index].forEach((e, i) => {
                //   this.users.push(e.name)
                // })
              } else {
                Message.error(res.data.errmsg)
              }
            })

          // console.log(this.deptList, 'this.deptList')
          this.childDept.forEach((item) => {
            this.checkAll.push(false)
            this.isIndeterminate.push(false)
            this.deptIdList.push(item.id)
          })

          // let rootId = 1
          // totalDeptList.forEach(e=>{
          //   if(e.parentid == 0){
          //     rootId = e.id
          //   }
          // })
        }
      })
      console.log(this.userList, 'this.userList')
    } else {
      this.userList = userList
    }
    // this.userList.forEach(e => {
    //   this.users.push(e.name)
    // })

    this.$bus.on('setAllUnCheck', () => {
      this.userList.forEach((item) => {
        item.isChecked = false
      })
    })
  },
  methods: {
    handleCheckedUserChange(value) {
      console.log(value, 'value')
      let valueLength = value.length
      let beforeValueLength = this.beforeCheckedValue.length
      //取消选择
      if (valueLength < beforeValueLength) {
        let cancelId = this.beforeCheckedValue[beforeValueLength - 1]
        // 取消底部框名字
        let isChildDeptUser = false
        this.childDept.forEach((e) => {
          if (e.id == cancelId) {
            isChildDeptUser = true
          }
        })
        if (isChildDeptUser) {
          // 取消的为子部门
          this.childUserList.forEach((e, i) => {
            if (e.department.indexOf(cancelId) != -1) {
              this.childUserList[i].isChecked = false
            }
          })
          console.log(this.childUserList, 'this.childUserList')
        } else {
          // 取消的为用户
          this.userList.forEach((e, i) => {
            if (e.id == cancelId) {
              this.userList[i].isChecked = false
            }
          })
        }
      }
      let deptIdList = this.deptList.filter((item) => {
        return item.id
      })
      // console.log(deptIdList, 'deptIdList')
      //判断部门下有无成员
      if (deptIdList.indexOf(value[value.length - 1])) {
        this.childDept.forEach((item) => {
          if (item.id == value[value.length - 1] && item.length == 0) {
            Message('当前部门无成员')
            value.pop()
          }
        })
      }
      //全选部门成员
      this.childDept.forEach((dept) => {
        if (dept.id == value[value.length - 1]) {
          this.childUserList.forEach((user) => {
            if (user.department.indexOf(dept.id) != -1) {
              user.isChecked = true
            }
          })
        }
      })
      // let currentNode = value[value.length - 1]
      // this.userList[this.userList.indexOf(currentNode)].isChecked = true
      // console.log(this.childUserList, 'childUserList')
      this.beforeCheckedValue = value
      this.value = value
      this.totalCheckedUsers = [
        ...this.userList.filter((item) => {
          return item.isChecked
        }),
        ...this.childUserList.filter((item) => {
          return item.isChecked
        }),
      ].reverse()
      console.log(this.totalCheckedUsers, 'totalCheckedUsers')
    },
    handleCheckedSearchUserChange(val) {
      let lastId = val[val.length - 1]
      if (this.beforeCheckLength < val.length) {
        this.userList.forEach((item) => {
          if (lastId == item.id) {
            item.isChecked = true
          }
        })
        this.childUserList.forEach((item) => {
          if (lastId == item.id) {
            item.isChecked = true
          }
        })
      }
      let lastId2 = this.beforeCheckList[this.beforeCheckList.length - 1]
      if (this.beforeCheckLength > val.length) {
        this.userList.forEach((item) => {
          if (lastId2 == item.id) {
            item.isChecked = false
          }
        })
        this.childUserList.forEach((item) => {
          if (lastId2 == item.id) {
            item.isChecked = false
          }
        })
      }
      this.beforeCheckList = val
      this.beforeCheckLength = val.length
    },
    handlerOk() {
      var users = this.value

      users.forEach((user, index) => {
        if (this.deptIdList.indexOf(user) != -1) {
          this.childUserList.forEach((item) => {
            if (item.department.indexOf(user)) {
              item.isChecked = true
            }
          })
        }
      })
      var totalUsers = []
      var totalUsersName = []
      this.userList.forEach((item) => {
        if (item.isChecked) totalUsers.push(item.userId)
        if (item.isChecked) totalUsersName.push(item.fullname)
      })
      this.childUserList.forEach((item) => {
        if (item.isChecked) totalUsers.push(item.userId)
        if (item.isChecked) totalUsersName.push(item.fullname)
      })
      localStorage.setItem('selUsers', JSON.stringify(totalUsers))
      this.$router.push({
        name: 'order',
        params: {selUsers: JSON.stringify(totalUsers), selUsersName: totalUsersName},
      })
    },
    changeActive(item) {
      // item.isActive = !item.isActive
      // console.log(this.deptList, 'this.deptList')
    },
    toDeptUsersSelect(item) {
      let isCheckAll = this.value.indexOf(item.id) != -1 ? true : false
      console.log(this.childUserList, 'this.childUserList')
      let userList = []
      this.childUserList.forEach((child) => {
        if (child.department.indexOf(item.id) != -1) userList.push(child)
      })
      if (isCheckAll) {
        userList.forEach((item) => {
          item.isChecked = true
        })
      }
      console.log(userList, 'JSON.stringify(userList)')
      localStorage.setItem('deptUsers', JSON.stringify(userList))
      this.$router.push({
        name: 'selDeptUsers',
        query: {
          deptId: item.id,
          isCheckAll: isCheckAll,
          deptUsers: JSON.stringify(userList) || [],
        },
      })
    },
    filterUserListByDeptid(id) {
      let users = this.users
      let userList = this.userList
      // let users2 = users.filter(i => {
      //   if (filUserList.find(item => { return item.name == i }) != undefined) {
      //     return true;
      //   } else {
      //     return false;
      //   }
      // })
      return userList.filter((item) => item.department.indexOf(id) != -1)
    },
    totalNum() {
      let checkedUserList = this.userList.filter((item) => {
        return item.isChecked == true
      })
      let checkedChildDeptUserList = this.childUserList.filter((item) => {
        return item.isChecked == true
      })

      return checkedUserList.length + checkedChildDeptUserList.length
    },
    onSearch(val) {
      this.searchUsers = []
      this.totalUsers.forEach((e) => {
        if (e.fullname.indexOf(val) != -1) {
          this.searchUsers.push(e)
        }
      })
    },
    onCancel() {
      this.searchVal = ''
      this.searchUsers = []
      this.$router.push({
        path: '/order',
      })
    },
    cancelCheckInbottom(item) {
      //取消的为子部门成员
      this.value.forEach((e, i) => {
        if (item.department.indexOf(e.id) != -1) {
          this.value[i].isChecked = false
        }
      })
      console.log(this.childDept, 'this.childDept')
      let index = this.totalCheckedUsers.indexOf(item)
      this.totalCheckedUsers.splice(index, 1)
      var i = this.userList.indexOf(item)
      if (i != -1) {
        this.userList[i].isChecked = false
      } else {
        i = this.childUserList.indexOf(item)
        this.childUserList[i].isChecked = false
      }
      let valIndex = this.value.indexOf(item.id)
      if (valIndex == -1) {
        this.$bus.emit('changeValue', item.id)
      } else {
        this.value.splice(valIndex, 1)
      }
    },
  },
  watch: {
    deptList: {
      immediate: true,
      deep: true,
      handler: function (newVal, oldVal) {},
    },
    userList: {
      immediate: true,
      deep: true,
      handler: function (newVal, oldVal) {},
    },
  },
  computed: {},
}
</script>
<style lang="scss" scoped>
.contianer {
  margin-top: 4em;
  .search {
    position: fixed;
    top: 4em;
    width: 100%;
    z-index: 999;
  }
  .main {
    margin-top: 4em;
    .item {
      height: 400PX;
      overflow: auto;
    }
  }
  .itemCol {
    display: flex;
    align-items: center;
    padding-top: 4vw;
    padding-left: 4vw;
    margin: 0;
  }
}
.childDept {
  // height: 52px !important;
  font-weight: 700;
  .deptItem {
    display: flex;
    padding: 0.5em;
    border-bottom: 1px solid #dddddd;
  }
  .itemText {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
      padding-right: 0.5em;
    }
  }
}

.el-checkbox__input.is-checked .el-checkbox__inner,
.el-checkbox__input.is-indeterminate .el-checkbox__inner {
  line-height: 22px !important;
}

.el-checkbox {
  height: 28px !important;
  line-height: 31px !important;
  padding-top: -3vw;
  padding-bottom: 3vw;
  border-bottom: 1px solid rgb(221, 221, 221);
  font-weight: 700;
}

.el-checkbox__inner {
  z-index: 0 !important;
}

.okBtn {
  position: fixed;
  bottom: 0;
  padding: 0.8em 0.5em;
  background-color: rgb(248, 248, 248);
  display: flex;
  align-content: center;
  justify-content: space-between;
  overflow: hidden;
  z-index: 999;
  width: 100%;
  box-sizing: border-box;
}

.okBtn .el-button {
  width: 22vw;
  padding-left: 3vw;
  margin-right: 14px;
}

.van-icon-search:before {
  margin-top: 0.5vw;
}

.van-field__control {
  padding: 0.5vw;
}

.displayName {
  /* height: 2em; */
  /* line-height: 1.5em; */
  overflow-x: scroll;
  /* 定义超出此盒子滚动 */
  overflow-y: hidden;
  display: flex;
}

.userNameItem {
  white-space: nowrap;
  border-radius: 0.2em;
}

.displayName::-webkit-scrollbar {
  display: none;
}

.van-tag--primary {
  padding: 0.4em;
}

.deptItem .el-checkbox {
  padding-left: 3vw;
}
</style>
