<template>
	<lay-container style="height:700px;overflow: hidden;">
		<view class="empty-small2">
			<lay-button v-if="editDataInfo.FAddChild" size="sm" type="normal" @click="editChildData()">新增子项
			</lay-button>
			<div v-else style="margin-top:30px;"></div>
			<lay-table class="table-box240" :columns="dataColumn" id="FID" :dataSource="dataList" height="250px">
				<template v-if="dataInfoObj.FType!=10" v-slot:operator="{ data }">
					<div v-if="dataList.length>0&&dataList[0].FID">
						<lay-button size="xs" type="normal" @click="editChildData(data)">查看</lay-button>
					</div>
					<div v-else>
						<lay-button size="xs" type="normal" @click="editChildData(data)">编辑</lay-button>
						<lay-button size="xs" type="danger" @click="_deleteChildData(data)">删除</lay-button>
					</div>
				</template>
				<template v-else v-slot:operator="{ data }">
					<lay-button v-if="data.FMaterialID<1" size="xs" type="danger" @click="_dockEdit(data)">提交MDM
					</lay-button>
				</template>
			</lay-table>
		</view>
		<lay-form :model="editDataInfo" class="edit-info layui-item50 color999">
			<lay-form-item label-width="140" label="系列" prop="FFactoryCode">
				<lay-input v-model="editDataInfo.FFactoryCode"></lay-input>
			</lay-form-item>
			<lay-form-item label-width="140" label="包规代码" prop="FCode" required >
				<lay-input v-model="editDataInfo.FCode" disabled="true"></lay-input>
			</lay-form-item>
			<lay-form-item label-width="140" label="标准BOM数量(KG)" prop="FBomUnit">
				<lay-input v-model="editDataInfo.FBomUnit" dis></lay-input>
			</lay-form-item>
			<lay-form-item label-width="140" label="包装规格" prop="FSpecs">
				<lay-input v-model="editDataInfo.FSpecs"></lay-input>
			</lay-form-item>
			<lay-form-item label-width="140" label="净重(KG)" prop="FNetWeight">
				<lay-input v-model="editDataInfo.FNetWeight" @change="culGrossWeight()"></lay-input>
			</lay-form-item>
			<lay-form-item label-width="140" label="毛重(KG)" prop="FGrossWeight">
				<lay-input v-model="editDataInfo.FGrossWeight" disabled="true"></lay-input>
			</lay-form-item>
			<lay-form-item label-width="140" label="外形尺寸(MM)" prop="FSize">
				<lay-input v-model="editDataInfo.FSize" disabled="true"></lay-input>
			</lay-form-item>
			<lay-form-item label-width="140" label="体积(m³)" prop="FVolume">
				<lay-input v-model="editDataInfo.FVolume" disabled="true"></lay-input>
			</lay-form-item>
			<lay-form-item label-width="140" label="备注" prop="FCode">
				<lay-input v-model="editDataInfo.FRemark" dis></lay-input>
			</lay-form-item>
		</lay-form>
		<view class="menuBtn" v-if="dataInfoObj.FCanEdit==1&&dataInfoObj.FType!=10">
			<lay-button type="danger" @click="submitClick">提交</lay-button>
			<lay-button @click="this.$emit('cancelClick')">取消</lay-button>
		</view>
		<div class="float-clear"></div>
		<lay-layer area="800px" v-model="showEditBox" :title="(itemInfoObj.FID?'查看':'新增')+'子项'">
			<PackageItem :dataInfoObj="itemInfoObj" :taskInfoObj="dataInfoObj" @submitClick="editChildSubmit"
				@cancelClick="cancelClick"></PackageItem>
		</lay-layer>
	</lay-container>
</template>
<style scoped>
	.edit-info {
		margin: 0 28px;
		display: block;
		display: block;
		clear: both;
		float: none;
		overflow: auto;
		height: 290px;
	}

	.float-clear {
		overflow: hidden;
		display: block;
		clear: both;
		float: none;
		height: 0;
	}

	.menuBtn {
		display: block;
		text-align: center;
		width: 96%;
		margin: 10px auto;
	}

	.empty-small2 {
		max-width: 96%;
		margin: 20px auto;
		display: block;
	}

	.empty-small2>.layui-btn {
		margin-bottom: 16px;
	}

	.note {
		color: #999;
		font-size: 12px;
		margin: 12px auto 2px;
		text-align: right;
	}
</style>
<script>
	import {
		ref,
		reactive
	} from 'vue';
	import {
		getFactoryList
	} from "/src/api/api/factory";
	import {
		getPackageInfo,
		updatePackageData,
		dockMDMCode
	} from "/src/api/api/package";

	import PackageItem from "./PackageItem.vue";

	export default {
		components: {
			PackageItem
		},
		setup() {
			let dataColumn = [{
					type: "number",
					width: "40px"
				}, {
					title: "子项代码",
					key: "FCode",
					width: "170px"
				}, {
					title: "名称",
					key: "FName",
				},
				{
					title: "包材外形尺寸(长*宽*高)(mm)",
					key: "FOutSize"
				},
				{
					title: "包材重量(kg)",
					key: "FWeight",
					width: "130px"
				},
				{
					title: "数量",
					key: "FCount",
					width: "100px"
				},
				{
					title: "单位",
					key: "FUnit",
					width: "100px"
				},
				{
					title: "操作",
					key: "operator",
					width: "140px",
					customSlot: 'operator'
				}
			];
			dataColumn.forEach((item) => {
				item.align = "center";
			});
			const dataList = ref([]);
			const editDataInfo = ref({});
			const factoryList = ref([]);
			const showEditBox = ref(false);
			const itemInfoObj = ref({});
			const isNewItem = ref(false);

			return {
				editDataInfo,
				dataColumn,
				dataList,
				factoryList,
				showEditBox,
				itemInfoObj,
				isNewItem
			}
		},
		props: {
			dataInfoObj: {
				type: Object,
				default: () => {},
			}
		},
		mounted() {
			if (this.dataInfoObj.FState == 2 && this.dataInfoObj.FCanEdit == 2) {
				let operator = this.dataColumn.find(s => s.key == "operator");
				if (operator != null) this.dataColumn.pop();
			}
			//this._getFactoryList();
			this._getPackageInfo();
		},
		methods: {
			async _getFactoryList() {
				let _list = await getFactoryList();
				this.factoryList = _list.map(item => {
					return {
						'label': item.FName,
						"value": item.FID,
						"code": item.FCode
					};
				});
			},
			async _getPackageInfo() {
				let result = await getPackageInfo(this.dataInfoObj) || {};
				this.editDataInfo = result.Main || {};
				this.editDataInfo.FCode = this.editDataInfo.FCode || result.FCode || "";
				this.editDataInfo.FTeamID = this.dataInfoObj.FTeamID;
				this.dataList = result.List || [];
				this.editDataInfo.FAddChild = this.dataInfoObj.FState == 1 && this.dataInfoObj.FCanEdit == 1 && this
					.dataInfoObj.FType != 10 && !(this.dataList.length > 0 && this.dataList[0].FID)
			},
			editChildData(itemData) {
				this.isNewItem = itemData === undefined;
				this.itemInfoObj = itemData || {};
				this.showEditBox = true;
			},
			editChildSubmit(itemInfo) {
				if (this.isNewItem) {
					this.dataList.push(itemInfo);
				} else {
					Object.assign(this.itemInfoObj, itemInfo);
				}

				// 当前子项选择包规对应尺寸
				if (itemInfo.FIsPackageSize == 1) {
					// 其他子项设置为包规不对应尺寸
					this.dataList.forEach(d => {
						d.FIsPackageSize = 0;
					});

					// 判断一下当前子项输入的尺寸是不是一个合规的数学表达式
					if (this.isMathExpression(itemInfo.FOutSize)) {
						// 当前包材的外形尺寸设置为子项的外形尺寸
						this.editDataInfo.FSize = itemInfo.FOutSize;

						// 根据外形尺寸计算体积
						var volume = eval(itemInfo.FOutSize) / 1000000000;
						this.editDataInfo.FVolume = volume.toString();
					}
				}

				// 计算毛重
				this.culGrossWeight();
				this.showEditBox = false;
			},
			cancelClick(isRefresh) {
				this.showEditBox = false;
				if (isRefresh) {
					this._getPackageInfo();
				}
			},
			_deleteChildData(data) {
				let $this = this;
				layer.confirm("子项新视图也会删除，你确定要删除此子项吗？", {
					title: "提示",
					btn: [{
							text: '确定',
							callback: function(id) {
								layer.close(id);
								$this.dataList.splice($this.dataList.indexOf(data), 1);

								// 计算毛重
								$this.culGrossWeight();
							}
						},
						{
							text: '取消',
							callback: function(id) {
								layer.close(id);
							}
						}
					]
				});
			},
			async submitClick() {
				let idx = layer.load(2);
				this.editDataInfo.FTeamID = this.dataInfoObj.FTeamID;
				let postData = JSON.parse(JSON.stringify(this.editDataInfo));
				delete postData["FAddDate"];
				delete postData["FEditDate"];
				delete postData["FDeleted"];
				// let factory = this.factoryList.find(s => s.value == postData.FFactoryID)
				// postData.FFactoryCode = factory != null ? factory.FCode : "";
				postData.FChild = JSON.stringify(this.dataList);
				postData.FTaskID = this.dataInfoObj.FID;
				let result = await updatePackageData(postData) || -1;
				if (result > 0) this.$emit('cancelClick', true);
				layer.close(idx);
			},
			//只让修改名字和那几个值
			_dockEdit(data) {
				data.FIsMdm = true;
				this.isNewItem = false;
				this.itemInfoObj = data;
				this.showEditBox = true;
			},
			async _dockData(data) {
				let postData = JSON.parse(JSON.stringify(this.editDataInfo));
				if (data != undefined) {
					postData.FList = [data];
				} else {
					postData.FList = this.dataList.filter(s => s.FMaterialID < 0) || [];
				}
				if (postData.FList.length <= 0) {
					return layer.msg('没用需要提交到MDM的子项信息')
				}
				let idx = layer.load(2);
				postData.FList = JSON.stringify(postData.FList);
				postData.FTeamID = this.dataInfoObj.FTeamID;
				let result = await dockMDMCode(postData);
				this._getPackageInfo();
				layer.close(idx);
			},
			// 设置毛重
			culGrossWeight() {
				// 计算子项重量
				var grossWeight = 0;
				console.log('this.dataList.length', this.dataList.length);
				if (this.dataList.length > 0) {
					this.dataList.forEach(d => {
						var weight = parseFloat(d.FWeight);
						if (!isNaN(weight)) {
							grossWeight = grossWeight + weight;
						}
					});
				}

				// 子项重量 + 净重
				var netWeight = parseFloat(this.editDataInfo.FNetWeight)
				if (!isNaN(netWeight)) {
					grossWeight = grossWeight + netWeight;
				}
				
				this.editDataInfo.FGrossWeight = grossWeight.toString();
			},
			// 校验字符串是否数学表达式（用于根据外形尺寸计算体积）
			isMathExpression(str) {
				const regex = /^[\d\+\-\*\/\(\)\.]+$/; // 定义匹配数学表达式的正则表达式
				if (!regex.test(str)) {
					return false; // 不符合正则表达式，不是数学表达式
				}

				// 判断左右括号的数量是否匹配
				let leftBracketCount = 0;
				let rightBracketCount = 0;
				for (let i = 0; i < str.length; i++) {
					if (str[i] === "(") {
					leftBracketCount++;
					} else if (str[i] === ")") {
					rightBracketCount++;
					}
				}
				if (leftBracketCount !== rightBracketCount) {
					return false; // 左右括号数量不匹配，不是数学表达式
				}

				// 判断运算符的使用是否符合运算优先级
				const operators = "+-*/";
				for (let i = 0; i < str.length; i++) {
					if (operators.includes(str[i])) {
					// 运算符前后必须都是数字或右括号
					if (
						(i === 0 || !/\d|\)/.test(str[i - 1])) ||
						(i === str.length - 1 || !/\d|\(|/.test(str[i + 1]))
					) {
						return false; // 不符合运算优先级，不是数学表达式
					}
					}
				}

				// 字符串符合数学表达式的规则
				return true;
			}
		}
	}
</script>
