<template>
	<view class="page" :class="{ big: isH5 }">
		<view class="panel">
			<view class="filters">
				<view class="chip" :class="{ active: query.rangeKey === '7d' }" @tap="setRange('7d')">近1周</view>
				<view class="chip" :class="{ active: query.rangeKey === '1m' }" @tap="setRange('1m')">近1月</view>
				<view class="chip" :class="{ active: query.rangeKey === '3m' }" @tap="setRange('3m')">近3月</view>
				<view class="chip" :class="{ active: query.rangeKey === '' }" @tap="setRange('')">全部时间</view>
			</view>
			<view class="filters" style="margin-top: 14rpx;">
				<view class="chip" :class="{ active: query.warningLevel === '' }" @tap="setLevel('')">全部</view>
				<view class="chip" :class="{ active: query.warningLevel === '低' }" @tap="setLevel('低')">低</view>
				<view class="chip" :class="{ active: query.warningLevel === '中' }" @tap="setLevel('中')">中</view>
				<view class="chip" :class="{ active: query.warningLevel === '高' }" @tap="setLevel('高')">高</view>
				<view class="chip" :class="{ active: query.warningLevel === '严重' }" @tap="setLevel('严重')">严重</view>
			</view>
			<view v-if="errorMsg" class="error">{{ errorMsg }}</view>
		</view>

		<view v-if="loading" class="state">
			<uni-icons type="spinner-cycle" size="28" color="#94A3B8"></uni-icons>
			<view class="state-text">加载中...</view>
		</view>
		<view v-else class="list">
			<view v-if="warnings.length === 0" class="state">
				<uni-icons type="notification" size="34" color="#CBD5E1"></uni-icons>
				<view class="state-text">暂无数据</view>
			</view>
			<view v-else>
				<view class="item" v-for="row in warnings" :key="row.warningId">
					<view class="head">
						<view class="badge" :class="badgeClass(row.warningLevel)">{{ row.warningLevel || '—' }}</view>
						<view class="head-title">{{ row.warningReason || '预警' }}</view>
					</view>
					<view class="item-desc">测评ID {{ row.assessmentId || '-' }} · {{ row.scaleName || '-' }} · {{ row.userName || '-' }}</view>
					<view class="item-foot">状态：{{ statusText(row.status) }}</view>
					<view class="actions">
						<view class="action-chip" v-if="row.status !== '2'" @tap.stop="onCreateTask(row)">创建任务</view>
						<view class="action-chip" v-if="row.status === '0'" @tap.stop="onHandle(row)">处理</view>
						<view class="action-chip" v-if="row.status !== '2'" @tap.stop="onRelieve(row)">解除</view>
					</view>
				</view>
				<view v-if="hasMore" class="load-more">上拉加载更多…</view>
				<view v-else class="load-more">没有更多了</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { listWarning, handleWarning, relieveWarning } from '../../api/psychology/warning'
	import UniIcons from '@/uni_modules/uni-icons/components/uni-icons/uni-icons.vue'
	export default {
		components: {
			UniIcons
		},
		data() {
			return {
				isH5: false,
				loading: false,
				errorMsg: '',
				warnings: [],
				total: 0,
				query: {
					pageNum: 1,
					pageSize: 10,
					warningLevel: '',
					status: '',
					rangeKey: '7d'
				}
			}
		},
		onLoad(options) {
			try {
				const info = uni.getSystemInfoSync()
				this.isH5 = info && info.uniPlatform === 'web'
			} catch (e) {
				this.isH5 = false
			}
			try {
				const st = options && typeof options.status !== 'undefined' ? String(options.status) : ''
				const wl = options && typeof options.warningLevel !== 'undefined' ? String(options.warningLevel) : ''
				if (st) this.query.status = st
				if (wl) this.query.warningLevel = wl
			} catch (e) {}
			this.refresh()
		},
		onShow() {
			this.refresh()
		},
		onPullDownRefresh() {
			this.refresh().finally(() => {
				uni.stopPullDownRefresh()
			})
		},
		onReachBottom() {
			if (this.loading) return
			if (!this.hasMore) return
			this.query.pageNum += 1
			this.fetchList(true)
		},
		computed: {
			hasMore() {
				return this.warnings.length < (this.total || 0)
			}
		},
		methods: {
			formatDateTime(value) {
				const pad = (n) => String(n).padStart(2, '0')
				const d = value instanceof Date ? value : new Date(value)
				return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
			},
			calcRange(key) {
				if (!key) return { beginTime: '', endTime: '' }
				const now = new Date()
				const end = this.formatDateTime(now)
				const begin = new Date(now.getTime())
				if (key === '7d') begin.setDate(begin.getDate() - 7)
				if (key === '1m') begin.setMonth(begin.getMonth() - 1)
				if (key === '3m') begin.setMonth(begin.getMonth() - 3)
				begin.setHours(0, 0, 0, 0)
				return { beginTime: this.formatDateTime(begin), endTime: end }
			},
			setLevel(level) {
				this.query.warningLevel = level
				this.refresh()
			},
			setRange(key) {
				this.query.rangeKey = key
				this.refresh()
			},
			refresh() {
				this.query.pageNum = 1
				this.warnings = []
				this.total = 0
				return this.fetchList(false)
			},
			fetchList(append) {
				this.errorMsg = ''
				this.loading = true
				const range = this.calcRange(this.query.rangeKey)
				const params = {
					pageNum: this.query.pageNum,
					pageSize: this.query.pageSize
				}
				if (this.query.warningLevel) params.warningLevel = this.query.warningLevel
				if (this.query.status) params.status = this.query.status
				if (range.beginTime) params['params[beginTime]'] = range.beginTime
				if (range.endTime) params['params[endTime]'] = range.endTime

				return listWarning(params)
					.then((res) => {
						this.loading = false
						const data = res && res.data ? res.data : null
						if (!data || data.code !== 200) {
							this.errorMsg = (data && data.msg) ? data.msg : '加载失败'
							return
						}
						const rows = data.rows || []
						this.total = data.total || 0
						this.warnings = append ? this.warnings.concat(rows) : rows
					})
					.catch((e) => {
						this.loading = false
						this.errorMsg = e && e.message ? e.message : '网络错误'
					})
			},
			statusText(status) {
				const map = {
					'0': '未处理',
					'1': '处理中',
					'2': '已解除'
				}
				return map[String(status)] || '未知'
			},
			badgeClass(level) {
				const v = (level || '').trim()
				if (v === '严重') return 'danger'
				if (v === '高') return 'high'
				if (v === '中') return 'warn'
				if (v === '低') return 'low'
				return 'low'
			},
			onCreateTask(row) {
				const wid = row && row.warningId ? row.warningId : ''
				const url = wid
					? ('/pages/warning/createTask?warningId=' + encodeURIComponent(wid))
					: '/pages/warning/createTask'
				uni.navigateTo({ url })
			},
			onHandle(row) {
				if (!row || !row.warningId) return
				uni.showModal({
					title: '处理预警',
					content: '确认将该预警标记为处理中？',
					success: (r) => {
						if (!r.confirm) return
						this.loading = true
						handleWarning({ warningId: row.warningId, handleResult: '移动端处理' })
							.then((res) => {
								this.loading = false
								const data = res && res.data ? res.data : null
								if (!data || data.code !== 200) {
									uni.showToast({ title: (data && data.msg) ? data.msg : '处理失败', icon: 'none' })
									return
								}
								uni.showToast({ title: '已处理', icon: 'success' })
								this.refresh()
							})
							.catch((e) => {
								this.loading = false
								uni.showToast({ title: e && e.message ? e.message : '网络错误', icon: 'none' })
							})
					}
				})
			},
			onRelieve(row) {
				if (!row || !row.warningId) return
				uni.showModal({
					title: '解除预警',
					content: '确认解除该预警？',
					success: (r) => {
						if (!r.confirm) return
						this.loading = true
						relieveWarning({ warningId: row.warningId, reliefReason: '移动端解除' })
							.then((res) => {
								this.loading = false
								const data = res && res.data ? res.data : null
								if (!data || data.code !== 200) {
									uni.showToast({ title: (data && data.msg) ? data.msg : '解除失败', icon: 'none' })
									return
								}
								uni.showToast({ title: '已解除', icon: 'success' })
								this.refresh()
							})
							.catch((e) => {
								this.loading = false
								uni.showToast({ title: e && e.message ? e.message : '网络错误', icon: 'none' })
							})
					}
				})
			}
		}
	}
</script>

<style scoped>
	.page {
		min-height: 100vh;
		padding: 24rpx 24rpx 120rpx;
		box-sizing: border-box;
		background: #F4F6FB;
	}
	.panel {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 18rpx;
		padding: 24rpx;
		border: 1px solid rgba(15, 23, 42, 0.06);
		box-shadow: 0 10rpx 22rpx rgba(15, 23, 42, 0.05);
		margin-bottom: 18rpx;
	}
	.filters {
		display: flex;
		flex-wrap: wrap;
	}
	.chip {
		padding: 14rpx 22rpx;
		border-radius: 999rpx;
		font-size: 26rpx;
		line-height: 36rpx;
		min-height: 60rpx;
		box-sizing: border-box;
		color: #64748B;
		background: rgba(15, 23, 42, 0.04);
		margin-right: 16rpx;
		margin-bottom: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.chip.active {
		color: #1677ff;
		background: rgba(22, 119, 255, 0.12);
	}
	.list {
		margin-top: 8rpx;
	}
	.item {
		background: rgba(255, 255, 255, 0.95);
		border-radius: 18rpx;
		padding: 18rpx;
		border: 1px solid rgba(15, 23, 42, 0.06);
		margin-bottom: 14rpx;
	}
	.head {
		display: flex;
		align-items: center;
		gap: 12rpx;
	}
	.badge {
		font-size: 22rpx;
		padding: 6rpx 12rpx;
		border-radius: 999rpx;
		color: #ffffff;
		background: #8f959e;
		flex: 0 0 auto;
	}
	.badge.danger { background: #ff4d4f; }
	.badge.high { background: #ff7a45; }
	.badge.warn { background: #faad14; }
	.badge.low { background: #52c41a; }
	.head-title {
		font-size: 28rpx;
		font-weight: 700;
		color: #111827;
		min-width: 0;
		flex: 1;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
	}
	.item-desc {
		margin-top: 10rpx;
		font-size: 24rpx;
		color: #64748B;
	}
	.item-foot {
		margin-top: 10rpx;
		font-size: 22rpx;
		color: #94A3B8;
	}
	.actions {
		margin-top: 14rpx;
		display: flex;
		justify-content: flex-end;
		gap: 12rpx;
	}
	.action-chip {
		padding: 10rpx 16rpx;
		border-radius: 999rpx;
		font-size: 24rpx;
		font-weight: 700;
		color: #1677ff;
		background: rgba(22, 119, 255, 0.10);
		border: 1px solid rgba(22, 119, 255, 0.16);
	}
	.action-chip:active {
		opacity: 0.85;
	}
	.state {
		height: 360rpx;
		border-radius: 20rpx;
		background: rgba(255, 255, 255, 0.85);
		border: 1px solid rgba(15, 23, 42, 0.06);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 12rpx;
	}
	.state-text {
		font-size: 24rpx;
		color: #94A3B8;
		font-weight: 700;
	}
	.load-more {
		text-align: center;
		color: #94A3B8;
		font-size: 22rpx;
		padding: 20rpx 0 6rpx;
	}
	.error {
		margin-top: 14rpx;
		font-size: 24rpx;
		color: #ff4d4f;
		line-height: 36rpx;
	}

	.page.big {
		padding: 14rpx 14rpx 120rpx;
		background-image:
			radial-gradient(1100rpx 520rpx at 50% 14%, rgba(43, 107, 255, 0.30) 0%, rgba(6, 16, 40, 0.0) 65%),
			linear-gradient(180deg, rgba(5, 11, 24, 0.90) 0%, rgba(8, 20, 45, 0.85) 42%, rgba(6, 16, 40, 0.92) 100%),
			url('/static/bg.png');
		background-size: auto, auto, cover;
		background-position: center, center, center;
		background-repeat: no-repeat, no-repeat, no-repeat;
	}
	.page.big .panel,
	.page.big .item {
		border: 1px solid rgba(116, 216, 255, 0.22);
		background: linear-gradient(180deg, rgba(10, 18, 38, 0.75) 0%, rgba(5, 10, 22, 0.55) 100%);
		box-shadow: 0 12rpx 24rpx rgba(0, 0, 0, 0.35);
	}
	.page.big .chip {
		color: rgba(201, 242, 255, 0.70);
		background: rgba(10, 18, 38, 0.65);
		border: 1px solid rgba(116, 216, 255, 0.20);
	}
	.page.big .chip.active {
		color: #0b1226;
		background: linear-gradient(90deg, rgba(116, 216, 255, 0.95) 0%, rgba(43, 107, 255, 0.90) 100%);
		border-color: rgba(116, 216, 255, 0.5);
	}
	.page.big .head-title {
		color: rgba(235, 248, 255, 0.92);
	}
	.page.big .item-desc {
		color: rgba(201, 242, 255, 0.70);
	}
	.page.big .item-foot,
	.page.big .load-more {
		color: rgba(201, 242, 255, 0.55);
	}
	.page.big .action-chip {
		color: rgba(201, 242, 255, 0.90);
		background: rgba(116, 216, 255, 0.10);
		border: 1px solid rgba(116, 216, 255, 0.22);
	}
	.page.big .state {
		background: rgba(7, 13, 28, 0.30);
		border: 1px dashed rgba(116, 216, 255, 0.22);
	}
	.page.big .state-text {
		color: rgba(201, 242, 255, 0.70);
	}
</style>
