<template>
	<view>
		<u-popup :show="visible" :round="0" :closeOnClickOverlay="false" :zIndex="99999" @close="closePopup">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">{{ title }}</text>
					<view class="close-btn" @click="closePopup">×</view>
				</view>

				<scroll-view class="popup-body" scroll-y>
					<view class="form-section">
						<view class="section-title">基本信息</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">工单编码</text>
								<view class="value-wrap" @click="selectQualityWorkOrder"
									v-if="!isSampleRecord || (isSampleRecord && type != 'add')">
									<u-input v-model="form.qualityWorkOrderCode" disabled placeholder=" "
										border="none"></u-input>
								</view>
								<view class="value-wrap" v-else>
									<u-input v-model="form.qualityWorkOrderCode" disabled placeholder=" "
										border="none"></u-input>
								</view>
							</view>
						</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">工单名称</text>
								<view class="value-wrap">
									<u-input v-model="form.qualityWorkOrderName" disabled placeholder=" "
										border="none"></u-input>
								</view>
							</view>
						</view>

						<view class="form-row">
							<view class="form-item">
								<text class="label">编码</text>
								<view class="value-wrap">
									<u-input v-model="form.productCode" disabled placeholder=" "
										border="none"></u-input>
								</view>
							</view>
						</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">名称</text>
								<view class="value-wrap">
									<u-input v-model="form.productName" disabled placeholder=" "
										border="none"></u-input>
								</view>
							</view>
						</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">批次号</text>
								<view class="value-wrap">
									<u-input v-model="form.batchNo" disabled placeholder=" " border="none"></u-input>
								</view>
							</view>
						</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">规格</text>
								<view class="value-wrap">
									<u-input v-model="form.specification" disabled placeholder=" "
										border="none"></u-input>
								</view>
							</view>
						</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">型号</text>
								<view class="value-wrap">
									<u-input v-model="form.modelType" disabled placeholder=" " border="none"></u-input>
								</view>
							</view>
						</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">牌号</text>
								<view class="value-wrap">
									<u-input v-model="form.brandNo" disabled placeholder=" " border="none"></u-input>
								</view>
							</view>
						</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">总数</text>
								<view class="value-wrap">
									<u-input v-model="form.total" disabled placeholder=" " border="none">
										<template #suffix>{{
                      tableList[0] && tableList[0].measureUnit
                    }}</template>
									</u-input>
								</view>
							</view>
						</view>
					</view>

					<view class="form-section">
						<view class="section-title">来源清单</view>
						<view class="table-info">
							<text>累计请样数量：{{ workSampleQuantity
                }}{{
                  (sampleList[0] && sampleList[0].measureUnit) ||
                  form.measureUnit
                }}</text>
						</view>
						<view class="table-wrapper">
							<scroll-view scroll-x scroll-y class="table-scroll">
								<view class="source-table">
									<view class="table-header">
										<view class="table-cell select-cell">
											<checkbox :checked="isAllSelected" @click="toggleSelectAll" />
										</view>
										<view class="table-cell" v-for="col in displaySourceColumns.filter(
                        (c) => c.prop !== 'select',
                      )" :key="col.prop">{{ col.label }}</view>
									</view>
									<view class="table-body">
										<view class="table-row" v-for="(item, index) in tableList" :key="index">
											<view class="table-cell select-cell">
												<checkbox :checked="isSelected(item)" @click="toggleSelect(item)" />
											</view>
											<view class="table-cell" v-for="col in displaySourceColumns.filter(
                          (c) => c.prop !== 'select',
                        )" :key="col.prop">
												{{ item[col.prop] || "-" }}
											</view>
										</view>
										<view class="table-empty" v-if="!tableList || tableList.length === 0">
											<text>暂无数据</text>
										</view>
									</view>
								</view>
							</scroll-view>
						</view>
					</view>

					<view class="form-section">
						<view class="section-title">请样信息</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">请样目的</text>
								<view class="value-wrap">
									<u-input v-model="form.pleasePurpose" placeholder="请输入" border="none"
										:disabled="type=='view'"></u-input>
								</view>
							</view>
						</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">质检方式</text>
								<view class="value-wrap">
									<DictSelection v-model="form.qualityMode" @itemChange="handleQualityModeChange"
										:disabled="form.isFirstSampling != '1'||type=='view'" dictName="取样类型">
									</DictSelection>
								</view>
							</view>
						</view>
						<view class="form-row">
							<view class="form-item">
								<text class="label">记录方法</text>
								<view class="value-wrap">


									<view class="select-input"
										:class="{ disabled: form.isFirstSampling != '1'||type=='view' }"
										@click="selectRecordingMethod">
										<text
											class="value-text">{{ recordingMethodList.find(item=>item.value==form.recordingMethod)&&recordingMethodList.find(item=>item.value==form.recordingMethod).label||'请选择' }}</text>
										<text class="arrow">›</text>
									</view>

								</view>
							</view>
						</view>

						<view class="form-section-inner" v-if="form.qualityMode == '2'">
							<view class="form-row">
								<view class="form-item">
									<text class="label">请样类型</text>
									<view class="value-wrap" @click="selectConditionType">


										<view class="select-input"
											:class="{ disabled: form.isFirstSampling != '1'||type=='view' }"
											@click="selectConditionType">
											<text
												class="value-text">{{ conditionTypeColumns.find(item=>item.value==form.conditionType)&&conditionTypeColumns.find(item=>item.value==form.conditionType).label||'请选择' }}</text>
											<text class="arrow">›</text>
										</view>




									</view>
								</view>
							</view>

							<view class="form-row" v-if="form.conditionType == 2">
								<view class="form-item">
									<text class="label">数量</text>
									<view class="value-wrap">
										<u-input v-model="form.quantity" :disabled="type=='view'" placeholder="请输入"
											border="none"></u-input>
									</view>
								</view>
							</view>
							<view class="form-row" v-if="form.conditionType == 2">
								<view class="form-item">
									<text class="label">单位</text>
									<view class="value-wrap">
										
										<DictSelection v-model="form.unit" @itemChange="handleQualityModeChange"
											:disabled="form.isFirstSampling != '1'||type=='view'" dictName="计量单位">
										</DictSelection>
										
								
									</view>
								</view>
							</view>
							<view class="form-row" v-if="form.conditionType == 2">
								<view class="form-item">
									<text class="label">条数</text>
									<view class="value-wrap">
										<u-input v-model="form.portion" :disabled="type=='view'" placeholder="请输入"
											border="none"></u-input>
									</view>
								</view>
							</view>

							<view class="form-row" v-if="form.conditionType == 1">
								<view class="form-item">
									<text class="label">数量</text>
									<view class="value-wrap">
										<u-input v-model="form.portion" :disabled="type=='view'" placeholder="请输入"
											border="none"></u-input>
									</view>
								</view>
							</view>
							<view class="form-row" v-if="form.conditionType == 1">
								<view class="form-item">
									<text class="label">单位</text>
									<view class="value-wrap"
										>
										
										
										<view class="select-input"
											:class="{ disabled: form.isFirstSampling != '1'||type=='view' }"
											@click="selectPackingUnit">
											<text
												class="value-text">{{ packingSpecificationOption.find(item=>item.id==form.packingUnit)&&packingSpecificationOption.find(item=>item.id==form.packingUnit).conversionUnit||'请选择' }}</text>
											<text class="arrow">›</text>
										</view>
										
										
										
							
									</view>
								</view>
							</view>

							<view class="confirm-btn-wrap" v-if="type != 'view'">
								<u-button type="primary" @click="handleSampleSubmit">确认</u-button>
							</view>
						</view>
					</view>

					<view class="form-section">
						<view class="section-title">样品信息</view>
						<view class="table-wrapper">
							<scroll-view scroll-x scroll-y class="table-scroll">
								<view class="sample-table">
									<view class="table-header">
										<view class="table-cell" v-for="col in displaySampleColumns" :key="col.prop">
											{{ col.label }}
										</view>
									</view>
									<view class="table-body">
										<view class="table-row" v-for="(item, index) in sampleList" :key="index">
											<view class="table-cell" v-for="col in displaySampleColumns"
												:key="col.prop">
												{{ item[col.prop] || "-" }}
											</view>
										</view>
										<view class="table-empty" v-if="!sampleList || sampleList.length === 0">
											<text>暂无数据</text>
										</view>
									</view>
								</view>
							</scroll-view>
						</view>
					</view>
				</scroll-view>

				<view class="popup-footer">
					<u-button type="default" @click="closePopup">关闭</u-button>
					<u-button type="primary" @click="save()" v-if="type != 'view'" :loading="loading">保存</u-button>
					<!-- <u-button type="success" @click="save('submit')" v-if="type != 'view' && isSamplingApproval == 1"
						:loading="loading">提交</u-button> -->
				</view>
			</view>
			<u-toast ref="uToast"></u-toast>

			<!-- 记录方法选择 -->
			<u-picker :show="showRecordingMethodPicker"  keyName="label" :columns="[recordingMethodList]" @confirm="confirmRecordingMethod" @cancel="showRecordingMethodPicker = false"></u-picker>

			<!-- 请样类型选择 -->
			<u-picker :show="showConditionTypePicker" :columns="[conditionTypeColumns]" keyName="label" @confirm="confirmConditionType"
				@cancel="showConditionTypePicker = false"></u-picker>

		
			<!-- 包装单位选择 -->
			<u-picker :show="showPackingUnitPicker" keyName="label" :columns="[packingSpecificationOption.map(item=>{
				return {
					label:item.conversionUnit,
					value:item.id
				}
			})]" @confirm="confirmPackingUnit"
				@cancel="showPackingUnitPicker = false"></u-picker>
		</u-popup>





	</view>
</template>

<script>
	import {
		recordingMethodList
	} from "@/utils/utils.js";
	import DictSelection from "@/components/Dict/DictSelection.vue";
	const defForm = {
		code: "", //编码
		name: "", //名称
		conditionType: "",
		quantity: "",
		unit: "",
		portion: "",
		qualityMode: "",
		qualityModeName: "",
		recordingMethod: 1,
		recordingMethodName: "",
		pleaseQuantity: "",
		pleasePurpose: "",
		pleaseUnit: "",
		sampleQuantity: "",
		qualityWorkOrderId: "",
		qualityWorkOrderCode: "",
		qualityWorkOrderName: "",
		isFirstSampling: "",
		measureUnit: ''
	};
	import {
		queryQualityInventory,
		queryQualityTempleContent,
	} from "@/api/inspectionWork";
	import {
		samplingrecordSave,
		getById,
		samplingrecordUpdate,
		samplingRecordsPage,
	} from "@/api/samplingRecords";
	import {
		getCodeList,
		getCode,
		parameterGetByCode
	} from '@/api/pda/picking.js'
	export default {
		components: {
			DictSelection
		},

		data() {
			return {
				recordingMethodList,
				form: {
					...defForm
				},
				activeComp: "main",
				tabOptions: [{
						key: "main",
						name: "请样详情"
					},
					{
						key: "bpm",
						name: "流程详情"
					},
				],
				workSampleQuantity: 0,
				visible: false,
				loading: false,
				sampleNumberList: [{
						label: "全检",
						value: 1
					},
					{
						label: "抽检",
						value: 2
					},
				],
				selection: [],
				// 弹窗相关

				showRecordingMethodPicker: false,
				showConditionTypePicker: false,
				showUnitPicker: false,
				showPackingUnitPicker: false,
				recordingMethodPickerColumns: [],
				conditionTypeColumns: [{
						label: "请整样",
						value: 1
					},
					{
						label: "请小样",
						value: 2
					},
				],
		
				packingUnitColumns: [
					[]
				],
				// 显示的表格列
				displaySourceColumns: [{
						label: "",
						prop: "select",
						type: "selection"
					},
					{
						label: "名称",
						prop: "categoryName"
					},
					{
						label: "计量数量",
						prop: "measureQuantity"
					},
					{
						label: "计量单位",
						prop: "measureUnit"
					},
					{
						label: "包装数量",
						prop: "packingQuantity"
					},
					{
						label: "包装单位",
						prop: "packingUnit"
					},
				],
				displaySampleColumns: [{
						label: "样品编码",
						prop: "sampleCode"
					},
					{
						label: "名称",
						prop: "categoryName"
					},
					{
						label: "计量数量",
						prop: "measureQuantity"
					},
					{
						label: "计量单位",
						prop: "measureUnit"
					},
					{
						label: "包装数量",
						prop: "packingQuantity"
					},
					{
						label: "包装单位",
						prop: "packingUnit"
					}
				],
				packingSpecificationOption: [],
				sampleList: [],
				schemeList: [],
				tableList: [],
				type: "add",
				title: "",
				isSamplingApproval: 0,
				isSampleRecord: false,
				isAllSelected: false,
			};
		},

		computed: {
			allSelected() {
				return (
					this.tableList.length > 0 &&
					this.selection.length === this.tableList.length
				);
			},
		},
		created() {},
		methods: {
			// 切换全选
			toggleSelectAll() {
				if (this.isAllSelected) {
					this.selection = [];
				} else {
					this.selection = [...this.tableList];
				}
				this.isAllSelected = !this.isAllSelected;
			},
			// 切换单选
			toggleSelect(item) {
				const index = this.selection.findIndex((row) => row.id === item.id);
				if (index > -1) {
					this.selection.splice(index, 1);
				} else {
					this.selection.push(item);
				}
				this.isAllSelected = this.selection.length === this.tableList.length;
			},
			// 判断是否选中
			isSelected(item) {
				return this.selection.findIndex((row) => row.id === item.id) > -1;
			},
			closePopup() {
				this.cancel();
			},
			async open(type, row) {
				// this.activeComp = 'main';
				this.visible = true;
				this.type = type;
				// this.parameterGetByCode();
				this.title =
					type == "add" ? "请样" : type == "edit" ? "修改请样" : "详情";
				if (type == "add") {
					if (row) {
						this.init(row);
					}
				} else {
					this.getById(row.id);
				}
			},



			// 记录方法选择
			selectRecordingMethod() {
				console.log(this.form.isFirstSampling, 'this.form.isFirstSampling')
				if (this.form.isFirstSampling != "1") return;
				// this.recordingMethodPickerColumns = [this.recordingMethodList];
				this.showRecordingMethodPicker = true;
			},
			confirmRecordingMethod(e) {
				this.form.recordingMethod = e.value[0].value;
				this.form.recordingMethodName = e.value[0].label;
				this.showRecordingMethodPicker = false;
			},
			// 请样类型选择
			selectConditionType() {
				if (this.form.isFirstSampling != "1") return;

				this.showConditionTypePicker = true;
			},
			confirmConditionType(e) {
				this.form.conditionType = e.value[0].value;
				this.form.conditionTypeName = e.value[0].label;
				this.showConditionTypePicker = false;
			},

			// 包装单位选择
			selectPackingUnit() {
				if (this.form.isFirstSampling != "1") return;
				// let unitList = this.packingSpecificationOption.map(
				// 	(item) => item.conversionUnit,
				// );
				// this.packingUnitColumns = [unitList];
				this.showPackingUnitPicker = true;
			},
			confirmPackingUnit(e) {
		
				this.$set(this.form, 'packingUnit', e.value[0].value);
				this.$set(this.form, 'unit', e.value[0].label);
				this.showPackingUnitPicker = false;
			},
			parameterGetByCode() {
				parameterGetByCode({
					code: "sampling_approval",
				}).then((res) => {
					this.isSamplingApproval = res.value;
				});
			},
			async init(row) {
				let isPackingUnit = false;
				let data = await samplingRecordsPage({
					qualityWorkOrderId: row.id,
				});
				let list = data.list.filter(
					(item) => item.status === 0 || item.status === 4,
				);
				let list1 = data.list.filter((item) => item.status != 3);
				if (list?.length) {
					this.getById(list[0].id);
					this.type = "edit";
					this.title = "修改请样";
				} else {
					row.sourceCode = row.qualityPlanCode || row.workOrderCode;
					this.form = JSON.parse(JSON.stringify(row));
					this.form.qualityWorkOrderId = row.id;
					this.form.qualityWorkOrderCode = row.code;
					this.form.qualityWorkOrderName = row.name;
					this.workSampleQuantity = Number(row.sampleQuantity) || 0;
					this.form.recordingMethod = this.form.recordingMethod || '1'

					if (!list1?.length) {
						this.form.isFirstSampling = 1;
						isPackingUnit = true;
						if (this.form.conditionType == 1) {
							this.$set(this.form, "packingUnit", "111");
						}
					} else {
						this.$set(this.form, "unit", list1[0].unit);
						this.$set(this.form, "measureUnit", list1[0].measureUnit);
					}
					await this.datasource(list1[0]?.unit, isPackingUnit);
					await this.queryQualityTempleContent(
						!list1.length && row.qualityMode == 1,
					);
				}
			},
			getById(id) {
				getById(id).then((res) => {
					this.workSampleQuantity =
						Number(res.qualityWorkOrderVO.sampleQuantity) || 0;
					[
						"id",
						"code",
						"name",
						"createTime",
						"createUserId",
						"status",
						"approvalStatus",
						"approvalUserId",
						"sampleQuantity",
						"processInstanceId",
					].forEach((it) => {
						delete res.qualityWorkOrderVO[it];
					});
					this.form = {
						...res,
						...res.qualityWorkOrderVO
					};
					this.datasource(this.form.unit);
					this.queryQualityTempleContent();
					if (this.form.qualityMode == 2) {
						if (res.qualityWorkOrderVO.conditionType == 1) {
							this.$set(this.form, "portion", res.quantity);
							this.$set(this.form, "quantity", 0);
						} else {
							this.$set(this.form, "portion", res.copies);
						}
					}

					this.sampleList = res.qualitySampleList;
				});
			},
			/* 查询质检模板内容 */
			async queryQualityTempleContent(is) {
				const res = await queryQualityTempleContent({
					qualityWorkerId: this.form.qualityWorkOrderId,
					page: 1,
					size: 10000,
				});
				this.schemeList = res.list;
				if (is) {
					this.updatePackingList();
				}
			},
			cancel() {
				this.form = {
					...defForm,
				};
				this.workSampleQuantity = 0
				this.schemeList = [];
				this.packingSpecificationOption = [];
				this.sampleList = [];
				this.tableList = [];

				this.visible = false;
			},

			async datasource(unit, isPackingUnit) {
				const res = await queryQualityInventory({
					qualityWorkerId: this.form.qualityWorkOrderId,
					pageNum: 1,
					size: -1,
				});
				console.log(res, "res");

				let o = res.list[0];
				let listArr = [];
				if (o.measureUnit) {
					listArr.push({
						packageCellTotal: 1,
						conversionUnit: o.measureUnit,
						id: "111",
					});
				}
				if (o.packingUnit) {
					listArr.push({
						packageCellTotal: o.measureQuantity - 0,
						conversionUnit: o.packingUnit,
						id: "222",
					});
				}
				if (unit) {
					this.$set(
						this.form,
						"packingUnit",
						listArr.find((item) => unit == item.conversionUnit)?.id,
					);
				}
				if (isPackingUnit) {
					this.$set(this.form, "unit", res.list[0]?.measureUnit);
				}
				this.form.pleaseUnit = res.list[0]?.measureUnit;
				res.list.map((el) => {
					el.weightProportion = el.weight ?
						(el.weight / el.measureQuantity).toFixed(4) :
						0;
					el.weightProportion = el.weightProportion - 0;
				});
				this.packingSpecificationOption = listArr;
				this.tableList = res.list;
				return res;
			},

			handleSampleSubmit() {
				let params = {
					conditionType: this.form.conditionType,
					quantity: this.form.quantity,
					sampleUnit: this.form.unit,
					portion: this.form.portion,
				};
				let specifications = this.packingSpecificationOption.find(
					(el) => el.id == this.form.packingUnit,
				);
				this.sampleFn(params, specifications);
			},

			async sampleFn(data, specifications) {
				console.log(this.selection, 'this.selection')
				this.sampleList = [];
				if (!this.selection || this.selection.length == 0) {
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: "请先选择来源清单！",
					}, )

					return;
				}
				const quantity = data.quantity || 1;
				const unit = data.sampleUnit;
				const sampleCount = Number(data.portion);
				try {
					// 2 取小样
					if (this.form.conditionType == 2) {
						if (!this.validateMeasureQuantity(quantity, unit, sampleCount))
							return; //取样数量验证
						if (unit === "KG" && !this.validateWeight(quantity, sampleCount))
							return; // 若计量单位为重量，还需验证总重量是否足够
						await this.getNewFullSampleList(
							Math.ceil(sampleCount),
							quantity,
							unit,
							specifications,
						);
					} else {
						let isFlag = this.validateSampleQuantity(sampleCount, specifications);
						if (!isFlag) return;
						if (this.form.inspectionStandards == 1) {
							await this.getNewFullSampleList(
								Math.ceil(sampleCount),
								quantity,
								unit,
								specifications,
							);
						} else {
							await this.handleWeightFullSample(sampleCount, specifications);
						}
					}
				} catch (error) {
					console.error("请样处理失败:", error);
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: "请样处理失败！",
					}, )



				}
			},
			validateWeight(quantity, sampleCount) {
				let totalMaxPossible = 0;
				this.selection.forEach((item) => {
					totalMaxPossible += item.measureQuantity / quantity;
				});

				if (totalMaxPossible < sampleCount) {
					console.error("请样处理失败:", error);
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `最大请样条数为${totalMaxPossible}`,
					}, )

					return false;
				}

				let totalWeight = this.selection.reduce(
					(sum, item) => sum + item.weight,
					0,
				);
				const weightUnit = this.selection[0].weightUnit;
				if (weightUnit === "G") totalWeight /= 1000;

				if (quantity * sampleCount > totalWeight) {

					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `请样计量重量不能大于总计量重量`,
					}, )

					return false;
				}

				const invalidItem = this.selection.find((item) => {
					const weight =
						item.weightUnit === "G" ? item.weight / 1000 : item.weight;
					return weight < quantity;
				});

				if (invalidItem) {
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `勾选条目重量小于请样重量`,
					}, )

					return false;

				}

				return true;
			},

			validateMeasureQuantity(quantity, unit, sampleCount) {
				if (quantity <= 0) {

					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `请样计量数量必须大于`,
					}, )

					return false;

				}

				const totalQuantity =
					this.selection.reduce((sum, item) => sum + item.measureQuantity, 0) -
					this.workSampleQuantity;

				if (
					this.selection[0].measureUnit === unit &&
					quantity * sampleCount > totalQuantity
				) {
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `请样计量数量不能大于总计量数量`,
					}, )


					return false;
				}

				const invalidItem = this.selection.find(
					(item) => item.measureQuantity < quantity,
				);
				if (invalidItem) {
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `条目计量数量小于请样计量数量`,
					}, )


					return false;
				}
				return true;
			},

			async handleWeightFullSample(sampleCount, specifications) {
				const dataList = [];
				let currentNum = sampleCount - this.selection.length;
				let currentNum1 = sampleCount;
				for (const item of this.selection) {
					const qualitySampleTemplateList = item.qualitySampleTemplateList?.length ?
						JSON.parse(JSON.stringify(item.qualitySampleTemplateList)) :
						JSON.parse(
							JSON.stringify(
								this.schemeList.map((item) => {
									item["qualityResults"] = 1;
									return item;
								}),
							),
						);

					if (sampleCount >= this.selection.length) {
						dataList.push({
							...item,
							measureQuantity: 1, //作为计量数量
							sampleCode: await getCode("sample_code"),
							qualitySampleTemplateList,
						});
					} else {
						if (dataList.length < sampleCount) {
							dataList.push({
								...item,
								measureQuantity: currentNum1 > 1 ? 1 : currentNum1, //作为计量数量
								sampleCode: await getCode("sample_code"),
								qualitySampleTemplateList,
							});
							currentNum1 -= 1;
						}
					}
				}
				if (sampleCount > this.selection.length) {
					dataList.forEach((item) => {
						if (currentNum > 0) {
							let data = this.selection.find((val) => val.id == item.id);
							item["measureQuantity"] =
								data.measureQuantity - 1 - currentNum > 0 ?
								currentNum + 1 :
								data.measureQuantity;
							currentNum = currentNum - (data.measureQuantity - 1);
						}
					});
				}
				// 更改 从新计算 样品清单 取整样 数据
				if (specifications && specifications.id) {
					dataList.map((el) => {
						el.measureQuantity =
							el.measureQuantity * specifications.packageCellTotal;
						el.weight = this.formatNumber(
							el.measureQuantity,
							el.weightProportion,
						);
					});
				}
				// 更改
				this.sampleList = dataList;
				this.getTotal();
			},
			// 小数点数据判断
			formatNumber(a, b, maxDecimals = 4) {
				if (a == 0 || b == 0 || !a || !b) {
					return 0;
				}
				const product = a * b;
				const rounded = Number(product.toFixed(maxDecimals));
				const str = rounded.toString();
				if (str.indexOf(".") !== -1) {
					return str.replace(/\.?0+$/, "");
				}
				return str;
			},
			//从来源数组取样到目标数组
			async getNewFullSampleList(
				sampleCount,
				sampleQuantity,
				sampleUnit,
				specifications,
			) {
				const sourceArray = this.selection;
				const isUnitMismatch =
					sourceArray.length > 0 && sourceArray[0].measureUnit !== sampleUnit;

				const items = sourceArray.map((item) => ({
					...item,
					remainingQuantity: isUnitMismatch ? Infinity : item["measureQuantity"],
					maxPossible: item["measureQuantity"] / sampleQuantity,
				}));

				const result = [];
				let remainingCount = sampleCount;
				let count = Math.ceil(remainingCount);
				const codeList = await this.batchCodes(count);
				let codeIdx = 0;

				while (remainingCount > 0) {
					items.sort(
						(a, b) =>
						b.remainingQuantity / b["measureQuantity"] -
						a.remainingQuantity / a["measureQuantity"],
					);

					let distributed = false;

					for (const item of items) {
						if (
							!isUnitMismatch ||
							(item.remainingQuantity >= sampleQuantity && remainingCount > 0)
						) {
							let qualitySampleTemplateList = [];
							if (
								item.qualitySampleTemplateList == undefined ||
								item.qualitySampleTemplateList == null ||
								item.qualitySampleTemplateList.length == 0
							) {
								qualitySampleTemplateList = JSON.parse(
									JSON.stringify(this.schemeList),
								);
							} else {
								qualitySampleTemplateList = item.qualitySampleTemplateList;
							}
							let sampleCode = codeList[codeIdx];
							if (
								this.form.conditionType == 1 &&
								this.form.inspectionStandards == 1
							) {
								result.push({
									...item,
									measureQuantity: 1,
									sampleCode,
									qualitySampleTemplateList,
								});
							} else if (this.form.conditionType == 2) {
								let weight = (item.weight / item.maxPossible).toFixed(2);
								result.push({
									...item,
									measureQuantity: sampleQuantity,
									measureUnit: sampleUnit,
									sampleCode,
									weight,
									qualitySampleTemplateList,
								});
							}
							if (!isUnitMismatch) {
								item.remainingQuantity -= sampleQuantity;
							}
							remainingCount = (remainingCount - 1).toFixed(2);
							codeIdx++;
							distributed = true;
						}
					}

					if (!distributed) {
						break;
					}
				}

				if (this.form.conditionType == 1 && specifications && specifications.id) {
					result.map((el) => {
						el.measureQuantity =
							el.measureQuantity * specifications.packageCellTotal;
						el.weight = this.formatNumber(
							el.measureQuantity,
							el.weightProportion,
						);
					});
				}
				this.sampleList = result;
				if (this.sampleList.length > sampleCount) {
					this.sampleList = this.sampleList.splice(0, sampleCount);
				}
				this.getTotal();
			},
			// 当计量类型 是数量的时候 取整样 校验
			validateSampleQuantity(sampleCount, specifications) {
				let packingUnit = this.selection[0].packingUnit?.trim() || "";
				let totalS = 0;
				let measureQuantityCount = 0;
				let labelKey =
					packingUnit == specifications.conversionUnit.trim() ?
					"packingQuantity" :
					"measureQuantity";
				let labelName = labelKey == "packingQuantity" ? "包装数量" : "计量数量";
				totalS = this.selection.reduce((total, el) => total + el[labelKey], 0);
				let formTotalS = this.tableList.reduce(
					(total, el) => total + el.measureQuantity,
					0,
				);
				if (sampleCount > totalS) {
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `所填的条目数量不能超过所选${labelName}总和${totalS}`,
					}, )


					return false;
				}
				if (labelKey == "packingQuantity") {
					measureQuantityCount = sampleCount * this.selection[0].measureQuantity;
				} else {
					measureQuantityCount = sampleCount;
				}
				if (measureQuantityCount > formTotalS - this.workSampleQuantity) {
					this.$refs.uToast.show({
						type: "error",
						icon: false,
						message: `请样数量不能大于${formTotalS - this.workSampleQuantity} ${
            this.selection[0].measureUnit
          }`,
					}, )


					return false;

				}
				return true;
			},

			handleQualityModeChange({
				dictCode,
				dictValue
			}) {
				if (dictCode == 1) {
					this.updatePackingList();
				} else {
					this.sampleList = [];
					this.getTotal();
				}
			},
			// 全检
			async updatePackingList() {
				let list = this.tableList;
				const dataList = [];
				let count = list ? list.length : 0;
				const codeList = await this.batchCodes(count);
				for (const [index, item] of list.entries()) {
					const qualitySampleTemplateList = item.qualitySampleTemplateList?.length ?
						JSON.parse(JSON.stringify(item.qualitySampleTemplateList)) :
						JSON.parse(
							JSON.stringify(
								this.schemeList.map((item) => {
									item["qualityResults"] = 1;
									return item;
								}),
							),
						);
					dataList.push({
						...item,
						measureQuantity: item.measureQuantity,
						sampleCode: codeList[index],
						qualitySampleTemplateList,
					});
				}
				this.sampleList = dataList;
				this.getTotal();
			},
			getTotal() {
				this.form.sampleQuantity = this.sampleList
					.reduce((total, el) => total + Number(el.measureQuantity), 0)
					.toFixed(2);
				this.form.sampleWeight = this.sampleList
					.reduce((total, el) => total + Number(el.weight), 0)
					.toFixed(2);
			},
			async batchCodes(count) {
				if (count <= 0) return;
				let params = {
					count
				};
				const res = await getCodeList("sample_code", params);
				return res;
			},
			/* 保存编辑 */
			save(type) {
				if (this.type == "add") {
					[
						"id",
						"code",
						"name",
						"createTime",
						"createUserId",
						"status",
						"approvalStatus",
						"approvalUserId",
					].forEach((key) => {
						delete this.form[key];
					});
				}
				let data = JSON.parse(JSON.stringify(this.form));

				// 验证
				if (!this.form.qualityWorkOrderCode) {
					uni.showToast({
						title: "请选择质检工单",
						icon: "none"
					});
					return;
				}
				if (!this.form.qualityMode) {
					uni.showToast({
						title: "请选择质检方式",
						icon: "none"
					});
					return;
				}
				if (!this.form.recordingMethod) {
					uni.showToast({
						title: "请选择记录方法",
						icon: "none"
					});
					return;
				}
				if (this.form.qualityMode == "2" && !this.form.conditionType) {
					uni.showToast({
						title: "请选择请样类型",
						icon: "none"
					});
					return;
				}
				if (!this.sampleList.length) {
					uni.showToast({
						title: "样品清单不能为空！",
						icon: "none"
					});
					return;
				}
				//抽检
				if (data.qualityMode == 2) {
					//取整样
					if (data.conditionType == 1) {
						data.quantity = data.portion;
					} else {
						data.copies = data.portion;
					}
				}
				data.measureUnit = this.sampleList[0].measureUnit;

				let api = this.type == "add" ? samplingrecordSave : samplingrecordUpdate;
				this.loading = true;

				api({
						...data,
						sampleList: this.sampleList,
					})
					.then((res) => {
						this.loading = false;

						uni.showToast({
							title: "操作成功",
							icon: "success"
						});

						if (type == "submit") {
							this.approvalSubmit(this.type == "add" ? res : data.id);
						} else {
							this.cancel();
							this.$emit("reload");
						}
					})
					.catch(() => {
						this.loading = false;
					});
			},
			async approvalSubmit(id) {
				const res = await getById(id);
				this.processSubmitDialogFlag = true;
				this.$nextTick(() => {
					let params = {
						businessId: res.id,
						businessKey: "sampling_approval_process",
						formCreateUserId: res.createUserId,
						variables: {
							businessCode: res.code,
							businessName: "请样",
							businessType: res.qualityWorkOrderVO.conditionType == 1 ? "整样" : "小样",
						},
					};
					this.$refs.processSubmitDialogRef.init(params);
				});
			},
			search() {
				this.cancel();
				this.$emit("reload");
			},
		},
	};
</script>

<style lang="scss" scoped>
	.popup-content {
		width: 100vw;
		height: 90vh;
		background: #fff;
		border-radius: 0;
		display: flex;
		flex-direction: column;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #e5e5e5;

		.popup-title {
			font-size: 36rpx;
			font-weight: bold;
			color: #333;
		}

		.close-btn {
			width: 60rpx;
			height: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 60rpx;
			color: #999;
			line-height: 1;
		}
	}

	.popup-body {
		flex: 1;
		overflow-y: auto;
		padding: 0 30rpx 30rpx;
	}

	.form-section {
		margin-top: 30rpx;

		.section-title {
			font-size: 32rpx;
			font-weight: bold;
			color: #333;
			margin-bottom: 20rpx;
			padding-left: 20rpx;
			border-left: 6rpx solid #157a2c;
		}

		.form-row {
			margin-bottom: 20rpx;

			.form-item {
				display: flex;
				align-items: center;
				padding: 20rpx 0;
				border-bottom: 1rpx solid #f5f5f5;

				.label {
					width: 150rpx;
					font-size: 28rpx;
					color: #333;
					flex-shrink: 0;

					&::after {
						content: "：";
					}
				}

				.value-wrap {
					flex: 1;
					min-height: 60rpx;
					display: flex;
					align-items: center;
					position: relative;

					&.disabled {
						opacity: 0.6;
					}

					.arrow {
						color: #999;
						font-size: 40rpx;
						line-height: 1;
					}
				}
			}
		}
	}

	.table-info {
		padding: 20rpx;
		font-size: 28rpx;
		color: #666;
		background: #f9f9f9;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
	}

	.table-wrapper {
		border: 1rpx solid #e5e5e5;
		border-radius: 8rpx;
		overflow: hidden;
		max-height: 400rpx;
	}

	.table-scroll {
		width: 100%;
		height: 400rpx;
	}

	.source-table {
		min-width: 100%;
		width: 950rpx;
	}

	.table-header {
		display: flex;
		background: #f5f5f5;
		z-index: 10;
		min-width: 100%;
		box-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.05);

		.table-cell {
			padding: 20rpx 10rpx;
			font-size: 26rpx;
			font-weight: bold;
			color: #333;
			text-align: center;
			border-right: 1rpx solid #e5e5e5;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			flex-shrink: 0;

			&.select-cell {
				width: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 20rpx;
			}

			&:nth-child(2) {
				width: 300rpx;
			}

			&:nth-child(3),
			&:nth-child(4),
			&:nth-child(5),
			&:nth-child(6) {
				width: 140rpx;
			}

			&:last-child {
				border-right: none;
			}
		}
	}

	.sample-table {
		min-width: 100%;
		width: 1040rpx;
	}

	.table-body {
		.table-row {
			display: flex;
			border-bottom: 1rpx solid #e5e5e5;

			&:last-child {
				border-bottom: none;
			}

			.table-cell {
				padding: 20rpx 10rpx;
				font-size: 24rpx;
				color: #666;
				text-align: center;
				border-right: 1rpx solid #e5e5e5;
				white-space: nowrap;
				overflow: hidden;
				text-overflow: ellipsis;
				flex-shrink: 0;

				&.select-cell {
					width: 80rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					padding: 20rpx;
				}

				&:nth-child(2) {
					width: 300rpx;
				}

				&:nth-child(3),
				&:nth-child(4),
				&:nth-child(5),
				&:nth-child(6) {
					width: 140rpx;
				}

				&:last-child {
					border-right: none;
				}
			}
		}

		.table-empty {
			padding: 60rpx 0;
			text-align: center;
			font-size: 28rpx;
			color: #999;
		}
	}

	// 样品信息表格特定样式
	.sample-table {
		.table-header {
			.table-cell {
				&:nth-child(1) {
					width: 200rpx;
				}

				&:nth-child(2) {
					width: 250rpx;
				}

				&:nth-child(3),
				&:nth-child(4),
				&:nth-child(5),
				&:nth-child(6) {
					width: 140rpx;
				}
			}
		}

		.table-body {
			.table-cell {
				&:nth-child(1) {
					width: 200rpx;
				}

				&:nth-child(2) {
					width: 250rpx;
				}

				&:nth-child(3),
				&:nth-child(4),
				&:nth-child(5),
				&:nth-child(6) {
					width: 140rpx;
				}
			}
		}
	}

	.confirm-btn-wrap {
		margin-top: 20rpx;
		padding: 0 20rpx;
	}

	.popup-footer {
		display: flex;
		padding: 20rpx 30rpx;
		border-top: 1rpx solid #e5e5e5;
		gap: 20rpx;

		/deep/ .u-button {
			flex: 1;
		}
	}

	.select-input {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 0;
		min-height: 70rpx;
		border-bottom: 1rpx solid #e5e5e5;
		width: 100%;

		&.disabled {
			opacity: 0.6;
		}

		.value-text {
			flex: 1;
			font-size: 28rpx;
			color: #333;

			&.empty {
				color: #999;
			}
		}

		.arrow {
			font-size: 40rpx;
			color: #999;
			line-height: 1;
			margin-left: 20rpx;
		}
	}
</style>