<template>
	<view>
		<cu-custom bgColor="bg-gradual-blueness" :isBack="true" :isRingt="true">
			<block slot="backText">返回</block>
			<block slot="content">检查信息</block>
		</cu-custom>
		<scroll-view scroll-y>
			<view class="cu-form-group">
				<view class="title">日期选择</view>
				<picker disabled mode="date" :value="date" start="2015-09-01" :end="date" @change="DateChange">
					<view class="picker">
						{{ date }}
					</view>
				</picker>
			</view>
			<view class="cu-form-group">
				<view class="title">时间选择</view>
				<picker disabled mode="time" :value="time" start="09:01" end="21:01" @change="TimeChange">
					<view class="picker">
						{{ time }}
					</view>
				</picker>
			</view>
			<view class="ace-list mt30">
				<view class="ace-title">
					<text class="text-semi">检查部门&人</text>
					<button v-if="ISLOG == '0'" class="cu-btn round bg-blue" @click="addOther">添加</button>
				</view>
				<view class="acb-content">
					<view class="add_pard_item" v-for="(item,index) of other">
						<view  class="add_pard_del" v-if="index>0 && ISLOG == '0'" @click="removeOther(index)">
							<text class="cuIcon-roundclosefill text-red f40"></text>
						</view>
						<view class="cu-form-group">
							<view class="title">检查部门</view>
							<view class="picker-tree-box">
								<view class="picker-tree" @tap="showYsTree(index)">
									{{ other[index].DEPARTMENT_NAME ? other[index].DEPARTMENT_NAME : '请选择' }}
								</view>
							</view>
							<tki-tree :ref="'tkiTree'+index" :selectParent=true :range="treeNode" rangeKey="name"
								@confirm="ystreeConfirm($event,index)"></tki-tree>
						</view>
						<view class="cu-form-group">
							<view class="title">检查人</view>
							<picker @change="PickerYsr($event,index)" :value="other[index].index"
								@click="haveUser(otherUserList[index])"
								:disabled="otherUserList[index] ==null || otherUserList[index].length==0"
								:range="otherUserList[index]" range-key="NAME">
								<view class="picker">
									{{ other[index].USER_NAME ? other[index].USER_NAME : '请选择' }}
								</view>
							</picker>
						</view>
					</view>
				</view>

			</view>
			<view class="ace-list mt30">
				<view class="ace-title">
					<text class="text-semi">添加隐患信息</text>
					<button v-if="ISLOG == '0'" class="cu-btn round bg-blue" @click="$noMultipleClicks(addOtherHidden)">添加</button>
				</view>
				<view class="ace-content" v-show="otherHiddenList && otherHiddenList.length > 0">
					<view class="add_pard_item" v-for="(item,index) of otherHiddenList">
						<view v-if="ISLOG == '0'" class="add_pard_del" @click="removeOtherHidden(item.HIDDEN_ID)">
							<text class="cuIcon-roundclosefill text-red f40"></text>
						</view>
						<view class="cu-form-textarea" @click="$noMultipleClicks(goToEdit,item.HIDDEN_ID)">
							<view class="cu-form-title">隐患描述</view>
							<textarea disabled placeholder="请输入备注信息..." v-model="item.HIDDENDESCR"></textarea>
						</view>
						<view class="cuIcon-infofill text-blue unqualified"></view>
					</view>
				</view>

			</view>
			<view class="cu-form-textarea margin-top">
				<view class="cu-form-title">备注</view>
				<textarea placeholder="请输入备注信息..." v-model="REMAKE"></textarea>
			</view>
			<view class="cu-form-group margin-top" v-if="isTongyong">
				<view class="title">检查人签字</view>
				<button v-if="ISLOG == '0'" class="cu-btn bg-green shadow" @tap="modalShow = true"
					data-target="Modal">手写签字</button>
			</view>
			<view class="cu-bar bg-white" v-show="imgList && imgList.length > 0" v-if="isTongyong">
				<view class="action">
					签字照片
				</view>

			</view>

			<view class="cu-form-group" v-show="imgList && imgList.length > 0" v-if="isTongyong">
				<view class="grid col-4 grid-square flex-sub">
					<view style="width: 60%;" class="bg-img" v-for="(item,index) in imgList" :key="index"
						@tap="ViewImage" data-type="0" :data-url="imgList[index].filePath">
						<image v-if="ISLOG == '0'" :src="imgList[index].filePath" mode="aspectFill"></image>
						<image v-else :src="imgList[index].filePath" mode="aspectFill"></image>
						<view v-if="ISLOG == '0'" class="cu-tag bg-red" @tap.stop="DelImg" data-type="0" :data-index="index">
							<text class='cuIcon-close'></text>
						</view>
					</view>
				</view>
			</view>

			<view class="cu-tabbar-height"></view>
		</scroll-view>
    <view class="cu-modal" :class="{'show':modalShow}">
      <sign @confirm="subCanvas" @cancel="modalShow = false"></sign>
    </view>
		<view v-if="ISLOG == '0'" class="bottom-fixed" @click="$noMultipleClicks(save)">
			<button class="cu-btn bg-green">提 交</button>
		</view>
	</view>
</template>

<script>
	import {
		basePath,
		corpinfoId,
		formatDate,
		loginUser,
		baseImgPath
	} from '@/common/tool.js';
	import tkiTree from "@/components/select-tree/select-tree.vue"
	import sign from '@/components/sign/sign.vue';
	export default {
		components: {
			tkiTree,
			sign
		},
		data() {
			return {
				noClick: true,
				time: '12:01',
				date: '2018-12-25',
				other: [{
					"DEPARTMENT_ID": '',
					"USER_ID": '',
					"DEPARTMENT_NAME": '',
					"USER_NAME": '',
					index: -1
				}], //其他验收人员
				otherUserList: [],
				treeNode: [], //部门下拉数据
				REMAKE: '',
				FIRE_RECORD_ID: '',
				LISTMANAGER_ID: '',
				ISLOG: '',
				otherHiddenList: [],
				imgList: [],
				modalShow: false,
				isTongyong: true,
				HIDDENINFOJSON: [],
			}
		},
		onLoad(e) {
			let now = new Date();
			this.date = formatDate(now, 'yyyy-MM-dd');
			this.time = formatDate(now, 'hh:mm');
			this.FIRE_RECORD_ID = e.FIRE_RECORD_ID;
			this.LISTMANAGER_ID = e.FIRE_CHECK_ID;
			this.ISLOG = e.ISLOG;
			this.getDept();
			if (corpinfoId == 'ffbf90f7064340ae9d56c16d4f560423') {
				this.isTongyong = false;
			}
		},
		onShow() {
			this.getOtherHidden();
		},
		methods: {
			showModal(e) {
				this.modalShow = true
			},
			TimeChange(e) {
				this.time = e.detail.value
			},
			DateChange(e) {
				this.date = e.detail.value
			},
			save() {
				var _this = this;
				uni.showLoading({
					title: '请稍候'
				})
				if (!_this.other[0].USER_ID) {
					uni.showToast({
						icon: 'none',
						title: '请添加检查人',
						duration: 1500
					});
					return;
				}
				var fileList = [];
				for (var i = 0; i < _this.imgList.length; i++) {
					if (!_this.imgList[i].id) {
						var file = {};
						file.type = 13;
						file.filePath = _this.imgList[i].filePath;
						fileList.push(file);
					}
				}
				new Promise((resolve, reject) => {
					_this.submit().then(() => {
						resolve();
					})
				}).then(() => {
					var i = 0;
					_this.uploadImg(fileList, i).then(() => {
						resolve();
					})
				}).then(() => {
					uni.showToast({
						icon: 'none',
						title: '提交成功',
						duration: 1500
					});
					setTimeout(function() {
						var pages = getCurrentPages(); // 获取当前页面栈
						var prePage = pages[pages.length - 3]; // 上二级页面
						prePage.$vm.initflag = true; // A 页面 init方法 为true
						uni.navigateBack({
							delta: 2
						});
						uni.hideLoading();
					}, 1500);
				})

			},
			submit() {
				var _this = this;
				return new Promise((resolve, reject) => {
					uni.request({
						url: basePath + "/app/fireRecordManger/finish", //提交接口
						method: 'POST',
						dataType: 'json',
						header: {
							'Content-type': 'application/x-www-form-urlencoded'
						},
						data: {
							CHECK_TIME: _this.date + ' ' + _this.time + ':00',
							REMAKE: _this.REMAKE,
							FIRE_RECORD_ID: _this.FIRE_RECORD_ID,
							CORPINFO_ID: corpinfoId,
							LISTMANAGER_ID: _this.LISTMANAGER_ID,
							OPERATOR: loginUser.USER_ID,
							CHECKUSERS: JSON.stringify(_this.other),
							HIDDENINFOJSON: _this.HIDDENINFOJSON
						},
						success: (res) => {
							uni.hideLoading();
							if ("success" == res.data.result) {
								resolve();

							} else {
								uni.showToast({
									icon: 'none',
									title: '系统错误',
									duration: 2000
								});
							}
						}
					});
				});
			},
			uploadImg(tempFilePaths, i) {
				return new Promise((resolve, reject) => {
					var _this = this;
					if (tempFilePaths.length == 0) {
						resolve();
					}
					uni.showLoading({
						title: '上传中'
					})
					uni.uploadFile({
						url: basePath + '/app/imgfiles/add',
						filePath: tempFilePaths[i].filePath,
						name: 'FFILE',
						formData: {
							'TYPE': 13,
							'FOREIGN_KEY': _this.FIRE_RECORD_ID
						},
						success: (res) => {
							i++;
							if (tempFilePaths.length > i) {
								_this.uploadImg(tempFilePaths, i);
							} else {
								uni.hideLoading();
								resolve();
							}
						},
						fail: (err) => {
							uni.hideLoading();
							uni.showModal({
								content: err.errMsg,
								showCancel: false
							});
						}
					})
				})
			},
			//跳转事件
			goToEdit(e) {
				uni.navigateTo({
					url: '/pages/application/fire-management/hidden-trouble-app/other-hidden-add?HIDDEN_ID=' + e+'&ISLOG='+this.ISLOG
				});
			},
			//根据主键ID获取数据
			addOther: function() {
				var _this = this;
				let o = {
					"DEPARTMENT_ID": '',
					"USER_ID": '',
					"DEPARTMENT_NAME": '',
					"USER_NAME": '',
					index: -1
				};
				_this.other.push(o);
				let index = _this.other.length - 1;
				_this.otherUserList[index] = [];
			},
			addOtherHidden: function() {
				uni.navigateTo({
					url: '/pages/application/fire-management/hidden-trouble-app/other-hidden-add?LISTMANAGER_ID=' +
						this.LISTMANAGER_ID + '&FIRE_RECORD_ID=' + this.FIRE_RECORD_ID+ '&ISLOG=' + this.ISLOG
				});
			},
			removeOther: function(index) {
				this.other.splice(index, 1);
				this.otherUserList.splice(index, 1);
			},
			removeOtherHidden: function(id) {
				var _this = this;
				uni.showModal({
					title: '提示',
					cancelText: '确认',
					confirmText: '取消',
					content: '确定删除隐患信息吗？',
					success: function(res) {
						if (res.cancel) {
							uni.request({
								url: basePath + "app/fireRecordManger/delOtherHidden", //提交接口
								method: 'POST',
								dataType: 'json',
								header: {
									'Content-type': 'application/x-www-form-urlencoded'
								},
								data: {
									HIDDEN_ID: id,
									FIRE_RECORD_ID: _this.FIRE_RECORD_ID,
								},
								success: (res) => {
									uni.hideLoading();
									if ("success" == res.data.result) {
										_this.getOtherHidden();
										uni.showToast({
											icon: 'none',
											title: '删除成功',
											duration: 1500
										});
									} else {
										uni.showToast({
											icon: 'none',
											title: '系统错误',
											duration: 2000
										});
									}
								}
							});
						}
					}
				});
			},
			getOtherHidden: function() {
				var _this = this;
				uni.showLoading({
					title: '请稍候'
				})
				uni.request({
					url: basePath + '/app/fireRecordManger/getOtherHidden',
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						LISTMANAGER_ID: _this.LISTMANAGER_ID,
						FIRE_RECORD_ID: _this.FIRE_RECORD_ID,
						ISLOG: _this.ISLOG,
						USER_ID: loginUser.USER_ID,
					},
					success: (res) => {
						if ("success" == res.data.result) {
							uni.hideLoading();
							_this.otherHiddenList = res.data.varList;
							if(res.data.baseInfo) {
								this.REMAKE =  res.data.baseInfo.REMAKE
								this.other = JSON.parse(res.data.baseInfo.CHECK_USERS_DEPARTMENT)
								this.date =  res.data.baseInfo.CHECK_TIME.split(" ")[0]
								this.time =  res.data.baseInfo.CHECK_TIME.split(" ")[1]
								this.imgList = []
								let files = res.data.imgs;
								for (var i = 0; i < files.length; i++) {
									let img = {};
									img.filePath = baseImgPath + files[i].FILEPATH;
									img.id = files[i].IMGFILES_ID;
									this.imgList.push(img);
								}
							}
							for (let i = 0; i < res.data.varList.length; i++) {
								this.HIDDENINFOJSON.push({
									HIDDENDESCR: res.data.varList[i].HIDDENDESCR,
									HIDDEN_ID: res.data.varList[i].HIDDEN_ID
								})
							}
						} else {
							uni.showToast({
								icon: 'none',
								title: '系统异常',
								duration: 2000
							});
						}
					}
				});
			},
			haveUser(e) {
				if (e == null || e.length == 0) {
					uni.showToast({
						icon: "none",
						title: '请先选择有人员的部门',
						duration: 2000
					});
				}
			},
			// 显示树形选择器
			showYsTree(index) {
				let ref = 'tkiTree' + index;
				this.$refs['tkiTree' + index][0]._show();
			},
			// 确定回调事件
			ystreeConfirm(e, index) {
				this.other[index].DEPARTMENT_ID = e[0].id;
				this.other[index].DEPARTMENT_NAME = e[0].name;
				this.other[index].USER_ID = '';
				this.other[index].USER_NAME = '';
				this.other[index].index = -1;
				this.getUserList(this.other[index].DEPARTMENT_ID, index);
				this.$forceUpdate(); //强制刷新
			},
			PickerYsr(e, index) {
				this.other[index].index = e.detail.value;
				this.other[index].USER_ID = this.otherUserList[index][e.detail.value] ? this.otherUserList[index][e.detail
					.value
				].USER_ID : '';
				this.other[index].USER_NAME = this.otherUserList[index][e.detail.value] ? this.otherUserList[index][e
					.detail.value
				].NAME : '';
				this.$forceUpdate(); //强制刷新
			},
			getDept() {
				var _this = this;
				uni.request({
					url: basePath + '/app/sys/listTree', //部门下拉接口
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					data: {
						CORPINFO_ID: corpinfoId,
					},
					success: (res) => {
						if ("success" == res.data.result) {
							_this.treeNode = eval(res.data.zTreeNodes);
							if (_this.isTongyong) {

								_this.other[0].DEPARTMENT_ID = loginUser.DEPARTMENT_ID;
								_this.other[0].DEPARTMENT_NAME = loginUser.DEPARTMENT_NAME;
								_this.other[0].USER_ID = loginUser.USER_ID;
								_this.other[0].USER_NAME = loginUser.NAME;
							}
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					}
				});
			},
			//获取人员列表
			getUserList(DEPARTMENT_ID, i) {
				//发送 post 请求
				var _this = this;
				uni.request({
					method: 'POST',
					dataType: 'json',
					header: {
						'Content-type': 'application/x-www-form-urlencoded'
					},
					url: basePath + '/app/sys/listUser',
					data: {
						DEPARTMENT_ID: DEPARTMENT_ID,
						NOMAIN: '1',
						tm: new Date().getTime()
					},
					success: function(res) {
						if ("success" == res.data.result) {
							if (i > -1) {
								_this.otherUserList[i] = [];
								_this.otherUserList[i] = res.data.userList;
								_this.$forceUpdate(); //强制刷新
							} else {
								_this.rectificationUserList = res.data.userList;
							}
						} else {
							uni.showToast({
								title: res.data.message,
								duration: 2000
							});
						}
					}
				})
			},

			//图片上传
			ChooseImage(e) {
				var _this = this;
				var ss = 4 - this.imgList.length;
				uni.chooseImage({
					count: ss, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera', 'album'], //从相册选择
					success: (res) => {
						if (e == 0) {
							let img = {};
							img.id = '';
							img.filePath = res.tempFilePaths[0];
							this.imgList.push(img)
						} else {
							let img = {};
							img.id = '';
							img.filePath = res.tempFilePaths[0];
							this.imgList1.push(img)
						}
					}
				});
			},
			ViewImage(e) {
				console.info(e.currentTarget.dataset.type)
				if (e.currentTarget.dataset.type == 0) {
					let files = [];
					for (var i = 0; i < this.imgList.length; i++) {
						files.push(this.imgList[i].filePath)
					}
					uni.previewImage({
						urls: files,
						current: e.currentTarget.dataset.url
					});
				} else {
					let files = [];
					for (var i = 0; i < this.imgList1.length; i++) {
						files.push(this.imgList1[i].filePath)
					}
					uni.previewImage({
						urls: files,
						current: e.currentTarget.dataset.url
					});
				}
			},
			DelImg(e) {
				var _this = this;
				let i = e.currentTarget.dataset.index
				uni.showModal({
					title: '秦港-双基双控',
					content: '确定要删除这张图片吗？',
					cancelColor: "#000000",
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							if (e.currentTarget.dataset.type == 0) {
								if (_this.imgList[i].id) {
									uni.showLoading({
										title: '处理中'
									})
									uni.request({
										url: basePath + '/app/imgfiles/delete',
										method: 'POST',
										dataType: 'json',
										header: {
											'Content-type': 'application/x-www-form-urlencoded'
										},
										data: {
											IMGFILES_ID: _this.imgList[i].id,
										},
										success: (res) => {
											uni.hideLoading();
											uni.showToast({
												icon: 'none',
												title: '删除成功',
												duration: 1500
											});
											_this.imgList.splice(i, 1)
										},
										fail: (err) => {
											uni.hideLoading();
											uni.showModal({
												content: err.errMsg,
												showCancel: false
											});
										}
									})
								} else {
									this.imgList.splice(e.currentTarget.dataset.index, 1)
								}
							} else {
								if (_this.imgList1[i].id) {
									uni.showLoading({
										title: '处理中'
									})
									uni.request({
										url: basePath + '/app/imgfiles/delete',
										method: 'POST',
										dataType: 'json',
										header: {
											'Content-type': 'application/x-www-form-urlencoded'
										},
										data: {
											IMGFILES_ID: _this.imgList1[i].id,
										},
										success: (res) => {
											uni.hideLoading();
											uni.showToast({
												icon: 'none',
												title: '删除成功',
												duration: 1500
											});
											_this.imgList1.splice(i, 1)
										},
										fail: (err) => {
											uni.hideLoading();
											uni.showModal({
												content: err.errMsg,
												showCancel: false
											});
										}
									})
								} else {
									this.imgList1.splice(e.currentTarget.dataset.index, 1)
								}
							}
						}
					}
				})
			},
			hideModal(e) {
				this.modalName = null
			},


			//完成
			subCanvas(e) {
				this.imgList.splice(0, this.imgList.length);
				this.imgList.push(e);
				this.modalShow = false;
			}
		}
	}
</script>

<style>
	.cu-form-title {
		padding: 20 upx 0;
	}

	.cu-form-textarea {
		background-color: #ffffff;
		padding: 1 upx 30 upx 20 upx;
		min-height: 100 upx;
	}

	.wrapper {
		width: 100%;
		height: 80vh;
		margin: 0;
		overflow: hidden;
		display: flex;
		align-content: center;
		flex-direction: row;
		justify-content: center;
		font-size: 28 upx;
	}

	.handWriting {
		background: #fff;
		width: 100%;
		height: 100%;
	}

	.handCenter {
		border: 4 upx dashed #e9e9e9;
		flex: 5;
		overflow: hidden;
		box-sizing: border-box;
	}

	.cu-form-textarea textarea {
		height: 4.6em;
		width: 100%;
		line-height: 1.2em;
		flex: 1;
		font-size: 28 upx;
		padding: 0;
	}
</style>
