<template>
    <scroll-view :scroll-y="true" class="nearby-scroll" @scrolltolower="scrollBottom">
        <view class="two-head">
            <view class="head-all">
                <text>热门商圈</text>
                <text class="color_333333 button-click" @click="handleOpenBusinessDistrict">
                    更多
                    <my-icons type="forward" color="#333333" size="28"></my-icons>
                </text>
            </view>
            <scroll-view class="scroll-head" :scroll-x="true" :scroll-into-view="activeTab" :show-scrollbar="false">
                <view class="head-item-content">
                    <view
                        class="head-item"
                        :class="{ active: state.comId === item.commercialAreaId }"
                        v-for="(item, index) in comlistPuted"
                        :key="item.commercialAreaName"
                        @click="clickCommercialArea(item)"
                    >
                        {{ item.commercialAreaName }}
                    </view>
                </view>
            </scroll-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>
        <select-filter2-col ref="selectFilter2ColModel"></select-filter2-col>
    </scroll-view>
</template>

<script setup>
import { reactive, inject, watch, ref, onMounted, onBeforeUnmount, computed } 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';
import selectFilter2Col from '@/components/selectFilter/selectFilter2Col.vue';

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

const comlistPuted = computed(() => {
    // const commercialArea = state.comlist.find((item) => item.commercialAreaId === state.comId);
    // if (commercialArea) {
    //     const otherItems = state.comlist.filter((item) => item.commercialAreaId !== state.comId);
    //     return [commercialArea, ...otherItems];
    // } else {
    //     return [state.areaInfo, ...state.comlist];
    // }
    // activeTab.value = state.areaInfo.commercialAreaId;
    return state.comlist;
});

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;
            getJobList('refresh');
        },
        cancel: () => {
            showFilter.value = false;
        },
    });
}

onLoad(() => {
    getBusinessDistrict();
});

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 clickCommercialArea(area) {
    state.areaInfo = area;
    state.comId = area.commercialAreaId;
    getJobList('refresh');
}

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 getBusinessDistrict() {
    $api.createRequest(`/app/common/commercialArea/getAllData`).then((resData) => {
        if (resData.data.length) {
            state.comlist = resData.data;
            state.areaInfo = resData.data[0];
            state.comId = resData.data[0].commercialAreaId;
        }
    });
}

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 = {
        longitude: state.areaInfo.longitude,
        latitude: state.areaInfo.latitude,
        current: pageState.page,
        pageSize: pageState.pageSize,
        radius: 2,
        ...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');
}

function handleOpenBusinessDistrict() {
    if (commercialAreaList.value.length) {
        openFilter2Col();
    } else {
        getBusinessDistrictList();
    }
}

function getBusinessDistrictList() {
    $api.createRequest(`/app/common/commercialArea`).then((resData) => {
        if (resData.data.length) {
            commercialAreaList.value = resData.data;
            openFilter2Col();
        }
    });
}

function openFilter2Col() {
    selectFilter2ColModel.value?.open({
        data: commercialAreaList.value,
        title: '商圈',
        currentValue: state.comId,
        maskClick: true,
        success: (values) => {
            pageState.search = {
                ...pageState.search,
                latitude: values.latitude,
                longitude: values.longitude,
            };
            state.areaInfo = values;
            state.comId = values.value;
            getJobList('refresh');
        },
    });
}

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

<style lang="stylus" scoped>
.scroll-head
    width: 100%;
    overflow: hidden;
.tabchecked
    color:  #4778EC !important
.nearby-scroll
    overflow: hidden;
    height: 100%;
    background: #f4f4f4;
    .two-head
        padding: 22rpx;
        display: flex;
        flex-direction: column
        flex-wrap: no-wrap
        // grid-template-columns: repeat(4, 1fr);
        // grid-column-gap: 10rpx;
        // grid-row-gap: 24rpx;
        background: #FFFFFF
        // border-radius: 17rpx 17rpx 17rpx 17rpx;
        .head-all{
            display: flex;
            justify-content: space-between;
            align-items: center
            margin-bottom: 16rpx
        }
        .head-item-content{
            display: flex
            flex-wrap: nowrap
        }
        .head-item
            padding: 0 10rpx
            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% - 140rpx)
    background: #f4f4f4
    display: flex;
    flex-direction: column;
    .one-cards{
        height: 100%
        display: flex;
        flex-direction: column;
        padding: 0 20rpx 20rpx 20rpx;
        background: #f4f4f4
        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>
