<!-- 底部菜单--库存--新增商品 -->
<template>
	<view class="page1">
		<view class="title">
			<view class="title-sreach">
				<view class="back-btn" @tap="back" :style="{'top': menuButtonInfo.top +'px'}">
					<uni-icons type="left" size="28"></uni-icons>
				</view>
				<view class="title-name" :style="{'padding-top': menuButtonInfo.top +'px'}">
					新增商品
				</view>
			</view>
		</view>
		<scroll-view scroll-y class="formBox" :scroll-into-view="scrollTarget" scroll-with-animation>
			<uni-forms ref="form" :modelValue="formData" :rules="rules" labelWidth="170rpx">
				<uni-forms-item label="商品名称" name="productName" required>
					<uni-easyinput type="text" v-model="formData.productName" placeholder="请输入商品名称" trim="all" />
				</uni-forms-item>
				<uni-forms-item label="商品主图" name="productPicture">
					<view class="upload-img" @tap="pictureAdd"
						style="background: rgba(247, 248, 248, 0.6);text-align: center;line-height: 160rpx;">
						<uni-icons type="camera" size="28" color="#777"></uni-icons>
					</view>
					<view style="overflow-x: scroll;display: flex;width: 350rpx;">
						<view v-if="formData.productPicture !=''" style="width: 160rpx;height: 160rpx;margin-left: 20rpx;">
							<img :src="formData.productPicture" alt="" class="upload-img">
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="排名" name="orderFiled">
					<input type="digit" class="content-input" v-model="formData.orderFiled" placeholder="请输入排名">
				</uni-forms-item>
				<uni-forms-item label="商品分类" name="editTitle">
					<view style="border: 4rpx solid #eee;display: flex;flex: 1;border-radius: 10rpx;">
						<input type="text" placeholder="请选择商品分类" disabled v-model="typeItem.categoryName"
							class="content-input" @tap="goGategoryLow" style="border: 0;">
						<uni-icons type="right" size="16"
							style="margin-left: 40rpx;line-height: 70rpx;"></uni-icons>
					</view>
				</uni-forms-item>
				<uni-forms-item label="商品价格" name="attributeListPrice">
					<view>
						<view v-for="(item,index) in formData.attributeListPrice" :key="index" style="display: flex;margin-top:10rpx;">
							<input class="content-input" v-model="item.specName" v-if="item.specName != ''&& formData.attributeListPrice.length != 1" style="padding-right: 20rpx;" disabled />
							<input type="digit" min="0.01" class="content-input" v-model="item.specPrice" style="padding-right: 20rpx;margin-right: 20rpx;" @click="changePrice(index)" placeholder="商品价格" />
							<input type="number" class="content-input" v-model="item.specNum" style="padding-right: 20rpx;" @input="changeSpecNum($event,index)" placeholder="商品库存"/>
							<button @click="deldantiaoguige(index)" v-if="formData.attributeListPrice.length>1" style="width: 240rpx;height: 60rpx;line-height: 60rpx;color: red;border:none;background: #fff;">删除</button>
						</view>
						<!-- <view @click="checkSpec('guige')" style="margin-top: 5px;width: 80px;height: 30px;text-align: center;line-height: 30px;background: rgba(0, 35, 28, 1);border-radius: 30px;color: rgba(166, 255, 234, 1);">
							选择规格
						</view> -->
					</view>
				</uni-forms-item>
				<uni-forms-item label="拼团信息" name="productGroupBuyPrices">
					<view>
						<view v-for="(item,index) in formData.productGroupBuyPrices" :key="index" style="display: flex;margin-top:10rpx;">
							<input type="number" min="2" class="content-input" v-model="item.groupCount" style="padding-right: 20rpx;margin-right: 20rpx;width: 100px;" placeholder="成团人数" />
							<input type="digit" class="content-input" v-model="item.groupPrice" style="padding-right: 20rpx;width: 100px;" placeholder="拼团价格"/>
							<view @click="delGroup(index)" v-if="formData.productGroupBuyPrices.length>1" style="width: 240rpx;height: 60rpx;line-height: 60rpx;color: red;border:none;background: #fff;">删除</view>
						</view>
						<view @click="addGroup()" style="margin-top: 10rpx;width: 160rpx;height: 60rpx;text-align: center;line-height: 60rpx;background: rgba(0, 35, 28, 1);border-radius: 60rpx;color: rgba(166, 255, 234, 1);">
							新增拼团
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="商品属性" name="attributeList1">
					<view style="display: flex;flex-direction: column;">
						<view v-for="(value,key) in Array.from(formData.attributeList1)" :key="key" style="display: flex;flex-wrap: wrap;align-items: center;margin-bottom: 10rpx;">
							{{value[0]}}(可选{{value[1].canbuy || 1}}个):
							<view v-for="(item,index) in value[1].title" :key="index">
								{{item}}、
							</view>
						</view>
						<view @click="checkSpec('shuxing')" style="width: 160rpx;height: 60rpx;text-align: center;line-height: 60rpx;background: rgba(0, 35, 28, 1);border-radius: 60rpx;color: rgba(166, 255, 234, 1);">
							选择属性
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="可售时间" name="sellTime">
					<view style="display: flex;flex-direction: column;">
						<view style="line-height: 74rpx;">
							<radio :checked="formData.sellTime==0" name="sellTime" @click="checkSellTime(0)" />全时段售卖
							<radio :checked="formData.sellTime==1" name="sellTime" @click="checkSellTime(1)" />自定义时段
						</view>
						<view style="display: flex;" v-if="formData.sellTime == 1">
							<picker mode="time" v-model="formData.sellBeginTime" start="00:00" end="23:59" @change="selectDateRange($event,'start')">
								<view class="uni-input">{{formData.sellBeginTime}}</view>
							</picker>
							<view style="width: 50rpx;height: 50rpx;line-height: 50rpx;text-align: center;">-</view>
							<picker mode="time" v-model="formData.sellEndTime" start="00:00" end="23:59" @change="selectDateRange($event,'end')">
								<view class="uni-input">{{formData.sellEndTime}}</view>
							</picker>
						</view>
					</view>
				</uni-forms-item>
				<uni-forms-item label="拼团搭配" name="isMoreBuy">
					<view style="line-height: 74rpx;">
						<radio :checked="formData.isMoreBuy==0" name="isMoreBuy" @click="checkisMoreBuy('0')" />否
						<radio :checked="formData.isMoreBuy==1" name="isMoreBuy" @click="checkisMoreBuy('1')" />是
						<view style="font-size: 24rpx;color: #999;line-height: 36rpx;">
							拼团商品下单时可搭配该商品一并下单
						</view>
					</view>
				</uni-forms-item>
				<view id="lunchBoxField" v-if="shopMerchantType == 1 && formData.isMoreBuy==0">
					<uni-forms-item label="餐盒费" name="lunchBox">
						<input type="digit" class="content-input" v-model="formData.lunchBox" placeholder="请输入餐盒费"
							:adjust-position="false" :cursor-spacing="160" @focus="focusFormField('lunchBoxField')" @blur="blurFormField">
					</uni-forms-item>
				</view>
				<view id="startPayNumField">
					<uni-forms-item label="起售数量" name="startPayNum">
						<input type="number" class="content-input" v-model="formData.startPayNum" @input="changeStartPayNum" placeholder="请输入起售数量"
							:adjust-position="false" :cursor-spacing="160" @focus="focusFormField('startPayNumField')" @blur="blurFormField">
					</uni-forms-item>
				</view>
				<uni-forms-item label="详细图文" name="startPayNum">
					<view class="xiangxi-box">
						<sp-editor
							:keys="keys" 
							@init="initEditor" 
							@input="inputOver" 
							@upinImage="upinImage" 
							@overMax="overMax">
						</sp-editor>
					</view>
				</uni-forms-item>
			</uni-forms>
			<view>
				<button @tap.stop="submit()">保存</button>
			</view>
			<view class="keyboard-safe-bottom"></view>
		</scroll-view>
		<!-- 添加分类弹出层 -->
		<uni-popup ref="addTypeDialog" background-color="#fff">
			<view class="add-popup-content">
				<view class="attr-popup-body">
					<scroll-view scroll-y class="content-left">
						<view class="left-box" v-for="(item,index) in categoryData" :key="index"
							:class="item.parentId ? 'left-box-hover':''" @tap="clickLeftBtn(index)">
							<text style="width: 100%;height: 100rpx;line-height: 100rpx;display: inline-block;overflow: hidden;"
								:class="item.parentId ? 'red' :''">{{item.title}}</text>
						</view>
					</scroll-view>
					<view class="attr-popup-right">
						<scroll-view scroll-y class="attr-value-scroll">
							<view v-for="(item,index) in categorySonData" :key="index" @tap="checkSpecValue(index)" class="content-low" :class="item.checked?'checked':''">
								{{item.title}}
							</view>
						</scroll-view>
						<view class="canbuy-box" v-if="modalclassType == 'shuxing'">
							<view class="canbuy-label">
								该分类可选数量
							</view>
							<input type="digit" class="content-input" v-model="currentCanbuy" placeholder="该分类可选几个(默认1)">
						</view>
					</view>
				</view>
				<view class="attr-popup-footer">
					<view class="attr-popup-btn plain" @tap="$refs.addTypeDialog.close()">取消</view>
					<view class="attr-popup-btn primary" @tap="guigeSubmit">提交</view>
					<view class="attr-manage-entry" v-if="modalclassType == 'shuxing'" @tap="goAttributeList">维护属性</view>
				</view>
			</view>
		</uni-popup>
		<common-loading />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				dataList: {},
				modalType:0,
				maxSelect:1,
				currentCanbuy:1,
				canbuyMap:{},
				categoryData:[],
				categoryIndex: 0,
				modalclassType:'',
				categorySonData:[],
				specValueArr:[],
				attrValueArr:[],
				scrollTarget:'',
				editorIns: null,
				typeItem: {},
				menuButtonInfo: {},
				shopMerchantType:0,
				formData: {
					id: '',
					shopId: '',
					attrId:'',
					categoryId: '', //商品分类id
					categoryName: '', //商品分类名称
					productPicture: '', //商品图标
					productName: '', //商品名称
					orderFiled: '', //商品名称
					lunchBox: 0, //餐盒
					startPayNum: '', //起售数量
					attributeListPrice: [{ //商品规格
						specPrice: "",
						specNum: 9999
					}],
					shopId:'',
					sellTime: 0, //可售时间
					isMoreBuy: 0,
					sellBeginTime: '', //可售时段自定义---开始时间
					sellEndTime: '', //可售时段自定义---结束时间
					attributeList: '',
					productGroupBuyPrices: [],
					attributeList1: new Map(), //商品属性
					productIntro: "" //详细图文
				},
				rules: {
					productName: {
						rules: [{
							required: true,
							errorMessage: '请输入名称',
						}]
					},
					categoryId: {
						rules: [{
							required: true,
							errorMessage: '请选择商品分类',
						}, ],
					},
				},
			}
		},
		filters: {

		},
		onShow() {
			this.attrId = uni.getStorageSync('attrId');
			this.shopMerchantType = uni.getStorageSync('shopMerchantType');
			this.menuButtonInfo = uni.getMenuButtonBoundingClientRect()
			uni.authorize({
				scope: 'scope.writePhotosAlbum',
				success() {
			
				},
				fail() {
					this.tui.toast("您未授权，图片上传功能可能会出现错误")
				}
			})
			this.typeItem = JSON.parse(JSON.stringify(this.typeItem)) || ''
			if (this.typeItem) {
				this.formData.categoryId = this.typeItem.id
			}
			this.formData.shopId = uni.getStorageSync('shopId')
		},
		onLoad(option) {
			this.getGategoryList()
			if (option.dataList != undefined && option.dataList != null && option.dataList != 'undefined') {
				this.dataList = JSON.parse(option.dataList)
				this.tui.request("/app/product/getById/" + this.dataList.id, "POST", {
			
				}, false, true).then((res) => {
					if (res.code == 200) {
						this.modalType = 1
						this.formData.id = res.result.id
						this.formData.shopId = res.result.shopId
						this.formData.categoryName = res.result.categoryName
						this.formData.orderFiled = res.result.orderFiled
						this.formData.lunchBox = res.result.lunchBox 
						this.formData.startPayNum = res.result.startPayNum 
						this.formData.attributeListPrice = JSON.parse(res.result.attributeListPrice)
						this.formData.shopId = res.result.shopId
						this.formData.sellTime = res.result.sellBeginTime !=''?1:0
						this.formData.isMoreBuy = res.result.isMoreBuy
						this.formData.sellBeginTime = res.result.sellBeginTime 
						this.formData.sellEndTime = res.result.sellEndTime
						this.formData.attributeList = res.result.attributeList
						this.formData.productGroupBuyPrices = res.result.productGroupBuyPrices
						this.formData.attributeList1 = new Map()
						this.formData.productName = res.result.productName
						this.formData.productPicture = res.result.productPicture
						this.formData.productIntro = res.result.productIntro
						this.formData.categoryId = res.result.categoryId
						this.edit(this.formData)
					} else {
						this.tui.toast(res.message)
					}
				}).catch((res) => {})
			}
		},
		methods: {
			/**
			 * 获取输入内容
			 * @param {Object} e {html,text} 内容的html文本，和text文本
			 */
			inputOver(e) {
				this.productIntro = e
			},
			/**
			 * 超出最大内容限制
			 * @param {Object} e {html,text} 内容的html文本，和text文本
			 */
			overMax(e) {
				// 若设置了最大字数限制，可在此处触发超出限制的回调
				console.log('==== overMax :', e)
			},
			/**
			 * 编辑器就绪
			 * @param {Object} editor 编辑器实例，你可以自定义调用editor实例的方法
			 * @tutorial editor组件 https://uniapp.dcloud.net.cn/component/editor.html#editor-%E7%BB%84%E4%BB%B6
			 * @tutorial 相关api https://uniapp.dcloud.net.cn/api/media/editor-context.html
			 */
			initEditor(editor) {
				this.editorIns = editor // 保存编辑器实例
				// 保存编辑器实例后，可以在此处获取后端数据，并赋值给编辑器初始化内容
				
			},
			/**
			 * 直接运行示例工程插入图片无法正常显示的看这里
			 * 因为插件默认采用云端存储图片的方式
			 * 以$emit('upinImage', tempFiles, this.editorCtx)的方式回调
			 * @param {Object} tempFiles
			 * @param {Object} editorCtx
			 */
			upinImage(tempFiles, editorCtx) {
				/**
				 * 本地临时插入图片预览
				 * 注意：这里仅是示例本地图片预览，因为需要将图片先上传到云端，再将图片插入到编辑器中
				 * 正式开发时，还请将此处注释，并解开下面 使用 uniCloud.uploadFile 上传图片的示例方法 的注释
				 * @tutorial https://uniapp.dcloud.net.cn/api/media/editor-context.html#editorcontext-insertimage
				 */
				// #ifdef MP-WEIXIN
				// 注意微信小程序的图片路径是在tempFilePath字段中
				editorCtx.insertImage({
					src: tempFiles[0].tempFilePath,
					width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
					success: function() {}
				})
				// #endif

				// #ifndef MP-WEIXIN
				editorCtx.insertImage({
					src: tempFiles[0].path,
					width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
					success: function() {}
				})
				// #endif

				/**
				 * 使用 uniCloud.uploadFile 上传图片的示例方法（可适用多选上传）
				 * 正式开发环境中，请将上面 本地临时插入图片预览 注释后，模仿以下写法
				 */
				// tempFiles.forEach(async (item) => {
				//   uni.showLoading({
				//     title: '上传中请稍后',
				//     mask: true
				//   })
				//   let upfile = await uniCloud.uploadFile({
				//     filePath: item.path,
				//     // 同名会导致报错 policy_does_not_allow_file_overwrite
				//     // cloudPath可由 想要存储的文件夹/文件名 拼接，若不拼文件夹名则默认存储在cloudstorage文件夹中
				//     cloudPath: `cloudstorage/${item.name}`,
				//     cloudPathAsRealPath: true
				//   })
				//   editorCtx.insertImage({
				//     src: upfile.fileID,
				//     width: '80%', // 默认不建议铺满宽度100%，预留一点空隙以便用户编辑
				//     success: function () {
				//       uni.hideLoading()
				//     }
				//   })
				// })
			},
			//跳转分类页
			goGategoryLow() {
				uni.navigateTo({
					url: '/package2/myCenter/addType'
				})
			},
			//初始化获取分类列表
			getGategoryList() {
				this.tui.request("/app/productCategory/list", "get", {
					shopId:uni.getStorageSync('shopId')
				}, false, true).then((res) => {
					if (res.code == 200) {
						if (res.result.length > 0) {
							if(this.formData.categoryId != '' && this.formData.categoryId != undefined){
								for(let i=0;i<res.result.length;i++){
									if(res.result[i].id == this.formData.categoryId){
										this.typeItem = res.result[i]
									}
								}
							}else{
								this.typeItem = res.result[0]
								this.formData.categoryId = this.typeItem.id
							}
							
						}
					} else {
						this.tui.toast(res.message)
					}
				}).catch((res) => {})
			},
			// 触发提交表单
			submit() {
				let that = this;
				if (!this.validateProductSpecs()) {
					return
				}
				if (!this.validateProductNumbers()) {
					return
				}
				if (!this.validateGroupBuyPrices()) {
					return
				}
				// this.$refs.form.validate((valid) => {
				// 	if (valid) {
						if (this.modalType == 0) {
							// 添加 避免编辑后传入id等数据 记得删除
							delete this.formData.id;
							if(this.formData.isMoreBuy != 1){
								this.formData.isMoreBuy = 0
							}
							this.formData.attributeListPrice = JSON.stringify(this.formData.attributeListPrice)
							this.formData.attributeList = Object.fromEntries(this.formData.attributeList1)
							this.formData.attributeList = JSON.stringify(this.formData.attributeList)
							
							
							this.tui.request("/app/product/save", "post", this.formData, false, false).then((res) => {
								if(res.code == 200){
									that.tui.toast("操作成功");
									uni.navigateBack()
								}
							}).catch(() => {});
						} else if (this.modalType == 1) {
							// 编辑
							this.formData.attributeListPrice = JSON.stringify(this.formData.attributeListPrice)
							this.formData.attributeList = Object.fromEntries(this.formData.attributeList1)
							this.formData.attributeList = JSON.stringify(this.formData.attributeList)
							this.formData.productPictures = []
							this.tui.request("/app/product/edit", "post", this.formData, false, false).then((res) => {
								if(res.code == 200){
									that.tui.toast("操作成功");
									uni.navigateBack()
								}
							}).catch(() => {});
						}
				// 	}
				// });
			},
			back() {
				uni.navigateBack()
			},
			validateProductSpecs() {
				for (let i = 0; i < this.formData.attributeListPrice.length; i++) {
					const specPrice = String(this.formData.attributeListPrice[i].specPrice).trim()
					if (!this.isValidPrice(specPrice)) {
						this.tui.toast('商品价格必须大于0且最多2位小数')
						return false
					}
					const specNum = String(this.formData.attributeListPrice[i].specNum).trim()
					if (!this.isValidInteger(specNum)) {
						this.tui.toast('商品库存只能输入整数')
						return false
					}
				}
				return true
			},
			validateProductNumbers() {
				const lunchBox = String(this.formData.lunchBox).trim()
				if (!this.isValidAmount(lunchBox)) {
					this.tui.toast('餐盒费最多2位小数')
					return false
				}
				const startPayNum = String(this.formData.startPayNum).trim()
				if (startPayNum !== '' && !this.isValidInteger(startPayNum)) {
					this.tui.toast('起售数量只能输入整数')
					return false
				}
				return true
			},
			validateGroupBuyPrices() {
				const minSpecPrice = Math.min(...this.formData.attributeListPrice.map((item) => Number(item.specPrice)))
				for (let i = 0; i < this.formData.productGroupBuyPrices.length; i++) {
					const groupCount = Number(this.formData.productGroupBuyPrices[i].groupCount)
					if (!groupCount || groupCount < 2) {
						this.tui.toast('拼团人数不能小于2')
						return false
					}
					const groupPrice = String(this.formData.productGroupBuyPrices[i].groupPrice).trim()
					if (!this.isValidPrice(groupPrice)) {
						this.tui.toast('拼团价必须大于0且最多2位小数')
						return false
					}
					if (Number(groupPrice) >= minSpecPrice) {
						this.tui.toast('拼团价必须低于商品价格')
						return false
					}
				}
				return true
			},
			isValidPrice(value) {
				return /^\d+(\.\d{1,2})?$/.test(value) && Number(value) > 0
			},
			isValidAmount(value) {
				return /^\d+(\.\d{1,2})?$/.test(value) && Number(value) >= 0
			},
			isValidInteger(value) {
				return /^\d+$/.test(value)
			},
			changeSpecNum(e,index){
				this.formData.attributeListPrice[index].specNum = String(e.detail.value).replace(/\D/g, '')
				if (this.specValueArr[index]) {
					this.specValueArr[index].specNum = this.formData.attributeListPrice[index].specNum
				}
			},
			changeStartPayNum(e){
				this.formData.startPayNum = String(e.detail.value).replace(/\D/g, '')
			},
			focusFormField(fieldId){
				this.scrollTarget = ''
				this.$nextTick(() => {
					this.scrollTarget = fieldId
				})
			},
			blurFormField(){
				this.scrollTarget = ''
			},
			checkisMoreBuy(type){
				this.formData.isMoreBuy = type;
			},
			checkSellTime(type){
				this.formData.sellTime = type;
			},
			selectDateRange(e,type){
				if(type == 'start'){
					this.formData.sellBeginTime = e.detail.value
				}else{
					this.formData.sellEndTime = e.detail.value
				}
			},
			guigeSubmit(){
				if(this.modalclassType == 'shuxing'){
					// 保存当前分类的canbuy值
					if(this.typeToAttrName){
						this.canbuyMap[this.typeToAttrName] = parseInt(this.currentCanbuy) || 1
					}
					for(let i=0;i<this.attrValueArr.length;i++){
						let parentName = this.attrValueArr[i].parentName
						let canbuyVal = parseInt(this.canbuyMap[parentName]) || 1
						if(this.formData.attributeList1.size == 0){
							//set  has get
							let data = {
								title:[],
								canbuy: canbuyVal
							}
							data.title.push(this.attrValueArr[i].title)
							this.formData.attributeList1.set(parentName,data)
						}else{
							if(this.formData.attributeList1.has(parentName) && this.formData.attributeList1.get(parentName).title.indexOf(this.attrValueArr[i].title) == -1){
								this.formData.attributeList1.get(parentName).title.push(this.attrValueArr[i].title)
								this.formData.attributeList1.get(parentName).canbuy = canbuyVal
							}else{
								let data = {
									title:[],
									canbuy: canbuyVal
								}
								data.title.push(this.attrValueArr[i].title)
								this.formData.attributeList1.set(parentName,data)
							}
						}
					}
				}else{
					//guige
					let message = []
					for(let i=0;i<this.specValueArr.length;i++){
						for(let m=0;m<this.formData.attributeListPrice.length;m++){
							if(this.specValueArr[i].id == this.formData.attributeListPrice[m].id){
								this.specValueArr[i].specPrice = this.formData.attributeListPrice[m].specPrice
								this.specValueArr[i].specName = this.formData.attributeListPrice[m].specName
								this.specValueArr[i].specNum = this.formData.attributeListPrice[m].specNum
							}
						}
						message.push({
							id:this.specValueArr[i].id,
							specName:this.specValueArr[i].specName == undefined ? this.specValueArr[i].title : this.specValueArr[i].specName,
							specPrice:this.specValueArr[i].specPrice == undefined ? '' : this.specValueArr[i].specPrice,
							specNum:this.specValueArr[i].specNum == undefined ? 9999 : this.specValueArr[i].specNum
						})
					}
					this.formData.attributeListPrice = message
				}
				this.$forceUpdate()
				this.$refs.addTypeDialog.close()
			},
			add() {
				if (!this.selectNode.id) {
					this.$Message.warning("请先选择一个分类");
					return;
				}
				this.modalType = 0;
				this.$refs.form.resetFields();
				this.form.sort = this.data.length + 1;
				this.formData = {
					id:'',
					shopId:'',
					categoryId:'', //商品分类id
					categoryName:'', //商品分类名称
					productPicture:'', //商品图标
					productName:'', //商品名称
					lunchBox:0, //餐盒
					startPayNum:'', //起售数量
					orderFiled:'',//排名
					attributeListPrice:[{ //商品规格
						specPrice:"",
						specNum:9999
					}],
					sellTime:0, //可售时间
					sellBeginTime:'', //可售时段自定义---开始时间
					sellEndTime:'', //可售时段自定义---结束时间
					attributeList:'',
					productGroupBuyPrices:[],
					attributeList1:new Map(), //商品属性
					productIntro:"" //详细图文
				}
				this.specValueArr = []
				this.attrValueArr = []
				this.formData.shopId = this.shopId
				this.formData.categoryId = this.selectNode.id
				this.formData.categoryName = this.selectNode.categoryName
				this.modalVisible = true;
			},
			edit(v) {
				this.modalType = 1;
				// 转换null为""
				for (let attr in v) {
					if (v[attr] == null) {
						v[attr] = "";
					}
				}
				let str = JSON.stringify(v);
				let data = JSON.parse(str);
				this.formData = data;
				
				// 解析attributeList（商品属性），兼容string和已解析的对象
				let attrObj = this.formData.attributeList
				if (typeof attrObj === 'string' && attrObj !== '') {
					attrObj = JSON.parse(attrObj)
				}
				if (!attrObj || typeof attrObj !== 'object') {
					attrObj = {}
				}
				this.formData.attributeList1 = new Map(Object.entries(attrObj));
				
				// 解析attributeListPrice（商品规格价格），兼容string和已解析的数组
				let priceArr = this.formData.attributeListPrice
				if (typeof priceArr === 'string' && priceArr !== '') {
					priceArr = JSON.parse(priceArr)
				}
				if (!Array.isArray(priceArr)) {
					priceArr = [{specPrice: "", specNum: 9999}]
				}
				this.formData.attributeListPrice = priceArr
				
				// 初始化canbuyMap，历史数据没有canbuy字段的默认为1
				this.canbuyMap = {}
				this.attrValueArr = []
				this.formData.attributeList1.forEach((value, key) => {
					value.canbuy = value.canbuy || 1
					this.canbuyMap[key] = value.canbuy
					for(let i = 0;i<value.title.length;i++){
						this.attrValueArr.push({
							parentName:key,
							title:value.title[i]
						})
					}
				});
				// 深拷贝attributeListPrice作为specValueArr，避免引用问题
				this.specValueArr = JSON.parse(JSON.stringify(this.formData.attributeListPrice))
				
				
				this.formData.sellTime = this.formData.sellBeginTime != '' ? 1 : 0
				this.modalVisible = true;
			},
			checkSpecValue(index){
				this.categorySonData[index].checked = !this.categorySonData[index].checked
				if(this.modalclassType == 'shuxing'){
					if(this.categorySonData[index].checked == true){
						this.categorySonData[index].parentName = this.typeToAttrName
						this.attrValueArr.push(this.categorySonData[index])
					}else{
						for(let i=0;i<this.attrValueArr.length;i++){
							if(this.categorySonData[index].title == this.attrValueArr[i].title){
								this.attrValueArr.splice(i,1)
							}
						}
					}
				}else{
					//guige
					if(this.categorySonData[index].checked == true){
						this.specValueArr.push(this.categorySonData[index])
					}else{
						for(let i=0;i<this.specValueArr.length;i++){
							if(this.categorySonData[index].id == this.specValueArr[i].id){
								this.specValueArr.splice(i,1)
							}
						}
					}
				}
				this.$forceUpdate()
			},
			//点击左侧菜单切换
			clickLeftBtn(index) {
				// 切换前保存当前分类的canbuy
				if(this.typeToAttrName){
					this.canbuyMap[this.typeToAttrName] = parseInt(this.currentCanbuy) || 1
				}
				for (var i = 0; i < this.categoryData.length; i++) {
					if (i == index) {
						this.categoryData[i].parentId = true
					} else {
						this.categoryData[i].parentId = false
					}
				}
				this.categoryIndex = index
				this.typeToAttrName = this.categoryData[this.categoryIndex].title
				// 恢复该分类之前设置的canbuy值
				this.currentCanbuy = this.canbuyMap[this.typeToAttrName] || 1
				this.getCateGorySon(this.categoryData[this.categoryIndex].id)
			},
			pictureAdd(id, huan) {
				let that = this
				uni.chooseMedia({
					count: 9,
					mediaType: ['image'],
					sourceType: ['album', 'camera'],
					success(res) {
						uni.showLoading({
							title: '加载中...',
							mask: true
						})
						for (let i = 0; i < res.tempFiles.length; i++) {
							that.upLoadFile(res.tempFiles[i].tempFilePath)
						}
					}
				})
			},
			checkSpec(type){
				let that = this
				this.$refs.addTypeDialog.open()
				this.modalclassType = type
				that.tui.request("/app/productAttribute/selectByCategoryId", "post", {categoryId:that.attrId}, false, true).then((res) => {
					if (res.code == 200) {
						that.categoryData = res.result
						if (that.categoryData.length == 0) {
							that.categorySonData = []
							return
						}
						for (var i = 0; i < that.categoryData.length; i++) {
							that.categoryData[i].title = that.categoryData[i].attributeName
							if (i == that.categoryIndex) {
								that.categoryData[i].parentId = true
							} else {
								that.categoryData[i].parentId = false
							}
						}
						//如果是选择属性，需要拿一个分类名，保存成parent
						that.typeToAttrName = res.result[that.categoryIndex].title
						// 恢复该分类之前设置的canbuy值
						that.currentCanbuy = that.canbuyMap[that.typeToAttrName] || 1
						that.getCateGorySon(res.result[that.categoryIndex].id)
					} else {
						this.tui.toast(res.message)
					}
				}).catch((res) => {})
			},
			getCateGorySon(id){
				let that = this
				that.tui.request("/app/productAttributeValue/selectByAttributeId", "get", {
					id: id,
				}, false, true).then((res) => {
					if (res.code == 200) {
						that.categorySonData = res.result
						for (var i = 0; i < that.categorySonData.length; i++) {
							that.categorySonData[i].title = that.categorySonData[i].value
							that.$set(that.categorySonData[i], 'checked', false)
						}
						if(that.modalclassType == 'shuxing'){
							for (var i = 0; i < that.categorySonData.length; i++) {
								for (var m = 0; m < that.attrValueArr.length; m++) {
									if(that.attrValueArr[m].title == that.categorySonData[i].title && that.attrValueArr[m].parentName == that.typeToAttrName){
										that.$set(that.categorySonData[i], 'checked', true)
									}
								}
							}
						}else{
							//guige
							for (var i = 0; i < that.categorySonData.length; i++) {
								for (var m = 0; m < that.specValueArr.length; m++) {
									if(that.specValueArr[m].id == that.categorySonData[i].id){
										that.$set(that.categorySonData[i], 'checked', true)
									}
								}
							}
						}
						that.$forceUpdate(that.categorySonData)
						that.$forceUpdate(that.categoryData)
					} else {
						uni.showToast({
							title: "删除失败",
							icon: 'none'
						})
					}
				}).catch((res) => {})
			},
			deldantiaoguige(index){
				for (var m = 0; m < this.specValueArr.length; m++) {
					if(this.specValueArr[m].id == this.formData.attributeListPrice[index].id){
						this.specValueArr.splice(m,1)
						this.formData.attributeListPrice.splice(index,1)
						if(this.formData.attributeListPrice.length == 1){
							this.formData.attributeListPrice = []
							this.formData.attributeListPrice.push({
								specName:"",
								specPrice:'',
								specNum:9999
							})
							this.specValueArr = []
						}
						this.$forceUpdate()
						return
					}
				}
			},
			delGroup(index){
				this.formData.productGroupBuyPrices.splice(index,1)
			},
			changePrice(index){
				this.specValueArr[index].specPrice = this.formData.attributeListPrice[index].specPrice
			},
			changeCount(index){
				this.specValueArr[index].specNum = this.formData.attributeListPrice[index].specNum
			},
			addGroup(){
				let data = {
					groupCount:'',
					groupPrice:''
				}
				this.formData.productGroupBuyPrices.push(data)
			},
			goAttributeList(){
				this.$refs.addTypeDialog.close()
				uni.navigateTo({
					url: '/package2/myCenter/attributeList'
				})
			},
			async upLoadFile(path) {
				let that = this;
				let hiver_token = uni.getStorageSync("hiver_token")
				await uni.uploadFile({
					url: that.tui.interfaceUrl() + '/upload/file',
					filePath: path,
					name: 'file',
					header: {
						"content-type": "multipart/form-data",
						'accessToken': hiver_token
					},
					formData: {},
					success: (uploadFileRes) => {
						let pathData = JSON.parse(uploadFileRes.data)
						that.formData.productPicture = pathData.result
						that.$forceUpdate()
					},
					fail: (err) => {
						uni.hideLoading();
						uni.showToast({
							title: JSON.stringify(err),
							icon: 'none'
						})
					}
				});
				await setTimeout(res => {
					uni.hideLoading();
				}, 1000)
			}
		}
	}
</script>

<style lang="scss">
	page {
		width: 100%;
		height: 100%;
		font-size: 24rpx;
		background: #F5F8F5;
		color: #00231C;
		overflow: hidden;
	}

	.page1 {
		width: 100%;
		height: 100vh;
		font-size: 24rpx;
		position: relative;
		overflow: hidden;
	}

	.title {
		background: url('https://jewel-shop.oss-cn-beijing.aliyuncs.com/8bc15960c2dc40268e295d6dd23aecce.png') no-repeat;
		width: 100%;
		height: 54%;
		position: fixed;
		top: 0;
		left: 0;
	}

	.title-sreach {
		width: 100%;
		display: flex;
		height: 200rpx;
		position: relative;
	}

	.back-btn {
		position: absolute;
		bottom: 0;
		left: 0;
	}

	.title-name {
		padding-top: 110rpx;
		font-size: 36rpx;
		font-weight: 700;
		flex: 1;
		text-align: center;
	}

	.formBox {
		padding: 20rpx 26rpx;
		border-radius: 14rpx;
		box-shadow: 0 1px 20rpx 4rpx #e2e2e2;
		background-color: #fff;
		position: fixed;
		top: 200rpx;
		left: 2.5%;
		width: 95%;
		bottom: 30rpx;
		box-sizing: border-box;
		overflow-y: scroll;
	}

	.upload-img {
		width: 160rpx;
		height: 160rpx;
	}

	button {
		height: 90rpx;
		line-height: 90rpx;
		font-size: 36rpx;
		background: linear-gradient(90deg, rgba(227, 255, 150, 1), rgba(166, 255, 234, 1));
		border-radius: 20rpx;
		font-weight: 700;
		flex: 1;
	}

	.content-input {
		width: auto;
		position: relative;
		overflow: hidden;
		flex: 1;
		line-height: 70rpx;
		font-size: 28rpx;
		height: 70rpx;
		border: 4rpx solid #eee;
		padding-left: 20rpx;
		border-radius: 10rpx;
		box-sizing: border-box;
		min-width: 0;
	}
	.keyboard-safe-bottom {
		height: 260rpx;
	}

	.add-popup-content {
		width: 660rpx;
		max-width: 92vw;
		height: 78vh;
		background-color: #fff;
		overflow: hidden;
		border-radius: 24rpx;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
	}
	.attr-popup-body {
		flex: 1;
		min-height: 0;
		display: flex;
	}
	.attr-popup-right {
		flex: 1;
		min-width: 0;
		display: flex;
		flex-direction: column;
		padding: 20rpx;
		box-sizing: border-box;
	}
	.attr-value-scroll {
		flex: 1;
		min-height: 0;
	}
	.canbuy-box {
		flex-shrink: 0;
		padding-top: 18rpx;
		background: #fff;
	}
	.canbuy-label {
		font-size: 28rpx;
		line-height: 56rpx;
		font-weight: 700;
		color: #00231C;
	}
	.attr-popup-footer {
		flex-shrink: 0;
		display: flex;
		flex-wrap: wrap;
		gap: 18rpx;
		padding: 18rpx 28rpx 26rpx;
		box-sizing: border-box;
		background: #fff;
		box-shadow: 0 -8rpx 24rpx rgba(0, 0, 0, 0.04);
	}
	.attr-popup-btn {
		flex: 1;
		height: 82rpx;
		line-height: 82rpx;
		text-align: center;
		border-radius: 82rpx;
		font-size: 30rpx;
		font-weight: 700;
		box-sizing: border-box;
	}
	.attr-popup-btn.plain {
		background: #F7F8F8;
		color: #00231C;
	}
	.attr-popup-btn.primary {
		background: linear-gradient(90deg, rgba(227, 255, 150, 1), rgba(166, 255, 234, 1));
		color: #00231C;
	}
	.attr-manage-entry {
		width: 100%;
		height: 78rpx;
		line-height: 78rpx;
		margin: 0;
		text-align: center;
		border-radius: 78rpx;
		border: 2rpx solid rgba(0, 35, 28, 0.18);
		color: #00231C;
		font-size: 28rpx;
		font-weight: 700;
		background: rgba(166, 255, 234, 0.2);
		box-sizing: border-box;
	}
	.xiangxi-box{
		flex: 1;
		border: 1px solid #eee;
		border-radius: 20rpx;
	}
	.left-box {
		width: 100%;
		height: 100rpx;
		font-size: 28rpx;
		text-align: center;
		line-height: 100rpx;
		border-bottom: 1px solid #fff;
	}
	
	.left-box-hover {
		width: 100%;
		height: 100rpx;
		font-size: 28rpx;
		text-align: center;
		line-height: 50rpx;
		border-bottom: 1px solid #fff;
		background-color: #fff;
	}
	.content-left {
		width: 160rpx;
		background: rgba(247, 248, 248, 0.6);
		height: 100%;
		scrollbar-width: none;
	}
	.content-low{
		height: 60rpx;
		padding: 0 10rpx;
		border: 1px solid #eee;
		display: inline-block;
		margin: 10rpx;
		font-weight: bold;
		line-height: 60rpx;
	}
	.checked{
		background: #60F3FF;
		color: #fff !important;
	}
	.uni-input{
		width: 200rpx;
		height: 50rpx;
		line-height: 50rpx;
		border-radius: 10rpx;
		border: 1px solid #eee;
		text-align: center;
	}
</style>