<template>
    <view class="min-h-screen bg-[var(--page-bg-color)] overflow-hidden">
        <view class="mescroll-box bg-[var(--page-bg-color)] detail" v-if="tabsData.length">
            <mescroll-body ref="mescrollRef" :down="{ use: false }" @init="mescrollInit" @up="getListFn">
                <view v-if="config.search.control == 1"
                    class="search-box z-10 bg-[#fff] fixed top-0 left-0 right-0 h-[100rpx] box-border"
                    :style="{ 'top': systemStore.topTabbarInfo.fullHeight || 0 }">
                    <view class="flex-1 search-input">
                        <text @click.stop="searchNameFn" class="nc-iconfont nc-icon-sousuo-duanV6xx1 btn"></text>
                        <input class="input" type="text" v-model.trim="searchName" :placeholder="config.search.title"
                            @confirm="searchNameFn" placeholderClass="text-[var(--text-color-light9)]">
                        <text v-if="searchName" class="nc-iconfont nc-icon-cuohaoV6xx1 clear"
                            @click="searchName = ''"></text>
                    </view>
                </view>
                <!--  #ifdef H5 -->
                <view class="tabs-box z-2 fixed left-0 bg-[#fff] bottom-[50px] top-0"
                    :class="{ '!top-[100rpx]': config.search.control == 1 }">
                    <scroll-view :scroll-y="true" class="scroll-height">
                        <view class="bg-[var(--temp-bg)]">
                            <view class="tab-item"
                                :class="{ 'tab-item-active': index == tabActive, 'rounded-br-[12rpx]': tabActive - 1 === index, 'rounded-tr-[12rpx]': tabActive + 1 === index }"
                                v-for="(item, index) in tabsData" :key="index" @click="firstLevelClick(index, item)">
                                <view class="text-box text-left leading-[1.3] break-words px-[16rpx]">
                                    {{ item.label }}
                                </view>
                            </view>
                        </view>
                    </scroll-view>
                </view>
                <!--  #endif -->
                <!--  #ifndef  H5 -->
                <view class="tabs-box z-2 fixed left-0 bg-[#fff] pb-ios bottom-[100rpx] top-0" :style="tabsBoxCss">
                    <scroll-view :scroll-y="true" class="scroll-height">
                        <view class="bg-[var(--temp-bg)]">
                            <view class="tab-item"
                                :class="{ 'tab-item-active': index == tabActive, 'rounded-br-[12rpx]': tabActive - 1 === index, 'rounded-tr-[12rpx]': tabActive + 1 === index }"
                                v-for="(item, index) in tabsData" :key="index" @click="firstLevelClick(index, item)">
                                <view class="text-box text-left leading-[1.3] break-words px-[16rpx]">{{ item.label }}
                                </view>
                            </view>
                        </view>
                    </scroll-view>
                </view>
                <!--  #endif -->
                <view class="flex justify-center flex-wrap pl-[188rpx] pb-[20rpx]"
                    :class="{ ' pt-[120rpx]': config.search.control, ' pt-[20rpx]': !(config.search.control == 1) }">
                    <template v-for="(item, index) in list" :key="index">
                        <view
                            class="box-border bg-white w-full flex mr-[20rpx] py-[24rpx] px-[20rpx] rounded-[var(--rounded-small)]"
                            :class="{ 'mt-[16rpx]': index }" @click.stop="toLink(item.id)">
                            <view
                                class="w-[168rpx] h-[168rpx] flex items-center justify-center rounded-[var(--goods-rounded-small)] overflow-hidden">
                                <u--image width="168rpx" height="168rpx" radius="var(--goods-rounded-small)"
                                    :src="img(item.productImage || '')" model="aspectFill">
                                    <template #error>
                                        <image class="w-[168rpx] h-[168rpx]"
                                            :src="img('https://v6.site.niucloud.com/static/resource/images/diy/shop_default.jpg')"
                                            mode="aspectFill" />
                                    </template>
                                </u--image>
                            </view>
                            <view class="flex flex-1 ml-[20rpx] flex-wrap flex-col">
                                <view class="max-h-[80rpx] text-[26rpx] leading-[40rpx] multi-hidden">{{ item.itemName
                                }}</view>
                                <view class="flex-1 flex items-end justify-between">
                                    <view class="text-[var(--price-text-color)] price-font -mb-[8rpx]">
                                        <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="h-[44rpx] relative">
                                        <view :id="'itemCart' + index"
                                            class="w-[102rpx] box-border text-center text-[#fff] primary-btn-bg h-[46rpx] text-[22rpx] leading-[46rpx] rounded-[100rpx]">
                                            购买</view>
                                    </view>
                                </view>
                            </view>
                        </view>

                    </template>
                    <mescroll-empty class="part" v-if="!list.length && !loading && listLoading"
                        :option="{ tip: '暂无商品' }"></mescroll-empty>
                </view>
                <add-cart-popup ref="cartRef" />
            </mescroll-body>
        </view>
        <view v-show="animationElStatus" :style="animationElStatus"
            class="fixed z-999 flex items-center justify-center text-[#fff] bg-color h-[44rpx] w-[44rpx] rounded-[22rpx] text-center">
            <text class=" nc-iconfont nc-icon-gouwucheV6xx6 !text-[30rpx]"></text>
        </view>
        <mescroll-empty v-if="!tabsData.length && !loading" :option="{ tip: '暂无商品分类' }"></mescroll-empty>
        <loading-page :loading="loading"></loading-page>
        <tabbar />
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, getCurrentInstance } from 'vue';
import { img, redirect } from '@/utils/common';
import { getGoodsCategoryTree, getGoodsPages, 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 addCartPopup from './add-cart-popup.vue'
import { onPageScroll, onReachBottom } from '@dcloudio/uni-app';
import useCartStore from '@/addon/shop/stores/cart'
import useSystemStore from '@/stores/system';
import { useGoods } from '@/addon/shop/hooks/useGoods'
const diyGoods = useGoods();
const systemStore = useSystemStore()

// 查询购物车列表
const cartStore = useCartStore();
cartStore.getList();

const tabsBoxCss = computed(() => {
    let style = ''
    if (config.search.control == '1') {
        style += `top: calc(${systemStore.topTabbarInfo.height || 0}px + 98rpx);`
    } else {
        style += `top: ${systemStore.topTabbarInfo.height || 0}px;`
    }
    return style
})
const { mescrollInit, getMescroll } = useMescroll(onPageScroll, onReachBottom);
const prop = defineProps({
    config: {
        type: Object,
        default: (() => {
            return {}
        })
    },
    categoryId: {
        type: [String, Number],
        default: ''
    }
})
let config = prop.config
let categoryId = prop.categoryId;
const list = ref<any>([]);
const searchName = ref("");
const loading = ref<boolean>(true);//页面加载动画
const listLoading = ref<boolean>(false);//列表加载动画
const cartData = ref<Array<any>>([])
cartData.value = uni.getStorageSync('shopCart') || []

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

const getListFn = (mescroll: mescrollStructure) => {
    listLoading.value = false
    getGoodsComponents({
        pageNum: mescroll.num,
        pageSize: mescroll.size,
        topCategoryId: categoryId, // 商品分类id
        searchKeyword: searchName.value
    }).then((res: any) => {
        let newArr = res.rows
        //设置列表数据

        if (mescroll.num == 1) {
            list.value = []; //如果是第一页需手动制空列表
        }
        list.value = list.value.concat(newArr);
        loading.value = false;
        mescroll.endSuccess(newArr.length);
        if (!list.value.length) listLoading.value = true
    }).catch(() => {
        loading.value = false;
        listLoading.value = true
        mescroll.endErr(); // 请求失败, 结束加载
    })
}

const toLink = (goods_id: string) => {
    redirect({ url: '/addon/shop/pages/goods/detail', param: { goodsId: goods_id } })
}

onMounted(() => {
    getCategoryData()
})

//设置购物车动画
const animationElStatus = ref('')

/**
 * @description 获取分类数据
 * */
const tabsData: any = ref<Array<Object>>([])
const getCategoryData = () => {
    loading.value = true;
    getGoodsCategoryTree({ platform: 0 }).then((res: any) => {
        tabsData.value = res.data;
        if (categoryId) {
            for (let i = 0; i < tabsData.value.length; i++) {
                if (tabsData.value[i].id == categoryId) {
                    tabActive.value = i;
                    break;
                }
                if (tabsData.value[i].child_list) {
                    for (let k = 0; k < tabsData.value[i].child_list.length; k++) {
                        if (tabsData.value[i].child_list[k].id == categoryId) {
                            tabActive.value = i;
                            break;
                        }
                    }
                }
            }
        } else {
            categoryId = res.data[0].id;
        }
        loading.value = false;
    }).catch(() => {
        loading.value = false;
    });
}

// 一级菜单样式控制
const tabActive = ref<number>(0)

// 一级菜单点击事件
const firstLevelClick = (index: any, data: any) => {
    tabActive.value = index;
    categoryId = data.id;
    list.value = [];
    getMescroll().resetUpScroll();
}

// 搜索名字
const searchNameFn = () => {
    getMescroll().resetUpScroll();
}
</script>

<style lang="scss" scoped>
.remove-border {
    &::after {
        border: none;
    }
}

.border-color {
    border-color: var(--primary-color) !important;
}

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

.bg-color {
    background-color: var(--primary-color) !important;
}

.class-select {
    position: relative;
    font-weight: bold;

    &::before {
        content: "";
        position: absolute;
        bottom: 0;
        height: 6rpx;
        background-color: var(--primary-color);
        width: 90%;
        left: 50%;
        transform: translateX(-50%);
    }
}

.list-select {
    position: relative;
    margin-right: 28rpx;

    &::before {
        content: "";
        position: absolute;
        background-color: #999;
        width: 2rpx;
        height: 70%;
        top: 50%;
        right: -14rpx;
        transform: translatey(-50%);
    }
}

.transform-rotate {
    transform: rotate(180deg);
}

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

.bg-color {
    background-color: var(--primary-color);
}

// search input
.search-box {
    display: flex;
    align-items: center;
    padding: 0 30rpx;
}

.search-box .search-ipt {
    height: 58rpx;
    background-color: #F6F8F8;
    border-radius: 33rpx;
}

.search-box .search-ipt .input-placeholder {
    color: #A5A6A6;
}

.tabs-box {
    width: 168rpx;
    font-size: 26rpx;
}

.tabs-box .tab-item {
    min-height: 56rpx;
    padding: 20rpx 0;
    text-align: center;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24rpx;
}

.tabs-box .tab-item-active {
    position: relative;
    color: var(--primary-color);
    background-color: var(--temp-bg);

    &::before {
        display: inline-block;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        content: '';
        width: 6rpx;
        height: 48rpx;
        background-color: var(--primary-color);
    }

    &::after {
        display: inline-block;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        content: '';
        width: 6rpx;
        height: 48rpx;
        background-color: var(--primary-color);
    }
}

.scroll-height {
    height: 100%;
}

/*  #ifdef  H5  */
.cart {
    .noData1 {
        height: calc(100vh - 146rpx - 100rpx - 50px - constant(safe-area-inset-bottom));
        height: calc(100vh - 146rpx - 100rpx - 50px - env(safe-area-inset-bottom));
    }

    .noData2 {
        height: calc(100vh - 40rpx - 100rpx - 50px - constant(safe-area-inset-bottom));
        height: calc(100vh - 40rpx - 100rpx - 50px - env(safe-area-inset-bottom));
    }
}

.detail {
    .noData1 {
        height: calc(100vh - 146rpx - 50px - constant(safe-area-inset-bottom));
        height: calc(100vh - 146rpx - 50px - env(safe-area-inset-bottom));
    }

    .noData2 {
        height: calc(100vh - 40rpx - 50px - constant(safe-area-inset-bottom));
        height: calc(100vh - 40rpx - 50px - env(safe-area-inset-bottom));
    }
}

/*  #endif  */
/*  #ifndef  H5  */
.cart {
    .noData1 {
        height: calc(100vh - 146rpx - 100rpx - 100rpx - constant(safe-area-inset-bottom));
        height: calc(100vh - 146rpx - 100rpx - 100rpx - env(safe-area-inset-bottom));
    }

    .noData2 {
        height: calc(100vh - 40rpx - 100rpx - 100rpx - constant(safe-area-inset-bottom));
        height: calc(100vh - 40rpx - 100rpx - 100rpx - env(safe-area-inset-bottom));
    }
}

.detail {
    .noData1 {
        height: calc(100vh - 146rpx - 100rpx - constant(safe-area-inset-bottom));
        height: calc(100vh - 146rpx - 100rpx - env(safe-area-inset-bottom));
    }

    .noData2 {
        height: calc(100vh - 40rpx - 100rpx - constant(safe-area-inset-bottom));
        height: calc(100vh - 40rpx - 100rpx - env(safe-area-inset-bottom));
    }
}

/*  #endif  */

// 空页面
.mescroll-empty.empty-page.part {
    width: 542rpx;
    height: 542rpx;
    margin-top: 0;
    margin-left: 0;
    padding-top: 50rpx;

    .img {
        width: 160rpx !important;
        height: 120rpx !important;
    }
}
</style>
