<template>
  <div>
    <v-card class="card-box pa-5">
      <div class="d-flex justify-center mt-3">
        <TextUI :item="textItem" @enter="handleEnter" @appendInnerClick="handleEnter"></TextUI>
      </div>
      <div class="text-end">
        <v-btn prepend-icon="mdi-plus" color="primary" @click="handleAdd">新增</v-btn>
        <span>
          <v-btn :loading="uploadLoading" prepend-icon="mdi-download-box-outline" color="primary" variant="tonal" class="ml-3" @click="handleUploadBefore">
            职位批量导入
          </v-btn>
          <File ref="uploadFile" :custom="true" customName="multipartFile" accept=".xlsx, .xls" @success="handleUploadPosition"></File>
        </span>
        <v-btn :loading="templateLoading" prepend-icon="mdi-export-variant" color="primary" variant="tonal" class="ml-3" @click="handleDownloadTemplate">批量导入模版下载</v-btn>
        <v-btn :loading="exportLoading" prepend-icon="mdi-export-variant" color="primary" variant="tonal" class="ml-3" @click="handleExport">职位导出</v-btn>
      </div>
      <div class="color-666 font-size-14">
        <span>可发布职位数 <strong class="color-primary">{{ baseInfo?.entitlement?.publishJobCount || 0 }}</strong> 个， </span>
        <span class="color-primary border-bottom-primary cursor-pointer" @click="router.push('/recruit/enterprise/membershipPackage/index?fromName=position')">可发布职位数不够用？点击去购买</span>
      </div>
      
      <div class="mt-3">
        <v-tabs v-model="tab" align-tabs="start" color="primary" bg-color="#f7f8fa" @update:model-value="handleChangeTab">
          <v-tab v-for="val in tabList" :key="val.value" :value="val.value"> {{ val.label }}</v-tab>
        </v-tabs>
        <v-window v-model="tab" class="mt-1">
          <v-window-item v-for="val in tabList" :key="val.value" :value="val.value">
            <PositionItem v-if="items.length" :tab="val.value" :items="items" @refresh="handleRefresh"></PositionItem>
          </v-window-item>
        </v-window>
        <Empty v-if="!items.length" :message="loading ? '加载中...' : tipsText" :elevation="false"></Empty>
        <CtPagination
          v-else
          :total="total"
          :page="query.pageNo"
          :limit="query.pageSize"
          @handleChange="handleChangePage"
        ></CtPagination>
      </div>
    </v-card>
  </div>
</template>

<script setup>
defineOptions({ name: 'enterprise-position-list'})
import { ref } from 'vue'
import TextUI from '@/components/FormUI/TextInput'
import PositionItem from './components/item.vue'
import { useRouter } from 'vue-router'; const router = useRouter()
import { getJobAdvertisedList, getJobAdvertisedExport, jobAdvertisedTemplateDownload, jobAdvertisedUpload } from '@/api/position'
import { dealDictArrayData } from '@/utils/position'
import { useI18n } from '@/hooks/web/useI18n'
import { useUserStore } from '@/store/user'
import { getEnterprisePubJobTypePermission } from '@/api/recruit/enterprise/position'
import download from '@/utils/download'
import Snackbar from '@/plugins/snackbar'
import Confirm from '@/plugins/confirm'
import { useRoute } from 'vue-router'; const route = useRoute()

const store = useUserStore()

const { t } = useI18n()
const total = ref(0)
const tipsText = ref(t('common.noData'))
const query = ref({
  pageSize: 10,
  pageNo: 1,
  status: 0, // 0招聘中 1已关闭
  hasExpiredData: false, // true 到期职位
  hire: false // true 众聘岗位
})
const templateLoading = ref(false)
const uploadLoading = ref(false)
const exportLoading = ref(false)
const uploadFile = ref()
const tab = ref(route.query?.tab ? route.query?.tab-0 : 1)
const tabList = [
  { label: '待发布', value: 0, status: 99 },
  { label: t('position.recruitmentInProgress'), value: 1, status: 0 },
  { label: t('position.closed'), value: 2, status: 1 },
  { label: t('position.expiredPosition'), value: 3 }
]
let baseInfo = ref(JSON.parse(localStorage.getItem('entBaseInfo')) || {})
store.$subscribe((mutation, state) => {
  if (Object.keys(state.entBaseInfo).length) baseInfo.value = state.entBaseInfo
})

if (router.currentRoute.value.query?.key) tab.value = Number(router.currentRoute.value.query.key)

const items = ref([])
const textItem = ref({
  type: 'text',
  width: 600,
  value: '',
  label: '请输入职位名称',
  clearable: true,
  appendInnerIcon: 'mdi-magnify'
})

const handleAdd = async () => {
  const data = await getEnterprisePubJobTypePermission()
  if (!data || !data.length) return Snackbar.warning('没有该操作权限，请联系平台管理员升级后再试')
  // 新增职位时查询是否有可发布职位数
  await store.getEnterpriseInfo(true)
  // if (baseInfo.value?.entitlement.publishJobCount <= 0) return Snackbar.warning('可发布职位数不足，请联系平台管理员')
  router.push('/recruit/enterprise/position/add')
  await store.getEnterpriseUserAccountInfo()
}

const loading = ref(false)
// 获取职位列表
const getPositionList = async () => {
  await store.getEnterpriseInfo(true)
  items.value = []; total.value = 0
  loading.value = true
  if (tab.value !== 3) {
    query.value.status = tabList[tab.value].status
    query.value.hasExpiredData = false
  } else {
    query.value.hasExpiredData = true
    delete query.value.status
  }
  const { list, total: number } = await getJobAdvertisedList(query.value)
  if (!list.length) {
    if (query.value.name) tipsText.value = '暂无数据，请更换关键词后再试'
  }
  total.value = number
  items.value = list.length ? dealDictArrayData([], list) : []
  loading.value = false
}
getPositionList()

const handleRefresh = (index) => {
  query.pageNo = 1
  if (index) tab.value = index
  getPositionList()
}

// 职位列表导出
const handleExport = async () => {
  exportLoading.value = true
  try {
    const data = await getJobAdvertisedExport(query.value)
    const label = tabList.find(e => e.value === tab.value)?.label || ''
    const txt = `职位列表${label? '(' + label + ')' : ''}`
    download.excel(data, txt + '.xlsx')
  } finally {
    exportLoading.value = false
  }
}

// 批量上传模版导出
const handleDownloadTemplate = async () => {
  templateLoading.value = true
  try {
    const data = await jobAdvertisedTemplateDownload()
    download.excel(data, '批量上传模版下载.xlsx')
  } finally {
    templateLoading.value = false
  }
}

// 批量上传
const handleUploadBefore = () => {
  const option = {
    otherBtnText: '去下载模板',
    sureText: '继续上传',
  }
  Confirm(t('common.confirmTitle'), '如还未下载过批量上传的模板，请先下载，并且使用模板格式上传职位', option).then((obj) => {
    if (obj?.otherClick) {
      Snackbar.info('开始下载！')
      handleDownloadTemplate()
    } else {
      uploadFile.value.trigger()
    }
  })
}

const handleUploadPosition = async (formData) => {
  uploadLoading.value = true
  try {
    await jobAdvertisedUpload(formData)
    Snackbar.success('上传成功')
    getPositionList()
  } finally {
    uploadLoading.value = false
  }
}

const handleChangeTab = () => {
  query.value.pageNo = 1
  getPositionList()
}

const handleChangePage = (index) => {
  query.value.pageNo = index
  getPositionList()
}

// 职位名称检索
const handleEnter = (e) => {
  query.value.name = e
  query.value.pageNo = 1
  getPositionList()
}
</script>

<style scoped lang="scss">
</style>
