<template>
  <div style="height: 100%;" class="department_box">
    <van-nav-bar class="headerbar no-down-icon" title="组织架构">
      <!--  v-if="user_info.id==owner_id" -->
      <template slot="left" v-if="pid > 0">
        <div @click="back">
          <van-icon name="arrow-left" /><span class="van-nav-bar__text">返回</span>
        </div>
      </template>
      <template slot="left" v-if="pid == 0">
        <div @click="$route_back">
          <van-icon name="arrow-left" /><span class="van-nav-bar__text">返回</span>
        </div>
      </template>
    </van-nav-bar>

    <div class="work_body_com">
      <scroller ref="scroller_com" :on-refresh="refresh">
        <van-search class="scroller-blur" v-model="keyOword" placeholder="请输入搜索姓名" @input="searchUser()" />
         <div class="dept_path" v-show="pid_list_arr.length > 0 ">
          <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>

        <div>
          <van-cell-group :border="false" v-show="pid==0" >
            <van-cell label-class="employee_count"
            :title="company_info.name"
            :border="false" clickable class="company_info"
            :is-link="this.getRole_noe"
            :label="employee_count.all +'人'">
              <template slot="icon">
                <img :src="company_info.logo_url?company_info.logo_url:'static/images/default_company_logo.png'" class="company_dept_img"/>
              </template>
            </van-cell>
          </van-cell-group>
          <van-cell-group>
            <van-cell  v-if="isApp && false" is-link title="邀请成员" @click="show_share" class="new_employee_cell employee_cell">
              <template slot="icon">
                <icon name="message_newinvit" class="message_newinvit"></icon>
              </template>
            </van-cell>
          </van-cell-group>
          <!-- 部门列表 -->
          <van-cell-group>
            <van-cell is-link v-for="(item,index) in dept_list" v-show="item.pid == pid" :key="index" :title="item.name + ' ('+ item.count +')'" class="employee_cell" @click="show_child(item)">
              <template slot="icon">
                <icon name="message_department" class="message_department"></icon>
              </template>
              <template slot="title">
                <Wxopendata type="departmentName" :openid="item.name"></Wxopendata>({{item.count}})
              </template>
            </van-cell>
            <van-cell v-if="user_info.id==owner_id && pid_list == false" is-link title="加入申请" class="employee_cell" to="/join_review">
              <template slot="icon">
                <img src="static/images/join_review.jpg" class="employee_cell_head_img"/>
              </template>
            </van-cell>
          </van-cell-group>

          <div class="employee_item" :class="{'letter-first': index == 0 || (index > 0 && employee_list[index-1].letter_index != item.letter_index)}" v-for="(item,index) in employee_list " :key="index">
            <van-cell class="employee_cell" :title="item.name">
              <template slot="icon">
                <userImage  :user_name="item.name" :img_url="item.img_url" width="0.9rem" height="0.9rem" style="margin-right: 0.24rem;" ></userImage>
              </template>
              <template slot="title">
                <Wxopendata type="userName" :openid="item.name"></Wxopendata>
              </template>
              <template slot="right-icon">
                <van-tag plain v-if="item.manage_dept_ids.length>0" type="warning">主管</van-tag>
                <van-tag plain v-if="item.status == 0">
                    <span>未加入</span>
                </van-tag>
                <van-tag plain v-if="item.status == 2">
                    <span>离职</span>
                </van-tag>
                <van-tag plain v-if="item.status == 3">
                    <span>再次邀请</span>
                </van-tag>
              </template>
            </van-cell>
          </div>

          <div v-if="employee_list.length == 0 && dept_list.length == 0 && showDom">
              <van-row type="flex" justify="space-around" class="c">
                <van-col span="24">
                  <div style="margin: 0.5rem 0 0.3rem 0;text-align: center;">
                    <img src='static/images/noPeople.png' style="width: 2.5rem;height: 2.5rem;"/>
                  </div>
                  <p class="text_center">暂无部门和人员</p>
                  <p class="text_center">点击右上方的+</p>
                   <p class="text_center">现加部门后加人</p>
                </van-col>
              </van-row>
          </div>
        </div>
      </scroller>
    </div>
    <van-popup :duration="0" class="search_popup" :class="{show_search_popup: show_search_popup}" v-model="show_search_popup_" position="right" get-container="body" style="width: 100vw; height: 100vh;" :overlay="false">
      <div :style="'padding-top:' + bar_height + 'px;background-color: #26A2FF;'"></div>
      <van-nav-bar class="headerbar no-down-icon" title="通讯录" left-text="返回" @click-left="close_search_popup" left-arrow></van-nav-bar>
      <van-search ref="search1" class="scroller-blur" placeholder="请输入搜索姓名" v-model="keyword" />
      <div class="search_list">
      </div>
      <noData v-show="search_show" v-model="search_result_list" ></noData>
    </van-popup>

    <van-action-sheet v-model="show" get-container="boby" title="邀请成员">
      <share :share_data="share_data"></share>
    </van-action-sheet>

    <qrcode v-if="show_qrcode" :show="qrcode_popup_show" :logo="company_info.logo_url" @changeShow="qrcode_popup_show=false"></qrcode>
  </div>

</template>

<script>
import request from '@/utils/request'
import {getRole_noe} from '@/utils/auth'
import share from '@/components/common/share'
import qrcode from '@/components/common/coreDialog'
import userImage from '@/components/common/user_image'
import Echo from 'laravel-echo'
import { _throttle } from '@/utils/auth';
import Vue from 'vue'
import {Search, Tag, IndexBar, IndexAnchor, Skeleton, DropdownMenu, DropdownItem, ActionSheet, Toast, SwipeCell} from 'vant'
Vue.use(Search).use(Tag).use(IndexBar).use(IndexAnchor).use(Skeleton).use(DropdownMenu).use(DropdownItem).use(ActionSheet).use(SwipeCell)
export default {
  name: 'department',
  data () {
    return {
      bar_height: '',
      show_search_popup_: true,
      showDom: false,
      pid_list_arr: [],
      list: [],
      dept_list: [],
      dept_info: {},
      showDepart: false,
      company_info: {},
      employee_list: [],
      employee_count: {},
      keyword: '',
      owner_id: 0,
      user_info: this.$store.getters.user_info,
      employee_map: this.$store.getters.employee_map,
      pid: 0,
      pid_list: [],
      options: [],
      share_data: {
        type: '',
        title: '',
        content: '',
        thumbs: '',
        href: ''
      },
      shares: [],
      show: false,
      qrcode_popup_show: false,
      search_result: false,
      search_result_list: [],
      isApp: !!window.plus,
      show_qrcode: false,
      show_search_popup: false,
      search_show: false,
      // 访问indexDB
      db: null,
      new_employee_num: 0,
      showHelp: false,
      getRole_noe: '',// 权限判断

      keyOword: '',//搜索
      deptId: 0,
    }
  },
  // 组件
  components: {
    share, qrcode, Echo, userImage
  },
  watch: {
    keyword (val) {
      let self = this
      if (val === '') {
        self.search_result_list = []
        self.search_show = false
      } else {
        let new_employee_list = []
        for (const i in this.employee_list) {
          if (self.employee_list[i].name.indexOf(val) != '-1') {
            new_employee_list.push(self.employee_list[i])
          }
        }
        if (new_employee_list.length > 0) {
          self.search_result_list = new_employee_list
        } else {
          self.search_result_list = []
          self.search_show = true
        }
      }
    }
  },
  methods: {
		//搜索
		searchUser: _throttle(function() {
      //keyOword
      console.log(this.keyOword)
      this.get_employee_list()
    }),
    // // 添加人员
    // goAddEmployee () {
    //   this.showHelp = false
    //   window.plus ? plus.storage.setItem('departmentHelp', '1') : localStorage.setItem('departmentHelp', '1')
    // },
    // 外层点击搜索
    parent_click () {
      this.show_search_popup = true
      document.querySelectorAll('.search_popup input').item(0).focus()
    },
    // 关闭搜索弹窗
    close_search_popup () {
      this.show_search_popup = false
      this.keyword = ''
      this.search_show = false
    },
    edit_site_info () {
      if (!this.getRole_noe) {
        return false
      }
      return this.$router.push({name: 'company_info'})
    },
    back_by_index (index, item) {
      if (index == 0) {
        this.pid = this.pid_list[index]
        this.pid_list.splice(index, 100)
        this.pid_list_arr.splice(index, 100)
        this.deptId = this.pid
        this.get_employee_list(this.pid)
        this.get_department_list()
        return
      }
      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.deptId = item.id
      this.get_employee_list(item.id)
      this.get_department_list(item.id)
      // this.get_dept_info(this.pid)
    },

    getContainer () {
      return document.body
    },
    // 加载
    showLoading () {
      this.$toast.loading({
        mask: true,
        type: 'spinner',
        message: '加载中...'
      })
    },
    // 下拉刷新
    refresh (done) {
      let self = this
      this.deptId = this.pid
      self.get_employee_list(this.pid)
      self.get_department_list()
      setTimeout(() => {
        done()
      }, 200)
    },
    back () {
      let array = this.pid_list_arr
      let newarray = array.slice(0, array.length - 1)
      this.pid_list_arr = newarray
      if (newarray.length == 0) {
        this.pid = 0
      } else {
        this.pid = newarray[newarray.length - 1].id
        // this.get_dept_info(this.pid)
      }
      this.deptId = this.pid
      this.get_employee_list(this.pid)
    },
    show_child (item) {
      this.pid = item.id
      this.pid_list_arr.push(item)
      this.pid_list.push(item.pid)
      // this.get_dept_info(item.id)
      this.deptId = item.id
      this.get_employee_list(item.id)
    },
    department_parse (dept_list, first) {
      let self = this
      let list = []
      if (first) {
        self.dept_list = []
      }
      for (let i in dept_list) {
        self.dept_list.push(dept_list[i], false)
        if (dept_list[i].children.length > 0) {
          self.department_parse(dept_list[i].children, false)
        }
      }
    },
    // 获取分享信息
    get_share_data () {
      let pictures = '_www/static/images/defalut_custmer_headicon.png'
      if (window.plus && window.plus.os.name == 'Android') {
        pictures = window.plus.io.convertLocalFileSystemURL(pictures)
      }
      this.share_data.type = 'web'
      this.share_data.title = this.user_info.name + '邀请你加入'
      this.share_data.content = '我们的同事都在用功道云，点击立即申请加入'
      this.share_data.thumbs = [pictures]
      this.share_data.href = process.env.WEB_LINK + '/#/invite_reg?site_id=' + this.user_info.site_id + '&employee_id=' + this.user_info.id + '&company_name=' + this.company_info.name + '&employee_name=' + this.user_info.name
    },
    // 获取部门树
    get_department_list (d) {
      let self = this
      this.$toast.loading({
        message: '加载中...',
        forbidClick: true
      })
      request('get', '/api/department/index').then((res) => {
        if (res.data.code == 1) {
          self.showDom = true
          self.dept_list = res.data.data.list
          self.company_info = res.data.data.company
          self.employee_count = res.data.data.count
          if (window.plus) {
            plus.share.getServices(function (s) {
              self.shares = s
              self.get_share_data()
            }, function (e) {
              alert('获取分享服务列表失败：' + e.message)
            })
          }
          self.$toast.clear()
        } else {
          self.$toast(res.data.msg)
        }
      }).finally(() => {
        this.show_qrcode = true
      })
    },

    plus_menu (val) {
      switch (val) {
        case 'add_dept_btn':
          let last = {}
          if (this.pid_list_arr.length > 0) {
            last = this.pid_list_arr.slice(-1)
            this.$router.push({name: 'dept', query: {type: 'add', parent_id: last[0].id}})
          } else {
            this.$router.push({name: 'dept', query: {type: 'add'}})
          }
          break
        case 'add_employee':
          this.$router.push({name: 'employee_add'})
          break
        case 'wechat':
          this.show_share()
          break
        default:
          this.qrcode_popup_show = true
      }
    },
    query_share (s) {
      if (s.id == 'weixin') {
        let pictures = '_www/static/images/logo.png'
        if (window.plus && plus.os.name == 'Android') {
          pictures = plus.io.convertLocalFileSystemURL(pictures)
        }
        s.send({
          extra: {scene: 'WXSceneSession'},
          type: 'web',
          title: this.user_info.name + '邀请你加入' + this.company_info.name,
          content: '我们的同事都在用功道云，点击立即申请加入',
          thumbs: [pictures],
          href: 'https://g107.com/#/site_id=' + this.user_info.site_id + '&employee_id=' + this.user_info.id + '&company_name=' + this.company_info.name
        }, function () {
          alert('分享成功！')
        }, function (e) {
          alert('分享失败：' + e.message)
        })
      }
    },
    // 编辑部门
    edit_dept (d) {
      if (!this.getRole_noe) {
        return false
      }
      this.$router.push({name: 'dept', query: {type: 'edit', id: d.id}})
    },
    // 查询部门信息
    get_dept_info (d) {
      let self = this
      self.showLoading()
      request('get', '/api/department/info', {id: d}).then((res) => {
        if (res.data.code == 1) {
          if (res.data.data.manager.length == 0) {
            self.showDepart = false
          } else {
            self.showDepart = true
          }
          self.dept_info = res.data.data
          self.$toast.clear()
        } else {
          self.$toast.clear()
        }
      }).catch((e) => {
        self.$toast(res.data.msg)
      })
    },
    // 查询员工列表
    get_employee_list (d) {
      this.showLoading()
      request('get', '/api/employee/list', {dept_id: this.deptId, page_size: 20000, keywords: this.keyOword}).then((res) => {
        if (res.data.code == 1) {
          this.showDom = true
          this.employee_list = res.data.data.list
          this.$nextTick(() => {
            this.$refs['scroller_com'].createPageIndex()
          })
        } else {
          this.$toast(res.data.msg)
        }
      }).finally(() => {
        this.$toast.clear()
      })
    },

    // 编辑人员
    edit_employee (d) {
      this.$router.push({name: 'employee_edit', query: {id: d.id}})
    },
    // 个人信息
    employee_info (d) {
      this.$router.push({name: 'employee_info', query: {id: d.id}})
    },
    // 邀请弹窗
    show_share () {
      this.show = true
    },
    // 判断是否是APP
    ifApp () {
      if (window.plus) {
        this.isApp = true
      }
    },
    // 获取新成员
    new_employee () {
      let self = this
      const data = {status: 0, page: 1}
      // request('get', '/api/join/index', data).then((res) => {
      //   if (res.data.code == 1) {
      //     if (res.data.data.total > 0) {
      //       self.new_employee_num = res.data.data.total
      //     }
      //   } else {
      //     self.$toast(res.data.msg)
      //   }
      // })
    }
  },
  keep_alive_update: {
    update_dept_list: function (vm, data) {
      if (data.type == 'edit') {
        vm.dept_list[data.id].name = data.name
        vm.dept_info.name = data.name
      } else {
        vm.refresh(function () {})
      }
    },
    company_info: function (vm, data) {
      vm.company_info.name = data.name
      vm.company_info.logo_url = data.logo_url
    },
    employee_list: function (vm, data) {
      for (let i in vm.employee_list) {
        if (vm.employee_list[i].id == data.id) {
          vm.employee_list[i].name = data.name
        }
      }
    },

    del_dept_info: function (vm, data) {
      vm.back()
      vm.refresh(function () {
        self.get_department_list()
        self.get_employee_list()
        self.ifApp()
      })
    },

    add_employee: function (vm, data) {
      vm.refresh(function () {

      })
    },
    del_employee: function (vm, data) {
      for (let i in vm.employee_list) {
        if (vm.employee_list[i].id == data.id) {
          vm.employee_list.splice(i, 1)
          vm.employee_count.all = vm.employee_count.all - 1
        }
      }
    },
    update_new_employee: function (vm, data) {
      vm.new_employee()
    }
  },
  created () {
    this.getRole_noe = getRole_noe()
    // this.get_employee_list()
    this.new_employee()
  },
  mounted () {
    let self = this

    if (window.plus) {
      self.bar_height = window.plus.navigator.getStatusbarHeight()
    }
    let options = []
    if (this.getRole_noe) {
      options.push({ text: '添加部门', value: 'add_dept_btn', icon: 'static/images/dept_add.png'})
    }
    if (this.getRole_noe) {
      options.push({ text: '添加人员', value: 'add_employee', icon: 'static/images/employee_add.png'})
    }
    if (window.plus) {
      if (this.getRole_noe) {
        options.push({ text: '微信邀请', value: 'wechat', icon: 'static/images/wechat_invite.png'})
        options.push({ text: '二维码邀请', value: 'qrcode', icon: 'static/images/qrcode_invite.png'})
      }
      self.options = options
    } else {
      self.options = options
    }
    // 引导页相关
    // this.$nextTick(() => {
    //   let employeeMap = window.plus ? JSON.parse(plus.storage.getItem('SET_EMPLOYEE_MAP')) : JSON.parse(localStorage.getItem('SET_EMPLOYEE_MAP'))
    //   if (employeeMap) {
    //     let arr = Object.keys(employeeMap)
    //     if (window.plus) {
    //       plus.storage.getItem('departmentHelp') || arr.length > 1 ? this.showHelp = false : this.showHelp = true
    //     } else {
    //       localStorage.getItem('departmentHelp') || arr.length > 1 ? this.showHelp = false : this.showHelp = true
    //     }
    //   }
    // })
  }
}
</script>

<style scoped>
  .pageIndexBtn{
    width:100%;
    text-align: left;
    padding: 0.1rem 0.4rem 0.05rem;
    color: #909399;
    background:rgb(245, 245, 245);
  }

  .cur_company_name {
    line-height: 0.8rem;
    text-indent: 0.5em;
    cursor: pointer;
  }

  .menu_title {
    text-indent: 0.5em;
    margin-bottom: 0.16rem;
  }

  .work_body_com {
    height: calc(100vh - 0.92rem);
    position: relative;
    z-index:0;
  }
  .work_body_com .search_list{
    /* background:#FFF;
    height: 100vh; */
  }

  .van-radio-group {
    padding: 0.24rem 0.32rem;
  }

  .van-radio {
    height: 0.8rem;
  }

  .employee_cell_head_img {
    width: 0.9rem;
    height: 0.9rem;
    -webkit-border-radius: 0.1rem;
    -moz-border-radius: 0.1rem;
    border-radius: 0.9rem;
    margin-right: 0.24rem;
  }
  .invite_employee_head_img{
    width: 0.8rem;
    height: 0.8rem;
    -webkit-border-radius: 0.1rem;
    -moz-border-radius: 0.1rem;
    border-radius: 0.1rem;
    margin-right: 0.24rem;
  }
  .employee_cell {
    z-index:0;
  }
  .employee_cell .message_department{
    width:0.9rem;
    height:0.9rem;
    margin-right: 0.24rem;
    color:#238dfa;
  }
  .employee_cell .message_newinvit{
    width:0.9rem;
    height:0.9rem;
    margin-right: 0.24rem;
    color:#FFCC00;
  }
  .employee_cell .message_newmember{
    width:0.9rem;
    height:0.9rem;
    margin-right: 0.24rem;
    color:#FF9600;
  }
  .employee_cell .van-cell__title{
    line-height: 0.9rem;
    color: #323233;
  }
  .employee_cell .van-cell__title span{
    font-size: 0.34rem;
  }
  .employee_cell .van-cell__right-icon{
    line-height: 0.9rem;
    color: #E4E7ED;
  }
  .company_image{
    background: #fff;
    padding-bottom: 0.1rem ;
    margin-bottom: 0.1rem
  }
  .company_info{
    padding: 0.32rem;
    margin-top:-0.2rem;
  }
  .company_info .van-cell__right-icon{
    line-height: 0.8rem;
  }
  .company_info .van-cell__title{
    padding: 0.05rem 0;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .company_info .van-cell__title span{
    font-family: mirsoft Yahei;
    font-size: 0.38rem;
    font-weight: 600;
    letter-spacing: 0.003rem;
    border-radius: 0.08rem;
  }

  .company_info .van-cell__title .van-cell__label span{
    font-size: x-small;
    color: #fff;
    margin-right: 0.1rem;
  }
  .company_info i.van-icon{
    line-height: 1.28rem
  }
  .van-hairline--top-bottom:after, .van-hairline-unset--top-bottom:after{
    border:none;
  }
  .company_dept_img{
    width: 1.08rem;
    height: 1.08rem;
    -webkit-border-radius: 0.1rem;
    -moz-border-radius: 0.1rem;
    border-radius: 0.125rem;
    margin-right: 0.26rem;
  }
  .qrcode_popup{
    width: 80vw
  }
  .employee_item{
    position: relative;
    z-index: 0;
  }

  .employee_item:before{
    position: absolute;
    left: 0rem;
    right: 0rem;
    top:0rem;
    box-sizing: border-box;
    content: ' ';
    pointer-events: none;
    border-bottom: 0.02rem solid #ebedf0;
    -webkit-transform: scaleY(.5);
    transform: scaleY(.5);
    z-index: 1;
  }
  .letter-first:before{
    border:none !important;
  }
  .department_box /deep/ .van-cell__left-icon{
    color:#323233 !important;
  }
  .pageIndexBtnText{font-size:0.24rem;}
.dept_path a {
  color: #238dfa;
  font-size: 0.28rem;
}
.dept_path a:nth-last-child(1) {
  color: #999;
}
.dept_path::after {
  /* content: '';
  color: #fff!important; */
}
.dept_path a * {
  vertical-align: middle;
}
.dept_path {
  position: relative;
  font-size: 0.32rem;
  line-height: 0.4rem;
  padding: 0.2rem 0.32rem 0.1rem 0.32rem;
}
.dept_path:after {
  /* content: ' ';
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #efefef; */
  /* height: 1px; */
  /* position: absolute;
  transform: scaleY(0.5); */
}
.text_center {
  font-size: 14px;
  margin:0;
  color: #969799;
}
.employee_count{
  font-size: 0.26rem;
}
.tag.num9 {
  padding: 0;
  width: 0.4rem;
  height: 0.4rem;
  border-radius: 50%;
  display: inline-block;
  text-align: center;
}
.tag.num10 {
  width: auto;
  line-height: 1;
}
.employee_cell .van-tag{
  display: inline-table;
  margin-top: 0.26rem;
}
.employee_cell .van-tag+.van-tag{
  margin-left: 0.2rem;
}
 .guild_notice{
  top:1.6rem;
  left: 4.3rem;
  width: 6rem;
  background: transparent;
  border-radius: 0.12rem;
  overflow-y: inherit;
}
.guild_notice .list{
  position: relative;
  padding: 0.2rem;
  background: #238dfa;
  border-radius: 0.12rem;
}
.title{
  font-size:0.32rem;
  line-height: 0.48rem;
  color:#ffffff;
}
.title:after{
  position: absolute;
  top: 0.825rem;
  content: ' ';
  width: 90%;
  border-bottom: 0.02rem #3798fb solid;
}
.num{
  display: block;
  font-size:0.32rem;
  line-height: 0.48rem;
  color:#ffffff;
}
.list .des{
  display:block;
  margin-top:0.4rem;
  font-size:0.36rem;
  font-weight:bold;
  color:#fff;
}
.list .next{
  margin-top: 0.3rem;
  color:#238dfa;
  background:#fff;
  border-radius:0.12rem;
}
.guild_notice .list:after{
  border:none;
}
.guild_down_icon{
  position: relative;
  top: 0.1vh;
  left: 72vw;
  content: ' ';
  width: 0;
  height: 0;
  border-left: 0.2rem solid transparent;
  border-right: 0.2rem solid transparent;
  border-top: 0.2rem solid #238dfa;
  transform: rotate(180deg);
}
.guild_dept_border{
  position: relative;
  text-align: center;
  top: 0vh;
  left: 69vw;
  width: 0.7rem;
  height: 0.7rem;
  margin-bottom: 2vh;
  font-size: 0.4rem;
  font-weight: bold;
  line-height: 0.7rem;
  color: #fff;
  border: 0.04rem #fff dashed;
  border-radius: 0.12rem;
}
</style>
