<template>
	<view class="risk-record-page">
		<u-sticky>
			<view class="filter-bar">
				<view class="filter filter-date-range" @click="handleShowPicker({title: '时间区间', name: 'dateRange'})">
					<text>{{dateFilterTxt}}</text>
					<u-icon size="14" style="margin-left: 4px;" name="arrow-down"></u-icon>
				</view>
				<uni-search-bar class="search-bar" radius="100" :value="keyword" @confirm="handleSearch"
					@cancel="handleCancelSearch" @clear="handleCancelSearch" placeholder="搜索"></uni-search-bar>
				<view class="filter filter-status" @click="handleShowPicker({title: '状态', name: 'status'})">
					<text>{{statusFilterTxt}}</text>
					<u-icon size="14" style="margin-left: 4px;" name="arrow-down"></u-icon>
				</view>
			</view>
		</u-sticky>
		<view class="main">
			<view class="content-list">
				<common-card :dataSource="item" v-for="item in lists" class="content" @click="showDetail(item.ID)">
					<view>
						<view class="field">
							<text class="label">时间：</text>
							<text class="value">{{item.START_TIME}} ~ {{item.END_TIME}}</text>
						</view>
						<view class="field">
							<text class="label">状态：</text>
							<text class="value">{{item.STATUS}}</text>
						</view>
					</view>
				</common-card>
			</view>
			<view v-if="!lists.length" class="empty-wrap">
				<u-empty text="暂无数据" icon="/static/empty@2x.png">
				</u-empty>
			</view>
		</view>
		<u-picker :show="comPickerInfo.showPicker" :columns="comPickerInfo.columns" @confirm="onConfirmPicker"
			:defaultIndex="[0]" @cancel="closePicker"></u-picker>
	</view>
</template>

<script>
	import {
		getRequestOrderPage
	} from '../../../../services/apply/FOServices/FOServices.js'
	import {
		extendInclude,
		extendRule,
		initFilter
	} from '../../../../utils/common'
	import {
		getEnum
	} from '../../../../services/common';

	export default {
		data() {
			return {
				pageIndex: 1,
				total: 0,
				lists: [],
				keyword: '',
				searchStartTime: '',
				filterStatus: null,
				dateFilterTxt: '时间区间',
				statusFilterTxt: '状态筛选',
				comPickerInfo: {
					showPicker: false,
					columns: [],
					title: '',
					name: ''
				},
				enumsData: {}, // 存储所有枚举数据（键：枚举名称，值：处理后的枚举列表）
				enumsText: {} // 存储枚举文本列表（用于下拉选择等场景）
			}
		},
		onLoad() {
			this.fetchEnums(['FOPreMeetingStatusEnum']);
			// this.getEnums()
			// this.loadData()
		},
		methods: {
			handleSearch(obj) {
				this.keyword = obj.value
			},
			handleCancelSearch() {
				this.keyword = ''
			},
			async fetchEnums(enumNames) {
				try {
					// 存储所有枚举请求的Promise
					const enumPromises = enumNames.map(name => {
						return getEnum({
							name
						}).then(res => {
							// 统一处理枚举格式：添加name/code字段，便于后续映射
							return {
								enumName: name,
								data: res.map(item => ({
									...item,
									name: item.NAME, // 统一显示名称字段
									code: item.ID // 统一值字段
								}))
							};
						});
					});
			
					// 等待所有枚举请求完成
					const results = await Promise.all(enumPromises);
					// 存储枚举结果到data中（键为枚举名称，值为处理后的数据）
					results.forEach(({
						enumName,
						data
					}) => {
						this.enumsData[enumName] = data;
						// 生成文本列表（如需要）
						this.enumsText[enumName] = data.map(item => item.name);
					});
					// 所有枚举获取完成后，执行loadData
					this.loadData();
				} catch (error) {
					console.error('枚举请求失败:', error);
					uni.showToast({
						title: '枚举数据加载失败',
						icon: 'none'
					});
				}
			},
			loadData() {
				const orgId = uni.getStorageSync('orgId')
				const json = initFilter(orgId, "", "CREATE_TIME", 1, this.pageIndex)
				extendInclude(json, "Nav_InitiatingDepartment")
				extendInclude(json, "Nav_LiableUser")
				if (this.keyword) {
					extendRule(json, 'NAME', 9, this.keyword)
				}
				if (this.searchStartTime) {
					extendRule(json, 'START_TIME', 6, this.searchStartTime)
				}
				if (this.filterStatus !== null) {
					extendRule(json, 'STATUS', 1, this.filterStatus)
				}
				getRequestOrderPage(json, "/HM/HazardTask/OrderPaged").then(res => {
					this.total = res.TotalCount;
					for (let i = 0; i < res.Data.length; i++) {
						// res.Data[i].STATUS = this.transStatus(res.Data[i].STATUS)
						res.Data[i].LEVEL = this.transLevel(res.Data[i].LEVEL)
						res.Data[i].START_TIME = res.Data[i].START_TIME.substring(0, 10)
						res.Data[i].END_TIME = res.Data[i].END_TIME.substring(0, 10)
					}

					let newRes = (res.Data || []).map(i => {
						return {
							...i,
							title: i.LEVEL + i.Nav_LiableUser.NAME + "-辨识任务",
							STATUS: i.STATUS!==undefined?this.enumsData['FOPreMeetingStatusEnum'].find(item => item.code === i.STATUS).name:''
						}
					})
					if (this.pageIndex !== 1) {
						this.lists = this.lists.concat(newRes)
					} else {
						this.lists = newRes
					}
				})
			},
			showDetail(id) {
				uni.navigateTo({
					url: '/pages/apply/subPages/HM/3hazardTaskShow?ID=' + id
				})
			},
			handleShowPicker(p) {
				let column = []
				if (p.name === 'dateRange') {
					column = ['全部', '当天', '最近三天', '最近一周', '最近一月']
				}
				if (p.name === 'status') {
					// column = ['全部', '草稿', '签到中', '归档']
					let arr = []
					arr.push('全部')
					this.enumsText['FOPreMeetingStatusEnum'].map(item => {
						arr.push(item)
					})
					column =arr
				}
				this.comPickerInfo = {
					showPicker: true,
					title: p.title,
					name: p.name,
					columns: [column]
				}
			},
			onConfirmPicker(e) {
				if (this.comPickerInfo.name === 'dateRange') {
					let currentDate = new Date();
					if (e.indexs[0] === 2) {
						currentDate.setDate(currentDate.getDate() - 3);
					} else if (e.indexs[0] === 3) {
						currentDate.setDate(currentDate.getDate() - 7);
					} else if (e.indexs[0] === 4) {
						currentDate.setDate(currentDate.getMonth());
					}
					if (e.indexs[0] === 0) {
						this.searchStartTime = ''
						this.dateFilterTxt = '时间区间'
					} else {
						this.dateFilterTxt = e.value[0]
						this.searchStartTime = uni.$u.timeFormat(currentDate, 'yyyy-mm-dd 00:00:00');
					}
				}
				if (this.comPickerInfo.name === 'status') {
					if(e.indexs[0] ==0 ){
						this.filterStatus=null
					}else{
						this.filterStatus = this.enumsData['FOPreMeetingStatusEnum'][e.indexs[0]-1].code 
					}
					this.statusFilterTxt = e.value[0]
					
				}
				this.closePicker()
			},
			closePicker() {
				this.comPickerInfo = {
					showPicker: false,
					columns: [],
					title: '',
					name: ''
				}
			},
			transStatus(status) {
				if (status == 0) {
					return '草稿';
				}
				if (status == 2) {
					return '签到中';
				}
				if (status == 4) {
					return '审核中';
				}
				if (status == 5) {
					return '归档';
				}
				if (status == 9) {
					return '审批拒绝';
				}
			},
			transLevel(level) {
				if (level == 0) {
					return '部门 ';
				}
				if (level == 1) {
					return '车间 ';
				}
				if (level == 2) {
					return '班组 ';
				}
				if (level == 3) {
					return '公司 ';
				}
			},
		},

		onReachBottom() {
			// 页码 +1
			if (this.total > 10 * this.pageIndex)
				this.pageIndex++
		},
		watch: {
			pageIndex(n, o) {
				this.loadData()
			},
			keyword(n, o) {
				this.pageIndex = 1
				this.keyword = n
				this.loadData()
			},
			searchStartTime(n, o) {
				this.pageIndex = 1
				this.searchStartTime = n
				this.loadData()
			},
			filterStatus(n, o) {
				this.pageIndex = 1
				this.filterStatus = n
				this.loadData()
			}
		}
	}
</script>

<style>
	.risk-record-page {
		position: relative;
	}

	.risk-record-page .main {
		padding: 0px 16px;
		position: relative;
	}

	.risk-record-page>>>.uni-searchbar {
		padding: 0px;
		display: flex;
		align-items: center;
		font-size: 12px;

		.uni-searchbar__box {
			height: 30px;
		}

		.uni-searchbar__box-icon-clear {
			display: flex;
			align-items: center;
		}

		.uni-input-placeholder {}

		.uni-searchbar__box-search-input {
			font-size: 12px;
		}

		.uni-searchbar__text-placeholder {
			font-size: 12px;
			margin-left: 0px;
		}

		.uni-text {
			font-size: 12px;
		}
	}

	.filter-bar .search-bar {
		margin-left: 20px;
		margin-right: 20px;
		width: 100%;
		display: flex;
		flex: 1;
		align-items: center;
		font-size: 12px;
	}

	.filter-bar {
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #ffffff;
		padding: 10px 16px 10px 16px;
		box-shadow: 0px 0px 5px 0px #eaedf4;
	}

	.filter-bar .filter {
		display: flex;
		align-items: center;
		font-size: 12px;
		line-height: 18px;
		color: #333;
	}

	.content-list {
		padding: 10px 0;
	}

	.content .field {
		font-size: 12px;
		line-height: 18px;
		margin-bottom: 4px;
	}

	.content .field .label {
		color: #666;
	}

	.content .field .value {
		color: #333333;
	}
</style>