<template>
	<view class="safe-page min-page">
		<up-sticky>
			<view class="bg-fff u-p-l-30  u-p-r-30 u-p-b-30">
				<!-- <view class="myTabs ">
				<myTabs :list="tabsList" @change="tabsChange"></myTabs>
			</view> -->
				<view class="input-wrapper">
					<view class="input-main">
						<view class="u-flex u-p-r-30 u-font-28" @click="onCategoryShowChange(true)">
							<text class="u-m-r-10 u-line-1"
								style="max-width: 100rpx;">{{pageData.categoryName||'全部' }}</text>
							<up-icon name="arrow-down" size="16"></up-icon>
						</view>
						<uni-easyinput clearable class='jeepay-search' :inputBorder="false"
							:placeholder="pageData.search.placeholder" v-model="pageData.query.name"
							@confirm="searchFunc">
							<template #prefixIcon>
								<image src="@/static/iconImg/icon-search.svg" class="input-icon" />
							</template>
						</uni-easyinput>
						<button type="text" @click="searchFunc()">搜索</button>
					</view>
				</view>
				<view class="u-flex  states1 u-row-between  u-font-28">
					<view class=" u-flex-1  item  u-flex u-row-center tranistion u-text-center color-333"
						:class="{'active':pageData.stateCurrent==index}" @tap="statesTableClick(index)"
						v-for="(item,index) in statesTabsList" :key="index">
						<view class="text">{{item}}</view>
					</view>
				</view>

			</view>
		</up-sticky>
		<template v-if="pageData.stateCurrent==0">
			<view class="goods-list  u-p-30">
				<template v-if="pageData.bindGoodsList.length">
					<view class="u-m-b-32" v-for="(item,index) in pageData.bindGoodsList" :key="index">
						<my-goods isBind  @radioClick="goodsRadioClick" :index="index"
							:data="item" @del="goodsDel" :showChecked="showChecked"
							:showDetail="pageData.showGoodsDetail"></my-goods>
					</view>
				</template>
				<template v-if="pageData.hasAjax&&!pageData.bindGoodsList.length">
					<my-img-empty tips="暂无绑定商品"></my-img-empty>
				</template>
				<view style="height: 100rpx;"></view>
			</view>
		</template>
		<template v-else>
			<view class="goods-list  u-p-30">
				<view class="bg-fff border-r-18 u-p-t-16 u-p-b-16 box-shadow">
					<template v-if="pageData.goodsList.length">
						<view class="" v-for="(item,index) in pageData.goodsList" :key="index">
							<my-goods  @goodsClick="goodsClick"
								@radioClick="goodsRadioClick" :index="index" :data="item" @del="goodsDel"
								:showChecked="showChecked" :showDetail="pageData.showGoodsDetail"></my-goods>
						</view>
					</template>
					<template v-if="pageData.hasAjax&&!pageData.goodsList.length">
						<my-img-empty tips="未找到相关商品"></my-img-empty>
					</template>
				</view>
				<view class="fixed-b">
					<my-button shape="circle" @click="save">确定</my-button>
				</view>
				<view style="height: 100rpx;"></view>
				<!-- <my-pagination :totalElements="pageData.totalElements" :size="pageData.query.size"
					@change="pageChange"></my-pagination> -->


				<!-- <my-control></my-control> -->
			</view>
		</template>


		<!-- 分类 -->
		<my-category v-model:isShow="pageData.categoryShow" @confirm="setCategory"></my-category>
	</view>

</template>

<script setup>
	import {
		onLoad,
		onReady,
		onShow,
		onPageScroll,
		onPullDownRefresh
	} from '@dcloudio/uni-app';
	import {
		reactive,
		ref,
		watch
	} from 'vue';
	import go from '@/commons/utils/go.js';
	import myGoods from './components/goods.vue'
	import myCategory from './components/category.vue'
	import infoBox from "@/commons/utils/infoBox.js"
	import myControl from './components/control.vue'
	import {
		$tbProduct,
		$upProSort,
		$updateProduct,
		$getProductDetail,
		$delProduct,
		$tbShopCategory,
		$updateProductStatus,
		$tbProductV2,
		$updateProductData
	} from "@/http/yskApi/goods.js"
	import {
		productListGet,
		tbProductGroupGet,
		tbProductGroupDelete,
		tbProductGroupPut,
		upGroupSort,
		tbProductGroupPost
	} from "@/http/yskApi/shop.js"
	
	import {hasPermission} from '@/commons/utils/hasPermission.js';
	
	import {
		returnAllCategory
	} from '@/pageProduct/util.js'

	const pageData = reactive({
		modelDesc: '是否下架',
		stateCurrent: 0,
		componentBottom: 45,
		search: {
			value: '',
			placeholder: '输入搜索的商品'
		},
		showGoodsDetail: false,
		selGoodsIndex: '',
		selGoods: {},
		totalElements: 0,
		totalPage: 0,
		bindGoodsList: [],
		goodsList: [],
		query: {
			page: 0,
			size: 999,
			categoryId: '',
			name: '',
			createdAt: [],
			id: "",
			sort: "createdAt,desc"
		},
		category: '',
		categoryList: [], //分类列表
		categoryShow: false,
		categoryName: '',
		hasAjax: false
	})
	watch(() => pageData.query.categoryId, (newval) => {
		getGoodsList()
	})

	watch(()=>pageData.stateCurrent,(newval)=>{
		if(newval){
			setGoodsList()
		}else{
			init()
		}
	})

	function isGroundingChange(e) {
		const {
			goodsIndex,
			guigeIndex
		} = popup.guige
		pageData.goodsList[goodsIndex].skuList[guigeIndex].isGrounding = e
	}

	function isPauseSaleChange(e) {
		const {
			goodsIndex,
			guigeIndex
		} = popup.guige
		pageData.goodsList[goodsIndex].skuList[guigeIndex].isPauseSale = e
	}

	function onCategoryShowChange(show) {
		console.log(show);
		pageData.categoryShow = show
	}

	function goodsClick(e) {
		console.log(e);
		pageData.goodsList[e].checked = !pageData.goodsList[e].checked
	}

	function setCategory(category) {
		pageData.query.categoryId = category.id
		pageData.categoryName = category.name
	}
	
	let $goodsList=[]
	function setGoodsList(){
		pageData.goodsList = $goodsList.filter(v=>!pageData.bindGoodsList.find(bindGoods=>bindGoods.id==v.id))
	}
	function getGoodsList() {
		$tbProductV2(pageData.query).then(res => {
			pageData.hasAjax = true
			pageData.totalElements = res.totalElements
			$goodsList=res.content.map(v=>{
				return {
					...v,checked:false
				}
			})
			setGoodsList()
			
		})
	}
	onShow(() => {
		// getGoodsList()
	})
	async function getGroupBindGoods() {
		const res = await productListGet(option.id)
		pageData.bindGoodsList = res
	}
	const option = reactive({})
	async function init() {
		const res = await productListGet(option.id)
		pageData.bindGoodsList = res
		getGoodsList()
	}
	onLoad((opt) => {
		tbProductGroupGet({
			page: 0,
			size: 999,
			sort: 'id',
			shopId: uni.getStorageSync('shopId')
		})
		Object.assign(option, opt)
		init()
		// $tbShopCategory({
		// 	page: 0,
		// 	size: 200
		// }).then(res => {
		// 	pageData.categoryList = returnAllCategory(res.content)
		// 	console.log(pageData.categoryList);
		// })
	})

	const statesTabsList = ['已添加', '未添加']

	const control = ref(null)
	const model = ref(null)
	const goodsStockModel = ref(null)

	function returnGoodsStockData() {
		return reactive({
			sort: 0,
			isStock: false,
			isDistribute: false,
			isPauseSale: false,
			isGrounding: false,
			stockNumber: 0,
		})
	}

	async function save() {
		const res=await hasPermission('允许修改分组')
		if(!res){
			return
		}
		console.log(pageData.goodsList);
		await tbProductGroupPut({
			...option,
			shopId:uni.getStorageSync('shopId'),
			productIds:[...pageData.bindGoodsList.map(v=>v.id),...pageData.goodsList.filter(v=>v.checked).map(v=>v.id)]
		})
		pageData.stateCurrent=0
	}
	
	
	function updateGroup(){
		
	}
	
	//删除商品
	async function goodsDel(index) {
		const res=await hasPermission('允许修改分组')
		if(!res){
			return
		}
		const goods = pageData.bindGoodsList[index]
		uni.showModal({
			title: '提示',
			content: '是否确认将' + goods.name + '从该分组中移除',
			success: function(res) {
				if (res.confirm) {
					pageData.bindGoodsList.splice(index, 1)
					tbProductGroupPut({
						...option,
						shopId:uni.getStorageSync('shopId'),
						productIds:pageData.bindGoodsList.map(v=>v.id)
					})
				} else if (res.cancel) {}
			}
		});
	}


	function statesTableClick(index) {
		pageData.stateCurrent = index
	}


	function tabsChange(i) {
		console.log(i);
		pageData.showGoodsDetail = i ? true : false
	}


	//改变商品的选中状态
	function changeGoodsChecked(checked, index) {
		if (index !== undefined) {
			pageData.goodsList[index].checked = checked
		} else {
			pageData.goodsList.map(v => {
				v.checked = checked
			})
		}
		control.value.setisSelectAll(isAllChecked() ? true : false)
	}


	// 获取已经选中的商品
	function getChechkedGoodsList() {
		return pageData.goodsList.filter(v => v.checked)
	}
	//是否全部选中
	function isAllChecked() {
		return getChechkedGoodsList().length === pageData.goodsList.length
	}
	// 是否有商品选中
	function isHasChekdGoods() {
		return getChechkedGoodsList().length ? true : false
	}

	function searchFunc() {
		console.log('searchFunc');
		getGoodsList()
	}

	let showChecked = ref(false)

	//商品start

	function goodsRadioClick(index) {
		var checked = !pageData.goodsList[index].checked
		changeGoodsChecked(checked, index)
	}


	//下架
	function offShelf() {
		const hasCheckedArr = getChechkedGoodsList()
		const hasChecked = isHasChekdGoods()
		if (!hasChecked) {
			return infoBox.showToast('您还没有选中商品！')
		}
		model.value.open()
	}
	//下架确认
	function modelConfirm() {
		console.log('confirm');
		model.value.close()
	}

	//商品end

	//控制条
	function controlChange(bol) {
		showChecked.value = bol
	}



	// 全选
	function allCheckedChange(checked) {
		changeGoodsChecked(checked)
	}

	// 页数改变事件
	function pageChange(page) {
		console.log(page);
		pageData.query.page = page - 1
		getGoodsList()
	}

	//分类
	const category = ref(null)

	function toggleCategory() {
		category.value.toggle()
	}

	function cateClick(cate) {
		console.log(cate);
		pageData.query.categoryId = cate.id
		pageData.categoryName = cate.name
		pageData.category = cate
		getGoodsList()
	}
</script>
<style scoped>
	page {
		background: #F9F9F9;
	}
</style>
<style lang="scss" scoped>
	.stock-btns {
		padding: 0 100rpx;
		display: flex;
		flex-direction: column;
		gap: 20rpx;
	}

	.safe-page {
		background: #F9F9F9;
	}

	.icon-guige {
		width: 42rpx;
		height: 42rpx;
	}

	.bg-fff {
		background-color: #fff;
	}

	.myTabs {
		margin: 0 auto;
		width: 434rpx;
		height: 64rpx;
	}

	.input-wrapper {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding-top: 26rpx;
		background-color: $J-bg-ff;

		.input-main {
			flex: 1;
			display: flex;
			align-items: center;
			height: 64rpx;

			image {
				padding: 22rpx;
				width: 26rpx;
				height: 26rpx;
			}

			input {
				flex: 1;
				font-size: 27rpx;
			}

			::v-deep uni-button {
				font-size: 28rpx;
				color: $my-main-color;
				background: rgba(255, 255, 255, 1);
			}

			::v-deep.uni-easyinput {
				.uni-easyinput__content {
					background-color: $J-bg-f5 !important;
					border-radius: $J-b-r12;

					.uni-easyinput__content-input {
						padding-left: 0 !important;

						.uni-input-input {
							border-radius: $J-b-r12 !important;
							overflow: hidden !important;
						}
					}

					.uni-input-placeholder {
						font-size: 27rpx;
					}

					.uni-icons {
						color: rgba(230, 230, 230, 1) !important;
					}
				}
			}
		}
	}

	.input-icon {
		position: relative;
		z-index: 10;
	}

	.search-button {
		position: absolute;
		right: 0;
		background-color: transparent !important;
		color: transparent !important;
	}

	.states1 {
		margin-top: 24rpx;

		.item {
			font-size: 28rpx;
			color: #666;

			.text {
				position: relative;
				padding-top: 14rpx;
				padding-bottom: 16rpx;

				&::after {
					content: '';
					display: block;
					position: absolute;
					transition: all .2s ease-in-out;
					left: 10rpx;
					right: 10rpx;
					bottom: 0;
					height: 4rpx;
					background: transparent;
					border-radius: 12rpx 12rpx 12rpx 12rpx;
				}
			}

			&.active {
				color: $my-main-color;
				border-radius: 8rpx 8rpx 8rpx 8rpx;

				.text {
					&::after {
						background-color: $my-main-color;
					}
				}

			}

		}


	}

	.fixed-b {
		position: fixed;
		bottom: calc(env(safe-area-inset-bottom) + 16rpx);
		/* #ifdef H5 */
		bottom: 50rpx;
		/* #endif */
		left: 110rpx;
		right: 110rpx;
	}
</style>