<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" />
				<img v-if="state.showStyle" src="../../static/img/icon_search1.jpg" alt="" @click="changeIcon"
				     style="width: 1.8rem;height: 1.6rem;margin-right: 3px">
				<img v-if="!state.showStyle" src="../../static/img/icon_search2.jpg" alt="" @click="changeIcon"
				     style="width: 1.8rem;height: 1.6rem;margin-right: 3px">
			</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;" v-if="state.showStyle">
				<van-col  span="12"  v-for="item in state.good.list" style="margin-bottom: 25rpx;align-self: baseline">
					<ShopCard :item="item"></ShopCard>
				</van-col>
			</van-row>
			<van-grid :center="false" :column-num="1" :gutter="7" v-else style="border-radius: 50%">
				<van-grid-item  class="text-left" v-for="(item, index) in state.good.list" :key="index"
						   >
					<van-row style="">
						<van-col span="7" style="position: relative" @click="goto(`/pages/good/detail?skuId=${item.skuId}&spuId=${item.spuId}`)">
							<van-image class="self_center" width="6rem" height="6rem" lazy-load
								     :src="item.mainImg" />
						</van-col>
						<van-col span="16">
							<view style="padding: 15rpx;background: #ffffff" @click="goto(`/pages/good/detail?skuId=${item.skuId}&spuId=${item.spuId}`)">
								<text class="text-s ellipsis line_over2" style="text-align: left;background: #ffffff;line-height: 36rpx">
									{{ item.title }}
								</text>
							</view>
							<van-row style="padding-top: 50rpx">
								<van-col span="24">
									<view style="display: flex;justify-content: space-between;align-items: center">
										<view style="display: flex;background: #ffffff;padding: 15rpx;margin-top: 10rpx" class="text01">
											<view  class="text-orange text-ss">￥
												<text class="text-bold text-l">{{ item.salePrice }}</text>
											</view>
											<view  class="text-ss" style="margin-left: 16rpx">
												<text class="text-gray text-ss line-through">￥{{ item.productPrice }}</text>
											</view>
										</view>
										<view @click="check(item)">
											<img  src="../../static/img/car_search.png"
												style="width: 1.8rem;margin-right: 6rpx" alt="">
										</view>
									</view>
								</van-col>
							</van-row>
						</van-col>
					</van-row>
				</van-grid-item>
			</van-grid>
		</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({
	  temPP:null,
        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) {
            state.temPP=JSON.parse(JSON.stringify(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(() => {
                window._wx.miniProgram.redirectTo({url: "/pages/login/login"})
            });
        }
    }
    function changeTab(e) {

        state.good.list = []
        state.good.page = 0
        if (e.name == 0) {
            state.params.sortType=0
            state.sortType=0
		delete state.params['sort']
        }
        if (e.name == 1) {
            state.params.sortType=3
            state.sortType=3
            if (state.temPP) {
                if(state.temPP.sortType==25){
                    state.sortType=25
                    state.params.sortType=25
		    }
                if(state.temPP.sortType==20){
                    state.sortType=21
                    state.params.sortType=21
                }
            }
            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() {
        if (state.temPP&&state.active==0) {
            if(state.temPP.sortType==25){
                state.sortType=0
                state.params.sortType=0
            }
            if(state.temPP.sortType==20){
                state.sortType=20
                state.params.sortType=20
            }
        }
        // 获取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>
