<template>
  <v-card class="card-box d-flex pa-3">
    <v-row no-gutters justify="space-between">
      <v-col cols="2">
        <div class="d-flex justify-start pr-3">
          <v-btn prepend-icon="mdi-plus" variant="text" density="compact" color="primary" @click="handleAdd(1)">{{ $t('enterprise.userManagement.addBranchOffice') }}</v-btn>
        </div>
        <v-treeview
          :items="treeData"
          activatable
          color="primary"
          item-value="id"
          open-all
          open-strategy="single"
          density="compact"
          @update:activated="handleClick"
          @update:opened="handleClick"
        >
          <template v-slot:title="{ item }">
            <div class="treeTitle font-size-15">
              {{ item.anotherName || item.name }}
              <v-tooltip activator="parent" location="end">{{ item.anotherName || item.name }}</v-tooltip>
            </div>
          </template>
        </v-treeview>
      </v-col>

      <v-divider vertical></v-divider>

      <v-col class="ml-10" cols="9">
        <div class="d-flex justify-space-between px-3">
          <TextInput v-model="query.name" :item="textItem" @change="getUserList"></TextInput>
          <v-btn prepend-icon="mdi-plus" color="primary" @click="handleAdd(0)">{{ $t('enterprise.userManagement.inviteNewColleagues') }}</v-btn>
        </div>
        <CtTable
          :items="tableData"
          :headers="headers"
          :loading="loading"
          :elevation="0"
          :is-tools="false"
          :showPage="true"
          :total="total"
          :page-info="query"
          itemKey="id"
          @pageHandleChange="handleChangePage"
        >
          <template #name="{ item }">
            <div class="d-flex align-center">
              <v-badge
                v-if="item?.sex === '1' || item?.sex === '2'"
                bordered
                offset-y="6"
                :color="badgeColor(item)"
                :icon="badgeIcon(item)">
                <v-avatar size="40" :image="getUserAvatar(item.avatar, item.sex)"></v-avatar>
              </v-badge>
              <v-avatar v-else size="40" :image="getUserAvatar(item.avatar, item.sex)"></v-avatar>
              <span class="ml-3">{{ item?.name }}</span>
            </div>
          </template>
          <template #actions="{ item }">
            <v-btn v-if="item.userType === '0'" color="primary" variant="text" @click="handleEdit(item)">编辑</v-btn>
            <v-btn v-if="item.status === '1' && item.userType !== '1'" color="primary" variant="text" @click="handleAction('', 0, item)">{{ $t('enterprise.userManagement.enable') }}</v-btn>
            <v-btn v-if="item.status === '0' && item.userType !== '1'" color="primary" variant="text" @click="handleAction('', 1, item)">{{ $t('enterprise.userManagement.disable') }}</v-btn>
          </template>
        </CtTable>
      </v-col>
    </v-row>
  </v-card>

  <CtDialog :visible="showEdit" :widthType="2" titleClass="text-h6" title="编辑员工基本信息" @close="showEdit = false; editId = null" @submit="handleSubmit">
    <CtForm ref="CtFormRef" class="mt-3" :items="formItems">
      <template #avatar="{ item }">
        <div style="width: 100%;">
          <div class="d-flex">
            <div style="color: #7a7a7a;">头像</div>
            <div class="avatarsBox" @mouseover="showIcon = true" @mouseleave="showIcon = false">
              <v-avatar class="elevation-5" size=80 :image="getUserAvatar(item.value, item.sex)"></v-avatar>
              <div v-show="showIcon" @click="openFileInput" v-bind="$attrs" class="mdi mdi-camera-outline">
                <input
                  type="file"
                  ref="fileInput"
                  accept="image/png, image/jpg, image/jpeg"
                  style="display: none;"
                  @change="handleUploadFile"
                />
              </div>
            </div>
          </div>
          <div class="text-center color-999 font-size-14 mb-5">*只支持JPG、JPEG、PNG类型的图片</div>
        </div>
      </template>
    </CtForm>
  </CtDialog>

  <ImgCropper :visible="isShowCopper" :image="selectPic" :cropBoxResizable="true" @submit="handleHideCopper" :aspectRatio="1 / 1" @close="isShowCopper = false"></ImgCropper>
</template>

<script setup>
defineOptions({ name: 'group-account'})
import { ref, computed } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { timesTampChange } from '@/utils/date'
import { getEnterpriseTree } from '@/api/recruit/enterprise/system/group'
import { getEnterpriseUserList, systemUserEnable, systemUserDisable } from '@/api/recruit/enterprise/system/user'
import Confirm from '@/plugins/confirm'
import Snackbar from '@/plugins/snackbar'
import { checkEmail } from '@/utils/validate'
import { updateGroupUserAccount } from '@/api/enterprise'
import { getDict } from '@/hooks/web/useDictionaries'
import { getUserAvatar } from '@/utils/avatar'
import { uploadFile } from '@/api/common'
import { getToken } from '@/utils/auth'

const { t } = useI18n()
const total = ref(0)
const loading = ref(false)
const query = ref({
  pageSize: 10,
  pageNo: 1,
  enterpriseId: '',
  name: null
})
const tableData = ref([])
const treeData = ref([])
const headers = [
  { title: t('login.username'), key: 'name', sortable: false },
  { title: t('enterprise.userManagement.affiliatedEnterprise'), key: 'enterpriseAnotherName', sortable: false, value: item => item.enterpriseAnotherName || item.enterpriseName },
  { title: t('enterprise.userManagement.post'), key: 'postName', sortable: false },
  { title: t('enterprise.userManagement.phone'), key: 'phone', sortable: false },
  { title: t('enterprise.userManagement.email'), key: 'email', sortable: false },
  { title: t('enterprise.userManagement.accountType'), key: 'userType', value: item => item.userType === '1' ? t('enterprise.userManagement.administrators') : t('enterprise.userManagement.regularUser'), sortable: false },
  { title: t('enterprise.userManagement.lastLoginTime'), key: 'loginDate', value: item => timesTampChange(item.loginDate), sortable: false },
  { title: t('common.actions'), key: 'actions', sortable: false }
]
const textItem = ref({
  type: 'text',
  value: null,
  width: 250,
  clearable: true,
  label: '请输入用户名称搜索'
})
const badgeColor = computed(() => (item) => {
  return (item && item.sex) ? (item.sex === '1' ? '#1867c0' : 'error') : 'error'
})

const badgeIcon = computed(() => (item) => {
  return (item && item.sex) ? (item.sex === '1' ? 'mdi-gender-male' : 'mdi-gender-female') : 'mdi-gender-female'
})

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const { list, total: number } = await getEnterpriseUserList(query.value)
    tableData.value = list
    total.value = number
  } finally {
    loading.value = false
  }
}

// 获取树形列表
const getTreeData = async () => {
  const data = await getEnterpriseTree()
  if (!data) return
  treeData.value = [data]
  query.value.enterpriseId = data.id
  // 获取用户列表
  getUserList()
}
getTreeData()

// 分页
const handleChangePage = (e) => {
  query.value.pageNo = e
  getUserList()
}

// 树形click
const handleClick = (e) => {
  if (!e.length) return
  query.value.enterpriseId = e[0]
  getUserList()
}

const apiList = [
  { api: systemUserEnable, desc: t('enterprise.userManagement.enableAccount') }, 
  { api: systemUserDisable, desc: t('enterprise.userManagement.disableAccount') }
]

// 启用、禁用账户
const handleAction = (type, index, item) => {
  const ids = [item.id]
  Confirm(t('common.confirmTitle'), apiList[index].desc).then(async () => {
    await apiList[index].api(ids)
    Snackbar.success(t('common.operationSuccessful'))
    query.value.pageNo = 1
    getUserList()
  })
}

// 打开生成邀请链接页面
const handleAdd = (type) => {
  if (!getToken(1)) {
    window.location.reload()
    return
  }
  // type: 类型(0 邀请同事 | 1 邀请子公司)
  window.open(`/recruit/enterprise/systemManagement/groupAccount/invite/${type}`)
}

const formItems = ref({
  options: [
    {
      slotName: 'avatar',
      key: 'avatar',
      value: null
    },
    {
      type: 'ifRadio',
      key: 'sex',
      value: '',
      label: '性别 *',
      width: 90,
      items: []
    },
    {
      type: 'text',
      key: 'name',
      value: '',
      label: '中文名 *',
      rules: [v => !!v || '请填写中文名']
    },
    {
      type: 'text',
      key: 'phone',
      value: '',
      label: '联系电话'
    },
    {
      type: 'text',
      key: 'email',
      value: '',
      label: '电子邮箱 *',
      disabled: false,
      rules: [
        value => {
          if (value) return true
          return '请输入联系邮箱'
        },
        value => {
          if (checkEmail(value)) return true
          return '请输入正确的电子邮箱'
        }
      ]
    },
    {
      type: 'text',
      key: 'postName',
      value: '',
      label: '所在岗位'
    }
  ]
})
getDict('menduner_sex').then(({ data }) => {
  data = data?.length && data || []
  formItems.value.options.find(e => e.key === 'sex').items = data
})


// 编辑员工信息
const showEdit = ref(false)
const CtFormRef = ref()
const editId = ref(null)
const showIcon = ref(false)
const handleEdit = async (item) => {
  formItems.value.options.forEach(e => { e.value = item[e.key] })
  editId.value = item.id
  showEdit.value = true
}

// 选择文件
const fileInput = ref()
const clicked = ref(false)
const selectPic = ref('')
const isShowCopper = ref(false)
const openFileInput = () => {
  if (clicked.value) return
  clicked.value = true
  fileInput.value.click()
  clicked.value = false
}

// 上传头像
const accept = ['jpg', 'png', 'jpeg']
const handleUploadFile = async (e) => {
  const file = e.target.files[0]
  if (!file) return

  const fileType = file.name.split('.')[1]
  if (!accept.includes(fileType)) return Snackbar.warning('请上传图片格式文件')

  const reader = new FileReader()
  reader.readAsDataURL(file)
  reader.onload = () => {
    selectPic.value = String(reader.result)
    isShowCopper.value = true
  }
}

const handleHideCopper = (data) => {
  isShowCopper.value = false
  if (data) {
    const { file } = data
    if (!file) return

    const formData = new FormData()
    formData.append('file', file)
    formData.append('path', 'img')
    uploadFile(formData).then(async ({ data }) => {
      if (!data) return
      formItems.value.options.find(e => e.key === 'avatar').value = data
    })
  }
}

// 提交
const handleSubmit = async () => {
  const { valid } = await CtFormRef.value.formRef.validate()
  if (!valid) return
  const obj = {
    id: editId.value
  } 
  formItems.value.options.forEach(e => { obj[e.key] = e.value })
  if (!obj.sex || obj.sex === '0') return Snackbar.warning('请选择员工性别')
  await updateGroupUserAccount(obj)
  showEdit.value = false
  editId.value = null
  Snackbar.success('编辑成功')
  getUserList()
}
</script>

<style scoped lang="scss">
.avatarsBox {
  height: 80px;
  width: 80px;
  position: relative;
  cursor: pointer;
  margin: 0 0 10px 100px;
  .img {
    width: 100%;
    height: 100%;
  }
  .mdi {
    font-size: 42px;
    color: #fff;
  }
  div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    border-radius: 50%;
  }
}
.treeTitle {
  width: 100%;
  max-width: 100%;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
