<template>
    <!-- 退料任务 -->
    <view class="accept page-common"> 
        <uni-row :gutter="24" class="search-form"> 
            <uni-col :span="18">
                <view>
                    <uni-easyinput v-model="queryParams.keyWord" placeholder="请输入内容"/>
                </view>
            </uni-col>
            <uni-col :span="6">
                <view class="search" @click="getTableList">查询</view>
            </uni-col>
        </uni-row>
		<!-- <uni-row :gutter="24" class="search-form">
			<uni-col :span="5">
			    <view style="font-size: 24rpx;">物资类型：</view> 
			</uni-col>
			<uni-col :span="19">
				<scroll-view scroll-x class="select-box">
                    <view class="select-box-content">
						<view class="select-box-item" :style="{ color: maId=='' ? 'red':'black' }" @click="getLevelOneList()">
						    全部
						</view> 
                        <view class="select-box-item" v-for="(item,index) in maList" :key="index" @click="chosenLevelOne(item)" :style="{ color: maId==item.id ? 'red':'black' }">
                            {{item.paName}}
                        </view> 
                    </view> 
				</scroll-view> 
			</uni-col>
		</uni-row>
        <uni-row :gutter="24" class="search-form">
			<uni-col :span="5">
			    <view style="font-size: 24rpx;">物资名称：</view> 
			</uni-col>
			<uni-col :span="19">
				<scroll-view scroll-x class="select-box">
                    <view class="select-box-content">
						<view class="select-box-item" :style="{ color: modelId=='' ? 'red':'black' }" @click="getLevelTwoList()">
						    全部
						</view> 
                        <view class="select-box-item" v-for="(item,index) in modelList" :key="index" @click="chosenLevelTwo(item)"  :style="{ color: modelId==item.id ? 'red':'black' }">
                            {{item.paName}}
                        </view> 
                    </view> 
				</scroll-view> 
			</uni-col>
		</uni-row> -->
		<view style="width:100%;">
			<uni-table border stripe emptyText="">
					<uni-tr>
						<uni-th style="font-size: 20rpx;" width="45px" align="center" >序号</uni-th> 
						<uni-th style="font-size: 20rpx;" width="70px" align="center">机具名称</uni-th>
						<uni-th style="font-size: 20rpx;" width="70px" align="center">规格型号</uni-th>
						<uni-th style="font-size: 20rpx;" width="70px" align="center">单位</uni-th>
						<uni-th style="font-size: 20rpx;" width="50px" align="center">库存</uni-th> 
						<uni-th style="font-size: 20rpx;" width="50px" align="center">在用</uni-th>
					</uni-tr>
					<uni-tr></uni-tr> 
			</uni-table>
		</view> 
        <scroll-view scroll-y class="scroll-container" @scrolltolower="onScrollTolower">
            <uni-table border stripe emptyText="暂无更多数据" sticky>
					<!-- <uni-tr>
						<uni-th style="font-size: 20rpx;" width="50px" align="center" >序号</uni-th> 
						<uni-th style="font-size: 20rpx;" width="80px" align="center">机具名称</uni-th>
						<uni-th style="font-size: 20rpx;" width="80px" align="center">规格型号</uni-th>
						<uni-th style="font-size: 20rpx;" width="80px" align="center">单位</uni-th>
						<uni-th style="font-size: 20rpx;" width="50px" align="center">库存</uni-th> 
						<uni-th style="font-size: 20rpx;" width="50px" align="center">在用</uni-th>
					</uni-tr> --> 
                <!-- 表格数据行 --> 
					<uni-tr v-for="(item,index) in tableList" :key="index">
						<uni-td style="width: 45px;font-size: 20rpx;text-align: center;">{{(index+1)}}</uni-td>
						<uni-td style="width: 70px;font-size: 20rpx;text-align: center;">{{item.typeName}}</uni-td>
						<uni-td style="width: 70px;font-size: 20rpx;text-align: center;">{{item.typeModelName}}</uni-td>
						<uni-td style="width: 70px;font-size: 20rpx;text-align: center;">{{item.unit}}</uni-td>
						<uni-td style="width: 50px;font-size: 20rpx;text-align: center;">{{item.storeNum}}</uni-td>
						<uni-td style="width: 50px;font-size: 20rpx;text-align: center;color: #409EFF" @click="goToUseDetails(item)">{{item.usNum}}</uni-td>  
					</uni-tr> 
            </uni-table>
        </scroll-view>
    </view>
</template>

<script setup>
import { ref, computed } from 'vue' 
import { onLoad,onShow} from '@dcloudio/uni-app' 
import { selectPartTreeListApi,selectPartTreeListByLevelApi } from '../../../services/partLease.js'
import { getRetainedEquipmentListApi } from '../../../services/stquery/stquery.js'
import { debounce } from 'lodash-es' 
const partList = ref([
    // {modelType:"手扶绞磨机", partName:"离合器轴", typeName:"XJSF-JM-1", storageNum:"20", preNum:"0"},{modelType:"手扶绞磨机", partName:"离合器轴", typeName:"XJSF-JM-2", storageNum:"20", preNum:"0"},{modelType:"手扶绞磨机", partName:"离合器轴", typeName:"XJSF-JM-3", storageNum:"20", preNum:"0"}
]) //列表数据源

const goToUseDetails = (item) => {
    uni.navigateTo({
        url: `/pages/stquery/deviceStatusRecord/useDetails?typeId=${item.typeId}`
    })
}

// --------1---------
// 类型数据
const maList = ref([])//一级选择数据
const maId = ref("")//一级选中id
// 获取类型数据(一级)
const getLevelOneList = async () => {
	const res = await selectPartTreeListApi({level:1})
	maList.value=res.data;
	maId.value="";
	getLevelTwoList()
} 
//选择类型(一级)
const chosenLevelOne = async (item) => {
	maId.value=item.id;
	const res = await selectPartTreeListApi({level:2,id:item.id})
	modelList.value=res.data.secondList;
	typeList.value=res.data.thirdList;
}
// --------2---------
 // 名称数据
const modelList = ref([])//二级选择数据
// 获取名称数据
const getLevelTwoList = async () => {
	const res = await selectPartTreeListApi({level:2})
	modelList.value=res.data
	modelId.value=""
	getLevelThreeList() 
}
const modelId = ref("")//二级选中id
//选择类型
const chosenLevelTwo = async (item) => {
	modelId.value=item.id;
	const res = await selectPartTreeListApi({level:3,id:item.id})
	typeList.value=res.data.thirdList
}
// --------3---------
 // 型号数据
const typeList = ref([])
// 获取名称数据
const getLevelThreeList = async () => {
	const res = await selectPartTreeListApi({level:3})
	typeList.value=res.data
	typeId.value="" 
}
const typeId = ref("") 
//选择类型
const chosenLevelThree = async(item) => {
	typeId.value=item.id; 
	let obj = { 
		partId:item.id,
		modelType:"",
		partName:"",
		typeName:item.paName,
		storageNum:item.storageNum,
		preNum:0
	}
	const res = await selectPartTreeListByLevelApi({id:item.id})
	res.data.forEach(i=>{
		if(i.level==1){
			obj.modelType=i.paName
		}
		if(i.level==2){
			obj.partName=i.paName
		}
	}) 
	//添加到table
	if(partList.value.length==0){
		partList.value[0]=obj
	}else{
		let index = partList.value.findIndex(v=>v.partId==item.id)
		if(index<0){//添加
			partList.value.push(obj)
		}else{//已存在
			uni.showToast({
				title: '当前领料任务已存在该规格型号！',
				icon: 'none',
			})
		}
	}
}

const tableList = ref([]) //列表数据源
const total = ref(0)
// 查询参数
const queryParams = ref({ 
    keyWord: '', //关键字 
    pageNum: 1,
    pageSize: 20,
})
// 滚动触底事件
const onScrollTolower = debounce(() => {
    console.log('触底事件')
    if (total.value > tableList.value.length) {
        queryParams.value.pageSize += 10
        getTableList()
    }
}, 500)
// 获取列表数据
const getTableList = async (isTap = false) => {
    try {
        uni.showLoading({ title: '加载中', mask: true })
        const res = await getRetainedEquipmentListApi(queryParams.value);
        const newRows = res?.data?.rows || [];
        total.value = res?.data?.total || 0;
      
        if (isTap || queryParams.pageNum === 1) {
          // 刷新或tab切换，直接替换
          tableList.value = newRows;
        } else {
          // 加载更多，按 typeId 去重后合并
          const existingIds = new Set(tableList.value.map(item => item.typeId));
          const filteredRows = newRows.filter(item => !existingIds.has(item.typeId));
          tableList.value.push(...filteredRows);
        }
    } catch (error) {
        console.log('🚀 ~ getTableList ~ error:', error)
    } finally {
        uni.hideLoading()
    }
};

const getRetainedEquipmentList = async () => {
	const res = await getRetainedEquipmentListApi({isApp:1})
	console.log(res)
	tableList.value=res.data
}
 
//点击记录
const goApply = () => { 
    // uni.navigateTo({ url: `/pages/part/part-lease/applyList` })
}
onLoad(() => {
    // getLevelOneList() 
	// getRetainedEquipmentList()
	tableList.value = []
	total.value = 0
	getTableList(true)
}) 
</script>

<style lang="scss" scoped>
.accept {
    height: 95vh;
    word-break: break-all;
    background-color: #f7f8fa;
    padding: 24rpx; 
    // 搜索表单
    .search-form {
        display: flex;
        align-items: center;
        background: #fff;
        padding: 10rpx;
        border-radius: 20rpx;
        margin-bottom: 24rpx;
        box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.05); 
		
		.select-box{
			width: 100%;
			height: 80rpx; 
		}
        .select-box-content{
            height: 75rpx; 
            width: auto;
            display: flex; 
			align-items: center;
            flex-wrap: nowrap;
        }
        .select-box-item{
            width: auto;
            padding: 5rpx;
            margin-right: 10rpx;
            height: 60rpx;
            line-height: 60rpx;
            font-size: 24rpx;
            word-break: keep-all;
            white-space: nowrap;
        }
		
        // 搜索按钮
        .search {
            height: 60rpx;
            background: linear-gradient(135deg, #4b8eff 0%, #3784fb 100%);
            text-align: center;
            line-height: 60rpx;
            color: #fff;
            border-radius: 12rpx;
            font-size: 28rpx;
            font-weight: 600;
            box-shadow: 0 6rpx 20rpx rgba(55, 132, 251, 0.2);
            transition: all 0.3s ease;

            &:active {
                transform: scale(0.98);
                opacity: 0.9;
            }
        }

        // 新增按钮
        .addBtn {
            height: 80rpx;
            background: linear-gradient(135deg, #19be6b 0%, #16a75c 100%);
            text-align: center;
            line-height: 80rpx;
            color: #fff;
            border-radius: 12rpx;
            font-size: 28rpx;
            font-weight: 600;
            box-shadow: 0 6rpx 20rpx rgba(25, 190, 107, 0.2);
            transition: all 0.3s ease;

            &:active {
                transform: scale(0.98);
                opacity: 0.9;
            }
        }
    }
}
 
// 列表容器
.scroll-container {
	width: 100%; 
    height: 65vh;
    margin: 0rpx auto; 
}

/* 针对Web平台 */
.scroll-view {
  overflow: auto; /* 允许滚动 */
  -ms-overflow-style: none; /* IE和Edge */
  scrollbar-width: none; /* Firefox */
}
 
/* 针对其他非Web平台，比如小程序，可以通过条件编译来设置 */
/* #ifdef MP-WEIXIN */
.scroll-view {
  scroll-view {
    scroll-x: true;
    scroll-y: auto;
    ::-webkit-scrollbar {
      display: none; /* 针对Webkit浏览器，隐藏滚动条 */
      width: 0;
      height: 0;
      color: transparent;
    }
  }
}
/* #endif */
</style>
