<template>
	<uni-navbar-lite :showLeft=false title="消息"></uni-navbar-lite>
    <view class="list-page">
        <!-- 搜索栏 -->
        <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" @confirm="handleSearch" />
            </view>
        </view>

        <!-- 列表内容 -->
        <common-list 
            :dataList="dataList" 
            :loading="loading" 
            :refreshing="refreshing" 
            :hasMore="hasMore" 
            @refresh="handleRefresh" 
            @loadMore="loadMore" 
            @itemClick="handleItemClick"
        >
            <template #default="{ item, index }">
                <view class="list-item">
                    <view class="item-container">
                        <view class="item-header">
                            <image class="location-icon" src="/static/images/workbench/list/2.png" mode="aspectFit"></image>
                            <text class="item-title">{{ getContractorName(item) }}</text>
                            <text class="detail-link">详情 ›</text>
                        </view>
                        <text class="item-address">{{ getCompanyAddress(item) }}</text>
                        <view class="item-info">
                            <view class="info-row">
                                <view class="info-item">
                                    <text class="info-label">法定代表人</text>
                                    <text class="info-value">{{ getLegalRepresentative(item) }}</text>
                                </view>
                                <view class="info-item">
                                    <text class="info-label">资质等级</text>
                                    <text class="info-value">{{ getQualificationLevel(item) }}</text>
                                </view>
                            </view>
                            <view class="info-row">
                                <view class="info-item">
                                    <text class="info-label">联系电话</text>
                                    <text class="info-value">{{ getContactPhone(item) }}</text>
                                </view>
                                <view class="info-item">
                                    <text class="info-label">创建时间</text>
                                    <text class="info-value">{{ getCreateTime(item) }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </template>
        </common-list>
		<custom-tabbar :current="2" />
    </view>
</template>

<script setup lang="uts">
    import { ref, computed, onBeforeUnmount } from 'vue'
    import type { ContractorInfo, ContractorListResponse } from '../../types/workbench'
    import { getContractorList } from '../../api/workbench/list'

    // 列表数据
    const dataList = ref<ContractorInfo[]>([])
    const keyword = ref<string>("")
    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 total = ref<number>(0)

    // 辅助函数：从 any 类型提取属性
    const getContractorName = (item: any | null): string => {
        if (item == null) return ''
        const contractorItem = item as ContractorInfo
        return contractorItem.contractorName
    }

    const getCompanyAddress = (item: any | null): string => {
        if (item == null) return ''
        const contractorItem = item as ContractorInfo
        return contractorItem.companyAddress
    }

    const getLegalRepresentative = (item: any | null): string => {
        if (item == null) return ''
        const contractorItem = item as ContractorInfo
        return contractorItem.legalRepresentative
    }

    const getQualificationLevel = (item: any | null): string => {
        if (item == null) return ''
        const contractorItem = item as ContractorInfo
        return contractorItem.qualificationLevel
    }

    const getContactPhone = (item: any | null): string => {
        if (item == null) return ''
        const contractorItem = item as ContractorInfo
        return contractorItem.contactPhone
    }

    const getCreateTime = (item: any | null): string => {
        if (item == null) return ''
        const contractorItem = item as ContractorInfo
        return contractorItem.createTime
    }

    // 加载列表数据
    const loadData = async (isRefresh: boolean | null): Promise<void> => {
        if (loading.value) {
            // 如果正在加载，直接重置刷新状态
            refreshing.value = false
            return
        }

        try {
            loading.value = true

            // 处理默认值
            const shouldRefresh = isRefresh != null ? isRefresh : false

            if (shouldRefresh) {
                page.value = 1
            }

            // 调用 API
            const searchKeyword = keyword.value.length > 0 ? keyword.value : null
            const result = await getContractorList(page.value, pageSize, searchKeyword)

            // 提取响应数据
            const resultObj = result as UTSJSONObject
            const success = resultObj['success'] as boolean
            const responseData = resultObj['data'] as any[]
            const responseTotal = resultObj['total'] as number

            if (success) {
                // 将 any[] 转换为 ContractorInfo[]
                const newData: ContractorInfo[] = []
                for (let i = 0; i < responseData.length; i++) {
                    const item = responseData[i] as UTSJSONObject
                    const contractorItem: ContractorInfo = {
                        id: item['id'] as string,
                        createBy: item['createBy'] as string,
                        createTime: item['createTime'] as string,
                        updateBy: item['updateBy'] as string | null,
                        updateTime: item['updateTime'] as string | null,
                        isDeleted: item['isDeleted'] as number,
                        remark: item['remark'] as string,
                        creditCode: item['creditCode'] as string,
                        contractorName: item['contractorName'] as string,
                        companyAddress: item['companyAddress'] as string,
                        legalRepresentative: item['legalRepresentative'] as string,
                        contactPhone: item['contactPhone'] as string,
                        qualificationLevel: item['qualificationLevel'] as string,
                        qualificationCertNo: item['qualificationCertNo'] as string,
                        businessScope: item['businessScope'] as string,
                        bankName: item['bankName'] as string,
                        bankAccount: item['bankAccount'] as string
                    }
                    newData.push(contractorItem)
                }

                if (shouldRefresh) {
                    dataList.value = newData
                } else {
                    dataList.value = [...dataList.value, ...newData]
                }

                total.value = responseTotal
                hasMore.value = dataList.value.length < responseTotal
            } else {
                const msg = resultObj['msg'] as string | null
                uni.showToast({
                    title: msg ?? '加载失败',
                    icon: 'none'
                })
            }

        } catch (e: any) {
            uni.showToast({
                title: e.message ?? '加载失败',
                icon: 'none'
            })
        } finally {
            loading.value = false
            // #ifdef WEB
            // Web 平台立即重置
            refreshing.value = false
            // #endif
            // #ifndef WEB
            // App 平台延迟重置刷新状态，确保 UI 更新
            setTimeout(() => {
                refreshing.value = false
            }, 100)
            // #endif
        }
        
        // #ifdef WEB
        // Web 平台额外确保重置
        refreshing.value = false
        // #endif
    }

    // 下拉刷新
    const handleRefresh = async (): Promise<void> => {
        refreshing.value = true
        // await loadData(true as boolean | null)
        
    }

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

    // 搜索
    const handleSearch = (): void => {
        page.value = 1
        // loadData(true as boolean | null)
    }

    // 点击列表项
    const handleItemClick = (item: any | null, index: number): void => {
        if (item == null) return
        const contractorItem = item as ContractorInfo
        uni.navigateTo({
            url: `/pages/workbench/detail/index?id=${contractorItem.id}`
        })
    }

    // 组件卸载前清理
    onBeforeUnmount(() => {
        refreshing.value = false
        loading.value = false
    })

    // 初始化
    // loadData(true as boolean | null)
</script>

<style lang="scss">
    .list-page {
        flex: 1;
        background-color: #e8f0f9;
    }

    .search-bar {
        padding: 20rpx 30rpx;
        background-color: #d7eafe;
    }

    .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;
        }
    }

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

    .item-container {
        padding: 30rpx;
    }

    .item-header {
        flex-direction: row;
        align-items: center;
        margin-bottom: 16rpx;

        .location-icon {
            width: 32rpx;
            height: 32rpx;
            margin-right: 8rpx;
        }

        .item-title {
            flex: 1;
            font-size: 32rpx;
            color: #333333;
            font-weight: bold;
        }

        .detail-link {
            font-size: 28rpx;
            color: #999999;
        }
    }

    .item-address {
        font-size: 26rpx;
        color: #999999;
        margin-bottom: 20rpx;
        line-height: 40rpx;
    }

    .item-info {
        padding: 20rpx;
        background-color: #f8f9fa;
        border-radius: 8rpx;

        .info-row {
            flex-direction: row;
            margin-bottom: 16rpx;

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

            .info-item {
                flex: 1;
                flex-direction: row;
                align-items: center;

                .info-label {
                    font-size: 26rpx;
                    color: #666666;
                    margin-right: 8rpx;
                    white-space: nowrap;
                }

                .info-value {
                    flex: 1;
                    font-size: 26rpx;
                    color: #333333;
                }
            }
        }
    }
</style>
