<template>
	<view>
    <Navbar title="招聘会" />
    <layout-page>
      <view class="defaultBgc" style="padding-bottom: 100px;" :style="{'height': `calc(100vh - ${(navbarHeight + 100)}px)`, 'padding-top': navbarHeight + 'px'}">
        <view v-if="items.length">
          <view class="commonBackground"></view>
          <scroll-view class="scrollBox" :scroll-y="true" @scrolltolower="loadingMore" style="position:relative;">
            <view v-for="val in items" :key="val.id" @tap="handleToJobFairEnterprises(val)" class="list-item default-border">
              <image v-if="val?.previewImg" class="ss-m-t-10" :src="val.previewImg" mode="widthFix" style="width: 100%; height: auto; border-radius: 6px;"></image>
			        <view class="ss-m-t-20">活动主题：{{ val.title }}</view>
              <view class="ss-m-t-20 ss-m-b-10">
                活动状态：
                <span class="font-weight-bold" :style="{'color': val.status === '0' ? '#00b760' : '#ff5252'}">
                  {{ val.status === '0' ? '进行中' : '已结束' }}
                </span>
              </view>
              <view>活动时间：{{ timesTampChange(val.startTime, 'Y-M-D') }}至{{ timesTampChange(val.endTime, 'Y-M-D') }}</view>
              <button class="ss-m-t-20 ss-m-b-10" style="background-color: #00B760; color: #fff;" type="primary">
                {{ val.status === '0' ? '立即加入' : '查看详情' }}
              </button>
            </view>
            <uni-load-more :status="more" />
          </scroll-view>
        </view>
        <view v-else>
          <view class="commonBackground"></view>
          <view class="nodata-img-parent" :style="{'height': `calc(100vh - ${(navbarHeight + 100)}px)`}">
            <image src="https://minio.menduner.com/dev/bb43df1dc91945e05ee93da76e49b34f87b0d10203eb76c20e2d4999a13b9a0a.png" mode="widthFix" style="width: 100vw;height: 100vh;"></image>
          </view>
        </view>
      </view>

      <payPopup ref="payRef" @paySuccess="paySuccess"></payPopup>
    </layout-page>
  </view>
</template>

<script setup>
import { ref, watch } from 'vue'
import layoutPage from '@/layout'
import Navbar from '@/components/Navbar'
import { onShow } from '@dcloudio/uni-app'
import { getAccessToken } from '@/utils/request'
import { showAuthModal } from '@/hooks/useModal'
import { getJobFairList, checkJobFairPermission } from '@/api/jobFair'
import { timesTampChange } from '@/utils/date'
import { userStore } from '@/store/user'
import payPopup from '@/components/payPopup'

const useUserStore = userStore()
const items = ref([])
const navbarHeight = ref(uni.getStorageSync('navbarHeight'))
const total = ref(0)
const query = ref({
	pageNo: 1,
	pageSize: 20
})
const more = ref('more')

// 获得招聘会列表
const getList = async () => {
	if (query.value.pageNo < 1) return
	if (query.value.pageNo === 1) items.value = []
  try {
	  more.value = 'loading'
	  uni.showLoading({ title: '加载中' })
    const res = await getJobFairList(query.value)
    const list = res?.data?.list || []
    if (!list?.length) {
      more.value = 'noMore'
      return
    }
    items.value = items.value.concat(...list)
    total.value = res.data.total
    more.value = 'more'
    if (items.value.length === +total.value) {
      more.value = 'noMore'
      return
    }
  } catch (error) {
	  query.value.pageNo--
	  more.value = 'more'
  } finally {
    uni.hideLoading()
  }
}

// 加载更多
const loadingMore = () => {
  if (more.value === 'noMore') return

  more.value = 'loading'
  query.value.pageNo++
  getList()
}

watch(() => useUserStore.refreshToken, () => {
	if (!useUserStore.refreshToken) return items.value = []
	getList()
})

onShow(() => {
	// 设置自定义tabbar选中值
  const currentPage = getCurrentPages()[0]  // 获取当前页面实例
  const currentTabBar = currentPage?.getTabBar?.()

  // 设置当前tab页的下标index
  currentTabBar?.setData({ selected: 3 })

	if (!getAccessToken()) return showAuthModal()

  getList()
})

//跳转招聘会详情
const payRef = ref()
const itemData = ref({})
const handleToJobFairEnterprises = async (val) => {
  itemData.value = val
  if (!val?.id) {
    uni.showToast({ title: '资源获取失败，请稍后重试', icon: 'none' })
  }
  uni.showLoading({ title: '加载中' })

  try {
    const { data } = await checkJobFairPermission(val.id)
    uni.hideLoading()
    if (data) {
      uni.navigateTo({
        url: '/pagesB/jobFair/details?id=' + val.id
      })
    }
  } catch (error) {
    uni.hideLoading()
    // 权限被禁用
    if (error?.code === 1100056008) {
      uni.showToast({ title: error.msg, icon: 'none', duration: 2000 })
      return
    }
    // 没有权限参加招聘会，购买门票
    if (error?.code === 1100056005) {
      // 没有设置门票金额则提示无权限参加
      if (!val?.admissionPrice || val?.admissionPrice <= 0) {
		    const title = val?.status === '1' ? '您没有参加该招聘会，暂无详情查看' : error.msg
        uni.showToast({ title, icon: 'none', duration: 2000 })
        return
      }
      // 设置门票金额则提示购买门票
      uni.showToast({ title: '您暂时无法参加该招聘会，请先购买门票', icon: 'none', duration: 2000 })

      payRef.value && payRef.value.handleOpen({ spuId: val?.id || '', spuName: val?.title || '', price: val.admissionPrice, type: 5 })
    }
  }
}

// 支付成功
const paySuccess = () => {
  uni.showToast({ title: '支付成功', icon: 'success', duration: 2000 })
  handleToJobFairEnterprises(itemData.value)
}
</script>

<style scoped lang="scss">
.scrollBox {
	height: 100vh;
	box-sizing: border-box;
	padding-bottom: 100px;
}
.list-item {
  margin: 0 30rpx 30rpx 30rpx;
  border-radius: 20rpx;
  padding: 30rpx;
  position: relative;
  background-color: #fbfbfb;
  box-shadow: 1px 2px 12px rgba(0, 0, 0, 0.17);
  view {
    font-size: 28rpx;
    color: #666;
  }
}
</style>
