<template>
    <view class="app-container">
        <view class="nav-filter">
            <view class="filter-top" @touchmove.stop.prevent>
                <scroll-view :scroll-x="true" :show-scrollbar="false" class="tab-scroll">
                    <view class="jobs-left">
                        <view
                            class="job button-click"
                            :class="{ active: state.tabIndex === 'all' }"
                            @click="choosePosition('all')"
                        >
                            全部
                        </view>
                        <view
                            class="job button-click"
                            :class="{ active: state.tabIndex === index }"
                            v-for="(item, index) in userInfo.jobTitle"
                            :key="index"
                            @click="choosePosition(index)"
                        >
                            {{ item }}
                        </view>
                    </view>
                </scroll-view>
                <view class="jobs-add button-click" @click="navTo('/pages/search/search')">
                    <my-icons class="iconsearch" color="#666D7F" type="search" size="36"></my-icons>
                    <text>搜索</text>
                </view>
            </view>
        </view>
        <view class="cards">
            <scroll-view :scroll-y="true" class="tab-scroll" @scrolltolower="scrollBottom">
                <view class="scroll-content">
                    <custom-waterfalls-flow
                        ref="waterfallsFlowRef"
                        :column="columnCount"
                        :columnSpace="columnSpace"
                        :value="list"
                    >
                        <template v-slot:default="job">
                            <view class="slot-item">
                                <view class="job-image btn-feel" @click="nextVideo(job)">
                                    <image class="cover-image" :src="job.cover" mode="aspectFill"></image>
                                    <view class="cover-triangle"></view>
                                </view>
                                <view class="job-info" @click="nextDetail(job)">
                                    <view class="salary">
                                        <Salary-Expectation
                                            :max-salary="job.maxSalary"
                                            :min-salary="job.minSalary"
                                            :is-month="true"
                                        ></Salary-Expectation>
                                        <image v-if="job.isHot" class="flame" src="/static/icon/flame.png"></image>
                                    </view>
                                    <view class="title">{{ job.jobTitle }}</view>
                                    <view class="desc">
                                        <image class="point3" src="/static/icon/point3.png"></image>
                                        <!-- <my-icons type="location" size="28"></my-icons> -->
                                        <view class="descText">{{ job.companyName }}</view>
                                    </view>
                                </view>
                            </view>
                        </template>
                    </custom-waterfalls-flow>
                    <empty v-if="!list.length"></empty>
                    <loadmore v-if="list.length >= pageSize" ref="loadmoreRef"></loadmore>
                </view>
            </scroll-view>
        </view>
    </view>
</template>

<script setup>
import { reactive, inject, watch, ref, onMounted, watchEffect, nextTick } from 'vue';
import { usePagination } from '@/hook/usePagination';
const { $api, navTo } = inject('globalFunction');
import { storeToRefs } from 'pinia';
import useUserStore from '@/stores/useUserStore';
import img from '@/static/icon/filter.png';
import useLocationStore from '@/stores/useLocationStore';
import { useColumnCount } from '@/hook/useColumnCount';
import { useRecommedIndexedDBStore, jobRecommender } from '@/stores/useRecommedIndexedDBStore.js';
const recommedIndexDb = useRecommedIndexedDBStore();
// status
const { userInfo } = storeToRefs(useUserStore());
const isLoaded = ref(false);
const waterfallsFlowRef = ref(null);
const loadmoreRef = ref(null);
const state = reactive({
    tabIndex: 'all',
});

// 响应式搜索条件（可以被修改）
const searchParams = ref({});
const pageSize = ref(10);
const { list, loading, refresh, loadMore,finished } = usePagination(
    (params) => $api.createRequest('/app/job/littleVideo', params),
    dataToImg, // 转换函数
    {
        pageSize: pageSize,
        search: searchParams,
        dataKey: 'data',
        onBeforeRequest: () => {
            loadmoreRef.value?.change('loading');
        },
    }
);
watch(()=>finished.value, (newVal) => {
  if (newVal) {
    // 确保瀑布流组件知道数据已加载完成
    loadmoreRef.value?.change('noMore')
  }else{
    loadmoreRef.value?.change('more')
  }
})

// function imageloaded() {
//     nextTick(() => {
//         console.log('触发',finished.value)
//         if (finished.value) {
//           loadmoreRef.value?.change('noMore')
//         } else {
//           loadmoreRef.value?.change('more')
//         }
//     })
// }

const { columnCount, columnSpace } = useColumnCount(() => {
    pageSize.value = 10 * (columnCount.value - 1);
    nextTick(() => {
        waterfallsFlowRef.value?.refresh?.();
        useLocationStore().getLocation();
    });
});

async function loadData() {
    try {
        if (isLoaded.value) return;
        isLoaded.value = true;
        refresh();
    } catch (err) {
        isLoaded.value = false; // 重置状态允许重试
        throw err;
    }
}

async function choosePosition(index) {
    state.tabIndex = index;
    if (index === 'all') {
        searchParams.value.jobTitle = '';
    } else {
        searchParams.value.jobTitle = userInfo.value.jobTitle[index];
    }
    console.log(searchParams.value);
    refresh('refresh');
    waterfallsFlowRef.value.refresh();
}

function scrollBottom() {
    loadMore();
}

function nextDetail(job) {
    // 记录岗位类型，用作数据分析
    if (job.jobCategory) {
        const recordData = recommedIndexDb.JobParameter(job);
        recommedIndexDb.addRecord(recordData);
    }
    navTo(`/packageA/pages/post/post?jobId=${btoa(job.jobId)}`);
}

function nextVideo(job) {
    uni.setStorageSync(`job-Info`, job);
    navTo(`/packageA/pages/tiktok/tiktok`);
}

function dataToImg(data) {
    return data.map((item) => ({
        ...item,
        // image: item.cover,
        image: img,
        hide: true,
    }));
}

defineExpose({ loadData });
</script>

<style lang="stylus" scoped>
.app-container
    width: 100%;
    height: calc(100vh - var(--window-top) - var(--status-bar-height) - var(--window-bottom));
    background: url('@/static/icon/background2.png') 0 0 no-repeat;
    background-size: 100% 728rpx;
    // background-color: #FFFFFF;
    display: flex;
    flex-direction: column
    .cards
        flex: 1;
        overflow: hidden;
        .tab-scroll
            height: 100%;
            white-space: nowrap;
            text-overflow: clip;
            .scroll-content{
                padding: 24rpx
                height: calc(100% - 48rpx)
            }

.nav-filter
    padding: 16rpx 28rpx 30rpx 28rpx
    .filter-top
        display: flex
        justify-content: space-between;
        .tab-scroll
            flex: 1;
            overflow: hidden;
            margin-right: 20rpx
            white-space: nowrap;
            overflow: hidden;
            text-overflow: clip;
            -webkit-mask-image: linear-gradient(to right, black 60%, transparent);
            mask-image: linear-gradient(to right, black 60%, transparent);
            .jobs-left
                display: flex
                flex-wrap: nowrap
                align-items: center
                .job
                    font-weight: 400;
                    font-size: 28rpx;
                    color: #666D7F;
                    margin-right: 32rpx;
                    white-space: nowrap
                .active
                    font-weight: 500;
                    font-size: 36rpx;
                    color: #000000;
        .jobs-add
            display: flex
            align-items: center;
            justify-content: center;
            font-weight: 400;
            font-size: 28rpx;
            color: #666D7F;
            line-height: 38rpx;
            .iconsearch
                margin-right: 6rpx
    .filter-bottom
        display: flex
        justify-content: space-between
        padding: 24rpx 0
        .btm-left
            display: flex
            .filterbtm
                font-weight: 400;
                font-size: 32rpx;
                color: #666D7F;
                margin-right: 24rpx
                padding: 0rpx 16rpx
            .active
                font-weight: 500;
                font-size: 32rpx;
                color: #256BFA;
        .btm-right
            font-weight: 400;
            font-size: 32rpx;
            color: #6C7282;
            .right-sx
                width: 26rpx;
                height: 26rpx;
            .active
                transform: rotate(180deg)

.slot-item
    background: #f4f4f4;
    // background: #f6f8fa;
    .job-image{
        width: 100%;
        height: 280rpx;
        position: relative;
        .cover-image{
            width: 100%;
            height: 100%;
            overflow: hidden;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .cover-triangle{
            position: absolute;
            right: 20rpx;
            top: 20rpx
            width: 36rpx
            height: 36rpx
            border-radius: 50%
            background: rgba(0,0,0,0.3)
        }
        .cover-triangle::after {
          content: '';
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-40%, -50%) rotate(90deg);
          width: 0;
          height: 0;
          border-left: 8rpx solid transparent;
          border-right: 8rpx solid transparent;
          border-bottom: 12rpx solid #fff;
        }
    }
    .job-info{
        padding: 10rpx 10rpx 24rpx 24rpx
    }
    .salary
        color: #4C6EFB;
        font-size: 28rpx
        display: flex
        align-items: flex-start
        justify-content: space-between
        font-family: DIN-Medium;
        .flame
            margin-top: 4rpx
            margin-right: 4rpx
            width: 24rpx
            height: 31rpx
    .title
        font-family: 'PingFangSC-Medium', 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, 'Microsoft YaHei', sans-serif;
        font-weight: 500;
        font-size: 32rpx;
        color: #333333;
        margin-top: 6rpx;
        white-space: pre-wrap
    .desc
        font-weight: 400;
        font-size: 24rpx;
        color: #6C7282;
        margin-top: 6rpx;
        display: flex
        align-items: flex-start
        .descText{
            flex: 1
            white-space: pre-wrap
        }
        .point3{
            margin: 4rpx 4rpx 0 0
            height: 26rpx
            width: 26rpx
        }
</style>
