<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="#ff6600" line-width="206rpx"
				    title-active-color="#ff6600" @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-grid :center="false" :column-num="2" :gutter="3" v-if="state.showStyle">
				<van-grid-item style="border-radius: 4px" class="text-left" v-for="(item, index) in state.good.list" :key="item.skuId"
						   @click="goto(`/pages/good/detail?skuId=${item.skuId}&spuId=${item.spuId}`)">
					<van-image class="self_center"  width="30vw" height="30vw" lazy-load :src="item.mainImg" />
                    <view :class="[item.zoneIcon||item.isVideoIcon||item.coTip==1?'mg-t-30-m':'']">
				  <!--活动角标-->
				  <div class="sign" v-if="item.subScriptImgUrl">
					  <img  :src="item.subScriptImgUrl" alt="" />
					  <div class="discount"  style="color: rgba(247, 103, 67, 1)">{{item.discount}}</div>
				  </div>
				  <span v-if="item.coTip==1" style="color: #ff5500;border: 1px solid #ff5500;font-size: 12px;margin-right: 2px;font-weight: bold;padding: 1px">热销</span>
				  <span v-if="item.leftDownIcons&&item.leftDownIcons.length>0">
					  <span v-for="item1 in item.leftDownIcons " style="margin-right: 3px" >
					<van-image  width="60rpx" height="32rpx" :src="item1" />
					  </span>
		    </span>
				  <van-image v-if="item.isVideoIcon" class="mg-l-5" width="32rpx" height="32rpx" src="/static/img/play.png" />
                    </view>
					<text class="text-s ellipsis line_over2 pd-t-10" style="width: 315rpx;margin-bottom:6px;">
						{{ item.title }}
					</text>
					<text class="text-ss">{{ item.size }}</text>
					<text class="text-gray text-ss"></text>
					<!--未开启设计师模式-->
					<div v-if="item.salePrice">
						<view v-if="!item.actPrice" class="text-gray text-ss line-through">零售价￥{{ item.productPrice }}</view>
						<view v-if="item.actPrice">
							<view class="text-gray text-ss">零售价￥{{ item.productPrice }}</view>
							<view class="text-gray text-ss line-through">优惠价￥{{ item.salePrice }}</view>
							<view class="text-orange text-ss">活动价￥
								<text class="text-bold text-l">{{ item.actPrice }}</text>
							</view>
						</view>
						<view v-else class="text-orange text-ss">优惠价￥
							<text class="text-bold text-l">{{ item.salePrice }}</text>
						</view>
					</div>
					<div v-else class="text-orange" style="font-size: 13px;margin-top: 3px">
						<view v-if="item.actPrice">
							<view class="text-gray text-ss line-through">零售价￥{{ item.productPrice }}</view>
							<view class="text-orange text-ss">活动价￥
								<text class="text-bold text-l">{{ item.actPrice }}</text>
							</view>
						</view>
						<text v-else class="text-bold text-ss" >零售价￥{{ item.productPrice }}</text>
					</div>
				</van-grid-item>
			</van-grid>
			<van-grid :center="false" :column-num="1" :gutter="7" v-else>
				<van-grid-item class="text-left" v-for="(item, index) in state.good.list" :key="index"
						   @click="goto(`/pages/good/detail?skuId=${item.skuId}&spuId=${item.spuId}`)">
					<van-row>
						<van-col span="7" style="position: relative">
							<van-image class="self_center" width="6rem" height="6rem" lazy-load
								     :src="item.mainImg" />
							<!--活动角标-->
							<div class="sign" style="top: 0" v-if="item.subScriptImgUrl">
								<img  :src="item.subScriptImgUrl" alt="" />
								<div class="discount"  style="color: rgba(247, 103, 67, 1)">{{item.discount}}</div>
							</div>
							<view style="position: absolute;left: 0;bottom: 0">
								<span v-if="item.coTip==1" style="color: #ff5500;border: 1px solid #ff5500;font-size: 12px;margin-right: 2px;font-weight: bold;padding: 1px">热销</span>
								<van-image v-if="item.zoneIcon" width="60rpx" lazy-load :src="item.zoneIcon" />
								<van-image v-if="item.isVideoIcon" class="pd-l-5" width="32rpx" height="32rpx" src="/static/img/play.png" />
							</view>
						</van-col>
						<van-col span="16" offset="1">

							<p class="text-s ellipsis line_over2 pd-t-10" >
								{{ item.title }}
							</p>
							<div style="line-height: 1.2rem">
								<p class="text-ss">{{ item.size }}</p>
								<p class="text-gray text-ss"></p>
								<div v-if="item.salePrice">
									<view v-if="item.actPrice">
										<p  class="text-gray text-ss">零售价￥{{ item.productPrice }}</p>
										<p  class="text-gray text-ss line-through">优惠价￥{{ item.salePrice }}</p>
										<p class="text-orange text-ss">
											<img @click.stop="check(item)" src="../../static/img/car_search.png"
											     style="float: right;width: 1.8rem;margin-top: -5px" alt="">
											活动价￥
											<text class="text-bold text-l">{{ item.actPrice }}</text>
										</p>
									</view>
									<view v-else>
										<p  class="text-gray text-ss line-through">零售价￥{{ item.productPrice }}</p>
										<p class="text-orange text-ss">
											<img @click.stop="check(item)" src="../../static/img/car_search.png"
											     style="float: right;width: 1.8rem;margin-top: -5px" alt="">
											优惠价￥
											<text class="text-bold text-l">{{ item.salePrice }}</text>
										</p>
									</view>
								</div>
								<div v-else>
									<view v-if="item.actPrice">
										<view class="text-gray text-ss line-through">零售价￥{{ item.productPrice }}</view>
										<p class="text-orange text-ss text-bold" style="font-size: 14px;margin-top: 6px" >
											活动价￥{{ item.actPrice }}
											<img @click.stop="check(item)" src="../../static/img/car_search.png"
											     style="float: right;width: 1.8rem;margin-top: -5px" alt="">
										</p>
									</view>
									<p class="text-orange text-ss text-bold" style="font-size: 14px;margin-top: 6px" v-else>
										零售价￥{{ item.productPrice }}
										<img @click.stop="check(item)" src="../../static/img/car_search.png"
										     style="float: right;width: 1.8rem;margin-top: -5px" alt="">
									</p>
								</div>
							</div>
						</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 { 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>
