<template>
  <div>
    <div v-for="val in items" :key="val.id" class="itemBox mb-3" style="height: 162px;">
      <div class="d-flex justify-space-between" style="padding: 10px 20px;">
        <div class="position">
          <div class="d-flex align-center" :class="{'cursor-pointer': tab === 1}" @click="handleEdit(val)">
            <svg-icon class="mr-3" name="pin" size="25"></svg-icon>
            <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']">
            <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"></span>
            <span>{{ val.positionName }}</span>
          </div>
          <div v-if="val?.hire" class="mt-2">
            <v-chip v-if="val?.hirePrice && val.hirePrice > 0" class="mr-3" label color="primary" size="small">M豆：{{ commissionCalculation(val.hirePrice / 100, 1) }}个</v-chip>
          </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" 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>
          {{ $t('position.refreshTime') }} ：{{ timesTampChange(val.updateTime, 'Y-M-D') }}
          <span v-if="tab === 1">
            <span class="septal-line"></span>
            到期时间：{{ val.expireTime ? timesTampChange(val.expireTime, 'Y-M-D') : '长期有效' }}
          </span>
        </div>
        <div class="d-flex align-center">
          <span v-if="val.status === '1' && tab === 2" class="cursor-pointer actions" @click="toPay(val)">职位已关闭，点击激活职位</span>
          <span v-if="(val.status-0) === 99" class="cursor-pointer color-primary" @click="toPay(val)">去支付</span>
          <span v-if="(val.status - 0) !== 99 && val.status !== '1' && tab === 1" class="cursor-pointer actions" @click="handleAction(0, val)">{{ $t('common.close') }}</span>
          <span v-if="tab !== 3 && val.edit" class="lines"></span>
          <span v-if="tab !== 3 && val.edit" class="cursor-pointer actions" @click="handleEdit(val)">编辑</span>
          <!-- <span v-if="tab === 3" class="cursor-pointer actions" @click="handleUpdateExpireTime(val)">修改到期时间</span> -->
          <span class="lines" v-if="tab !== 3"></span>
          <span class="cursor-pointer actions" @click="handleDetail(val)">详情</span> 
        </div>
      </div>
    </div>
  </div>
  <confirmPaymentDialog
    v-if="showConfirmPaymentDialog"
    :cost="cost"
    :spuId="spuId"
    :spuName="spuName"
    :orderType="2"
    @paySuccess="paySuccess"
    @close="showConfirmPaymentDialog = false"
  ></confirmPaymentDialog>

  <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" style="height: 100px;"></CtForm>
  </CtDialog>
</template>

<script setup>
import { commissionCalculation } from '@/utils/position'
defineOptions({ name: 'enterprise-position-item'})
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { timesTampChange } from '@/utils/date'
import { useI18n } from '@/hooks/web/useI18n'
import { closeJobAdvertised, enableJobAdvertised, updatePositionExpireTime } from '@/api/position'
import Snackbar from '@/plugins/snackbar'
import confirmPaymentDialog from '@/components/pay/confirmPaymentDialog.vue'
import { getEnterprisePubJobTypePermission } from '@/api/recruit/enterprise/position'

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

const loading = ref(false)
const showConfirmPaymentDialog = ref(false)
const cost = ref(0)
const spuId = ref('')
const spuName = ref('')
const operateObj = ref({})
const toPay = (val) => { // 已关闭的职位激活需要再次支付
  operateObj.value = val
  spuId.value = val.id || ''
  spuName.value = val.name || ''
  cost.value = val.hirePrice
  // 打开支付弹窗
  showConfirmPaymentDialog.value = true
}

// 支付成功
const paySuccess = async () => {
  showConfirmPaymentDialog.value = false
  // console.log(' operateObj.value?.status',  operateObj.value?.status)
  // if (operateObj.value?.status === '1') {
  //   handleAction(1, operateObj.value)
  // }
  setTimeout(() => {
    emit('refresh')
  }, 1000)
}

const showExpire = ref(false)
const CtFormRef = ref()
const formItem = ref({
  options: [
    {
      type: 'datePicker',
      key: 'time',
      value: null,
      format: 'YYYY-MM-DD',
      label: '到期时间 *',
      labelWidth: 110,
      disabledDate: true,
      teleported: true
    }
  ]
})

const apiList = [ closeJobAdvertised, enableJobAdvertised ]

// 职位关闭、激活
const handleAction = async (index, { id }) => {
  const ids = [id]
  if (!ids.length && !index) return
  loading.value = true
  try {
    await apiList[index](ids)
    Snackbar.success(t('common.operationSuccessful'))
    emit('refresh')
  } finally {
    loading.value = false
  }
}

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/hirePosition/edit?id=${val.id}`)
}

// 职位过期时间修改
const expireTimeId = ref('')
const handleUpdateExpireTime = (item) => {
  expireTimeId.value = item.id
  showExpire.value = true
}
const handleSubmit = async () => {
  // const { valid } = await CtFormRef.value.formRef.validate()
  // if (!valid) return
  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 handleDetail = async (val) => {
  if (!val.id) return
  window.open(`/recruit/enterprise/position/details?id=${val.id}`)
}

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