<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" @search="onSearch"></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="show" :columns="columns" @confirm="confirm" @cancel="show = false"></u-picker>
		<u-picker :show="showFlPicker" :columns="flColumns" @confirm="flConfirm" @cancel="showFlPicker = false"></u-picker>
		<view class="box" v-for="item in list" :key="item.id" @click="xq(item, $event)">
			<view class="top" style="margin-bottom: 10px;">
				<span class="f1">{{ item.sbm }}</span>
			</view>
			<view class="top2">
				<span class="f4">规格</span>
				<span class="f5">{{ item.gg || '无' }}</span>
			</view>
			<view class="top2">
				<span class="f4">分类</span>
				<span class="f5">{{ getFlName(item.fl) || '无' }}</span>
			</view>
			<view class="top2">
				<span class="f4">关联产品</span>
				<span class="f5">{{ getProductName(item.sssb) || '无' }}</span>
			</view>
			<view class="xx">
			</view>
			<view class="footer">
				<view class="">
					<u-button size="small" type="primary" text="查看" @click.stop="xq(item, $event)"></u-button>
				</view>
			</view>
		</view>
		</view>
	</view>
</template>

<script>
export default {

	data() {
		return {
			keyword: "",
			show: false,
			columns: [
				['设备名', '零部件名', '故障类型','关键词']
			],
			title: "关键词",
			form: {
				currentPage: 1,
				pageSize: 20,
				sort: 'desc',
				sidx: '',
				keyword: '',
				sssb: '' // 关联产品筛选
			},
			list: [],
			total: 0,
			flOptions: [],
			showFlPicker: false,
			flColumns: [['全部']],
			flMap: {},
			selectedFlName: '',
			cpglOptions: [],
			searchTimer: null
		}
	},
	onLoad() {
		this.getflOptions();
		this.getCpglOptions();
		setTimeout(() => this.fetchList(), 100);
	},
	onUnload() {
		if (this.searchTimer) {
			clearTimeout(this.searchTimer);
			this.searchTimer = null;
		}
	},
	watch: {
		'form.keyword'(newVal) {
			if (this.searchTimer) {
				clearTimeout(this.searchTimer);
				this.searchTimer = null;
			}
			this.form.currentPage = 1;
			this.list = [];
			this.searchTimer = setTimeout(() => {
				this.fetchList();
				this.searchTimer = null;
			}, 500);
		},
		'form.sssb'() {
			this.form.currentPage = 1;
			this.list = [];
			if (this.searchTimer) {
				clearTimeout(this.searchTimer);
				this.searchTimer = null;
			}
			this.fetchList();
		}
	},
	onReachBottom() {
		const pages = Math.ceil(this.total / this.form.pageSize);
		if (pages > this.form.currentPage) {
			this.form.currentPage = this.form.currentPage + 1;
			this.fetchList();
		} else {
			uni.showToast({
				icon: 'error',
				title: '没有更多内容'
			});
		}
	},
		methods:{
			// 获取分类选项
			getflOptions(){
				this.API.hqcpfl("626798056427226373").then(res => {
					if(res.code == 200 && res.data && res.data.list){
						this.flOptions = res.data.list;
					}
				}).catch(err => {
					console.error('获取分类选项失败:', err);
					this.flOptions = [];
				});
			},
			// 获取产品选项（关联产品筛选，仅当前用户可查看的产品）
			getCpglOptions() {
				this.API.hqcpglAllowedList({ currentPage: 1, pageSize: 1000 }).then(res => {
					if (res && res.code == 200 && res.data && res.data.list) {
						this.cpglOptions = res.data.list;
						const productNames = res.data.list.map(item =>
							item.cpmc ? `${item.cpmc}${item.cpid ? ' (' + item.cpid + ')' : ''}` : (item.cpid || item.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 {
						this.cpglOptions = [];
						this.flColumns = [['全部']];
						this.flMap = {};
					}
				}).catch(() => {
					this.cpglOptions = [];
					this.flColumns = [['全部']];
					this.flMap = {};
				});
			},
			flConfirm(e) {
				const selectedIndex = e.indexs[0];
				const selectedText = e.value[0];
				if (selectedIndex === 0 || selectedText === '全部') {
					this.form.sssb = '';
					this.selectedFlName = '';
				} else {
					this.form.sssb = this.flMap[selectedText] || '';
					this.selectedFlName = selectedText;
				}
				this.showFlPicker = false;
			},
			getProductName(productId) {
				if (!productId) return '';
				const product = this.cpglOptions.find(item => item.id === productId);
				return product ? (product.cpmc || product.cpid || productId) : productId;
			},
			// 根据分类ID获取分类名称
			getFlName(flId){
				if (!flId) return '';
				// 递归查找分类名称（包括子分类）
				const findFlName = (options, id) => {
					for(let i = 0; i < options.length; i++){
						if(options[i].id === id){
							return options[i].fullName;
						}
						// 如果有子分类，递归查找
						if(options[i].children && options[i].children.length > 0){
							const found = findFlName(options[i].children, id);
							if(found) return found;
						}
					}
					return null;
				};
				const flName = findFlName(this.flOptions, flId);
				return flName || flId; // 如果找不到，返回原始ID
			},
			fetchList(){
				const params = {
					n: Date.now(),
					currentPage: this.form.currentPage,
					pageSize: this.form.pageSize,
					sort: this.form.sort,
					sidx: this.form.sidx || 'id'
				};
				if (this.form.keyword && this.form.keyword.trim()) {
					params.sbm = this.form.keyword.trim();
				}
				if (this.form.sssb && this.form.sssb.trim()) {
					params.sssb = this.form.sssb.trim();
				}
				// 权限：管理员看全部知识，客户只看"我的设备"中已有设备关联产品的知识库
				const userInfo = uni.getStorageSync('userinfo') || {};
				const userAccount = (userInfo.userAccount || '').toString();
				const isAdministrator = userInfo.isAdministrator === true;
				if (!isAdministrator && userAccount !== 'admin') {
					const sskhbh = (userInfo.userId || userInfo.id || '').toString();
					if (sskhbh) params.sskhbh = sskhbh;
				}
				this.API.zsklist(params).then(res=>{
					this.total = 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]);
						}
					}
				});
			},
			onSearch(){
				this.form.currentPage = 1;
				this.list = [];
				this.fetchList();
			},
		formatDate(timestamp) {
			// 如果时间戳为空、null、undefined或空字符串，返回空字符串
			if (timestamp === null || timestamp === undefined || timestamp === '') {
				return '';
			}
			// 如果是字符串类型的时间戳，尝试转换为数字
			if (typeof timestamp === 'string') {
				const numTimestamp = parseInt(timestamp);
				if (isNaN(numTimestamp) || numTimestamp === 0) {
					return '';
				}
				timestamp = numTimestamp;
			}
			// 如果时间戳为0或负数，返回空字符串（0通常表示未设置的日期，会显示为1970-01-01）
			if (timestamp === 0 || timestamp < 0) {
				return '';
			}
			// 检查日期对象是否有效
			const date = new Date(timestamp);
			if (isNaN(date.getTime())) {
				return '';
			}
			// 如果时间戳小于86400000（1天的毫秒数），很可能是未设置的默认值（1970-01-01）
			// 86400000 = 24 * 60 * 60 * 1000，表示1970-01-02 00:00:00的时间戳
			if (timestamp < 86400000) {
				return '';
			}
			// 格式化日期
			return this.timestampToTime(timestamp);
		},
		timestampToTime(timestamp) {
			const date = new Date(timestamp);
			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.navigateBack({
				    delta: 1
			});
		},
		confirm(e){
			console.log("11",e);
			this.title = e.value[0]
			this.show = false
			this.keyword = ''
		},
			xq(item, e){
				// 处理事件对象（如果存在）
				if (e && e.stopPropagation) {
					e.stopPropagation();
				}
				uni.navigateTo({
					url:`/pages/new/zsk/detail?id=${item.id}`
				})
			},
	}
}
</script>

<style scoped lang="scss">
	@import '../zlgl/index.scss';
</style>
