<template>
  <div>
    <div v-if="props.items.length" class="d-flex align-center mb-1">
      <v-checkbox v-if="tab !== 3" v-model="selectAll" :label="!selectAll ? $t('common.selectAll') : `已选中${selectList.length}条`" hide-details color="primary" @update:model-value="handleChangeSelectAll"></v-checkbox>
      <div v-if="tab === 1" class="ml-8">
        <v-btn :disabled="!selectAll" color="primary" variant="tonal" size="small" @click="handleAction(2, 'batch', {})">一键刷新</v-btn>
        <v-btn class="mx-3" :disabled="!selectAll" color="primary" variant="tonal" size="small" @click="handleAction(3, 'top', {})">{{ $t('common.topping') }}</v-btn>
        <v-btn class="mr-3" :disabled="!selectAll" color="primary" variant="tonal" size="small" @click="handleAction(4, 'top', {})">取消置顶</v-btn>
        <v-btn :disabled="!selectAll" color="primary" variant="tonal" size="small" @click="handleAction(0, 'close', {})">{{ $t('common.close') }}</v-btn>
      </div>
      <v-btn v-if="tab === 2" class="ml-8" :disabled="!selectAll" color="primary" variant="tonal" size="small" @click="handleAction(1, 'activation', {})">一键激活</v-btn>
    </div>
    <div v-for="val in items" :key="val.id" class="itemBox mb-3" style="height: 134px;">
      <div v-if="val.top && tab === 1" style="position: absolute;">
        <svg-icon name="top" size="50"></svg-icon>
      </div>
      <div class="d-flex justify-space-between" style="padding: 10px 20px;">
        <div class="position">
          <div class="item-select ml-5" v-if="tab !== 3">
            <v-checkbox v-model="val.select" hide-details color="primary" @update:model-value="handleChangeSelect"></v-checkbox>
          </div>
          <div class="d-flex align-center" :class="{'cursor-pointer': tab === 1, 'ml-15': tab !== 3}" @click="handleEdit(val)">
            <span v-if="val.name.indexOf('style')" v-html="val.name" class="position-name"></span>
            <span v-else class="position-name">{{ val.name }}</span>
          </div>
          <div :class="['mt-3', 'other-info', 'ellipsis', 'ml-10']">
            <span>{{ val.areaName }}</span>
            <span class="lines" v-if="val.areaName && val.eduName"></span>
            <span>{{ val.eduName }}</span>
            <span class="lines"></span>
            <span>{{ val.expName }}</span>
            <span class="lines"></span>
            <span v-if="!val.payFrom && !val.payTo">面议</span>
            <span v-else>{{ val.payFrom ? val.payFrom + '-' : '' }}{{ val.payTo }}{{ val.payName ? '/' + val.payName : '' }}</span>
            <span class="lines" v-if="val.positionName"></span>
            <span>{{ val.positionName }}</span>
          </div>
        </div>
        <!-- <div class="d-flex align-center">
          <v-btn v-if="tab === 1" class="ml-3" color="primary" @click="handleAction(2, '', val)">
            <span>{{ $t('common.refresh') + $t('common.position') }}</span>
            <v-icon class="ml-2">mdi-help-circle-outline</v-icon>
            <v-tooltip activator="parent" location="top">刷新职位后，发布时间为最新的</v-tooltip>
          </v-btn>
          <v-btn v-if="tab === 2" color="primary" @click="handleAction(1, '', val)">{{ $t('common.activatePosition') }}</v-btn>
        </div> -->
      </div>
      <div class="bottom pa-5 d-flex justify-space-between align-center">
        <div>
          {{ $t('position.refreshTime') }} ：{{ timesTampChange(val.updateTime, 'Y-M-D') }}
          <span>
            <span class="septal-line"></span>
            到期时间：{{ val.expireTime ? timesTampChange(val.expireTime, 'Y-M-D') : '长期有效' }}
          </span>
        </div>
        <div class="d-flex">
          <div class="ml-10 d-flex">
            <div v-if="tab === 1">
              <span class="cursor-pointer actions" @click="handleAction(val.top ? 4 : 3, '', val)">{{ val.top ? '取消置顶' : $t('common.topping') }}</span>
              <span class="lines"></span>
              <span class="cursor-pointer actions" @click="handleAction(0, '', val)">{{ $t('common.close') }}</span>
              <span class="lines"></span>
            </div>
            <div v-if="tab === 1" class="cursor-pointer actions" @click="handleEdit(val)">{{ $t('common.edit') }}</div>
            <div v-if="tab === 3" class="cursor-pointer actions" @click="handleUpdateExpireTime(val)">修改到期时间</div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <Loading :visible="loading"></Loading>

  <CtDialog :visible="showExpire" :widthType="2" titleClass="text-h6" title="修改职位到期时间" @close="showExpire = false; expireTimeId = null" @submit="handleSubmit">
    <CtForm v-if="showExpire" ref="CtFormRef" :items="formItem"></CtForm>
  </CtDialog>
</template>

<script setup>
defineOptions({ name: 'enterprise-position-item'})
import { ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { timesTampChange } from '@/utils/date'
import { useI18n } from '@/hooks/web/useI18n'
import { getEnterprisePubJobTypePermission } from '@/api/recruit/enterprise/position'
import { closeJobAdvertised, enableJobAdvertised, refreshJobAdvertised, topJobAdvertised, updatePositionExpireTime, topJobAdvertisedCancel } from '@/api/position'
import Snackbar from '@/plugins/snackbar'
import { useUserStore } from '@/store/user'

const store = useUserStore()
const { t } = useI18n()
const emit = defineEmits(['refresh'])
const props = defineProps({
  tab: {
    type: Number,
    default: 1
  },
  items: Array
})

const showExpire = ref(false)
const CtFormRef = ref()
const loading = ref(false)
const selectAll = ref(false) // 全选
const selectList = ref([]) // 选中列表
const formItem = ref({
  options: [
    {
      type: 'datePicker',
      key: 'time',
      value: null,
      format: 'YYYY-MM-DD',
      label: '到期时间 *',
      labelWidth: 110,
      teleported: true,
      disabledDates: true
    }
  ]
})
const dealSelect = () => {
  selectList.value = props.items.filter(e => e.select).map(k => k.id)
}

// 全选
const handleChangeSelectAll = () => {
  props.items.map(k => {
    k.select = selectAll.value
    return k
  })
  dealSelect()
}
// 单选
const handleChangeSelect = () => {
  const length = props.items.filter(k => k.select).length
  selectAll.value = length > 0 ? true : false
  dealSelect()
}

// tab改变时清空选中的项
watch(
  () => props.tab,
  () => {
    props.items.map(e => e.select = false)
    selectList.value = []
    selectAll.value = false
  },
  { immediate: true }
)

// 分页选中回显
watch(
  () => props.items,
  (newVal) => {
    selectList.value.forEach(e => {
      const obj = newVal.find(k => k.id === e)
      if (obj) obj.select = true
    })
  },
  { immediate: true },
  { deep: true }
)

let baseInfo = ref(JSON.parse(localStorage.getItem('entBaseInfo')) || {})
store.$subscribe((mutation, state) => {
  if (Object.keys(state.entBaseInfo).length) baseInfo.value = state.entBaseInfo
})
const apiList = [closeJobAdvertised, enableJobAdvertised, refreshJobAdvertised, topJobAdvertised, topJobAdvertisedCancel]
// 职位关闭、激活、刷新、置顶
const handleAction = async (index, type, { id }) => {
  // 激活职位时查询是否有可发布职位数
  if (index === 1) {
    await store.getEnterpriseInfo(true)
    if (baseInfo.value?.entitlement.publishJobCount <= 0) return Snackbar.warning('可发布职位数不足，请联系平台管理员')
  }
  const ids = type ? props.items.filter(e => e.select).map(k => k.id) : [id]
  if (!ids.length && !index) return
  loading.value = true
  try {
    await apiList[index](ids)
    Snackbar.success(t('common.operationSuccessful'))
    // 清空选项
    selectList.value = []
    selectAll.value = false
    emit('refresh')
  } finally {
    loading.value = false
  }
}

// 职位过期时间修改
const expireTimeId = ref('')
const handleUpdateExpireTime = (item) => {
  expireTimeId.value = item.id
  showExpire.value = true
}
const handleSubmit = async () => {
  const time = formItem.value.options.find(e => e.key === 'time').value
  if (!time) return Snackbar.warning('请选择职位到期时间')
  await updatePositionExpireTime({ id: expireTimeId.value, time })
  expireTimeId.value = ''
  showExpire.value = false
  emit('refresh')
}

const router = useRouter()
// 职位编辑
const handleEdit = async (val) => {
  if (props.tab !== 1) return
  const data = await getEnterprisePubJobTypePermission()
  if (!data || !data.length) return Snackbar.warning('没有该操作权限，请联系平台管理员升级后再试')
  router.push(`/recruit/enterprise/position/edit?id=${val.id}`)
}
</script>

<style scoped lang="scss">
.itemBox {
  position: relative;
  border: 1px solid #e5e6eb;
}
.position-name {
  color: var(--color-333);
  font-size: 19px;
}
.position {
  position: relative;
  .item-select {
    position: absolute;
    left: -8px;
    top: -13px;
  }
}
.lines {
  display: inline-block;
  width: 1px;
  height: 17px;
  vertical-align: middle;
  background-color: #e0e0e0;
  margin: 0 10px;
}
.other-info {
  font-size: 15px;
  color: var(--color-666);
}
.bottom {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 40px;
  background-color: #f7f8fa;
  font-size: 14px;
  color: var(--color-888);
}
.actions:hover {
  color: var(--v-primary-base);
}
</style>
