<template>
  <!-- 团队架构 -->
  <div class="team-frame">
    <van-action-sheet
      v-model="showActionSheet"
      cancel-text="取消"
      close-on-click-action
      :actions="actions"
      @select="handleAction"
    />
    <main-page
      main-bg="bg-white"
      header-bg="bg-white"
      :title="pageTitle"
      :loading="loading"
    >
      <div v-if="showHomeIcon" slot="left">
        <app-icon
          class-name="w-6.5 h-6.5"
          icon-name="home"
          @click="handleBack"
        />
      </div>
      <template slot="right">
        <div v-if="!isEdit">
          <div class="w-8 h-8 flex items-center justify-center" @click="showActionSheet=true">
            <app-icon
              class-name="w-5 h-1"
              icon-name="dot-h-black"
            />
          </div>
        </div>
        <div
          v-else
          class="text-color-primary"
          @click="handleCancel"
        >取消</div>
      </template>
      <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="isEdit"
            :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" v-if="showBottomBtn">
          <div v-if="isEdit">
            <c-button @click="confirmEdit">确定</c-button>
          </div>
          <div v-else class="grid gap-2.5" :class="isNotDepRoot ? 'grid-cols-3' : 'grid-cols-2'">
            <c-button round @click="addMember">添加成员</c-button>
            <c-button round @click="addDep">添加部门</c-button>
            <c-button round @click="setDepartment" v-if="isNotDepRoot">部门设置</c-button>
          </div>
        </div>
      </div>
    </main-page>
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
import { getUserInfo, close, goBack, openCompanyUserInfo, isAppEnv, refreshCompanyState } 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: 'TeamFrame',
  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 {
      title: '导航',
      tree,
      loading: false,
      contacts: [] as Staff[],
      parentId: '-1',
      entId: '',
      ifContainChildDep: true,
      currentDep: {} as Department,
      // 是否显示check
      checkedMemberId: [],
      role:3,
      leaders: {} as { list: Staff[], title?: string },
      commonMember: [] as Staff[],
      teamArr: [] as Department[],
      showActionSheet: false,
      isEdit: false,
      multiple: false,
      pageTitle: '组织架构'
    }
  },
  async created() {
    const userInfoDev = {
      depId: '168398222891421697',
      entId: '168398222891421696',
      // id: '1K7cApKbEU9h5WySPVLNgdSd67i2XkSuoS',
      id: '1Gwr2QzfHF3CYCYdPKJoEAxfCUimg1cPup',
      joinTime: 1631090065,
      name: '徐丹',
      role: 0
    }
    let usrId = ''
    if (process.env.NODE_ENV === 'development') {
      usrId = 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)
      }
      localStorage.setItem('USR_INFO', JSON.stringify(usrData))
      usrId = usrData.id
    }
    this.getStaffInfo(usrId)
  },
  computed: {
    isNotDepRoot():boolean {
      return this.currentDep.parentId !== '-1'
    },
    showBottomBtn(): boolean {
      if (process.env.NODE_ENV === 'development') return true
      return this.role === Role.SUPER_ADMIN || this.role === Role.LEADER
    },
    actions() {
      if ([Role.LEADER, Role.SUPER_ADMIN].indexOf(this.role) > -1) {
        return [
          {name: '编辑成员', action: 'edit'},
          {name: '管理团队', action: 'manage'}
        ]
      }
      return [{name: '退出团队', action: 'quit'}]
    },
    showHomeIcon(): boolean {
      return !this.isEdit
    }
  },
  methods: {
    handleCancel() {
      this.isEdit = false
      this.pageTitle = '组织架构'
    },
    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) {
            localStorage.setItem('USR_INFO', JSON.stringify(data.data))
            this.role=data.data.role
            this.entId = data.data.entId
            this.getEntInfo()
          }
        }).catch(() => this.loading=false)
    },
    handleBack() {
      if (isAppEnv()) {
        this.close()
      } else {
        postMessage(PostMsg.RELOAD)
      }
    },
    handleAction(item: {name: string, action: string}) {
      if (item.action === 'manage') {
        this.$router.push('/team/team-management')
        return
      }
      if (item.action === 'edit') {
        this.isEdit = true
        this.pageTitle = '选择成员'
        return
      }
      if (item.action === 'quit') {
        this.$dialog.confirm({
        title: '提示',
        message: '确定要退出当前团队吗？'
        // confirmButtonText: '解散'
        }).then(() => {
          const entId = JSON.parse(localStorage.getItem('ENT_INFO') as string).id
          const id = JSON.parse(localStorage.getItem('USR_INFO') as string).id
          this.loading=true
          this.$service.staff.resign({
            entId,
            id
          }).then((res: any) => {
            this.loading=false
            const {data} = res
            if (data.code === this.$global.success) {
              if (isAppEnv()) {
                refreshCompanyState({goHome: true})
                // this.close()
              } else {
                postMessage(PostMsg.RELOAD)
              }
            } else {
              this.$toast(data.msg)
            }
          })
        }).catch(() => {
          console.log('取消解散')
        })
      }
    },
    confirmEdit() {
      if (this.checkedMemberId.length === 0) return
      const id = this.checkedMemberId[0]
      this.$router.push({
        path: '/team/add-member',
        query: {
          usrId: id,
          edit: '1'
        }
      })
    },
    // 点击面包屑上一级部门
    goPre(dep: Department) {
      this.parentId = dep.id
      this.getStaff()
    },
    // 返回原生页面
    close,
    goBack,
    // 获取企业信息
    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) {
          localStorage.setItem('ENT_INFO', JSON.stringify(data.data))
          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()
    },

    // 部门设置
    setDepartment() {
      const id = this.currentDep.id
      this.$router.push(`/team/department-management/${id}`)
    },
    // 添加成员
    addMember() {
      this.$router.push({
        path: '/team/add-member',
        query: {
          id: this.currentDep.id
        }
      })
    },
    // 添加部门
    addDep() {
      this.$router.push({
        path: '/team/add-department',
        query: {
          id: this.currentDep.id
        }
      })
    }
  }
})
</script>

<style lang="less">

</style>
