<template>
  <div style="height: 100%;">
    <van-search v-model="keyword" placeholder="请输入姓名搜索" />
    <div class="body_com" :class="{show_dept_path:pid_list_arr.length > 0}">
      <scroller :on-refresh="get_user_list" ref="scroller_com">
        <!-- can_select_dept  选择部门传值 -->
        <van-cell
          :is-link="!can_select_dept"
          v-for="(item,index) in dept_list"
          :key="index"
          :title="item.name"
          v-show="item.pid == pid && item.name.indexOf(keyword) >= 0 && dept_not_select.indexOf(item.id) < 0"
          class="employee_cell"
          @click="select_dept(item)"
        >
        
          <template slot="icon">
            <van-checkbox v-if="can_select_dept" v-model="item.checked"></van-checkbox>
            <img v-if="can_select_dept" src="static/images/e66f.jpg" class="employee_cell_head_img" />
            <!-- <userImage :id="item.id" width="0.8rem" height="0.8rem" ></userImage> -->
          </template>
          <template slot="right-icon" v-if="can_select_dept&&item.count>0">
            <a href="javascript:void(0);" class="child_btn" @click.stop="show_child(item)">| 下级</a>
          </template>
        </van-cell>
        <div v-for="(item,index) in list" :key="index" v-if="can_select_employee" v-show="item.name.indexOf(keyword) >= 0">
          <div
            v-if="index == 0"
            :data-pageindex="item.letter_index"
            class="pageIndexBtn"
          >{{item.letter_index}}</div>
          <div
            v-if="index > 0 && list[index-1].letter_index != item.letter_index"
            :data-pageindex="item.letter_index"
            class="pageIndexBtn"
          >{{item.letter_index}}</div>
          <van-cell
            :class="{'letter-first': index == 0 || (index > 0 && list[index-1].letter_index != item.letter_index)}"
            v-if="can_select_employee"
            :title="item.name"
            class="employee_cell"
            @click="select_employee(item)"
          >
            <template slot="icon">
              <van-checkbox
                :style="{opacity: employee_not_select.indexOf(item.id) < 0 ? 1 :0}"
                v-model="item.checked"
              ></van-checkbox>
              <userImage
                class="employee_cell_head_img"
                :img_url ="item.img_url"
                :user_name="item.name"
                width="0.8rem"
                height="0.8rem"
                fontSize="0.2"
              ></userImage>
              <!-- <img :src="item.img_url"class="employee_cell_head_img"/> -->
            </template>
            <template slot="right-icon" v-if="typeof(item.status) != 'undefined'">
              <van-tag plain v-show="item.status == 0 || item.status == 2">{{item.status == 0 ?'未加入':'离职'}}</van-tag>
            </template>
          </van-cell>
        </div>
      </scroller>
    </div>
    <slot name="footer"></slot>
    <div class="bottom_menu">
      <div class="selected_box" ref="selected_box">
        <ul :style="'width:'+selected_box_width">
          <li v-for="(item,index) in employee_selected_list" @click.stop="employee_cancel(item)" :key="index" style="width:0.9rem; overflow: hidden; height:0.9rem;">
            <userImage
              :img_url ="item.img_url"
              :user_name="item.name"
              width="0.9rem"
              height="0.9rem"
              fontSize="0.2"
            ></userImage>
            <div class="name_mini">{{item.name}}</div>
          </li>
          <li v-for="(item,index) in dept_selected_list" :key="index">
            <img @click="dept_cancel(item)" src="static/images/e66f.jpg" />
            <div class="name_mini">{{item.dept_name}}</div>
          </li>
        </ul>
      </div>
    </div>
  </div>

</template>

<script>
import Vue from 'vue';
import { ActionSheet, Popup, Checkbox, Tag } from 'vant';
Vue.use(Popup).use(Tag);
Vue.use(Checkbox);
Vue.use(ActionSheet);
import { Search } from 'vant';
import userImage from '@/components/common/user_image'
Vue.use(Search);
import request from '@/utils/request'
export default {
  props: {
    position: {
      type: String,
      default: 'bottom'
    },
    append_body: {
      type: Boolean,
      default: false
    },
    visible: {
      type: Boolean,
      default: false
    },
    can_select_dept: {
      type: Boolean,
      default: true
    },
    can_select_employee: {
      type: Boolean,
      default: true
    },
    employee_not_select: {
      type: Array,
      default: () => { return [] }
    },
    dept_not_select: {
      type: Array,
      default: () => { return [] }
    },
    selected: {
      type: Object,
      default: () => {
        return { employee: [], dept: [] }
      }
    },
    multi: {
      type: Boolean,
      default: true
    },
    dept_multi: {
      type: Boolean,
      default: true
    },
    employee_list: {
      type: Array,
      default: null
    },
    use_employee_list: {
      type: Boolean,
      default: false
    },
    close_clear_data: {
      type: Boolean,
      default: true
    },
    max: {
      type: Number,
      default: 0
    },
    include_self:{
      type: Boolean,
      default: true
    },
    show_manager_only:{
      type: Boolean,
      default: false
    },
    title:{
      type: String,
      default: ''
    },
  },
  name: "EmployeeSelectorNoMark",
  components: { userImage },
  data() {
    let selected = JSON.parse(JSON.stringify(this.selected))
    return {
      employee_selected_list: selected.employee,
      dept_selected_list: selected.dept,
      employee_selected: [],
      dept_selected: [],
      com_height: '100%',
      company_info: {},
      actions_show: false,
      dept_name: '',
      dept_id: 0,
      list: [],
      dept_list: [],
      keyword: '',
      owner_id: 0,
      user_info: this.$store.getters.user_info,
      pid: 0,
      pid_list: [],
      selected_box_width: '0',
      pid_list_arr: [],
      visible_: false,
      cache_list: []
    }
  },
  watch: {
    max(val) {
      this.set_button_width()
    },
    selected(val) {
      let selected = JSON.parse(JSON.stringify(val))
      this.employee_selected = []
      this.dept_selected = []
      this.employee_selected_list = selected.employee
      this.dept_selected_list = selected.dept
      for (let i in selected.employee) {
        this.employee_selected.push(selected.employee[i].id)
      }
      for (let i in selected.dept) {
        this.dept_selected.push(selected.dept[i].dept_id)
      }
      for(let i in this.list){
        this.list[i]['checked'] = false
        if (this.employee_selected.indexOf(this.list[i].id) >= 0) {
          this.list[i]['checked'] = true
        }
      }

      this.set_button_width()
    },
    visible(val) {
      this.visible_ = JSON.parse(JSON.stringify(val))
      if (val) {
        setTimeout(() => {
          if (this.$route.query.pid) {
            this.pid = this.$route.query.pid
          }
          this.get_user_list(function () {

          })
          this.get_dept_list()
        }, 200)
      }
      this.set_button_width()
    },
    employee_selected_list() {
      let l = this.employee_selected_list.length + this.dept_selected_list.length
      let width = 0.9 * l;
      this.selected_box_width = width + 'rem'
      this.set_button_width()
    },
    dept_selected_list() {
      let l = this.employee_selected_list.length + this.dept_selected_list.length
      let width = 0.9 * l;
      this.selected_box_width = width + 'rem'
      this.set_button_width()
    },
    keyword() {
      this.get_user_list(function () {

      })
    }
  },
  beforeDestroy() {
    if (this.append_body) {
      document.body.removeChild(this.$el)
    }
    this.close();
  },
  methods: {
    set_button_width() {

    },
    back() {
      this.pid = this.pid_list[this.pid_list.length - 1]
      this.pid_list.splice(this.pid_list.length - 1)
      this.pid_list_arr.splice(this.pid_list_arr.length - 1)
      this.get_user_list(function () {

      })
    },
    back_by_index(index) {

      if (index == this.pid_list.length) {
        return false
      }
      this.pid = this.pid_list[index]
      this.pid_list.splice(index, 100)
      this.pid_list_arr.splice(index, 100)
      this.get_user_list(function () {

      })
    },
    show_child(item) {
      this.pid_list.push(this.pid)
      this.pid_list_arr.push(item)
      this.pid = item.id
      this.list = []
      this.get_user_list(function () {

      })
    },
    employee_cancel(item) {
      this.employee_selected.splice(this.employee_selected.indexOf(item.id), 1)
      let delete_index = -1
      for (let i in this.employee_selected_list) {
        if (this.employee_selected.indexOf(this.employee_selected_list[i].id) < 0) {
          delete_index = i
        }
      }
      if (delete_index >= 0) {
        this.employee_selected_list.splice(delete_index, 1)
        for (let i in this.list) {
          if (this.list[i].id == item.id) {
            this.$set(this.list[i], 'checked', false)
          }
        }
      }
      this.$emit('confirm', {
        employee: this.employee_selected_list,
        dept: this.dept_selected_list
      })
    },
    dept_cancel(item) {
      this.dept_selected.splice(this.dept_selected.indexOf(item.id), 1)
      let delete_index = -1
      for (let i in this.dept_selected_list) {
        if (this.dept_selected.indexOf(this.dept_selected_list[i].id) < 0) {
          delete_index = i
        }
      }
      if (delete_index >= 0) {
        this.dept_selected_list.splice(delete_index, 1)
        for (let i in this.dept_list) {
          if (this.dept_list[i].dept_id == item.id) {
            this.$set(this.dept_list[i], 'checked', false)
          }
        }
      }
    },
    select_employee(item) {
      if (this.employee_not_select.indexOf(item.id) >= 0) {
        return false
      }
      if (item.checked) {
        item.checked = false
        this.employee_cancel(item)
      } else {
        if (!this.multi) {
          this.employee_selected = []
          this.employee_selected_list = []
          for (let i in this.list) {
            this.$set(this.list[i], 'checked', false)
          }
        }
        if (this.max > 0 && this.employee_selected.length == this.max && this.multi) {
          this.$toast('最多只能选择' + this.max + '人')
          return false
        }
        this.employee_selected.push(item.id)
        this.employee_selected_list.push({ id: item.id, name: item.name, img_url: item.img_url })
        item.checked = true
      }
      this.$emit('confirm', {
        employee: this.employee_selected_list,
        dept: this.dept_selected_list
      })
    },
    select_dept(item) {
      if (!this.can_select_dept) {
        this.show_child(item)
        return false
      }
      if (item.checked) {
        item.checked = false
        this.dept_cancel(item)
      } else {
        if (!this.dept_multi) {
          this.dept_selected = []
          this.dept_selected_list = []
          for (let i in this.dept_list) {
            this.$set(this.dept_list[i], 'checked', false)
          }
        }
        this.dept_selected.push(item.id)
        this.dept_selected_list.push({ dept_id: item.id, dept_name: item.name, avatar: 'static/images/e66f.jpg' })
        item.checked = true
      }
    },
    close() {
      //this.visible = false
      this.$emit('update:visible', false)
      this.$emit('cancel')
      if (this.close_clear_data) {
        this.employee_selected = []
        this.employee_selected_list = []
        this.dept_selected = []
        this.dept_selected_list = []
        for (let i in this.list) {
          this.$set(this.list[i], 'checked', false)
        }
        for (let i in this.dept_list) {
          this.$set(this.dept_list[i], 'checked', false)
        }
      }

    },
    confirm() {
      this.$emit('confirm', {
        employee: this.employee_selected_list,
        dept: this.dept_selected_list
      })
      this.close()
    },
    get_dept_list() {
      if (this.use_employee_list || this.show_manager_only) {
        return
      }
      request('get','/api/department/index',{ pid: this.pid, keyword: this.keyword }).then((res) => {
        for (let i in res.data.data.list) {
          res.data.data.list[i]['checked'] = false
          if (this.dept_selected.indexOf(res.data.data.list[i].id) >= 0) {
            res.data.data.list[i]['checked'] = true
          }
        }
        this.dept_list = res.data.data.list
        this.owner_id = res.data.data.owner_id
        this.company_info = res.data.data.company_info
        if (res.data.data.dept_info == null) {
          this.dept_name = JSON.parse(JSON.stringify(res.data.data.company_info.name))
          this.dept_id = 0
        } else {
          this.dept_name = JSON.parse(JSON.stringify(res.data.data.dept_info.name))
          this.dept_id = res.data.data.dept_info.id
        }
        this.$toast.clear()
      }).catch((e) => {
        this.$toast.clear()
      })
    },
    parse_list(data) {
      this.list = []
      let _list = []
      for (let i in data) {
        data[i]['checked'] = false
        if (this.employee_selected.indexOf(data[i].id) >= 0) {
          data[i]['checked'] = true
        }
        if (data[i].img_url == '') {
          data[i].img_url = ''
        }
      }

      this.list = data
      this.$nextTick(() => {
        if (this.visible && this.can_select_employee) {
          this.$refs['scroller_com'].createPageIndex()
        }
      })
    },
    get_user_list(done) {
      if (this.use_employee_list) {
        let list = this.employee_list
        for (let i in list) {
          list[i]['letter_index'] = '#'
          if (this.$store.getters.employee_map[list[i].id]) {
            list[i]['letter_index'] = this.$store.getters.employee_map[list[i].id].letter_index
            if (this.$store.getters.employee_map[list[i].id].img_url == '') {
              list[i]['img_url'] = 'static/images/defalut_custmer_headicon.png'
            } else {
              list[i]['img_url'] = this.$store.getters.employee_map[list[i].id].img_url
            }
            list[i]['status'] = this.$store.getters.employee_map[list[i].id].status
          }

          list[i]['checked'] = false
          if (this.employee_selected.indexOf(list[i].id) >= 0) {
            list[i]['checked'] = true
          }

        }
        this.list = list.sort((a, b) => {
          return a.letter_index.charCodeAt(0) - b.letter_index.charCodeAt(0)
        })
        done()
        this.$nextTick(() => {
          if (this.visible && this.can_select_employee) {
            this.$refs['scroller_com'].createPageIndex()
          }
        })

        this.removeSelf(list)
        this.dept_list = []
        return false
      }
      if (this.cache_list[this.pid]) {
        this.parse_list(this.cache_list[this.pid])
        done()
      }

      if (this.loadingUserList){
         return
      }

      this.loadingUserList = true
      request('get','/api/employee/list',{ dept_id: this.pid, keywords: this.keyword, page: 0, page_size: 2000 }).then((res) => {
        let _list = []
        if(this.show_manager_only){
          //把其它无关的人干掉
          for(let i in res.data.data.list){
            let is_manager = false
            for(let j in res.data.data.list[i].role_list){
              if(res.data.data.list[i].role_list[j].name == 'creator' || res.data.data.list[i].role_list[j].name == 'point_manager' || res.data.data.list[i].role_list[j].name == 'dept_manager' || res.data.data.list[i].role_list[j].name == 'admin'){
                is_manager = true
              }
            }
            if(is_manager){
              _list.push(res.data.data.list[i])
            }
          }
        }else{
          _list = res.data.data.list
        }
        const list = _list

        this.cache_list[this.pid] = this.removeSelf(list)
        this.parse_list(list)
        done()
        this.$toast.clear()
      }).catch((e) => {
        done()
        this.$toast.clear()
      }).finally(()=>this.loadingUserList = false)
    },
    removeSelf(list){
      if (!this.include_self){
        const currUserId = this.$store.getters.user_info.id
        const index = list.findIndex(o=>o.id === currUserId)
        if(index > -1){
          list.splice(index, 1)
        }
      }
      return list
    }
  },
  created() {
    if (document.documentElement.style.height) {
      this.com_height = document.documentElement.style.height
    }
    this.pid = this.$route.query.pid || 0
  }
}
</script>

<style scoped>
.body_com {
  height: calc(100% - 2rem);
  position: relative;
}
.body_com.show_dept_path {
  height: calc(100% - 3.48rem);
}
.bottom_menu {
  height: 0.8rem;
  text-align: center;
  line-height: 0.8rem;
  position: relative;
  display: table;
}
.bottom_menu:before {
  content: ' ';
  height: 1px; /*no*/
  background-color: #eee;
  width: 100%;
  top: 0;
  left: 0;
  position: absolute;
}
.bottom_menu a {
  color: #1989fa;
  font-size: 0.32rem;
}

.employee_cell_head_img {
  width: 0.8rem;
  height: 0.8rem;
  margin-left: 0.16rem;
  -webkit-border-radius: 0.1rem;
  -moz-border-radius: 0.1rem;
  border-radius: 0.1rem;
  margin-right: 0.15rem;
}

.employee_cell {
  padding: 0.16rem 0.32rem;
}
.employee_cell .van-checkbox {
  overflow: visible;
}
.employee_cell .van-cell__title {
  line-height: 0.8rem;
}
.employee_cell .van-cell__right-icon {
  margin-top: 0.2rem;
}
.employee_cell .van-icon {
  color: #999;
  margin-top: 0.2rem;
}

.employee_selector_popup {
  height: 100%;
}
.child_btn {
  color: #1989fa;
  display: block;
  height: 1.14rem;
  position: absolute;
  right: 0.32rem;
  top: 0;
  padding: 0 0.16rem;
  line-height: 1.1rem;
  font-size: 0.28rem;
}
.child_btn:active {
  color: #323233;
}
.bottom_menu {
  width: 100%;
  height: 0.9rem;
}
.selected_box,
.selected_btn {
  vertical-align: top;
  text-align: left;
}
.selected_btn {
  text-align: center;
  float: right;
}

.selected_box {
  overflow-x: scroll;
  width: 7.5rem;
  float: left;
  min-height: 0.5rem;
}
.selected_box ul,
.selected_box li {
  margin: 0;
  padding: 0;
  text-align: left;
}
.selected_box li {
  display: block;
  text-align: left;
  float: left;
  position: relative;
}
.selected_box li img {
  width: 0.8rem;
  vertical-align: top;
  height: 0.8rem;
  padding: 0.05rem;
  -webkit-border-radius: 0.1rem;
  -moz-border-radius: 0.1rem;
  border-radius: 0.1rem;
}
.name_mini {
  font-size: 0.2rem;
  position: absolute;
  bottom: 0.05rem;
  left: 0.05rem;
  right: 0.05rem;
  padding: 0.02rem 0;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.4);
  height: 0.2rem;
  color: #fff;
  line-height: 0.2rem;
}
.dept_path a {
  color: #238dfa;
  font-size: 0.28rem;
}
.dept_path a:nth-last-child(1) {
  color: #999;
}
.dept_path a * {
  vertical-align: middle;
}
.dept_path {
  height: 0.6rem;
  position: relative;
  font-size: 0.32rem;
  line-height: 0.4rem;
  overflow-x: scroll;
  padding: 0 0.32rem;
}
.dept_path:after {
  content: ' ';
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #efefef;
  height: 1px;
  position: absolute;
  transform: scaleY(0.5);
}
.pageIndexBtn {
  width: 100%;
  text-align: left;
  padding: 0.1rem 0.4rem 0.05rem;
  color: #909399;
  background: rgb(245, 245, 245);
  font-size: 0.24rem;
}
.employee_cell .van-tag{
  display: inline-table;
  margin-top: 0.16rem;
}
</style>

