<template>

	<view>
		<button type="primary" size="mini" @click="add">添加</button>
		<uni-row>
			<uni-col :span="12">
				<view style="margin-bottom: 10px;">物料编码 <input v-model="mc" /> </view>
				<view style="margin-bottom: 10px;">物料批号 <input v-model="materialBatchNo" /></view>
			</uni-col>
			<uni-col :span="12">
				<view style="margin-bottom: 10px;">物料名称 <input v-model="materialName" /> </view>
				<view style="margin-bottom: 10px;">规格 <input v-model="specification1" /></view>
			</uni-col>
		</uni-row>
		<view style="background-color: #fff;">
			<uni-table ref="table" :loading="loading" border stripe emptyText="暂无更多数据" style="padding-bottom: 18vh;">
				<uni-tr>
					<uni-th width="50" align="center">序号</uni-th>
					<uni-th width="50" align="center">质检标准项/单位</uni-th>
					<uni-th width="50" align="center">质检实际检测值</uni-th>
					<uni-th width="50" align="center">是否合格</uni-th>
					<uni-th width="50" align="center">图片上传</uni-th>
				</uni-tr>
				<uni-tr v-for="(item, index) in dataslice(tableData,historyCurPage)" :key="index">
					<uni-td>{{ item.seq }}</uni-td>
					<uni-td>{{ item.qualityStandardItem }}/{{ item.qualityStandardUnit }}</uni-td>
					<uni-td>
						<uni-easyinput @change="count(index)" type="text" v-model="item.qualityActualValue" />
					</uni-td>
					<uni-td>
						<uni-data-select v-model="item.isQuality" :localdata="range"></uni-data-select>
					</uni-td>
					<uni-td align="center">
						<!-- 						<uni-file-picker :value="item.qcImages" @select @success="success" :listStyles="listStyles"
							limit="3"></uni-file-picker> -->
						<u-upload :fileList="item.qcImages" @afterRead="afterRead(index, $event)"
							@delete="deletePic(index, $event)" name="1" multiple :maxCount="5"></u-upload>
						<!-- <view class="addrpage_text" style="">
							<view class="addrimg">
								<view class="upimg">
									<view class="uni-uploader__files">
										<view v-for="(image, index1) in item.qcImages" :key="index1">
											<view class="uni-uploader__file">
												<view class="delete" @tap="onDeleteClick(index,index1)">
													<text>✖️</text>
												</view>
												<image class="uni-uploader__img" @tap.stop="lookimgbut(index,image)"
													:src="image"></image>
											</view>
										</view>
									</view>
									<view class="upload" @tap="onGetImgClick(index)" style="">
										<uni-icons custom-prefix="iconfont" type="icon-jiahao"
											style="color: #C6C6C6;margin-top:30rpx;" size="40"></uni-icons>
									</view>
								</view>
							</view>
						</view> -->
					</uni-td>
				</uni-tr>

			</uni-table>
			<view style="position: fixed;bottom: 0;background-color: #fff;width: 100%;padding: 10px 0;">
				<uni-pagination :total="historyTotal" :pageSize="historyPageSize" @change="changePage" title="标题文字" />
				<view style="margin: 10px 0 10px 0;text-align: center;">
					<text
						class="example-info">当前页：{{ historyCurPage }}，数据总量：{{ historyTotal }}条，每页数据：{{ historyPageSize }}</text>
				</view>
				<u-button type="primary" @click="submit">提交</u-button>
			</view>

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

<script>
	import {
		uploadImage,
		getStandardList,
		addQualityHistoryList,
		listQualityHistory,
		updateQualityHistory
	} from "@/api/qc/qc.js";
	// var did;
	// var list = null;
	// var qscid = null;
	export default {
		onLoad: function(option) { //option为object类型，会序列化上个页面传递的参数
			console.log(option);
			this.materialBatchNo = option.materialBatchNo;
			this.materialCode = option.materialCode;
			this.materialName = option.materialName;
			this.specification1 = option.specification1;
			this.qscid = Number(option.qscid);
			this.number = option.number;
			this.billId = option.billId;
			this.did = option.did;
			this.mc = this.materialCode.replace(/\"/g, "");
		},
		data() {
			return {
				qualityStandardDetailOptions: [],
				queryDetailParams: {},
				fileList1: [],
				qscid: null,
				did: null,
				qualityStandardCode: null,
				materialBatchNo: null,
				materialCode: null,
				specification1: null,
				materialName: '',
				mc: null,
				number: null,
				tableData: [],
				qualityActualValue: null,
				loading: false,
				historyCurPage: 1,
				historyTotal: 0,
				historyPageSize: 1,
				range: [{
						value: 0,
						text: "不合格"
					},
					{
						value: 1,
						text: "合格"
					},
				],
				listStyles: {
					// 是否显示边框
					border: true,
					// 是否显示分隔线
					dividline: true,
					// 线条样式
					borderStyle: {
						width: 1,
						color: 'blue',
						style: 'dashed',
						radius: 2
					}
				},
			}
		},
		filters: {
			dataslice(array, historyCurPage) {
				const newdata = array.filter((item) => {
					return item.seq == historyCurPage;
				});
				return newdata;
			},
		},
		mounted() {
			this.first();
		},
		methods: {
			changePage(e) {
				console.log(e)
				this.historyCurPage = e.current
			},
			dataslice(array, historyCurPage) {
				const newdata = array.filter((item) => {
					return item.seq == historyCurPage;
				});
				return newdata;
			},
			// 删除图片
			deletePic(index, event) {
				this.tableData[index].qcImages.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(index, event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				console.log(this.tableData[index].qcImages)
				let fileListLen = this.tableData[index].qcImages.length
				lists.map((item) => {
					this.tableData[index].qcImages.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					console.log(1)
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.tableData[index].qcImages[fileListLen]
					// console.log(item)
					this.tableData[index].qcImages.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uploadImage({
						filePath: url
					}).then(response => {
						uni.showToast({
							title: "上传成功",
							icon: 'success'
						});
						console.log(response)
						resolve(response.fileName)
					});
				})
			},
			// 获取上传状态
			select(e) {
				console.log('选择文件：', e)
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {

				console.log(e)
			},

			// 上传失败
			fail(e) {
				console.log('上传失败：', e)
			},
			onGetImgClick(index) {
				const _this = this
				console.log(index);
				console.log(_this.tableData[index].qcImages);
				uni.chooseImage({
					count: 5, // 最多可以选择的图片张数，默认9
					sizeType: ['original', 'compressed'], //original 原图，compressed 压缩图，默认二者都有
					sourceType: ['album', 'camera'], //album 从相册选图，camera 使用相机，默认二者都有。如需直接开相机或直接选相册，请只使用一个选项
					success: function(res) {
						console.log(JSON.stringify(res.tempFilePaths));

						for (let i = 0; i < res.tempFilePaths.length; i++) {
							let a = res.tempFilePaths[i];
							let data = {
								filePath: res.tempFilePaths[i]
							}
							uploadImage(data).then(response => {
								uni.showToast({
									title: "上传成功",
									icon: 'success'
								});
								_this.tableData[index].qcImages.push(response.url);
							});
						}

						// if(_this.tableData[index].qcImages!=null){
						// 	const len = _this.tableData[index].qcImages.length;
						// 	console.log(len);
						// 	for (let i = 0; i < 5 - len; i++) {
						// 		if (res.tempFilePaths[i]) _this.tableData[index].qcImages.push(res.tempFilePaths[i])
						// 	}
						// }else{
						// 	for (let i = 0; i < 5; i++) {
						// 		if (res.tempFilePaths[i]) _this.tableData[index].qcImages.push(res.tempFilePaths[i])
						// 	}
						// }
					}
				})
			},
			//删除功能
			onDeleteClick(index, index1) {
				const _this = this
				console.log(index + ' ' + index1 + ' ' + _this.tableData[index].qcImages);

				_this.tableData[index].qcImages.splice(index1, 1);
			},
			// 预览功能
			lookimgbut(index, image) {
				uni.previewImage({
					urls: this.tableData[index].qcImages,
					current: image,
					loop: false //是否可循环预览，默认值为 false，有需要的可以设置为true
				})
			},
			//先执行，查看已添加的质检序列
			first() {
				// this.materialBatchNo = row.materialBatchNo;
				// this.materialCode = row.materialCode;
				// this.materialLotNo = row.materialLotNo;
				// this.qualityStandardId = row.qualityStandardCode;
				// this.qualityBillId = this.form.id;
				// this.qualityBillDetailId = row.id;

				this.queryDetailParams.batchNo = this.materialBatchNo;
				this.queryDetailParams.materialCode = this.materialCode;
				this.queryDetailParams.qualityBillId = this.billId;
				this.queryDetailParams.qualityStandardId = this.qscid;
				this.queryDetailParams.qualityBillDetailId = this.did;

				// getStandardList(this.qualityStandardId).then((response) => {
				//   this.qualityStandardDetailOptions =
				//     response.data.qcQualtyStandardListDetailList;
				// });
				this.tableData = [];
				getStandardList(this.qscid).then((response) => {
					this.qualityStandardDetailOptions =
						response.data.qcQualtyStandardListDetailList;
				});
				listQualityHistory(this.queryDetailParams).then((res) => {
					console.log(res.rows);
					let arry = res.rows;
					for (let i in arry) {
						if (arry[i].isQuality != "") {
							arry[i].isQuality = Number(arry[i].isQuality);
						} else {
							arry[i].isQuality = 1;
						}

						if (arry[i].qcImages != null) {
							arry[i].qcImages = arry[i].qcImages.split(',');
						} else {
							arry[i].qcImages = [];
						}

						this.tableData.push(arry[i]);
					}
					console.log(this.tableData);
				});
				// this.tableData = [];
				// let obj = {
				// 	batchNo: this.materialBatchNo,
				// 	materialCode: this.materialCode
				// }
				// listQualityHistory(obj).then(async res => {
				// 	console.log(res.rows);
				// 	let arry = res.rows;
				// 	for (let i in arry) {
				// 		if (arry[i].isQuality != "") {
				// 			arry[i].isQuality = Number(arry[i].isQuality);
				// 		}

				// 		if (arry[i].qcImages != null) {
				// 			arry[i].qcImages = arry[i].qcImages.split(',');
				// 		} else {
				// 			arry[i].qcImages = [];
				// 		}
				// 		this.tableData.push(arry[i]);
				// 	}
				// 	console.log(this.tableData);
				// });
			},
			add() {
				this.tableData = [];
				var objs = [];
				for (let seq = 0; seq < this.number; seq++) {
					for (let i = 0; i < this.qualityStandardDetailOptions.length; i++) {
						let obj = {};
						obj.seq = seq + 1;
						obj.batchNo = this.materialBatchNo;
						obj.lotNo = this.materialLotNo;
						obj.materialCode = this.materialCode;
						obj.qualityStandardItem =
							this.qualityStandardDetailOptions[i].qualityStandardItem;
						obj.downQualityStandardValue =
							this.qualityStandardDetailOptions[i].downQualityStandardValue;
						obj.upQualityStandardValue =
							this.qualityStandardDetailOptions[i].upQualityStandardValue;
						obj.upValueRate = this.qualityStandardDetailOptions[i].upValueRate;
						obj.downValueRate = this.qualityStandardDetailOptions[i].downValueRate;
						obj.qualityStandardValue =
							this.qualityStandardDetailOptions[i].qualityStandardValue;
						obj.qualityStandardUnit =
							this.qualityStandardDetailOptions[i].qualityStandardUnit;
						obj.qualityActualValue = "";
						obj.isQuality = 1;
						obj.remark = "";
						// 设置单据Id,方便追溯
						obj.qualityBillId = this.queryDetailParams.qualityBillId;
						obj.qualityStandardId = this.queryDetailParams.qualityStandardId;
						obj.qualityBillDetailId = this.queryDetailParams.qualityBillDetailId;
						objs.push(obj);
					}
				}
				this.tableData = this.tableData.concat(objs);
				this.historyTotal = this.tableData.length;
				this.historyPageSize = this.historyTotal / this.number;
			},
			count(index) {
				var qsv = this.tableData[index].qualityStandardValue;
				var uqsv = this.tableData[index].upQualityStandardValue;
				var dqsv = this.tableData[index].downQualityStandardValue;
				var v = this.tableData[index].qualityActualValue;
				var m = /\d+(\.\d+)?/g;
				var rangeUp = null;
				var rangeDown = null;
				if (uqsv && dqsv) {
					rangeUp = Number(qsv.match(m)) + Number(uqsv.match(m));
					rangeDown = Number(qsv.match(m)) - Number(dqsv.match(m));
					console.log(rangeUp + " " + rangeDown);
					if (v <= rangeUp && v >= rangeDown) {
						console.log("合格");
						this.tableData[index].isQuality = 1;
						console.log(this.tableData[index].isQuality);
					} else {
						console.log("不合格");
						this.tableData[index].isQuality = 0;
						console.log(this.tableData[index].isQuality);
					}
				}
			},
			submit() {
				/** 计算合格数 */
				var passNumber = 0;
				for (var i = 1, k = 0; i <= this.tableData.length; i++) {
					k += Number(this.tableData[i - 1].isQuality);
					if (i % this.qualityStandardDetailOptions.length == 0) {
						if (k == this.qualityStandardDetailOptions.length) {
							passNumber++;
							k = 0;
						} else {
							k = 0;
						}
					}
					// console.log(this.tableData[i].qcImages)
					// if (this.tableData[i].qcImages.length > 0) {
					// 	console.log(this.tableData[i].qcImages)
					// 	// this.tableData[i].qcImages = this.tableData[i].qcImages.map(obj => obj.url).join(', ');
					// }
				}
				// var zjNum = 0;
				// var zjhgNum = 0;
				// var a = null;
				for (var i in this.tableData) {
					// this.tableData[i].materialCode = this.materialCode;
					// this.tableData[i].index = i;
					// if (this.tableData[i].qualityActualValue != null && this.tableData[i].isQuality != null) {
					// 	zjNum++;
					// 	if (this.tableData[i].isQuality == 1) {
					// 		zjhgNum++;
					// 	}
					// }
					if (this.tableData[i].qcImages) {
						this.tableData[i].qcImages = this.tableData[i].qcImages.map(obj => obj.url).join(', ');
					}
				}
				console.log(this.tableData);
				this.$modal.loading('提交中')
				addQualityHistoryList(this.tableData, this.queryDetailParams.qualityBillDetailId).then(async res => {
					this.$modal.closeLoading();
					console.log(getCurrentPages());
					var pages = getCurrentPages();
					var prevPage = pages[pages.length - 2]; //上一个页面
					var object = {
						number: this.tableData.length /
							this.qualityStandardDetailOptions.length,
						passNumber: passNumber,
						did: this.did
					}
					prevPage.$vm.otherFun(object); //重点$vm

					uni.navigateBack();

					// this.$tab.navigateTo('/pages/qc/ipqc');
				});
			}
		}
	}
</script>

<style lang="scss">
	.u-reset-button {
		background-color: #3c9cff;
		font-size: 18px;
		color: #fff;
	}

	.example-body {
		padding: 10px;
		padding-top: 0;
	}

	.upload {
		float: left;
		width: 100%;
		display: block;
	}

	.addrimg {
		width: 100%;
		background-color: rgb(255, 255, 255);
		margin-top: 40rpx;
	}

	.uptext {
		color: rgba(74, 74, 74, 1);
		font-size: 28rpx;
		padding: 30rpx 0rpx 0rpx 30rpx;
	}

	.upimg {
		width: 100%;
	}

	.upimg::after {
		content: '';
		display: block;
		clear: both;
	}

	.upimg>image {
		width: 159rpx;
		height: 159rpx;
		margin: 20rpx 0rpx 20rpx 30rpx;
		float: left;
	}

	.uni-uploader__file {
		float: left;
		width: 159rpx;
		height: 159rpx;
		margin: 20rpx 0rpx 20rpx 30rpx;
		position: relative;
	}

	/* 上传成功的图片 */
	.uni-uploader__img {
		float: left;
		width: 100rpx;
		height: 100rpx;
	}

	.delete {
		width: 40rpx;
		height: 40rpx;
		border-radius: 40rpx;
		line-height: 45rpx;
		/* color: rgb(255, 255, 255); */
		font-size: 26rpx;
		position: absolute;
		top: -20rpx;
		right: 30rpx;
		background-color: rgb(255, 255, 255);
		z-index: 99;
		text-align: center;
		border: 1rpx solid rgb(255, 255, 255);
	}

	.delete>text {
		position: absolute;
		top: -2rpx;
		right: -10rpx;
	}
</style>