<template>
  <!-- 团队管理 -->
  <main-page
    left-arrow
    :loading="loading"
    @click-left="goBack"
  >
    <!-- 右侧二维码图标 -->
    <template slot="right">
      <div
        class="h-6.5 w-6.5 flex items-center justify-end mr-2"
        @click="editTeamName"
      >
        <app-icon
          icon-name="edit-black"
          class-name="h-4 w-4 inline-block ml-1"
        />
      </div>
      <div class="h-6.5 w-6.5 flex items-center justify-end" @click="showCode">
        <app-icon
          icon-name="code"
          class-name="w-4 h-4"
        />
      </div>
    </template>
    <van-overlay :show="showQrcode" :z-index="2000" @click="showQrcode = false">
      <div class="bg-white w-full h-full relative">
        <div class="absolute left-0 top-0 w-full h-12 px-4 flex items-center">
          <app-icon
            icon-name="left-arrow"
            class-name="w-6.5 h-6.5"
            @click="showQrcode = false"
          />
        </div>
        <qrcode
          :ent-info="enterpriseInfo"
          :text="qrCodeText"
        ></qrcode>
      </div>
    </van-overlay>
    <member-selector
      :show.sync="showMemberSelector"
      :show-team="true"
      :multiple="multiple"
      :title="selectorTitle"
      :checked-member-id.sync="selectedLeaderId"
      @confirm="confirm"
    />
    <div class="px-4 pt-14">
      <!-- 头部 -->
      <div class="flex items-start pt-1 pb-5">
        <div class="h-13 w-13 rounded overflow-hidden flex-shrink-0">
          <div v-if="enterpriseInfo.avatar">
            <img :src="enterpriseInfo.avatar" alt="">
          </div>
          <div v-else class="">
            <app-icon
              type="png"
              :path="require('@/assets/icons/team-icon.png')"
              class-name="h-13 w-13"
            />
          </div>
        </div>
        
        <!-- 名称 -->
        <div class="ml-4 flex-1 text-text-primary overflow-hidden">
          <span class="break-all">
            {{ enterpriseInfo.name }}
          </span>
          <!-- 团队号 -->
          <div class="text-text-secondary text-sm">
            <div class="mt-1 truncate">团队号 {{enterpriseInfo.id}}</div>
            <div class=""></div>
            <div class="truncate">服务器 {{enterpriseInfo.oaServer}}</div>
            <div class=""></div>
          </div>
        </div>
      </div>
      <c-cell dot title="组织架构" @click="$router.push('/team/team-frame')" />
      <c-cell dot title="添加成员" @click="$router.push('/team/add-member')" />
      <c-cell dot title="添加部门" @click="$router.push('/team/add-department')" />
      <div class="mt-4">
        <template v-if="isLeader">
          <c-cell dot title="团队管理权限" :content="`共${managerNum}人`" @click="$router.push('/team/auth-management')" />
          <c-cell dot title="转让负责人" @click="transferManagement" />
          <c-cell dot title="申请管理" @click="$router.push('/team/apply-list')" />
        </template>
      </div>
      <c-button v-if="isLeader" round type="secondary" class="mt-16" @click="deleteTeam">
        解散团队
      </c-button>
    </div>
  </main-page>
</template>

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

Vue.use(Overlay)

export default Vue.extend({
  name: 'TeamManagement',
  components: {
    'app-icon': () => import('@/components/common/Icon.vue'),
    'main-page': () => import('@/layout/main-page.vue'),
    'c-cell': () => import('@/components/common/c-cell.vue'),
    'c-button': () => import('@/components/common/c-button.vue'),
    'member-selector': () => import('@/views/team/components/member-selector.vue'),
    qrcode: () => import('@/views/team/components/qrcode.vue')
  },
  beforeRouteEnter(to, from, next) {
    const path = from.path
    next((vm: any) => {
      vm.fromFrame = path === '/team/team-frame'
    })
  },
  data() {
    return {
      enterpriseInfo: {} as LocalStoreEnt,
      loading: false,
      managerNum: 0,
      showMemberSelector: false,
      selectorTitle: '',
      multiple: false,
      selectedLeaderId: [] as string[],
      fromFrame: true,
      role: 0,
      // 企业id，跟部门id
      entId: '',
      showQrcode: false,
      qrCodeText: ''
    }
  },
  async created() {
    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)
      }
      localStorage.setItem('USR_INFO', JSON.stringify(usrData))
      usrId = usrData.id
      this.entId = usrData.entId
    } else {
      usrId = userInfoDev.id
      this.entId = userInfoDev.entId
    }
    let url = window.location.origin + '/oa/team/join-team'
    this.qrCodeText = `${url}?entId=${encodeURIComponent(this.entId)}`
    this.getEntInfo()
    await this.getStaff(usrId)
  },
  computed: {
    isLeader(): boolean {
      return this.role === Role.LEADER
    }
  },
  methods: {
    showCode() {
      this.showQrcode = true
    },
    getStaff(id: string) {
      this.loading = true
      return this.$service.staff.getInfo({
        id
      }).then((res: any) => {
        const {data} = res
        this.loading = false
        if (data.code === this.$global.success) {
          localStorage.setItem('USR_INFO', JSON.stringify(data.data))
          this.role = data.data.role
          this.entId = data.data.entId
          if (this.role === Role.COMMON_MEMBER) {
            this.$router.replace('/team/team-frame')
          }
        } else {
          this.$toast(data.msg)
        }
      }).catch(() => this.loading = false)
    },
    goBack() {
      if (this.fromFrame) {
        this.$router.push('/team/team-frame')
      } else {
        close()
      }
    },
    getSub() {
      const {id, rootDepId} = this.enterpriseInfo
      this.loading=true
      this.$service.department.getSub({
        entId: id,
        parentId: rootDepId,
        hasStaff: true,
        isDirect: false
      }).then((res: any) => {
        this.loading = false
        const {data} = res
        if (data.code === this.$global.success) {
          const arr = data.data.staffList?.filter((s: Staff) => [Role.LEADER, Role.SUPER_ADMIN].indexOf(s.role) > -1)
          this.managerNum = arr.length
        } else {
          this.$toast(data.msg)
        }
      }).catch(() => this.loading=false)
    },
    getEntInfo() {
      this.loading = true
      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.enterpriseInfo = data.data
          this.getSub()
        } else {
          this.$toast(data.msg)
        }
      })
    },
    editTeamName() {
      console.log('edit')
      this.$router.push('/team/team-info')
    },
    confirm(arr: string[]) {
      if (arr.length === 0) return
      this.loading = true
      const newLeaderId = arr[0]
      const id = JSON.parse(localStorage.getItem('ENT_INFO') as string).id
      this.$service.enterprise.updateLeader({
        id,
        newLeaderId
      }).then((res: any) => {
        this.loading = false
        const {data} = res
        if (data.code === this.$global.success) {
          this.$router.replace('/team/team-frame')
        } else {
          this.$toast(data.msg)
        }
      }).catch(() => this.loading=false)
    },
    transferManagement() {
      this.showMemberSelector = true
      this.selectorTitle = '转让负责人'
      // this.selectorTitle = [this.leaderL]
    },
    deleteTeam() {
      this.$dialog.confirm({
        title: '提示',
        message: '解散团队将同时解散团队所有相关的群和员工信息，确定删除吗？',
        confirmButtonText: '解散'
      }).then(() => {
        this.loading = true
        this.$service.enterprise.deleteEnterprise({
          id: this.enterpriseInfo.id
        }).then(async (res: any) => {
          this.loading = false
          const {data} = res
          if (data.code === this.$global.success) {
            this.$toast('解散成功')
            localStorage.removeItem('ENT_INFO')
            if (!isAppEnv()) {
              postMessage(PostMsg.RELOAD)
              return
            }
            await refreshCompanyState({goHome: true})
            close()
          } else {
            this.$toast(data.msg)
          }
        })
      }).catch(() => {
        this.loading = false
        console.log('取消解散')
      })
    }
  }
})
</script>

<style lang="less">

</style>
