<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">
					<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="showFlPicker" 
				:columns="flColumns" 
				@confirm="flConfirm" 
				@cancel="showFlPicker = false"
				class="fl-picker-custom"
			></u-picker>
			<view v-if="list.length === 0 && !loading" class="empty-tip">
				<view style="text-align: center; padding: 40px 20px; color: #999;">
					<text>仅显示您所属设备关联产品的备件，暂无数据时可前往「我的设备」添加设备</text>
				</view>
			</view>
			<view class="box" v-for="item in list" :key="item.id">
				<view class="top" style="margin-bottom: 10px;">
					<span class="f1">{{ item.mc || '' }}</span>
				</view>
				<view class="top2">
					<span class="f4">备件情况</span>
					<span class="f5">{{ item.bjqk == null ? '' : item.bjqk }}</span>
				</view>
				<view class="top2">
					<span class="f4">备件位置</span>
					<span class="f5">{{ item.bjwz ? item.bjwz : (item.wz == null ? '' : item.wz) }}</span>
				</view>
				<view class="top2">
					<span class="f4">关联产品</span>
					<span class="f5">{{ item.glcpmc || '' }}</span>
				</view>
				<view class="footer" style="border-top: 1px solid #ccc;padding-top: 10px;" @click="tz(item)">
					<span></span>
					<view class="">
						<u-button size="small" type="primary" text="查看"></u-button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				list: [],
				loading: false,
				form: {
					currentPage: 1,
					pageSize: 20,
					sort: 'desc',
					sidx: '',
					bjfl: '',
					keyword: "",
					fl: "" // 关联产品筛选
				},
				nv_length: 0,
				showFlPicker: false,
				flOptions: [], // 产品选项
				flColumns: [['全部']], // 产品选择器的列数据
				flMap: {}, // 产品名称到ID的映射
				selectedFlName: "", // 选中的产品名称
				searchTimer: null // 搜索防抖定时器
			}
		},
		onLoad(options) {
			console.log('list页面接收参数：', options)
			if (options && options.bjfl) {
				this.form.bjfl = options.bjfl
				console.log('设置分类ID：', this.form.bjfl)
			}
			this.getflOptions(); // 获取产品选项
			this.fetchList()
		},
		onUnload() {
			// 页面卸载时清除防抖定时器
			if(this.searchTimer){
				clearTimeout(this.searchTimer);
				this.searchTimer = null;
			}
		},
		watch:{
			'form.keyword'(newVal, oldVal){
				console.log('keyword changed', newVal, oldVal)
				// 清除之前的定时器
				if(this.searchTimer){
					clearTimeout(this.searchTimer);
					this.searchTimer = null;
				}
				// 重置分页和列表
				this.form.pageSize = 20
				this.form.currentPage = 1
				this.list = []
				// 设置防抖，500ms后执行搜索
				this.searchTimer = setTimeout(() => {
					this.fetchList();
					this.searchTimer = null;
				}, 500);
			},
			'form.fl'(newVal, oldVal){
				// 关联产品变化时立即搜索，不需要防抖
				this.form.pageSize = 20
				this.form.currentPage = 1
				this.list = []
				// 如果有关键字搜索的防抖定时器，先清除它
				if(this.searchTimer){
					clearTimeout(this.searchTimer);
					this.searchTimer = null;
				}
				this.fetchList();
			},
		},
		onReachBottom() {
			const page = Math.ceil(this.nv_length / this.form.pageSize)
			if (page > parseInt(this.form.currentPage)) {
				this.form.currentPage = parseInt(this.form.currentPage) + 1
				this.fetchList(true)
			} else {
				uni.showToast({
					icon: 'error',
					title: '没有更多内容'
				})
			}
		},
		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;
			},
			ht() {
				// 获取页面栈
				const pages = getCurrentPages();
				// 如果页面栈中只有一页（当前页），则直接跳转到首页
				if (pages.length === 1) {
					// 首页是 tabBar 页面，使用 switchTab
					uni.switchTab({
						url: '/pages/home/home'
					});
				} else {
					// 否则返回上一页
					uni.navigateBack({
						delta: 1
					});
				}
			},
			tz(data){
				uni.setStorageSync("bjxqdetail",data)
				uni.navigateTo({
					url:"/pages/new/bjzc/detail"
				})
			},
			fetchList(append = false) {
				if (this.loading) return
				this.loading = true
				
				// 构建查询参数
				const params = {
					currentPage: this.form.currentPage,
					pageSize: this.form.pageSize,
					sort: this.form.sort,
					sidx: this.form.sidx
				};
				
				// 如果有搜索关键字或关联产品筛选，使用简单搜索API
				if ((this.form.keyword && this.form.keyword.trim() !== '') || (this.form.fl && this.form.fl.trim() !== '')) {
					if(this.form.keyword && this.form.keyword.trim() !== ''){
						params.searchKey = this.form.keyword.trim();
					}
					if(this.form.fl && this.form.fl.trim() !== ''){
						params.fl = this.form.fl.trim();
					}
					// 如果有分类筛选，也加上
					if(this.form.bjfl && this.form.bjfl.trim() !== ''){
						params.bjfl = this.form.bjfl.trim();
					}
					
					console.log('简单搜索请求参数：', params)
					uni.showLoading({
						title: '加载中...'
					})
					this.API.bjyzclistSimpleSearch(params).then(res => {
						console.log('简单搜索API返回数据：', res)
						uni.hideLoading()
						this.loading = false
						if (res && res.code === 200 && res.data) {
							this.nv_length = res.data.pagination ? res.data.pagination.total : 0
							const rows = Array.isArray(res.data.list) ? res.data.list : []
							if (!append) this.list = []
							for (let i = 0; i < rows.length; i++) {
								this.list.push(rows[i])
							}
							if (this.list.length === 0 && !append) {
								uni.showToast({
									icon: 'none',
									title: '暂无数据'
								})
							}
						} else {
							if (!append) this.list = []
							uni.showToast({
								icon: 'none',
								title: res?.msg || '加载失败'
							})
						}
					}).catch((error) => {
						console.error('简单搜索请求失败：', error)
						uni.hideLoading()
						this.loading = false
						if (!append) this.list = []
						uni.showToast({
							icon: 'none',
							title: '加载失败，请稍后重试'
						})
					})
				} else {
					// 没有搜索条件，使用原来的API，保留分类筛选
					if(this.form.bjfl && this.form.bjfl.trim() !== ''){
						params.bjfl = this.form.bjfl.trim();
					}
					
					console.log('请求参数：', params)
					uni.showLoading({
						title: '加载中...'
					})
					this.API.bjyzclist(params).then(res => {
						console.log('API返回数据：', res)
						uni.hideLoading()
						this.loading = false
						if (res && res.code === 200 && res.data) {
							this.nv_length = res.data.pagination ? res.data.pagination.total : 0
							const rows = Array.isArray(res.data.list) ? res.data.list : []
							if (!append) this.list = []
							for (let i = 0; i < rows.length; i++) {
								this.list.push(rows[i])
							}
							if (this.list.length === 0 && !append) {
								uni.showToast({
									icon: 'none',
									title: '暂无数据'
								})
							}
						} else {
							if (!append) this.list = []
							uni.showToast({
								icon: 'none',
								title: res?.msg || '加载失败'
							})
						}
					}).catch((error) => {
						console.error('请求失败：', error)
						uni.hideLoading()
						this.loading = false
						if (!append) this.list = []
						uni.showToast({
							icon: 'none',
							title: '加载失败，请稍后重试'
						})
					})
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	@import '../zlgl/index.scss';
	@import '../gzpc/index.scss';
	// 修复返回按钮点击区域
	.toptitle_left {
		padding: 10px 15px !important;
		cursor: pointer;
		user-select: none;
		display: flex;
		align-items: center;
		justify-content: center;
		min-width: 44px;
		min-height: 44px;
	}
</style>