<template>
    <div class="interaction-page">
        <custom-header name="农情互动" bgColor="#f2f4f5" :isClose="true" :showClose="false" />
        <div class="interaction-content">
            <!-- 顶部说明 -->
            <div class="intro-card">
                完善作物品种以及物候信息，精准匹配种植方案，实现精细化管理
            </div>

            <!-- 作物块（每个农场一块） -->
            <div v-for="(crop, cropIndex) in farmData" :key="cropIndex" class="crop-section">
                <div class="crop-header">
                    <div class="crop-tag">{{ crop.speciesName }}</div>
                    <div class="add-btn" @click="addVariety(crop)">+ 新增品种</div>
                </div>

                <div v-for="(region, regionIndex) in crop.regions" :key="regionIndex" class="variety-card">
                    <div class="field-row">
                        <div class="field-value">
                            <el-select 
                                v-model="region.regionId" 
                                class="variety-input" 
                                placeholder="选择品种"
                            >
                                <el-option v-for="(item, index) in crop.typeIdItems" :key="index" :label="item.name"
                                    :value="item.id" />
                                    <template #footer>
                                        <el-button text bg @click="onAddOption(region)">
                                            + 增加品种
                                        </el-button>
                                    </template>
                            </el-select>
                        </div>
                    </div>

                    <div class="field-row">
                        <div class="field-label">当下物候期</div>
                        <div class="field-value">
                            <el-select
                                v-model="region.phenologyId"
                                class="select-input"
                                placeholder="选择物候期"
                            >
                                <el-option v-for="(item, index) in crop.phenologyOptions" :key="index" :label="item.phenologyName"
                                    :value="item.phenologyId" />
                            </el-select>
                        </div>
                    </div>

                    <div class="field-row" v-if="region.phenologyId">
                        <div class="field-label">{{ getPhenologyLabel(crop, region.phenologyId) }}</div>
                        <div class="field-value">
                            <el-date-picker
                                :editable="false"
                                style="width: 100%"
                                v-model="region.phenologyStartDate"
                                class="date-picker"
                                type="date"
                                placeholder="选择时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 底部按钮 -->
        <div class="fixed-btn-wrap">
            <div class="fixed-btn" @click="handleConfirm">
                确认信息
            </div>
        </div>
    </div>

    <tip-popup v-model:show="showTipPopup" type="success" text="您的作物信息已完善" />


    <popup class="add-tag-popup" :z-index="2500" round v-model:show="showAddPopup" @update:show="handlePopupClose">
        <div class="tag-item">
            <div class="popup-title">新增品种名称</div>
            <el-input autofocus class="popup-input" v-model="newVarietyName" placeholder="请输入品种名称" size="large" />
        </div>
        <div class="popup-button">
            <div class="cancel" @click="handleCancelAdd">取消</div>
            <div @click="handleAddVariety">确认</div>
        </div>
    </popup>
</template>

<script setup>
import { ref, nextTick, onActivated } from "vue";
import { ElMessage } from "element-plus";
import { Popup } from "vant";
import customHeader from "@/components/customHeader.vue";
import { useRoute } from "vue-router";
import tipPopup from "@/components/popup/tipPopup.vue";

const route = useRoute();

onActivated(() => {
    const subjectId = route.query.subjectId;
    getPhenologyInitOrConfirmStatus(subjectId);
});

const farmData = ref([])
const getPhenologyInitOrConfirmStatus = async (subjectId) => {
    const {data} = await VE_API.farm_v3.phenologyInitOrConfirmStatus({subjectId});
    farmData.value = data.farms;
    farmData.value.forEach(item => {
        addVariety(item);
    });
}

const addVariety = (crop) => {
    if (!Array.isArray(crop.regions)) {
        crop.regions = [];
    }
    crop.regions.push({
        regionId: null,
        phenologyId: null,
        phenologyStartDate: "",
    });
};

// 获取物候期对应的时间标签
const getPhenologyLabel = (farm, phenologyId) => {
    if (!farm?.phenologyOptions) return "选择时间";
    const found = farm.phenologyOptions.find(
        (item) => item.id === phenologyId || item.phenologyId === phenologyId
    );
    return found?.startDateLabel || "选择时间";
};

const showTipPopup = ref(false);

const handleConfirm = async () => {
    // 组装为 initFarmData 接口所需的 farmDataList 结构
    const farmDataList = farmData.value
        .map((farm) => {
            const typeIdItems = (farm.regions || [])
                .filter(
                    (r) => r.regionId && r.phenologyId && r.phenologyStartDate
                )
                .map((r) => {
                    const origin =
                        (farm.typeIdItems || []).find(
                            (t) => String(t.id) === String(r.regionId)
                        ) || {};
                    return {
                        id: r.regionId,
                        name: origin.name || "",
                        phenologyId: r.phenologyId,
                        phenologyStartDate: r.phenologyStartDate,
                    };
                })
                .filter((item) => item.id);

            return {
                farmId: farm.farmId,
                speciesId: farm.speciesId,
                typeIdItems,
            };
        })
        .filter((item) => item.typeIdItems.length > 0);

    if (!farmDataList.length) {
        ElMessage.warning("请先选择品种、物候期和时间");
        return;
    }

    const params = {
        expertMiniUserId: 81881,
        farmDataList,
    };
    console.log("params", params);

    const { code, msg } = await VE_API.farm_v3.initFarmData(params);
    if (code === 0) {
        showTipPopup.value = true;
    } else {
        ElMessage.error(msg || "提交失败");
    }

    // 大物候期转换所需参数// 组装为后端所需的 farmDataList 结构
    // const farmDataList = farmData.value
    //     .map((farm) => {
    //         const regionPhenologyItems = (farm.regions || [])
    //             .filter(
    //                 (r) => r.regionId && r.phenologyId && r.phenologyStartDate
    //             )
    //             .map((r) => ({
    //                 regionId: r.regionId,
    //                 phenologyId: r.phenologyId,
    //                 phenologyStartDate: r.phenologyStartDate,
    //             }));

    //         return {
    //             farmId: farm.farmId,
    //             regionPhenologyItems,
    //         };
    //     })
    //     .filter((item) => item.regionPhenologyItems.length > 0);

    // console.log("farmDataList", farmDataList);
    
    // const params = {
    //     farmDataList,
    //     expertMiniUserId: 81881,
    // }
    // const {code, msg} = await VE_API.farm_v3.confirmReproductivePhenology(params);
    // if(code === 0) {
    //     qrCodePopupRef.value.showPopup();
    // } else {
    //     ElMessage.error(msg);
    // }
};

const showAddPopup = ref(false);
const newVarietyName = ref("");
const currentVariety = ref(null); // 记录当前正在添加品种的 variety 对象

const handleAddVariety = () => {
    if (!newVarietyName.value.trim()) {
        return;
    }
    
    // 如果当前有正在添加品种的 variety，则自动选中新增的品种
    if (currentVariety.value) {
        currentVariety.value.variety = newVarietyName.value;
    }
    
    newVarietyName.value = "";
    showAddPopup.value = false;
    currentVariety.value = null;
}

const onAddOption = async (region) => {
    // 先关闭下拉菜单
    if (document.activeElement) {
        document.activeElement.blur();
    }
    
    // 等待下拉菜单关闭后再显示弹窗
    await nextTick();
    
    // 记录当前 region
    currentVariety.value = region;
    showAddPopup.value = true;
}

const handleCancelAdd = () => {
    newVarietyName.value = "";
    showAddPopup.value = false;
    currentVariety.value = null;
}

const handlePopupClose = (show) => {
    if (!show) {
        // 弹窗关闭时清空状态
        newVarietyName.value = "";
        currentVariety.value = null;
    }
}
</script>

<style lang="scss" scoped>
.interaction-page {
    height: 100vh;
    box-sizing: border-box;
    background: #F2F4F5;
    font-size: 14px;
    color: #1d2129;
}

.interaction-content {
    height: calc(100% - 40px);
    overflow: auto;
    padding: 12px 10px 70px 10px;
    box-sizing: border-box;
}

.intro-card {
    padding: 10px;
    border-radius: 6px;
    background: #ffffff;
    color: #666666;
    box-shadow: 0 2px 8px rgba(15, 35, 52, 0.06);
    margin-bottom: 12px;
    line-height: 17px;
}

.crop-section {
    background: #ffffff;
    border-radius: 6px;
    padding: 10px;
    box-shadow: 0 2px 8px rgba(15, 35, 52, 0.04);
    margin-bottom: 10px;
}

.crop-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 10px;

    .crop-tag {
        padding: 0 16px;
        border-radius: 2px;
        background: #2199F8;
        color: #ffffff;
        font-size: 14px;
        height: 26px;
        line-height: 26px;
    }

    .add-btn {
        padding: 0 12px;
        border-radius: 4px;
        height: 26px;
        line-height: 26px;
        box-sizing: border-box;
        border: 0.5px solid rgba(33, 153, 248, 0.5);
        color: #0B84E4;
    }
}

.variety-card {
    margin-top: 8px;
    padding: 10px;
    border-radius: 5px;
    background: rgba(33, 153, 248, 0.05);
    border: 1px solid rgba(33, 153, 248, 0.2);
}

.field-row {
    display: flex;
    align-items: center;
    margin-bottom: 10px;

    &:last-child {
        margin-bottom: 0;
    }
}

.field-label {
    width: 118px;
    flex: none;
    font-size: 14px;
    color: #1D2129;
}

.field-value {
    flex: 1;
}

.select-input,
.date-picker {
    width: 100%;
}

.variety-input {
    width: 110px;
    ::v-deep {
        .el-select__wrapper {
            box-shadow: none;
            background-color: rgba(33, 153, 248, 0.1);
            // box-shadow: 0 0 0 1px var(--el-border-color) inset;
        }
        .el-select__placeholder {
            color: #2199F8;
        }
        .el-select__caret {
            color: #2199F8;
        }
    }
}

.fake-select {
    height: 32px;
    border-radius: 4px;
    border: 1px solid rgba(0, 0, 0, 0.08);
    background: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 8px;
    box-sizing: border-box;

    .text {
        color: #1d2129;
        font-size: 14px;
    }

    .arrow {
        font-size: 10px;
        color: #c0c4cc;
    }

    &.fake-select--plain {
        background: #ffffff;
    }
}


.fixed-btn-wrap {
    display: flex;
    justify-content: center;
    position: fixed;
    bottom: 0px;
    left: 0;
    right: 0;
    background: #fff;
    padding: 10px 12px;
    box-sizing: border-box;
    // box-shadow: 0 -2px 8px rgba(15, 35, 52, 0.06);
    box-shadow: 2px 2px 4.5px 0px #00000066;

    .fixed-btn {
        min-width: 110px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-radius: 20px;
        background: linear-gradient(180deg, #70bffe, #2199f8);
        color: #ffffff;
        font-size: 14px;
    }
}

.date-input {
    height: 32px;
    border-radius: 4px;
    border: 1px dashed rgba(33, 153, 248, 0.6);
    background: #ffffff;
    display: flex;
    align-items: center;
    padding: 0 8px;
    box-sizing: border-box;
    color: #c0c4cc;
    font-size: 14px;
}

.success-text {
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: #000;
    .success-icon {
        width: 28px;
        height: 28px;
        margin-right: 5px;
    }
}


.add-tag-popup {
    width: 90%;
    padding: 24px 16px 20px 16px;
    background: linear-gradient(360deg, #FFFFFF 74.2%, #D1EBFF 100%);

    .popup-title {
        font-size: 16px;
        font-weight: 400;
        margin-bottom: 12px;
        color: #000000;
        .name-text{
            font-weight: 500;
            color: #2199F8;
            padding: 0 2px;
        }
    }

    .ml-2 {
        margin-left: 3px;
    }

    .popup-input {
        margin-bottom: 24px;
    }

    .popup-button {
        display: flex;

        div {
            flex: 1;
            font-size: 16px;
            padding: 9px;
            border-radius: 20px;
            background: #2199F8;
            color: #fff;
            text-align: center;
            cursor: pointer;
        }

        .cancel {
            margin-right: 13px;
            color: #000;
            background: #fff;
            border: 1px solid #999999;
        }
        .delete {
            margin-right: 13px;
            color: #FF3D3D;
            background: #fff;
            border: 1px solid rgba(255, 61, 61, 0.4);
        }
    }
}
</style>