<template>
	<view class="page u-font-24 color-333">
		<view class="box ">
			<view>
				<uni-forms :model="FormData" :rules="rules" err-show-type="undertext" validateTrigger="blur" ref="form"
					:border="true" :label-width="130">
					<view class="block">
						<view class="border-top-0">
							<uni-forms-item label="选择规格" required name="categoryId">
								<uni-data-picker :clear-icon="false" @change="specIdChange"
									:map="{text:'name',value:'id'}" placeholder="请选择规格" popup-title="请选择规格"
									:localdata="FormData.specList" v-model="FormData.specId">
								</uni-data-picker>
							</uni-forms-item>
						</view>
						<view class="">
							<view class="u-m-t-32" v-for="(item,index) in FormData.selectSpec" :key="index">
								
								<view class="font-bold">
									{{item.name}}
								</view>
								
								<view class="u-m-t-24">
									<uni-data-checkbox @change="createResult" multiple :selectedColor="color.ColorMain"
										v-model="item.selectSpecResult" :localdata="item.value"></uni-data-checkbox>

								</view>

							</view>
						</view>
					</view>
					
					<!-- <view class="block u-m-b-32 u-p-30">
						<view class="font-bold">批量修改</view>
						<view class="u-flex  fast-edit u-flex-wrap gap-20 u-m-t-12">
							<view  class="color-main item u-flex u-row-center u-col-center" v-for="(item,index) in fastEdit.list" :key="index">
								<view class="u-flex u-col-center">
									<view class="u-m-r-12">{{item.text}}</view>
									<up-icon size="16" :color="color.ColorMain"  name="edit-pen"></up-icon>
								</view>
							</view>
							
						</view>
					</view> -->
					<view>
						<view class="block u-m-b-32" v-for="(item,index) in FormData.result" :key="index">
							
							<view class="">
								<view class="u-m-t-16" v-for="(val,key) in item.names" :key="key">
									<text class="font-bold u-m-r-12">
										{{key}}
									</text>
									<text class="color-999">{{val}}</text>
								</view>
							</view>
							<view class="u-m-t-24">
								<view  label="">
									<view class="font-bold">
										图片
									</view>	
									<view class="u-m-t-24">
										<my-upload-file @change="changeResultCover($event,index)" :limit="1" :ref="setRefFile(index)" :images="item.coverImg"></my-upload-file>
									</view>	
									<!-- <uni-file-picker v-model="FormData.images" file-mediatype="image" mode="grid"
										:limit="10" @progress="FileUploadprogress" @success="FileUploadsuccess"
										@fail="FileUploadail" @select="FileUploadselect" /> -->
								</view>
							</view>
							<view class="skus u-m-t-32">
								<view class="">
									<uni-forms-item label="售价" required>
										<uni-easyinput @blur="priceFormat(item.skus,'salePrice')"
											:paddingNone="inputPaddingNone" :placeholderStyle="placeholderStyle"
											:inputBorder="inputBorder" v-model="item.skus.salePrice" type="digit"
											placeholder="请输入售价（元）" />
									</uni-forms-item>
								</view>

								<uni-forms-item label="会员价（元）" required>
									<uni-easyinput @blur="priceFormat(item.skus,'memberPrice')"
										:paddingNone="inputPaddingNone" :placeholderStyle="placeholderStyle"
										:inputBorder="inputBorder" v-model="item.skus.memberPrice" type="digit"
										placeholder="请输入会员价（元）" />
								</uni-forms-item>
								<uni-forms-item label="成本价（元）" required>
									<uni-easyinput @blur="priceFormat(item.skus,'costPrice')"
										:paddingNone="inputPaddingNone" :placeholderStyle="placeholderStyle"
										:inputBorder="inputBorder" v-model="item.skus.costPrice" type="digit"
										placeholder="请输入成本价（元）" />
								</uni-forms-item>
								<uni-forms-item label="原价（元）" required>
									<uni-easyinput @blur="priceFormat(item.skus,'originPrice')"
										:paddingNone="inputPaddingNone" :placeholderStyle="placeholderStyle"
										:inputBorder="inputBorder" v-model="item.skus.originPrice" type="digit"
										placeholder="请输入原价（元）" />
								</uni-forms-item>
								<uni-forms-item label="起售数量" required>
									<uni-easyinput @blur="priceFormat(item.skus,'suit')" :paddingNone="inputPaddingNone"
										:placeholderStyle="placeholderStyle" :inputBorder="inputBorder"
										v-model="item.skus.suit" type="digit" placeholder="请输入起售数量" />
								</uni-forms-item>
								<uni-forms-item label="库存数量" required>
									<uni-easyinput @blur="priceFormat(item.skus,'stockNumber')"
										:paddingNone="inputPaddingNone" :placeholderStyle="placeholderStyle"
										:inputBorder="inputBorder" v-model="item.skus.stockNumber" type="digit"
										placeholder="请输入库存数量" />
								</uni-forms-item>
								<uni-forms-item label="分销金额" required>
									<uni-easyinput @blur="priceFormat(item.skus,'firstShared')"
										:paddingNone="inputPaddingNone" :placeholderStyle="placeholderStyle"
										:inputBorder="inputBorder" v-model="item.skus.firstShared" type="digit"
										placeholder="请输入分销金额" />
								</uni-forms-item>
								<uni-forms-item label="商品条码" required>
									<uni-easyinput disabled :paddingNone="inputPaddingNone"
										:placeholderStyle="placeholderStyle" :inputBorder="inputBorder"
										v-model="item.skus.barCode" placeholder="请输入商品条码" />
								</uni-forms-item>
							</view>
						</view>
					</view>
				</uni-forms>
			</view>

			<view class="save-btn-box">
				<button class="save-btn" hover-class="btn-hover-class" @click="save">保存</button>
				<button class="save-btn edit-btn" hover-class="btn-hover-class" @click="fastEditShow">
					<view class="u-flex u-row-center">
						<view class="u-m-r-6">批量修改</view>
						<up-icon name="edit-pen" :color="color.ColorMain"></up-icon>
					</view>
				</button>
			</view>
		</view>
		<view class="bottom" ref="bottom"></view>
		
		<pop-fast-edit @update="updateSkuKey"  v-model:show="fastEdit.show"></pop-fast-edit>
	</view>
</template>
<script setup>
	import myUploadFile from '@/components/my-components/my-upload-file'
	import {
		formatPrice
	} from "@/commons/utils/format.js";
	import popFastEdit from "./components/fast-edit.vue"
	const refFiles = ref([]);
	//绑定文件上传元素
	function setRefFile(index) {
		refFiles.value[index] = null;
		return (el) => {
			if (el) {
				refFiles.value[index] = el;
			}
		};
	}
	
	const fastEdit=reactive({
		show:false,
		list:[
			{text:'会员价',key:'memberPrice',value:''},
			{text:'成本价',key:'costPrice',value:''},
			{text:'原价',key:'originPrice',value:''},
			{text:'起售数量',key:'suit',value:''},
			{text:'库存数量',key:'stockNumber',value:''},
			{text:'分销金额',key:'firstShared',value:''}
		],
		sel:''
	})
	function fastEditShow(){
		fastEdit.show=true
	}
	//上个页面传来的参数
	let option={}
	
	
	
	//number类型数据限制
	function priceFormat(item, key) {
		nextTick(() => {
			const min = 0;
			const max = 100000000;
			console.log(item[key]);
			const newval = formatPrice(item[key], min, max, true)
			if (typeof newval !== 'number') {
				item[key] = newval.value
				uni.showToast({
					title: `请输入${min}到${max}范围内的数字`,
					icon: 'none'
				})
			} else {
				item[key] = newval
			}
		})
	}

	import dayjs from "dayjs";
	import go from '@/commons/utils/go.js';
	import color from '@/commons/color.js';
	import {
		$defaultSku
	} from '../goodsData.js'
	import {
		$productSpec
	} from '@/http/yskApi/goods.js';
	import {
		onLoad,
		onReady
	} from '@dcloudio/uni-app';
	import {
		onMounted,
		reactive,
		nextTick,
		ref,
		onBeforeMount,
		watch
	} from 'vue';

	function updateSkuKey(arr){
		for(let i in FormData.result){
			const sku=FormData.result[i].skus
			for(let k in arr){
				const item=arr[k]
				if(sku.hasOwnProperty(item.key)){
					sku[item.key]=item.value
				}
			}
			
		}
	}
	
	const inputPaddingNone = ref(true)
	const form = ref(null)
	const originSpecMap={}
	const FormData = reactive({
		specId: '',
		specItem: '',
		result: [],
		selectSpec: [],
	})
	//表单相关事件
	function changeResultCover(val,index) {
		FormData.result[index].coverImg=val
		console.log(FormData.result[index]);
	}
	
	watch(() => FormData.specId, (newval) => {
		FormData.result = []
	})
	const bottom = ref(null)
	// 表单样式
	const placeholderStyle = ref('font-size:28rpx;')
	//表单边框
	const inputBorder = ref(false)

	//生成笛卡尔集

	function combineSpecs(specs) {
		if (specs.length === 0) {
			return [
				[]
			];
		} else {
			const [head, ...tail] = specs;
			const rest = combineSpecs(tail);
			const pairs = head.value.map(value => rest.map(r => {
				return {
					[head.name]: value,
					...r
				}
			}));
			return [].concat(...pairs);
		}
	};
	const defaultSku = reactive({
		...$defaultSku,
		shopId:uni.getStorageSync('shopId'),
		coverImg:'',
		productId:option.productId,
		barCode: `${uni.getStorageSync("shopId")}${dayjs().valueOf()}`
	})
	
	function returnDefaultSku(){
		const randomNumber=Math.floor(Math.random()*1000)
		return {
			...defaultSku,
			productId:option.productId,
			barCode: `${uni.getStorageSync("shopId")}${dayjs().valueOf()-randomNumber}`
		}
	}
	
	function createResult() {
		let arr = []
		for (let k of FormData.selectSpec) {
			if (k.selectSpecResult.length) {
				arr.push({
					value: k.selectSpecResult,
					name: k.name
				})
			}
		}
		const spes = combineSpecs(arr)
		FormData.result = spes.filter(v => {
			return !Array.isArray(v)
		}).map(v => {
			const specSnap=returnSpecSnap(v)
			const data= originSpecMap[specSnap]
			const skus=returnDefaultSku()
			const newdata={
				names: v,
				specSnap,
				skus
			}
			return data||newdata
		})
		console.log(FormData.result);
	}
	
	

	function specIdChange(e) {
		console.log(e);
		const item = FormData.specList.find(v => v.id === FormData.specId)
		FormData.selectSpec = (item.specList || [])

	}
	//获取规格数据
	function getTbProductSpec() {
		$productSpec.get({
			page: 0,
			size: 200,
			sort: "id"
		}).then(res => {
			FormData.specList = res.content.map(item => {
				return {
					...item,
					specList: item.specList.map(spe => {
						return {
							...spe,
							selectSpecResult: [],
							value: spe.value.map(v => {
								return {
									text: v,
									value: v
								}
							})
						}
					})
				}
			})
		})
	}


	//表单验证
	const rules = {
		optionPrice: {
			rules: [{
				required: true,
				errorMessage: '必填'
			}]
		}
	}




	//页面滚动到最底部
	function scrollPageBottom() {
		nextTick(() => {
			uni.pageScrollTo({
				duration: 100, // 过渡时间
				scrollTop: 100000, // 滚动的实际距离
			})
		})
	}





	let emitName = ''

	function triggerEvent(emitName, data) {
		if (emitName) {
			uni.$emit(emitName, data)
		}
	}
	
	
	//生成name
	function returnSpecSnap(names){
		const specSnap=Object.keys(names).reduce((prve,cur)=>{
			return prve+names[cur]+','
		},'')
		return specSnap.substring(0,specSnap.length-1)
	}
	
	
	onLoad(opt => {
		getTbProductSpec()
		const obj = uni.getStorageSync('guige')
		if (obj&&JSON.stringify(obj) !== '{}') {
			console.log(obj.selectSpec);
			option.productId=opt.productId
			Object.assign(FormData, obj)
			for(let i of obj.result){
				const key=returnSpecSnap(i.names)
				originSpecMap[key]=i
			}
			nextTick(() => {
				FormData.result = obj.result
				console.log(FormData.result);
			})
		}
		console.log(opt);
		if (opt && JSON.stringify(opt) !== '{}' && opt.emitName) {
			emitName = opt.emitName
		}

	})

	function emitspecificationsSave() {
		// emitspecificationsSave  触发规格保存事件将数据给到添加商品页面
		// guigeEdit  触发规格保存事件将数据给到添加规格页面
		uni.removeStorageSync('guige')
		triggerEvent(emitName, FormData)
		go.back()
	}

	function returnPromise(prosise) {
		return new Promise((resolve, reject) => {
			prosise.then(res => {
				console.log(res);
				resolve({
					sucees: true
				})
			}).catch(err => {
				console.log(err);
				resolve({
					sucees: false
				})
			})
		})
	}
	async function save() {
		let isAllPassForm = 0
		const res = await returnPromise(form.value.validate())
		//判断验证是否通过
		if (res.sucees) {
			console.log('pass');
			console.log(FormData);
			emitspecificationsSave()
		}

	}
</script>
<style scoped>
	page {
		background: #F9F9F9;
	}
</style>
<style lang="scss" scoped>
	$icon-size: 34rpx;
	$icon-line-width: 20rpx;
	$icon-line-height: 4rpx;

	::v-deep.uni-forms-item__content {
		margin: auto;
	}

	::v-deep.uni-forms-item {
		min-height: inherit;
	}

	.page {
		background: #F9F9F9;
		padding: 30rpx;
		padding-bottom: 200rpx;
	}

	.my-switch {
		transform: scale(0.7);
	}

	::v-deep .uni-forms-item__error {
		display: none !important;
	}

	::v-deep .option .uni-forms-item {
		padding: 0;
		min-height: inherit;
		background-color: transparent;
		border-top: none;
	}

	.icon {
		width: $icon-size;
		height: $icon-size;
		position: relative;
		border-radius: 50%;

		&:before,
		&::after {
			position: absolute;
			display: block;
			content: '';
			background-color: #fff;
		}
	}

	.icon-add {
		background-color: $my-main-color;

		&::before {
			width: $icon-line-height;
			height: $icon-line-width;
			top: calc(($icon-size /2) - ($icon-line-width / 2));
			left: calc(($icon-size /2) - ($icon-line-height / 2));
		}

		&::after {
			width: $icon-line-width;
			height: 4rpx;
			top: calc(($icon-size /2) - ($icon-line-height / 2));
			left: calc(($icon-size /2) - ($icon-line-width / 2));
		}
	}

	.icon-reduce {
		background-color: $my-red-color;

		&::after {
			width: $icon-line-width;
			height: $icon-line-height;
			top: calc(($icon-size /2) - ($icon-line-height / 2));
			left: calc(($icon-size /2) - ($icon-line-width / 2));
		}
	}

	.label-title {
		font-size: 28rpx;
		font-weight: bold;
		font-family: Source Han Sans CN, Source Han Sans CN;
	}

	.lh40 {
		line-height: 40rpx;
	}

	.box {
		margin-top: 70rpx;
		font-size: 28rpx;

		.block {
			background: #FFFFFF;
			border-radius: 18rpx 18rpx 18rpx 18rpx;
			padding: 12rpx 24rpx;
			margin-bottom: 32rpx;
		}
	}

	.save-btn-box {
		position: fixed;
		left: 30rpx;
		right: 30rpx;
		bottom: 60rpx;
		z-index: 100;
	}

	::v-deep.uni-forms-item {
		align-items: inherit;
	}

	::v-deep .uni-forms-item .uni-forms-item__label {
		text-indent: 0;
		font-size: 28rpx !important;
		font-weight: bold;
		color: #333;
	}

	::v-deep .border-top-0 .uni-forms-item.is-direction-top {
		border-color: transparent !important;
	}

	.save-btn {
		background-color: $my-main-color;
		color: #fff;
		border-radius: 12rpx;
		font-size: 28rpx;
	}
	.edit-btn{
		background-color: #fff;
		color: #333;
		border-radius: 12rpx;
		font-size: 28rpx;
	}
	.btn-hover-class {
		opacity: .6;
	}

	.zuofa {
		padding: 28rpx 0;
		background: #F9F9F9;
		padding-left: 42rpx;
		border-radius: 14rpx 14rpx 14rpx 14rpx;
	}
	.fast-edit{
		.item{
			color: #333;
			border: 1px solid #bbb;
			padding: 4rpx 10rpx 8rpx 10rpx;
			border-radius: 10rpx;
			min-width: 186rpx;
			&.active{
				color: $my-main-color;
			}
		}
	}
	::v-deep .uni-input-placeholder {
		font-size: 28rpx;
	}

	.option {
		padding: 26rpx 30rpx 24rpx 24rpx;
		background: #F9F9F9;
	}

	.option-item {
		margin-bottom: 34rpx;
	}
</style>