<template>
	<view class="text-center pd-b-px-55">
		<van-sticky>
			<div style="display: flex;align-items:center;background: #ffffff">
				<van-icon size="1.5rem" name="arrow-left" style="color: #757575;" @click="goBack" />
				<van-search v-model="state.keyword" style="flex: 1" placeholder="请输入搜索关键词" @click.stop="topSearch" />
			</div>
			<van-tabs v-model:active="state.active" color="#EBA926" line-width="206rpx"
				    title-active-color="#EBA926" @click-tab="changeTab">
				<van-tab title="默认">
				</van-tab>
				<van-tab>
                    <template #title>
                        价格 <van-icon v-if="state.params.sort!==undefined" :class="state.params.sort==0?'down_price':'up_price'" name="play" />
                    </template>
				</van-tab>
				<van-tab title="筛选">
				</van-tab>
			</van-tabs>
		</van-sticky>

		<div style="margin-top: .2rem"></div>
		<van-list :loading="state.good.loading" :finished="state.good.finished" finished-text="没有更多了"
			    @load="onGoodLoad">
			<van-row gutter="12" style="margin: 20rpx 20rpx;">
				<van-col  span="12"  v-for="item in state.good.list" style="margin-bottom: 25rpx">
					<ShopCard :item="item"></ShopCard>
				</van-col>
			</van-row>
		</van-list>
		<view v-if="state.good.fail" class="text-ss text-gray pd-50" @click="failReset">请求失败，点击重试
			<van-icon name="replay" />
		</view>
		<to-top :showNav="true"/>
	</view>
</template>

<script setup lang="ts">
    import ShopCard from '@/components/ShopCard.vue';
    import { Dialog } from "vant";
    import {Toast} from 'vant';
    import api from "@/api";
    import {onMounted, reactive, getCurrentInstance} from 'vue';
    import toTop from '@/components/tool/toTop.vue';
    import { onPageScroll } from '@dcloudio/uni-app'
    import { PageUtils } from '@/utils/utils'
    onPageScroll(e => { }) // uniapp的Bug，这句话不要去掉，否则to-top不生效

    const state = reactive({
        skuId: '',
        spuId: '',
        params: {},
        sortType:0,
        showStyle: true,
        active: 0,
        keyword: "",
        loading: {
            cartAdd: false,
            productFav: false,
            brandFav: false,
            share: false
        },
        banner: {
            top: [] as any,
            afterTop: [] as any,
            afterTap: [] as any
        },
        good: {
            loading: false,
            finished: false,
            fail: false,
            page: 0,
            list: [] as any
        }
    })
    onMounted(() => {
        state.showStyle = uni.getStorageSync('searchCard') === ''? true:uni.getStorageSync('searchCard')
        let search = getCurrentInstance().ctx.$page.options || ''
        if (search) {
            // 价格搜索
            if (search['money']) {
                let minSalePrice = ''
                let maxSalePrice = ''
                let money = search['money']
                if (money.indexOf('元以下') > -1) {
                    maxSalePrice = money.replace('元以下', '')
                } else if (money.indexOf('以上') > -1) {
                    minSalePrice = money.replace('以上', '')
                } else {
                    let str = money.replace('元', '')
                    minSalePrice = str.split('-')[0]
                    maxSalePrice = str.split('-')[1]
                }
                state.params['minSalePrice'] = minSalePrice
                state.params['maxSalePrice'] = maxSalePrice
                return
            }
            if (search['search']) {
                state.keyword = decodeURIComponent(search['search'])
            }
            if (search['actId']) {
                state.params['actId'] = search['actId']
                state.keyword=''
            }
            let key = Object.keys(search)
            state.params[key] = search[key]
        }
        state.params = search
        // console.log(getUrl(window.location.href));
    });

    function goto(url: any) {
        url && uni.navigateTo({url})
    }
    function cartAdd(data) {
        if (state.loading.cartAdd) return
        state.loading.cartAdd = true
        api.cartAdd({
            skuId: data.skuId,
            link: uni.getStorageSync('subdomain'),
            productQty: 1, // B端去除起订量限制 skuData.value.moq
        }).then(() => {
            Toast.success('加入购物车')
        }).finally(() => {
            state.loading.cartAdd = false
        })
    }
    function check(item) {
        const { token } = uni.getStorageSync("user") || {};
        if (token) {
            cartAdd(item)
        } else {
            Dialog.confirm({
                message: '您尚未登录，请前往登录',
                title: "提示",
                cancelButtonText: '取消'
            }).then(() => {
                uni.navigateTo({
                    url: '/pages/login/login'
                })
            });
        }
    }
    function changeTab(e) {
        state.good.list = []
        state.good.page = 0
        if (e.name == 0) {
            state.sortType=0
		delete state.params['sort']
        }
        if (e.name == 1) {
            state.sortType=3
            state.params['sort'] == 1 ? state.params['sort'] = 0 : state.params['sort'] = 1
        }
        onGoodLoad()
        if (e.name == 2) {
            if(localStorage.getItem('isClassify')){
                history.back()
		}else {
                uni.navigateTo({
                    url:'/pages/classify/index?good=1'
                });
		}
            localStorage.removeItem('isClassify');
        }
    }

    function changeIcon() {
        state.showStyle = !state.showStyle
        uni.setStorageSync('searchCard', state.showStyle)
    }

    function topSearch() {
        uni.navigateTo({
            url: "/pages/topSearch/index",
        });
    }

    function getUrl(url) {
        const q = {};
        url.replace(/([^?&=]+)=([^&]+)/g, (_, k, v) => q[k] = v);
        return q;
    }

    function onGoodLoad() {
        // 获取link参数
        // url.indexOf('localhost') == -1 ? link :
        //  let url = window.location.href
        // let link = url.substring((url.indexOf("/") + 2), url.indexOf("."))
        if (state.good.loading || state.good.fail) return
        state.good.loading = true
        ++state.good.page
        api.productList({
            sortType: state.sortType,
            ...state.params,
            pageNum: state.good.page,
            pageSize: 20,
            link:uni.getStorageSync("subdomain")?uni.getStorageSync("subdomain"):'alisa'
        }).then((data: any) => {
            if (!data||!data.hasNextPage){
                state.good.finished = true
            }
            state.good.list.push(...data.list)
        })
            .catch(() => {
                state.good.fail = true
            })
            .finally(() => {
                state.good.loading = false
            })
    }

    function failReset() {
        state.good.page -= 1
        state.good.finished = false
        state.good.fail = false
        onGoodLoad()
    }

    function goBack() {
        PageUtils.goBack()
    }
</script>

<style lang="scss" scoped>
	.sign {
		position: absolute;
		right: 1.8vw;
		top: 2vw;
		width: 40px;
		text-align: center;

		img {
			width: 40px;
			margin-bottom: -18px;
		}

		.discount {
			font-family: MiSans-Semibold;
			text-shadow: 0.5px 0.5px #ddd;
			color: #A532E0;
			font-weight: 1000;
			font-size: 12px;
		}
	}
	:root {
		--van-sidebar-selected-border-height: 30px;
	}

	.search_bar {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		width: 100vw;
		z-index: 5;
	}

	.banner_top {
		height: 43.5vw;
	}

	.banner_afterTop,
	.banner_afterTap {
		height: 20vw;
	}

	.block_title {
		margin: 40 rpx auto 25 rpx auto;
		width: 60vw;
	}
    .down_price {
        transition: all ease-in-out .2s;
        transform: rotate(90deg);
    }
    .up_price {
        transition: all ease-in-out .2s;
        transform: rotate(-90deg);
    }
</style>
