<template>
  <div>
    <div v-if="props.items.length" class="d-flex align-center mb-1">
      <v-checkbox
        v-if="tab === 1"
        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 :disabled="!selectAll" color="primary" variant="tonal" size="small" @click="handleAction(0, 'close', {})">{{ $t('common.close') }}</v-btn>
      </div>
    </div>
    <div v-for="val in items" :key="val.id" class="itemBox mb-3" :style="{'height': val.jobFairName ? '160px' : '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" :style="{'max-width': (val.status-0) === 99 && tab === 0 ? '70%' : '85%'}">
          <div class="item-select ml-5" v-if="tab === 1 && !val.jobFairName">
            <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 === 1 && !val.jobFairName}"
            @click="handleDetail(val)"
          >
            <svg-icon v-if="val.jobFairName" name="jobFair" size="20"></svg-icon>
            <span class="position-name" v-ellipse-tooltip>{{ formatName(val.name) }}</span>
          </div>
          <div :class="['mt-3', 'other-info', 'ellipsis', {'ml-10': tab === 1  && !val.jobFairName}]">
            <span>{{ !val.areaId ? '全国' : val.area?.str }}</span>
            <span class="lines" v-if="val.eduName"></span>
            <span>{{ val.eduName }}</span>
            <span class="lines"></span>
            <span>{{ val.expName }}</span>
            <span class="lines" v-if="val.expName"></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
            v-if="val.jobFairName"
            class="color-primary font-size-15 mt-3"
            >
            招聘会：{{ val.jobFairName }}
          </div>
        </div>
        <div v-if="tab !== 0" class="text-center color-primary d-flex flex-column justify-center cursor-pointer" @click="handleToResume(val)">
          <div class="font-weight-bold font-size-18">{{ val.count || 0 }}</div>
          <div class="font-size-14">已投递简历</div>
        </div>
        <div v-if="(val.status-0) === 99 && tab === 0" class="d-flex align-center">
          <v-chip color="warning" label>职位待发布，支付成功后自动发布</v-chip>
        </div>
      </div>
      <div class="bottom pa-5 d-flex justify-space-between align-center">
        <div v-if="val.hrName" class="d-flex align-center bottom-item">
          <v-avatar size="30">
            <v-img :src="getUserAvatar(val.hrHeadImg)" />
          </v-avatar>
          <div class="ml-3" v-ellipse-tooltip>{{ val.hrName }}</div>
        </div>
        <div class="bottom-item" v-ellipse-tooltip :style="{'text-align': val.hrName ? 'center' : 'start'}">
          <span>{{ $t('position.refreshTime') }} ：{{ val.refreshTime ? timesTampChange(val.refreshTime, 'Y-M-D h:m') : '暂无' }}</span>
        </div>
        <div class="d-flex bottom-item justify-end">
          <div class="ml-10 d-flex">
            <div v-if="tab === 1">
              <span>
                <span
                  class="cursor-pointer"
                  :class="{'actions': !val.jobFairName}"
                  :style="{'color': !val.jobFairName ? '#333' : '#999'}"
                  @click="handleAction(val.top ? 4 : 3, '', val)"
                  >
                  {{ val.top ? '取消置顶' : $t('common.topping') }}
                </span>
                <v-tooltip v-if="val.jobFairName" activator="parent" location="top">该职位属于招聘会职位，无法置顶</v-tooltip>
              </span>
              <span class="lines"></span>
              <span>
                <span
                  class="cursor-pointer actions color-333"
                  @click="handleAction(0, '', val)"
                  >
                  {{ $t('common.close') }}
                </span>
                <v-tooltip v-if="val.jobFairName" activator="parent" location="top">该职位属于招聘会职位，前往招聘会中进行关闭</v-tooltip>
              </span>
            </div>

            <!-- 待发布的职位有额度时可使用额度发布职位 -->
            <span v-if="jobNum && +jobNum > 0 && (val.status-0) === 99 && tab === 0">
              <span class="cursor-pointer color-primary" @click="handleRelease(val)">使用额度发布</span>
              <span class="lines"></span>
            </span>

            <span
              v-if="(val.status-0) === 99 && tab === 0"
              class="cursor-pointer color-primary"
              @click="toPay(val)"
              >
              支付发布
            </span>

            <span class="lines" v-if="tab !== 2"></span>
            <span>
              <span
                v-if="tab === 2"
                class="cursor-pointer color-333 actions"
                @click="handleAction(1, '', val, val)"
                >
                激活
              </span>
              <v-tooltip v-if="val.jobFairName" activator="parent" location="top">该职位属于招聘会职位，前往招聘会中进行激活</v-tooltip>
            </span>

            <span class="lines" v-if="tab === 2"></span>
            <span class="cursor-pointer actions" @click="handleDetail(val)">详情</span>

            <!-- 编辑（招聘会职位只可在招聘会中进行操作） -->
            <div>
              <span class="lines"></span>
              <span
                class="cursor-pointer"
                :class="{'actions': val.edit}"
                :style="{'color': val.edit || val.jobFairName ? '#333' : '#999'}"
                @click="handleEdit(val)"
              >
                {{ $t('common.edit') }}
              </span>
              <v-tooltip v-if="!val.edit" activator="parent" location="top">职位发布时间超过24小时的不支持编辑</v-tooltip>
              <v-tooltip v-if="val.jobFairName" activator="parent" location="top">该职位属于招聘会职位，前往招聘会进行编辑</v-tooltip>
            </div>

            <!-- 待发布职位删除 -->
            <span v-if="(val.status-0) === 99 && tab === 0">
              <span class="lines"></span>
              <span class="cursor-pointer actions color-error" @click="handleDelete(val)">删除</span>  
            </span>
          </div>
        </div>
      </div>
    </div>
  </div>

  <confirmPaymentDialog
    v-if="showConfirmPaymentDialog"
    :cost="39900"
    :spuId="spuId"
    :spuName="spuName"
    :showEnterpriseJump="true"
    :showOriginalPrice="true"
    :orderType="1"
    @paySuccess="paySuccess"
    @close="showConfirmPaymentDialog = false"
  ></confirmPaymentDialog>

  <Loading :visible="loading"></Loading>
</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, topJobAdvertisedCancel, createTradeOrder } from '@/api/position'
import Snackbar from '@/plugins/snackbar'
import { useUserStore } from '@/store/user'
import Confirm from '@/plugins/confirm'
import { getUnpaidOrder } from '@/api/common'
import { formatName } from '@/utils/getText'
import { getUserAvatar } from '@/utils/avatar'
import { updatePositionStatus, deletePosition } from '@/api/enterprise'

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

const loading = ref(false)
const selectAll = ref(false) // 全选
const selectList = ref([]) // 选中列表
const dealSelect = () => {
  selectList.value = props.items.filter(e => e.select).map(k => k.id)
}

// 全选
const handleChangeSelectAll = () => {
  const isFairJob = props.items.every(k => k.jobFairId)
  if (isFairJob) {
    Snackbar.warning('招聘会职位不支持批量操作')
    selectAll.value = false
    return
  }

  props.items.map(k => {
    k.select = k.jobFairName ? false : 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 handleRelease = async (val) => {
  if (!val.id) return
  try {
    await updatePositionStatus(val.id)
    Snackbar.success('发布成功')
    emit('refresh', 1)
  } catch {}
}

// 删除待支付职位
const handleDelete = async (val) => {
  if (!val.id) return
  try {
    await deletePosition(val.id)
    Snackbar.success('删除成功')
    emit('refresh', 1)
  } catch {}
}

const showConfirmPaymentDialog = ref(false)
const spuId = ref('')
const spuName = ref('')
const operateObj = ref({})
// 支付
const toPay = async (val) => {
  // 待发布且有额度的激活职位即可
  // if (baseInfo.value.entitlement?.publishJobCount > 0) {
  //   await enableJobAdvertised([val.id])
  //   Snackbar.success('发布成功')
  //   emit('refresh', 1)
  //   return
  // }

  operateObj.value = val
  spuId.value = val.id || ''
  spuName.value = val.name || ''
  showConfirmPaymentDialog.value = true
}

// 支付成功
const paySuccess = async () => {
  showConfirmPaymentDialog.value = false
  setTimeout(() => {
    emit('refresh', 1)
  }, 1000)
}

const apiList = [closeJobAdvertised, enableJobAdvertised, refreshJobAdvertised, topJobAdvertised, topJobAdvertisedCancel]
// 职位关闭、激活、刷新、置顶
const handleAction = async (index, type, { id, jobFairName, jobFairId }, item) => {
  // 招聘会职位跳转去招聘会进行操作
  if (jobFairName) {
    window.open(`/recruit/enterprise/jobFair/details/${jobFairId}`)
    return
  } 
  const ids = type ? props.items.filter(e => e.select).map(k => k.id) : [id]
  if (!ids.length && !index) return

  // 关闭职位提醒
  if (index === 0) {
    const text = baseInfo.value?.entitlement?.publishJobCount && baseInfo.value?.entitlement?.publishJobCount > 0 ? '将消耗一个发布点数' : '将重新收取费用'
    Confirm('系统提示', `是否确认关闭所选职位？关闭后再激活，${text}`).then(async () => {
      await apiList[index](ids)
      Snackbar.success(t('common.operationSuccessful'))
      // 清空选项
      selectList.value = []
      selectAll.value = false
      emit('refresh')
    })
    return
  }

  // 没有可发布额度激活职位需重新付款
  await store.getEnterpriseInfo(true)
  if (index === 1 && baseInfo.value?.entitlement.publishJobCount <= 0) {
    // 判断是否已有创建好的订单，有就直接跳转支付，没有就创建订单
    const data = await getUnpaidOrder({ spuId: id, type: 1 })
    if (!data) await createTradeOrder({ spuId: id, spuName: item.name, price: 39900, type: 1 })
    toPay(item)
    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 router = useRouter()
// 职位编辑
const handleEdit = async (val) => {
  if (!val.id) return

  // 跳转招聘会职位编辑页面
  if (val.jobFairName) {
    window.open(`/recruit/enterprise/jobFair/details/${val.jobFairId}/edit?id=${val.id}`)
    return
  }

  if (!val.edit) return
  const data = await getEnterprisePubJobTypePermission()
  if (!data || !data.length) return Snackbar.warning('没有该操作权限，请联系平台管理员升级后再试')
  router.push(`/recruit/enterprise/position/edit?id=${val.id}`)
}

// 职位详情
const handleDetail = async (val) => {
  if (!val.id) return
  let path = `/recruit/enterprise/position/details?id=${val.id}`
  if (val.jobFairId) path += `&jobFairId=${val.jobFairId}`
  window.open(path)
}

// 查看职位投递简历
const handleToResume = (val) => {
  let path = `/recruit/enterprise/resume?id=${val.id}`
  if (val.jobFairId) path += `&jobFairId=${val.jobFairId}`
  router.push(path)
}
</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);

  &-item {
    width: 33.3%;
    max-width: 33.3%;
  }
}
.actions:hover {
  color: var(--v-primary-base) !important;
}
</style>
