<template>
	<view class="  uni-container uni-container-bg">
		<view class="example container" :style="'height: ' + (screenHeight - wheight - 10) + 'px'">
			<view class="uni-padding-wrap uni-common-mt">
				<uni-segmented-control :current="current" :values="items" style-type="text"
					active-color="rgb(25, 146, 148)" @clickItem="onClickItem" />
			</view>
			<!-- 		<uni-row class="demo-uni-row align-center flex padding-tb-sm" :gutter="20" width="100%">
			<uni-col :span="12" class="flex flex-direction-row ">
				<text class="text-Width">开始时间：</text>
				<u-button customStyle="color: #2563EB;" plain shape="circle" size="small" color="#2563EB"
					@click="showtimeStart = true" :text="formData.start"></u-button>
				<u-datetime-picker :show="showtimeStart" :value="formData.start" mode="date" closeOnClickOverlay
					@confirm="confirmStarttime" @cancel="showtimeStart = false" @change="changetime"
					@close="showtimeStart = false">
				</u-datetime-picker>
			</uni-col>
			<uni-col :span="12" class="flex flex-direction-row ">
				<text class="text-Width">结束时间：</text>
				<u-button customStyle="color: #2563EB;" plain shape="circle" size="small" color="#2563EB"
					@click="showtimeEnd = true" :text="formData.end"></u-button>
				<u-datetime-picker :show="showtimeEnd" :value="formData.end" mode="date" closeOnClickOverlay
					@confirm="confirmEndtime" @cancel="showtimeEnd = false" @change="changetime"
					@close="showtimeEnd = false">
				</u-datetime-picker>
			</uni-col>
		</uni-row> -->
			<!-- 搜索 -->
			<!-- <uni-row class="demo-uni-row padding-tb-sm" :gutter="20" width="100%">
			<view class="" style="display: flex; align-items: center;">
				<uni-col :span="22">
					<view class="u-page__tag-item">
						<u-search v-model="keyword" :show-action="false"></u-search>
					</view>
				</uni-col>
				<uni-col :span='2'>
					<u-icon name="hourglass-half-fill" size="28" style='float: right;' @click='showSearch=true'>
					</u-icon>
				</uni-col>
			</view>
		</uni-row> -->
			<view v-if="current == 0">
				<view class="" style="margin-bottom: 100rpx;">
					<u-list @scrolltolower="scrolltolower">
						<u-list-item v-for="(item, index) in tableData" :key="index" link>
							<uni-row>
								<uni-col :span="2">
									<view class="" style="position: absolute;top: 0rpx;">
										<image :src="item.checked ?zhengchang:moren" class="tupian"
											@click="listItemChecked(item,index)">
										</image>
									</view>
								</uni-col>
								<uni-col :span="22">
									<view class="">
										<uni-row class="demo-uni-row  " :gutter="20" width="100%">
											<uni-col :span="18"
												class="text-xl font-weight-700">{{item.insp_name}}</uni-col>
											<uni-col :span="6" class="text-xl font-weight-700">
												<u-button size="mini" :color="'#ed7d31'">
													未确认
												</u-button>
											</uni-col>
										</uni-row>
										<uni-row class="demo-uni-row  " :gutter="20" width="100%">
											<uni-col :span="24" class="text-2cut text-grey1   ">{{item.description}}
											</uni-col>
										</uni-row>
										<uni-row class="demo-uni-row  " :gutter="20" width="100%">
											<uni-col :span="18"
												class="text-cut text-grey1">巡查时间：{{item.inspect_time}}</uni-col>
											<uni-col :span="6" class="justify-end flex ">
												<!-- 	<u-button size="small"
							:color="item.status==='0'||item.status==='3'?'red':item.status==='1'?'green':'blue'"
							style="width: 160rpx;">{{statusListTran(item.status)}}</u-button> -->
												<u-button size="small" color="rgb(25, 146, 148)" style="width: 160rpx;"
													@click.native="onClick(item)">查看详情</u-button>
											</uni-col>
										</uni-row>
									</view>
								</uni-col>
							</uni-row>
						</u-list-item>
					</u-list>
				</view>
				<view class="review-button heigthButton">
					<u-button size="small" color="rgb(25, 146, 148)" :customStyle="btnGetCode" style="width: 280rpx;"
						@click.native="sureBtn">确认</u-button>
				</view>
			</view>
			<view v-else-if="current == 1">
				<view class="" style="margin-bottom: 100rpx;">
					<u-list @scrolltolower="scrolltolower">
						<u-list-item v-for="(item, index) in tableData" :key="index" link>
							<uni-row>
								<uni-col :span="2">
									<view class="" style="position: absolute;top: 0rpx;">
										<image :src="item.checked ?zhengchang:moren" class="tupian"
											@click="listItemChecked(item,index)">
										</image>
									</view>
								</uni-col>
								<uni-col :span="22">
									<view class="">
										<uni-row class="demo-uni-row  " :gutter="20" width="100%">
											<uni-col :span="18"
												class="text-xl font-weight-700">{{item.insp_name}}</uni-col>
											<uni-col :span="6" class="text-xl font-weight-700">
												<u-button size="mini" color="#ed7d31">
													未处理
												</u-button>
											</uni-col>
										</uni-row>
										<uni-row class="demo-uni-row  " :gutter="20" width="100%">
											<uni-col :span="24" class="text-2cut text-grey1   ">{{item.description}}
											</uni-col>
										</uni-row>
										<uni-row class="demo-uni-row  " :gutter="20" width="100%">
											<uni-col :span="18" class="text-cut text-grey1">巡查时间：{{item.inspect_time}}
											</uni-col>
											<uni-col :span="6" class="justify-end flex ">
												<!-- 	<u-button size="small"
							:color="item.status==='0'||item.status==='3'?'red':item.status==='1'?'green':'blue'"
							style="width: 160rpx;">{{statusListTran(item.status)}}</u-button> -->
												<u-button size="small" color="rgb(25, 146, 148)" style="width: 160rpx;"
													@click.native="onClick(item)">查看详情</u-button>
											</uni-col>
										</uni-row>
									</view>
								</uni-col>
							</uni-row>
						</u-list-item>
					</u-list>
				</view>
				<view class="review-button heigthButton">
					<u-button size="small" color="rgb(25, 146, 148)" :customStyle="btnGetCode" style="width: 280rpx;"
						@click.native="reviewBtn">复 查</u-button>
				</view>
			</view>

			<view v-else-if="current == 2">
				<view class="" style="margin-bottom: 100rpx;">
					<u-list @scrolltolower="scrolltolower">
						<u-list-item v-for="(item, index) in tableData" :key="index" link>
							<uni-row>
								<!-- <uni-col :span="2">
								<view class="" style="position: absolute;top: 0rpx;" v-if="item.denger_status==0">
									<image :src="item.checked ?zhengchang:moren" class="tupian"
										@click="listItemChecked(item,index)">
									</image>
								</view>
							</uni-col> -->
								<uni-col :span="22">
									<view class="">
										<uni-row class="demo-uni-row  " :gutter="20" width="100%">
											<uni-col :span="18"
												class="text-xl font-weight-700">{{item.insp_name}}</uni-col>
											<uni-col :span="6" class="text-xl font-weight-700">
												<!-- <u-button size="mini" :color="item.denger_status=='0'?'#ed7d31':'#aace99'">
												{{ item.denger_status=='0'?'未处理':'已处理'}}
											</u-button> -->
												<u-button size="mini" color="#aace99">
													已处理
												</u-button>
											</uni-col>
										</uni-row>
										<uni-row class="demo-uni-row  " :gutter="20" width="100%">
											<uni-col :span="24" class="text-2cut text-grey1   ">{{item.description}}
											</uni-col>
										</uni-row>
										<uni-row class="demo-uni-row  " :gutter="20" width="100%">
											<uni-col :span="18"
												class="text-cut text-grey1">巡查时间：{{item.inspect_time}}</uni-col>
											<uni-col :span="6" class="justify-end flex ">
												<!-- 	<u-button size="small"
							:color="item.status==='0'||item.status==='3'?'red':item.status==='1'?'green':'blue'"
							style="width: 160rpx;">{{statusListTran(item.status)}}</u-button> -->
												<u-button size="small" color="rgb(25, 146, 148)" style="width: 160rpx;"
													@click.native="onClick(item)">查看详情</u-button>
											</uni-col>
										</uni-row>
									</view>
								</uni-col>
							</uni-row>
						</u-list-item>
					</u-list>
				</view>
			</view>
		</view>
		<!-- 搜索框 -->
		<u-popup :show="showSearch" :round="20" mode="bottom" @close="close" @open="open">
			<view class="searchpopup">
				<u--form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
					labelPosition="left" label-width="68px">
					<u-form-item label="处理结果" prop="handleResult">
						<u--input v-model="queryParams.handleResult" placeholder="请输入处理结果" clearable
							@keyup.enter.native="handleQuery" />
					</u-form-item>
					<u-form-item label="解决方式" prop="handleMethod">
						<u-radio-group v-model="queryParams.handleMethod">
							<u-radio :customStyle="{marginRight: '16px'}" v-for="dict in dengerHandle" :key="dict.value"
								:label="dict.label" :name="dict.value">
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<u-form-item>
						<u-button @click="showSearch=false">取消</u-button>
						<u-button type="primary" color="rgb(25, 146, 148)" @click="handleQuery">搜索</u-button>
					</u-form-item>
				</u--form>
			</view>
		</u-popup>
		<u-modal title="隐患复查" width="640rpx" :show="showreview " showCancelButton buttonReverse @confirm="onreviewclick"
			@cancel="cancelClick" confirmColor="rgb(25, 146, 148)">
			<view class="" style="width: 100%;">
				<u--form :model="reviewFromdata" ref="reviewfrom" label-width='95px'>
					<u-form-item label="解决方式:" prop="handleMethod">
						<u-radio-group v-model="reviewFromdata.handleMethod">
							<u-radio :customStyle="{marginRight: '16px'}" activeColor="rgb(25, 146, 148)"
								v-for="dict in dengerHandle" :key="dict.value" :label="dict.label" :name="dict.value">
							</u-radio>
						</u-radio-group>
					</u-form-item>
					<!-- <u-form-item label="是否上报:" prop="isReport">
						<u-radio-group v-model="reviewFromdata.isReport">
							<u-radio :customStyle="{marginRight: '16px'}" activeColor="rgb(25, 146, 148)"
								v-for="dict in isReportList" :key="dict.value" :label="dict.label" :name="dict.value">
							</u-radio>
						</u-radio-group>
					</u-form-item> -->
					<u-form-item label="截止日期:" prop="handleTime" @click="showHandleTime  = true; hideKeyboard()">
						<u--input v-model="reviewFromdata.handleTime" :disabled="true" disabledColor="#ffffff"
							suffixIcon="calendar" suffixIconStyle="color: #909399">
						</u--input>
					</u-form-item>
					<u-form-item label="复查人员:" @click="
						showOrg = true;showHandleTime = false
						hideKeyboard()" prop="receiverName">
						<u-input border="none" disabled v-model="reviewFromdata.receiverName" style="padding:18rpx"
							placeholder="请选择复查人员"></u-input>
					</u-form-item>

					<!-- <swiperl :list="list5" @change="e => current = e.current" :autoplay="false" previousMargin="60"
						nextMargin="60" circular radius="5" bgColor="#ffffff" @click="swiperClick">
						<view slot="indicator" class="indicator">
							<view class="indicator__dot" v-for="(item, index) in list5" :key="index"
								:class="[index === current && 'indicator__dot--active']">
							</view>
						</view>
					</swiperl> -->
				</u--form>
			</view>
		</u-modal>
		<u-action-sheet :show="showOrg" :actions="list5" title="请选择复查人员" @close="showOrg = false" @select="sexSelect">
		</u-action-sheet>
		<u-datetime-picker :show="showHandleTime" v-model="time" mode="date" closeOnClickOverlay
			@confirm="confirmReviewTime" @cancel="showHandleTime = false" @change="changeReviewTime"
			@close="showHandleTime = false">
		</u-datetime-picker>
		<!-- 加载中 -->
		<isLodingModel></isLodingModel>
	</view>
</template>
<script>
	let that = null;
	import {
		getPageDenger, // 历史记录隐患记录 
	} from "@/api/historical_record";
	import {
		getSelfEmp, //  获取本单位下的人员信息 
		dangeRreview, //  隐患复查  
		batchSetDangerStatus
	} from "@/api/hiddenTrouble";
	import {
		DICT_TYPE,
		getDictDatas
	} from "@/utils/dict";
	import swiperl from "@/components/swiper/swiper.vue"
	import {
		shijianc
	} from '@/utils/common.js'
	import config from '@/config'
	const baseUrlImg = config.baseUrlImg
	export default {
		components: {
			swiperl
		},
		data() {
			return {
				screenHeight: this.$screenHeight,
				wheight: '',
				items: ['隐患确认', '待复查', '已处理'],
				current: 0,
				moren: `${baseUrlImg}/checkActive/moren.png`, //默认图片
				zhengchang: `${baseUrlImg}/checkActive/zhengchang.png`,
				photograph: `${baseUrlImg}/checkActive/photograph.png`,
				btnGetCode: {
					width: '280rpx', // 注意驼峰命名，并且值必须用引号包括，因为这是对象 
				},
				// 数据
				tableData: [],
				// 每页数据量
				pageSize: 20,
				// 当前页
				pageNo: 1,
				// 数据总量
				total: 0,
				// tableData数据加载中
				loading: false,
				showOrg: false,
				// 初始化时搜索框的值
				keyword: '',
				// 开始时间与结束时间
				formData: {
					start: '请选择开始时间',
					end: '请选择结束时间',
				},
				showtimeStart: false,
				showtimeEnd: false,
				statusList: {
					0: "未解决",
					1: "已解决",
					2: "审核中",
					3: "审核未通过"
				},
				// 搜索框显示控制
				showSearch: false,
				// 查询参数
				queryParams: {
					pageNo: 1,
					pageSize: 10,
					dengerStatus: 0,
					handleResult: null,
					handleTime: [],
					status: 0,
					handleMethod: null,
					orgId: null,
					userId: null,
				},
				dengerHandle: getDictDatas(DICT_TYPE.DENGER_HANDLE),
				// =========================================
				time: Number(new Date()),
				reviewFromdata: {
					broadId: 0,
					dangerMapList: [],
					handleMethod: "",
					handleResult: "",
					handleTime: "",
					orgId: 0,
					receiver: "",
					sender: 0,
					isReport: "",
					receiverName: ""
				},
				isReportList: [{
					value: 0,
					label: "否"
				}, {
					value: 1,
					label: "是"
				}],
				showHandleTime: false,
				showreview: false,
				list5: [],
				current: 0,
				currentChecked: false,
				dangerIdStatus: {
					"dangerIds": [],
					"dangerStatus": 1
				}, //点击确认
				dangerIds: [],
				rules: {
					'handleMethod': {
						// type: 'string',
						required: true,
						message: '请选择解决方式',
						trigger: ['blur', 'change']
					},
					// 'isReport': {
					// 	// type: 'string',
					// 	required: true,
					// 	message: '请选择是否上报',
					// 	trigger: ['blur', 'change']
					// },
					'handleTime': {
						// type: 'string',
						required: true,
						message: '请选择截止日期',
						trigger: ['blur', 'change']
					},
					'receiverName': {
						// type: 'string',
						required: true,
						message: '请选择复查人员',
						trigger: ['blur', 'change']
					},
				},
			}
		},
		// 在 vue页面，向起始页通过事件传递数据
		onLoad: function(option) {
		},
		onShow() {
			this.$nextTick(() => {
				uni.createSelectorQuery().in(this).select('.heigthButton').boundingClientRect(data => {
					this.wheight = data.height
				}).exec()
			})
			this.tableData = []
			this.getData(1)
		},
		mixins: [uni.$u.mixin],
		watch: {
			loading: {
				handler(newLength, oldLength) {
					this.$modal.isLoadingModel(this.loading)
				},
				immediate: true
			},
			// this.$refs.uForm.setRules(this.rules);
			showreview: {
				handler(value) {
					this.$nextTick(() => { //在弹窗加载出来只有 show 才会变成 true
						if (value == true) { //判断 弹窗 v-model 变成 true 的时候去加载规则。 原理：在弹窗渲染完成之后表单渲染完成之前去加载规则就不会报错了
							// 如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则
							this.$refs.reviewfrom.setRules(this.rules);
						}
					})
				},
				immediate: true, // 重点
				deep: true, // 重点
			},
		},
		methods: {
			cancelClick() {
				this.list5=[]
				this.showOrg = false
				this.showreview = false
			},
			// tab头部点击
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex;
				}
				this.queryParams.dengerStatus = e.currentIndex == 2 ? 2 : (e.currentIndex == 0 ? 0 : 1)

				this.tableData = []
				this.getData(1)
				this.dangerIds = []
			},
			hideKeyboard() {
				uni.hideKeyboard()
			},
			// =================数据转换==================
			statusListTran(val) { //status状态转换
				return this.statusList[val]
			},
			// ================================
			// 获取数据
			getData(pageNo, value = '') {
				this.queryParams.orgId = this.$store.state.user.orgId
				this.queryParams.userId = this.$store.state.user.id
				this.loading = true
				this.queryParams.pageNo = pageNo
				getPageDenger(this.queryParams).then(response => {
					// 为数据赋值：通过展开运算符的形式，进行新旧数据的拼接
					this.tableData = [...this.tableData, ...response.data.list]
					// this.tableData = response.data.list;
					this.total = response.data.total;
					this.loading = false;
					this.tableData.map(i => {
						i.checked = false
						i.inspect_time = shijianc(i.inspect_time)
					})
				});
			},
			onClick(val) {
				if (val.insp_type == 'fpd') {
					uni.navigateTo({
						url: '/pagesA/fire/hidden_trouble/trouble_xf_deetails/trouble_xf_deetails?id=' + val.id,
					})
				} else {
					uni.navigateTo({
						url: '/pagesA/fire/hidden_trouble/trouble_details/trouble_details?id=' + val.id,
					})
				}
			},
			// 触底的事件
			scrolltolower() {
				// 判断是否还有下一页数据
				if (this.queryParams.pageNo * this.queryParams.pageSize >= this.total) return
				// 判断是否正在请求其它数据，如果是，则不发起额外的请求
				if (this.loading) return
				this.pageNo += 1
				this.getData(this.pageNo)
			},
			//日期范围
			// 开始日期 
			confirmStarttime(e) {
				this.showtimeStart = false
				let value = new Date(e.value)
				this.formData.start = uni.$u.timeFormat(e.value, 'yyyy/mm/dd');
			},
			changetime(e) {
			},
			confirmEndtime(e) {
				this.showtimeEnd = false
				let value = new Date(e.value)
				this.formData.end = uni.$u.timeFormat(e.value, 'yyyy/mm/dd');
			},
			// 搜索框
			open(e) {
			},
			close(e) {
				this.showSearch = false
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.showSearch = false
				this.queryParams.pageNo = 1
				this.getData(this.queryParams.pageNo)
			},
			// ===搜索框结束=============================
			// =====复选框====================================
			restReviewform() {
				this.reviewFromdata = {
					broadId: 0,
					dangerMapList: [],
					handleMethod: "",
					handleResult: "",
					handleTime: "",
					orgId: 0,
					receiver: 0,
					sender: 0,
				}
			},
			sexSelect(e) {
				this.reviewFromdata.receiver = e.id;
				this.reviewFromdata.receiverName = e.name;
			},

			confirmReviewTime(e) {
				var time = uni.$u.timeFormat(e.value, 'yyyy-mm-dd');
				this.reviewFromdata.handleTime = time
				this.showHandleTime = false
				// this.list5=[]
			},
			changeReviewTime(e) {
			},
			listItemChecked(val, index) {
				this.tableData[index].checked = !this.tableData[index].checked
				this.dangerIds.push(val.id)
				this.$forceUpdate()
				// val.checked=!val.checked 
			},
			sureBtn() { //确认
				this.current = 1
				this.dangerIdStatus.dangerStatus = 1
				this.dangerIdStatus.dangerIds = Array.from(new Set(this.dangerIds)) //去重
				batchSetDangerStatus(JSON.stringify(this.dangerIdStatus)).then(res => {
					if (res.data) {
						this.current = 1
						this.queryParams.dengerStatus = 1
						this.tableData=[]
						this.getData(1)
					}
				})

			},
			reviewBtn() {
				let list = this.tableData
				let checedkList = list.filter(i => i.checked == true)
				if (checedkList.length == 0) {
					this.$modal.msgError('请先选择隐患')
					return
				}
				const newArr = checedkList.map(item => item.orgId);
				const isRepeat = Array.from(new Set(newArr)) //去重 
				if (isRepeat.length > 1) {
					this.$modal.msgError('单位所属不一致')
					return
				}
				getSelfEmp({
					orgId: isRepeat[0]
				}).then(response => {
					this.showreview = true,
						// this.list5 = response.data;  
						response.data.map(i => {
							this.list5.push({
								id: i.accountId,
								name: i.empRyxm
							});
							// i.title = i.empRyxm
							// i.image = i.image ? i.image : ''
						})
					// this.list5 = response.data;
				});
			},
			onreviewclick() {
				let list = this.tableData
				let checedkList = list.filter(i => i.checked == true)
				if (checedkList.length == 0) {
					this.$modal.msgError('请先选择隐患')
					return
				}

				const newArr = checedkList.map(item => item.orgId);
				const isRepeat = Array.from(new Set(newArr)) //去重
				if (isRepeat.length > 1) {
					this.$modal.msgError('单位所属不一致')
					return
				}
				var dangerMapList = []
				checedkList.map(i => {
					dangerMapList.push({
						id: i.id,
						insp_id: i.insp_id,
						org_id: i.org_id,
						task_id: i.task_id,
						broad_id: i.broad_id
					})
				})
				this.reviewFromdata.broadId = checedkList[0].broad_id //后端返回的checedkList中的broad_id都相同，取任意一个就行
				this.reviewFromdata.dangerMapList = dangerMapList
				this.reviewFromdata.orgId = isRepeat[0]
				// this.reviewFromdata.receiver = this.list5[this.current].accountId
				this.reviewFromdata.sender = this.$store.state.user.id
				// 如果有错误，会在catch中返回报错信息数组，校验通过则在then中返回true
				this.$refs.reviewfrom.validate().then(res => {
					// uni.$u.toast('校验通过')

					dangeRreview(this.reviewFromdata).then(response => {
						if (response.data) this.$modal.msgSuccess('修改成功')
						this.showreview = false
						this.list5 = []
						this.restReviewform()
						this.tableData = []
						this.getData(1)
					});
				}).catch(errors => {
					// uni.$u.toast('校验失败')/
				})
			},
			swiperClick(e) {
			}
		}
	}
</script>
<style scoped lang="scss">
	::v-deep .u-list-item {
		transition: border linear .2s, box-shadow linear .5s;
		-moz-transition: border linear .2s, -moz-box-shadow linear .5s;
		-webkit-transition: border linear .2s, -webkit-box-shadow linear .5s;
		outline: none;
		border-color: rgba(86, 165, 168, 0.4);
		box-shadow: 0 0 8px rgba(93, 149, 242, .105);
		-moz-box-shadow: 0 0 8px rgba(93, 149, 242, .5);
		-webkit-box-shadow: 0 0 8px rgb(86, 165, 168);
	}

	.addInsp {
		width: 40px;
		position: fixed;
		right: 4px;
		z-index: 99999;
	}

	::v-deep .u-icon__icon {
		margin-right: 0px !important;
	}

	.searchpopup {
		height: 60vh;
		display: flex;
		justify-content: center;
		padding: 20rpx
	}

	.tupian {
		width: 48rpx;
		height: 48rpx;
	}

	.review-button {
		position: fixed;
		bottom: 0rpx;
		width: 100%;
		background: #F5F7F9;
		height: 100rpx;
		display: flex;
		align-items: center;
	}

	/deep/.u-action-sheet {
		overflow-y: auto;
		height: 1000rpx;
		background-color: #fff;
	}

	/deep/.u-action-sheet {
		overflow-y: auto;
		height: 1000rpx;
		background-color: #fff;
	}

	.example {
		overflow-y: auto;
	}
</style>