<template>
	<!-- 入户安全检查 -->
	<view>
		<u-navbar title="入户安全检查" autoBack placeholder></u-navbar>
		<view class="card_order_details">
			<u--form labelPosition="top" :model="ruleForm" :rules="rules" ref="uForm" labelWidth="auto">
				<u-form-item label="入户检查图片" prop="homeCheckImg">
					<u-upload :fileList="fileList1" name="1" multiple :maxCount="10" @afterRead="afterRead"
						@delete="deletePic"></u-upload>
				</u-form-item>
				<u-form-item label="状态" prop="state">
					<u-radio-group v-model="ruleForm.state" placement="row">
						<u-radio shape="circle" :customStyle="{marginRight: '20px'}" v-for="(item, index) in radiolist"
							:key="index" :label="item.name" :name="item.value"></u-radio>
					</u-radio-group>
				</u-form-item>
				<u-form-item label="整改前照片" prop="beforeRectifyImg" v-if="ruleForm.state == 0">
					<u-upload :fileList="fileList2" name="2" multiple :maxCount="10" @afterRead="afterRead"
						@delete="deletePic"></u-upload>
				</u-form-item>
				<u-form-item label="客户签字" prop="customerImg">
					<view class="card_signs center_in" v-if="clientFlag" @click="goSignature('client')">客户签字</view>
					<u--image :showLoading="true" :src="imageData" width="200rpx" height="160rpx" v-else></u--image>
				</u-form-item>
				<u-form-item label="送气员签字" prop="signImg">
					<view class="card_signs center_in" v-if="aeratorFlag" @click="goSignature('aerator')">送气员签字</view>
					<u--image :showLoading="true" :src="aeratorData" width="200rpx" height="160rpx" v-else></u--image>
				</u-form-item>
			</u--form>
			<view class="card_plate">
				<view class="card_check">安全检查项目<span style="color: red;">*</span></view>
				<u-line></u-line>
				<view class="card_security">
					<view class="" v-for="(item,index) in checkEntry" :key="index">
						<view class="title_item_check">{{index + 1}}、{{item.label}}</view>
						<u-radio-group v-model="item.value" placement="row">
							<u-radio shape="circle" :customStyle="{marginRight: '20px'}"
								v-for="(item1, index1) in radioData" :key="index1" :label="item1.name"
								:name="item1.value"></u-radio>
						</u-radio-group>
					</view>
				</view>
			</view>
		</view>
		<view style="width: 100%;height: 170rpx;"></view>
		<view class="check_btn">
			<view class="btn_submit">
				<u-button type="primary" text="提交" @click="entrySecurity"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	const ENV = require('@/.env.js')
	import {
		check
	} from '@/static/js/announcements.js'
	export default {
		data() {
			return {
				fileList1: [],
				fileList2: [],
				radiolist: [{
					name: '合格',
					value: -1,
					disabled: false
				}, {
					name: '待整改',
					value: 0,
					disabled: false
				}],
				radioData: [{
					name: '合格',
					value: '0',
					disabled: false
				}, {
					name: '待整改',
					value: '1',
					disabled: false
				}],
				checkEntry: [],
				clientFlag: true,
				aeratorFlag: true,
				personnelType: '',
				imageData: '',
				aeratorData: '',
				ruleForm: {
					orderId: '',
					customerId: '',
					homeCheckImg: '',
					customerImg: '',
					signImg: '',
					state: -1,
					inspectExpandList: [],
				},
				rules: {
					'homeCheckImg': {
						type: 'string',
						required: true,
						message: '请上传入户检查图片',
						trigger: ['blur', 'change']
					},
					'customerImg': {
						type: 'string',
						required: true,
						message: '请上传客户签名',
						trigger: ['blur', 'change']
					},
					'signImg': {
						type: 'string',
						required: true,
						message: '请上传送气员签名',
						trigger: ['blur', 'change']
					},
				},
			}
		},
		onLoad(e) {
			this.ruleForm.orderId = e.orderId
			this.ruleForm.customerId = e.customerId
			//注册监听事件
			uni.$on('sign', (data) => {
				//base64编码的图片
				if (this.personnelType == 'client') {
					this.clientFlag = false
					this.imageData = data.replace(/[\r\n]/g, "");
					const blob = this.base64ToBlob(data);
					const url = URL.createObjectURL(blob);
					this.getUpload(url)
				} else {
					this.aeratorFlag = false
					this.aeratorData = data.replace(/[\r\n]/g, "");
					const blob = this.base64ToBlob(data);
					const url = URL.createObjectURL(blob);
					this.getUpload(url)
				}
				//处理自己的业务逻辑
			})
		},
		//销毁监听事件
		onUnload() {
			uni.$off('sign');
		},
		mounted() {
			this.checkEntry = check()
		},
		methods: {
			// 提价入户安全检查项
			entrySecurity() {
				this.$refs.uForm.validate().then(res => {
					const param = {
						...this.ruleForm
					}
					const arrList = []
					this.checkEntry.forEach(item => {
						const arr1 = {
							inspectItem: '',
							itemCode: '',
						}
						arr1.inspectItem = item.id
						arr1.itemCode = item.value
						arrList.push(arr1)
					})
					param.inspectExpandList = arrList
					this.$api.post('/api/inspect_record', param).then(res => {
						if (res.code == 200) {
							uni.$u.toast('操作成功')
							setTimeout(()=>{
								uni.navigateBack({
									delta: 1
								});
							},1500)
						}
					})
				}).catch(errors => {
					// uni.$u.toast('校验失败')
				})
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 签名板
			async getUpload(file) {
				const result = await this.uploadFilePromise(file)
				if (this.personnelType == 'client') {
					this.ruleForm.customerImg = result
				} else {
					this.ruleForm.signImg = result
				}
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				if (event.name == '1') {
					var arr = []
					this.fileList1.forEach(item1 => {
						arr.push(item1.url)
					})
					this.ruleForm.homeCheckImg = arr.join()
					this.$refs.uForm.validateField('homeCheckImg')
				} else {
					var arr1 = []
					this.fileList2.forEach(item2 => {
						arr.push(item2.url)
					})
					this.ruleForm.beforeRectifyImg = arr1.join()
					this.$refs.uForm.validateField('beforeRectifyImg')
				}
			},
			base64ToBlob(base64Data) {
				const arr = base64Data.split(','); // 分割Base64字符串
				const mimeType = arr[0].match(/:(.*?);/)[1]; // 获取MIME类型
				const byteString = atob(arr[1]); // Base64解码
				let n;
				const dataLength = byteString.length;
				const uInt8Array = new Uint8Array(dataLength);
				for (n = 0; n < dataLength; ++n) {
					uInt8Array[n] = byteString.charCodeAt(n);
				}
				return new Blob([uInt8Array], {
					type: mimeType
				});
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: ENV.APP_DEV_URL + '/api/upload', // 仅为示例，非真实的接口地址
						filePath: url,
						name: 'file',
						// formData: {
						// 	user: 'test'
						// },
						header: {
							'Authorization': 'Bearer ' + uni.getStorageSync('access_token'),
						},
						success: (res) => {
							let state = JSON.parse(res.data)
							setTimeout(() => {
								if (state.code == 200) {
									resolve(state.data)
								}
							}, 1000)
						}
					});
				})
			},
			// 签字
			goSignature(title) {
				this.personnelType = title
				uni.navigateTo({
					url: '/pages/order/signatureBoard'
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	.card_order_details {
		margin: 20rpx 40rpx;
	}

	.card_plate {
		margin-top: 20rpx;
		margin-bottom: 40rpx;
	}

	.details_title {
		color: #333;
		font-size: 40rpx;
		font-weight: 500;
	}

	.card_check {
		font-size: 34rpx;
		font-weight: 500;
		margin-bottom: 20rpx;
	}

	.title_item_check {
		margin-top: 30rpx;
		font-size: 30rpx;
		margin-bottom: 15rpx;
	}

	.check_btn {
		position: fixed;
		display: flex;
		align-items: center;
		justify-content: center;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: #fff;
		border-top: 1rpx solid #f7f7f7;
		padding-bottom: constant(safe-area-inset-bottom); //兼容 IOS<11.2
		padding-bottom: env(safe-area-inset-bottom); //兼容 IOS>11.2
	}

	.btn_submit {
		margin-top: 10rpx;
		padding-bottom: 20rpx;
		width: calc(100% - 80rpx);
	}

	.card_signs {
		width: 200rpx;
		height: 160rpx;
		background-color: #f4f5f7;
		color: #d3d4d6;
		font-size: 32rpx;
		border-radius: 4rpx;
	}
</style>