<template>
	<u-popup :show="show" @close="cancel" :closeable="false">
		<view class="mainBox">
			<uni-nav-bar fixed="true" statusBar="true" left-icon="back" title="实验" @clickLeft="cancel">

			</uni-nav-bar>
			<view class="wrapper">
				<view class="herder_item">
					<view class="herder_text"></view>
					<view class="herder_view">
						实验时间
					</view>
				</view>
				<view class="marginTop20">
					<uni-datetime-picker v-if="type=='edit'" type="datetime"
						v-model="form.experimentalTime"></uni-datetime-picker>
					<u-input v-else :disabled="true" placeholder=" " border="surround"
						:value="form.experimentalTime"></u-input>
				</view>
				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						执行标准
					</view>
				</view>
				<u--input suffixIcon="arrow-right" style="background-color:#fff ;" :disabledColor="'#ffffff'"
					:disabled="true" class="marginTop20" placeholder=" " border="surround"
					:value="getDictValue('质检标准类型', projectData.qualityStandardType+'')">

				</u--input>
				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						实验室
					</view>
				</view>
				<view class="marginTop20">
					<uni-data-picker v-if="type=='edit'" :disabled='type=="view"' v-model="form.workshopName"
						placeholder="请选择" :localdata="laboratoryList" @change="getWorkshopId">
					</uni-data-picker>
					<u-input v-else :disabled="true" placeholder=" " border="surround"
						:value="form.workshopName"></u-input>
				</view>
				<!-- 		<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						实验设备
					</view>
				</view> -->
				<view v-for="(item, index) in form.experimentEquipmentList">
					<view class="herder_item marginTop20" @click="delEquipmentList(index)">
						<view class="herder_text"></view>
						<view class="herder_view">
							实验设备{{(index + 1)}}
						</view>
						<u-icon name="trash-fill" style="margin-ledt: 10rpx;" color="red" v-if="type=='edit'"></u-icon>
					</view>
					<u--input class="marginTop20" readonly placeholder="请选择" border="surround" :disabled="type=='view'"
						@click.native="add(index,'experimentEquipmentList',2)" v-model="item.equipmentName">

					</u--input>
					<view class="herder_item marginTop20">
						<view class="herder_text"></view>
						<view class="herder_view">
							开始时间
						</view>
					</view>


					<uni-datetime-picker v-if="type=='edit'" type="datetime" class="marginTop20"
						v-model="item.startTime"></uni-datetime-picker>
					<u-input v-else :disabled="true" placeholder=" " border="surround" class="marginTop20"
						:value="item.startTime"></u-input>
					<view class="herder_item marginTop20">
						<view class="herder_text"></view>
						<view class="herder_view">
							结束时间
						</view>
					</view>
					<uni-datetime-picker v-if="type=='edit'" type="datetime" class="marginTop20"
						v-model="item.endTime"></uni-datetime-picker>
					<u-input v-else :disabled="true" placeholder=" " border="surround" class="marginTop20"
						:value="item.endTime"></u-input>
					<view class="herder_item marginTop20">
						<view class="herder_text"></view>
						<view class="herder_view">
							运行参数
						</view>
					</view>
					<u-input class="marginTop20" placeholder="请输入内容" border="surround" :disabled="type=='view'"
						v-model="item.operatingParameters">

					</u-input>
				</view>

				<view class="marginTop20" v-if="type=='edit'">
					<view class="experimentP" @click="addExperimentEquipmentList"><u-icon name="plus-circle"
							style="margin-right: 10rpx;"></u-icon>添加实验设备
					</view>
				</view>
				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						工艺要求
					</view>
				</view>
				<view class="marginTop20 defValue">

					{{ form.processRequirementsJson}}
				</view>


				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						实验工具

					</view>
					<u-badge max="99" :value="form.toolJson.length"></u-badge>
				</view>
				<view class="marginTop20">
					<view class="experimentP" @click="addTool('toolJson')"><u-icon name="plus-circle"
							style="margin-right: 10rpx;"></u-icon> {{type=='view'?'查看实验工具':'添加实验工具'}}
					</view>
				</view>
				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						实验耗材
					</view>
					<u-badge max="99" :value="form.consumablesJson.length"></u-badge>
				</view>
				<view class="marginTop20">
					<view class="experimentP" @click="addTool('consumablesJson')"><u-icon name="plus-circle"
							style="margin-right: 10rpx;"></u-icon> {{type=='view'?'查看实验耗材':'添加实验耗材'}}
					</view>
				</view>
				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						实验过程
					</view>
				</view>
				<experimentationProcess ref="experimentationProcess1" :readonly="type=='view'" class="marginTop20"></experimentationProcess>
				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						实验记录
					</view>
				</view>
				<experimentationProcess ref="experimentationProcess2" :readonly="type=='view'" class="marginTop20"></experimentationProcess>
				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						实验结果
					</view>
				</view>
				<u--textarea class="marginTop20" placeholder="请输入内容" border="surround" autoHeight
					:disabled="type=='view'" v-model="form.resultsDescription"></u--textarea>
				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						实验结论
					</view>
				</view>
				<uni-data-picker v-if="type!='view'" class="marginTop20" v-model="form.results" placeholder="请选择"
					:localdata="[{
					text:'合格',value:1
				},{
					text:'不合格',value:2
				}]">
				</uni-data-picker>
				<u-input disabled v-else class="marginTop20" placeholder="请输入内容" border="surround"
					:value="form.results==2?'不合格':'合格'">
				</u-input>
				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						实验图片
					</view>
				</view>
				<view v-if="type!='view'" class="marginTop20 imgAdd" @click="chooseImage('imgUrl')">
					<u-icon name="camera"></u-icon>
				</view>
				<PreviewPhoto :type="type" @imagedelete="imagedelete" :imageList="imgUrl" />
				<view class="herder_item marginTop20">
					<view class="herder_text"></view>
					<view class="herder_view">
						附件图片
					</view>
				</view>
				<view v-if="type!='view'" class="marginTop20 imgAdd" @click="chooseImage('attachmentUrl')">
					<u-icon name="camera"></u-icon>
				</view>
				<PreviewPhoto :type="type" @imagedelete="imagedelete1" :imageList="attachmentUrl" />
			</view>
			<view style="height: 84rpx;"></view>
			<view class="footerButton">
				<u-button @click="cancel" type="default" text="返回"></u-button>
				<u-button v-if="type!='view'" type="primary" @click="save" text="保存"></u-button>
			</view>

		</view>
		<u-popup :show="toolJsonShow" :closeable="false" v-if="toolJsonShow">
			<view style="min-height:400rpx;position:relative">
				<uni-nav-bar fixed="true" statusBar="true" left-icon="back" :title="toolKey=='toolJson'?'实验工具':'实验耗材'"
					@clickLeft="toolJsonShow=false">

				</uni-nav-bar>
				<view v-for="(item, index) in form[toolKey]" :key="index" style="position: relative;">
					<myCard :item="item" :index="index+1" :btnList="[{
					name: '删除',
					apiName: 'del',
					btnType: 'error ',
					type: '2',
					pageUrl: '',
					judge: [{
						fn: isBtn
					}],
				}]" :columns="columns()" @del="del(index)">

						<u-input slot="batchNo" placeholder="请输入" border="surround" :disabled="type=='view'"
							v-model="item.batchNo">
						</u-input>
						<u--textarea slot="remark" placeholder="请输入内容" border="surround" autoHeight
							:disabled="type=='view'" v-model="item.remark"></u--textarea>
					</myCard>
				</view>
				<view class="add" @click="add(-1,toolKey,1)" v-if="type=='edit'">
					<u-icon name="plus" color="#fff"></u-icon>
				</view>
			</view>


		</u-popup>
	</u-popup>
</template>

<script>
	const defForm = {
		experimentalTime: '',
		qualityStandardType: '',
		workshopId: '',
		workshopName: '',
		processRequirementsJson: '',
		resultsDescription: '',
		results: 1,
		experimentEquipmentList: [],
		imgUrl: [],
		attachmentUrl: [],
		toolJson: [],
		consumablesJson: [],
		correlationId: '',
		qualityStandardName: '',
		qualityStandardId: '',
		qualityWorkOrderId: '',
	}
	import dictMixns from '@/mixins/dictMixins'
	import {
		getFactoryarea,
		getByIdExperiment,
		saveExperiment,
		updateExperiment
	} from '@/api/inspectionWork/index.js'
	import PreviewPhoto from '@/pages/maintenance/check/components/PreviewPhoto.vue'
	import myCard from '@/pages/saleManage/components/myCard.vue'
	import experimentationProcess from '@/components/templateDiv/experimentationProcess.vue'

	export default {
		mixins: [dictMixns],
		components: {
			PreviewPhoto,
			myCard,
			experimentationProcess
		},
		props: {
			type: {
				type: String,
				default: 'view'
			},
		},
		computed: {
			imgUrl() {
				return this.form.imgUrl.map(item => {
					return this.getFileUrl(item)
				})
			},
			attachmentUrl() {
				return this.form.attachmentUrl.map(item => {
					return this.getFileUrl(item)
				})
			}
		},

		data() {
			return {
				dateShow: false,
				toolJsonShow: false,
				form: {
					...defForm
				},
				laboratoryList: [],
				show: false,
				currentIndex: '',
				currentKey: '',
				toolKey: '',
				projectData: {}

			}
		},
		created() {
			uni.$off('setProduceList')
			uni.$on('setProduceList', (data) => {
				if (this.currentKey == 'experimentEquipmentList') {
					this.$set(
						this.form[this.currentKey][this.currentIndex],
						'equipmentId',
						data[0].id
					);
					this.$set(
						this.form[this.currentKey][this.currentIndex],
						'equipmentName',
						data[0].name
					);
				} else {
					this.form[this.currentKey].push(...data)
				}

			})
		},
		onUnload() {
			uni.$off('setProduceList')

		},
		methods: {
			isBtn() {
				return this.type == 'edit'
			},
			columns() {
				console.log(this.toolKey, 'this.toolKey')
				if (this.toolKey == 'toolJson') {
					return [
						[{
							label: '工具名称：',
							prop: 'name',
							type: 'title',
						}],
						[{
							label: '型号：',
							prop: 'modelType'
						}],
						[{
							label: '编号：',
							prop: 'code'
						}],
						[{
							label: '操作：',
							prop: 'action',
							type: 'action',
							className: 'perce100',
						}],
					]
				} else {
					return [
						[{
							label: '耗材名称：',
							prop: 'name',
							type: 'title',
						}],
						[{
							label: '编号：',
							prop: 'code'
						}],
						[{
							label: '批次号：',
							prop: 'batchNo',
							slot: 'batchNo',
						}],
						[{
							label: '浓度：',
							prop: 'specification',
						}],
						[{
							label: '来源：',
							prop: 'gys',
						}],
						[{
							label: '过程：',
							prop: 'remark',
							slot: 'remark',
						}],
						[{
							label: '操作：',
							prop: 'action',
							type: 'action',
							className: 'perce100',
						}],
					]
				}
			},
			getFileUrl(item) {
				let fileNames = item.storePath.split('/')
				let url = this.apiUrl +
					'/main/file/getFile?objectName=' + item.storePath +
					'&fullfilename=' + fileNames[fileNames.length -
						1]
				return url
			},

			getWorkshopId({
				detail
			}) {
				if (detail.value[0]) {
					this.form.workshopId = detail.value[0].value
				} else {
					this.form.workshopId = ''
				}

			},
			add(index, key, type) {
				this.currentIndex = index;
				this.currentKey = key
				uni.navigateTo({
					url: '/pages/purchasingManage/components/selectProduce?isAll=' + type
				})
			},
			imagedelete(index) {
				this.form.imgUrl.splice(index, 1);
			},
			imagedelete1(index) {
				this.form.attachmentUrl.splice(index, 1);
			},
			addTool(key) {
				this.toolKey = key
				this.toolJsonShow = true
			},
			del(index) {
				this.form[this.toolKey].splice(index, 1);
			},
			delEquipmentList(index) {
				if (this.view == 'view') {
					return
				}
				this.form.experimentEquipmentList.splice(index, 1);

			},
			async open(row, type) {
				this.projectData = row
				if (row.experimentId) {
					this.$set(this, 'form', await getByIdExperiment(row.experimentId));
				} else {
					this.form.correlationId = row.id;
					this.form.qualityStandardName = row.qualityStandardName;
					this.form.qualityStandardId = row.qualityStandardId;
					this.form.qualityWorkOrderId = row.qualityWorkOrderId;
					this.form.recordJson = row.recordJson;
					this.form.procedureJson = row.procedureJson;
					if (row.symbol) {
						this.form.processRequirementsJson += row.symbol;
					}
					if (row.textType == 3) {
						this.form.processRequirementsJson +=
							row.minValue + '-' + row.maxValue;
					} else {
						this.form.processRequirementsJson += row.defaultValue;
					}
					if (row.unitName) {
						this.form.processRequirementsJson += row.unitName;
					}
				}
				getFactoryarea({
					pageNum: 1,
					size: 1000,
					type: 3
				}).then(res => {
					this.laboratoryList = res.list.map(item => {
						return {
							text: item.workshopName,
							value: item.workshopId
						}
					})
				})
				this.show = true
				this.$nextTick(() => {
					// console.log(this.form,'this.form')
					if (this.form.procedureJson) {
						this.$refs.experimentationProcess1.init(
							this.form.procedureJson.tempJson
						);
					}
					if (this.form.recordJson) {
						this.$refs.experimentationProcess2.init(
							this.form.recordJson.tempJson
						);
					}
				});

				// this.init()
			},

			chooseImage(key) {
				const _this = this
				uni.chooseImage({
					count: 9, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: function(res) {
						uni.showLoading({
							title: '加载中'
						})

						_this.uploadFile(res.tempFilePaths).then(res => {
							_this.form[key].push(...res)
							console.log(this.form)
							// res.forEach(item => {
							// 	let fileNames = item.storePath.split('/')
							// 	let url = _this.apiUrl +
							// 		'/main/file/getFile?objectName=' + item.storePath +
							// 		'&fullfilename=' + fileNames[fileNames.length -
							// 			1]
							// 	_this.imgs.push(url)
							// })
							uni.hideLoading()

						})

					}
				});
			},
			uploadFile(list) {
				let PromiseAll = []
				const apiUrl = this.apiUrl
				const token = uni.getStorageSync("token"); //取存本地的token
				list.forEach(item => {
					PromiseAll.push(
						new Promise((resolve, reject) => {
							uni.uploadFile({
								url: apiUrl + '/main/file/upload',
								filePath: item,
								name: 'multiPartFile',
								header: {
									authorization: token
								},
								success: (uploadFileRes) => {
									let data = JSON.parse(uploadFileRes.data)
									resolve(data.data)
								}
							});
						}),
					)
				})

				return Promise.all(PromiseAll)

			},
			cancel() {
				this.form = {
					...defForm
				}
				this.show = false;
			},

			addExperimentEquipmentList() {
				this.form.experimentEquipmentList.push({});
			},
			save() {
				// if (!this.form.qualityResultContent) {
				// 	this.$refs.uToast.show({
				// 		type: "error",
				// 		icon: false,
				// 		message: "请填写质检内容！",
				// 	}, )
				// 	return
				// }
				// if (!this.form.sampleQuantity) {
				// 	this.$refs.uToast.show({
				// 		type: "error",
				// 		icon: false,
				// 		message: "请填写样品数！",
				// 	}, )
				// 	return
				// }
				let data = JSON.parse(JSON.stringify(this.form));
				let procedureJson = this.$refs.experimentationProcess1.getValue();
				let recordJson = this.$refs.experimentationProcess2.getValue();
				if (procedureJson) {
					data.procedureJson = {
						tempJson: JSON.stringify(procedureJson)
					};
				}
				if (recordJson) {
					data.recordJson = {
						tempJson: JSON.stringify(recordJson)
					};
				}
				let api = data.id ? updateExperiment : saveExperiment
				// console.log(data,'data')
				// return
				api(data)
					.then((msg) => {

						
						this.$emit('success', {
							workId: data.qualityWorkOrderId,
							projectId: this.projectData.id,
						})
						this.cancel()
					})
					.catch((e) => {
						this.cancel()
					});
			},




		}
	}
</script>

<style lang="scss" scoped>
	.mainBox {
		background-color: #f3f8fb;
		height: 100vh;
		font-size: 27rpx;
		overflow-y: auto;
	}

	.footerButton {
		width: 100%;
		height: 84rpx;
		display: flex;
		position: fixed;
		bottom: 0;
		z-index: 10;
		background-color: #fff;

		/deep/.u-button {
			height: 100%;
		}

		>view {
			flex: 1;
		}
	}

	.defValue {
		color: #c1353c;
		text-indent: 2ch;
	}

	/deep/.uni-textarea {
		padding: 0;
		max-height: auto;
	}

	/deep/uni-textarea {
		max-height: auto;
	}

	/deep/.input-value {
		font-size: 28rpx !important;
		height: 70rpx
	}

	.defValue {
		color: #c1353c;
		text-indent: 2ch;
	}

	.marginTop20 {
		margin-top: 30rpx;
	}


	.herder_item {
		display: flex;

		font-weight: bold;
		// font-size: 26rpx;

		.herder_text {

			min-width: 10rpx;
			height: 32rpx;
			border-radius: 10rpx;
			background: #00c0a1;
			margin-right: 12rpx;
			margin-top: 5rpx;
		}
	}

	.wrapper {
		width: 720rpx;
		background: #fff;
		margin: 20rpx auto 0;
		border-radius: 30rpx;
		padding: 26rpx;
	}

	.experimentP {
		width: 100%;
		background-color: #f7f8fa;
		border-radius: 20rpx;
		height: 80rpx;
		justify-content: center;
		align-items: center;
		display: flex;
		font-weight: 800;
	}

	.imgAdd {
		width: 160rpx;
		height: 160rpx;
		background-color: #f7f8fa;
		border-radius: 20rpx;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.add {
		width: 96rpx;
		height: 96rpx;
		border-radius: 48rpx;
		background: #3c9cff;
		position: absolute;
		bottom: 50rpx;
		right: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
</style>