<template>
	<view class="safe-page min-page">
		<up-sticky>
			<view class="bg-fff u-p-l-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"
						trim="all"
							:placeholder="pageData.search.placeholder" v-model="pageData.query.name"
							@clear="searchFunc"
							@confirm="searchFunc">
							<template #prefixIcon>
								<image src="@/static/iconImg/icon-search.svg" class="input-icon" />
							</template>
						</uni-easyinput>
						<view class="u-m-l-4">
							<button class="" type="text" @click="searchFunc()"> <text class="color-333">搜索</text></button>
						</view>
					</view>
				</view>
				<view class="u-flex  states1 u-row-between u-p-r-28  u-font-28">
					<view class="u-flex">
						<view class="u-p-l-16 item u-p-r-16 u-p-t-6 u-p-b-6 tranistion u-text-center color-333"
							:class="{'active':pageData.stateCurrent==index}" @tap="statesTableClick(index)"
							v-for="(item,index) in statesTabsList" :key="index">
							{{item}}
						</view>
					</view>
					<view class="u-flex u-col-center" @click="go.to('PAGES_PRODUCT_SPECIF_TEMPLATE')">
						<image src="/pageProduct/static/images/icon-guige.svg" class="icon-guige" />
						<text class="color-666 u-m-l-12 u-font-24">规格模版</text>
					</view>
				</view>

			</view>
		</up-sticky>
		<view class="goods-list u-p-30">
			<template v-if="pageData.goodsList.length">
				<view class="u-m-b-32" v-for="(item,index) in pageData.goodsList" :key="index">
					<my-goods :key="item.id" @update="getGoodsList" @changePrice="changePriceShow"
						@changeClick="goodsChangeClick" @edit="toGoodsDetail" @editStock="changeStockShow"
						@guigeClick="editGuigeShow" @baosun="baosunShow" @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>
			<template v-if="pageData.goodsList.length">
				<my-pagination :page="pageData.query.page+1" :totalElements="pageData.totalElements" :size="pageData.query.size"
					@change="pageChange"></my-pagination>
			</template>

			<view style="height: 100rpx;"></view>
		</view>

		<my-control ref="control" :categoryShow="pageData.categoryShow" :categoryName="pageData.categoryName"
			@offShelf="offShelf" @allCheckedChange="allCheckedChange" @controlChange="controlChange"
			@toggleCategory="toggleCategory" :bottom="pageData.componentBottom"></my-control>
		<!-- <my-category ref="category" @change="onCategoryShowChange" @cateClick="cateClick"
			:bottom="pageData.componentBottom+100"></my-category> -->
		<!-- 下架弹窗 -->
		<my-model :desc="pageData.modelDesc" ref="model" @confirm="modelConfirm"></my-model>
		<!-- 商品库存修改弹窗 -->
		<my-model ref="goodsStockModel" title="商品修改" @close="goodsStockModelClose">
			<template #desc>
				<view class="u-p-40 u-text-left">
					<view>
						<view class="">排序:</view>
						<view class="u-m-t-24">
							<uni-easyinput v-model="goodsStockData.sort" placeholder="请输入排序"></uni-easyinput>
						</view>
					</view>
					<view class="u-flex u-m-t-32">
						<view class="">库存开关:</view>
						<view class="u-m-l-46 ">
							<my-switch v-model="goodsStockData.isStock"></my-switch>
						</view>
					</view>
					<!-- <view class="u-flex u-m-t-32">
						<view class="">共享库存:</view>
						<view class="u-m-l-46 ">
							<my-switch v-model="goodsStockData.isDistribute"></my-switch>
						</view>
					</view>
					<view class="u-flex u-m-t-32">
						<view class="">售罄:</view>
						<view class="u-m-l-46 ">
							<my-switch v-model="goodsStockData.isPauseSale"></my-switch>
						</view>
					</view>
					<view class="u-flex u-m-t-32">
						<view class="">上架:</view>
						<view class="u-m-l-46 ">
							<my-switch v-model="goodsStockData.isGrounding"></my-switch>
						</view>
					</view> -->

					<!-- <view class="u-m-t-24 u-m-t-32" v-if="goodsStockData.isStock">
						<view class="">数量:</view>
						<view class="u-m-t-24">
							<uni-easyinput v-model="goodsStockData.stockNumber" placeholder="请输入库存数量"></uni-easyinput>
						</view>
					</view> -->
				</view>

			</template>
			<template #btn>
				<view class="stock-btns u-p-b-40">
					<my-button shape="circle" @tap="goodsStockModelSave">保存</my-button>
					<my-button shape="circle" type="default" @tap="goodsStockModelCancel">取消</my-button>
				</view>
			</template>
		</my-model>

		<!-- 分类 -->
		<my-category v-model:isShow="pageData.categoryShow" @confirm="setCategory"></my-category>
		<!-- 修改价格弹窗 -->
		<edit-price :category="pageData.categoryList" v-model:show="popup.price.show" @save="changePriceConfirm"
			:goods="pageData.selGoods"></edit-price>
		<!-- 修改库存弹窗 -->
		<edit-stock :category="pageData.categoryList" v-model:show="popup.stock.show" @save="changeStockConfirm"
			:goods="pageData.selGoods"></edit-stock>
		<!-- 规格弹窗 -->
		<edit-guige @isGroundingChange="isGroundingChange" v-model:show="popup.guige.show" @isPauseSaleChange="isPauseSaleChange"
			:goods="popup.guige.data"></edit-guige>
		<!-- 报损 -->
		<baosun-vue :category="pageData.categoryList" v-model:show="popup.baosun.show"
			:goods="pageData.selGoods"></baosun-vue>
	</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 {
		hasPermission
	} from '@/commons/utils/hasPermission.js';
	import myGoods from './components/goods.vue'
	import myControl from './components/control.vue'
	import myCategory from './components/category.vue'
	import infoBox from "@/commons/utils/infoBox.js"
	import editPrice from './components/edit-price.vue';
	import editGuige from './components/edit-guige.vue';
	import editStock from './components/edit-stock.vue';
	import baosunVue from './components/baosun.vue';
	import {
		$tbProduct,
		$upProSort,
		$updateProduct,
		$getProductDetail,
		$delProduct,
		$tbShopCategory,
		$updateProductStatus,
		$tbProductV2,
		$updateProductData
	} from "@/http/yskApi/goods.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,
		goodsList: [],
		query: {
			page: 0,
			size: 10,
			createdAt: [],
			id: "",
			categoryId: '',
			name: '',
			isPauseSale: '',
			sort: "createdAt,desc",
			isGrounding: ''
		},
		category: '',
		categoryList: [], //分类列表
		categoryShow: false,
		categoryName: '',
		hasAjax: false
	})
	watch(() => pageData.query.categoryId, (newval) => {
		getGoodsList()
	})
	watch(() => pageData.query.isPauseSale, (newval) => {
		getGoodsList()
	})
	watch(() => pageData.query.isGrounding, (newval) => {
		getGoodsList()
	})
	const popup = reactive({
		price: {
			show: false
		},
		guige: {
			show: false,
			data: {},
			goodsIndex: '',
			guigeIndex: '',
		},
		stock: {
			show: false
		},
		baosun: {
			show: false
		}
	})

	//报损弹窗展示
	function baosunShow(index) {
		pageData.selGoodsIndex = index
		const goods = pageData.goodsList[index]
		pageData.selGoods = goods
		popup.baosun.show = true
	}

	// 修改价格弹窗展示
	function changePriceShow(index) {
		pageData.selGoodsIndex = index
		const goods = pageData.goodsList[index]
		goods.skuList = goods.skuList.map(v => {
			return {
				...v,
				_lowPrice: v.lowPrice
			}
		})
		const lowPrice = goods.lowPrice.replace('￥', '') * 1
		pageData.selGoods = {
			...goods,
			lowPrice,
			_lowPrice: lowPrice
		}
		popup.price.show = true
	}




	async function changePriceConfirm(goods) {
		let goodsArr = []
		if (goods.typeEnum == '单规格') {
			goodsArr = [{
				shopId: uni.getStorageSync('shopId'),
				isSku: false,
				id: goods.id,
				key: 'salePrice',
				value: goods.lowPrice
			}]
		} else {
			goodsArr = goods.skuList.map(v => {
				return {
					shopId: uni.getStorageSync('shopId'),
					isSku: true,
					id: v.id,
					key: 'salePrice',
					value: v.lowPrice
				}
			})
		}
		const res = await $updateProductData(goodsArr)
		infoBox.showToast('修改成功')
		popup.price.show = false
		getGoodsList()
	}


	// 修改库存弹窗展示
	async function changeStockShow(index) {
		const res = await hasPermission('允许修改商品库存')
		if (!res) {
			return
		}
		pageData.selGoodsIndex = index
		const goods = pageData.goodsList[index]
		goods.skuList = goods.skuList.map(v => {
			return {
				...v,
				_stockNumber: v.stockNumber
			}
		})
		const stockNumber = goods.stockNumber
		pageData.selGoods = {
			...goods,
			stockNumber,
			_stockNumber: stockNumber
		}
		popup.stock.show = true
	}
	async function changeStockConfirm(goods) {
		let goodsArr = []
		// if (goods.typeEnum == '单规格') {
		// 	goodsArr = [{
		// 		shopId: uni.getStorageSync('shopId'),
		// 		isSku: false,
		// 		id: goods.id,
		// 		key: 'stockNumber',
		// 		value: goods.stockNumber
		// 	}]
		// } else {
		// 	goodsArr = goods.skuList.map(v => {
		// 		return {
		// 			shopId: uni.getStorageSync('shopId'),
		// 			isSku: true,
		// 			id: v.id,
		// 			key: 'stockNumber',
		// 			value: v.stockNumber 
		// 		}
		// 	})
		// }
		goodsArr = [{
			shopId: uni.getStorageSync('shopId'),
			isSku: false,
			id: goods.id,
			key: 'stockNumber',
			value: goods.stockNumber
		}]
		const res = await $updateProductData(goodsArr)
		infoBox.showToast('修改成功')
		popup.stock.show = false
		getGoodsList()
	}

	//修改规格上下架，售罄
	function editGuigeShow(goodsIndex, guigeIndex) {
		console.log(goodsIndex, guigeIndex);
		const goodsGuige = pageData.goodsList[goodsIndex].skuList[guigeIndex]
		popup.guige.data = goodsGuige
		popup.guige.goodsIndex = goodsIndex
		popup.guige.guigeIndex = guigeIndex
		popup.guige.show = true
	}

	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 setCategory(category) {
		pageData.query.categoryId = category.id
		pageData.categoryName = category.name
	}

	function getGoodsList() {
		pageData.hasAjax = false
		$tbProductV2(pageData.query).then(res => {
			pageData.hasAjax = true
			console.log(res);
			pageData.goodsList = res.content.map(v => {
				return {
					...v,
					isSellNone: false,
					checked: false,
					showDetail: false
				}
			})
			pageData.totalElements = res.totalElements
		})
	}

	function watchEmitInit() {
		uni.$off('update:productIndex')
		uni.$off('del:productIndex')
		uni.$on('update:productIndex', (data) => {
			getGoodsList()
		})
		uni.$on('del:productIndex', (productId) => {
			if(pageData.goodsList.length<=1){
				pageData.query.page-=1
			}
			getGoodsList()
		})

	}
	onShow(() => {
		// getGoodsList()
		watchEmitInit()
	})
	onLoad(() => {
		getGoodsList()
		$tbShopCategory({
			page: 0,
			size: 200
		}).then(res => {
			pageData.categoryList = returnAllCategory(res.content)
			console.log(pageData.categoryList);
		})
	})

	const tabsList = ['简洁', '详情']
	const statesTabsList = ['全部', '已售罄', '在售中', '已下架']
	const control = ref(null)
	const model = ref(null)
	const goodsStockModel = ref(null)
	let reportDamage = ref(null) //报损组件
	// 商品报损
	function reportDamageClick(index) {
		pageData.reportData = pageData.goodsList[index]
		reportDamage.value.open();
	}

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

	function goodsStockModelClose() {
		console.log('goodsStockModelClose');
		goodsStockData = returnGoodsStockData()
	}

	function goodsStockModelCancel() {
		console.log('goodsStockModelCancel');
		goodsStockModel.value.close()
		goodsStockData = returnGoodsStockData()
	}

	async function goodsStockModelSave() {
		const item = pageData.goodsList[pageData.selGoodsIndex]
		const goods = await $getProductDetail(item.id, false)
		$updateProduct({
			...goods,
			sort: goodsStockData.sort,
			isStock: goodsStockData.isStock
		}).then(res => {
			item.sort = goodsStockData.sort
			item.isStock = goodsStockData.isStock
			item.stockNumber = goodsStockData.stockNumber
			goodsStockModelCancel()
		})
	}



	//点击修改按钮弹出修改商品弹窗
	function goodsChangeClick(index) {
		pageData.selGoodsIndex = index
		const goods = pageData.goodsList[index]
		Object.assign(goodsStockData, goods)
		goodsStockModel.value.open()
	}

	//删除商品
	function goodsDel(index) {
		const goods = pageData.goodsList[index]
		uni.showModal({
			title: '提示',
			content: '确认删除该商品',
			success: function(res) {
				if (res.confirm) {
					$delProduct([goods.id]).then(res => {
						uni.showToast({
							title: '删除成功',
							icon: 'none'
						})
						pageData.goodsList.splice(index, 1)
					})
				} else if (res.cancel) {}
			}
		});
	}

	function resetQuery() {
		pageData.totalElements = 0;
		pageData.query.page = 0;
	}

	async function toGoodsDetail(id) {
		const res = await hasPermission('允许修改商品')
		if (!res) {
			return
		}
		go.to('PAGES_PRODUCT_ADD', {
			type: 'edit',
			productId: id
		})
	}

	function statesTableClick(index) {
		pageData.stateCurrent = index;
		resetQuery()
		console.log(index);
		if (index == 0) {
			pageData.query.isPauseSale = ''
			pageData.query.isGrounding = ''
			return
		}
		if (index == 1) {
			pageData.query.isPauseSale = 1
			pageData.query.isGrounding = ''
			return
		}
		if (index == 2) {
			pageData.query.isPauseSale = ''
			pageData.query.isGrounding = 1
			return
		}
		if (index == 3) {
			pageData.query.isPauseSale = ''
			pageData.query.isGrounding = 0
			return
		}
	}
	let test = ref(false)

	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');
		resetQuery()
		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: 40rpx;

		.item {
			font-size: 24rpx;
			color: #666;
			margin-right: 30rpx;
			background: #F4F4F4;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
		}

		.item.active {
			background: #E6F0FF;
			color: $my-main-color;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
		}
	}
</style>