<!-- 区域选择弹窗 -->
<template>
    <ele-modal
        form
        :width="1080"
        :bodyStyle="{ 'min-height': '400px' }"
        v-model="visible"
        :title="title"
    >
        <div class="flex flex-col" v-loading="loading">
            <div class="flex" v-for="dq in areaList" :key="dq.code">
                <el-checkbox
                    :label="dq.name"
                    :indeterminate="isIndeterminateShow(dq)"
                    style="min-width: 100px"
                    @change="(value) => handleDqChange(value, dq)"
                />

                <div
                    v-for="item in dq.children"
                    class="mr-6 flex items-center"
                    :key="item.code"
                >
                    <!-- Province Checkbox -->
                    <el-checkbox
                        @change="(value) => handleParentChange(value, item)"
                        :data-id="item.id"
                        v-model="item.mySelected"
                        style="margin-right: 5px"
                        :true-value="1"
                        :false-value="0"
                        :indeterminate="isIndeterCityShow(item, 'mySelected')"
                    />

                    <ele-popover
                        :width="400"
                        trigger="click"
                        :title="item.district"
                        :showArrow="false"
                        :disabled="isPopoverDisabled(item)"
                    >
                        <template #reference>
                            <div
                                class="flex items-center cursor-pointer"
                                :class="{
                                    'disabled-popover': isPopoverDisabled(item)
                                }"
                            >
                                <el-text
                                    :type="
                                        item.mySelected == 1 ? 'primary' : ''
                                    "
                                    >{{ item.district }}</el-text
                                >
                                <el-text type="warning" v-if="isShowAll(item)"
                                    >(全)</el-text
                                >
                                <el-icon>
                                    <CaretBottom />
                                </el-icon>
                            </div>
                        </template>
                        <template
                            v-for="child in item.childInfo"
                            :key="child.id"
                        >
                            <el-checkbox
                                @change="
                                    (value) =>
                                        handleChildChange(value, item, child)
                                "
                                :data-id="child.id"
                                v-model="child.mySelected"
                                :label="child.district"
                                :true-value="1"
                                :false-value="0"
                            />
                        </template>
                    </ele-popover>
                </div>
            </div>
        </div>

        <template #footer>
            <el-button @click="handleCancel">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
        </template>
    </ele-modal>
</template>

<script setup>
    import {
        ref,
        reactive,
        nextTick,
        computed,
        defineEmits,
        defineExpose
    } from 'vue';
    import { CaretBottom } from '@element-plus/icons-vue';
    import request from '@/utils/request';

    const emit = defineEmits(['confirm']);
    const visible = defineModel({ type: Boolean });

    const title = ref('选择配送区域');
    const loading = ref(false);
    const areaList = ref([]);

    // Fetch Province Info
    const getProvinceInfo = async () => {
        loading.value = true;
        try {
            const res = await request.get('/shipping/templete/provinceInfo');
            if (res.data.code === 200) {
                return res.data.data || [];
            }
        } catch (error) {
            console.error(error);
        } finally {
            loading.value = false;
        }
        return [];
    };

    const handleOpen = async (existingSelection) => {
        visible.value = true;
        loading.value = true;

        const data = await getProvinceInfo();

        // Transform API data to component structure
        areaList.value = data.map((area) => ({
            name: area.areaCode,
            code: area.areaCode,
            children: (area.provinceInfo || []).map((prov) => ({
                id: prov.provinceId,
                district: prov.provinceName,
                mySelected: 0,
                childInfo: [] // API only provides provinces, no cities
            }))
        }));

        // Restore selection
        if (existingSelection && Array.isArray(existingSelection)) {
            const selectedIds = new Set(
                existingSelection.map((item) => item.provinceId)
            );
            areaList.value.forEach((area) => {
                area.children.forEach((prov) => {
                    if (selectedIds.has(prov.id)) {
                        prov.mySelected = 1;
                    }
                });
            });
        }

        loading.value = false;
    };

    const handleCancel = () => {
        visible.value = false;
    };

    // Computed Properties
    const isPopoverDisabled = computed(() => (item) => {
        return true; // Always disabled as no cities
    });

    const isShowAll = computed(() => (item) => {
        return false; // No cities to show all
    });

    const isIndeterminateShow = computed(() => (dq) => {
        let len = dq.children.length;
        let length = dq.children.filter((i) => i.mySelected == 1).length;
        return length > 0 && length < len;
    });

    const isIndeterCityShow = computed(() => (item, type) => {
        return false;
    });

    // Event Handlers
    const handleDqChange = (value, dq) => {
        const val = value ? 1 : 0;
        dq.children.forEach((item) => {
            item.mySelected = val;
        });
    };

    const handleParentChange = (value, item) => {
        // value is boolean from checkbox
        // item.mySelected is bound to v-model, so it updates automatically?
        // Wait, v-model="item.mySelected" on checkbox updates it.
        // But we also need to handle 'change' event if we want extra logic.
        // The template uses: @change="(value) => handleParentChange(value, item)"
        // and v-model="item.mySelected".
        // Element Plus checkbox change emits the new value.
        // We don't need to manually set item.mySelected if v-model is used,
        // but the original code did manual updates for children.
        // Since we have no children (cities), we might just rely on v-model.
        // However, keeping the handler for consistency.
        item.mySelected = value ? 1 : 0;
    };

    const handleChildChange = (value, item, child) => {
        // No children
    };

    const handleSubmit = () => {
        // Collect selected provinces
        const selected = [];
        areaList.value.forEach((dq) => {
            dq.children.forEach((prov) => {
                if (prov.mySelected === 1) {
                    selected.push({
                        provinceId: prov.id,
                        provinceName: prov.district
                    });
                }
            });
        });

        emit('confirm', selected);
        visible.value = false;
    };

    defineExpose({
        handleOpen
    });
</script>

<style lang="scss" scoped>
    .disabled-popover {
        cursor: not-allowed;
        .el-text {
            color: #909399;
        }
        .el-icon {
            color: #909399;
            fill: #909399;
        }
    }
</style>
