<template>
    <ShopPageHead></ShopPageHead>
    <!-- xc_shop_search_more_no_card  乡村网-商城-搜索-查看更多 -->
    <main class="index_main" id="all_vue">
        <HomeAdvertising :imgurl="adImg1"></HomeAdvertising>
        <!--子菜单和地区选择-->
        <ShopSubMenu2></ShopSubMenu2>
        <!-- 地区选择 -->
        <div class="categ_crumb_box clearfix_2">
            <!-- 当前位置 -->
            <div class="categ_crumb_left">
                <span class="categ_crumb_left_a" title=""> 当前位置： </span>
                <NuxtLink
                    :to="`/xiangcunshangcheng/index.html`"
                    class="categ_crumb_left_a"
                >
                    乡村商城
                </NuxtLink>
                &gt;
                <NuxtLink
                    :to="`/${towgetRoute}/index.html`"
                    class="categ_crumb_left_a"
                >
                    {{name}}
                </NuxtLink>
                &gt;
                <NuxtLink
                    :to="`/${alltargetRoute}/index.html`"
                    class="categ_crumb_left_a"
                >
                    {{name2}}
                </NuxtLink>
                &gt;
                <span class="categ_crumb_left_text">求购</span>
            </div>
            <!-- 当前位置 -->
            <!-- 当前商品所在地 -->
            <div class="categ_crumb_right clearfix" v-if="cityList.length > 0">
                <div class="categ_crumb_right_text">当前商品所在地：</div>
                <div class="categ_crumb_right_text hand">{{cityName}}</div>
                <div class="categ_crumb_right_btn back100 hand" @click="btn_if_categ_crumb_panel_fun" tabindex="1"
                    @blur="categ_crumb_panel_btn_blur_fun">
                </div>
            </div>
            <!-- 当前商品所在地 -->
            <div class="categ_crumb_panel" v-show="if_categ_crumb_panel" tabindex="0"
                @click="categ_crumb_panel_focus_fun" @blur="categ_crumb_panel_blur_fun">
                <h4 class="categ_crumb_panel_h4">您可以选择以下详细地区</h4>
                <div class="categ_crumb_panel_btn_box clearfix">
                    <span 
                        class="categ_crumb_panel_btn hand"
                        :class="{ categ_crumb_panel_btn_only: item.id == chooseCityId }"
                        v-for="item in cityList"
                        @click="chooseCity(item.id)"
                    >
                        {{ item.name }}
                    </span>
                </div>
            </div>
        </div>
        <!-- 您可以选择以下详细分类 -->
        <!-- <div class="categ_grey_box clearfix" v-if="secondNav.length > 0">
            <div class="categ_grey_head">您可以选择以下详细分类：</div>
            <div class="categ_grey_ul clearfix">
                <span 
                    :class="['categ_grey_btn hand', { 'categ_grey_btn_only': selectedSecondId == item.category_id }]"
                    v-for="item in secondNav"
                    @click="selectSecond(item)"
                >
                    {{ item.alias }}
                </span>
            </div>
        </div> -->
        <!-- 您可以选择以下详细分类 -->

        <!-- 供应信息列表 -->
        <div class=" clearfix">
            <div class="categ_1_index clearfix">
                <div class="categ_head_box clearfix_2">
                    <a class="categ_head_a" href="" title="">求购信息列表</a>
                </div>
                <div class="categ_table clearfix">
                    <div class="categ_table_head_box">
                        <div class="categ_table_td_1">产品图片</div>
                        <div class="categ_table_td_2">供求信息/公司</div>
                        <div class="categ_table_td_3">发布时间</div>
                        <div class="categ_table_td_4">地区</div>
                    </div>
                    <ShopNoData v-if="pageDataType2.length == 0" :pagetype="'list'"></ShopNoData>
                    <div class="categ_table_li" v-for="item in pageDataType2">
                        <NuxtLink
                            :to="getShopPathDetail1(item)"
                            class="categ_table_li_a"
                            :title="item.name"
                        >
                            <div class="categ_table_td_1">
                                <img class="categ_table_td_1_img" :src="item.imgurl" :alt="item.name">
                            </div>
                            <div class="search_table_td_2 ">
                                <div class="search_table_td_2_in clearfix">
                                    <div class="search_table_td_2_head dot1">
                                        {{ item.name }}
                                    </div>
                                    <div class="search_table_td_2_dot3 dot2" v-if="item.com!=''&&item.com!= null">
                                        {{item.com}}
                                    </div>
                                    <div class="search_table_td_2_dot2 dot2">
                                        {{ item.description }}
                                    </div>
                                </div>
                            </div>
                            <div class="categ_table_td_3">{{ getTime(item.created_at, 'year', 1) }}</div>
                            <div class="categ_table_td_4 dot1">{{ item.city_name }}</div>
                        </NuxtLink>
                    </div>
                </div>
            </div>
            <!-- 分页器 -->
            <div class="pagination" v-if="total">
                <el-pagination 
                    size="small" 
                    background layout="prev, pager, next" 
                    :total="total"
                    v-model:page-size="pageSize" 
                    prev-text="上一页" 
                    next-text="下一页" 
                    :current-page="pageNum"
                    @current-change="changePage" 
                />
            </div>
        </div>
        <ShopHotNews></ShopHotNews>
    </main>
    <!-- 页面底部 -->
    <HomeFoot></HomeFoot>
</template>

<script setup>
//1.页面必备方法 start ---------------------------------------->
import { ref, onMounted,watch } from 'vue'
import { ElMessage,ElPagination } from 'element-plus'

//分页
let pageNum = ref(1);
let pageSize = ref(10);
let total = ref(0);

let changePage = (value) => {
    console.log("当前页码", value);
    navigateTo(`/xiangcunshangcheng/${targetSegment}/${targetSegment2}/gongying/list-${value}.html`)
}
//1.页面必备方法 end ---------------------------------------->

//2.页面路径 start ---------------------------------------->
//2.1 获得页面数据id
const route = useRoute();
const router = useRouter()

//2.2 获得第一层面包屑地址
let articleId = 0; //把路径转换为数据id
const name = ref('') //当前频道名称
const targetLastRoute = getRoutePath(3);//返回第三层的路径id
const targetSegment = getRoutePath(2);//返回第二层的路径id
const targetRoute = getRoutePath(1);//返回第一层的路径id
const towgetRoute = targetRoute + "/" + targetSegment;
const alltargetRoute = targetRoute + "/" + targetSegment + "/" + targetLastRoute;
//通过导航路径反向查询导航id
const getRouteId = await requestDataPromise('/web/getWebsiteRoute', {
    method: 'GET',
    query: {
        'pinyin': towgetRoute,
    },
});
if(getRouteId.code == 200){
    articleId = getRouteId.data.category_id;
    name.value = getRouteId.data.alias;
}else{
    console.log("错误位置：获得页面路径")
}

//2.3 获得第二层面包屑地址
let articleId2 = 0; //把路径转换为数据id
const name2 = ref('') 
//const targetSegment2 = getRoutePath(3);//返回第二层的路径id
//通过导航路径反向查询导航id
const getRouteId2 = await requestDataPromise('/web/getWebsiteRoute', {
    method: 'GET',
    query: {
        'pinyin': alltargetRoute,
    },
});
if(getRouteId2.code == 200){
    articleId2 = getRouteId2.data.category_id;
    name2.value = getRouteId2.data.alias;
}else{
    console.log("错误位置：获得页面路径")
}

//2.4 获得子栏目列表
// const secondNav = ref([]);
const selectedSecondId = ref(route.query.catid);//当前选中了哪个子导航
// let getSecondNav = async () => {
//     const listData = await requestDataPromise('/web/getWebsiteModelCategory', {
//         method: 'GET',
//         query: {
//             'placeid': 1,
//             'pid': articleId,
//             'num': 50,
//         },
//     });
//     if (listData.code == 200) {
//         secondNav.value = listData.data
//     } else {
//         console.log("错误位置：获得子级栏目列表")
//     }
// }
// getSecondNav();

//2.5 获得cityid
const cityId = ref(route.query.cityid)
//2.页面路径 end ---------------------------------------->

//3.选择商品所在地 start ---------------------------------------->
//3.1 弹出下拉框
const if_categ_crumb_panel = ref(false)//当前商品所在地下拉板
const if_categ_crumb_panel_click = ref(false)//判断是否点击在下拉板内
const btn_if_categ_crumb_panel_fun = () => {//点击下拉btn
    if_categ_crumb_panel.value = !if_categ_crumb_panel.value
}
const categ_crumb_panel_btn_blur_fun = () => {//btn失去焦点事件
    setTimeout(() => {
        if (if_categ_crumb_panel_click.value == true) {
            //点击在下拉panel内
        } else {
            //没点击在下拉panel内
            if_categ_crumb_panel.value = false
        }
    }, 100);
}
//3.2 点击下拉panel
const categ_crumb_panel_focus_fun = () => {
    if_categ_crumb_panel_click.value = true
    if_categ_crumb_panel.value = true
}
//3.3 下拉panel失去焦点事件
const categ_crumb_panel_blur_fun = () => {
    if_categ_crumb_panel_click.value = false
    if_categ_crumb_panel.value = false
}

//3.4 获得详细地址列表
const cityName = ref('')
const cityList = ref([])
const chooseCityId = ref('')
let getCityList = async (id) => {
    const shengData =  await requestDataPromise('/web/selectWebsiteArea', {
        method: 'GET',
        query: {
            'pid': id,
        },
    });
    if(shengData.code==200){
        cityList.value = shengData.data;
        cityName.value = shengData.data[0].pid_name;
    }else{
        ElMessage.error(shengData.message)
    }
}
//3.5 初始化的时候先获取一下城市列表
if(cityId.value != undefined){
    getCityList(cityId.value);
}
//3.6 选择城市
const chooseCity = (id) => {
    chooseCityId.value = id;
    router.replace({
        query: { 
            ...route.query, 
            select: id
        }
    })
}
//3.选择商品所在地 end ---------------------------------------->

//4.搜索 start ---------------------------------------->
//4.1 选择一个子导航
const selectSecond = (item) => {
    //高亮显示当前选中的子导航
    selectedSecondId.value = item.category_id
    router.replace({
        query: { ...route.query, catid: item.category_id }
    })
}

//4.2 页面展示的数据
//const pageDataType1 = ref([]);//供应数据
const pageDataType2 = ref([]);//求购数据 此页面不需要求购数据

//4.3 发起搜索
const pageSearch = async () => {
    let params = {
        catid:"",//栏目id
        city_id:"",//城市id
        keyword:"",//搜索关键词 - 该页不需要
        page:1,
        pageSize:10,
        type_id:2//1:供应 2:求购
    }

    if(selectedSecondId.value == undefined){
        params.catid = articleId2
    }else{
        params.catid = parseFloat(selectedSecondId.value)
    }

    let routeCiteId = route.query.select;

    if(routeCiteId != undefined && routeCiteId != ''){
        params.city_id = parseFloat(routeCiteId)
    }else{
        if(cityId.value == undefined || cityId.value == '' || cityId.value == 'NaN'){
            //删除变量params中的city_id参数
            delete params.city_id
        }else{
            params.city_id = parseFloat(cityId.value)
        }
    }

    const pageData = await requestDataPromise('/web/getWebsiteshopList', {
        method: 'GET',
        query: params,
    });

    if (pageData.code == 200) {
        //pageDataType1.value = pageData.data.type1;
        pageDataType2.value = pageData.data.type2;
        total.value = pageData.data.type2_count;
    } else {
        console.log("错误位置：获得该页面数据失败！")
    }
    //开始请求数据
    console.log(params)
    console.log(pageData)
}
//页面初始化的时候调用一下搜索
pageSearch();

//4.4 每次路由一变化就重新请求数据
//4.4.1 监听cityid
watch(() => route.query.cityid, (newVal, oldVal) => {
    if(newVal != undefined){
        cityId.value = parseFloat(newVal)
        getCityList(newVal)
    }else{
        cityList.value = []
    }
    pageSearch()
})
//4.4.2 监听catid
watch(() => route.query.catid, (newVal, oldVal) => {
    pageSearch()
})
//4.4.3 监听select
//如果路由中存在select参数就忽略cityid
watch(() => route.query.select, (newVal, oldVal) => {
    if(newVal != undefined){
        pageSearch()
    }else{
        chooseCityId.value = '';
        pageSearch()
    }
})
//4.搜索 end ---------------------------------------->


//5.广告 start ---------------------------------------->
//获得所有广告
let adImg1 = ref({})
onMounted(async () => {
    const { $webUrl, $CwebUrl } = useNuxtApp();
    //从客户端启动广告
    //广告1
    let url = `${$webUrl}/web/getWebsiteAdvertisement?ad_tag=xcw_shoplist_0001`
    const responseAd1 = await fetch(url, {
        headers: {
            'Content-Type': 'application/json',
            'Userurl': $CwebUrl,
            'Origin': $CwebUrl
        }
    });
    const resultAd1 = await responseAd1.json();
    adImg1.value = resultAd1.data[0];
})
//5.广告 end ---------------------------------------->

//6.设置seo信息 start---------------------------------------->
//6.1 设置seo信息
const setData = await requestDataPromise('/web/getWebsiteCategoryHead', {
    method: 'GET',
    query: {
        'catid': articleId2
    },
});

if (setData.code == 200) {
    let seoTitle = setData.data.seo_title;
    let seoDescription = setData.data.seo_description;
    let seoKeywords = setData.data.seo_keywords;
    let seoSuffix = setData.data.suffix;
    let seoName = setData.data.website_name;

    useSeoMeta({
        title: seoTitle + "_求购_" + seoName + "_" + seoSuffix,
        meta: [
            { name: 'description', content: seoDescription + "_" + seoName + "_" + seoSuffix, tagPriority: 10 },
            { name: 'keywords', content: seoKeywords + "_" + seoName + "_" + seoSuffix, tagPriority: 10 },
            { name: 'viewport', content:"width=device-width,initial-scale=1,user-scalable=no"}

        ]
    });
} else {
    // console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
    // console.log("错误位置：设置列表页面SEO数据")
    // console.log("后端错误反馈：", setData.message)
    // console.log("SSR waring ---------- SSR waring ---------- SSR waring ---------->")
}
//6.设置seo信息 end---------------------------------------->
</script>


<style lang="less" scoped>
@import '@/assets/css/shop/list.less';
</style>