<template>
    <uni-forms ref="formRef" :model="formData" :rules="rules" label-width="100px" label-position="top">
        <uni-forms-item label="合同号" name="cusName" class="f-c-right">
            <view @click="chooseCustomer" class="form-item-container">
                <text class="name">{{ formData.customerCode || '点击选择合同数据' }}</text>
            </view>
        </uni-forms-item>	
        <uni-forms-item label="合同号" name="customerCode" class="f-c-right">
            <uni-easyinput v-model="formData.customerCode" placeholder="请输入合同号" name="input" :disabled="isDisabled"/>
        </uni-forms-item>
        
        <uni-forms-item label="批号" name="batchNumber" class="f-c-right">
            <uni-easyinput v-model="formData.batchNumber" placeholder="请输入批号" name="input" :disabled="isDisabled" @input="handleBatchNumberChange"/>
        </uni-forms-item>
        
        <uni-forms-item label="供货数量" name="supplyQuantity" class="f-c-right">
            <uni-easyinput v-model="formData.supplyQuantity" type="text" placeholder="请输入供货数量" name="input" :disabled="isDisabled"/>
        </uni-forms-item>
        
        <uni-forms-item label="产品规格型号" name="specificationModel" class="f-c-right">
            <uni-easyinput v-model="formData.specificationModel" placeholder="请输入产品规格型号" name="input" :disabled="isDisabled"/>
        </uni-forms-item>
        
        <uni-forms-item label="母批号" name="motherBatch" class="f-c-right">
            <uni-easyinput v-model="formData.motherBatch" placeholder="请输入母批号" name="input" :disabled="isDisabled"/>
        </uni-forms-item>
        
        <uni-forms-item label="产品ID" name="materialId" class="f-c-right">
            <uni-easyinput v-model="formData.materialId" placeholder="请输入产品ID" name="input" :disabled="isDisabled"/>
        </uni-forms-item>
    </uni-forms>
    <view class="footer-con">
        <button class="btn-default" type="default" @click="handleDeleteDetailItem" size="mini" v-if="false">删除</button>
        <button class="btn-primary" type="primary" @click="submitForm" size="mini">保存</button>
    </view>
</template>

<script setup name="qualityFeedbackDetailComponent">
import { ref, reactive } from 'vue'
import cache from '../../../../utils/cache'
import { onShow,onLoad, onUnload } from '@dcloudio/uni-app';
import {
		getMockBatchData,
        qualityFeedbackDetailAdd
	} from '@/api/eqf/qualityFeedback.js'

let isDisabled = ref(false)
const props = defineProps({
    cusName: String, //客户单位名称
    cusId: Number, //客户ID
    feedbackId: Number, //质量反馈ID
    status: String //状态
})

// 表单数据
const formData = ref({
    customerCode: '',
    batchNumber: '',
    supplyQuantity: '',
    specificationModel: '',
    motherBatch: '',
    materialId: '',
    eqfId: '',
});

// 验证规则
const rules = {
    contractNumber: {
        rules: [
            { required: true, errorMessage: '请输入合同号' }
        ]
    },
    batchNumber: {
        rules: [
            { required: true, errorMessage: '请输入批号' }
        ]
    },
    supplyQuantity: {
        rules: [
            { required: true, errorMessage: '请输入供货数量' },
            { type: 'number', errorMessage: '请输入数字' }
        ]
    },
    specificationModel: {
        rules: [
            { required: true, errorMessage: '请输入产品规格型号' }
        ]
    }
};

// 表单ref
const formRef = ref(null);


onLoad((options) => {
    //清空表单
    clearForm()
    // 然后设置eqfId
    if (options && options.id) {
        formData.value.eqfId = options.id;
    }
    // 清除相关缓存，确保首次加载时没有旧数据干扰
    cache.remove(`qualityFeedbackDetail_${options?.id || ''}`);
})

//获取当前外反的明细
const detailList = ref([])
const getQualityFeedbackDetail = async () => {
    let param = {
        eqfId: formData.value.eqfId
    }
    let detailRes = await qualityFeedbackDetailAdd(param);
    detailList.value = detailRes.rows[0];
}

//删除明细项的内容
function handleDeleteDetailItem() {
    // 使用本地存储或其他方式暂存删除操作
    uni.showToast({
        title: '删除成功',
        duration: 2000
    });
    //清空表单
    clearForm()
}

// 清空表单
function clearForm() {
    formData.value.customerCode = ''
    formData.value.batchNumber = ''
    formData.value.supplyQuantity = ''
    formData.value.specificationModel = ''
    formData.value.motherBatch = ''
    formData.value.materialId = ''
}

// 选择合同页面跳转
function chooseCustomer() {
    uni.navigateTo({
        url: '/pages/business/EQF/components/customerOrder'
    })
}

// 提交表单
const submitForm = async () => {
    try {
        // 表单校验
        await formRef.value.validate()
        console.log(formData,"5555")
        const res = await qualityFeedbackDetailAdd(formData.value);
        uni.showToast({
            title: '提交成功',
            icon: 'success'
        })
            // 发送刷新列表事件，同时支持两种事件名称以兼容现有代码
            uni.$emit('refreshMarketList');
            uni.$emit('refreshFeedbackList');
            setTimeout(() => {
                uni.navigateBack(1);
                }, 1500);
                
        console.log('表单数据:', formData.value)
    } catch (err) {
        console.log('表单验证失败:', err)
    }
}


//页面渲染完成后，查询详情
onShow(() => {
    // Try to load from cache if available
    const cachedData = cache.get(`qualityFeedbackDetail_${props.feedbackId}`);
    if (cachedData) {
        formData.value = {
            ...formData.value,
            ...cachedData
        };
    }
    
    if (props.status == '完成') {
        isDisabled.value = true
    } else {
        isDisabled.value = false
    }
    
    // 监听客户订单选择事件
    uni.$on('onCustomerSelected', handleCustomerSelected);
});

// 处理客户订单选择结果
function handleCustomerSelected(data) {
    // 确保数据存在
    if (!data || typeof data !== 'object') {
        console.error('无效的数据:', data);
        return;
    }
    
    // 如果返回的是对象
    let selectedItems = [];
    
    console.log('接收到的数据:', data);
    
    // 兼容新格式
    selectedItems = data.originalData || [];
    
    if (selectedItems && selectedItems.length > 0) {
        // 清空表单
        clearForm();
        
        console.log('选中的项目数量:', selectedItems.length);
        console.log('选中的项目详情:', selectedItems);
        
        // 循环拼接所有选中项目的字段
        const customerCodes = selectedItems.map(item => item.orderCoode || '').filter(Boolean);
        const supplyQuantities = selectedItems.map(item => item.amount || '').filter(Boolean);
        const specificationModels = selectedItems.map(item => item.name || '').filter(Boolean);
        const motherBatches = selectedItems.map(item => item.texing || '').filter(Boolean);
        const materialIds = selectedItems.map(item => item.materialId || '').filter(Boolean);
        const batchNumbers = selectedItems.map(item => item.tokenCode || '').filter(Boolean);

        console.log('拼接前的合同号:', customerCodes);
        
        // 使用nextTick确保DOM更新
        setTimeout(() => {
            formData.value.customerCode = customerCodes.join(',');
            formData.value.supplyQuantity = supplyQuantities.join(',');
            formData.value.specificationModel = specificationModels.join(',');
            formData.value.motherBatch = motherBatches.join(',');
            formData.value.materialId = materialIds.join(',');
            formData.value.batchNumber = batchNumbers.join(',');
            
            console.log('设置后的表单数据:', formData.value);
        }, 0);
        
        // 显示提示信息
        uni.showToast({
            title: `已选择${selectedItems.length}个批次`,
            icon: 'none',
            duration: 2000
        });
        
        // 保存到缓存
        cache.set(`qualityFeedbackDetail_${props.feedbackId || ''}`, formData.value);
    }
};

// 页面卸载时移除事件监听
onUnload(() => {
    uni.$off('onCustomerSelected', handleCustomerSelected);
});

// 处理批号变化，自动查询数据
const handleBatchNumberChange = async (value) => {
    const trimmedValue = value?.trim() || '';
    // 防止空值查询
    if (!trimmedValue) {
        console.log('批号为空，不执行查询');
        return;
    }
    
    try {
        // 显示加载提示
        uni.showLoading({
            title: '查询中...',
        });
        const  param = { batchNumber: value };
        console.log('查询参数:', param);
        // 尝试从缓存获取数据，减少重复请求
        const cacheKey = `batchInfo_${trimmedValue}`;
        let batchInfo = cache.get(cacheKey);
        console.log('缓存数据:', batchInfo);

        if (1==1) {
            // 调用API获取数据
            console.log('准备调用API...');
			let apiData 
            try {
                const res = await getMockBatchData(param);
                console.log('API响应原始数据:', res);
				// 根据isTransformResponse=false的设置，正确处理响应数据
				// 修复4: 处理可能的嵌套数据结构
				apiData = res;
				// 检查是否有data字段，适应不同的响应结构
				if (res.data !== undefined) {
				    apiData = res.data;
				}
            } catch (apiError) {
                console.error('API调用直接失败:', apiError);
                // 重新抛出错误，让外层catch处理
                throw new Error(`API调用失败: ${apiError?.message || '未知错误'}`);
            }

            console.log('处理后的数据:', apiData);
            
            if (typeof apiData === 'object' && apiData !== null) {
                // 提取并格式化有用的数据
                batchInfo = {
                    supplyQuantity: apiData.supplyQuantity || '',
                    specificationModel: apiData.specificationModel || '',
                    motherBatch: apiData.motherBatch || '',
                    materialId: apiData.materialId || '',
                    batchNumber: trimmedValue // 确保不会覆盖用户已输入的批号
                };
                
                // 保存到缓存，过期时间设置为1小时
                cache.set(cacheKey, batchInfo, 3600000);
                
                // 安全更新表单数据，避免覆盖整个formData对象
                formData.value.batchNumber = trimmedValue;
                formData.value.supplyQuantity = apiData.rows[0].amount || '';
                formData.value.specificationModel = apiData.rows[0].itemName || '';
                formData.value.motherBatch = apiData.rows[0].texing || '';
                formData.value.materialId = apiData.rows[0].materialId || '';
                formData.value.customerCode = apiData.rows[0].orderCode || '';

                console.log('apiData:', apiData.rows[0]);
                console.log('更新后的formData:', formData.value);
                
                // 显示查询成功提示
                uni.showToast({
                    title: '查询成功',
                    duration: 2000
                });
            } else {
                // 没有数据时的处理
                console.log('未查询到相关数据');
                uni.showToast({
                    title: '未查询到相关数据',
                    icon: 'none',
                    duration: 2000
                });
            }
        } else {
            // 使用缓存数据更新表单
            formData.value = {
                ...formData.value,
                ...batchInfo,
                // 确保不会覆盖用户正在输入的批号
                batchNumber: trimmedValue
            };
        }
    } catch (error) {
        console.error('查询批号数据失败:', error);
        uni.showToast({
            title: '查询失败，请重试',
            icon: 'none',
            duration: 2000
        });
    } finally {
        // 隐藏加载提示
        uni.hideLoading();
    }
};


// 明确暴露给父组件的方法
defineExpose({
    clearForm
})
</script>

<style scoped>
.footer-con {
    display: flex;
    justify-content: flex-end;
    padding: 20rpx;
    gap: 20rpx;
}

.btn-default {
    background-color: #f0f0f0;
    color: #333;
}

.btn-primary {
    background-color: #6FA2F8;
    color: #fff;
}
</style>