<template>
  <v-card class="card-box d-flex pa-3" height="80vh">
    <v-row no-gutters justify="space-between">
      <v-col cols="2">
        <v-treeview
          :items="treeData"
          activatable
          color="primary"
          item-value="id"
          item-title="anotherName"
          open-all
          open-strategy="single"
          @update:activated="handleClick"
          @update:opened="handleClick"
        ></v-treeview>
      </v-col>

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

      <v-col class="ml-10">
        <TextInput v-model="query.name" :item="textItem" @change="getUserList"></TextInput>
        <v-data-table
          :loading="loading"
          color="#00897B"
          :items="tableData"
          :headers="headers"
        >
          <template v-slot:item.actions="{ item }">
            <v-btn color="primary" variant="text" @click="handleBinding(item)">{{ $t('enterprise.userManagement.jobBinding') }}</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>
          <template #bottom>
            <CtPagination
              v-if="total > 0"
              :total="total"
              :page="query.pageNo"
              :limit="query.pageSize"
              @handleChange="handleChangePage"
            ></CtPagination>
          </template>
        </v-data-table>
      </v-col>
    </v-row>
  </v-card>

  <CtDialog :visible="show" :widthType="2" titleClass="text-h6" :title="$t('enterprise.userManagement.selectBinding')" @close="handleClose" @submit="handleSubmit">
    <CtForm ref="formPageRef" :items="formItems"></CtForm>
  </CtDialog>
</template>

<script setup>
defineOptions({ name: 'group-account'})
import { ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { timesTampChange } from '@/utils/date'
import { getEnterprisePostPage } from '@/api/recruit/enterprise/system/post'
import { getEnterpriseTree } from '@/api/recruit/enterprise/system/group'
import { getEnterpriseUserList, systemUserEnable, systemUserDisable, systemUserBindingPost } from '@/api/recruit/enterprise/system/user'
import Confirm from '@/plugins/confirm'
import Snackbar from '@/plugins/snackbar'

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' },
  { title: t('enterprise.userManagement.affiliatedEnterprise'), key: 'enterpriseAnotherName' },
  { title: t('enterprise.userManagement.post'), key: 'post.nameCn' },
  { title: t('enterprise.userManagement.phone'), key: 'phone' },
  { title: t('enterprise.userManagement.email'), key: 'email' },
  { 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' }
]
const textItem = ref({
  type: 'text',
  value: null,
  width: 250,
  clearable: true,
  label: '请输入用户名称搜索'
})

const show = ref(false)
const formPageRef = ref()
const bindQuery = ref({})
const postList = ref([])
const formItems = ref({
  options: [
    {
      type: 'autocomplete',
      key: 'postId',
      value: null,
      label: '岗位 *',
      noAttach: false,
      itemText: 'nameCn',
      itemValue: 'id',
      rules: [v => !!v || '请选择要绑定的岗位'],
      items: []
    }
  ]
})

// 获取用户列表
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 getPostList = async () => {
  const res = await getEnterprisePostPage({ pageNo: 1, pageSize: 100 })
  postList.value = res.list
}
getPostList()

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 handleBinding = async (item) => {
  if (!postList.value.length) {
    Snackbar.warning(t('enterprise.userManagement.postNodataToAdd'))
    return
  }
  bindQuery.value.id = item.id
  const obj = formItems.value.options.find(e => e.key === 'postId')
  obj.items = postList.value
  obj.value = item.postId
  show.value = true
}

const handleClose = () => {
  show.value = false
  query.value = {}
}

const handleSubmit = async () => {
  const { valid } = await formPageRef.value.formRef.validate()
  if (!valid) return
  const postId = formItems.value.options.find(e => e.key === 'postId').value
  await systemUserBindingPost(bindQuery.value.id, postId)
  Snackbar.success(t('common.operationSuccessful'))
  handleClose()
  getUserList()
}
</script>

<style scoped lang="scss">

</style>
