<template>
	<view class="page-container">
		<view class="toptitle">
			<view class="toptitle_left" @click="ht">
				<u-icon name="arrow-left" color="#fff" size="20"></u-icon>
			</view>
			<view class="toptitle_title">
				故障排查
			</view>
		</view>
		<view class="title">
			<view class="title-search-wrapper">
				<u-search shape="square" :clearabled="true" :showAction="false" placeholder="请输入故障代码（完全匹配）" v-model="form.keyword"></u-search>
				<!-- 暂时隐藏关联产品筛选 -->
				<!-- <view class="filter-btn" @click="showFlPicker = true" v-if="false">
					<text class="filter-btn-text">{{ selectedFlName || '关联产品' }}</text>
					<text class="filter-btn-icon">▼</text>
				</view> -->
			</view>
		</view>
		<view class="main">
			<view class="search-placeholder"></view>
		<u-picker :show="show" :columns="columns" @confirm="confirm" @cancel="show = false"></u-picker>
		<view v-if="list.length === 0 && !loading" class="empty-tip">
			<view style="text-align: center; padding: 40px 20px; color: #999;">
				<text>{{ !(form.keyword || '').trim() ? '请输入故障代码进行检索（完全匹配）' : '未找到匹配的故障，请检查故障代码是否正确' }}</text>
			</view>
		</view>
		<u-picker 
			:show="showFlPicker" 
			:columns="flColumns" 
			@confirm="flConfirm" 
			@cancel="showFlPicker = false"
			class="fl-picker-custom"
		></u-picker>
		<view class="box" v-for="item in list" :key="item.id" @click="xq(item)">
			<view class="top" style="margin-bottom: 10px;">
				<span class="f1" v-if="item.zwbjwb != null">{{item.zwbjwb}}</span>
			</view>
			<view class="top2">
				<span class="f4">故障代码</span>
				<span class="f5">{{item.code}}</span>
			</view>
			<view class="top2">
				<span class="f4">严重程度</span>
			<view :class="['severity-pill', severityClass(item.yzdcd)]">
				{{ item.yzdcd == null ? '无' : item.yzdcd }}
			</view>
			</view>
			<view class="top2">
				<span class="f4">关联产品</span>
				<span class="f5">{{item.glcpmc == null || item.glcpmc == '' ? '无' : item.glcpmc}}</span>
			</view>
			<view class="top2" >
				<span class="f4">描述</span>
				<span class="f5" style="overflow: hidden;
				text-overflow: ellipsis;
				display:-webkit-box; 
				-webkit-box-orient:vertical; 
				-webkit-line-clamp:2;">
					{{item.wbjdm == null || item.wbjdm == undefined || item.wbjdm == '' ? '无' : item.wbjdm}}
				</span>
			</view>
			<view class="xx">
			</view>
			<view class="footer">
				<span></span>
				<view class="">
					<u-button size="small" type="primary" text="查看"></u-button>
				</view>
			</view>
		</view>
		</view>
	</view>
</template>

<script>
	export default {

		data() {
			return {
				keyword: "",
				show: false,
				columns: [
					['故障代码','关键词']
				],
				title: "关键词",
				form:{
					currentPage:1,
					pageSize:10,
					keyword:"",
					fl: "" // 分类筛选
				},
				list:[],
				loading: false,
				nv_length:0,
				showFlPicker: false,
				flOptions: [], // 分类选项
				flColumns: [['全部']], // 分类选择器的列数据
				flMap: {}, // 分类名称到ID的映射
				selectedFlName: "", // 选中的分类名称
				searchTimer: null // 搜索防抖定时器
			}
		},
		onLoad() {
			this.getflOptions(); // 获取分类选项
			// 进入页面不加载数据，仅支持通过故障代码检索后展示
			if(uni.getStorageSync("sycx") == '1' && uni.getStorageSync("keyword") && uni.getStorageSync("keyword").trim() !== ''){
				this.form.keyword = uni.getStorageSync("keyword");
				// 有缓存的 keyword 时自动触发检索
				this.$nextTick(() => this.gzpclist());
			}
		},
		onReachBottom() {
			if(!(this.form.keyword || '').trim()) return; // 无关键字时不加载更多
			var page = Math.ceil(this.nv_length / 10);
			if (page > parseInt(this.form.currentPage)) {
				this.form.currentPage = parseInt(this.form.currentPage) + 1
				this.gzpclist();
			} else {
				uni.showToast({
					icon: "error",
					title: "没有更多内容"
				})
			}
		},
		onUnload() {
			// 页面卸载时清除防抖定时器
			if(this.searchTimer){
				clearTimeout(this.searchTimer);
				this.searchTimer = null;
			}
		},
		watch:{
			'form.keyword'(newVal, oldVal){
				// 清除之前的定时器
				if(this.searchTimer){
					clearTimeout(this.searchTimer);
					this.searchTimer = null;
				}
				// 重置分页和列表
				this.form.pageSize = 10
				this.form.currentPage = 1
				this.list = []
				const kw = (newVal || '').trim();
				// 仅当输入故障代码时才检索，清空时不再请求
				if(kw === ''){
					return;
				}
				// 设置防抖，500ms后执行搜索
				this.searchTimer = setTimeout(() => {
					this.gzpclist();
					this.searchTimer = null;
				}, 500);
			},
			'form.fl'(newVal, oldVal){
				// 分类变化时，仅当有关键字时才搜索
				if(!(this.form.keyword || '').trim()) return;
				this.form.pageSize = 10
				this.form.currentPage = 1
				this.list = []
				if(this.searchTimer){
					clearTimeout(this.searchTimer);
					this.searchTimer = null;
				}
				this.gzpclist();
			},
		},
		methods:{
			// 获取产品选项（用于关联产品筛选，仅当前用户可查看的产品）
			getflOptions(){
				this.API.hqcpglAllowedList({
					currentPage: 1,
					pageSize: 1000 // 获取足够多的产品
				}).then(res => {
					if(res && res.code == 200 && res.data && res.data.list){
						this.flOptions = res.data.list;
						// 构建选择器的列数据（产品名称列表）
						const productNames = res.data.list.map(item => {
							// 显示格式：产品名称 (产品ID)
							const displayName = item.cpmc ? `${item.cpmc}${item.cpid ? ' (' + item.cpid + ')' : ''}` : (item.cpid || item.id);
							return displayName;
						});
						// 构建ID映射（产品名称到ID的映射）
						this.flMap = {};
						res.data.list.forEach(item => {
							const displayName = item.cpmc ? `${item.cpmc}${item.cpid ? ' (' + item.cpid + ')' : ''}` : (item.cpid || item.id);
							this.flMap[displayName] = item.id;
						});
						// 添加"全部"选项
						this.flColumns = [['全部', ...productNames]];
					} else {
						console.error('获取产品列表失败，响应:', res);
						this.flOptions = [];
						this.flColumns = [['全部']];
						this.flMap = {};
					}
				}).catch(err => {
					console.error('获取产品列表失败:', err);
					this.flOptions = [];
					this.flColumns = [['全部']];
					this.flMap = {};
				});
			},
			// 分类选择确认
			flConfirm(e){
				const selectedIndex = e.indexs[0];
				const selectedText = e.value[0];
				if(selectedIndex === 0 || selectedText === '全部'){
					this.form.fl = '';
					this.selectedFlName = '';
				} else {
					this.form.fl = this.flMap[selectedText] || '';
					this.selectedFlName = selectedText;
				}
				this.showFlPicker = false;
			},
			severityClass(val){
				const s = String(val == null ? '' : val).replace(/\s+/g,'');
				// 兼容包含说明文字的值，例如：轻微(蓝色椭圆带白色文字)
				if(s.includes('轻微') || s.includes('蓝色')) return 'sev-light';
				if(s.includes('一般') || s.includes('黄色')) return 'sev-medium';
				if(s.includes('严重') || s.includes('红色')) return 'sev-high';
				return 'sev-none';
			},
			gzpclist(){
				const kw = (this.form.keyword || '').trim();
				if(!kw){
					this.list = [];
					this.loading = false;
					return; // 必须有故障代码才请求
				}
				this.loading = true
				const params = {
					currentPage: this.form.currentPage,
					pageSize: this.form.pageSize,
					searchKey: kw
				};
				if(this.form.fl && this.form.fl.trim() !== ''){
					params.fl = this.form.fl.trim();
				}
				if (this.form.currentPage === 1) {
					this.list = []
				}
				this.API.gzpclistSimpleSearch(params).then(res=>{
					this.loading = false
					if (res && res.code === 200 && res.data) {
						this.nv_length = res.data.pagination ? res.data.pagination.total : 0
						if(res.data.list && res.data.list.length > 0){
							for(let i = 0;i < res.data.list.length;i++){
								this.list.push(res.data.list[i])
							}
						}
					}
				}).catch(err => {
					this.loading = false
					uni.showToast({ title: err.msg || err.message || '加载失败', icon: 'none' })
				})
			},
			timestampToTime(timestamp) {
			    const date = new Date(timestamp); //时间戳为10位需*1000，13位不需乘
			    const Y = date.getFullYear() + '-';
			    const M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
			    const D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
			    const h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
			    const m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
			    const s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
			    
			    return Y + M + D + h + m + s;
			},
			ht(){
				uni.setStorageSync("sycx",'2')
				// 跳转到首页（tabBar页面需要使用switchTab）
				uni.switchTab({
					url: '/pages/home/home'
				});
			},
			confirm(e){
				console.log("11",e);
				this.title = e.value[0]
				this.show = false
				this.keyword = ''
			},
			xq(item){
				var data = JSON.stringify(item)
				uni.setStorageSync("detail",data)
				console.log(item)
				uni.navigateTo({
					url:"/pages/new/gzpc/detail"
				})
				// this.API.hqgzxqxx(item).then(res=>{
				// 	console.log("1111",res);
				// })
				
			},
		}
	}
</script>

<style scoped lang="scss">
	@import '../zlgl/index.scss';
	@import './index.scss';
  .severity-pill{
    display: inline-block;
    padding: 2px 10px;
    border-radius: 999px;
    font-size: 12px;
    line-height: 20px;
    color: #fff;
    margin-left: 8px;
  }
  .sev-light{ background-color: #3A7AFE; }
  .sev-medium{ background-color: #FFB020; }
  .sev-high{ background-color: #E34D59; }
  .sev-none{ background-color: #C0C4CC; }
</style>

			