<template>
    <view class="bg-gray-100 min-h-[100vh]" :style="themeColor()">
        <view class="fixed left-0 right-0 top-0 product-warp bg-[#fff]">
            <view class="py-[14rpx] flex items-center justify-between px-[20rpx]">
                <view class="flex-1 search-input mr-[20rpx]">
                    <text @click.stop="searchTypeFn('all')" class="nc-iconfont nc-icon-sousuo-duanV6xx1 btn"></text>
                    <input class="input" maxlength="50" type="text" v-model="goods_name" placeholder="请搜索您想要的商品"
                        placeholderClass="text-[var(--text-color-light9)] text-[24rpx]" confirm-type="search"
                        @confirm="searchTypeFn('all')">
                    <text v-if="goods_name" class="nc-iconfont nc-icon-cuohaoV6xx1 clear"
                        @click="goods_name = ''"></text>
                </view>
                <view
                    :class="['iconfont text-[32rpx] text-[#333] -mb-[2rpx]', listType ? 'icona-yingyongzhongxinV6xx-32' : 'icona-yingyongliebiaoV6xx-32']"
                    @click="listIconBtn"></view>
            </view>
            <view class="flex justify-between tems-center h-[88rpx] px-[30rpx]">
                <view class=" flex items-center justify-between text-[26rpx] flex-1">
                    <text class="text-[#333]" :class="{ 'text-[var(--primary-color)] font-500': searchType == 'all' }"
                        @click="searchTypeFn('all')">综合排序</text>
                    <!-- <view class="flex items-center text-[#333]"
                        :class="{ 'text-[var(--primary-color)] font-500': searchType == 'stock' }"
                        @click="searchTypeFn('stock')">
                        <text class="mr-[4rpx]">库存</text>
                        <text v-if="searchType === 'stock' && currentSortOrder === 'Asc'"
                            class="text-[16rpx] nc-iconfont nc-icon-a-xiangshangV6xx1"
                            :class="{ 'text-[var(--primary-color)]': searchType == 'stock' }"></text>
                        <text v-else-if="searchType === 'stock'"
                            class="text-[16rpx] nc-iconfont nc-icon-a-xiangxiaV6xx1"
                            :class="{ 'text-[var(--primary-color)]': searchType == 'stock' }"></text>
                    </view> -->
                    <view class="flex items-center"
                        :class="{ 'text-[var(--primary-color)] font-500': searchType == 'isSelf' }"
                        @click="searchTypeFn('isSelf')">
                        <text class="mr-[8rpx]">{{ cusType == 'all' ? '是否自营' : cusType == 1 ? '自营' : '非自营' }}</text>
                    </view>
                    <view class="flex items-center text-[#333]"
                        :class="{ 'text-[var(--primary-color)] font-500': searchType == 'price' }"
                        @click="searchTypeFn('price')">
                        <text class="mr-[4rpx]">价格</text>
                        <text v-if="searchType === 'price' && currentSortOrder === 'Asc'"
                            class="text-[16rpx] nc-iconfont nc-icon-a-xiangshangV6xx1"
                            :class="{ 'text-[var(--primary-color)]': searchType == 'price' }"></text>
                        <text v-else-if="searchType === 'price'"
                            class="text-[16rpx] nc-iconfont nc-icon-a-xiangxiaV6xx1"
                            :class="{ 'text-[var(--primary-color)]': searchType == 'price' }"></text>
                    </view>
                    <view class="flex items-center"
                        :class="{ 'text-[var(--primary-color)] font-500': searchType == 'label', 'text-[#333]': searchType != 'label' }"
                        @click="searchTypeFn('label')">
                        <text class="mr-[8rpx]">筛选</text>
                        <text class="iconfont font-500 icona-shaixuanV6xx-34 -mb-[4rpx] !text-[26rpx]"></text>
                    </view>
                </view>
            </view>
        </view>
        <u-popup :show="labelPopup" mode="top" @close="labelPopup = false">
            <view @touchmove.prevent.stop class="h-[50vh] overflow-auto mt-[30rpx]">
                <view v-for="(item, index) in categoryList" :key="index">
                    <view class="text-[28rpx] px-[20rpx] mt-[10rpx]">{{ item.label }}</view>
                    <view class="flex flex-wrap pl-[20rpx] pt-[20rpx]">
                        <text @click="loadCategory(item.id, '')" :key="item.id"
                            :class="{ 'label-select': mediumCategoryId == '' && item.id == topCategoryId }"
                            class="truncate text-[#333] border-[2rpx] border-solid border-transparent w-[162rpx] h-[56rpx] flex items-center justify-center mr-[20rpx] mb-[30rpx] box-border bg-[var(--temp-bg)] rounded-[50rpx] text-[24rpx]">
                            全部
                        </text>
                        <text @click="loadCategory(item.id, subItem.id)" v-for="(subItem, index) in item.children"
                            :key="subItem.id" :class="{ 'label-select': mediumCategoryId == subItem.id }"
                            class="truncate text-[#333] border-[2rpx] border-solid border-transparent w-[162rpx] h-[56rpx] flex items-center justify-center mr-[20rpx] mb-[30rpx] box-border bg-[var(--temp-bg)] rounded-[50rpx] text-[24rpx]">
                            {{ subItem.label }}
                        </text>
                    </view>
                </view>
            </view>
        </u-popup>

        <u-popup :show="cusPopup" mode="top" @close="cusPopup = false">
            <view @touchmove.prevent.stop class="h-[50vh] overflow-auto mt-[30rpx]">
                <view class="flex flex-wrap pl-[20rpx] pt-[20rpx]">
                    <text @click="onCub('all')" :class="{ 'label-select': cusType == 'all' }"
                        class="truncate text-[#333] border-[2rpx] border-solid border-transparent w-[162rpx] h-[56rpx] flex items-center justify-center mr-[20rpx] mb-[30rpx] box-border bg-[var(--temp-bg)] rounded-[50rpx] text-[24rpx]">
                        全部
                    </text>
                    <text @click="onCub(1)" :class="{ 'label-select': cusType == 1 }"
                        class="truncate text-[#333] border-[2rpx] border-solid border-transparent w-[162rpx] h-[56rpx] flex items-center justify-center mr-[20rpx] mb-[30rpx] box-border bg-[var(--temp-bg)] rounded-[50rpx] text-[24rpx]">
                        自营
                    </text>
                    <text @click="onCub(0)" :class="{ 'label-select': cusType == 0 }"
                        class="truncate text-[#333] border-[2rpx] border-solid border-transparent w-[162rpx] h-[56rpx] flex items-center justify-center mr-[20rpx] mb-[30rpx] box-border bg-[var(--temp-bg)] rounded-[50rpx] text-[24rpx]">
                        非自营
                    </text>
                </view>
            </view>
        </u-popup>

        <mescroll-body ref="mescrollRef" top="176rpx" bottom="60px" @init="mescrollInit" :down="{ use: false }"
            @up="getAllAppListFn">
            <view v-if="goodsList.length" :class="['sidebar-margin', !listType ? 'biserial-goods-list' : '']">
                <template v-if="listType">
                    <view v-for="(item, index) in goodsList" :key="index"
                        class="bg-white flex px-[20rpx] py-[24rpx] rounded-[var(--rounded-small)] overflow-hidden top-mar"
                        :class="{ 'mb-[20rpx]': (index + 1) == goodsList.length }" @click="toDetail(item.id)">
                        <image v-if="item.productImage" class="w-[190rpx] h-[190rpx] rounded-[var(--rounded-mid)]"
                            :src="img(item.productImage)" :mode="'aspectFill'"
                            @error="item.productImage = 'https://v6.site.niucloud.com/static/resource/images/diy/shop_default.jpg'" />
                        <image v-else class="w-[190rpx] h-[190rpx] rounded-[var(--rounded-mid)]"
                            :src="img('static/resource/images/diy/shop_default.jpg')" :mode="'aspectFill'" />

                        <view class="flex-1 flex flex-col ml-[20rpx] py-[6rpx]">
                            <view class="text-[28rpx] text-[#333] leading-[40rpx] multi-hidden mb-[10rpx]"></view>
                            <view class="text-[24rpx] text-[#999] leading-[30rpx] using-hidden mb-[8rrpx]">
                                <view class="brand-tag"> {{ item.isSelf == 1 ? '自营商品' : '非自营' }} </view>
                                {{ item.itemName }}
                            </view>
                            <view class="flex flex-wrap">
                                <view class="base-tag" :style="diyGoods.baseTagStyle()">
                                    {{ item.brandName || '' }}
                                </view>
                                <view class="base-tag" :style="diyGoods.baseTagStyle()">
                                    {{ item.bottomCategoryName || '' }}
                                </view>
                                <view class="base-tag" :style="diyGoods.baseTagStyle()" v-if="item.isCustomize == 1">
                                    可定制
                                </view>
                            </view>
                            <view class="mt-auto flex justify-between items-baseline">
                                <view class="flex items-baseline mt-[20rpx]">
                                    <view class="text-[var(--price-text-color)] price-font flex items-baseline">
                                        <text class="text-[24rpx] font-500 mr-[4rpx]">￥</text>
                                        <text class="text-[40rpx] font-500">{{
                                            diyGoods.goodsPrice(item).toFixed(2).split('.')[0] }}</text>
                                        <text class="text-[24rpx] font-500">.{{
                                            diyGoods.goodsPrice(item).toFixed(2).split('.')[1] }}</text>
                                    </view>
                                    <view class="ml-[12rpx] text-[var(--text-color-light9)] text-[22rpx]"
                                        style="text-decoration: line-through">
                                        ￥{{ item.marketPrice }}
                                    </view>
                                </view>
                                <text class="text-[22rpx] mt-[20rpx] text-[var(--text-color-light9)]">
                                    起订{{ item.minOrderQuantity || 1 }}{{ item.unitName || '件' }}
                                </text>
                            </view>
                        </view>
                    </view>
                </template>
                <template v-else>
                    <view>
                        <template v-for="(item, index) in goodsList">
                            <view v-if="(index % 2) == 0"
                                class="flex flex-col bg-[#fff] box-border rounded-[var(--rounded-mid)] overflow-hidden mt-[var(--top-m)]"
                                @click="toDetail(item.id)">
                                <image v-if="item.productImage"
                                    class="w-[100%] h-[344rpx] rounded-tl-[var(--rounded-mid)] rounded-tr-[var(--rounded-mid)]"
                                    :src="img(item.productImage)" :mode="'aspectFill'"
                                    @error="item.productImage = 'static/resource/images/diy/shop_default.jpg'" />
                                <image v-else
                                    class="w-[100%] h-[344rpx] rounded-tl-[var(--rounded-mid)] rounded-tr-[var(--rounded-mid)]"
                                    :src="img('https://v6.site.niucloud.com/static/resource/images/diy/shop_default.jpg')"
                                    :mode="'aspectFill'" />

                                <view class="px-[20rpx] flex-1 pt-[16rpx] pb-[24rpx] flex flex-col justify-between">
                                    <view class="text-[24rpx] text-[#999] leading-[30rpx] using-hidden my-[5rpx]">
                                        <view class="brand-tag"> {{ item.isSelf == 1 ? '自营商品' : '非自营' }} </view>
                                        {{ item.itemName }}
                                    </view>
                                    <view class="flex flex-wrap">
                                        <view class="base-tag" :style="diyGoods.baseTagStyle()">{{ item.brandName || ''
                                        }}</view>
                                        <view class="base-tag" :style="diyGoods.baseTagStyle()">{{
                                            item.bottomCategoryName || '' }}</view>
                                        <view v-if="item.isCustomize == 1" class="base-tag"
                                            :style="diyGoods.baseTagStyle()">可定制</view>
                                    </view>
                                    <view class="flex justify-between flex-wrap items-end">
                                        <view class="flex items-baseline mt-[20rpx]">
                                            <view class="text-[var(--price-text-color)] price-font flex items-baseline">
                                                <text class="text-[24rpx] font-500">￥</text>
                                                <text class="text-[40rpx] font-500">{{
                                                    diyGoods.goodsPrice(item).toFixed(2).split('.')[0] }}</text>
                                                <text class="text-[24rpx] font-500">.{{
                                                    diyGoods.goodsPrice(item).toFixed(2).split('.')[1] }}</text>
                                            </view>
                                            <view class="ml-[12rpx] text-[var(--text-color-light9)] text-[22rpx]"
                                                style="text-decoration: line-through">
                                                ￥{{ item.marketPrice }}
                                            </view>
                                        </view>
                                        <text class="text-[22rpx] text-[var(--text-color-light9)] mt-[20rpx]"> 起订{{
                                            item.minOrderQuantity || 1 }}{{ item.unitName || '件' }}</text>
                                    </view>
                                </view>
                            </view>
                        </template>
                    </view>
                    <view>
                        <template v-for="(item, index) in goodsList">
                            <view v-if="(index % 2) == 1"
                                class="flex flex-col bg-[#fff] box-border rounded-[var(--rounded-mid)] overflow-hidden mt-[var(--top-m)]"
                                @click="toDetail(item.id)">
                                <image v-if="item.productImage"
                                    class="w-[100%] h-[344rpx] rounded-tl-[var(--rounded-mid)] rounded-tr-[var(--rounded-mid)]"
                                    :src="img(item.productImage)" :mode="'aspectFill'"
                                    @error="item.productImage = 'static/resource/images/diy/shop_default.jpg'" />
                                <image v-else
                                    class="w-[100%] h-[344rpx] rounded-tl-[var(--rounded-mid)] rounded-tr-[var(--rounded-mid)]"
                                    :src="img('static/resource/images/diy/shop_default.jpg')" :mode="'aspectFill'" />
                                <view class="px-[20rpx] flex-1 pt-[16rpx] pb-[24rpx] flex flex-col justify-between">
                                    <view class="text-[#303133] leading-[40rpx] text-[28rpx] multi-hidden"></view>
                                    <view class="text-[24rpx] text-[#999] leading-[30rpx] using-hidden my-[5rpx]">
                                        <view class="brand-tag"> {{ item.isSelf == 1 ? '自营商品' : '非自营' }} </view>
                                        {{ item.itemName }}
                                    </view>
                                    <view class="flex flex-wrap">
                                        <view class="base-tag" :style="diyGoods.baseTagStyle()">{{ item.brandName || ''
                                        }}</view>
                                        <view class="base-tag" :style="diyGoods.baseTagStyle()">{{
                                            item.bottomCategoryName || '' }}</view>
                                        <view v-if="item.isCustomize == 1" class="base-tag"
                                            :style="diyGoods.baseTagStyle()">可定制</view>
                                    </view>
                                    <view class="flex justify-between flex-wrap items-baseline">
                                        <view class="flex items-baseline mt-[20rpx]">
                                            <view class="text-[var(--price-text-color)] price-font flex items-baseline">
                                                <text class="text-[24rpx] font-500">￥</text>
                                                <text class="text-[40rpx] font-500">{{
                                                    diyGoods.goodsPrice(item).toFixed(2).split('.')[0] }}</text>
                                                <text class="text-[24rpx] font-500">.{{
                                                    diyGoods.goodsPrice(item).toFixed(2).split('.')[1] }}</text>
                                            </view>
                                            <view class="ml-[12rpx] text-[var(--text-color-light9)] text-[22rpx]"
                                                style="text-decoration: line-through">
                                                ￥{{ item.marketPrice }}
                                            </view>
                                        </view>
                                        <text class="mt-[20rpx] text-[22rpx] text-[var(--text-color-light9)]">起订{{
                                            item.minOrderQuantity || 1 }}{{ item.unitName || '件' }}</text>
                                    </view>
                                </view>
                            </view>
                        </template>
                    </view>
                </template>
            </view>
            <mescroll-empty v-if="!goodsList.length && loading" :option="{ tip: '暂无商品', btnText: '去逛逛' }"
                @emptyclick="redirect({ url: '/addon/shop/pages/index', mode: 'reLaunch' })"></mescroll-empty>
        </mescroll-body>

        <tabbar />
    </view>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted } from 'vue'
import { t } from '@/locale'
import { redirect, img, handleOnloadParams } from '@/utils/common';
import { getGoodsCategoryTree, getGoodsComponents } from '@/addon/shop/api/goods';
import MescrollBody from '@/components/mescroll/mescroll-body/mescroll-body.vue';
import MescrollEmpty from '@/components/mescroll/mescroll-empty/mescroll-empty.vue';
import useMescroll from '@/components/mescroll/hooks/useMescroll.js';
import { onLoad, onPageScroll, onReachBottom } from '@dcloudio/uni-app';
import { useGoods } from '@/addon/shop/hooks/useGoods'

const { mescrollInit, downCallback, getMescroll } = useMescroll(onPageScroll, onReachBottom);
const diyGoods = useGoods();
const categoryList = ref<any>([]);
const goodsList = ref<Array<any>>([]);
const currGoodsCategory = ref<number | string>('');
const mescrollRef = ref(null);
const loading = ref<boolean>(false);
const topCategoryId = ref<any>(null);
const mediumCategoryId = ref<any>(null);
// 标签
const labelPopup = ref(false);
const goods_name = ref("");
const searchType = ref('all');
//列表类型
const listType = ref(true)
//定制
const cusPopup = ref(false);
const cusType = ref<any>('all');

// 新增：用于存储当前排序方式（Asc / Desc）
const currentSortOrder = ref('Asc');

onLoad(async (option: any) => {
    // #ifdef MP-WEIXIN
    // 处理小程序场景值参数
    option = handleOnloadParams(option);
    // #endif
    if (option.topCategoryId) topCategoryId.value = option.topCategoryId;
    if (option.mediumCategoryId) mediumCategoryId.value = option.mediumCategoryId;
    if (option.goods_name) goods_name.value = option.goods_name;
    currGoodsCategory.value = option.curr_goods_category || ''
    goods_name.value = option.goods_name ? decodeURIComponent(option.goods_name) : ''
    await getGoodsCategoryTree({ platform: 0 }).then((res: any) => {
        const initData = { label: "全部", id: '' };
        categoryList.value.push(initData);
        categoryList.value = categoryList.value.concat(res.data);
    });
})

interface mescrollStructure {
    num: number,
    size: number,
    endSuccess: Function,
    [propName: string]: any
}

const getAllAppListFn = (mescroll: mescrollStructure) => {
    loading.value = false;

    let sortField = '';
    let sortOrder = '';

    if (searchType.value === 'all') {
        sortField = '1'; // 智能排序
        sortOrder = 'Asc';
    } else if (searchType.value === 'stock') {
        sortField = '2'; // 库存匹配
        sortOrder = currentSortOrder.value;
    } else if (searchType.value === 'price') {
        sortField = '3'; // 价格排序
        sortOrder = currentSortOrder.value;
    }

    let data: object = {
        topCategoryId: topCategoryId.value,
        mediumCategoryId: mediumCategoryId.value,
        pageNum: mescroll.num,
        pageSize: mescroll.size,
        searchKeyword: goods_name.value,
        sortField,
        isSelf: cusType.value == 'all' ? '' : cusType.value,
        sortOrder
    };

    getGoodsComponents(data).then((res: any) => {
        let newArr = (res.rows as Array<Object>);
        console.log(newArr, 'newArrnewArrnewArrnewArr')
        //设置列表数据
        if (Number(mescroll.num) === 1) {
            goodsList.value = []; //如果是第一页需手动制空列表
        }
        goodsList.value = goodsList.value.concat(newArr);
        mescroll.endSuccess(newArr.length);
        loading.value = true;
    }).catch(() => {
        loading.value = true;
        mescroll.endErr(); // 请求失败, 结束加载
    })
}

onPageScroll((e) => {
    // uni.$emit('scroll')
})

const loadCategory = (id: string, cid: any) => {
    if (cid == '') {
        topCategoryId.value = id;
        mediumCategoryId.value = '';
    } else {
        topCategoryId.value = id;
        mediumCategoryId.value = cid;
    }
    goodsList.value = [];
    getMescroll().resetUpScroll();
    labelPopup.value = false;
}

const onCub = (res: any) => {
    cusType.value = res;
    goodsList.value = [];
    getMescroll().resetUpScroll();
    cusPopup.value = false;
}

// 搜索
const searchTypeFn = (type: any) => {
    if (type === 'label') {
        cusPopup.value = false;
        labelPopup.value = true;
        return;
    }
    if (type === 'isSelf') {
        labelPopup.value = false;
        cusPopup.value = true;
        return;
    }

    // 切换排序类型时重置顺序为 Asc
    if (searchType.value !== type) {
        currentSortOrder.value = 'Asc';
    } else {
        // 同一类型点击切换升降序
        currentSortOrder.value = currentSortOrder.value === 'Asc' ? 'Desc' : 'Asc';
    }

    searchType.value = type;
    labelPopup.value = false;
    cusPopup.value = false;
    goodsList.value = [];
    getMescroll().resetUpScroll();
}

//列表样式切换
const listIconBtn = () => {
    listType.value = !listType.value
}
const toDetail = (id: string | number) => {
    redirect({ url: '/addon/shop/pages/goods/detail', param: { goodsId: id }, mode: 'navigateTo' })
}
onMounted(() => {
    setTimeout(() => {
        getMescroll().optUp.textNoMore = '-- 到底了 --';
    }, 500)
});
</script>

<style lang="scss" scoped>
@import '@/addon/shop/styles/common.scss';

.scroll-view-wrap {
    word-break: keep-all;
}

.text-color {
    color: var(--primary-color);
}

.label-select {
    color: var(--primary-color);
    border-color: var(--primary-color);
    background-color: var(--primary-color-light);
}

:deep(.u-popup .u-transition) {
    top: 156rpx !important;
}

.product-warp {
    z-index: 99999;
}

:deep(.tab-bar-placeholder) {
    display: none !important;
}

:deep(.u-tabbar__placeholder) {
    display: none !important;
}

:deep(.u-input__content__clear) {
    width: 28rpx;
    height: 28rpx;
    font-size: 28rpx;
    background-color: var(--text-color-light9);
}

.biserial-goods-list {
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-gap: 10px;
}
</style>
