<template>
	<uni-navbar-lite :showRight=false title="物料清单"></uni-navbar-lite>
	<view class="page-container">
		<view class="list-page">
		    <!-- 搜索栏和类型标签 -->
		    <view class="search-block">
		        <view class="search-bar">
		            <view class="search-box">
		                <image class="search-icon" src="/static/images/workbench/list/1.png" mode="aspectFit"></image>
			                <input class="search-input" type="text" placeholder="请输入关键字查询" v-model="keyword" @input="handleSearch" />
		                <view v-if="keyword.length > 0" class="clear-btn" @tap="clearKeyword">
		                	<text class="clear-btn-text">×</text>
		                </view>
		                <view class="search-btn" @tap="handleSearch">
		                	<text class="search-btn-text">搜索</text>
		                </view>
		            </view>
		        </view>
		
		        <!-- 类型标签 -->
		        <view class="status-tabs">
		            <scroll-view class="scroll-view_H" direction="horizontal" :show-scrollbar="false">
		                <view 
		                    v-for="(cat, idx) in categories" 
		                    :key="idx" 
		                    class="status-tab" 
		                    :class="{ 'active': currentStatus === cat.id }" 
		                    @click="switchStatus(cat.id)"
		                >
		                    <text class="status-tab-text" :class="{ 'active-text': currentStatus === cat.id }">{{ cat.name }}</text>
		                </view>
		            </scroll-view>
		        </view>
		    </view>
		
		    <!-- 列表内容 -->
		    <common-list 
		        :dataList="dataList" 
		        :loading="loading" 
		        :refreshing="refreshing" 
		        :hasMore="hasMore" 
		        @refresh="handleRefresh" 
		        @loadMore="loadMore"
		    >
		        <template #default="{ item, index }">
		            <view class="list-item" @click="handleItemClick(item)">
		                <view class="item-container">
		                    <view class="item-header">
		                        <view class="item-main-info">
		                            <view class="item-name-row">
		                                <text class="item-name">{{ getItemName(item) }}</text>
		                                <text class="item-measure">{{ getMeasureName(item) }}</text>
		                            </view>
		                            <view class="item-details">
		                                <text class="item-code">编码: {{ getItemCode(item) }}</text>
		                                <text class="item-warehouse">仓库: {{ getWarehouseName(item) }}</text>
		                            </view>
		                        </view>
		                        <text class="item-type">{{ getItemTypeName(item) }}</text>
		                    </view>
		                </view>
		            </view>
		        </template>
		    </common-list>
		</view>
	</view>
</template>

<script setup lang="uts">
    import { ref, onMounted } from 'vue'
	import { onShow } from '@dcloudio/uni-app';
    import { getItemList, getItemTypeListByParentId } from '../../api/apply/index'

    type CategoryItem = { id: string; name: string; code: string }

    // 列表数据
    const dataList = ref<any[]>([])
    const keyword = ref<string>("")
    let searchTimer: number | null = null
    const page = ref<number>(1)
    const pageSize: number = 10
    const hasMore = ref<boolean>(true)
    const loading = ref<boolean>(false)
    const refreshing = ref<boolean>(false)

    // 分类数据
    const categories = ref<CategoryItem[]>([])
    const currentStatus = ref<string>('')
    const isSearching = ref<boolean>(false)

    // 获取物料名称
    const getItemName = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['itemName']
        return val != null ? val.toString() : ''
    }

    // 获取物料类型
    const getItemTypeName = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['itemTypeName']
        return val != null ? val.toString() : ''
    }

    // 获取计量单位
    const getMeasureName = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['measureName']
        return val != null ? val.toString() : ''
    }

    // 获取物料编码
    const getItemCode = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['itemCode']
        return val != null ? val.toString() : ''
    }

    // 获取仓库名称
    const getWarehouseName = (item: any | null): string => {
        if (item == null) return ''
        const jsonItem = item as UTSJSONObject
        const val = jsonItem['warehouseName']
        return val != null ? val.toString() : ''
    }

    // 点击列表项跳转到详情页
    const handleItemClick = (item: any | null): void => {
        if (item == null) return
        const jsonItem = item as UTSJSONObject
        const itemId = jsonItem['itemId']
        if (itemId != null) {
            uni.navigateTo({
                url: '/pages/item/detail?id=' + itemId.toString()
            })
        }
    }

    // 获取当前选中的分类code
    const getCurrentCategoryCode = (): string => {
        const currentCat = categories.value.find((c: CategoryItem) => c.id === currentStatus.value)
        return currentCat != null ? currentCat.code : ''
    }
	
	// 加载列表数据
	const loadData = async (isRefresh: boolean): Promise<void> => {
	    if (loading.value) return
	
	    try {
	        loading.value = true
	
	        if (isRefresh) {
	            page.value = 1
	        }
	
	        const searchKeyword = keyword.value != null ? keyword.value : ''
	        const itemTypeCode = getCurrentCategoryCode()
	        const result = await getItemList(itemTypeCode, page.value, pageSize, searchKeyword)
	        const resultObj = result as UTSJSONObject
	        const rows = resultObj['rows']
	        const total = resultObj['total'] as number
	
	        if (rows != null) {
	            const newData = rows as any[]
	            if (isRefresh) {
	                dataList.value = newData
	            } else {
	                dataList.value = [...dataList.value, ...newData]
	            }
	            hasMore.value = dataList.value.length < total
	        } else {
	            if (isRefresh) {
	                dataList.value = []
	            }
	            hasMore.value = false
	        }
	
	    } catch (e) {
	        console.error('加载失败:', e)
	    } finally {
	        loading.value = false
	        refreshing.value = false
	    }
	}

    // 加载分类数据
    const loadCategories = (): void => {
        getItemTypeListByParentId(200).then((res: any) => {
            const data = res as UTSJSONObject
            const list = data['data']
            if (list != null) {
                const listData = list as UTSJSONObject[]
                if (listData.length > 0) {
                    const arr: CategoryItem[] = []
                    listData.forEach((item: UTSJSONObject) => {
                        const idVal = item['itemTypeId']
                        const nameVal = item['itemTypeName']
                        const codeVal = item['itemTypeCode']
                        const cat: CategoryItem = {
                            id: idVal != null ? idVal.toString() : '',
                            name: nameVal != null ? nameVal.toString() : '',
                            code: codeVal != null ? codeVal.toString() : ''
                        }
                        arr.push(cat)
                    })
                    const allItem: CategoryItem = {id: '', name: '全部', code: ''}
                    arr.unshift(allItem)
                    categories.value = arr
                    // 加载第一个分类的物料
                    if (arr.length > 0) {
                        currentStatus.value = arr[0].id
                        loadData(true)
                    }
                    return
                }
            }
            const defaultArr: CategoryItem[] = []
            const defaultItem: CategoryItem = {id: '', name: '全部', code: ''}
            defaultArr.push(defaultItem)
            categories.value = defaultArr
        }).catch(() => {
            const defaultArr: CategoryItem[] = []
            const defaultItem: CategoryItem = {id: '', name: '全部', code: ''}
            defaultArr.push(defaultItem)
            categories.value = defaultArr
        })
    }

    // 切换分类
    const switchStatus = (status: string): void => {
        if (loading.value) {
            return;
        }
        if (isSearching.value) {
            return
        }
        isSearching.value = true
        currentStatus.value = status
        page.value = 1
        loadData(true)
        setTimeout(() => {
            isSearching.value = false
        }, 100)
    }
	
    // 下拉刷新
    const handleRefresh = (): void => {
        refreshing.value = true
        loadData(true)
    }

    // 加载更多
    const loadMore = (): void => {
        if (!hasMore.value || loading.value) return
        page.value++
        loadData(false)
    }

    // 搜索
    const handleSearch = (): void => {
		const timer = searchTimer
		if (timer != null) {
			clearTimeout(timer)
		}
		searchTimer = setTimeout(() => {
			page.value = 1
			loadData(true)
		}, 300)
    }

    // 清空搜索关键字
    const clearKeyword = (): void => {
        keyword.value = ''
        page.value = 1
        loadData(true)
    }



    // 初始化
    onMounted(() => {
        loadCategories()
    })

    // 页面显示时刷新列表
    onShow(() => {
        loadData(true)
    })
</script>

<style lang="scss">
	.page-container {
	    flex: 1;
	    background-color: #f5f8fe;
	    padding-top: env(safe-area-inset-top);
		background-color: #e8f0f9;
		padding: 20rpx 10rpx 20rpx 10rpx;
	}
	.page-header{
		font-size: 32rpx;
		color: #333333;
		font-weight: bold;
		padding-top:20px;
		padding-bottom: 10px;
	}
    .list-page {
        flex: 1;
        background-color: #e8f0f9;
    }

    .search-block {
        background-color: #ffffff;
		border-radius: 15rpx;
    }

    .search-bar {
        padding: 20rpx 30rpx;
    }

    .search-box {
        flex-direction: row;
        align-items: center;
        height: 72rpx;
        padding: 0 24rpx;
        background-color: #f5f5f5;
        border-radius: 36rpx;

        .search-icon {
            width: 32rpx;
            height: 32rpx;
            margin-right: 12rpx;
        }

        .search-input {
            flex: 1;
            font-size: 28rpx;
            color: #333333;
        }

        .search-btn {
            padding: 10rpx 20rpx;
            background-color: #007aff;
            border-radius: 8rpx;
            margin-left: 10rpx;
        }

        .search-btn-text {
            color: #ffffff;
            font-size: 24rpx;
        }

        .clear-btn {
            width: 36rpx;
            height: 36rpx;
            border-radius: 18rpx;
            background-color: #cccccc;
            align-items: center;
            justify-content: center;
            margin-left: 10rpx;
        }

        .clear-btn-text {
            color: #ffffff;
            font-size: 24rpx;
            font-weight: bold;
        }
    }

    .status-tabs {
        padding: 20rpx 30rpx;
        background-color: #ffffff;
        border-bottom: 1rpx solid #eeeeee;
    }

    .scroll-view_H {
        width: 100%;
        flex-direction: row;
    }

    .status-tab {
        padding: 16rpx 24rpx;
        text-align: center;
        margin-right: 16rpx;
        border-radius: 8rpx;
        background-color: #f5f5f5;
        flex-shrink: 0;

        &:last-child {
            margin-right: 0;
        }

        &.active {
            background-color: #007aff;
        }

        .status-tab-text {
            font-size: 26rpx;
            color: #666666;

            &.active-text {
                color: #ffffff;
                font-weight: bold;
            }
        }
    }

    .list-item {
        margin: 10rpx 10rpx;
        background-color: #ffffff;
        border-radius: 16rpx;
    }

    .item-container {
        padding: 30rpx;
    }

    .item-header {
        flex-direction: row;
        align-items: flex-start;
        justify-content: space-between;
        margin-bottom: 10rpx;
        width: 100%;

        .item-main-info {
            flex: 1;
            margin-right: 20rpx;
        }

        .item-name-row {
            flex-direction: row;
            align-items: center;
            margin-bottom: 8rpx;
        }

        .item-name {
            font-size: 28rpx;
            color: #333333;
            font-weight: bold;
        }

        .item-measure {
            font-size: 24rpx;
            color: #999999;
            margin-left: 10rpx;
        }

        .item-details {
            flex-direction: row;
            justify-content: space-between;
            width: 100%;
        }

        .item-code {
            font-size: 23rpx;
            color: #797979;
            flex: 1;
        }

        .item-warehouse {
            font-size: 23rpx;
            color: #797979;
            flex: 1;
            text-align: right;
        }

        .item-type {
            font-size: 24rpx;
            color: #007aff;
            background-color: #e6f7ff;
            padding: 8rpx 16rpx;
            border-radius: 8rpx;
            white-space: nowrap;
        }
    }
</style>
