<template>
	<view class="situationsCenter-page">
		<tmNavbar @onsearchChange="onsearchChangehandle" :is-back="false" @checkMessage="checkMessageHandle"
			:titleMod="nowPermission == 6||nowPermission == 4||nowPermission ==7||nowPermission == 8?'Filter':'Normal'"
			:filterKeys="filterKeys" :isShowFilter="true" :messageStatus="true" :isShowSearch="true"
			@filterClick="filterClickHandle" :title="pageTitle" title-color="#292C33"></tmNavbar>

		<view class="situation-list">

			<scroll-view class="scroll-box" scroll-y="true" @scrolltolower="toLower" lower-threshold="5">
				<view class="content" :style="[situationList.length === 0 ?{height:'100%'}:{}]">
					<view class="situation" v-for="(item) in situationList" :key="item.id"
						@click="gotoDetail(item.situationID?item.situationID:item.id,item.systemSituationType,item)">
						<!-- 左上角类型角标图片（系统/个案/自查督查） -->
						<image class="type-badge" :src="typeBadgeSrc(item.systemSituationType)" />

						<!-- 右上角组徽标（图标 + 组名） -->
						<view class="group-badge">
							<image class="group-icon" src="/static/images/zu_text.png" />
							<text class="group-text">{{ item.checkGroupName }}</text>
						</view>

						<view class="title">
							<text class="title-name">{{ item.name }}</text>

							<!-- 状态角标：在标题行右侧，且仅自查督查时显示 -->
							<view v-if="item.systemSituationType == 2 && nowPermission != 1" :class="['status-badge', statusClass(item)]">{{ situationStatusName(item) }}</view>
						</view>
						<view class="check-group">
							<text class="group-text-a">{{ planText(item) }}</text>
							<image  class="improve-btn" src="/static/images/quwanshan_btn.png" @click.stop="gotoImprove(item)" />
						</view>
					</view>
					<tm-no-data v-if="situationList.length === 0" :textArr="['还没有情境', '快点击右下方按钮新建一个吧']" />
				</view>
			</scroll-view>
		</view>
		<view v-if="nowPermission == 1" class="situaions-add" @click="gotoCreate">
			<image class="add-pic" src="/static/situation-add.png"></image>
		</view>
		<tm-tabbar :permission="nowPermission" />
	</view>
</template>
/**
* 情境中心
*/
<script>
	import websocket from "../../utils/ws.js"; //引入websocket
	import tmNavbar from "@/components/tm-navbar/tm-navbar.vue";
	import {
		wsURL
	} from "../../utils/requestUrl.js";
	// import appUpdate from "@/components/app-update/app-update.vue"

	export default {
		components: {
			tmNavbar
		},
		data() {
			return {

				page: 1, //页数
				inputValue: "",
				nowPermission: "",
				isSearchBarShow: false, //搜索栏是否可见
				isSearchBoxShow: true, //搜索图标是否可见
				situationList: [], //情境卡片列表
				copied_situationList: [], //复制情境卡片列表 用于筛选
				totalCount: "", //返回数据的总条数
				refTimer: null,
				isInitWs: null,
				messageType: null,
				num: 1,
				pageTitle: '情境中心',
				// showUpdatePop:false,
				timer: null,
				// ws接口参数
				initParams: {},

			};
		},
		// components:{appUpdate},
		created: function() {
			this.nowPermission = uni.getStorageSync("nowPermission");
			this.init(true);
			this.refTimer = setInterval(() => {
				this.isInitWs = websocket.ws ? false : true;
				const {
					hiId,
					user,
					permission
				} = this.initParams;
				this.isInitWs && this.initWebsocket(hiId, user, permission);
			}, 3 * 60 * 1000);

			// this.messStatus();
		},
		beforeDestroy() {
			// 关闭ws连接
			websocket.close();
			clearInterval(this.refTimer);
			clearTimeout(this.timer);
		},
		computed: {
			statusBarHeight() {
				const {
					statusBarHeight
				} = uni.getSystemInfoSync();
				return statusBarHeight;
			},
			filterKeys() {

				const list = [{
						text: '全部',
						checked: true,
						key: '0'
					},
					{
						text: '已完成',
						checked: false,
						key: '6'
					},
					{
						text: '进行中',
						checked: false,
						key: '2'
					},
					{
						text: '待分配',
						checked: false,
						key: '4'
					}
				];
				
				return list;

				// const modify = (key) => {
				// 	const _list = list.map(a => {
				// 		if (a.key == key) {
				// 			return {
				// 				...a,
				// 				checked: true
				// 			}
				// 		} else {
				// 			return {
				// 				...a,
				// 				checked: false
				// 			}
				// 		}
				// 	});
				// 	return _list;
				// }

				// if (this.nowPermission == 6) {
				// 	//职能科室负责人
				// 	return modify(1);
				// }
				// if (this.nowPermission == 6) {
				// 	//职能科室负责人
				// 	return modify(4);
				// }

			}

		},
		mounted() {

		},
		methods: {
			// 是否需要展示“去完善”按钮：当查核计划或下次查核缺失时
			needImprove(item) {
				// 分配权限卡片不展示“去完善”
				if (this.nowPermission == 2) return false;
				// 计划值：自查督查用 checkPlanCount/checkStatus，其他用 checkStatus
				const hasPlan = (item.systemSituationType == 2)
					? (typeof item.checkPlanCount === 'number' ? item.checkPlanCount > 0 : !!item.checkStatus)
					: !!item.checkStatus;
				const hasNext = !!item.nextCheckTime;
				return !(hasPlan && hasNext);
			},
			planText(item) {
				// 统一生成“查核计划 | 下次查核”的展示文案：
				// 仅对“查核计划”的值进行“到次为止”的截取，“下次查核”保留展示
				const clipToCi = (text) => {
					// 截取到包含“次”的位置（含“次”），若没有“次”则原样返回
					try {
						const str = String(text || '');
						const idx = str.indexOf('次');
						return idx >= 0 ? str.slice(0, idx + 1) : str;
					} catch (e) { return text; }
				}
				// 1）分配权限优先显示“剩余待分配”
				if (this.nowPermission == 2) {
					return `剩余${item.toDistributeCount || 0}个待分配`;
				}
				// 2）自查督查类型展示“第N/次”，并展示“下次查核”
				if (item.systemSituationType == 2) {
					const times = (typeof item.checkPlanCount === 'number' ? item.checkPlanCount : parseInt(item.checkStatus, 10)) || 0;
					const planVal = `第${times}/次`;
					const next = item.nextCheckTime ? `下次查核：${item.nextCheckTime}` : '下次查核：--';
					return `查核计划：${clipToCi(planVal)}  |  ${next}`;
				}
				// 3）其他类型：截取“查核计划”到“次”，并展示“下次查核”
				const planRaw = item.checkStatus ? String(item.checkStatus) : '暂无计划';
				const next = item.nextCheckTime ? `下次查核：${item.nextCheckTime}` : '下次查核：--';
				return `查核计划：${clipToCi(planRaw)}  |  ${next}`;
			},
			typeBadgeSrc(type) {
				// 根据类型返回左上角角标图片路径
				if (type === 1) return '/static/images/xitongzhuizong.png';
				if (type === 0) return '/static/images/gean.png';
				if (type === 2) return '/static/images/zichaducha.png';
				return '/static/images/xitongzhuizong.png';
			},
			statusClass(item) {
				// 根据情境状态返回样式类名
				if (item.situationStatus == 2) return 'doing';
				if (item.situationStatus == 6) return 'complete';
				if (item.situationStatus == 4) return 'wait';
				if (item.situationStatus == 5) return 'complete';
				return '';
			},
			filterClickHandle(filterData) {
	
				if (filterData.key != 0) {
					const _situationList = this.copied_situationList.filter(item => item.situationStatus == Number(
						filterData.key));
					this.situationList = _situationList;
				}else{
					this.situationList = this.copied_situationList
				}

			},
			situationStatusName(item) {

				if (item.situationStatus == 2) {
					return '进行中'
				}
				if (item.situationStatus == 6) {
					return '全部完成'
				}
				if (item.situationStatus == 4) {
					return '待分配'
				}
				if (item.situationStatus == 5) {
					return '已完成'
				}

				return null

			},
			situationTypeName(item, type) {

				if (item.systemSituationType == 0) {
					return type == 1 ? '个案' : 'Mark case'
				}
				if (item.systemSituationType == 1) {
					return type == 1 ? '系统' : 'Mark system'
				}
				if (item.systemSituationType == 2) {
					return type == 1 ? '自查督查' : 'Mark zichaducha'
				}
			},
			getClass(item) {
				if (item.situationStatus == 2) {
					return 'topMark doing'
				}
				if (item.situationStatus == 6) {
					return 'topMark complete'
				}
				if (item.situationStatus == 4) {
					return 'topMark wait'
				}
				if (item.situationStatus == 5) {
					return 'topMark complete'
				}

				return 'topMark'
			},
			onsearchChangehandle(keywords) {
				this.searchByKeywords(keywords);
			},
			openSearchBar() {
				this.isSearchBarShow = true;
				this.isSearchBoxShow = false;
			},
			checkMessageHandle() {
				//查看消息
				uni.navigateTo({
					url: `/pages/messages/messages`,
				});
			},
			closeSearchBar() {
				this.isSearchBarShow = false;
				this.isSearchBoxShow = true;
			},
			valueEmpty() {
				this.inputValue = "";
			},
			gotoCreate() {
				uni.navigateTo({
					url: "/pages/creatingSituations/creatingSituations",
				});
			},
			gotoImprove(item) {
				// 去完善：进入创建页编辑模式，先回显数据，再从第一步重走
				const id = item.situationID ? item.situationID : item.id;
				const systemSituationType = item.systemSituationType;
				const name = item.name || '';
                let url = `/pages/creatingSituations/creatingSituations?id=${id}&type=PUT&from=improve`;
                if (systemSituationType == 2) {
                    // 自查督查：仅走管理员路线（MULTI），不再附带 planSet
                    url += `&systemSituationType=${systemSituationType}&themeName=${encodeURIComponent(name)}&situationId=${id}`;
                }
				uni.navigateTo({ url });
			},
			gotoDetail(id, systemSituationType, item) {
				console.log(this.situationList);
                console.log({id, systemSituationType, item});
				this.$store.commit({
					type: 'situationsCenter/comChangeState',
					key: 'currentSelectedSituation',
					data: item
				});

				uni.navigateTo({
					url: `/pages/situationDetail/situationDetail?situationId=${id}&systemSituationType=${systemSituationType}`,
				});
			},
			getSituationList(data, callback) {
				this.$store
					.dispatch({
						type: "situationsCenter/commActions",
						payload: {
							data,
							key: "situationList",
						},
					})
					.then((data) => {
						if (data) callback(data);
					});
			},
			searchByKeywords(keywords) {
				let data = {
					pageNum: 1,
					pageSize: 300,
					keyword: keywords,
				};
				this.getSituationList(data, (data) => {
					this.situationList = [];
					this.createSituationList(data.list);
				});
			},
			createSituationList(list = []) {
				list.map((item, index) => {
					this.situationList.push({
						name: item.name,
						checkStatus: item.checkStatus,
						nextCheckTime: item.nextCheckTime,
						systemSituationType: item.systemSituationType,
						//systemSituationType == 0 普通 1 自查督查
						checkGroupName: item.systemSituationType != 2 ? item.checkGroupName : (item
							.department.map(v => v.deptClassName)).join(','),
						topic: item.topic == 0 ? true : false,
						situationStatus: item.situationStatus,
						situationID: item.id,
						toDistributeCount: item.toDistributeCount,
					});
				});
			},
			toLower() {

				uni.showToast({
					title: "加载中....",
					icon: "loading",
					duration: 2000,
				});
				let count = this.situationList.length;
				if (this.totalCount != count) {
					this.page++;
					let data = {
						pageNum: this.page,
						pageSize: 300,
					};
					// this.getSituationList(data, (data) => {
					// 	this.createSituationList(data.list);
					// 	let hiId = uni.getStorageSync("hiId");
					// 	let user = uni.getStorageSync("id");
					// 	let permission = uni.getStorageSync("nowPermission");
					// 	this.initParams = {
					// 		hiId,
					// 		user,
					// 		permission
					// 	};
					// 	this.isInitWs && this.initWebsocket(hiId, user, permission);
					// });
				} else {
					uni.showToast({
						title: "没有更多数据了",
						icon: "none",
						duration: 1000,
					});
				}
			},
			// toMessagePage() {
			// 	// this.messageType = false;
			// 	uni.navigateTo({
			// 		url: `/pages/messages/messages`,
			// 	});
			// },
			init(isInitWs) {
				this.isInitWs = isInitWs;
				this.initSituationList();
			},
			initWebsocket(hiId, user, permission) {
				websocket.url = wsURL(hiId, user, permission);
				websocket.createWebSocket(this.resolverWsData.bind(this));
			},
			// 解析websocket返回数据
			resolverWsData(type) {
				let types = JSON.parse(type);
				switch (types.type) {
					case "TO_READ":
						this.messageType = true;
						break;
					default:
						this.messageType = false;
						break;
				}
			},
			initSituationList() {
				let data = {
					pageNum: 1,
					pageSize: 300,
				};
				this.getSituationList(data, (data) => {
					this.totalCount = data.totalCount;
					this.createSituationList(data.list);
					this.copied_situationList = data.list;
					let hiId = uni.getStorageSync("hiId");
					let user = uni.getStorageSync("id");
					let permission = uni.getStorageSync("nowPermission");
					this.initParams = {
						hiId,
						user,
						permission
					};
					this.isInitWs && this.initWebsocket(hiId, user, permission);
				});
			},
			// messStatus(){
			// 	let num = 1;
			// 	let timer = setInterval(()=>{
			// 	  this.$store.dispatch({
			// 		  type: "calendar/commActions",
			// 		  payload: {
			// 			key: "messagesList",
			// 		  },
			// 		}).then((res)=>{
			// 			if(res && res.list.length == 0){
			// 				clearInterval(timer)
			// 			}else if(res && res.list.length != 0){
			// 				res.list.map((item)=>{
			// 					if(!item.readStatus){
			// 						this.messageType = true;
			// 						return;
			// 					}
			// 				})
			// 			}
			// 		})
			// 	  num++;
			// 	},200)


			// }
			
		},
	};
</script>

<style lang="less" scoped>
	.situationsCenter-page {
		height: 100%;

		.navbar {
			background-color: #ffffff;
		}

		.calender-remind {
			width: 62.5rpx;
			height: 62.5rpx;
			position: fixed;
			top: 20rpx;
			right: 25rpx;
			background: rgba(255, 255, 255, 0.95);
			border-radius: 50%;
			z-index: 2;

			image {
				margin-left: 17.5rpx;
				margin-top: 16.87rpx;
				width: 27.5rpx;
				height: 28.75rpx;
			}
		}

		.search-box {
			position: fixed;
			top: 20rpx;
			left: 25rpx;
			z-index: 2;

			.search-model {
				height: 62.5rpx;
				width: 62.5rpx;
				background-color: #ffffff;
				text-align: center;
				border-radius: 50%;
				box-shadow: 0px 10px 10px 0px rgba(217, 221, 228, 0.5);
				border: 1px solid #e6eaf2;
				opacity: 0.85;

				.search-pic {
					width: 27.5rpx;
					height: 27.5rpx;
					margin-top: 17.5rpx;
				}
			}

			.search-bar {
				background-color: #ffffff;
				width: 700rpx;
				height: 62.5rpx;
				top: 0rpx;
				position: absolute;
				z-index: 2;

				.search-item {
					background-color: #ffffff;
					width: 593.75rpx;
					height: 62.5rpx;
					float: left;
					border-radius: 6.25rpx;
					border-right: 1.25rpx solid #f0f2f7;
					;

					.search-pic {
						width: 21.87rpx;
						height: 21.87rpx;
						margin-left: 12.5rpx;
						margin-top: 20.62rpx;
						float: left;
					}

					.searh-input {
						background-color: #ffffff;
						width: 525rpx;
						height: 55rpx;
						font-size: 22.5rpx;
						float: right;
						margin-top: 3.75rpx;
						margin-left: 3.12rpx;
					}

					.text-clear {
						width: 21.87rpx;
						height: 21.87rpx;
						float: right;
						margin-top: 20.62rpx;
						margin-right: 6.25rpx;
					}
				}

				.cancel-text {
					font-size: 22.5rpx;
					line-height: 62.5rpx;
					color: #a1a7b3;
					margin-right: 31.25rpx;
					float: right;
				}
			}
		}

		.situation-list {
			position: relative;
			height: 100%;

			.scroll-box {
				width: 100%;
				height: calc(100% - 87.5rpx);

				.content {
					display: flex;
					flex-flow: column nowrap;
					padding-bottom: 100rpx;

					.situation {
						position: relative;
						height: 187.5rpx;
						width: 700rpx;
						background: #ffffff;
						box-shadow: 0px 6px 20px 0px rgba(0, 13, 51, 0.1);
						border-radius: 8px;
						margin-left: 25rpx;
						margin-right: 25rpx;
						margin-top: 25rpx;
						// overflow: hidden;

						/* 左上角类型角标图片样式 */
						.type-badge {
							position: absolute;
							top: 0rpx;
							left: 0rpx;
							width: 480rpx;
							height: 40rpx;
							z-index: 1;
						}

						/* 右上角组徽标样式（图标 + 文字） */
						.group-badge {
							position: absolute;
							top: 8rpx;
							right: 8rpx;
							display: flex;
							align-items: center;
							padding: 4rpx 10rpx;
							background: #F2F5FA;
							border-radius: 10rpx;
							max-width: 220rpx;
						}

						.group-icon {
							width: 22rpx;
							height: 22rpx;
							margin-right: 6rpx;
						}

						.group-text {
							font-size: 18rpx;
							color: #7A8599;
							max-width: 190rpx;
							overflow: hidden;
							text-overflow: ellipsis;
							white-space: nowrap;
						}

						/* 标题行右侧的状态角标 */
						.status-badge {
							margin-left: auto;
							padding: 3rpx 10rpx;
							font-size: 13.75rpx;
							color: #FFFFFF;
							border-radius: 10rpx;
						}
						.status-badge.doing { background-color: rgba(255, 204, 102, 1); }
						.status-badge.wait { background-color: rgba(102, 179, 255, 1); }
						.status-badge.complete { background-color: rgba(173, 184, 204, 1); }

						.situation-topic {
							width: 62.5rpx;
							height: 25rpx;
							float: right;
						}

						.title {
							margin-left: 20rpx;
							margin-top: 70rpx;
							display: flex;
							align-items: center;
                            height: 50rpx !important;
							.title-name {
								font-size: 40rpx !important;
								&>span {
									display: inline-block;
									width: 300rpx;
									
									color: #292c33;
									overflow: hidden; //超出的文本隐藏
									text-overflow: ellipsis; //溢出用省略号显示
									white-space: nowrap; //溢出不换行
								}
								

							}
						}

						.check-group {
							margin-left: 20rpx;
							margin-top: 15rpx;
							margin-bottom: 25rpx;
							height: 17.5rpx;
							display: flex;
							align-items: center;

							.group-text-a {
								font-size: 22rpx;
								font-family: SourceHanSansCN-Normal, SourceHanSansCN;
								font-weight: 400;
								color: #666e80;
								overflow: hidden;
								text-overflow: ellipsis;
								white-space: nowrap;
							}

							/* 去完善按钮样式：与文案同一行右侧显示 */
							.improve-btn {
								margin-left: auto;
								width: 120rpx;
								height: 45rpx;
								margin-right: 20rpx;
							}
						}

					}
				}
			}
		}

		.situaions-add {
			position: fixed;
			right: 25rpx;
			bottom: 130rpx;

			.add-pic {
				width: 75rpx;
				height: 75rpx;
			}
		}
	}
</style>
