<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"
            :checkable="{isActivated: true, checkable: true}"
            @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, getGroupMembers } 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)

enum Action {
  CREATE='createGroup',
  INVITE='inviteGroup'
}

interface RouteQuery {
  type: string,
  excludeSelf: string,
  action: Action,
  gid?: string
}

interface Member extends Staff {
  checkable: boolean
}

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,
      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,
      groupUsers: ['1Gwr2QzfHF3CYCYdPKJoEAxfCUimg1cPup'] as string[],
      userId: '',
      excludeSelf: 'true',
      action: 'inviteGroup'
    }
  },
  async created() {
    const query = this.$route.query as unknown as RouteQuery
    const {type, excludeSelf, action, gid} = query
    this.multiple = type === 'multiple'
    this.excludeSelf = excludeSelf
    this.action = action
    const userInfoDev = {
      depId: '174172709863821313',
      entId: '174172709863821312',
      id: '1Gwr2QzfHF3CYCYdPKJoEAxfCUimg1cPup',
      joinTime: 1631090065,
      name: '徐丹',
      role: 0
    }
    if (process.env.NODE_ENV === 'development') {
       this.userId = userInfoDev.id
    } else {
      let usrData = {} as Staff
      if (!isAppEnv()) {
        const result = await postMessage(PostMsg.GET_USER_INFO)
        usrData = result.data
      } else {
        usrData = JSON.parse(getUserInfo() as string)
        console.log(type, excludeSelf, action, gid, 'query')
        if (action === Action.INVITE) {
          const groupUsers = getGroupMembers({gid}) || '[]'
          console.log(groupUsers, 'groupUsers')
          this.groupUsers = JSON.parse(groupUsers as string)
        }
      }
      this.userId = usrData.id
    }
    this.getStaffInfo(this.userId)
  },
  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
          // app 过滤成员数据
          data.data.staffList = data.data.staffList?.map((s: Member) => {
            s.checkable=true
            if (this.excludeSelf === 'true' && s.id === this.userId) {
              s.checkable = false
            }
            if (this.action === Action.INVITE && this.groupUsers.length > 0 && this.groupUsers.indexOf(s.id) > -1) {
              s.checkable = false
            }
            return s
          })
          // 负责人/管理员
          if (this.isNotDepRoot) {
            // 不在架构根目录
            const leader = data.data.leader
            if (typeof leader !== 'undefined' && leader.id !== '') {
              const staff = {...data.data.leader, isDepAdmin: true, checkable: this.excludeSelf === 'true' && this.userId === leader.id}
              this.leaders.list = [staff]
            } else {
              this.leaders.list = []
            }
          } else {
            this.leaders.list = data.data.staffList?.filter((i: Member) => i.role !== Role.COMMON_MEMBER).sort((a: Member, b: Member) => 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>
