<template>
    <up-popup :show="modelValue" mode="right" @close="handleClose" @open="handleOpen">
        <up-navbar :fixed="false" bgColor="transparent">
            <template #left>
                <view class="c-#333 f-s-34 f-w-5">请选择放置的具体位置</view>
            </template>
        </up-navbar>
        <view class="w-700 d-flex flex-cln" id="scroll">
            <view class="d-flex">
                <scroll-view class="w-50% bg-#f7f7f7 c-#fff" :style="`height: calc(100vh - 70px - ${top}px)`" scroll-y="true">
                    <view v-for="(item, index) in list" :key="index" class="border-#E6E6E6 pd-20 title" :class="{ activeTitle: activeBase == index }" @click="changeBase(index, item)">
                        <view class="">
                            <view class="base mb-20">{{ item?.landName }}</view>
                            <view class="area">
                                <text class="mr-10">{{ item?.layers }}层</text>
                                <text>每层{{ item?.capacityAmount }}{{ item?.capacityUnit }}</text>
                            </view>
                        </view>
                    </view>
                </scroll-view>
                <up-virtual-list v-if="mixData.length > 0" :listData="mixData" :itemHeight="60" :height="600" :buffer="8" class="mt-10">
                    <template #default="{ item }">
                        <view class="custom-checkbox" :class="{ 'custom-checkbox--checked': item.selected }" @click="handleCustomCheckboxClick(item.id)">
                            <view class="custom-checkbox__inner">
                                <text v-if="item.selected" class="custom-checkbox__icon">✓</text>
                                <text class="custom-checkbox__label">{{ item.landName }}</text>
                            </view>
                        </view>
                    </template>
                </up-virtual-list>
                <!-- <scroll-view class="w-50% pd-16" :style="`height: calc(100vh - 70px - ${top}px)`" scroll-y="true">
                    <view v-if="mixData.length > 0" class="custom-checkbox custom-checkbox--all" @click="handleAllCheckboxChange(!aloneChecked)">
                        <view class="custom-checkbox__inner">
                            <text v-if="aloneChecked" class="custom-checkbox__icon">✓</text>
                            <text class="custom-checkbox__label">全选</text>
                        </view>
                    </view>
                    <view v-if="mixData.length == 0 && showtitle" class="">请先在左侧添加选择组培架，选择后此处将会展示具体信息。</view>
                </scroll-view> -->
            </view>
            <view class="w-700 bg-#fff h-100 d-flex a-c gap-20 pt-20 pb-20" style="position: fixed; bottom: 0; right: 0">
                <up-button @click="handleClose" style="margin-left: 20rpx">取消</up-button>
                <up-button type="primary" @click="confirm" style="margin-right: 20rpx">确定</up-button>
            </view>
        </view>
    </up-popup>
</template>
<script setup lang="ts">
import { useClientRequest } from '@/utils/request';
import { ref, reactive, watch, computed } from 'vue';
const instance = getCurrentInstance();
const props = defineProps<{
    modelValue: boolean;
    baseId?: string | null;
    landIds?: Array<string | null>;
}>();
setTimeout(() => {
    console.log(props?.baseId);
}, 2000);
const form = ref({
    baseId: props.baseId,
    landIds: props.landIds || [],
});
// 左侧地块列表数据
const list = ref<any[]>([]);
// 右侧架子数据
const mixData = ref<any[]>([]);
const showtitle = ref(true);
// 当前选择地块
const landId = ref(-1);
// 定义emit事件：通知父组件状态变化
const emit = defineEmits<{
    (e: 'update:modelValue', value: boolean): void;
    (e: 'open'): void;
    (e: 'close'): void;
    (e: 'confirm', data: { medicineName: string; swyqMedicineName: string; checkBox: any[]; data: any[]; aloneChecked: boolean; baseName: string; area?: string; gapFlag: number; swyqRes: number; areaUnit: string; adcodeName: string; address: string }): void; // 新增
}>();
// 处理关闭事件
function handleClose() {
    emit('update:modelValue', false);
    emit('close');
}
// 处理打开事件
function handleOpen() {
    emit('open');
}
// 切换基地>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const activeBase = ref(-1);
const changeBase = (index: number, item: any) => {
    if (activeBase.value == index) return;
    activeBase.value = index;
    //创建右侧的架数据
    mixData.value = [];
    const layersCount = Number(item.layers);
    // 解析 capacityAmount 为数字
    const capacityCount = Number(item.capacityAmount);

    // 创建两个序列数组
    const layersArray = Array.from(
        { length: layersCount || 0 },
        (_, index) => index + 1 // 生成 1-10
    );

    const capacityArray = Array.from(
        { length: capacityCount || 0 },
        (_, index) => index + 1 // 生成 1-capacityCount
    );
    // 双重循环使用 flatMap
    const newData = layersArray.flatMap((layer) =>
        capacityArray.map((capacity) => ({
            id: `${layer}-${capacity}`,
            landName: `${layer}-${capacity}`,
            selected: false, // 添加 selected 字段，初始为 false
        }))
    );
    mixData.value = newData;
    setTimeout(() => {
        console.log(mixData.value);
    }, 2000);

    landId.value = item.id;
    aloneChecked.value = false;
};
// 选择checkbox>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const aloneChecked = ref(false);

// 自定义复选框点击事件处理
const handleCustomCheckboxClick = (id: string) => {
    const item = mixData.value.find((item) => item.id === id);
    if (item) {
        item.selected = !item.selected;
        updateAllCheckedState();
    }
};

// 全选框change事件处理
const handleAllCheckboxChange = (value: boolean) => {
    aloneChecked.value = value;
    mixData.value.forEach((item) => {
        item.selected = value;
    });
};

// 更新全选框状态
const updateAllCheckedState = () => {
    const allSelected = mixData.value.every((item) => item.selected);
    aloneChecked.value = allSelected;
};
const top = ref(0);
// 虚拟列表高度
const virtualListHeight = ref(0);
// 获取地块信息
const getBaseInfo = async (pageNum: number, pageSize: number) => {
    const params = {
        pageNum,
        pageSize,
        ...form.value,
    };
    const res = await useClientRequest.post('/plt-api/app/baseLandInfo/chooseLandPageList', params);
    if (res) {
        const { data } = res;
        list.value = data;
    }
};
// 提交
const confirm = () => {
    if (landId.value == -1) {
        uni.showToast({
            title: '请选择基地',
            icon: 'none',
        });
        return;
    } else {
        // 检查是否有选中的项
        const selectedItems = mixData.value.filter((item) => item.selected);
        if (selectedItems.length == 0) {
            uni.showToast({
                title: '请选择地块',
                icon: 'none',
            });
            return;
        }
    }

    // 通过 landId 查找选中的地块
    const selectedBase = list.value.find((item) => item.id === landId.value);
    // 获取选中的数据项
    const selectedData = mixData.value.filter((item) => item.selected);
    // 获取选中的ID数组
    const selectedIds = selectedData.map((item) => item.id);

    if (selectedBase) {
        // 抛出对象给父组件
        emit('confirm', {
            baseName: selectedBase.baseName,
            area: selectedBase.gapInfo?.area,
            areaUnit: selectedBase.gapInfo?.areaUnit,
            adcodeName: selectedBase.gapInfo?.adcodeName,
            address: selectedBase.gapInfo?.address,
            aloneChecked: aloneChecked.value,
            gapFlag: selectedBase.gapFlag,
            swyqRes: selectedBase.swyqRes,
            swyqMedicineName: selectedBase.swyqMedicineName,
            medicineName: selectedBase.gapInfo?.medicineName,
            data: selectedData,
            checkBox: selectedIds,
        });
    }

    // 关闭抽屉
    emit('update:modelValue', false);
    emit('close');
};

onMounted(() => {
    const querys = uni.createSelectorQuery().in(instance?.proxy);
    querys
        .select('#scroll')
        .boundingClientRect((data: any) => {
            top.value = data.top;

            // 获取屏幕高度并计算固定高度
            const systemInfo = uni.getSystemInfoSync();
            const screenHeight = systemInfo.windowHeight;
            const calculatedHeight = screenHeight - 70 - data.top - 60;
            virtualListHeight.value = Math.max(calculatedHeight, 100); // 确保最小高度为100px
        })
        .exec();
    getBaseInfo(1, 100);
});
</script>
<style scoped lang="scss">
:deep(.u-border-bottom) {
    border-color: transparent !important;
}
.title {
    .base {
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        margin-right: 20rpx;
        word-break: break-all;
    }
    .area {
        font-size: 24rpx;
        color: #999;
    }
    .label {
        font-size: 24rpx;
        color: #37a954;
        border-radius: 100rpx;
        background-color: #e3efe6;
        width: max-content;
        padding-left: 14rpx;
        padding-right: 14rpx;
        padding-top: 6rpx;
        padding-bottom: 6rpx;
    }
}
.activeTitle {
    background-color: #37a954;
    .base {
        font-size: 28rpx;
        color: #fff;
        font-weight: 500;
        margin-right: 20rpx;
    }
    .area {
        font-size: 24rpx;
        color: #ebf6ee;
    }
    .label {
        font-size: 24rpx;
        color: #fff;
        border-radius: 100rpx;
        background-color: #5fba76;
        width: max-content;
        padding-left: 14rpx;
        padding-right: 14rpx;
        padding-top: 6rpx;
        padding-bottom: 6rpx;
    }
}
:deep(.u-checkbox-label--left) {
    flex-direction: row-reverse !important;
}
:deep(.u-checkbox__icon-wrap) {
    margin-right: 0 !important;
    margin-left: 10px;
}

/* 自定义复选框样式 */
.custom-checkbox {
    display: flex;
    align-items: center;
    padding: 16rpx 20rpx;
    margin-bottom: 10rpx;
    border: 2rpx solid #dcdfe6;
    border-radius: 8rpx;
    background-color: #fff;
    transition: all 0.3s ease;
    cursor: pointer;
}

.custom-checkbox:hover {
    border-color: #37a954;
}

.custom-checkbox--checked {
    border-color: #37a954;
    background-color: #f0f9f4;
}

.custom-checkbox--all {
    margin-bottom: 20rpx;
    border-color: #37a954;
    background-color: #f0f9f4;
    font-weight: 500;
}

.custom-checkbox__inner {
    display: flex;
    align-items: center;
    width: 100%;
}

.custom-checkbox__icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 32rpx;
    height: 32rpx;
    margin-right: 16rpx;
    border-radius: 4rpx;
    background-color: #37a954;
    color: #fff;
    font-size: 24rpx;
    font-weight: bold;
}

.custom-checkbox__label {
    font-size: 28rpx;
    color: #333;
    flex: 1;
}

.custom-checkbox--checked .custom-checkbox__label {
    color: #37a954;
    font-weight: 500;
}

.custom-checkbox--all .custom-checkbox__label {
    color: #37a954;
    font-weight: 600;
}
</style>
