<template>
  <van-popup @open="openPopup" :duration="0.2" :overlay="false" class="employee_selector_popup" v-model="visible_" :position="position" :style="'height:' + com_height">
    <slot name="nav"></slot>
    <van-nav-bar v-if="!$slots.nav" :title="title" left-text="取消" @click-left="close"></van-nav-bar>
    <van-search v-model="keyword" v-if="can_select_employee" placeholder="请输入姓名搜索" />
    <van-search v-model="keyword" v-else placeholder="请输入部门名称搜索" />
    <template v-if="isShowDeptsAll">
      <div @click="isShowDeptSelect()" class="sax">
        部门筛选
        <van-icon style="position: relative;top: 2px;" :name="!isShowDept ? 'arrow-down' : 'arrow-up'" color="#909399" />
      </div>
      <div class="dept_path" v-show="pid_list_arr.length > 0 && isShowDept">
        <a href="javascript:void(0);" @click="back_by_index(0)">全公司</a>
        <a v-for="(item, index) in pid_list_arr" :key="index" href="javascript:void(0);" @click="back_by_index(index + 1, item)">
          <van-icon name="arrow" />
          <Wxopendata type="departmentName" :openid="item.name"></Wxopendata>
        </a>
      </div>
    </template>
    <div class="body_com" :class="{ show_dept_path: pid_list_arr.length > 0 }">
      <scroller ref="scroller_com">
        <van-cell
          :is-link="!can_select_dept"
          v-for="(item, index) in dept_list"
          :key="index"
          :title="item.name"
          v-show="isShowDept && 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" />
          </template>
          <template slot="title">
            <Wxopendata type="departmentName" :openid="item.name"></Wxopendata>
          </template>
          <template slot="right-icon" v-if="item.children.length > 0">
            <a href="javascript:void(0);" class="child_btn" @click.stop="show_child(item)">| 下级</a>
          </template>
        </van-cell>

        <div style="height: .4rem; background: rgb(245, 245, 245);" v-show="selected_all"></div>
        <van-cell v-show="selected_all">
          <template #title>
            <van-checkbox v-model="checked_btn" @change="checked_change">全选</van-checkbox>
          </template>
        </van-cell>
        <div v-for="(item, index) in list" :key="index" v-if="can_select_employee">
          <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 + (item.identification ? '(直属上级)' : '')"
            class="employee_cell"
            @click="select_employee(item)"
          >
            <template slot="icon">
              <van-checkbox
                v-if="selectedQuitEmployee"
                :style="item.status > 1 || employee_not_select.indexOf(item.id) >= 0 ? 'opacity: 0' : 'opacity: 1'"
                v-model="item.checked"
              ></van-checkbox>
              <van-checkbox v-if="!selectedQuitEmployee" :style="employee_not_select.indexOf(item.id) > 0 ? 'opacity: 0' : 'opacity: 1'" 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>
            </template>
            <template slot="title">
              <Wxopendata type="userName" :openid="item.name"></Wxopendata>
              {{ item.identification ? '(直属上级)' : '' }}
            </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>
        <van-empty v-if="list.length == 0" description="暂无数据..." />
        <div style="height: 1rem;"></div>
      </scroller>
    </div>
    <slot name="footer"></slot>
    <div class="bottom_menu flex-box flex-v-ce" :class="{ isIos: isIos }">
      <div class="selected_box flex-1">
        <div class="flex-box flex-v-ce ul" :style="'width:' + selected_box_width">
          <div v-for="(item, index) in employee_selected_list" :key="index" @click="employee_cancel(item)" class="li">
            <userImage :img_url="item.img_url" :user_name="item.name" width="0.9rem" height="0.9rem" fontSize="0.2"></userImage>
          </div>
          <div v-for="(item, index) in dept_selected_list" :key="index" @click="dept_cancel(item)" class="fb">
            <img src="static/images/e66f.jpg" />
            <div class="name_mini"><Wxopendata type="departmentName" :openid="item.dept_name"></Wxopendata></div>
          </div>
        </div>
      </div>
      <div class="selected_btn" ref="selected_btn">
        <van-button ref="selected_button" style="height: 0.7rem; line-height: 0.7rem;" type="info" @click="confirm">
          确定
          <template v-if="multi && max * 1 > 0">
            ({{ employee_selected_list.length }}/{{ max }})
          </template>
        </van-button>
      </div>
    </div>
  </van-popup>
</template>

<script>
import Vue from 'vue';
import { ActionSheet, Popup, Checkbox, Tag, Search } from 'vant';

import userImage from '@/components/common/user_image';
import request from '@/utils/request';
Vue.use(Popup).use(Tag);
Vue.use(Checkbox);
Vue.use(ActionSheet);
Vue.use(Search);
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: {
      // 排除员工的ID，包含ID时不出现在选择列表中
      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: {
      // 指定显示的员工列表，注意：传值后组件的员工数据将不是统一向服务器获取的，而是指定的员工列表，格式是：[{id: 1, name: “张三”, img_url: “”}]
      type: Array,
      default: () => {
        return [];
      }
    },
    use_employee_list: {
      // 为true时，employee_list才生效
      type: Boolean,
      default: false
    },
    close_clear_data: {
      // 关闭时是否清空选择的数据
      type: Boolean,
      default: true
    },
    max: {
      // 当multi为true时，用来限制选择人数，0不生效
      type: Number,
      default: 0
    },
    include_self: {
      // 是否显示当前登录的员工信息
      type: Boolean,
      default: true
    },
    show_manager_only: {
      // 是否只显示管理者列表
      type: Boolean,
      default: false
    },
    title: {
      // cell的显示名称
      type: String,
      default: ''
    },
    selected_all: {
      // 是否选择全部
      type: Boolean,
      default: false
    },
    selectedQuitEmployee: {
      //
      type: Boolean,
      default: true
    },
    is_filtration_creator: {
      // 是否过滤掉创始人
      type: Boolean,
      default: false
    },
    isShowDepts: {
      // 默认是否显示部门
      type: Boolean,
      default: false
    },
    deptId: {
      // 指定显示某部门的人员，（这是部门ID）
      type: Number,
      default: 0
    },
    isShowDeptsAll: {
      // 是否不可看部门选择
      type: Boolean,
      default: true
    }
  },
  name: 'EmployeeSelector',
  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%',
      dept_name: '', // 公司名称
      dept_id: 0, // 公司ID
      list: [], // 人员列表
      dept_list: [], // 部门列表
      dept_list_all: [], // 备用
      keyword: '', // 关键字
      pid: 0,
      selected_box_width: '0',
      pid_list_arr: [], // 选择的公司，顶部显示
      visible_: false, // 是否显示组件
      cache_list: [],
      checked_btn: false,
      isIos: false, // 是否需要兼容IOS X以上
      isShowDept: false // 控制显示部门选择
    };
  },
  watch: {
    selected(val) {
      this.setSelected(val);
    },
    // 显示组件并调用初始化数据接口
    visible(val) {
      this.visible_ = JSON.parse(JSON.stringify(val));
      if (val) {
        setTimeout(() => {
          if (this.$route.query.pid) {
            this.pid = this.$route.query.pid;
          }
          if (this.deptId != 0) {
            this.pid = this.deptId;
          }
          this.get_user_list(function() {});
          this.get_dept_list();
        }, 200);
      }
    },
    employee_selected_list() {
      let l = this.employee_selected_list.length + this.dept_selected_list.length;
      let width = 1 * l;
      this.selected_box_width = width + 'rem';
    },
    dept_selected_list() {
      let l = this.employee_selected_list.length + this.dept_selected_list.length;
      let width = 1 * l;
      this.selected_box_width = width + 'rem';
    }
    // keyword () {
    //   this.get_user_list(function () {})
    // }
  },
  mounted() {
    this.isShowDept = this.isShowDepts;
  },
  methods: {
    setSelected(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);
      }
    },
    // 打开时触发
    openPopup() {
      this.setSelected(this.selected);
    },
    // 控制部门显示隐藏
    isShowDeptSelect() {
      this.isShowDept = !this.isShowDept;
    },
    checked_change(val) {
      if (val) {
        for (let i in this.list) {
          this.$set(this.list[i], 'checked', true);
        }
        this.$nextTick(() => {
          let employeeSelectedList = JSON.parse(JSON.stringify(this.employee_selected_list));
          let employeeSelectedIds = [],
            total = 0;
          employeeSelectedList.forEach(element => {
            employeeSelectedIds.push(element.id);
          });
          for (const i in this.list) {
            if (this.employee_not_select.indexOf(this.list[i].id) < 0) {
              this.$set(this.list[i], 'checked', true);
              if (employeeSelectedIds.includes(this.list[i].id)) {
                total += 1;
              } else {
                this.employee_selected_list.push(this.list[i]);
              }
            }
          }
        });
      } else {
        this.employee_selected_list = [];
        this.employee_selected = [];
        for (let i in this.list) {
          this.$set(this.list[i], 'checked', false);
        }
      }
    },
    back_by_index(index, item) {
      this.pid_list_arr.splice(index, 100);
      if (index == 0) {
        // 点击全部
        this.dept_list = this.dept_list_all;
        this.pid_list_arr = [];
        this.pid = 0;
      }
      if (item) {
        if (item.children) {
          this.dept_list = item.children;
          this.pid = item.id;
        }
      }
      this.get_user_list(function() {});
    },
    show_child(item) {
      if (item.children) {
        this.dept_list = item.children;
      }
      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);
          }
        }
      }
    },
    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.selectedQuitEmployee) {
        if (this.employee_not_select.indexOf(item.id) >= 0 || item.status > 1) {
          return false;
        }
      } else {
        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;
      }
    },
    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.$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() {
      this.dept_map = {};
      request('get', '/api/department/tree', '')
        .then(res => {
          var userList = res.data.data.list || [];
          for (let i in userList) {
            userList[i]['checked'] = false;
            if (this.dept_selected.indexOf(userList[i].id) >= 0) {
              userList[i]['checked'] = true;
            }
          }
          this.dept_list = userList;
          this.dept_list_all = userList;
        })
        .finally(() => {
          this.$toast.clear();
        });
    },
    // 选择部门来筛选人，默认选择中的人勾上
    parse_list(data) {
      this.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.loadingUserList) {
        return;
      }
      this.loadingUserList = true;
      request('get', '/api/employee/index', { dept_id: this.pid, keywords: this.keyword, page: 0, page_size: 2000, is_official: 1 })
        .then(res => {
          var list = this.filtration(res.data.data.list); // 过滤各种条件
          // 当有指定显示列表时
          console.log(this.use_employee_list);
          console.log(this.employee_list);
          console.log(list);
          if (this.use_employee_list) {
            var employeeList = this.employee_list;
            var userData = [];
            list.map(item => {
              // 列表数据是否是自己的管理范围
              employeeList.map(item2 => {
                if (item.id == item2.id) {
                  userData.push(item);
                }
              });
            });
            console.log(userData);
            this.parse_list(userData);
          } else {
            // 没有指定人员列表
            this.cache_list[this.pid] = list;
            this.parse_list(list);
          }
        })
        .finally(() => {
          done();
          this.$toast.clear();
          this.loadingUserList = false;
        });

      // 当点击选择部门时,传入部门ID过去出符合人员
      if (this.cache_list[this.pid]) {
        this.parse_list(this.cache_list[this.pid]);
        done();
      }
    },
    // 过滤各种条件：如：自己，创始人，只显示管理者等。。。
    filtration(data) {
      var list = data;
      // 去除已经离职的人
      for (let i = 0; i < list.length; i++) {
        if (list[i].status == 2) {
          list.splice(i, 1);
          i--;
        }
      }
      var managerList = []; // 管理者列表
      // 只显示管理者
      if (this.show_manager_only) {
        var isManager;
        list.map(item => {
          isManager = false;
          item.employee_detail.role_list.map(item2 => {
            if (item2.name == 'creator' || item2.name == 'point_manager' || item2.name == 'dept_manager' || item2.name == 'admin') {
              isManager = true;
            }
          });
          if (isManager) {
            managerList.push(item);
          }
        });
        list = managerList;
      }

      // 过滤自己
      if (!this.include_self) {
        const currUserId = this.$userInfo().id;
        for (let i = 0; i < list.length; i++) {
          if (list[i].id == currUserId) {
            list.splice(i, 1);
            i--;
          }
        }
      }
      // 过滤创始人
      if (this.is_filtration_creator) {
        for (let i = 0; i < list.length; i++) {
          if (list[i].is_creator == 1) {
            list.splice(i, 1);
            i--;
          }
        }
      }
      return list;
    }
  },
  created() {
    if (document.documentElement.style.height) {
      this.com_height = document.documentElement.style.height;
    }
    if (window.plus) {
      this.isIos = plus.storage.getItem('iPhone') == 'false' ? false : true;
    }
  },
  // 组件生命周期销毁时调用
  beforeDestroy() {
    if (this.append_body) {
      this.$nextTick(() => {
        if (document.body.contains(this.$el)) {
          //判断有无在body中
          document.body.removeChild(this.$el);
        }
      });
    }
    this.close();
  }
};
</script>

<style scoped>
.sax {
  text-align: center;
  font-size: 0.32rem;
  padding-bottom: 0.2rem;
  border-bottom: 1px solid #f1f1f1;
}
.body_com {
  height: calc(100% - 3.2rem);
  position: relative;
}
.isIos {
  padding-bottom: 0.4rem !important;
}
.body_com.show_dept_path {
  height: calc(100% - 3.48rem);
}
.bottom_menu {
  text-align: center;
  position: fixed;
  padding: 0.1rem 0.16rem;
  min-height: 0.9rem;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
}
.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;
  transition: all 1s;
}

.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%;
  width: 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;
}
.selected_box,
.selected_btn {
  vertical-align: top;
}
.selected_btn {
  text-align: center;
}
.selected_box {
  overflow-x: scroll;
  margin-right: 0.16rem;
}
.ul .li {
  width: 0.9rem;
  height: 0.9rem;
  margin-right: 0.1rem;
}
.ul .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;
}
.ul .fb {
  width: 0.9rem;
  height: 0.9rem;
  margin-right: 0.1rem;
  position: relative;
}
.ul .fb 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: 0rem;
  left: 0rem;
  right: 0rem;
  padding: 0.02rem 0;
  text-align: center;
  background-color: rgba(0, 0, 0, 0.4);
  height: 0.2rem;
  color: #fff;
  line-height: 0.2rem;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.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.5rem;
  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>
