<template>
	<view class="safe-page min-page">
		<up-sticky>
			<view class="bg-fff u-p-l-30   u-p-b-30">
				<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 pageData.statesTabsList" :key="index">
							{{item.laber}}
						</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" @edit="toGoodsDetail"
					@radioClick="radioClick"
						@editStock="changeStockShow" @guigeClick="editGuigeShow" @baosun="baosunShow" :index="index"
						:showChecked="showChecked" :data="item" :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" :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"
			@allCheckedChange="allCheckedChange" :bottom="pageData.componentBottom"></my-control>


		<!-- 下架弹窗 -->
		<my-model :desc="pageData.modelDesc" ref="model" @confirm="modelConfirm"></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"
			@save="getGoodsList"></baosun-vue>
	</view>

</template>

<script setup>
	import {
		onLoad,
		onShow
	} 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 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 {
		getProductPage,
		getCategoryList,
		updateProduct,
		productModifyStock
	} from '@/http/api/product.js'

	import {
		returnAllCategory
	} from '@/pageProduct/util.js'

	const showChecked = ref(false)
	
	function radioClick(index){
		pageData.goodsList[index].checked=!pageData.goodsList[index].checked
	}

	function allCheckedChange(e) {
		showChecked.value = e
	}

	const pageData = reactive({
		modelDesc: '是否下架',
		stateCurrent: 0,
		componentBottom: 45,
		search: {
			value: '',
			placeholder: '输入搜索的商品'
		},
		statesTabsList: [{
				laber: '全部',
				value: ''
			},
			{
				laber: '已售罄',
				value: 'sold_out'
			},
			{
				laber: '在售中',
				value: 'on_sale'
			},
			{
				laber: '已下架',
				value: 'off_sale'
			},
		],
		showGoodsDetail: false,
		selGoodsIndex: '',
		selGoods: {},
		totalElements: 0,
		totalPage: 0,
		goodsList: [],
		query: {
			page: 1,
			size: 10,
			categoryId: '',
			name: '',
			orderBy: "create_time desc",
			status: '',
		},
		category: '',
		categoryList: [], //分类列表
		categoryShow: false,
		categoryName: '',
		hasAjax: false
	})
	const tabsList = ['简洁', '详情']
	const control = ref(null)
	const model = ref(null)
	watch(() => pageData.query.categoryId, (newval) => {
		getGoodsList()
	})
	watch(() => pageData.query.isSoldStock, (newval) => {
		getGoodsList()
	})
	watch(() => pageData.query.isSale, (newval) => {
		getGoodsList()
	})
	const popup = reactive({
		price: {
			show: false
		},
		guige: {
			show: false,
			data: {},
			goodsIndex: '',
			guigeIndex: '',
		},
		stock: {
			show: false
		},
		baosun: {
			show: false
		}
	})
	onShow(() => {
		// getGoodsList()
		watchEmitInit()
	})
	onLoad(() => {
		getGoodsList()
		getCategory()
	})

	/**
	 * 获取商品列表
	 */
	function getGoodsList() {
		pageData.hasAjax = false
		getProductPage(pageData.query).then(res => {
			pageData.hasAjax = true
			pageData.goodsList = res.records.map(v => {
				return {
					...v,
					isSellNone: false,
					checked: false,
					showDetail: false
				}
			})
			pageData.totalElements = res.totalRow
		})
	}

	/**
	 * 获取商品分类列表
	 */
	function getCategory() {
		getCategoryList({
			page: 1,
			size: 200
		}).then(res => {
			pageData.categoryList = returnAllCategory(res)
		})
	}

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

	/**
	 * 修改价格弹窗展示
	 * @param {Object} index
	 */
	function changePriceShow(index) {
		pageData.selGoodsIndex = index
		let goods = pageData.goodsList[index]
		console.log(goods)
		if (goods.type != 'sku') {
			goods.lowPrice = goods.skuList[0].salePrice
		}
		goods.skuList = goods.skuList.map(v => {
			return {
				...v,
				_lowPrice: v.salePrice
			}
		})
		console.log(goods)
		let lowPrice = goods.lowPrice.toString().replace('￥', '') * 1
		pageData.selGoods = {
			...goods,
			lowPrice,
			_lowPrice: lowPrice
		}
		popup.price.show = true
	}

	/**
	 * 修改价格确认
	 * @param {Object} goods
	 */
	async function changePriceConfirm(goods) {
		let goodsArr = []
		if (goods.type == 'sku') {
			goodsArr = goods.skuList.map(v => {
				return {
					shopId: uni.getStorageSync('shopId'),
					isSku: true,
					id: v.id,
					key: 'salePrice',
					value: v.lowPrice
				}
			})

		} else {
			goodsArr = [{
				shopId: uni.getStorageSync('shopId'),
				isSku: false,
				id: goods.id,
				key: 'salePrice',
				value: goods.lowPrice
			}]
		}
		const res = await updateProduct(goodsArr)
		uni.$utils.showToast('修改成功')
		popup.price.show = false
		getGoodsList()
	}

	/**
	 * 修改库存弹窗展示
	 * @param {Object} index
	 */
	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
	}

	/**
	 * 库存修改确认
	 * @param {Object} goods
	 */
	async function changeStockConfirm(goods) {
		const res = await productModifyStock({
			id: goods.id,
			stockNumber: goods.stockNumber,
			remark: goods.remark
		})
		uni.$utils.showToast('修改成功')
		popup.stock.show = false
		getGoodsList()
	}

	/**
	 * 修改规格上下架，售罄
	 * @param {Object} goodsIndex
	 * @param {Object} guigeIndex
	 */
	function editGuigeShow(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
	}

	/**
	 * 规格上下架
	 * @param {Object} e
	 */
	function isGroundingChange(e) {
		const {
			goodsIndex,
			guigeIndex
		} = popup.guige
		pageData.goodsList[goodsIndex].skuList[guigeIndex].isGrounding = e
	}

	/**
	 * 规格已售罄
	 * @param {Object} e
	 */
	function isPauseSaleChange(e) {
		const {
			goodsIndex,
			guigeIndex
		} = popup.guige
		pageData.goodsList[goodsIndex].skuList[guigeIndex].isPauseSale = e
	}

	/**
	 * 分类筛选打开
	 * @param {Object} show
	 */
	function onCategoryShowChange(show) {
		pageData.categoryShow = show
	}

	/**
	 * 分类筛选确定
	 * @param {Object} category
	 */
	function setCategory(category) {
		pageData.query.categoryId = category.id
		pageData.categoryName = category.name
	}


	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()
		})

	}

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

	/**
	 * 商品类型切换
	 * @param {Object} index
	 */
	function statesTableClick(index) {
		pageData.stateCurrent = index;
		pageData.query.status = pageData.statesTabsList[index].value
		searchFunc()
	}

	/**
	 * 搜索
	 */
	function searchFunc() {
		pageData.totalElements = 0;
		pageData.query.page = 1;
		getGoodsList()
	}

	/**
	 * 下架确认
	 */
	function modelConfirm() {
		console.log('confirm');
		model.value.close()
	}

	/**
	 * 页数改变事件
	 * @param {Object} page
	 */
	function pageChange(page) {
		pageData.query.page = page
		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>