<template>
	<!-- <page-meta :page-style="'overflow:'+(missionShow?'hidden':'visible')"></page-meta> -->
	<page-meta :page-style="missionShow?'overflow:hidden':''"></page-meta>
	<view class='container'>
		<uni-forms ref="formdata" :model="form" validateTrigger='blur' :rules="rules" labelWidth="100px"
			label-position="left">
			<uni-forms-item label="任务名称" name="mission_id">
				<uni-easyinput @focus='openMission' @clear='clearMission' v-model="mission_name" placeholder="请选择任务" />
				<qianziyu-select @updateRadioValue="updateRadioValue" :radioValue='radioValue' :show="missionShow"
					:maskClose='false' type="radio" :popupTitle="'任务名称'" name="cworkStationName"
					:dataLists="missionList" placeholder="输入任务名称搜索" @search="missionSearch" @submit="missionSubmit"
					@cancel="missionCancel" />
			</uni-forms-item>
			<uni-forms-item label="检查日期" name="date" required>
				<uni-datetime-picker ref="calendar" type="date" :hide-second='true' returnType="string"
					v-model="form.date" />
			</uni-forms-item>
			<uni-forms-item label="检查地点" name="site_id">
				<uni-easyinput @focus='openSite' :clearable='false' v-model="nowAddress" placeholder="请选择地点" />
			</uni-forms-item>
			<uni-forms-item label="上报人" name="up_admin_id">
				<uni-data-select v-model="form.up_admin_id" :localdata="userdata"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="问题类型" name="ask_id" required>
				<uni-data-select v-model="form.ask_id" :clear="true" :localdata="askList"></uni-data-select>
			</uni-forms-item>
			<uni-forms-item label="建议整改科室" name="ask_department">
				<uni-combox emptyTips='暂无搜索数据' label="" clearable :emptyTips="''" :candidates="depList" @input="changeDep"
					placeholder="请选择或输入建议整改科室" v-model="form.ask_department"></uni-combox>
			</uni-forms-item>
			<uni-forms-item label="附件-照片" name="file_ids">
				<uni-file-picker v-model="filesList" fileMediatype="image" mode="grid" @select="select"
					@progress="progress" @success="success" @fail="fail" @delete="deleteFile" />
			</uni-forms-item>
			<uni-forms-item label="问题描述" name="ask_introduce" required>
				<uni-easyinput type='textarea' v-model="form.ask_introduce" placeholder="请输入问题描述" />
			</uni-forms-item>
			<uni-forms-item label="整改建议" name="tips">
				<uni-easyinput type='textarea' v-model="form.tips" placeholder="请输入整改建议" />
			</uni-forms-item>
		</uni-forms>
		<view class="sbtn">
			<button type="primary" size="large" @click="submit">提交</button>
		</view>
		<!-- 地点弹窗 -->
		<u-popup :show="showSite" @close="cancelSite">
			<view class="title" style="font-size: 50rpx;text-align: center;padding: 20rpx 0;">选择地点</view>
			<view style="padding: 20rpx;">

				<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y" @scrolltolower="$emit('lower')">


					<view style="margin-bottom:20rpx">站点选择：</view>
					<!-- <u-radio-group class='radioGroup' :borderBottom="true" iconPlacement="right" placement="column"
							@change="e=>{return groupChange(e,'site')}" v-model="nowAddress">
							<u-radio :customStyle="{marginBottom: '12px'}" v-for="item in nearByList"
								:label="item.name" :name="item.name">
							</u-radio>
						</u-radio-group> -->
					<lx-cascade-select ref="caser" :list="nearByList" useName='name'
						@click="e=>{return groupChange(e,'site')}" />
					<view style="margin-bottom:20rpx">当前位置：</view>
					<u-radio-group :borderBottom="true" iconPlacement="right" placement="column"
						@change="e=>{return groupChange(e,'now')}" v-model="nowAddress">
						<u-radio :customStyle="{marginBottom: '12px'}" :label="address" :name="address">
						</u-radio>
					</u-radio-group>
				</scroll-view>

				<view class="buttons">
					<u-row>
						<u-col customStyle="padding:20rpx 0rpx 20rpx 0rpx" span="12">
							<u-button @click="changeSite" type="primary" throttleTime="1000">确认</u-button>
						</u-col>
					</u-row>
				</view>
			</view>
		</u-popup>

	</view>
</template>

<script>
	import qianziyuSelect from '@/components/qianziyu-select/qianziyu-select.vue'
	import lxCascadeSelect from '@/components/lx-cascade-select/lx-cascade-select'
	import {
		HOST,
		getStorageSync,
		setStorageSync,
	} from '@/utils/util.js'
	export default {
		components: {
			qianziyuSelect,
			lxCascadeSelect,
		},
		data() {
			return {
				showSite: false,
				showSecond: false,
				scrollTop: 0,
				address: '',
				nowAddress: '',
				nearByList: [],
				lat: '',
				lon: '',
				inspectionObj: {},
				missionShow: false,
				radioValue: 0,
				missionKeyword: '',
				mission_name: '',
				unitTypeId: '',
				missionList: [],
				depList: [],
				depListAll: [],
				siteList: [],
				askList: [],
				filesList: [],
				userdata: [],
				submitFileList: [],
				id: '',
				isgoon: '',
				form: {
					mission_id: '',
					date: '',
					site_id: '',
					ask_id: '',
					up_admin_id: '',
					ask_department: '',
					file_ids: [],
					ask_introduce: '',
					ask_department_ids: [],
					tips: '',
				},
				rules: {
					date: {
						rules: [{
							required: true,
							errorMessage: '请选择检查日期',
						}]
					},
					ask_id: {
						rules: [{
							required: true,
							errorMessage: '请选择问题类型',

						}]
					},
					ask_introduce: {
						rules: [{
							required: true,
							errorMessage: '请输入问题描述',

						}]
					}
				},
			}
		},
		onReady() {},
		onLoad(options) {
			console.log("HOST", HOST)
			this.getNowDate()
			this.getUnitType()
			// this.getMission()
			this.getDep()
			this.getAsk()
			// this.getUser()
			this.getUserId()
			let that = this
			that.util.initAddress(function(res) {
				that.lat = res.latitude; // 纬度
				that.lon = res.longitude; // 经度
				that.address = res.address
				that.getSite()
			})
			if (options.id) {
				this.id = options.id
				this.missionShow = false
				this.getDetail(this.id)
			}

			// 继续检查
			if (options.isgoon) {
				this.isgoon = options.isgoon
				this.form = getStorageSync('patrol_form') ? getStorageSync('patrol_form') : {},
					this.mission_name = getStorageSync('patrol_form') ? getStorageSync('patrol_form').mission_name : ''
				this.nowAddress = getStorageSync('patrol_form') ? getStorageSync('patrol_form').nowAddress : ''
				// this.form.ask_id = ''
				this.$set(this.form,"ask_id",'')
				this.$set(this.form,"ask_introduce",'')
				// this.form.ask_introduce = ''
				this.missionShow = false
				if (!this.form.date) {
					let date = new Date()
					let year = date.getFullYear()
					let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1
					let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
					this.form.date = year + '-' + month + '-' + day
				}
			}
			// if (options.site_id) {
			// 	this.form.site_id = options.site_id
			// 	this.form.address = options.address
			// 	this.form.lat = options.lat
			// 	this.form.lon = options.lon
			// 	this.nowAddress = options.name
			// } else {
			// 	this.nowAddress = options.address
			// 	this.form.address = options.address
			// 	this.form.lat = options.lat
			// 	this.form.lon = options.lon
			// }
			// this.$forceUpdate()
		},
		methods: {
			getDep() {
				let that = this
				this.util.request({
					api: '/api/admin/department',
					data: {},
					method: 'GET',
					utilSuccess: function(res) {
						let arr = []
						that.depListAll = res
						for (var k of res) {
							arr.push(k.name)
						}
						that.depList = arr
					},
					utilFail: function(res) {
						that.util.toast(res)
					}
				})
			},
			getUserId() {

				let that = this
				this.util.request({
					api: '/api/admin/auth/me',
					data: {},
					method: 'POST',
					utilSuccess: function(res) {
						that.$set(that.form,'up_admin_id',res.id)
						// that.form.up_admin_id = res.id
						console.log("res123", res)
						that.getUser()
					},
					utilFail: function(res) {
						that.util.toast(res)
					}
				})
			},
			getUser() {
				let that = this
				this.util.request({
					api: '/api/admin/other/admin-user-list',
					data: {
						page_size: 9999
					},
					method: 'GET',
					utilSuccess: function(res) {
						let arr = []
						let _arr = res.data ? res.data.reverse() : []
						for (var k of _arr) {
							arr.push({
								value: k.id,
								text: k.name
							})
						}
						that.userdata = arr
					},
					utilFail: function(res) {
						that.util.toast(res)
					}
				})
			},
			changeUser(e) {

			},
			changeDep(e) {
				let arr = []
				this.depListAll.map(item => {
					if (item.name == e) {
						arr.push(item.id)
					}
				})
				this.form.ask_department_ids = arr
				this.form.ask_department = e
			},
			openMission() {
				uni.hideKeyboard()
				this.missionShow = true
			},
			async getUnitType() {
				let that = this
				this.util.request({
					api: '/api/admin/parameter/show',
					data: {
						number: "unitTypeList"
					},
					method: 'GET',
					utilSuccess: function(res) {
						var data = res.detail
						for (var k of data) {
							if (k.remark == '检查') {
								that.unitTypeId = k.id
								that.getMission()
							}
						}

					},
					utilFail: function(res) {
						that.util.toast(res)
					}
				})
			},
			getMission(issearch) {
				let that = this
				this.util.request({
					api: '/api/admin/mission/index',
					data: {
						page: 1,
						page_size: 999,
						keyword: this.missionKeyword,
						audit_status: 1,
						unit_type: that.unitTypeId
					},
					method: 'GET',
					utilSuccess: function(res) {
						let arr = []
						res.data.map((k, index) => {
							let labelName = ''
							if (k.name == '日常检查') {
								labelName = k.name + "(长期)"
								that.radioValue = index
							} else {
								// labelName = k.name + "(" + k.start_date + "至" + k.end_date + ")"
								labelName = k.name
							}
							arr.push({
								value: k.id,
								name: labelName,
								mission_name: k.name,
								id: k.id,
							})
						})
						that.missionList = arr
						if ((that.id || that.isgoon) && !issearch) {
							that.missionShow = false
						} else {
							that.missionShow = true
						}
					},
					utilFail: function(res) {
						that.util.toast(res)
					}
				})
			},
			changeMission(e) {},
			updateRadioValue(e) {
				console.log("e", e)
				this.radioValue = e
			},
			clearMission() {
				this.mission_name = ''
				this.form.mission_id = ''
				this.radioValue = ''

			},
			missionSearch(e) {
				this.missionKeyword = e
				this.getMission(true)
			},
			missionSubmit(e) {
				console.log(e)
				this.form.mission_id = e.id
				this.mission_name = e.mission_name
				this.missionShow = false
			},
			missionCancel(e) {
				this.missionKeyword = ''
				this.missionShow = false
			},
			getNowDate() {
				let _time = this.util.formatTimeMin(new Date())
				this.form.date = _time
				console.log(_time)
			},
			confirmdate(e) {
				console.log(e)
				this.form.date = e
				console.log("this.form.date", this.form.date)
			},
			openSite() {
				uni.hideKeyboard()
				this.showSite = true
			},
			cancelSite() {
				this.showSite = false
			},
			groupChange(e, type, item) {
				console.log(this.nowAddress)
				if (type == 'now') {
					// this.showSecond = false
					this.$refs.caser.listArray = []
					this.$refs.caser.selectedArray = []
					// this.$refs.caser.listReal = this.nearByList
					this.inspectionObj = {
						address: this.address,
						lat: this.lat,
						lon: this.lon,
					}
				} else {
					this.nowAddress = ''
					this.inspectionObj = {
						name: e[1].name,
						address: e[1].address,
						lat: e[1].lat,
						lon: e[1].lon,
						id: e[1].id
					}
				}
				console.log("inspectionObj", this.inspectionObj)
				// if (type == 'site') {
				// 	let obj = {}
				// 	this.nearByList.map(item => {
				// 		if (item.name == e) {
				// 			this.inspectionObj = {
				// 				name: item.name,
				// 				address: item.address,
				// 				lat: item.lat,
				// 				lon: item.lon,
				// 				id: item.id
				// 			}
				// 		}
				// 	})
				// }
			},
			changeSite() {
				if (this.inspectionObj.id) {
					this.form.site_id = this.inspectionObj.id
					this.form.address = this.inspectionObj.address
					this.form.lat = this.inspectionObj.lat
					this.form.lon = this.inspectionObj.lon
					this.nowAddress = this.inspectionObj.name
				} else {
					this.form.site_id = ''
					this.form.address = this.inspectionObj.address
					this.form.lat = this.inspectionObj.lat
					this.form.lon = this.inspectionObj.lon
					this.nowAddress = this.inspectionObj.address
				}
				this.showSite = false
			},
			getSite() {
				let that = this
				console.log(that.lon, that.lat)
				// /api/admin/site/index
				this.util.request({
					api: '/api/admin/site/index',
					data: {
						// lon:that.lon,
						// lat:that.lat
						page: 1,
						page_size: 9999
					},
					method: 'GET',
					utilSuccess: function(res) {

						if (res.length == 0) {
							// that.isPoint = false
							// uni.showToast({
							// 	title: '附近暂无站点信息',
							// 	icon: 'none'
							// })
						} else {
							let data = res.data ? res.data.reverse() : []
							let arr = that.contactSite(data)
							console.log("arr", arr)
							that.nearByList = arr
						}
					},
					utilFail: function(res) {
						that.util.toast(res)
					}
				})

			},
			contactSite(arr) {
				let tempArr = [],
					newArr = []
				for (let i = 0; i < arr.length; i++) {
					if (tempArr.indexOf(arr[i].type) === -1) {
						newArr.push({
							type: arr[i].type,
							name: arr[i]['type_detail']['value'],
							children: [arr[i]]
						})
						tempArr.push(arr[i].type);
					} else {
						for (let j = 0; j < newArr.length; j++) {
							if (newArr[j].type == arr[i].type) {
								newArr[j].children.push(arr[i])
							}
						}
					}
				}
				return newArr
			},
			getAsk() {
				let that = this
				this.util.request({
					api: '/api/admin/parameter/show',
					data: {
						number: 'askList'
					},
					method: 'GET',
					utilSuccess: function(res) {
						let arr = []
						for (var k of res.detail) {
							arr.push({
								value: k.id,
								text: k.value
							})
						}
						that.askList = arr
					},
					utilFail: function(res) {
						that.util.toast(res)
					}
				})
			},
			changeAsk(e) {
				console.log(e)
				if (e) {
					this.form.ask_id = e
				}
			},
			// 获取上传状态
			uploadFiles(tempFilePaths) {
				let that = this
				let token = uni.getStorageSync('user_info_key').token;
				// 图片上传
				uni.uploadFile({
					url: HOST + '/api/admin/upload-file',
					filePath: tempFilePaths,
					name: 'file',
					method: 'POST',
					header: {
						authorization: 'Bearer ' + token
					},
					success: (uploadFileRes) => {

						if (uploadFileRes.statusCode == 200) {
							const res = JSON.parse(uploadFileRes.data);
							that.filesList.push({
								"name": res.original_name,
								"extname": res.extension,
								"url": res.url,
								'id': res.id
							})
							uni.showToast({
								title: '上传成功',
								icon: 'none'
							})
						}
						that.submitFileList = that.filesList
					}
				});
			},
			select(e) {
				console.log('选择文件：', e)
				const tempFilePaths = e.tempFilePaths;
				for (var k of tempFilePaths) {
					this.uploadFiles(k)
				}
			},
			// 获取上传进度
			progress(e) {
				console.log('上传进度：', e)
			},

			// 上传成功
			success(e) {
				console.log('上传成功', e)
			},

			// 上传失败
			fail(e) {
				uni.showToast({
					title: '上传失败',
					icon: 'none'
				})
				console.log('上传失败：', e)
			},
			deleteFile(e) {
				console.log("删除", e)
				this.filesList.map((item, index) => {
					if (item.url == e.tempFile.url) {
						this.filesList.splice(index, 1)
					}
				})
				this.submitFileList = this.filesList
			},
			getDetail(id) {
				let that = this
				this.util.request({
					api: '/api/admin/inspection/show',
					data: {
						id: id
					},
					method: 'GET',
					utilSuccess: function(res) {
						that.form = res
						console.log("res1234", res)
						that.mission_name = res.mission ? res.mission.name : ''
						that.nowAddress = res.site ? res.site.name : res.address
						console.log("nowAddress", that.nowAddress)
						for (var f of res.files) {
							that.filesList.push({
								"name": f.original_name,
								"extname": f.extension,
								"url": f.url,
								'id': f.id
							})
						}
						that.submitFileList = that.filesList
						console.log("that.form", that.form)

					},
					utilFail: function(res) {
						that.util.toast(res)
					}
				})
			},
			submit() {
				console.log("form", this.form)
				// return
				let arr = []
				for (var d of this.depList) {
					if (this.form.ask_department) {

					}
				}
				for (var k of this.submitFileList) {
					if (k.response) {
						arr.push(k.response.id)
					} else {
						arr.push(k.id)
					}
				}
				this.form.file_ids = arr
				// return
				this.$refs['formdata'].validate().then(res => {
					let that = this
					this.util.request({
						api: '/api/admin/inspection/save',
						data: that.form,
						method: 'POST',
						utilSuccess: function(res) {
							uni.showToast({
								title: '上报成功',
								icon: 'none'
							})
							setTimeout(function() {
								uni.redirectTo({
									url: '/pages/index/mypatrol'
								})
							})
							that.form.mission_name = that.mission_name
							that.form.nowAddress = that.nowAddress
							setStorageSync('patrol_form', that.form, 30 * 60)

						},
						utilFail: function(res) {
							that.util.toast(res)
						}
					})
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			}
		}
	}
</script>

<style scoped>
	.container {
		background-color: #fff;
		padding: 30rpx
	}

	/deep/ .uni-section .uni-section-header {
		display: none;
	}

	.radioGroup {
		height: 200px;
		padding: 10px 0px 20px 0;
	}
</style>