<template>
    <popup v-model:show="showValue" round class="confirm-draw-type-popup" teleport="body">
        <div class="popup-title">{{ $t('请确认勾画类型') }}</div>
        <div class="type-list">
            <div
                v-for="item in typeOptions"
                :key="item.code"
                class="type-item"
                :class="{ 'type-item--active': selectedType === item.code }"
                @click="handleTypeClick(item)"
            >
                {{ item.name }}
            </div>
        </div>

        <template v-if="selectedType !== 'DORMANCY'">
            <div class="popup-sub-title">{{ $t('请确认 具体勾画类别') }}</div>
            <div class="category-list">
                <div
                    v-for="(item, index) in currentCategoryOptions"
                    :key="`${selectedType}-${index}`"
                    class="category-item"
                    :class="{ 'category-item--active': selectedCategory === index }"
                    @click="selectedCategory = index"
                >
                    {{ item.regionName || item.problemZoneTypeName }}
                </div>
            </div>
        </template>

        <textarea v-if="selectedType !== 'ABNORMAL'" v-model="remark" class="remark-input" maxlength="200"
            :placeholder="$t('添加备注')"></textarea>

        <div class="confirm-btn" @click="handleConfirm">{{ $t('确认') }}</div>
    </popup>

    <!-- 异常问题区：点击确认后弹出的照片上传进度弹窗 -->
    <popup v-model:show="showUploadProgressPopup" round class="upload-progress-popup" teleport="body">
        <div class="upload-progress-title">
            <span>{{ uploadPromptText }}</span>
            <el-progress class="upload-progress" :percentage="uploadPercentage" :stroke-width="10" :format="format" />
        </div>
        <div class="upload-box">
            <upload
                ref="abnormalUploadRef"
                :maxCount="10"
                :initImgArr="initImgArr"
                @handleUpload="handleUploadSuccess"
            />
        </div>
        <textarea v-model="remark" class="remark-input" maxlength="200" :placeholder="$t('添加备注')"></textarea>
        <div class="confirm-btn" :class="{ 'confirm-btn-loading': confirmUploadLoading }" @click="handleConfirmUpload">
            {{ confirmUploadLoading ? '上传中...' : '确认上传' }}
        </div>
    </popup>
</template>

<script setup>
import { Popup } from "vant";
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import upload from "@/components/upload.vue";

const emit = defineEmits(["confirm"]);

const showValue = ref(false);

const typeOptions = ref([])
const currentCategoryOptions = ref([]);
const tempCategoryOptions = ref({});

const openPopup = (payload) => {
    tempCategoryOptions.value = payload;
    remark.value = payload.remark || "";
    // remark.value = "";
    typeOptions.value = payload.regionInfo.problemZoneList;

    if(payload.activeRegionType === 'variety'){
        currentCategoryOptions.value = payload.regionInfo.regionList;
    }else{
        const arr = payload.regionInfo.problemZoneList.filter(item => item.code === payload.activeRegionType);
        currentCategoryOptions.value = arr[0].children;
    }

    selectedType.value = payload.activeRegionType;
    selectedCategory.value = payload.activeVarietyIndex;

    showValue.value = true;
};

const close = () => {
    showValue.value = false;
};

defineExpose({
    openPopup,
    close,
});


const selectedType = ref("");
const selectedCategory = ref(null);
const remark = ref("");

const handleTypeClick = (item) => {
    selectedType.value = item.code;
    if(item.code === 'variety'){
        currentCategoryOptions.value = tempCategoryOptions.value.regionInfo.regionList;
    }else{
        currentCategoryOptions.value = item.children;
    }
    selectedCategory.value = 0;
};

const handleConfirm = () => {
    if (!selectedType.value || selectedCategory.value == null) {
        ElMessage.warning("请选择勾画类型和类别");
        return;
    }

    const payload = {
        type: selectedType.value,
        category: currentCategoryOptions.value[selectedCategory.value],
        remark: remark.value.trim(),
    };

    // 异常问题区：先打开上传弹窗，再发出 confirm
    if (selectedType.value === "ABNORMAL") {
        pendingConfirmPayload.value = payload;
        initImgArr.value = [];
        uploadData.value = [];
        totalUploadCount.value = 0;
        uploadedSuccessCount.value = 0;
        showUploadProgressPopup.value = true;
        close();
        return;
    }

    emit("confirm", payload);
    close();
};

// ---------------- 上传进度弹窗逻辑（只用于异常问题区） ----------------
const showUploadProgressPopup = ref(false);
const pendingConfirmPayload = ref(null);

const uploadPromptText = computed(() => {
    const c = pendingConfirmPayload.value?.category;
    const name = c?.regionName || c?.problemZoneTypeName || c?.name || c?.title || c?.label || "";
    return name ? `请上传 ${name} 照片` : "请上传照片";
});

const totalUploadCount = ref(0);
const uploadedSuccessCount = ref(0);
const uploadPercentage = computed(() => {
    if (!totalUploadCount.value) return 0;
    return Math.round((uploadedSuccessCount.value / totalUploadCount.value) * 100);
});
const format = () => {
    if (!totalUploadCount.value) return "0/0";
    return `${uploadedSuccessCount.value}/${totalUploadCount.value}`;
};

const initImgArr = ref([]);
const uploadData = ref([]);
const confirmUploadLoading = ref(false);
const abnormalUploadRef = ref(null);

const handleUploadSuccess = (data) => {
    uploadData.value = data?.imgArr || [];
    const len = (data?.imgArr && data.imgArr.length) || 0;
    totalUploadCount.value = len;
    uploadedSuccessCount.value = len;
};

const handleConfirmUpload = async () => {
    if (confirmUploadLoading.value) return;
    if (!uploadData.value || uploadData.value.length === 0) {
        ElMessage.warning("请先上传照片");
        return;
    }
    confirmUploadLoading.value = true;
    try {
        const payload = pendingConfirmPayload.value;
        if (pendingConfirmPayload.value) {
            pendingConfirmPayload.value.remark = remark.value.trim();
        }
        const images = [...uploadData.value];
        abnormalUploadRef.value?.uploadReset();
        initImgArr.value = [];
        uploadData.value = [];
        totalUploadCount.value = 0;
        uploadedSuccessCount.value = 0;
        showUploadProgressPopup.value = false;
        pendingConfirmPayload.value = null;
        emit("confirm", {
            ...(payload || {}),
            images, // 预留字段，父组件当前逻辑不受影响
        });
    } finally {
        confirmUploadLoading.value = false;
    }
};
</script>

<style scoped lang="scss">
.confirm-draw-type-popup {
    width: 100%;
    padding: 16px 10px;

    .popup-title,
    .popup-sub-title {
        font-size: 16px;
    }

    .popup-sub-title {
        margin-top: 12px;
    }

    .type-list,
    .category-list {
        margin-top: 12px;
        display: flex;
        gap: 6px;
        flex-wrap: wrap;
    }

    .type-item,
    .category-item {
        padding: 7px 12px;
        border-radius: 2px;
        font-size: 12px;
        color: #575757;
        background: #F4F4F4;
        border: 1px solid transparent;
        box-sizing: border-box;
    }

    .type-item--active,
    .category-item--active {
        color: #2199f8;
        border-color: #2199f8;
        background: rgba(33, 153, 248, 0.1);
    }

    .remark-input {
        margin-top:20px;
        width: 100%;
        height: 72px;
        resize: none;
        border: 1px solid #e6e6e6;
        border-radius: 8px;
        padding: 10px 12px;
        box-sizing: border-box;
        font-size: 14px;
        color: #333;
    }

    .remark-input::placeholder {
        color: #c9c9c9;
    }

    .confirm-btn {
        margin-top: 20px;
        padding: 8px;       
        text-align: center;
        color: #fff;
        background: #2199f8;
        border-radius: 25px;
        font-size: 16px;
    }
}

.upload-progress-popup {
    width: 100%;
    padding: 16px 10px;

    .upload-progress-title {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 12px;
    }

    .upload-box {
        margin: 10px 0 16px;
    }

    // 上传弹窗里的备注输入框样式：保持与主弹窗输入框一致
    .remark-input {
        margin-bottom: 20px;
        width: 100%;
        height: 72px;
        resize: none;
        border: 1px solid #e6e6e6;
        border-radius: 8px;
        padding: 10px 12px;
        box-sizing: border-box;
        font-size: 14px;
        color: #333;
    }

    .remark-input::placeholder {
        color: #c9c9c9;
    }

    .confirm-btn {
        width: 100%;
        text-align: center;
        color: #fff;
        background: #2199f8;
        border-radius: 25px;
        padding: 10px 0;
        font-size: 16px;
    }
}
</style>
