<template>
  <view class="ss-m-x-20">
    <!-- 岗位列表 -->
    <view v-if="list?.length" class="ss-p-b-30 ss-p-t-20">
      <view v-for="(item, index) in list" :key="index" class="mList" @click="handleDetail(item)">
        <!-- 职位信息 -->
        <view class="list-shape" style="border-radius: 12px;">
          <!-- 职位 -->
          <view class="titleBox my-5">
            <view style="display: flex;align-items: center;">
              <image v-if="item.jobFairIds?.length" src="/static/svg/jobFair.svg" class=" ss-m-r-10" style="width: 20px; height: 20px;"></image>
              <rich-text v-if="item.name?.indexOf('style') !== -1" class="job-name" :nodes="item.name"></rich-text>
              <view v-else class="job-name">{{ formatName(item.name) }}</view>
            </view>
            <image v-if="item.top && tab === 1" src="/static/svg/topUp.svg" class="TopUpSvg ss-m-r-10" @tap.stop="topUpSvgClick(item)"></image>
          </view>
          <!-- 职位类型 -->
          <view class="font-size-13 ellipsis ss-m-5" style="color: #808080;">
            <span>{{item.positionName }}</span>
          </view>
          <!-- 薪酬、工作地、学历、工作经验 -->
          <view class="d-flex align-center justify-space-between">
            <view class="font-size-13 ellipsis" style="flex: 1;">
              <span class="tag-gap" style="color: #808080;">
                <span>{{item.area?.str ?? '全国' }}</span>
                <span class="divider-mx" v-if="item.eduName">|</span>
                <span>{{item.eduName }}</span>
                <span class="divider-mx" v-if="item.expName">|</span>
                <span>{{item.expName }}</span>
                <span class="divider-mx">|</span>
                <span>{{!item.payFrom && !item.payTo ? '面议' : `${item.payFrom}-${item.payTo}${item.payName ? '/' + item.payName : ''}` }}</span>
              </span>
            </view>
          </view>
          <view class="font-size-13 color-666 ss-m-t-10">
            <view class="ss-m-t-10">刷新时间：{{ item.refreshTime ? timesTampChange(item.refreshTime, 'Y-M-D h:m') : '暂无' }}</view>
            <view class="ss-m-t-10">到期时间：{{ item.expireTime ? timesTampChange(item.expireTime, 'Y-M-D') : '长期有效' }}</view>
          </view>
          <view class="sub-li-bottom ss-m-t-20">
            <view v-if="tab === 0" class="sub-li-bottom-item color-primary" style="width: 100%;" @tap.stop="toPay(item)">发布</view>
            <view v-if="tab !== 0" class="sub-li-bottom-item color-primary" style="width: 45%;" @tap.stop="handleToResume(item)">{{ item.count || 0 }} 已投递简历</view>
            <view v-if="tab === 1" class="sub-li-bottom-item color-warning" @tap.stop="handleAction(item.top ? 4 : 3, '', item)">{{ item.top ? '取消置顶' : '置顶' }}</view>
            <view v-if="tab === 1" class="sub-li-bottom-item color-666" @tap.stop="handleAction(0, '', item, item)">关闭</view>
            <view v-if="tab === 2" class="sub-li-bottom-item color-warning" @tap.stop="handleAction(1, '', item, item)">激活</view>
          </view>
        </view>
      </view>
      <view v-if="props.noMore" class="noMore">暂无更多数据</view>
    </view>
    <view v-else>
      <image src="https://minio.citupro.com/dev/static/nodata.png" mode="widthFix" style="width: 100vw;height: 100vh;"></image>
      <view style="color: gray; text-align: center;">暂无数据</view>
    </view>
    <!-- 确认框 -->
    <uni-popup ref="confirm" type="dialog">
      <uni-popup-dialog
        type="warn"
        cancelText="取消"
        confirmText="确认" 
        title="系统提示"
        :content="dialogContent"
        @confirm="handleConfirm"
        @close="handleClose"
      ></uni-popup-dialog>
    </uni-popup>
    <!-- 支付 -->
    <payPopup v-if="props.payable" ref="payRef" amount="123" @paySuccess="paySuccess"></payPopup>
  </view>
</template>

<script setup>
import { ref } from 'vue'
// import { commissionCalculation } from '@/utils/position'
import { timesTampChange } from '@/utils/date'
import { formatName } from '@/utils/getText'
import payPopup from '@/components/payPopup'
import {
  topJobAdvertisedCancel,
  topJobAdvertised,
  refreshJobAdvertised,
  closeJobAdvertised,
  enableJobAdvertised
} from '@/api/new/position'
import { userStore } from '@/store/user'; const useUserStore = userStore()
const emit = defineEmits(['entClick', 'refresh'])
const props = defineProps({
  tab: { type: Number, default: 0 },
  list: { type: Array, default: () => [] },
  noMore: { type: Boolean, default: false },
  showWelfareTag: { type: Boolean, default: true },
  payable: { type: Boolean, default: false },
})

const userInfo = ref(useUserStore?.userInfo || {})

const payRef = ref()
// 支付
const toPay = async (val) => {
  // 待发布且有额度的激活职位即可
  if (userInfo.value.entitlement?.publishJobCount > 0) {
    await enableJobAdvertised([val.id])
    emit('refresh', true)
    setTimeout(() => { uni.showToast({ title: '发布成功', icon: 'success' }) }, 1000)
    return
  }
  payRef.value && payRef.value.handleOpen({ spuId: val?.id||'', spuName: val?.name||'', price: 1, type: 1 })
}

// setTimeout(() => { toPay(props.list[0]) }, 2000)

const confirm = ref()
const confirmType = ref('closeJob') // 确认框类型
const dialogContent = ref('')
let handleActionInfo = {}
const apiList = [closeJobAdvertised, enableJobAdvertised, refreshJobAdvertised, topJobAdvertised, topJobAdvertisedCancel]
// 职位关闭、激活、刷新、置顶
const handleAction = async (index, type, { id }, item) => {
  const ids = type ? [] : [id]
  if (!ids?.length && !index) return
  try {
    handleActionInfo.ids = ids
    handleActionInfo.index = index
    uni.showLoading({ title: '操作中...', mask: true })

    // 关闭职位提醒
    if (index === 0) {
      const text = userInfo.value?.entitlement?.publishJobCount && userInfo.value?.entitlement?.publishJobCount > 0 ? '将消耗一个发布点数' : '将重新收取费用'
      const positionName = item?.name ? '【' + formatName(item?.name) + '】' : '所选'
      confirmType.value = 'closeJob' // 确认框类型
      dialogContent.value = `是否确认关闭${positionName}职位？关闭后再激活，${text}！`
      confirm.value.open()
      return
    }

    // 没有可发布额度激活职位需重新付款
    userInfo.value = await useUserStore.getUserInfos()
    if (index === 1 && userInfo.value?.entitlement.publishJobCount <= 3990039900) {
      toPay(item)
      return
    }
    await apiList[index](ids)
    emit('refresh', true)
    setTimeout(() => { uni.showToast({ title: '操作成功', icon: 'success' }) }, 1000)
    // 
  } catch (error) {
    uni.showToast({ title: '操作失败', icon: 'error', duration: 2000 })
    console.log(error)
  } finally {
    uni.hideLoading()
  }
}

const handleClose = () => {
  confirm.value.close()
}

// 取消置顶
const topUpSvgClickVal = ref({})
const topUpSvgClick = (item) => {
  topUpSvgClickVal.value = item
  confirmType.value = 'topUpJob' // 确认框类型
  const positionName = item?.name ? '【' + formatName(item?.name) + '】职位' : '职位'
  dialogContent.value = `是否取消置顶${positionName}？`
  confirm.value.open()
}

const handleConfirm = () => {
  if (confirmType.value === 'closeJob') closeJob()
  if (confirmType.value === 'topUpJob') handleAction(4, '', topUpSvgClickVal.value)
}

// 关闭职位
const closeJob = async () => {
  try {
    uni.showLoading({ title: '关闭中...', mask: true })
    await apiList[handleActionInfo?.index](handleActionInfo?.ids)
    emit('refresh', true)
    setTimeout(() => { uni.showToast({ title: '关闭成功', icon: 'success' }) }, 1000)
  } catch (error) {
    uni.showToast({ title: '关闭失败', icon: 'error' })
    console.log(error)
  } finally {
    uni.hideLoading()
  }
}

// 编辑职位
const handleEdit = async (val) => {
  if (!val.id || !val.edit) {
    uni.showToast({ title: '职位发布时间超过24小时的不支持编辑', icon: 'none', duration: 2000 })
    return
  }
  uni.navigateTo({ url: `/pagesB/positionEdit/index?jobId=${val.id}` })
}

// 职位详情
const handleDetail = (item) => {
  if (!item.id) return
  let url = `/pagesB/positionDetail/index?jobId=${item.id}&isEdit=${item.edit}`
  uni.navigateTo({ url })
}

// 查看职位投递简历
const handleToResume = (val) => {
  let url = `/pagesA/resume/index?jobId=${val.id}&jobName=${formatName(val.name)}`
  if (val.bizId) url += `&jobFairId=${val.bizId}`
  uni.navigateTo({ url })
}

const paySuccess = () => {
  emit('refresh', true)
  setTimeout(() => { uni.showToast({ title: '发布成功', icon: 'success' }) }, 1000)
}

</script>

<style scoped lang="scss">
.noMore{
  margin: 20px 0;
}

.date-time{
  color:#d9d0d2;
  float: right;
}

.divided-line {
  width: 100%;
  height: 1px;
  background-color: #f0f2f7;
  margin: 20px 0;

}
.enterAvatar{
	width: 40px;
	height: 40px;
	// border-radius: 50%;
	margin: auto;
}

.job-name {
  font-size: 16px;
  font-weight: 700;
  color: #0E100F;
  max-width: 80vw;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}


.salary-text {
	float: right;
	color: #00B760;
  font-weight: 700;
}
.list-shape {
	padding: 10px 30rpx 10px;
  background-color: #fff;
  border-radius: 12px 12px 0 0;
  .titleBox {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.tag-gap{
	margin: 10rpx 10rpx 10rpx 0;
}
.tag-gap1{
  margin-bottom: 20px;
}
.divider-mx{
	margin: 0 10rpx;
}
.divider {
	color:#e4d4d2;
}

//公司名称
.cer-end{
  position: absolute;
  top: 85%;
  right: 16%;
}
.cer-text{
  text-decoration: underline;
  margin: 0 5rpx;
}
//一行展示不全...
.dis{
	display: flex;
	align-items: center;
}
.show-more{
	width: 26vw;
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
.mList {
  margin-bottom: 20rpx;
}
/* 列表触底暂无更多 */
.noMore{ text-align:center; color:grey; }
.mt { margin-top: 15rpx; }
.mb { margin-bottom: 10rpx; }
.ml { margin-left: 20rpx; }
.mr { margin-right: 20rpx; }
.mr-10{ margin-right: 10rpx; }
.my-5{ margin: 5px 0; }
.disable {
  position: relative;
  overflow: hidden;
  &::after {
    content: '已失效';
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2em;
    font-weight: bold;
    color: #fc796f;
    top: 0;
    border-radius: 12px;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(255, 255, 255, 0.75);
  }
}
.resumeCount {
  color: #00B760;
  font-size: 12px;
  margin: 0 10px;
}

.sub-li-bottom {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
  font-size: 13px;
  color: #666;
	&-item {
		width: 25%;
		height: 35px;
		line-height: 35px;
		text-align: center;
		margin-right: 15px;
		background-color: #f7f8fa;
		border-radius: 4px;
		&:last-child {
			margin-right: 0;
		}
	}
}
.TopUpSvg {
  width: 25px; height: 25px; color: #FB8C00;
}
</style>
