<template>
  <!-- 部门管理 -->
  <main-page
    left-arrow
    :loading="loading"
    @click-left="$router.go(-1)"
  >
    <member-selector
      :show-team="true"
      :dep-id="depId"
      :title="memberSelectorTitle"
      :show.sync="showMemberSelector"
      :multiple="multiple"
      :checked-member-id.sync="selectedMemberId"
      :action="actionType"
    ></member-selector>
    <contact-selector
      :contact-title="contactTitle"
      :ent-id="entId"
      :dep="currentDep"
      :title="contactSelectorTitle"
      :show.sync="showContactSelector"
      :multiple="multiple"
      :action="actionType"
      :contacts="contacts"
      :leader="leader"
    ></contact-selector>
    <dep-selector
      :ent-id="entId"
      :show.sync="showDepSelector"
      :selected.sync="selectedDepId"
      :cur-dep-id="currentDep.id"
    ></dep-selector>
    <div class="pt-14 px-4">
      <input-cell
        v-model="depName"
        required
        :limit="20"
        label="部门名称"
        placeholder="请输入部门名称"
        error-msg="名称不能为空"
      ></input-cell>
      <c-cell
        dot
        title="部门主管"
        :content="leaderInfo.leaderName"
        class="mt-4"
        @click="selectLeader"
      ></c-cell>
      <c-cell
        dot
        title="上级部门"
        :content="depInfo.name"
        @click="selectParentDep"
      ></c-cell>
      <!-- <switch-cell title="该部门包含子部门成员" :checked.sync="check" /> -->
      <c-cell
        dot
        title="添加成员"
        class="mt-4"
        @click="addMember"
      ></c-cell>
      <c-cell
        dot
        title="移除成员"
        @click="removeMember"
      ></c-cell>
      <switch-cell class="mt-4" title="创建部门群" :checked.sync="hasGroup"></switch-cell>
      <c-button
        round
        class="mt-10"
        @click="save"
      >
        保存
      </c-button>
      <c-button
        round
        type="secondary"
        class="mt-2.5"
        @click="deleteDep"
      >
        删除部门
      </c-button>
    </div>
  </main-page>
</template>

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

export default Vue.extend({
  name: 'DepartmentManagement',
  components: {
    // 'app-icon':()=>import('./components/common/Icon.vue'),
    'main-page': () => import('@/layout/main-page.vue'),
    'input-cell': () => import('@/components/common/input-cell.vue'),
    'c-cell': () => import('@/components/common/c-cell.vue'),
    'c-button': () => import('@/components/common/c-button.vue'),
    'switch-cell': () => import('@/components/common/switch-cell.vue'),
    'member-selector': () => import('@/views/team/components/member-selector.vue'),
    'contact-selector': () => import('@/views/team/components/contact-selector.vue'),
    'dep-selector': () => import('@/views/team/components/dep-selector.vue')
  },
  data() {
    const selectedMemberId: Array<string> = []
    return {
      name: '产品部',
      loading: false,
      depId: '',
      depName: '',
      entId: '',
      hasGroup: false,
      depInfo: {} as Department, // 上级部门
      leaderInfo: {
        leaderName: '',
        leaderId: ''
      }, // 领导信息

      showMemberSelector: false,
      containChild: true,
      selectedMemberId,
      memberSelectorTitle: '',
      multiple: false,

      contacts: [] as Array<Staff>,
      leader: {} as {list: Staff[]},
      showContactSelector: false,
      contactSelectorTitle: '',
      actionType: 'add',
      contactTitle: '',

      showDepSelector: false,
      selectedDepId: '',
      // currentDepId: '', // 当前部门id
      currentDep: {} as Department
    }
  },
  async created() {
    // 获取修改的部门id
    this.depId = this.$route.params.id
    this.entId = JSON.parse(localStorage.getItem('ENT_INFO') || '{}').id
    // 当前部门
    this.currentDep = await this.getDepInfo(this.depId)

    this.depName = this.currentDep.name
    // 主管信息
    this.leaderInfo.leaderName = this.currentDep.leaderName!
    this.leaderInfo.leaderId = this.currentDep.leaderId
    // 上级部门信息
    if (this.currentDep.parentId === '-1') {
      // 父级部门parentId -1 上级部门显示企业名称
      this.depInfo = JSON.parse(localStorage.getItem('ENT_INFO') as string)
    } else {
      // 查询上级部门显示
      this.depInfo = await this.getDepInfo(this.currentDep.parentId)
    }
    this.selectedDepId = this.depInfo.id
  },
  methods: {
    selectParentDep() {
      this.showDepSelector = true
      // this.getStaff(this.depInfo.id, false)
    },
    getDepInfo(id: string) {
      this.loading = true
      return this.$service.department.getDep({
        entId: this.entId,
        id
      }).then((res: any) => {
        const { data } = res
        this.loading = false
        if (data.code === this.$global.success) {
          return data.data
        } else {
          this.$toast(data.msg)
        }
      })
    },
    getStaffInfo(id: string) {
      this.loading = true
      this.$service.staff.getInfo({
        id
      }).then((res: any) => {
        const {data} = res
        this.loading = false
        if (data.code === this.$global.success) {
          this.leaderInfo.leaderId = data.data.id
          this.leaderInfo.leaderName = data.data.name
        }else {
          this.$toast(data.msg)
        }
      })
    },
    // 获取通讯录
    getStaff(id: string, isDirect: boolean) {
      this.loading = true
      this.$service.department.getSub({
        parentId: id,
        entId: this.entId,
        hasStaff: true,
        isDirect: isDirect
      }).then((res: any) => {
        const { data } = res
        this.loading = false
        if (data.code === this.$global.success) {
          // 通讯录
          this.contacts = data.data.staffList || []
          if (this.actionType === 'add') {
            this.leader.list = data.data.staffList?.filter((i: Staff) => i.role !== Role.COMMON_MEMBER).sort((a: Staff, b: Staff) => a.role - b.role)
            this.contactTitle = JSON.parse(localStorage.getItem('ENT_INFO') as string).name
          } else {
            const leader = data.data.leader
            if (typeof leader === 'undefined' || leader.id === '') {
              this.leader.list = []
            } else {
              const staff = {...data.data.leader, isDepAdmin: true}
              this.leader.list = typeof data.data.leader === 'undefined' ? [] : [staff]
            }
          }
        } else {
          this.$toast(data.msg)
        }
      })
    },
    selectLeader() {
      this.showMemberSelector = true
      this.multiple=false
      this.actionType='select'
      this.memberSelectorTitle='选择主管'
      this.selectedMemberId = [this.leaderInfo.leaderId]
    },
    addMember() {
      this.showMemberSelector = true
      this.actionType='add'
      this.multiple=true
      this.memberSelectorTitle='添加成员'
      this.selectedMemberId = []
    },
    removeMember() {
      this.showContactSelector = true
      this.actionType="remove"
      this.contactSelectorTitle = '移除成员'
      this.multiple = true
      // 查询当前部门的成员
      this.getStaff(this.currentDep.id, true)
    },
    deleteDep() {
      this.$dialog.confirm({
        title: '提示',
        message: '确定删除该部门吗？若该部门有子部门、部门群，则子部门和对应群消息、群文件都会删除！'
        // confirmButtonText: '解散'
      }).then(() => {
        const data = {
          entId: this.entId,
          id: this.currentDep.id
        }
        this.loading=true
        this.$service.department.deleteDep(data).then((res:any) => {
          const {data} = res
          this.loading=false
          if (data.code === this.$global.success) {
            this.$toast('删除成功')
            this.$router.replace('/team/team-frame')
          } else {
            this.$toast(data.msg)
          }
        })
      }).catch(() => {
        console.log('取消')
      })
    },
    save() {
      if (this.depId === this.depInfo.id) {
        this.$toast('上级部门与当前部门相同')
        return
      }
      this.loading = true
      const data = {
        name: this.depName,
        id: this.depId,
        leaderId: this.leaderInfo.leaderId,
        entId: this.entId,
        parentId: this.depInfo.id,
        hasGroup: this.hasGroup
      }
      this.$service.department.updateDep(data).then((res: any) => {
        const {data} = res
        this.loading = false
        if (data.code === this.$global.success) {
          this.$toast('保存成功')
          this.$router.replace('/team/team-frame')
        } else {
          this.$toast(data.msg)
        }
      })
    }
  },
  watch: {
    selectedMemberId(newVal) {
      if(this.actionType === 'select') {
        this.getStaffInfo(newVal[0])
      }
    },
    async selectedDepId(val: string) {
      if (val !== this.depInfo.id) {
        this.depInfo = await this.getDepInfo(val)
      }
    },
    // async showContactSelector(val) {
    //   if (!val && this.actionType === 'remove') {
    //     const data = await this.getDepInfo(this.currentDep.id)
    //     this.leaderInfo.leaderName = data.leaderName!
    //     this.leaderInfo.leaderId = data.leaderId
    //   }
    // }
  }
})
</script>

<style lang="less">

</style>
