<template>
	<view class="" id="page">
		<view class="Width100 Box BorderBox">
			<top-title :is-show-left="true" :title="'治理结果'" class="custom_bg">
			</top-title>
		</view>
		<view class="navBar-top">

		</view>
		<view class="form-content">
			<view>
				<uni-forms border style="margin-bottom: 12px;">
					<view class="formBox" v-for="(itemData,indexData) in hiddenDangerList" :key="indexData">
						<view class="label-box">
							<view class="border"></view> 问题{{formatIndex(indexData)}}
						</view>
						<view style="margin-bottom:20rpx; display: flex; align-items: baseline">
							<uni-forms-item label="问题类型" label-position="top" label-width="80px" />
							<view class="value" style="font-size:28rpx">
								{{ itemData.dangerProblem}}
							</view>
						</view>

						<view style="margin-bottom: 30rpx;">
							<view class="investigation-item" style="width: 100%; padding: 0">
								<view class="detail-item">
									<uni-forms-item label="问题描述" label-position="top" label-width="200px" />
									<u-textarea placeholder="- -" :disabled="true" border="none"
										v-model="itemData.hdDesc" style="margin-top: -20rpx;" />
								</view>
							</view>
							<view class="investigation-item" style="width: 100%; padding: 0">
								<view class="detail-item">
									<uni-forms-item label="隐患图片" label-position="top" label-width="200px" />
									<u-upload :fileList="itemData.hdPic" :disabled="true" style="margin-top: -20rpx;"
										name="1" :maxCount="10"></u-upload>
								</view>
							</view>
							<view class="investigation-item" style="width: 100%; padding: 0">
								<view class="detail-item">
									<uni-forms-item label="补充信息" label-position="top" label-width="200px" />
									<u-textarea :disabled="true" placeholder="- -" border="none"
										v-model="itemData.hdInfo" style="margin-top: -20rpx;" />
								</view>
							</view>
							<view class="investigation-item" style="width: 100%; padding: 0">
								<view class="detail-item">
									<uni-forms-item label="治理措施" label-position="top" label-width="100px" required />
									<!-- <upload-file @fileSuccess="fileSuccess.call(this,$event, indexData)"
										@fileDelete="fileDelete.call(this, $event, indexData)"
										:fileList="itemData.zlMeasure" /> -->
									<u-textarea placeholder="请输入治理措施" border="none" v-model="itemData.zlMeasure"
										style="margin-top: -20rpx;" />
								</view>
							</view>
							<view class="investigation-item" style="width: 100%; padding: 0">
								<view class="detail-item detail-item-flex">
									<uni-forms-item label="治理单位" label-position="top" label-width="100px" required />
									<input class="BorderNone Height100 formInput"
										style="font-size: 14px; text-align: right;" placeholder-style="fontSize: 14px"
										v-model="itemData.zlUnit" placeholder="请输入治理单位" />
								</view>
							</view>
							<view class="investigation-item" style="width: 100%; padding: 0">
								<view class="detail-item">
									<uni-forms-item label="治理后照片" label-position="top" label-width="100px" required />
									<locationUpload :fileList="itemData.zlPic" style="margin-top: -20rpx;" name="1"
										:maxCount="9" @afterRead="afterRead.call(this, $event,indexData)"
										@delete="deletePic.call(this, $event,indexData)"></locationUpload>
								</view>
							</view>
							<view class="investigation-item" style="width: 100%; padding: 0">
								<view class="detail-item detail-item-flex" @click="handleOpenDate(indexData)">
									<uni-forms-item label="完成时间" label-position="top" label-width="100px" required />
									<view class="value" :class="itemData.wcTime ? 'value-date' : 'value-placeholder'">
										{{itemData.wcTime || '请选择入完成时间'}}
									</view>
								</view>
							</view>

						</view>

					</view>
					<view class="formBox">
						<view class="investigation-item" style="width: 100%; padding: 0">
							<view class="detail-item detail-item-flex" style="align-items: baseline;">
								<uni-forms-item label="验收材料" label-position="top" label-width="100px" required />
								<upload-file @fileSuccess="fileSuccess.call(this,$event)"
									@fileDelete="fileDelete.call(this, $event)" :fileList="acceptanceData" />

							</view>
						</view>
						<view class="investigation-item" style="width: 100%; padding: 0">
							<view class="detail-item">
								<uni-forms-item label="验收照片" label-position="top" label-width="100px" required />
								<locationUpload :fileList="acceptancePhotos" style="margin-top: -20rpx;" name="1"
									:maxCount="9" @afterRead="afterReadImg.call(this, $event)"
									@delete="deletePic.call(this, $event, '')"></locationUpload>
							</view>
						</view>
					</view>
				</uni-forms>
			</view>
		</view>
		<three class="footer-buttons" :type="'view'" first-text="取消" next-text="确认" :second-primary="true"
			@first="handleBack" @last="handleSubmit" />
		<u-datetime-picker :show="dateShow" :value="dateTime" :maxDate="maxDate" @cancel="dateShow = false"
			@confirm="handleConfirm" mode="datetime" :defaultIndex="[1, 2, 1, 1, 1]"></u-datetime-picker>
	</view>
</template>

<script>
	import TopTitle from "../../components/top-title";
	import Three from "../../components/bottom-button/three.vue";
	import uploadFile from "../../components/upload-file.vue";
	import locationUpload from '@/components/u-upload/index.js'
	const indexList = ['一', '二', '三', '四', '五', '六', '七', '八', '九', '十', '十一', '十二', '十三', '十四', '十五', '十六', '十七', '十八',
		'十九', '二十'
	]
	export default {
		components: {
			TopTitle,
			Three,
			uploadFile,
			locationUpload
		},
		data() {
			return {
				hiddenDangerList: [],
				acceptancePhotos: [],
				acceptanceData: [],
				businessId: '',
				dateShow: false,
				dateTime: this.formatTime(),
				curIndex: 0,
				maxDate: null
			}
		},
		onLoad(e) {
			this.businessId = e.id
			this.initPage()
		},
		methods: {
			handleConfirm(value) {
				this.$set(this.hiddenDangerList[this.curIndex], 'wcTime', this.formatTime(value.value))
				this.dateShow = false
			},
			handleOpenDate(index) {
				this.curIndex = index
				this.dateTime = this.hiddenDangerList[index].wcTime || this.formatTime()
				this.$nextTick(() => {
					this.maxDate = this.getCurTimeForX()
					this.dateShow = true
				})
			},
			getCurTimeForX() {
				return (new Date()).getTime()
			},
			formatTime(time) {
				console.log(time)
				return this.$moment(time).format('YYYY-MM-DD HH:mm')
			},
			fileSuccess(result) {
				this.acceptanceData.push({
					id: this.uuid(),
					fileName: result.fileName,
					filePath: result.result
				})

			},
			fileDelete(fileIndex) {
				this.acceptanceData.splice(
					fileIndex,
					1,
				);
			},
			initPage() {
				this.$.showLoading()
				Promise.all([
						this.$request
						.globalRequest(
							"/hiddenDanger/highDanger/getUserHiddenDangerList", {
								// nuserid: this.$.getData("token"),
								pcType: 1,
								businessId: this.businessId
							},
							"GET"
						),
						this.$request
						.globalRequest(
							"/hiddenDanger/highDanger/getUserHiddenDangerList", {
								// nuserid: this.$.getData("token"),
								pcType: 2,
								businessId: this.businessId
							},
							"GET"
						)
					])
					.then((resArr) => {
						this.hiddenDangerList = resArr.reduce((arr, item) => {
							if (item.code === 200) {
								const itemResArr = item.result.map(item => ({
									...item,
									hdPic: item.hdPic ? item.hdPic.split(',').map(item => ({
										url: item
									})) : [],
									zlPic: []
								}))
								arr.push(...itemResArr)
							}
							return arr
						}, [])

					}).finally(() => {
						this.$.hideLoading()
					})
			},
			getPageData() {},
			formatIndex(index) {
				return indexList[index]
			},
			//获取随机id
			uuid(len, binary) {
				len = !len ? 36 : len;
				binary = !binary ? 16 : binary;
				return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx"
					.replace(/[xy]/g, function(c) {
						var r = (Math.random() * binary) | 0,
							v = c == "x" ? r : (r & 0x3) | 0x8;
						return v.toString(binary);
					})
					.substring(0, len);
			},
			async afterReadImg(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				const id = this.uuid();
				this.acceptancePhotos.push({
					id,
					...event.file,
					status: "uploading",
					message: "上传中",
				});
				const result = await this.uploadFilePromise(event);
				const resultInfo = JSON.parse(result);
				const fileIndex = this.acceptancePhotos.findIndex((v) => v.id === id);
				if (resultInfo.code == 200) {
					this.acceptancePhotos.splice(
						fileIndex,
						1,
						Object.assign(event.file, {
							status: "success",
							message: "",
							result: resultInfo,
							url: resultInfo.result,

						})
					);
					console.log(this.acceptancePhotos)
				} else {
					this.$.toast("上传失败");
					this.acceptancePhotos.splice(
						fileIndex,
						1,
					);
				}
			},
			deletePic(event, index) {
				if (index === '') {
					this.acceptancePhotos.splice(event.index, 1);
				} else {
					this.hiddenDangerList[index].zlPic.splice(event.index, 1);
				}
			},
			uploadFilePromise(event) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: this.$.baseUrl + "/hiddenDanger/ftp/uploadFileToFtp", // 仅为示例，非真实的接口地址
						filePath: event.file.url,
						name: "file",
						formData: {
							position: event.position,
							longitude: event.longitude,
							latitude: event.latitude
						},
						success: (res) => {
							resolve(res.data);
						},
					});
				});
			},
			async afterRead(event, index) {
				console.log(event, index)
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				const id = this.uuid();
				this.hiddenDangerList[index].zlPic.push({
					id,
					...event.file,
					status: "uploading",
					message: "上传中",
				});
				const result = await this.uploadFilePromise(event);
				const resultInfo = JSON.parse(result);
				const fileIndex = this.hiddenDangerList[index].zlPic.findIndex((v) => v.id === id);
				if (resultInfo.code == 200) {
					this.hiddenDangerList[index].zlPic.splice(
						fileIndex,
						1,
						Object.assign(event.file, {
							status: "success",
							message: "",
							result: resultInfo,
							url: resultInfo.result,

						})
					);
					console.log(this.hiddenDangerList[index].zlPic)
				} else {
					this.$.toast("上传失败");
					this.hiddenDangerList[index].zlPic.splice(
						fileIndex,
						1,
					);
				}
			},
			handleBack() {
				this.$.back(1)
			},
			getFormatData() {
				const hiddenDangerList = this.hiddenDangerList.map(item => ({
					zlMeasure: item.zlMeasure,
					zlPic: item.zlPic.map(item => item.url).join(','),
					zlUnit: item.zlUnit,
					wcTime: item.wcTime,
					hdTerm: item.hdTerm,
					nid: item.nid
				}))
				return {
					businessId: this.businessId,
					nuserid: this.$.getData('token'),
					acceptancePhotos: this.acceptancePhotos.map(item => item.url).join(','),
					acceptanceData: this.acceptanceData.map(item => item.filePath).join(','),
					describe: hiddenDangerList
				}
			},
			validDate(data) {
				const {
					describe = [], acceptanceData, acceptancePhotos
				} = data
				if (!describe.length || !acceptanceData.length || !acceptancePhotos.length) return false
				return describe.reduce((result, item) => {
					if (!result) return false
					const {
						zlMeasure,
						zlPic,
						zlUnit,
						wcTime
					} = item
					if (zlMeasure && zlPic && zlUnit && wcTime) {
						return true
					}
					return false
				}, true)
			},
			handleSubmit() {
				const formData = this.getFormatData()
				console.log('formData', formData)
				if (this.validDate(formData)) {
					this.$.showLoading()
					this.$request.globalRequest('/hiddenDanger/government/saveGovernment', formData, 'post').then(res => {
						if (res.code === 200) {
							console.log('提交成功', res)
							this.$.toast('提交成功')
							setTimeout(() => {
								this.handleBack()
							}, 500)
						}
					}).finally(() => {
						this.$.hideLoading()
					})
				} else {
					this.$.toast('请填写完整的表单必填项*')
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background: #F6F8FA;
		font-size: 14px;
	}

	.navBar-top {
		height: calc(var(--status-bar-height) + 88rpx);
	}

	.form-content {
		padding-bottom: 120rpx;
	}

	.formBox {
		margin: 30rpx 20rpx;
		border: 1px solid #e6e6e6;
		background: #ffffff;
		padding: 0 20rpx 20rpx;
		box-sizing: border-box;

		/deep/ .uni-forms-item--border .uni-forms-item__content {
			justify-content: flex-end;
			text-align: right;
		}

		.photo {
			width: 100%;

			image {
				width: 100%;
			}
		}
	}

	.label-box {
		display: flex;
		align-items: center;
		height: 110rpx;
		font-size: 30rpx;
		font-weight: 600;

		.border {
			background-color: #2663BF;
			height: 35rpx;
			width: 6rpx;
			margin-right: 14rpx;
		}
	}

	.detail-item-flex {
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.uni-forms-item--border {
		border: none;
	}

	.investigation-item {
		border-top: 1px solid #eee;
	}

	.value-placeholder {
		color: #B4BAC9
	}
</style>