<template>
    <up-popup :show="modelValue" mode="right" @close="handleClose" @open="handleOpen">
        <ut-navbar :fixed="false" bgColor="transparent" :breadcrumb="false">
            <template #left>
                <view class="c-#333 f-s-34 f-w-5">请选择采收所在基地</view>
            </template>
        </ut-navbar>
        <view class="h-86 pd-20 pt-0">
            <ut-search ref="searchRef" v-model="form.keyword" @search="changeSeach" margin="0" :border="false" placeholder="搜基地名称、编号、地址、负责人" bgColor="#f7f7f7" height="86rpx" borderRadius="16rpx"></ut-search>
        </view>
        <view class="d-flex pl-20 mb-20">
            <view class="f-s-26 w-90 h-54 radius-100 bg-#f7f7f7 d-flex a-c j-c mr-20 c-#333" @click="changeSelect(0)" :style="{ backgroundColor: activeSelect == 0 ? '#37A954' : '', color: activeSelect == 0 ? '#FFF' : '' }">全部</view>
            <view class="f-s-26 w-150 h-54 radius-100 bg-#f7f7f7 d-flex a-c j-c mr-20 c-#333" @click="changeSelect(1)" :style="{ backgroundColor: activeSelect == 1 ? '#37A954' : '', color: activeSelect == 1 ? '#FFF' : '' }">GAP基地</view>
            <view class="f-s-26 w-200 h-54 radius-100 bg-#f7f7f7 d-flex a-c j-c mr-20 c-#333" @click="changeSelect(2)" :style="{ backgroundColor: activeSelect == 2 ? '#37A954' : '', color: activeSelect == 2 ? '#FFF' : '' }">三无一全基地</view>
        </view>
        <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" @scrolltolower="scrolltolower">
                    <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="">
                            <text class="base">{{ item?.baseName }}</text>
                            <text class="area">{{ item?.gapInfo?.area }}{{ item?.gapInfo?.areaUnit }}</text>
                        </view>
                        <view class="pt-10 d-flex">
                            <view v-if="+item?.gapFlag" class="label mr-10">GAP</view>
                            <view v-if="+item?.swyqRes" class="label">三无一全</view>
                        </view>
                    </view>
                </scroll-view>
                <scroll-view class="w-50% pd-16" :style="`height: calc(100vh - ${top}px)`" scroll-y="true">
                    <up-checkbox v-if="mixData.length > 0" label="全选" labelColor="#333" name="agree" usedAlone :checked="aloneChecked" @change="handleAllCheckboxChange"></up-checkbox>
                    <!-- 复选框组包含全选框 -->
                    <up-checkbox-group v-if="mixData.length > 0" activeColor="#37a954" :modelValue="checkBox" @change="handleCheckboxGroupChange" iconPlacement="right" placement="column">
                        <up-checkbox v-for="(item, index) in mixData" :key="index" :name="item?.id" :label="item?.landName"></up-checkbox>
                    </up-checkbox-group>
                    <view v-if="mixData.length == 0 && showtitle" class="">请先在左侧添加选择基地，选择后此处将会展示地块/圈舍/组培架信息。</view>
                </scroll-view>
            </view>
            <view v-if="medicineName || swyqMedicineName" class="w-700 c-primary bg-#EBF6EE f-s-24" style="position: fixed; bottom: 140rpx; right: 0">
                <view class="pd4-10-20-10-20 d-flex a-c">
                    <view class="">该基地获评:</view>
                    <view class="" v-if="medicineName">{{ medicineName }}GAP基地</view>
                    <view class="" v-if="medicineName && swyqMedicineName">和</view>
                    <view class="" v-if="swyqMedicineName">{{ swyqMedicineName }}三无一全基地 </view>
                </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; baseType?: string }>();
const form = ref({
    keyword: '',
    tempFlag: 0,
    gapFlag: '',
    swyqRes: '',
    plBaseType: props.baseType,
});
// 左侧基地列表数据
const list = ref<any[]>([]);
//左侧GAP基地的名称（种植的作物）
const medicineName = ref<string>('');
//左侧三无一全基地的名称
const swyqMedicineName = ref<string>('');
// 右侧地块数据
const mixData = ref<any[]>([]);
const showtitle = ref(true);
// 当前选择基地
const baseID = ref(-1);
// 请求的次数
const pageNum = 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 activeSelect = ref(0);
const changeSelect = (index: number) => {
    if (activeSelect.value == index) return;
    activeBase.value = -1;
    activeSelect.value = index;
    if (index == 0) {
        form.value.gapFlag = '';
        form.value.swyqRes = '';
    } else if (index == 1) {
        form.value.gapFlag = '1';
        form.value.swyqRes = '';
    } else if (index == 2) {
        form.value.gapFlag = '';
        form.value.swyqRes = '1';
    }
    baseID.value = -1;
    pageNum.value = 1;
    list.value = [];
    mixData.value = [];
    medicineName.value = '';
    swyqMedicineName.value = '';
    allCheckboxNames.value = [];
    checkBox.value = [];
    aloneChecked.value = false;
    getBaseInfo(pageNum.value, 10);
};

// 处理搜索
const changeSeach = () => {
    console.log('搜索关键词:', form.value.keyword);
    // 这里可以添加实际的搜索逻辑
};
// 切换基地>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
const activeBase = ref(-1);
const changeBase = (index: number, item: any) => {
    if (activeBase.value == index) return;
    activeBase.value = index;
    mixData.value = [];
    baseID.value = item.id;
    medicineName.value = '';
    swyqMedicineName.value = '';
    allCheckboxNames.value = [];
    checkBox.value = [];
    aloneChecked.value = false;
    if (item.gapInfo?.medicineName) {
        medicineName.value = item.gapInfo.medicineName;
    }
    if (item.gapInfo?.swyqMedicineName) {
        swyqMedicineName.value = item.swyqMedicineName;
    }
};
// 选择checkbox>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
// 所有复选框的name值
let allCheckboxNames = ref<string[]>([]);
let checkBox = ref<string[]>([]);
const aloneChecked = ref(false);

// 全选框change事件处理
const handleAllCheckboxChange = (value: boolean) => {
    aloneChecked.value = value;
    if (value) {
        // 全选：将checkBox设置为所有name
        checkBox.value = [...allCheckboxNames.value];
    } else {
        // 取消全选：清空checkBox
        checkBox.value = [];
    }
};

// 复选框组change事件处理
const handleCheckboxGroupChange = (value: string[]) => {
    checkBox.value = value;
    // 检查是否所有复选框都被选中
    const allSelected = allCheckboxNames.value.every((name) => value.includes(name));
    aloneChecked.value = allSelected;
};
const top = ref(0);

//scroll-view滚动监听
const scrolltolower = () => {
    console.log('滚动到底部');
    pageNum.value += 1;
    getBaseInfo(pageNum.value, 10);
};
// 获取基地信息
const getBaseInfo = async (pageNum: number, pageSize: number) => {
    const params = {
        pageNum,
        pageSize,
        ...form.value,
        baseType: props.baseType,
    };
    const res = await useClientRequest.get('/plt-api/app/base/pageList', params);
    if (res) {
        const { rows } = res;
        list.value.push(...rows);
    }
};
// 提交
const confirm = () => {
    if (baseID.value == -1) {
        uni.showToast({
            title: '请选择基地',
            icon: 'none',
        });
        return;
    } else {
        if (checkBox.value.length == 0) {
            uni.showToast({
                title: '请选择地块',
                icon: 'none',
            });
            return;
        }
    }

    // 通过 baseID 查找选中的基地
    const selectedBase = list.value.find((item) => item.id === baseID.value);
    //checkBox是一个数组，里边存的是mixData里的id，找到对应的id的mixData
    const data = checkBox.value.map((id) => mixData.value.find((item) => item.id === 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: data,
            checkBox: checkBox.value,
        });
    }

    // 关闭抽屉
    emit('update:modelValue', false);
    emit('close');
};
watch(
    () => baseID.value,
    async () => {
        if (baseID.value == -1) {
            showtitle.value = true;
            return;
        }
        showtitle.value = false;
        const res = await useClientRequest.get('/plt-api/app/baseLandInfo/pageList', { baseId: baseID.value });
        mixData.value = [];
        const { rows } = res;
        mixData.value = rows;
        allCheckboxNames.value = [];
        checkBox.value = [];
        aloneChecked.value = false;
        mixData.value.forEach((item) => {
            allCheckboxNames.value.push(item.id);
        });
        showtitle.value = true;
    },
);
onMounted(() => {
    const querys = uni.createSelectorQuery().in(instance?.proxy);
    querys
        .select('#scroll')
        .boundingClientRect((data: any) => {
            top.value = data.top;
        })
        .exec();
    getBaseInfo(pageNum.value, 10);
});
</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;
}
</style>
