<template>
	<div class="reviewRecord">
		<headNav
			@backPage="backPage"
			:RText="showR"
			@addRoad="linkToRecord"
			:title="'监督检查记录'"
		></headNav>

		<div class="topInfo">
			<div class="item FontColorNormal mb10">
				<div class="label">文件名称</div>
				<div class="FontColorInfo">消防监督检查记录</div>
			</div>

			<div class="item FontColorNormal">
				<div class="label">下发单位</div>
				<div class="FontColorInfo">监督检查单位</div>
			</div>

			<div class="item FontColorNormal">
				<div class="label">编号</div>
				<div class="FontColorInfo">{{ codeNum }}</div>
			</div>

			<div class="item FontColorNormal">
				<div class="label">检查时间</div>
				<div v-if="!isHasRecord" class="FontColorNormal cont" @click="show_time = true">
					<div class="mr5 FontColorInfo">{{ currentDate.toLocaleDateString() }}</div>
					<div class="icon"><van-icon name="arrow" /></div>
				</div>
				<div v-else class="FontColorInfo">{{ currentDate.toLocaleDateString() }}</div>
			</div>

			<div class="item FontColorNormal">
				<div class="label">检查类型</div>
				<div
					v-if="!isHasRecord"
					class="FontColorNormal cont_type"
					@click="show_type = true"
				>
					<div class="mr5 FontColorInfo">{{ getCheckName(checkType) }}</div>
					<div class="icon df"><van-icon name="arrow" /></div>
				</div>
				<div v-else class="FontColorInfo">{{ getCheckName(checkType) }}</div>
			</div>

			<div class="compantSituation">
				<van-form>
					<div class="inputItem">
						<van-field
							label="单位（场所）名称"
							input-align="right"
							placeholder="请输入"
							v-model="companyName"
							:disabled="isHasRecord"
						/>
					</div>
					<div class="inputItem">
						<van-field
							label="地址"
							input-align="right"
							placeholder="请输入"
							v-model="address"
							:disabled="isHasRecord"
						/>
					</div>
					<div class="inputItem">
						<van-field
							label="主要责任人"
							input-align="right"
							placeholder="请输入"
							v-model="mainManager"
							:disabled="isHasRecord"
						/>
					</div>
					<div class="inputItem">
						<van-field
							label="联系人及方式"
							input-align="right"
							placeholder="请输入"
							v-model="mainContact"
							:disabled="isHasRecord"
						/>
					</div>
					<div class="inputItem">
						<div class="inputLabel">检查内容和情况</div>
						<van-field
							type="textarea"
							:disabled="isHasRecord"
							row="4"
							autosize
							placeholder="请输入检查内容和情况"
							v-model="checkContent"
						/>
					</div>
					<div class="inputItem">
						<div class="inputLabel">备注</div>
						<van-field
							type="textarea"
							:disabled="isHasRecord"
							autosize
							row="4"
							v-model="remarks"
							placeholder="请输入备注"
						/>
					</div>
				</van-form>
			</div>

			<div class="bottom">
				<div class="item FontColorNormal">
					<div class="label">检查结论</div>
					<div
						v-if="!isHasRecord"
						class="FontColorNormal cont_type"
						@click="show_res = true"
					>
						<div class="FontColorInfo">{{ checkResult }}</div>
						<div class="icon df"><van-icon name="arrow" /></div>
					</div>
					<div v-else class="FontColorInfo">{{ checkResult }}</div>
				</div>

				<div class="item FontColorNormal" v-if="!isHasRecord">
					<div>被检查单位（场所）签收</div>
					<div class="FontColorInfo">
						<div class="ml10 underline" @click="show_sign_checkCompany = true">
							打开签字坂
						</div>
					</div>
				</div>
				<div v-else class="item_sign FontColorNormal">
					<div>被检查单位（场所）签收</div>
					<div>
						<div class="signImg"><van-image :src="getSrc_Company"></van-image></div>
					</div>
				</div>

				<div class="item FontColorNormal" v-if="!isHasRecord">
					<div>检查人员签字</div>
					<div class="FontColorInfo">
						<div class="ml10 underline" @click="show_sign_checkPerson = true">
							打开签字坂
						</div>
					</div>
				</div>
				<div v-else class="item_sign FontColorNormal">
					<div>检查人员签字</div>
					<div>
						<div class="signImg"><van-image :src="getSrc_Person"></van-image></div>
					</div>
				</div>

				<div class="btn" v-if="!isHasRecord">
					<van-button type="info" @click="sureRecord">确定</van-button>
				</div>
			</div>

			<!-- 时间弹窗 -->
			<van-popup v-model="show_time" position="bottom">
				<van-datetime-picker
					type="date"
					:value="currentDate"
					title="选择年月日"
					:min-date="minDate"
					:max-date="maxDate"
					@cancel="show_time = false"
					@confirm="chooseDate"
				/>
			</van-popup>

			<!-- 类型弹窗 -->
			<van-popup v-model="show_type" position="bottom">
				<van-picker
					show-toolbar
					title="检查类型"
					:columns="missionSelect"
					:default-index="pickerDefault"
					@cancel="show_type = false"
					@confirm="chooseType"
				/>
			</van-popup>

			<!-- 结论弹窗 -->
			<van-popup v-model="show_res" position="bottom">
				<van-picker
					show-toolbar
					title="检查结论"
					:columns="missionResult"
					@cancel="show_res = false"
					@confirm="chooseResult"
				/>
			</van-popup>

			<!-- 签字弹窗 -->
			<van-popup v-model="show_sign_checkCompany" position="bottom">
				<div class="signContent">
					<sign-canvas
						class="sign-canvas"
						ref="SignCanvas_checkCompany"
						:options="options"
						v-model="signValue_checkCompany"
					/>
				</div>
				<div class="btn">
					<div>
						<van-button type="warning" @click="clearCanvas_checkCompany">
							清除
						</van-button>
					</div>
					<div>
						<van-button type="info" @click="show_sign_checkCompany = false">
							保存
						</van-button>
					</div>
				</div>
			</van-popup>

			<van-popup v-model="show_sign_checkPerson" position="bottom">
				<div class="signContent">
					<sign-canvas
						class="sign-canvas"
						ref="SignCanvas_checkCompany"
						:options="options"
						v-model="signValue_checkPerson"
					/>
				</div>
				<div class="btn">
					<div>
						<van-button type="warning" @click="clearCanvas_checkPerson">
							清除
						</van-button>
					</div>
					<div>
						<van-button type="info" @click="show_sign_checkPerson = false">
							保存
						</van-button>
					</div>
				</div>
			</van-popup>
		</div>

		<!-- 遮罩层 -->
		<v-mask :showOverLay="showOverLay" :tipMsg="tipMsg"></v-mask>
	</div>
</template>

<script>
import headNav from '@/components/headNav.vue';
import mask_overLay from '@/components/overLay_xy.vue';
import { get, post, put, postImg, imgBaseUrl } from '@/utils/http.js';

export default {
	name: 'reviewRecord',
	components: {
		headNav,
		'v-mask': mask_overLay
	},
	data() {
		return {
			show_time: false,
			show_type: false,
			show_res: false,
			showR: '',
			currentDate: new Date(),
			minDate: new Date(2000, 0, 1),
			maxDate: new Date(2050, 10, 1),
			missionSelect: [
				'大型群众性活动举办前的检查',
				'建设工程施工现场检查',
				'对举报投诉的核查',
				'复查',
				'申请恢复施工、使用、生产、经营的检查',
				'申请解除临时查封的检查',
				'其他检查'
			],
			pickerDefault: 3,
			missionResult: ['已改', '未改'],
			signValue_checkCompany: '',
			signValue_checkPerson: '',
			options: {
				isSign: true,
				isShowBorder: false,
				canvasWidth: 350,
				canvasHeight: 245,
				bgColor: '#aaffff'
			},
			show_sign_checkCompany: false,
			show_sign_checkPerson: false,
			showOverLay: false,
			tipMsg: '加载中',
			checkType: '4',
			checkResult: '已改',
			companyName: '',
			address: '',
			mainManager: '',
			mainContact: '',
			checkContent: '',
			remarks: '',
			isHasRecord: false,
			companyInfo: '',
			codeNum: ''
		};
	},
	mounted() {
		this.init();
	},
	computed: {
		getSrc_Company() {
			return imgBaseUrl + this.signValue_checkCompany;
		},
		getSrc_Person() {
			return imgBaseUrl + this.signValue_checkPerson;
		}
	},
	methods: {
		// 初始化
		async init() {
			if (this.$route.params.status != undefined) {
				this.isReportCheck = true;
			}

			if (this.isReportCheck) {
				if (this.$route.params.status === '1') {
					this.checkType = '3';
					this.pickerDefault = 2;
				} else {
					this.checkType = '7';
					this.pickerDefault = 6;
				}
			}

			this.tipMsg = '加载中';
			this.showOverLay = true;
			const res = await this.getConditionApi();
			this.getCodeApi();
			this.showOverLay = false;
			if (res.data.length > 0) {
				this.isHasRecord = true;

				this.currentDate = new Date(res.data[0].checkaName);
				this.checkType = res.data[0].checkType;
				this.companyName = res.data[0].unitsSiteName;
				this.address = res.data[0].unitsAddr;
				this.mainManager = res.data[0].mainPricipalName;
				this.mainContact = res.data[0].contactTel;
				this.checkContent = res.data[0].checkCont;
				this.remarks = res.data[0].checkRemark;
				this.checkResult = res.data[0].checkEndResult === '1' ? '已改' : '未改';
				this.signValue_checkCompany = res.data[0].unitsSign;
				this.signValue_checkPerson = res.data[0].unitsPersonSign;
				
				this.isReportCheck && (this.showR = '判断');
			} else {
				this.isHasRecord = false;
				await this.getCompanyInfoApi();
				this.companyName = this.companyInfo.unitName;
				this.address = this.companyInfo.unitAddress;
				this.mainManager = this.companyInfo.unitlegalPerson;
				this.mainContact = this.companyInfo.principalPhone;
				const hasCheckedList = this.$store.state.review.hasCheckedList;

				let contentArr = '';
				hasCheckedList.map(item => {
					if (item.recheckStatus === '1') {
						contentArr +=
							item.itemName +
							'：' +
							item.recheckDesc +
							' (已改)' +
							' ' +
							' ' +
							' ' +
							' ';
					} else {
						contentArr +=
							item.itemName +
							'：' +
							item.recheckDesc +
							' (未改)' +
							' ' +
							' ' +
							' ' +
							' ';
					}
				});
				this.checkContent = contentArr;
			}
		},

		async getConditionApi() {
			return get('/cdsupervisionCheckRecord/listByCondition', {
				taskId: this.$route.params.taskId
			});
		},

		async getCompanyInfoApi() {
			let byCheckId = this.$store.state.taskInfo.taskInfo.companyId;

			await get(`/cdSuperObjE/get/${byCheckId}`).then(res => {
				if (res.success == true) {
					this.companyInfo = res.data;
				}
			});
		},

		// 获取编号
		async getCodeApi() {
			await get('/cdsupervisionCheckRecord/getSerialNum').then(res => {
				res.success && (this.codeNum = res.data);
			});
		},

		linkToRecord() {
			this.$router.push(
				`/checkResultDetail/${this.$route.params.ID}/${this.$route.params.taskId}/1`
			);
		},

		// 后退一栏
		backPage() {
			this.$router.go(-1);
		},

		// 选择日期
		chooseDate(value) {
			this.currentDate = value;
			this.show_time = false;
		},

		// 选定类型
		chooseType(value, index) {
			this.checkType = (index + 1).toString();
			this.show_type = false;
		},

		// 选定结论
		chooseResult(value) {
			this.checkResult = value;
			this.show_res = false;
		},

		// 清除画布
		clearCanvas_checkCompany() {
			this.$refs.SignCanvas_checkCompany.canvasClear();
		},

		clearCanvas_checkPerson() {
			this.$refs.SignCanvas_checkCompany.canvasClear();
		},

		// 获取check名字
		getCheckName(index) {
			switch (index) {
				case '1':
					return '大型群众性活动举办前的检查';
				case '2':
					return '建设工程施工现场检查';
				case '3':
					return '对举报投诉的核查';
				case '4':
					return '复查';
				case '5':
					return '申请恢复施工';
				case '6':
					return '申请解除临时查封的检查';
				case '7':
					return '其他检查';
			}
		},

		// base64转blob
		dataURItoBlob(base64Data) {
			var byteString;

			if (base64Data.split(',')[0].indexOf('base64') >= 0)
				byteString = atob(base64Data.split(',')[1]);
			else byteString = unescape(base64Data.split(',')[1]);

			var mimeString = base64Data
				.split(',')[0]
				.split(':')[1]
				.split(';')[0];

			var ia = new Uint8Array(byteString.length);

			for (var i = 0; i < byteString.length; i++) {
				ia[i] = byteString.charCodeAt(i);
			}

			return new Blob([ia], {
				type: mimeString
			});
		},

		async postImgApi(file) {
			return postImg('/upload/moreUploadImg', file);
		},

		//  确定保存监督检查记录
		async sureRecord() {
			if (this.companyName === '' || this.companyName.trim() === '') {
				this.$toast.fail('请输入单位名称');
			} else if (this.address === '' || this.address.trim() === '') {
				this.$toast.fail('请输入地址');
			} else if (this.mainManager === '' || this.mainManager.trim() === '') {
				this.$toast.fail('请输入主要负责人');
			} else if (this.mainContact === '' || this.mainContact.trim() === '') {
				this.$toast.fail('请输入联系方式');
			} else if (this.checkContent === '' || this.checkContent.trim() === '') {
				this.$toast.fail('请输入检查内容情况');
			} else if (this.remarks === '' || this.remarks.trim() === '') {
				this.$toast.fail('请输入备注');
			} else if (!this.signValue_checkCompany) {
				this.$toast.fail('被检查单位未签收');
			} else if (!this.signValue_checkPerson) {
				this.$toast.fail('检查人员未签字');
			} else {
				this.showOverLay = true;
				this.tipMsg = '数据提交中';

				let time = this.$getTime(this.currentDate);
				time = time.split(' ');

				var blob1 = this.dataURItoBlob(this.signValue_checkCompany); // 上一步中的函数

				var fd1 = new FormData();

				fd1.append('file', blob1, `${new Date().getTime()}.png`);

				let res1 = await this.postImgApi(fd1);

				let imgSrc1 = '';
				if (res1.success) {
					imgSrc1 = res1.data;
				}

				var blob2 = this.dataURItoBlob(this.signValue_checkPerson); // 上一步中的函数

				var fd2 = new FormData();

				fd2.append('file', blob2, `${new Date().getTime()}.png`);

				let res2 = await this.postImgApi(fd2);

				let imgSrc2 = '';
				if (res2.success) {
					imgSrc2 = res2.data;
				}

				let byCheckId = this.$store.state.taskInfo.taskInfo.companyId;

				const subData = {
					taskId: this.$route.params.taskId,
					checkaName: time[0],
					checkType: this.checkType.toString(),
					unitsSiteName: this.companyName,
					unitsAddr: this.address,
					mainPricipalName: this.mainManager,
					contactTel: this.mainContact,
					checkCont: this.checkContent,
					checkRemark: this.remarks,
					checkEndResult: this.checkResult === '已改' ? '1' : '2',
					unitsSign: imgSrc1,
					unitsPersonSign: imgSrc2,
					serialNum: this.codeNum,
					objId: byCheckId
				};

				if (this.isReportCheck) {
					//  举报检查
					const res_record = await this.saveRecheckRecordApi(subData);

					if (res_record) {
						this.showOverLay = false;
						
						this.$router.push(
							`/checkResult/${this.$route.params.ID}/${
								this.$route.params.taskId
							}`
						);
					} else {
						this.showOverLay = false;
						this.$toast.fail(res_record);
					}
				} else {
					// 复查
					const res_review = await this.saveReviewApi();

					if (res_review === true) {
						const res_record = await this.saveRecheckRecordApi(subData);
						if (res_record === true) {
							this.$router.push('/');
						} else {
							this.showOverLay = false;

							this.$toast.fail(`${res_record}`);
						}
					} else {
						this.showOverLay = false;
						this.$toast.fail(`${res_review}`);
					}
				}
			}
		},

		// 上传复查记录
		async saveReviewApi() {
			const hasCheckedList = this.$store.state.review.hasCheckedList;
			const res = await post('/cdsupervisionAnswer/resCheck', hasCheckedList);
			if (res.success === false) {
				return res.msg;
			} else {
				return true;
			}
		},

		// 上传监督检查记录
		async saveRecheckRecordApi(subList) {
			const res = await post('/cdsupervisionCheckRecord/add', subList);
			if (res.success === false) {
				return res.msg;
			} else {
				return true;
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.reviewRecord {
	font-size: 14px;

	.headTip {
		margin-bottom: 10px;
		padding: 0 10px;
	}

	.underline {
		text-decoration: underline;
	}

	.topInfo {
		margin-top: 57px;

		.item {
			background-color: #fff;
			padding: 10px 15px;
			border: 1px solid #fcfcfc;
			display: flex;
			align-items: center;
			font-size: 12px;
			border-bottom: none;
			justify-content: space-between;

			.label {
				width: 80px;
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				color: #646566;
				font-size: 13px;
			}

			.cont {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin: 0 5px;
				margin-top: 2px;
			}

			.cont_type {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin: 0 5px;
			}
		}

		.item_sign {
			background-color: #fff;
			padding: 10px 15px;
			border: 1px solid #fcfcfc;
			font-size: 12px;
			border-bottom: none;

			.signImg {
				margin-top: 10px;
				width: 100%;
				background-color: #d4ffff;
				border: 1px solid #b9b9b9;
				border-radius: 5px;
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}
	}

	.compantSituation {
		margin-top: 10px;
		background-color: #fff;

		.inputLabel {
			padding-left: 16px;
			margin-top: 10px;
			font-size: 13px;
			color: #646464;
		}
	}

	.bottom {
		margin-top: 10px;

		.btn {
			width: 100%;
			display: flex;
			justify-content: center;

			button {
				margin: 10px 15px;
			}
		}
	}

	.btn {
		width: 100%;
		display: flex;
		justify-content: center;

		div {
			flex: 1;
			padding: 0px 13px;

			&:first-child {
				padding-right: 5px;
			}

			&:last-child {
				padding-left: 5px;
			}
		}
		button {
			height: 35px;
			width: 100%;
		}
	}

	.signContent {
		width: 100%;
		height: 260px;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}
</style>

<style lang="scss">
.reviewRecord {
	.van-cell.van-field {
		border-bottom: 1px solid #fcfcfc;
	}

	.van-cell__title.van-field__label {
		width: 120px;
		font-size: 13px;
	}

	.van-field__control {
		// background-color: #fcfcfc;
		padding: 3px 10px;
		border-bottom: 1px solid #f3f3f3;
	}

	.van-cell__value.van-cell__value--alone.van-field__value {
		.van-field__control {
			background-color: #fdfdfd;
			padding: 3px 10px;
			height: 120px !important;
		}
	}

	.icon {
		display: flex;
		align-items: center;
		color: #9e9e9e;
	}

	.van-field--disabled .van-field__label {
		color: #646566;
	}
}
</style>
