<template>
    <scroll-view :scroll-y="true" class="nearby-scroll" @scrolltolower="scrollBottom">
        <view class="two-head">
            <view
                class="head-item"
                :class="{ active: item.value === fromValue.area }"
                v-for="(item, index) in oneDictData('area')"
                :key="item.value"
                @click="changeArea(item.value, item)"
            >
                {{ item.label }}
            </view>
            <view
                class="head-item"
                :class="{ active: state.tabBxText === fromValue.area }"
                @click="changeArea(state.tabBxText, item)"
            >
                不限区域
            </view>
        </view>
        <view class="nearby-list">
            <view class="nav-filter" @touchmove.stop.prevent>
                <view class="filter-top">
                    <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('/packageA/pages/addPosition/addPosition')">
                        <my-icons class="iconsearch" color="#666D7F" type="plusempty" size="36"></my-icons>
                        <text>添加</text>
                    </view>
                </view>
                <view class="filter-bottom">
                    <view class="btm-left">
                        <view
                            class="button-click filterbtm"
                            :class="{ active: pageState.search.order === item.value }"
                            v-for="item in rangeOptions"
                            @click="handelHostestSearch(item)"
                            :key="item.value"
                        >
                            {{ item.text }}
                        </view>
                    </view>
                    <view class="btm-right button-click" @click="openFilter">
                        筛选
                        <image class="right-sx" :class="{ active: showFilter }" src="@/static/icon/shaixun.png"></image>
                    </view>
                </view>
            </view>
            <view class="one-cards">
                <renderJobs :list="list" :longitude="longitudeVal" :latitude="latitudeVal"></renderJobs>
                <empty v-if="!list.length"></empty>
                <loadmore v-show="list.length > pageState.pageSize" ref="loadmoreRef"></loadmore>
            </view>
        </view>
        <!-- 筛选 -->
        <select-filter ref="selectFilterModel"></select-filter>
    </scroll-view>
</template>

<script setup>
import { reactive, inject, watch, ref, onMounted, onBeforeUnmount } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
const { $api, navTo, debounce, customSystem } = inject('globalFunction');
import { storeToRefs } from 'pinia';
import useLocationStore from '@/stores/useLocationStore';
import useUserStore from '@/stores/useUserStore';
import useDictStore from '@/stores/useDictStore';
const { oneDictData } = useDictStore();
const { userInfo } = storeToRefs(useUserStore());
const { longitudeVal, latitudeVal } = storeToRefs(useLocationStore());
import point2 from '@/static/icon/point2.png';
import LocationPng from '@/static/icon/Location.png';
import selectFilter from '@/components/selectFilter/selectFilter.vue';

const emit = defineEmits(['onFilter']);
const state = reactive({
    tabIndex: 'all',
    tabBxText: 'buxianquyu',
});
const isLoaded = ref(false);
const showFilter = ref(false);
const selectFilterModel = ref();
const fromValue = reactive({
    area: 0,
});
const loadmoreRef = ref(null);
const pageState = reactive({
    page: 0,
    total: 0,
    maxPage: 2,
    pageSize: 10,
    search: {
        order: 0,
    },
});
const list = ref([]);

const rangeOptions = ref([
    { value: 0, text: '推荐' },
    { value: 1, text: '最热' },
    { value: 2, text: '最新发布' },
]);

function choosePosition(index) {
    state.tabIndex = index;
    list.value = [];
    if (index === 'all') {
        pageState.search = {
            ...pageState.search,
            jobTitle: '',
        };
        getJobList('refresh');
    } else {
        // const id = useUserStore().userInfo.jobTitleId.split(',')[index];
        pageState.search.jobTitle = userInfo.value.jobTitle[index];
        getJobList('refresh');
    }
}

function openFilter() {
    showFilter.value = true;
    selectFilterModel.value?.open({
        title: '筛选',
        maskClick: true,
        success: (values) => {
            pageState.search = {
                ...pageState.search,
            };
            for (const [key, value] of Object.entries(values)) {
                pageState.search[key] = value.join(',');
            }
            showFilter.value = false;
            console.log(pageState.search);
            getJobList('refresh');
        },
        cancel: () => {
            showFilter.value = false;
        },
    });
}

async function loadData() {
    try {
        if (isLoaded.value) return;
        const area = oneDictData('area')[0];
        fromValue.area = area.value;
        getJobList('refresh');
        isLoaded.value = true;
    } catch (err) {
        isLoaded.value = false; // 重置状态允许重试
        throw err;
    }
}

function scrollBottom() {
    getJobList();
    loadmoreRef.value.change('loading');
}

// function choosePosition(index) {
//     state.tabIndex = index;
//     if (index === 'all') {
//         pageState.search.jobTitle = '';
//     } else {
//         pageState.search.jobTitle = userInfo.jobTitle[index];
//     }
//     getJobList('refresh');
// }
function changeArea(area, item) {
    fromValue.area = area;
    getJobList('refresh');
}
function getJobList(type = 'add') {
    if (type === 'add' && pageState.page < pageState.maxPage) {
        pageState.page += 1;
    }
    if (type === 'refresh') {
        pageState.page = 1;
        pageState.maxPage = 2;
    }
    let params = {
        current: pageState.page,
        pageSize: pageState.pageSize,
        countyIds: [fromValue.area],
        ...pageState.search,
    };
    if (fromValue.area === state.tabBxText) {
        params.countyIds = [];
    }
    $api.createRequest('/app/job/countyJob', params, 'POST').then((resData) => {
        const { rows, total } = resData;
        if (type === 'add') {
            const str = pageState.pageSize * (pageState.page - 1);
            const end = list.value.length;
            const reslist = rows;
            list.value.splice(str, end, ...reslist);
        } else {
            list.value = rows;
        }
        pageState.total = resData.total;
        pageState.maxPage = Math.ceil(pageState.total / pageState.pageSize);
        if (loadmoreRef.value && typeof loadmoreRef.value.change === 'function') {
            if (rows.length < pageState.pageSize) {
                loadmoreRef.value.change('noMore');
            } else {
                loadmoreRef.value.change('more');
            }
        }
    });
}

function handelHostestSearch(val) {
    pageState.search.order = val.value;
    getJobList('refresh');
}

function handleFilterConfirm(val) {
    pageState.search = {
        order: pageState.search.order,
    };
    for (const [key, value] of Object.entries(val)) {
        pageState.search[key] = value.join(',');
    }
    getJobList('refresh');
}

defineExpose({ loadData, handleFilterConfirm });
</script>

<style lang="stylus" scoped>
.tabchecked
    color:  #4778EC !important
.nearby-scroll
    overflow: hidden;
    height: 100%;
    background: #f4f4f4;
    .two-head
        padding: 22rpx;
        display: flex;
        flex-wrap: wrap
        background: #FFFFFF;
        // grid-template-columns: repeat(4, 1fr);
        // grid-column-gap: 10rpx;
        // grid-row-gap: 24rpx;

        border-radius: 17rpx 17rpx 17rpx 17rpx;
        .head-item
            margin: 10rpx
            white-space: nowrap
            min-width: 156rpx
            line-height: 64rpx
            text-align: center;
            width: fit-content;
            font-size: 21rpx;
            font-weight: 400;
            font-size: 28rpx;
            color: #6C7282;
            background: #F6F6F6;
            border-radius: 12rpx 12rpx 12rpx 12rpx;
        .active
            font-family: 'PingFangSC-Medium', 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, 'Microsoft YaHei', sans-serif;
            color: #256BFA;
            background: #E9F0FF;
            border-radius: 12rpx 12rpx 12rpx 12rpx;
.nearby-list
    border-top: 2rpx solid #EBEBEB;
    min-height: calc(100% - 252rpx)
    background: #f4f4f4
    display: flex;
    flex-direction: column;
    .one-cards{
        display: flex;
        flex-direction: column;
        padding: 0 20rpx 20rpx 20rpx;
        background: #f4f4f4
        height: 100%
        flex: 1
    }
    .nav-filter
        padding: 16rpx 28rpx 0 28rpx
        background: #ffffff
        .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
                    .job
                        font-weight: 400;
                        font-size: 36rpx;
                        color: #666D7F;
                        margin-right: 32rpx;
                        white-space: nowrap
                    .active
                        font-family: 'PingFangSC-Medium', 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, 'Microsoft YaHei', sans-serif;
                        font-weight: 500;
                        font-size: 36rpx;
                        color: #000000;
            .jobs-add
                display: flex
                align-items: center;
                justify-content: center;
                font-weight: 400;
                font-size: 32rpx;
                color: #666D7F;
                line-height: 38rpx;
        .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: 40rpx
                .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)
</style>
