<template>
  <!-- 选择成员 -->
  <van-overlay :show="show" z-index="2000" :lock-scroll="false">
    <div class="select-team w-screen h-screen overflow-auto" id="member-selector">
      <main-page
        main-bg="bg-white"
        header-bg="bg-white"
        :title="title"
        :loading="loading"
        left-arrow
        @click-left="goBack"
      >
        <!-- <template slot="right">
          <app-icon
            type="png"
            class-name="w-6.5 h-6.5"
            :path="require('@/assets/icons/search.png')"
          />
        </template> -->
        <div class="px-4 pt-14">
          <!-- 团队架构详情 -->
          <team-tree
            v-if="showTeam"
            :tree-data="tree"
            :teams="teamArr"
            @click-child="clickItem"
            @click-bread="goPre"
          />
          <!-- 显示成员是否包含子部门成员 -->
          <switch-cell
            title="部门包含子部门成员"
            :checked.sync="ifContainChildDep"
            @change="handleSwitchChange"
          />
          <!-- <div class="py-2">{{currentDep.name}}</div> -->
          <!-- 通讯录 -->
          <div class="pb-16">
            <!-- <div class="text-text-secondary py-1">成员</div> -->
            <team-contacts
              container-id="member-selector"
              :leader="leaders"
              :radio="true"
              :multiple="multiple"
              :checked.sync="checkedMember"
              :contact-list="contacts"
            />
          </div>
          <!-- 底部操作 -->
          <div class="py-2 px-4 bg-white w-screen fixed bottom-0 left-0 z-30">
            <c-button round @click="confirmSelect">确定</c-button>
          </div>
        </div>
      </main-page>
    </div>
  </van-overlay>
</template>

<script lang="ts">
import Vue, {PropType} from 'vue'
import { Department, Staff } from '@/Interface'
import { Role } from '@/service/moudles/service.dto'
// import {openCompanyUserInfo} from '@/util/Bridge'

export default Vue.extend({
  name: 'MemberSelector',
  components: {
    'main-page': () => import('@/layout/main-page.vue'),
    'app-icon': () => import('@/components/common/Icon.vue'),
    'team-tree': () => import('@/views/team/components/team-tree.vue'),
    'team-contacts': () => import('@/views/team/components/team-contacts.vue'),
    'c-button': () => import('@/components/common/c-button.vue'),
    'switch-cell': () => import('@/components/common/switch-cell.vue')
  },
  props: {
    show: Boolean,
    showTeam: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    checkedMemberId: {
      type: Array as PropType<Array<String>>
    },
    title: {
      type: String,
      default: '选择主管'
    },
    action: {
      type: String,
      default: 'select'
    },
    depId: String
  },
  data() {
    const tree: Array<Department> = []
    return {
      tree,
      teamArr: [] as Department[],
      loading: false,
      contacts: [] as Array<Staff>,
      parentId: '',
      entId: '',
      ifContainChildDep: true,
      currentDep: {} as Department,

      checkedMember: [] as string[],
      showRadio: true,
      leaders: {} as{list: Staff[], title?: string}
    }
  },
  mounted() {
    this.entId = JSON.parse(localStorage.getItem('USR_INFO') || '{}').entId
    this.getEntInfo()
  },
  computed: {
    isNotDepRoot():boolean {
      return this.currentDep.parentId !== '-1'
    },
  },
  methods: {
    goPre(dep: Department) {
      this.parentId = dep.id
      this.getStaff()
    },
    // 确认选择
    confirmSelect() {
      this.$emit('confirm', this.checkedMember)
      if (this.action === 'select') {
        this.$emit('update:show', false)
        this.$emit('update:checkedMemberId', this.checkedMember)
        return
      }
      if (this.action === 'add') {
        this.$dialog.confirm({
          title: '提示',
          message: `确定要添加选中的成员吗？`
          // confirmButtonText: '解散'
        }).then(() => {
          this.loading=true
          const params = {
            entId: this.entId,
            depId: this.depId,
            ids: this.checkedMember as Array<string>
          }
          this.$service.staff.changeDep(params).then((res:any) => {
            this.loading=false
            const {data} = res
            if (data.code===this.$global.success) {
              this.$toast('添加成功')
              const usrId = JSON.parse(localStorage.getItem('USR_INFO') as string).id
              if(params.ids.indexOf(usrId) > -1) {
                this.getStaffInfo(usrId)
              }
              this.$emit('update:show', false)
            } else {
              this.$toast(data.msg)
            }
          }).catch(err=> this.loading = false)
        }).catch(()=>{})
      }
    },
    getStaffInfo(id: string) {
      this.$service.staff.getInfo({
        id,
      }).then((res: any) => {
        const {data} = res
        if (data.code === this.$global.success) {
          localStorage.setItem('USR_INFO', JSON.stringify(res.data.data))
        }
      })
    },
    goBack(){
      this.$emit('update:show', false)
    },
    getEntInfo() {
      this.loading = true
      return this.$service.enterprise.getEnterpriseInfo({
        id: this.entId
      }).then((res: any) => {
        const { data } = res
        this.loading = false
        if (data.code === this.$global.success) {
          this.parentId = data.data.rootDepId
          this.getStaff()
        } else {
          this.$toast(data.msg)
        }
      })
    },
    // 获取成员
    getStaff() {
      this.loading = true
      this.$service.department.getSub({
        parentId: this.parentId,
        entId: this.entId,
        hasStaff: true,
        isDirect: !this.ifContainChildDep
      }).then((res: any) => {
        const { data } = res
        this.loading = false
        if (data.code === this.$global.success) {
          this.currentDep = data.data.dep
          // 负责人/管理员
          if (this.isNotDepRoot) {
            // 不在架构根目录
            const leader = data.data.leader
            if (typeof leader !== 'undefined' && leader.id !== '') {
              const staff = {...data.data.leader, isDepAdmin: true}
              this.leaders.list = [staff]
            } else {
              this.leaders.list = []
            }
          } else {
            this.leaders.list = data.data.staffList?.filter((i: Staff) => i.role !== Role.COMMON_MEMBER).sort((a: Staff, b: Staff) => a.role - b.role)
          }
          // 普通成员
          this.contacts = data.data.staffList || []
          // 部门树
          const depTree = data.data.dep
          const index = this.teamArr.findIndex(d => d.id === this.parentId)
          if (index < 0) {
            this.teamArr.push(depTree)
          } else {
            this.teamArr = this.teamArr.slice(0, index + 1)
          }
          this.tree = data.data.subDepList || []
        } else {
          this.$toast(data.msg)
        }
      })
    },
    clickItem(val: Department) {
      this.parentId = val.id
      this.getStaff()
      // this.$router.push(`/team/team-frame/${val.id}`)
    },
    // 切换成员显示
    handleSwitchChange(val: boolean) {
      this.getStaff()
    }
  },
  watch: {
    checkedMemberId(val: string[]) {
      this.checkedMember = val
    }
  },
})
</script>

<style lang="less">

</style>