<template>
    <view v-for="(data, index) in datasModel" :key="index" class="bg-#FBFDFB border-#AFDDBB pd-24 b-radius mb-10">
        <view v-if="showClose" class="c-#F81242 f-s-36 ab2-10-10 pl-20 pr-10" style="position: absolute; right: 10rpx; top: 0rpx" @click="() => handleClose(index)"> × </view>
        <view class="d-flex a-c pb-10">
            <view class="c-primary pd-4 bg-#E7F4EA radius-10" style="font-style: italic">{{ index + 1 < 10 ? '0' + (index + 1) : index + 1 }}</view>
            <view class="c-#333 f-s-34 f-w-5 ml-10">{{ data?.materialName }}</view>
        </view>
        <view class="pt-6 pb-6 d-flex a-c">
            <view class="c-#666 f-s-28"> 入库批次号：</view>
            <view class="c-#333 f-s-28 f-w-5">{{ data?.batchCode }}</view>
        </view>
        <view class="pt-6 pb-6 d-flex a-c">
            <view class="c-#666 f-s-28"> 供应商：</view>
            <view class="c-#333 f-s-28 f-w-5">{{ data?.supplier }}</view>
        </view>
        <view class="pt-6 pb-6 d-flex a-c">
            <view class="c-#666 f-s-28 w-s-no"> 所在库房：</view>
            <view class="c-#333 f-s-28 f-w-5">{{ data?.warehouses }}</view>
        </view>
        <view class="pt-6 pb-6 d-flex mb-12" v-if="showClose">
            <view class="w-50% d-flex a-c">
                <view class="c-#666 f-s-28"> 入库量：</view>
                <view class="c-#333 f-s-28 f-w-5">{{ data?.capacity }}{{ data?.unit }}</view>
            </view>
            <view class="w-50% d-flex a-c">
                <view class="c-#666 f-s-28"> 剩余量：</view>
                <view class="c-primary f-s-28 f-w-5">{{ data?.restAmount }}{{ data?.unit }}</view>
            </view>
        </view>
        <view v-if="!showClose" class="pt-6 pb-6 d-flex a-c">
            <view class="c-#666 f-s-28 w-s-no">本次使用量：</view>
            <view class="c-#333 f-s-28 f-w-5">{{ data?.quantity }}{{ data?.unit }}</view>
        </view>
        <up-line v-if="showClose" color="#AFDDBB" style="margin-left: -24rpx; margin-right: -24rpx; width: auto"></up-line>
        <view v-if="showClose" class="f-s-28 c-#666 pt-16">本次使用量：</view>
        <view v-if="showClose" class="pt-6 pb-6 d-flex a-c">
            <view class="flex1 mr-10">
                <up-input v-model="inputsModel[index].inputAmount" placeholder="请输入本次使用量" border="bottom" style="padding-left: 0" type="number" :error="hasError(index)" :errorMessage="getErrorMessage(index)">
                    <template #suffix>
                        <view class="c-#333 f-s-28 f-w-5">{{ data?.unit }}</view>
                    </template>
                </up-input>
            </view>
            <view class="">
                <up-checkbox label="全部使用" usedAlone v-model:checked="useAllFlags[index]" @change="handleUseAllChange(index)"></up-checkbox>
            </view>
        </view>
    </view>
</template>
<script setup lang="ts">
import { ref, watch, computed } from 'vue';
// 从外部获取数据
const props = defineProps<{
    showClose?: boolean;
}>();

// 双向绑定
const datasModel = defineModel<any[]>('datas', { default: () => [] });
const inputsModel = defineModel<any[]>('inputs', { default: () => [] });
setTimeout(() => {
    console.log(inputsModel.value, 'inputsModel');
    console.log(datasModel.value, 'datasModel');
}, 2000);
// 用于跟踪"全部使用"复选框的状态
const useAllFlags = ref<boolean[]>([]);

// 初始化 inputsModel 数据结构
const initInputsModel = () => {
    if (!datasModel.value || datasModel.value.length === 0) {
        inputsModel.value = [];
        useAllFlags.value = [];
        return;
    }
    // 确保 inputsModel 与 datasModel 长度一致
    const newInputs = [...inputsModel.value];
    const newUseAllFlags = [...useAllFlags.value];

    datasModel.value.forEach((data, index) => {
        if (!newInputs[index] || newInputs[index].id !== data.id) {
            newInputs[index] = {
                id: data.id,
                inputAmount: '',
            };
        }
        if (newUseAllFlags[index] === undefined) {
            newUseAllFlags[index] = false;
        }
    });
    1;
    // 移除多余的元素
    if (newInputs.length > datasModel.value.length) {
        newInputs.splice(datasModel.value.length);
        newUseAllFlags.splice(datasModel.value.length);
    }

    inputsModel.value = newInputs;
    useAllFlags.value = newUseAllFlags;
};

// 监听 datasModel 变化，初始化 inputsModel
watch(
    () => datasModel.value,
    () => {
        initInputsModel();
    },
    { immediate: true, deep: true },
);
watch(
    () =>
        inputsModel.value.map((item, idx) => ({
            amount: item.inputAmount,
            index: idx,
            rest: datasModel.value[idx]?.restAmount,
        })),
    (newItems) => {
        newItems.forEach(({ amount, index, rest }) => {
            const numAmount = Number(amount) || 0;
            if (numAmount >= rest) {
                inputsModel.value[index].inputAmount = rest;
                useAllFlags.value[index] = true;
            } else {
                useAllFlags.value[index] = false;
            }
        });
    },
    { deep: true, flush: 'post' },
);
// 处理"全部使用"复选框变化
const handleUseAllChange = (index: number) => {
    console.log(useAllFlags.value[index], datasModel.value[index]);

    if (!useAllFlags.value[index] && datasModel.value[index]) {
        inputsModel.value[index].inputAmount = datasModel.value[index].restAmount;
    } else if (useAllFlags.value[index]) {
        inputsModel.value[index].inputAmount = '';
    }
};

// // 验证输入量
// const validateInputAmount = async (index: number) => {
//     const inputAmount = inputsModel.value[index]?.inputAmount || 0;
//     const restAmount = datasModel.value[index]?.restAmount || 0;

//     if (inputAmount > restAmount) {
//         // 如果超过剩余量，自动调整为剩余量
//         inputsModel.value[index].inputAmount = '';
//         await nextTick();
//         inputsModel.value[index].inputAmount = restAmount;
//         useAllFlags.value[index] = true;
//     }
// };

// 检查是否有错误
const hasError = (index: number): boolean => {
    const inputAmount = inputsModel.value[index]?.inputAmount || 0;
    const restAmount = datasModel.value[index]?.restAmount || 0;
    return inputAmount > restAmount;
};

// 获取错误信息
const getErrorMessage = (index: number): string => {
    const inputAmount = inputsModel.value[index]?.inputAmount || 0;
    const restAmount = datasModel.value[index]?.restAmount || 0;
    if (inputAmount > restAmount) {
        return `使用量不能超过剩余量 ${restAmount}`;
    }
    return '';
};

// 处理关闭物料
const handleClose = (index: number) => {
    datasModel.value.splice(index, 1);
    inputsModel.value.splice(index, 1);
    useAllFlags.value.splice(index, 1);
};
</script>
