<template>
    <view class="min-h-screen bg-[var(--page-bg-color)] overflow-hidden">
        <view class="mescroll-box bg-[#f6f6f6] detail" v-if="tabsData.length">
            <mescroll-body ref="mescrollRef" :down="{ use: false }" @init="mescrollInit" @up="getListFn">
                <view v-if="config.search.control == 1"
                    class="box-border search-box z-10 bg-[#fff] fixed top-0 left-0 right-0 h-[96rpx]"
                    :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"
                            placeholderClass="text-[var(--text-color-light9)]" @confirm="searchNameFn" />
                        <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-[96rpx]': config.search.control,
                    'pb-[98rpx]': config.cart.control && config.cart.event === 'cart',
                }">
                    <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 &&
                                    (!tabsData[tabActive].children ||
                                        !tabsData[tabActive].children.length),
                                'rounded-tr-[12rpx]':
                                    tabActive + 1 === index &&
                                    (!tabsData[tabActive].children ||
                                        !tabsData[tabActive].children.length),
                            }" v-for="(item, index) in tabsData" :key="index" @click="firstLevelClick(index, item)">
                                <view class="text-box leading-[1.3] break-words px-[24rpx]">{{
                                    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 &&
                                    (!tabsData[tabActive].children ||
                                        !tabsData[tabActive].children.length),
                                'rounded-tr-[12rpx]':
                                    tabActive + 1 === index &&
                                    (!tabsData[tabActive].children ||
                                        !tabsData[tabActive].children.length),
                            }" v-for="(item, index) in tabsData" :key="index" @click="firstLevelClick(index, item)">
                                <view class="text-box px-[16rpx] leading-[1.3] break-words">{{
                                    item.label
                                    }}</view>
                            </view>
                        </view>
                    </scroll-view>
                </view>
                <!--  #endif -->

                <view
                    class="flex items-center h-[98rpx] pl-[24rpx] pr-[48rpx] py-[20rpx] z-10 bg-white fixed left-[168rpx] right-0 box-border top-0"
                    :style="twoTabCss" :class="{ '!top-[94rpx]': config.search.control }" v-if="
                        tabsData[tabActive]?.children &&
                        tabsData[tabActive]?.children.length
                    ">
                    <template v-if="!labelPopup">
                        <scroll-view :scroll-x="true" scroll-with-animation
                            :scroll-into-view="'id' + (subActive ? subActive - 1 : 0)"
                            class="flex-1 h-[54rpx] scroll-Y box-border pr-[24rpx] bg-white">
                            <view class="flex items-center h-[54rpx] box-border">
                                <text
                                    class="w-[150rpx] flex-shrink-0 px-[14rpx] h-[54rpx] truncate text-center !leading-[50rpx] !text-[24rpx] border-[2rpx] border-solid !rounded-[100rpx] box-border text-[#333] box-border"
                                    :class="{
                                        'bg-[var(--primary-color-light)] font-500 text-[var(--primary-color)] border-[var(--primary-color)]':
                                            index === subActive,
                                        'border-[var(--temp-bg)]  bg-[var(--temp-bg)]':
                                            index != subActive,
                                        ' ml-[24rpx]': index != 0,
                                    }" v-for="(item, index) in tabsData[tabActive]?.children" :key="tabsData[tabActive].id"
                                    :id="'id' + index" @click="subMenuClick(index, item, 2)">{{ item.label }}</text>
                            </view>
                        </scroll-view>
                        <view
                            class="absolute right-[24rpx] nc-iconfont nc-icon-xiaV6xx text-[30rpx] w-[30rpx] h-[30rpx] text-center transform"
                            @click="labelPopup = true"></view>
                    </template>
                    <template v-else>
                        <view
                            class="flex-1 h-[48rpx] text-[28rpx] text-[var(--text-color-light9)] pr-[24rpx] leading-[48rpx]">
                            全部分类</view>
                        <text class="absolute right-[24rpx] nc-iconfont nc-icon-shangV6xx-1 text-[#333] text-[30rpx]"
                            @click="labelPopup = false"></text>
                    </template>
                </view>
                <view class="labelPopup" :class="{ active: config.search.control }">
                    <u-popup :show="labelPopup" mode="top" @close="labelPopup = false">
                        <view class="flex flex-wrap pb-[24rpx]" :style="labelPopupCss" @touchmove.prevent.stop>
                            <text
                                class="px-[14rpx] flex-shrink-0 w-[160rpx] box-border ml-[20rpx] mb-[26rpx] h-[60rpx] text-center leading-[56rpx] text-[24rpx] border-[2rpx] border-solid !rounded-[100rpx] text-[#333] truncate"
                                :class="{
                                    'bg-[var(--primary-color-light)] font-500 text-[var(--primary-color)] border-[var(--primary-color)]':
                                        index === subActive,
                                    'border-[var(--temp-bg)]  bg-[var(--temp-bg)]':
                                        index != subActive,
                                }" v-for="(item, index) in tabsData[tabActive]?.children" :key="tabsData[tabActive].category_id"
                                @click="subMenuClick(index, item, 2)">{{ item.category_name }}</text>
                        </view>
                    </u-popup>
                </view>
                <view class="flex justify-center flex-wrap pl-[168rpx] pt-[20rpx] pb-[20rpx]" :class="{
                    '!pt-[214rpx]':
                        config.search.control &&
                        tabsData[tabActive]?.children &&
                        tabsData[tabActive]?.children.length,
                    'pt-[120rpx]':
                        config.search.control &&
                        (!tabsData[tabActive].children ||
                            !tabsData[tabActive].children.length),
                    'pt-[118rpx]':
                        tabsData[tabActive]?.children &&
                        tabsData[tabActive]?.children.length &&
                        !config.search.control,
                }">
                    <template v-for="(item, index) in list" :key="index">
                        <view
                            class="w-[536rpx] box-border bg-white w-full flex mx-[20rpx] py-[24rpx] px-[20rpx] rounded-[var(--rounded-small)]"
                            :class="{ 'mt-[20rpx]': index }" @click.stop="toLink(item.id)">
                            <view
                                class="w-[168rpx] h-[168rpx] flex items-center justify-center mr-[20rpx] 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 flex-wrap flex-col">
                                <view class="max-h-[80rpx] text-[26rpx] leading-[40rpx] multi-hidden">{{ item.itemName
                                    }}</view>
                                <view class="flex items-end justify-between flex-1">
                                    <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 pl-[20rpx]">
                                        <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>
        <view class="flex justify-center items-center w-[100%]" v-if="!tabsData.length && !loading">
            <mescroll-empty :option="{ tip: '暂无商品分类' }"></mescroll-empty>
        </view>
        <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";
const systemStore = useSystemStore();
import { useGoods } from "@/addon/shop/hooks/useGoods";
const diyGoods = useGoods();

const cartStore = useCartStore();
// 查询购物车列表
cartStore.getList();
const { mescrollInit, getMescroll } = useMescroll(onPageScroll, onReachBottom);
const prop = defineProps({
    config: {
        type: Object,
        default: () => {
            return {};
        },
    },
    categoryId: {
        type: [String, Number],
        default: 0,
    },
});
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 labelPopup = ref<boolean>(false);
const cartData = ref<Array<any>>([]);
const mediumCategoryId = ref<any>(null);
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,
        searchKeyword: searchName.value,
        topCategoryId: categoryId, // 商品分类id
        mediumCategoryId:mediumCategoryId.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(); // 请求失败, 结束加载
        });
};
// 左侧tab切换样式
const tabsBoxCss = computed(() => {
    let style = "";
    if (config.search.control) {
        style += `top: calc(${systemStore.topTabbarInfo.height || 0}px + 96rpx);`;
    } else {
        style += `top: ${systemStore.topTabbarInfo.height || 0}px;`;
    }
    return style;
});
// 二级菜单样式
const twoTabCss = computed(() => {
    let style = "";
    if (config.search.control) {
        style += `top: calc(${systemStore.topTabbarInfo.height || 0
            }px + 94rpx) !important;`;
    } else {
        style += `top: ${systemStore.topTabbarInfo.height || 0}px !important;`;
    }
    return style;
});

// 二级菜单弹窗样式
const labelPopupCss = computed(() => {
    let style = "";
    // #ifdef MP-WEIXIN
    style = `padding-top: calc(${systemStore.topTabbarInfo.height || 0
        }px + 20rpx) !important;`;
    // #endif
    // #ifdef H5
    style = `padding-top: 20rpx !important;`;
    // #endif
    return style;
});

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

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

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

const tabsData: any = ref<Array<Object>>([]);
const getCategoryData = () => {
    loading.value = true;
    getGoodsCategoryTree({ platform: 0 })
        .then((res: any) => {
            tabsData.value = res.data;
            for (let i = 0; i < tabsData.value.length; i++) {
                if (tabsData.value[i].children) {
                    let obj = {
                        label: "全部",
                        id: '',
                    };
                    tabsData.value[i].children.unshift(obj);
                }
            }
            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].children) {
                        for (let k = 0; k < tabsData.value[i].children.length; k++) {
                            if (tabsData.value[i].children[k].id == categoryId) {
                                tabActive.value = i;
                                subActive.value = k;
                                break;
                            }
                        }
                    }
                }
            } else {
                categoryId = res.data[0].id;
            }
            loading.value = false;
        })
        .catch(() => {
            loading.value = false;
        });
};

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

// 一级菜单点击事件
const firstLevelClick = (index: any, data: any) => {
    tabActive.value = index;
    labelPopup.value = false;
    mediumCategoryId.value = null;
    if (data.children && data.children.length) {
        subMenuClick(0, data, 1);
    } else {
        categoryId = data.id;
        list.value = [];
        getMescroll().resetUpScroll();
    }
};

/**
 * @description 二级菜单点击事件
 * @param {number} index
 * @param {Object} data
 * */
const subMenuClick = (index: any, data: any, type: number) => {
    subActive.value = index;
    if (type == 1) {
        categoryId = data.id;
    } else {
        mediumCategoryId.value = data.id;
    }
    labelPopup.value = false;
    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: $u-primary;
        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: $u-primary;
}

.border-color {
    border-color: $u-primary;
}

.bg-color {
    background-color: $u-primary;
}

// 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 {
    display: flex;
    align-items: center;
    justify-content: center;
    min-height: 56rpx;
    padding: 20rpx 0;
    background-color: #fff;
    font-size: 24rpx;
}

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

    &::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);
    }
}

/*  #ifdef  H5  */
.category .labelPopup :deep(.u-transition) {
    top: 92rpx !important;
    left: 168rpx !important;
    z-index: 8 !important;
}

.category .labelPopup.active :deep(.u-transition) {
    top: 192rpx !important;
}

/*  #endif  */

.scroll-height {
    height: 100%;
}

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

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

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

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

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

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

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

    .noChild.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 {
    .child.noData1 {
        height: calc(100vh - 146rpx - 92rpx - 100rpx - 100rpx - constant(safe-area-inset-bottom));
        height: calc(100vh - 146rpx - 92rpx - 100rpx - 100rpx - env(safe-area-inset-bottom));
    }

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

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

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

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

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

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

    .noChild.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: 0;
    padding-top: 50rpx;

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