<template>
  <!-- 团队架构 -->
  <div class="team-frame">
    <main-page
      main-bg="bg-white"
      header-bg="bg-white"
      :title="pageTitle"
      :loading="loading"
    >
      <div slot="left">
        <app-icon
          class-name="w-6.5 h-6.5"
          icon-name="home"
          @click="handleBack"
        />
      </div>
      <div class="px-4 pt-14">
        <!-- 团队架构详情 -->
        <team-tree
          :tree-data="tree"
          :teams="teamArr"
          @click-child="clickItem"
          @click-bread="goPre"
        />
        <!-- 显示成员是否包含子部门成员 -->
        <switch-cell
          title="部门包含子部门成员"
          :checked.sync="ifContainChildDep"
          @change="handleSwitchChange"
        />
        <!-- 通讯录 -->
        <div class="pb-16">
          <!-- <div class="text-text-secondary py-1">成员</div> -->
          <team-contacts
            :radio="true"
            :multiple="multiple"
            :leader="leaders"
            :checked.sync="checkedMemberId"
            :contact-list="commonMember"
            @click-member="clickMember"
          />
        </div>
        <!-- 底部操作 -->
        <div class="py-2 px-4 bg-white w-screen fixed bottom-0 left-0 z-30">
          <c-button @click="confirmEdit">确定</c-button>
        </div>
      </div>
    </main-page>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getUserInfo, close, openCompanyUserInfo, isAppEnv, selectGroupMembers } from '@/util/Bridge'
import {postMessage} from '@/util/PostMessage'
import { Department, PostMsg, Staff } from '@/Interface'
import { ActionSheet } from 'vant'
import { Role } from '@/service/moudles/service.dto'
// import {openCompanyUserInfo} from '@/util/Bridge'

Vue.use(ActionSheet)

export default Vue.extend({
  name: 'Selector',
  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')
  },
  data() {
    const tree: Department[]= []
    return {
      tree,
      loading: false,
      contacts: [] as Staff[],
      parentId: '-1',
      entId: '',
      ifContainChildDep: true,
      currentDep: {} as Department,
      // 是否显示check
      checkedMemberId: [],
      leaders: {} as { list: Staff[], title?: string },
      commonMember: [] as Staff[],
      teamArr: [] as Department[],
      pageTitle: '选择成员',
      multiple: false
    }
  },
  async created() {
    this.multiple = this.$route.query.type === 'multiple'
    const userInfoDev = {
      depId: '168398222891421697',
      entId: '168398222891421696',
      id: '1K7cApKbEU9h5WySPVLNgdSd67i2XkSuoS',
      joinTime: 1631090065,
      name: '徐丹',
      role: 0
    }
    let usrId = ''
    if (process.env.NODE_ENV === 'production') {
      let usrData = {} as Staff
      if (!isAppEnv()) {
        const result = await postMessage(PostMsg.GET_USER_INFO)
        usrData = result.data
      } else {
        usrData = JSON.parse(getUserInfo() as string)
      }
      usrId = usrData.id
    } else {
      usrId = userInfoDev.id
    }
    this.getStaffInfo(usrId)
  },
  computed: {
    isNotDepRoot():boolean {
      return this.currentDep.parentId !== '-1'
    }
  },
  methods: {
    getStaffInfo(id: string) {
      this.loading = true
      this.$service.staff.getInfo({id})
        .then((res: any) => {
          this.loading=false
          const {data} = res
          if (data.code === this.$global.success) {
            this.entId = data.data.entId
            this.getEntInfo()
          }
        }).catch(() => this.loading=false)
    },
    handleBack() {
      this.close()
    },
    confirmEdit() {
      if (this.checkedMemberId.length === 0) {
        this.$toast('请选择成员')
        return
      }
      selectGroupMembers(this.checkedMemberId)
    },
    // 点击面包屑上一级部门
    goPre(dep: Department) {
      this.parentId = dep.id
      this.getStaff()
    },
    // 返回原生页面
    close,
    // 获取企业信息
    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
          // 通讯录
          this.contacts = data.data.staffList || []
          // 负责人/管理员
          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.commonMember = 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)
        }
      })
    },
    // 点击成员，原生操作
    clickMember(member: Staff) {
      if (!isAppEnv()) {
        postMessage(PostMsg.FOCUS_USER, {
          id: member.id,
          name: member.name
        })
      } else {
        openCompanyUserInfo(String(member.id))  
      }
    },
    // 点击部门
    clickItem(val: Department) {
      this.parentId = val.id
      this.getStaff()
    },
    // 切换成员显示
    handleSwitchChange(val: boolean) {
      this.getStaff()
    }
  }
})
</script>

<style lang="less">

</style>
