<template>
    <view>
        <u-form-item label="库存批次" :prop="'detailInfos[' + rowIndex + '].goodsName'" :required="true">
            <u--input :value="currentValue" placeholder="请选择报损库存批次" readonly :disabled="disabled"
                @focus="openPicker"></u--input>
        </u-form-item>

        <view class="selector-mask" :class="{ show: visible }" @tap="closePicker"></view>
        <view class="selector-panel" :class="{ show: visible }">
            <view class="selector-header">
                <view class="selector-action" @tap="closePicker">取消</view>
                <view class="selector-title">选择库存批次</view>
                <view class="selector-action selector-action-placeholder">取消</view>
            </view>
            <view class="selector-search">
                <u-search :show-action="false" v-model="keyword" placeholder="搜索商品名称"></u-search>
            </view>
            <scroll-view scroll-y class="selector-list">
                <view v-if="loading" class="selector-state">加载中...</view>
                <view v-else-if="filteredList.length === 0" class="selector-state">暂无可选批次</view>
                <view v-else class="selector-list-inner">
                    <view class="selector-card" v-for="item in filteredList" :key="item.id || item.tradeName + item.produceDate"
                        @tap="selectItem(item)">
                        <view class="selector-name">{{ item.tradeName || '-' }}</view>
                        <view class="selector-meta">
                            <text>入库批次：{{ item.wareHouseNumber || '-' }}</text>
                            <text>入库日期：{{ formatDisplayDate(item.wareHouseDate) || '-' }}</text>
                        </view>
                        <view class="selector-meta">
                            <text>库存：{{ item.stockBottleCount || '0' }}</text>
                            <text v-if="item.company">单位：{{ item.company }}</text>
                        </view>
                        <view class="selector-meta">
                            <text>品牌：{{ item.brand || '-' }}</text>
                            <text>规格：{{ item.specification || '-' }}</text>
                        </view>
                    </view>
                </view>
            </scroll-view>
        </view>
    </view>
</template>

<script>
import WareHouseService from '@/api/psi/WareHouseService'

export default {
    name: 'LossGoodsSelector',
    props: {
        rowIndex: Number,
        inputForm: Object,
        disabled: Boolean
    },
    data() {
        return {
            visible: false,
            loading: false,
            keyword: '',
            goodsList: [],
            wareHouseService: null
        }
    },
    computed: {
        currentRow() {
            return (this.inputForm.detailInfos || [])[this.rowIndex] || {}
        },
        currentValue() {
            return this.currentRow.goodsName || ''
        },
        filteredList() {
            const keyword = (this.keyword || '').trim().toLowerCase()
            if (!keyword) {
                return this.goodsList
            }
            return this.goodsList.filter(item => (item.tradeName || '').toLowerCase().includes(keyword))
        }
    },
    created() {
        this.wareHouseService = new WareHouseService()
    },
    methods: {
        isEmpty(value) {
            if (value === null || value === undefined) {
                return true
            }
            if (typeof value === 'string' && value.trim() === '') {
                return true
            }
            if (Array.isArray(value) && value.length === 0) {
                return true
            }
            return false
        },
        formatDisplayDate(date) {
            if (this.isEmpty(date)) {
                return ''
            }
            const dateValue = new Date(date)
            if (Number.isNaN(dateValue.getTime())) {
                return ''
            }
            const year = dateValue.getFullYear()
            const month = `${dateValue.getMonth() + 1}`.padStart(2, '0')
            const day = `${dateValue.getDate()}`.padStart(2, '0')
            return `${year}-${month}-${day}`
        },
        formatNumber(value) {
            const numberValue = Number(value || 0)
            if (Number.isNaN(numberValue)) {
                return '0'
            }
            return numberValue % 1 === 0 ? String(numberValue) : numberValue.toFixed(2).replace(/\.?0+$/, '')
        },
        getStockBottleCount(item) {
            const currentInventory = Number(item.currentInventory || 0)
            const spec = Number(item.spec || 1)
            return this.formatNumber(currentInventory * (spec > 0 ? spec : 1))
        },
        async openPicker() {
            if (this.disabled) {
                return
            }
            this.visible = true
            this.keyword = ''
            await this.loadGoodsList()
        },
        closePicker() {
            this.visible = false
        },
        async loadGoodsList() {
            this.loading = true
            try {
                const data = await this.wareHouseService.getByProduceDateNotMerge({
                    current: 1,
                    size: 1000
                })
                const records = (data && data.records) || []
                this.goodsList = records.filter(item => Number(item.currentInventory || 0) > 0).map(item => ({
                    ...item,
                    stockBottleCount: this.getStockBottleCount(item)
                }))
            } catch (e) {
                this.goodsList = []
                uni.showToast({
                    title: '物品数据加载失败',
                    icon: 'none'
                })
            } finally {
                this.loading = false
            }
        },
        selectItem(item) {
            this.$emit('selected', {
                index: this.rowIndex,
                item
            })
            this.closePicker()
        }
    }
}
</script>

<style scoped>
.selector-mask {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.35);
    opacity: 0;
    visibility: hidden;
    transition: all 0.25s ease;
    z-index: 1000;
}

.selector-mask.show {
    opacity: 1;
    visibility: visible;
}

.selector-panel {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 70vh;
    background: #f7f9fc;
    border-radius: 28rpx 28rpx 0 0;
    transform: translateY(100%);
    transition: transform 0.25s ease;
    z-index: 1001;
    display: flex;
    flex-direction: column;
}

.selector-panel.show {
    transform: translateY(0);
}

.selector-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 28rpx 32rpx 16rpx;
    background: #fff;
    border-bottom: 1rpx solid #eef2f7;
}

.selector-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #1f2937;
}

.selector-action {
    min-width: 80rpx;
    font-size: 28rpx;
    color: #2979ff;
}

.selector-action-placeholder {
    opacity: 0;
}

.selector-search {
    padding: 20rpx 24rpx 8rpx;
    background: #fff;
}

.selector-list {
    flex: 1;
    padding: 16rpx 24rpx 32rpx;
}

.selector-list-inner {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
}

.selector-state {
    padding-top: 120rpx;
    text-align: center;
    font-size: 28rpx;
    color: #94a3b8;
}

.selector-card {
    background: #fff;
    border-radius: 20rpx;
    padding: 24rpx;
    box-shadow: 0 8rpx 24rpx rgba(15, 23, 42, 0.06);
}

.selector-name {
    font-size: 30rpx;
    font-weight: 600;
    color: #0f172a;
}

.selector-meta {
    display: flex;
    justify-content: space-between;
    gap: 16rpx;
    margin-top: 10rpx;
    font-size: 24rpx;
    color: #64748b;
}
</style>
