<template>
  <div class="file">
    <dep-selector
      :show.sync="showDepSelector"
      :ent-id="entId"
      :selected.sync="selectedDepId"
    />
    <main-page
      left-arrow
      :loading="loading"
      :title="pageTitle"
      @click-left="handleClickLeft"
    >
      <template #right v-if="!isEdit">
        <div class="text-color-primary" @click="$router.push({ name: 'Import' })">
          批量导入
        </div>
      </template>
      <div class="px-4 pt-14 pb-6">
        <!-- 姓名/职位 -->
        <input-cell
          v-model="acceptJoin.name"
          required
          :limit="10"
          label="真实姓名"
          placeholder="请输入姓名"
          error-msg="姓名不能为空"
        />
        <input-cell
          v-model="acceptJoin.position"
          :limit="10"
          label="职位"
          placeholder="请输入职位"
          error-msg="职位不能为空"
        />
        <!-- 手机号/员工编号/入职时间  -->
        <c-cell
          v-if="!isEdit"
          v-model="acceptJoin.phone"
          required
          title="手机号"
          placeholder="请输入手机号"
          error-msg="手机号码不能为空"
          class="mt-4"
          type="input"
          input-type="number"
          :validator="checkPhone"
        />
        <c-cell
          v-else
          title="手机号"
          :content="acceptJoin.phone"
          class="mt-4"
        />
        <c-cell
          v-model="acceptJoin.shortPhone"
          title="短号"
          placeholder="请输入短号"
          type="input"
          input-type="number"
        />
        <c-cell
          v-model="acceptJoin.email"
          title="邮箱"
          placeholder="请输入邮箱"
          type="input"
          :validator="checkMail"
        />
        <c-cell
          v-model="date"
          dot
          title="入职时间"
          :content="formatDate(acceptJoin.joinTime*1000 || new Date().getTime(), 'YYYY-MM-DD')"
          @click="show = true"
        />
        <van-calendar
          v-model="show"
          :round="false"
          color="#4F62C1"
          :show-confirm="true"
          :style="{ height: '100%' }"
          :min-date="new Date(1981,1,1)"
          @confirm="selectJoinTime"
        />
        <!-- 选择部门 -->
        <group-cell class="mt-4" title="所属部门" @click.native="selectDep">
          <c-cell dot :title="currentDep.name" />
        </group-cell>
        <group-cell v-if="isEdit" class="mt-4" title="绑定账户">
          <c-cell
            v-model="usrId"
            :readonly="true"
            class-input="text-left"
            placeholder="请输入账户ID"
            type="input"
          />
        </group-cell>
        <!--按钮-->
        <div class="mt-4">
          <div v-if="!isEdit">
            <!-- <c-button @click="generateQrCode">生成邀请二维码</c-button> -->
            <c-button @click="addMember">确认添加</c-button>
          </div>
          <div v-else>
            <c-button @click="save">保存</c-button>
            <c-button class="mt-2" type="secondary" @click="deleteUsr">删除员工</c-button>
          </div>
        </div>
      </div>
    </main-page>
  </div>
</template>

<script lang="ts">

import Vue from 'vue'
import { Calendar, Overlay } from 'vant'
import { AcceptJoinDTO, AddStaffDTO, UpdateStaffDTO } from '@/service/moudles/service.dto'
import { trim } from '@/util/Contact'
import { Department, PostMsg } from '@/Interface'
import { formatDate } from '@/util/FormatDate'
import { getPublicKey, getSign, getUserInfo, isAppEnv } from '@/util/Bridge'
import {postMessage} from '@/util/PostMessage'
import {validateMail, validatePhone} from '@/util/Validator'
Vue.use(Calendar).use(Overlay)

export default Vue.extend({
  name: 'AddMember',
  components: {
    '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'),
    'group-cell': () => import('@/components/common/group-cell.vue'),
    'dep-selector': () => import('@/views/team/components/dep-selector.vue')
  },
  beforeRouteEnter(to, from, next) {
    const path = from.path
    next((vm: any) => {
      vm.fromManagement = path === '/team/team-management'
    })
  },
  data() {
    const acceptJoin: AcceptJoinDTO = {
      expiration: 0,
      inviterId: '',
      name: '',
      oaServer: '',
      depId: '',
      entId: '',
      hash: '',
      joinTime: Math.round(new Date().getTime()/1000),
      phone: '',
      position: '',
      shortPhone: '',
      email: ''
    }
    return {
      formatDate,
      date: '请选择入职时间', // 入职时间
      show: false, // 日期弹窗
      depId: '',
      entId: '',
      selectedDepId: '',
      currentDep: {} as Department,
      loading: false,
      acceptJoin,
      updateStaff: {} as UpdateStaffDTO,
      showDepSelector: false,
      depTree: {} as Department,
      pageTitle: '添加成员',
      isEdit: false,
      usrId: '',
      shortPhone: '',
      fromManagement: false,
      addMemberInfo: {} as AddStaffDTO
    }
  },
  async created() {
    const query = this.$route.query
    const entInfo = JSON.parse(localStorage.getItem('ENT_INFO') || '{}')
    if (query.edit === '1') {
      // 编辑
      this.isEdit = true
      this.pageTitle = '编辑成员'
      this.usrId = query.usrId as string
      this.entId = entInfo.id
      const usrInfo = await this.getStaff(this.usrId)
      this.selectedDepId = this.depId = usrInfo.depId
      this.date = this.formatDate(usrInfo.joinTime)
      this.acceptJoin = Object.assign({}, this.acceptJoin, usrInfo)
    } else {
      // 添加
      // const entInfo = JSON.parse(localStorage.getItem('ENT_INFO') || '{}')
      this.selectedDepId = this.depId = this.$route.query.id as string || entInfo.rootDepId
      this.entId = entInfo.id
      this.date = this.formatDate(new Date())
      this.pageTitle = '添加成员'
    }
    const dep = await this.getSub(this.depId)
    this.currentDep = dep.dep
  },
  methods: {
    validateParmas(): boolean {
      const {phone, name} = this.acceptJoin
      return !validatePhone(phone) || name === ''
    },
    getStaff(id: string) {
      this.loading = true
      return this.$service.staff.getInfo({
        id: this.usrId
      }).then((res: any) => {
        this.loading = false
        const {data} = res
        if (data.code === this.$global.success) {
          return data.data
        } else {
          this.$toast(data.msg)
        }
      })
    },
    deleteUsr() {
      this.$dialog.confirm({
        title: '提示',
        message: '删除成员后，将移出团队和对应的部门群，若是主管，则对应部门群群主将随机抽取群管理员或群内成员临时担任，确定删除吗？'
        // confirmButtonText: '解散'
      }).then(() => {
        this.loading = true
        this.$service.staff.resign({
          entId: this.entId,
          id: this.usrId
        }).then((res: any) => {
          this.loading = false
          const {data} = res
          if (data.code === this.$global.success) {
            this.$toast('删除成功')
            this.$router.replace('/team/team-frame')
          } else {
            this.$toast(data.msg)
          }
        }).catch(() => this.loading=false)
      }).catch(() => {
        console.log('删除')
      })
    },
    save() {
      if (this.validateParmas()) {
        this.$toast('请检查输入内容')
        return
      }
      const {depId, entId, joinTime, name, phone, position, shortPhone, email} = this.acceptJoin
      this.updateStaff = {
        depId: this.currentDep.id,
        entId,
        joinTime,
        name,
        phone,
        position,
        id: this.usrId,
        leaderId: this.currentDep.leaderId,
        shortPhone,
        email
      }
      console.log(this.updateStaff, 'update')
      this.loading = true
      this.$service.staff.updateInfo(this.updateStaff).then((res: any) => {
        this.loading = false
        const {data} = res
        if (data.code === this.$global.success) {
          this.$toast('更新成功')
          this.$router.replace('/team/team-frame')
        } else {
          this.$toast(data.msg)
        }
      }).catch(()=>this.loading=false)
    },
    async selectDep() {
      const parentId = JSON.parse(localStorage.getItem('ENT_INFO') as string).rootDepId
      const dep = await this.getSub(parentId)
      this.depTree = dep.dep
      this.depTree.children = dep.subDepList
      this.showDepSelector = true
    },
    getSub(parentId: string) {
      this.loading = true
      return this.$service.department.getSub({
        entId: this.entId,
        parentId: parentId
      }).then((res: any) => {
        const { data } = res
        this.loading = false
        if (data.code === this.$global.success) {
          return data.data
        } else {
          this.$toast(data.msg)
        }
      })
    },
    getDep(depId: string) {
      this.loading = true
      this.$service.department.getDep({
        entId: this.entId,
        id: depId
      }).then((res: any) => {
        const { data } = res
        this.loading = false
        if (data.code === this.$global.success) {
          this.currentDep = data.data
        } else {
          this.$toast(data.msg)
        }
      })
    },
    checkPhone(value: any, callback: Function) {
      if (!validatePhone(value)) {
        callback(new Error('手机号码格式有误，请重新输入'))
      } else {
        callback()
      }
    },
    checkMail(value: string, callback: Function) {
      if (!validateMail(value)) {
        callback(new Error('邮箱格式有误，请重新输入'))
      } else {
        callback()
      }
    },
    handleClickLeft() {
      // this.$router.replace('/team/team-frame')
      if (this.fromManagement) {
        this.$router.push('/team/team-management')
      } else {
        this.$router.push('/team/team-frame')
      }
    },
    // 入职日期
    selectJoinTime(date: Date) {
      this.acceptJoin.joinTime = Math.round(new Date(date).getTime()/1000)
      this.show = false
      this.date = this.formatDate(date)
    },
    // 添加成员
    addMember() {
      if (this.validateParmas()) {
        this.$toast('请检查输入内容')
        return
      }
      this.loading = true
      const {joinTime, name, phone, position, shortPhone, email} = this.acceptJoin
      this.addMemberInfo.depId = this.currentDep.id
      this.addMemberInfo.entId = this.entId
      this.addMemberInfo.name = name
      this.addMemberInfo.position = position
      this.addMemberInfo.phone = phone
      this.addMemberInfo.shortPhone = shortPhone
      this.addMemberInfo.joinTime = joinTime
      this.addMemberInfo.email = email
      this.$service.staff.addMember(this.addMemberInfo).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(() => this.loading=false)
    },
    generateQrCode() {
      if (this.validateParmas()) {
        this.$toast('请检查输入内容')
        return
      }
      this.$dialog.confirm({
        title: '提示',
        message: '确定保存该成员信息，并生成成员信息二维码邀请该成员加入团队？'
      }).then(async () => {
        this.acceptJoin.entId = this.entId
        this.acceptJoin.depId = this.selectedDepId
        this.acceptJoin.expiration = Math.round(new Date().getTime()/1000) + 24 * 60 * 60
        this.acceptJoin.oaServer = localStorage.getItem('ENT_INFO')? JSON.parse(localStorage.getItem('ENT_INFO') as any).oaServer : 'http://172.16.101.107:20000'
        const {depId,entId,expiration,joinTime,name,oaServer,phone,position,shortPhone} = this.acceptJoin
        if (process.env.NODE_ENV === 'development') {
          this.acceptJoin.inviterId = '1FKxgaEh5fuSm7a35BfUnKYAmradowpiTR'
          this.acceptJoin.hash = 'mock-hash'
        } else {
          if (!isAppEnv()) {
            const pubKeyData = await postMessage(PostMsg.GET_PUB_KEY)
            if (pubKeyData.method === PostMsg.GET_PUB_KEY) {
              this.acceptJoin.inviterId = pubKeyData.data
            }
            console.log(this.acceptJoin.inviterId, 'inviterId')
            const signData = await postMessage(PostMsg.GET_SIGN, {
              depId,entId,expiration,inviterId: this.acceptJoin.inviterId,joinTime,name,oaServer,phone,position,shortPhone
            })
            if (signData.method === PostMsg.GET_SIGN) {
              this.acceptJoin.hash = signData.data
            }
          } else {
            this.acceptJoin.inviterId = getPublicKey()
            this.acceptJoin.hash = getSign({
              depId,entId,expiration,inviterId: this.acceptJoin.inviterId,joinTime,name,oaServer,phone,position,shortPhone
            })
          }
        }
        this.$store.commit('setAcceptJoin', this.acceptJoin)
        this.$router.push('/team/two-code')
      }).catch(() => { })
    }
  },
  watch: {
    selectedDepId(val: string) {
      this.getDep(val)
    }
  }
})
</script>

<style lang="less">
</style>
