<!-- 商品分类列表 -->
<template>
	<s-layout title="分类" tabbar="/pages/index/category" :bgStyle="{ color: '#fff' }">
		<view style="background-color: #fff;display: flex;justify-content: flex-end;">
			<view style="background-color:#fff;width: 200rpx;">
				<uni-search-bar v-if="!navbar" class="ss-flex-1" radius="40" placeholder="请输入" cancelButton="none"
					clearButton="none" @confirm="onSearch" v-model="state.searchVal" />
			</view>
		</view>

		<view class="s-category">
			<view class="three-level-wrap ss-flex ss-col-top" :style="[{ height: pageHeight + 'px' }]">
				<!-- 商品分类（左） -->
				<scroll-view class="side-menu-wrap" scroll-y :style="[{ height: pageHeight + 'px' }]">
					<view class="menu-item ss-flex" v-for="(item, index) in state.categoryList" :key="item.id"
						:class="[{ 'menu-item-active': index === state.activeMenu }]" @tap="onMenu(index)">
						<view class="menu-title ss-line-1">
							{{ item.name }}
						</view>
					</view>
				</scroll-view>
				<!-- 商品分类（右） -->
				<scroll-view class="goods-list-box" scroll-y :style="[{ height: pageHeight + 'px' }]"
					v-if="state.pagination.list?.length">
					<view v-if=" state.pagination.total > 0" class="goods-list ss-m-t-20">
						<view class="ss-p-l-20 ss-p-r-20 ss-m-b-20" v-for="(item,index) in state.pagination.list"
							:key="item.id">
							<s-goods-column class="" size="lg" :data="item" :index="index" :topRadius="10" :bottomRadius="10"
								@click="sheep.$router.go('/pages/goods/index', { id: item.id })" />
						</view>
					</view>
					
					<!-- <image
            v-if="state.categoryList[state.activeMenu].picUrl"
            class="banner-img"
            :src="sheep.$url.cdn(state.categoryList[state.activeMenu].picUrl)"
            mode="widthFix"
          />
          <first-one v-if="state.style === 'first_one'" :pagination="state.pagination" />
          <first-two v-if="state.style === 'first_two'" :pagination="state.pagination" />
          <second-one
            v-if="state.style === 'second_one'"
            :data="state.categoryList"
            :activeMenu="state.activeMenu"
          />
          <uni-load-more
            v-if="
              (state.style === 'first_one' || state.style === 'first_two') &&
              state.pagination.total > 0
            "
            :status="state.loadStatus"
            :content-text="{
              contentdown: '点击查看更多',
            }"
            @tap="loadMore"
          /> -->
				</scroll-view>
			</view>
			<!-- v-if="state.list.length > 0" -->

		</view>
		<su-fixed bottom :val="48" placeholder :isInset="false">
			<view class="cart-footer ss-flex ss-col-center ss-row-between ss-p-x-30 border-bottom" @click="goCartList">
				<view class="footer-left ss-flex ss-col-center">
					<!-- <label class="check-box ss-flex ss-col-center ss-p-r-30" @tap="onSelectAll">
                                        <radio :checked="state.isAllSelected" color="var(--ui-BG-Main)"
                                                style="transform: scale(0.8)" @tap.stop="onSelectAll" />
                                        <view class="ss-m-l-8"> 全选 </view>
                                </label> -->
					<text>合计：</text>
					<view class="text-price price-text">
						{{ state.totalPriceSelected?fen2yuan(state.totalPriceSelected):0 }}
					</view>
				</view>
				<view class="footer-right">
					<button v-if="state.editMode" class="ss-reset-button ui-BG-Main-Gradient pay-btn ui-Shadow-Main"
						@tap="onDelete">
						删除
					</button>
					<button v-else class="ss-reset-button ui-BG-Main-Gradient pay-btn ui-Shadow-Main" @tap.stop="onConfirm">
						去结算
						{{ state.selectedIds?.length ? `(${state.selectedIds.length})` : '' }}
					</button>
				</view>
			</view>
		</su-fixed>
	</s-layout>
</template>

<script setup>
	import secondOne from './components/second-one.vue';
	import firstOne from './components/first-one.vue';
	import firstTwo from './components/first-two.vue';
	import hxNumberBox from './components/uni-number-box';
	import sGoodsColumn from './components/s-goods-column.vue';
	import sheep from '@/sheep';
	import CategoryApi from '@/sheep/api/product/category';
	import SpuApi from '@/sheep/api/product/spu';
	import {
		onLoad,
		onReachBottom
	} from '@dcloudio/uni-app';
	import {
		computed,
		reactive
	} from 'vue';
	import _ from 'lodash';
	import {
		handleTree
	} from '@/sheep/util';
	import {
		fen2yuan
	} from '../../sheep/hooks/useGoods';

	// uni.hideTabBar();
	const cart = sheep.$store('cart');

	const state = reactive({
		style: 'second_one', // first_one（一级 - 样式一）, first_two（二级 - 样式二）, second_one（二级）
		categoryList: [], // 商品分类树
		activeMenu: 0, // 选中的一级菜单，在 categoryList 的下标

		pagination: {
			// 商品分页
			list: [], // 商品列表
			total: [], // 商品总数
			pageNo: 1,
			pageSize: 6,
		},
		loadStatus: '',
		categoryId: 0,
		keyword: '',
		list: computed(() => cart.list),
		selectedIds: computed(() => cart.selectedIds),
		totalPriceSelected: computed(() => cart.totalPriceSelected),
	});

	const {
		safeArea
	} = sheep.$platform.device;
	const pageHeight = computed(() => safeArea.height - 44 - 50);

	// 加载商品分类
	async function getList() {
		const {
			code,
			data
		} = await CategoryApi.getCategoryList();

		if (code !== 0) {
			return;
		}
		state.categoryList = handleTree(data);

		console.log(state.categoryList[state.activeMenu], 'state.categoryList[state.activeMenu]')
		const res = await SpuApi.getSpuPage({
			categoryId: state.categoryList[state.activeMenu].id,
			pageNo: state.pagination.pageNo,
			pageSize: state.pagination.pageSize,
		});
		state.pagination.list = _.concat(state.pagination.list, res.data.list)
		state.pagination.total = res.data.total;
		state.loadStatus = state.pagination.list.length < state.pagination.total ? 'more' : 'noMore';
	}

	// 选中菜单
	const onMenu = (val) => {
		console.log(val, 'valllll')
		state.activeMenu = val;
		console.log(state.style, 'state.style')
		// if (state.style === 'first_one' || state.style === 'first_two') {
		//   state.pagination.pageNo = 1;
		//   state.pagination.list = [];
		//   state.pagination.total = 0;
		getGoodsList();
		// }
	};
	// 结算
	function onConfirm() {
		let items = []
		let goods_list = [];
		state.selectedList = state.list.filter((item) => state.selectedIds.includes(item.id));
		state.selectedList.map((item) => {
			// 此处前端做出修改
			items.push({
				skuId: item.sku.id,
				count: item.count,
				cartId: item.id,
			})
			goods_list.push({
				// goods_id: item.goods_id,
				goods_id: item.spu.id,
				// goods_num: item.goods_num,
				goods_num: item.count,
				// 商品价格id真没有
				// goods_sku_price_id: item.goods_sku_price_id,
			});
		});
		// return;
		if (goods_list.length === 0) {
			sheep.$helper.toast('请选择商品');
			return;
		}
		sheep.$router.go('/pages/order/confirm', {
			data: JSON.stringify({
				// order_type: 'goods',
				// goods_list,
				items,
				// from: 'cart',
				deliveryType: 1,
				pointStatus: false,
			}),
		});
	} 

	// 加载商品列表
	async function getGoodsList() {
		// 加载列表
		state.loadStatus = 'loading';
		const res = await SpuApi.getSpuPage({
			categoryId: state.categoryList[state.activeMenu].id,
			pageNo: state.pagination.pageNo,
			pageSize: state.pagination.pageSize,
		});
		if (res.code !== 0) {
			return;
		}
		// 合并列表
		// state.pagination.list = _.concat(state.pagination.list, res.data.list);
		state.pagination.list = res.data.list
		state.pagination.total = res.data.total;
		state.loadStatus = state.pagination.list.length < state.pagination.total ? 'more' : 'noMore';
	}
	function goCartList(){
		uni.navigateTo({
		  url:'/pages/index/cart'
		});
	}

	// 加载更多商品
	function loadMore() {
		if (state.loadStatus === 'noMore') {
			return;
		}
		state.pagination.pageNo++;
		getGoodsList();
	}

	onLoad(async () => {

		await getList();
		// const id=state.categoryList[state.activeMenu].id
		// state.categoryId = id;
		// state.keyword = options.keyword;
		console.log(state.categoryList[state.activeMenu], 'state.categoryList[state.activeMenu]')
		// 如果是 first 风格，需要加载商品分页
		if (state.style === 'first_one' || state.style === 'first_two') {
			onMenu(0);
		}
	});

	onReachBottom(() => {
		loadMore();
	});
</script>

<style lang="scss" scoped>
	.s-category {
		:deep() {
			.side-menu-wrap {
				width: 200rpx;
				height: 100%;
				padding-left: 12rpx;
				background-color: #f6f6f6;

				.menu-item {
					width: 100%;
					height: 88rpx;
					position: relative;
					transition: all linear 0.2s;

					.menu-title {
						line-height: 32rpx;
						font-size: 30rpx;
						font-weight: 400;
						color: #333;
						margin-left: 28rpx;
						position: relative;
						z-index: 0;

						&::before {
							content: '';
							width: 64rpx;
							height: 12rpx;
							background: linear-gradient(90deg,
									var(--ui-BG-Main-gradient),
									var(--ui-BG-Main-light)) !important;
							position: absolute;
							left: -64rpx;
							bottom: 0;
							z-index: -1;
							transition: all linear 0.2s;
						}
					}

					&.menu-item-active {
						background-color: #fff;
						border-radius: 20rpx 0 0 20rpx;

						&::before {
							content: '';
							position: absolute;
							right: 0;
							bottom: -20rpx;
							width: 20rpx;
							height: 20rpx;
							background: radial-gradient(circle at 0 100%, transparent 20rpx, #fff 0);
						}

						&::after {
							content: '';
							position: absolute;
							top: -20rpx;
							right: 0;
							width: 20rpx;
							height: 20rpx;
							background: radial-gradient(circle at 0% 0%, transparent 20rpx, #fff 0);
						}

						.menu-title {
							font-weight: 600;

							&::before {
								left: 0;
							}
						}
					}
				}
			}

			.goods-list-box {
				background-color: #fff;
				width: calc(100vw - 100px);
				padding: 10px;
			}

			.banner-img {
				width: calc(100vw - 130px);
				border-radius: 5px;
				margin-bottom: 20rpx;
			}
		}
	}

	.cart-footer {
		height: 100rpx;
		color: #fff;
		background-color: #313131;
		border-radius: 49rpx;

		.pay-btn {
			width: 180rpx;
			height: 70rpx;
			font-size: 28rpx;
			line-height: 28rpx;
			font-weight: 500;
			border-radius: 40rpx;
		}
	}
</style>