bjzc.vue 15.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
<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 v-else class="box" v-for="item in list" :key="item.id" @click="xq(item)">
				<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;">
					<span></span>
					<view class="">
						<u-button size="small" type="primary" text="查看"></u-button>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {

		data() {
			return {
				dataTree: [],
				expandedIds: [],
				keyword: "",
				show: false,
				columns: [
					['设备名','备件名称/备件编号','关键词']
				],
				title: "关键词",
				list:[],
				loading: false,
				form:{
					currentPage:1,
					pageSize:20,
					keyword:"",
					fl: "" // 关联产品筛选
				},
				nv_length:0,
				categoryCounts: {}, // 存储每个分类的备件数量 {categoryId: count}
				showFlPicker: false,
				flOptions: [], // 产品选项
				flColumns: [['全部']], // 产品选择器的列数据
				flMap: {}, // 产品名称到ID的映射
				selectedFlName: "", // 选中的产品名称
				searchTimer: null // 搜索防抖定时器
			}
		},
		computed: {
			hasSearchKeyword() {
				return (this.form.keyword && this.form.keyword.trim() !== '') || (this.form.fl && this.form.fl.trim() !== '');
			}
		},
		onReachBottom() {
			// 分页加载
			var page = Math.ceil(this.nv_length / this.form.pageSize);
			if (page > parseInt(this.form.currentPage)) {
				this.form.currentPage = parseInt(this.form.currentPage) + 1
				this.bjyzclist(true);
			} else {
				uni.showToast({
					icon: "error",
					title: "没有更多内容"
				})
			}
		},
		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.currentPage = 1
				this.list = []
				// 设置防抖,500ms后执行搜索
				this.searchTimer = setTimeout(() => {
					this.bjyzclist();
					this.searchTimer = null;
				}, 500);
			},
			'form.fl'(newVal, oldVal){
				// 关联产品变化时立即搜索,不需要防抖
				this.form.currentPage = 1
				this.list = []
				// 如果有关键字搜索的防抖定时器,先清除它
				if(this.searchTimer){
					clearTimeout(this.searchTimer);
					this.searchTimer = null;
				}
				this.bjyzclist();
			},
		},
		onLoad() {
			this.getflOptions(); // 获取产品选项
			this.bjyzclist(); // 直接加载备件列表
		},
		methods:{
			isExpanded(id){
				return this.expandedIds.indexOf(id) !== -1;
			},
			toggleExpand(id){
				const idx = this.expandedIds.indexOf(id);
				if(idx === -1){
					this.expandedIds.push(id);
				}else{
					this.expandedIds.splice(idx,1);
				}
			},
			selectCategory(node){
				const id = node.id || ''
				if(!id){
					return
				}
				// 如果有子节点,只展开/收起,不跳转
				if(node.children && node.children.length > 0){
					this.toggleExpand(node.id)
					return
				}
				// 如果没有子节点,跳转到列表页
				uni.navigateTo({
					url: `/pages/new/bjzc/list?bjfl=${id}`
				})
			},
			// 获取分类
			hqcpfl(){
				this.API.hqcpfl("625969064434468101").then(res=>{
					console.log("获取分类",res);
					if(res && res.code == 200 && res.data && res.data.list){
						if(res.data.list.length > 0){
							const mapNode = (n)=>({
								id: n.id,
								name: n.fullName,
								children: Array.isArray(n.children) ? n.children.map(mapNode) : []
							});
							this.dataTree = res.data.list.map(mapNode);
							console.log("分类树数据:", this.dataTree);
							// 获取所有分类的备件数量
							this.loadCategoryCounts();
						} else {
							console.warn("分类列表为空");
							this.dataTree = [];
						}
					} else {
						console.error("获取分类失败,响应:", res);
						this.dataTree = [];
					}
				}).catch(err => {
					console.error("获取分类异常:", err);
					this.dataTree = [];
				})
			},
			// 获取所有叶子分类的备件数量
			loadCategoryCounts(){
				// 获取所有叶子节点(没有子节点的分类)
				const getLeafNodes = (nodes) => {
					let leafNodes = [];
					nodes.forEach(node => {
						if (!node.children || node.children.length === 0) {
							leafNodes.push(node);
						} else {
							leafNodes = leafNodes.concat(getLeafNodes(node.children));
						}
					});
					return leafNodes;
				};
				
				const leafNodes = getLeafNodes(this.dataTree);
				console.log('叶子节点:', leafNodes);
				
				// 为每个叶子节点获取数量
				if (leafNodes.length > 0) {
					const promises = leafNodes.map(node => {
						return this.API.bjyzclist({
							currentPage: 1,
							pageSize: 1, // 只需要总数,设置最小页大小
							bjfl: node.id
						}).then(res => {
							if (res && res.code === 200 && res.data && res.data.pagination) {
								const count = res.data.pagination.total || 0;
								this.$set(this.categoryCounts, node.id, count);
								return { id: node.id, count };
							}
							this.$set(this.categoryCounts, node.id, 0);
							return { id: node.id, count: 0 };
						}).catch(err => {
							console.error(`获取分类 ${node.id} 数量失败:`, err);
							this.$set(this.categoryCounts, node.id, 0);
							return { id: node.id, count: 0 };
						});
					});
					
					Promise.all(promises).then(results => {
						console.log('所有分类数量:', results);
					});
				}
			},
			// 获取分类的备件数量(如果当前节点没有,尝试从子节点汇总)
			getCategoryCount(node){
				if (!node || !node.id) return null;
				// 如果是叶子节点,直接返回数量(如果已加载则返回,否则返回 null 表示未加载)
				if (!node.children || node.children.length === 0) {
					// 检查是否已经加载过该分类的数量
					if (this.categoryCounts.hasOwnProperty(node.id)) {
						return this.categoryCounts[node.id] || 0;
					}
					// 还未加载,返回 null
					return null;
				}
				// 如果有子节点,计算所有叶子子节点的总数
				const getLeafCount = (n) => {
					if (!n.children || n.children.length === 0) {
						if (this.categoryCounts.hasOwnProperty(n.id)) {
							return this.categoryCounts[n.id] || 0;
						}
						return null; // 未加载
					}
					let total = 0;
					let hasLoaded = false;
					n.children.forEach(child => {
						const childCount = getLeafCount(child);
						if (childCount !== null) {
							total += childCount;
							hasLoaded = true;
						}
					});
					return hasLoaded ? total : null;
				};
				return getLeafCount(node);
			},
			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;
			},
			// 获取产品选项(用于关联产品筛选,仅当前用户可查看的产品)
			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;
			},
			bjyzclist(append = false){
				if (this.loading) return
				this.loading = true
				
				// 构建查询参数
				const params = {
					currentPage: this.form.currentPage,
					pageSize: this.form.pageSize
				};
				
				// 如果有搜索关键字或关联产品筛选,使用简单搜索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();
					}
					
					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
					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: '加载失败,请稍后重试'
						})
					})
				}
			},
			ht(){
				// 获取页面栈
				const pages = getCurrentPages();
				// 如果页面栈中只有一页(当前页),则直接跳转到首页
				if (pages.length === 1) {
					// 首页是 tabBar 页面,使用 switchTab
					uni.switchTab({
						url: '/pages/home/home'
					});
				} else {
					// 否则返回上一页
					uni.navigateBack({
						delta: 1
					});
				}
			},
			confirm(e){
				console.log("11",e);
				this.title = e.value[0]
				this.show = false
				this.keyword = ''
			},
			xq(item){
				uni.setStorageSync("bjxqdetail", item)
				uni.navigateTo({
					url:"/pages/new/bjzc/detail"
				})
			},
		}
	}
</script>

<style scoped lang="scss">
	@import '../zlgl/index.scss';
	@import '../gzpc/index.scss';
  .category-tree{
    background-color: #fff;
    border-radius: 5px;
    padding: 10px;
  }
  .category-row{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 6px 8px;
  }
  .category-name{
    font-size: 14px;
    color: #333;
  }
  .caret{
    font-size: 12px;
    color: #666;
    width: 20px;
    text-align: center;
  }
  .category-item {
    cursor: pointer;
    user-select: none;
    min-height: 44px;
  }
  .category-name-wrapper {
    flex: 1;
    cursor: pointer;
    user-select: none;
    padding: 10px 0;
  }
  .category-toggle {
    cursor: pointer;
    user-select: none;
    padding: 10px;
    min-width: 40px;
    text-align: center;
  }
  .category-count {
    margin-left: 8px;
    color: #666;
    font-size: 12px;
    font-weight: normal;
  }
  .category-count-zero {
    color: #ccc;
  }
  // 修复返回按钮点击区域
  .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>