<template>
    <div class="select-equipment" :class="{ 'is-service-equipment': isService }">
        <div class="select-equipment__content">
            <div class="page-header">
                <div class="page-title">{{ pageTitle }}</div>
                <div class="page-subtitle">{{ pageSubtitle }}</div>
            </div>

            <div class="toolbar">
                <div class="search-bar">
                    <el-icon class="search-icon"><Search /></el-icon>
                    <input
                        v-model="searchKeyword"
                        class="search-input"
                        type="text"
                        placeholder="请输入农机名称"
                        @keyup.enter="handleSearch"
                    />
                    <div class="search-btn" @click="handleSearch">搜索</div>
                </div>
                <div class="add-btn" @click="handleAddMachine">+ 添加农机</div>
            </div>

            <div class="equipment-list" v-loading="loading">
                <div v-for="group in displayGroups" :key="group.name" class="equipment-card">
                    <div class="section-title">
                        <img class="title-icon" src="@/assets/img/home/label-icon.png" alt="" />
                        <span>{{ group.name }}</span>
                    </div>
                    <div v-if="group.desc" class="section-desc">{{ group.desc }}</div>
                    <div class="tag-group">
                        <div
                            v-for="item in group.items"
                            :key="item.id"
                            class="tag-item"
                            :class="{ selected: selectedIds.has(String(item.id)) }"
                            @click="toggleSelect(item)"
                        >
                            <span class="text">{{ item.name }}</span>
                        </div>
                    </div>
                </div>
                <div v-if="!loading && !displayGroups.length" class="empty-tip">暂无匹配农机</div>
            </div>
        </div>

        <div class="custom-bottom-fixed-btns">
            <div class="btns-l">
                <div class="bottom-btn secondary-btn" @click="emit('prev')">上一步</div>
                <div
                    v-if="isLastStep && !isService"
                    class="bottom-btn secondary-btn"
                    :class="{ disabled: submitting }"
                    @click="handleSkip"
                >
                    跳过
                </div>
            </div>
            <div class="bottom-btn primary-btn" :class="{ disabled: submitting }" @click="handleSubmit">
                {{ primaryBtnText }}
            </div>
        </div>

        <add-machine-popup
            v-model:show="showAddPopup"
            @confirm="handleAddConfirm"
        />

        <tip-popup
            v-model:show="showSuccessPopup"
            type="executeSuccess"
            :text="isService ? '您的信息已提交成功' : '您的信息已上传'"
            :text2="isService ? '' : '请等待诊断报告生成'"
            buttonText="完成"
            @confirm="handleComplete"
        />

    </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import addMachinePopup from "./addMachinePopup.vue";
import tipPopup from "@/components/popup/tipPopup.vue";

const emit = defineEmits(["prev", "next", "confirm"]);
const props = defineProps({
    isService: { type: Boolean, default: false },
    isLastStep: { type: Boolean, default: true },
    equipmentScope: { type: String, default: "" },
    totalSteps: { type: Number, default: 4 },
});

const EQUIPMENT_KEY = "ENTRY_SELECTED_EQUIPMENT";
const TASK_KEY = "ENTRY_SELECTED_FARM_TASKS";
const SELECTED_LIST_KEY = "ENTRY_SELECTED_VARIETY_LIST";
const CATEGORY_SESSION_KEY = "ENTRY_SELECTED_CATEGORY";
const LOCATION_KEY = "ENTRY_RESIDENT_LOCATION";
const EDIT_UID_KEY = "ENTRY_VARIETY_EDIT_UID";
const STEP_KEY = "ENTRY_INFORMATION_STEP";

const loading = ref(false);
const submitting = ref(false);
const showAddPopup = ref(false);
const searchKeyword = ref("");
const appliedKeyword = ref("");
const selectedIds = reactive(new Set());
const equipmentGroups = ref([]);
let customMachineId = 9000;

const DEFAULT_GROUPS = [
    {
        name: "耕地（整地、施肥、撒肥、中耕等）",
        items: [
            { id: 101, name: "滴灌系统" },
            { id: 102, name: "喷灌设备" },
            { id: 103, name: "水肥一体机" },
            { id: 104, name: "水泵机组" },
            { id: 105, name: "施肥机" },
            { id: 106, name: "过滤设备" },
        ],
    },
    {
        name: "种（播种、育秧、移栽、补苗等）",
        items: [
            { id: 201, name: "拖拉机" },
            { id: 202, name: "旋耕机" },
            { id: 203, name: "开沟机" },
            { id: 204, name: "植保机" },
            { id: 205, name: "无人机" },
            { id: 206, name: "运输车" },
        ],
    },
    {
        name: "收（收割、烘干、运输等）",
        items: [
            { id: 301, name: "修剪机" },
            { id: 302, name: "采收机" },
            { id: 303, name: "割草机" },
            { id: 304, name: "粉碎机" },
            { id: 305, name: "发电机" },
            { id: 306, name: "其他设备" },
        ],
    },
];

const FIELD_GROUPS = [
    {
        name: "耕地（整地、施肥、撒肥、中耕等）",
        items: [
            { id: 1001, name: "大中型拖拉机" },
            { id: 1002, name: "手扶拖拉机" },
            { id: 1003, name: "旋耕机" },
            { id: 1004, name: "微耕机" },
            { id: 1005, name: "挖掘机" },
            { id: 1006, name: "培土机" },
            { id: 1007, name: "撒肥机" },
            { id: 1008, name: "秸秆还田机" },
            { id: 1009, name: "开沟机" },
            { id: 1010, name: "水田打浆机" },
            { id: 1011, name: "深松机" },
            { id: 1012, name: "起垄机" },
            { id: 1013, name: "甘蔗开行机" },
            { id: 1014, name: "棉花拔杆机" },
        ],
    },
    {
        name: "种（播种、育秧、移栽、补苗等）",
        items: [
            { id: 2001, name: "插秧机" },
            { id: 2002, name: "一体育秧机" },
            { id: 2003, name: "播种机" },
            { id: 2004, name: "移栽机" },
            { id: 2005, name: "无人机播种" },
            { id: 2006, name: "小麦/玉米精量播种机" },
            { id: 2007, name: "免耕播种机" },
            { id: 2008, name: "花生覆膜播种机" },
            { id: 2009, name: "马铃薯播种机" },
        ],
    },
    {
        name: "收（收割、烘干、运输等）",
        items: [
            { id: 3001, name: "联合收割机" },
            { id: 3002, name: "半喂入收割机" },
            { id: 3003, name: "玉米联合收割机" },
            { id: 3004, name: "水稻收割机" },
            { id: 3005, name: "烘干机" },
            { id: 3006, name: "运粮车" },
            { id: 3007, name: "挂车" },
        ],
    },
];

const FRUIT_GROUPS = [
    {
        name: "土壤与园地管理",
        desc: "（整地、除草、清园、开沟修渠等）",
        items: [
            { id: 4001, name: "旋耕机" },
            { id: 4002, name: "微耕机" },
            { id: 4003, name: "挖掘机" },
            { id: 4004, name: "旋耕开沟机" },
            { id: 4005, name: "割草机" },
            { id: 4006, name: "清沟机" },
            { id: 4007, name: "运输车" },
            { id: 4008, name: "开沟施肥机" },
            { id: 4009, name: "树盘管理机" },
            { id: 4010, name: "行间除草机" },
            { id: 4011, name: "生草播种机" },
            { id: 4012, name: "压草机" },
        ],
    },
    {
        name: "肥水管理",
        desc: "（施肥、灌水、灌药等）",
        items: [
            { id: 5001, name: "水肥一体化" },
            { id: 5002, name: "滴灌系统" },
            { id: 5003, name: "注肥/注药泵" },
            { id: 5004, name: "施肥枪" },
            { id: 5005, name: "移动水车" },
            { id: 5006, name: "水泵" },
        ],
    },
    {
        name: "植保打药",
        desc: "（冠层打药、内膛打药等）",
        items: [
            { id: 6001, name: "植保无人机" },
            { id: 6002, name: "风送式喷雾机" },
            { id: 6003, name: "背负式喷雾器" },
            { id: 6004, name: "柴油喷药机" },
            { id: 6005, name: "烟雾机" },
            { id: 6006, name: "高架喷雾机" },
        ],
    },
];

const displayGroups = computed(() => {
    const keyword = (appliedKeyword.value || "").trim();
    if (!keyword) return equipmentGroups.value;
    return equipmentGroups.value
        .map((group) => ({
            ...group,
            items: group.items.filter((item) => item.name.includes(keyword)),
        }))
        .filter((group) => group.items.length);
});

const allEquipmentItems = computed(() =>
    equipmentGroups.value.flatMap((group) => group.items)
);

const pageTitle = computed(() =>
    props.isService ? "完善设备信息" : "请填写您的农场设备"
);
const pageSubtitle = computed(() =>
    props.isService ? "让农机调度更精准（可多选）" : "完善设备信息，让农机调度更精准"
);
const primaryBtnText = computed(() => {
    if (submitting.value) return "提交中...";
    return props.isLastStep ? "提交信息" : `下一步 (3/${props.isService ? props.totalSteps : 4})`;
});

function readJson(key) {
    try {
        const raw = sessionStorage.getItem(key);
        return raw ? JSON.parse(raw) : null;
    } catch {
        return null;
    }
}

function cloneGroups(groups) {
    return groups.map((group) => ({
        name: group.name,
        desc: group.desc || "",
        items: group.items.map((item) => ({ ...item })),
    }));
}

function flattenEquipment(cached) {
    if (!cached) return [];
    if (Array.isArray(cached)) return cached;
    return [...(cached.field || []), ...(cached.fruit || [])];
}

function getScopeList(cached, scope) {
    if (!cached) return [];
    if (Array.isArray(cached)) return scope === "fruit" ? [] : cached;
    return cached[scope] || [];
}

function getCurrentScope() {
    if (props.equipmentScope === "fruit") return "fruit";
    if (props.equipmentScope === "field") return "field";
    return "";
}

function restoreSelection() {
    const cached = readJson(EQUIPMENT_KEY);
    const scope = getCurrentScope();
    const list = scope ? getScopeList(cached, scope) : flattenEquipment(cached);
    list.forEach((item) => {
        if (item?.id == null) return;
        selectedIds.add(String(item.id));
        if (!item.custom) return;
        const exists = allEquipmentItems.value.some((row) => String(row.id) === String(item.id));
        if (exists) return;
        let group = equipmentGroups.value.find((row) => row.name === item.groupName);
        if (!group) group = equipmentGroups.value[equipmentGroups.value.length - 1];
        if (group) {
            group.items.push({ id: item.id, name: item.name, custom: true });
        }
        if (Number(item.id) >= customMachineId) customMachineId = Number(item.id);
    });
}

function saveSelectionDraft() {
    const scope = getCurrentScope();
    const selected = allEquipmentItems.value
        .filter((item) => selectedIds.has(String(item.id)))
        .map((item) => {
            const group = equipmentGroups.value.find((row) =>
                row.items.some((rowItem) => String(rowItem.id) === String(item.id))
            );
            return { ...item, scope: scope || "farmer", groupName: group?.name };
        });
    if (!props.isService) {
        sessionStorage.setItem(EQUIPMENT_KEY, JSON.stringify(selected));
        return;
    }
    const cached = readJson(EQUIPMENT_KEY);
    const next = {
        field: Array.isArray(cached) ? cached : cached?.field || [],
        fruit: Array.isArray(cached) ? [] : cached?.fruit || [],
    };
    if (scope === "fruit") next.fruit = selected;
    else next.field = selected;
    sessionStorage.setItem(EQUIPMENT_KEY, JSON.stringify(next));
}

function fetchEquipmentList() {
    loading.value = true;
    if (!props.isService) {
        equipmentGroups.value = cloneGroups(DEFAULT_GROUPS);
    } else if (props.equipmentScope === "fruit") {
        equipmentGroups.value = cloneGroups(FRUIT_GROUPS);
    } else {
        equipmentGroups.value = cloneGroups(FIELD_GROUPS);
    }
    loading.value = false;
}

const handleSearch = () => {
    appliedKeyword.value = searchKeyword.value;
};

const handleAddMachine = () => {
    showAddPopup.value = true;
};

const handleAddConfirm = ({ name }) => {
    const machineName = String(name || "").trim();
    if (!machineName) return;

    const CUSTOM_GROUP_NAME = "我的农机";

    // 已存在同名则直接选中
    const exists = allEquipmentItems.value.find((item) => item.name === machineName);
    if (exists) {
        selectedIds.add(String(exists.id));
        saveSelectionDraft();
        ElMessage.success("已选中该农机");
        return;
    }

    // 确保「自定义类」作为第一组存在
    let customGroup = equipmentGroups.value.find((group) => group.name === CUSTOM_GROUP_NAME);
    if (!customGroup) {
        customGroup = { name: CUSTOM_GROUP_NAME, items: [] };
        equipmentGroups.value.unshift(customGroup);
    } else {
        const index = equipmentGroups.value.indexOf(customGroup);
        if (index > 0) {
            equipmentGroups.value.splice(index, 1);
            equipmentGroups.value.unshift(customGroup);
        }
    }

    const newItem = {
        id: ++customMachineId,
        name: machineName,
        custom: true,
    };
    customGroup.items.push(newItem);
    selectedIds.add(String(newItem.id));
    saveSelectionDraft();
    ElMessage.success("添加成功");
};

const toggleSelect = (item) => {
    const id = String(item.id);
    if (selectedIds.has(id)) {
        selectedIds.delete(id);
    } else {
        selectedIds.add(id);
    }
    saveSelectionDraft();
};

function getVarietyDraftList() {
    const draft = readJson(SELECTED_LIST_KEY);
    if (Array.isArray(draft)) return draft;
    if (Array.isArray(draft?.list)) return draft.list;
    return [];
}

function getPhenophaseLabel(item) {
    return item.phenophase || item.phenologyName || String(item.phenologyId || "");
}

function buildPlotPayload(includeEquipment = true) {
    const baForm = readJson("ENTRY_BA_FORM") || {};
    const varietyList = getVarietyDraftList();
    const equipmentCache = readJson(EQUIPMENT_KEY);
    const equipmentList = includeEquipment ? flattenEquipment(equipmentCache) : [];
    const taskCache = readJson(TASK_KEY);
    const taskList = Array.isArray(taskCache)
        ? taskCache
        : [...(taskCache?.field || []), ...(taskCache?.fruit || [])];

    return {
        user_name: baForm.name,
        tel: baForm.phone,
        team_name: baForm.teamName || "",
        team_type: baForm.teamType || "",
        invite_type: baForm.inviteType || (props.isService ? "service" : "farmer"),
        crops: varietyList.map((item) => ({
            crop_type: item.categoryName,
            crop_id: Number(item.categoryId),
            variety_list: [Number(item.id)],
            phenophase: getPhenophaseLabel(item),
            start_time: item.startTime,
            plant_area: Number(item.area),
            point: item.location,
        })),
        farm_machines: equipmentList.map((item) => ({
            id: item.id,
            name: item.name,
        })),
        farm_tasks: taskList.map((item) => ({
            id: item.id,
            name: item.name,
        })),
        field_tasks: (taskCache?.field || []).map((item) => ({ id: item.id, name: item.name })),
        fruit_tasks: (taskCache?.fruit || []).map((item) => ({ id: item.id, name: item.name })),
    };
}

function clearEntrySession() {
    sessionStorage.removeItem(SELECTED_LIST_KEY);
    sessionStorage.removeItem(CATEGORY_SESSION_KEY);
    sessionStorage.removeItem("ENTRY_BA_FORM");
    sessionStorage.removeItem(LOCATION_KEY);
    sessionStorage.removeItem(EDIT_UID_KEY);
    sessionStorage.removeItem(EQUIPMENT_KEY);
    sessionStorage.removeItem(TASK_KEY);
    sessionStorage.removeItem("ENTRY_MANUAL_VIEW");
    sessionStorage.removeItem(STEP_KEY);
    sessionStorage.removeItem("ENTRY_INVITE_TYPE");
}

const showSuccessPopup = ref(false);

async function submitEntry(includeEquipment = true) {
    if (submitting.value) return;
    const varietyList = getVarietyDraftList();

    if (!props.isService && !varietyList.length) {
        ElMessage.warning("请先完善种植品种信息");
        return;
    }
    const baForm = readJson("ENTRY_BA_FORM");
    if (!baForm?.name || !baForm?.phone) {
        ElMessage.warning("请先完善个人信息");
        return;
    }

    submitting.value = true;
    try {
        const params = buildPlotPayload(includeEquipment);
        console.log("entry submit params", params);
        // const res = await VE_API.entry.addPlotInfo(params);
        // if (res.code === 200) {
        //     ElMessage.success(res.msg || "提交成功");
        //     clearEntrySession();
        //     emit("confirm", params);
        // } else {
        //     ElMessage.error(res.msg || "提交失败，请稍后再试");
        // }

        showSuccessPopup.value = true;
        clearEntrySession();
    } catch (error) {
        console.error("entry submit failed", error);
        ElMessage.error("提交失败");
    } finally {
        submitting.value = false;
    }
}

const handleComplete = () => {
    showSuccessPopup.value = false;
    emit("confirm");
};

const handleSkip = () => {
    if (!props.isLastStep) {
        emit("next");
        return;
    }
    submitEntry(false);
};

const handleSubmit = () => {
    saveSelectionDraft();
    if (!props.isLastStep) {
        emit("next");
        return;
    }
    submitEntry(true);
};

onMounted(() => {
    fetchEquipmentList();
    restoreSelection();
});
</script>

<style lang="scss" scoped>
.select-equipment {
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    &__content {
        flex: 1;
        min-height: 0;
        overflow-y: auto;
        -webkit-overflow-scrolling: touch;
        padding: 8px 16px 80px;
    }

    .page-header {
        padding: 8px 4px 16px;

        .page-title {
            font-size: 26px;
            color: #005599;
            font-family: "PangMenZhengDao";
            line-height: 36px;
        }

        .page-subtitle {
            margin-top: 4px;
            font-size: 14px;
            color: rgba(46, 46, 46, 0.4);
            line-height: 20px;
        }
        .text-tip {
            font-size: 20px;
        }
    }

    .toolbar {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-bottom: 12px;
    }

    .search-bar {
        flex: 1;
        min-width: 0;
        display: flex;
        align-items: center;
        height: 36px;
        padding: 0 12px;
        background: rgba(255, 255, 255, 0.5);
        border: 1px solid rgba(33, 153, 248, 0.5);
        border-radius: 6px;
        box-sizing: border-box;

        .search-icon {
            color: rgba(0, 0, 0, 0.35);
            font-size: 16px;
            margin-right: 6px;
            flex-shrink: 0;
        }

        .search-input {
            flex: 1;
            min-width: 0;
            border: none;
            outline: none;
            background: transparent;
            font-size: 14px;
            color: #333;

            &::placeholder {
                color: rgba(0, 0, 0, 0.3);
            }
        }

        .search-btn {
            flex-shrink: 0;
            padding-left: 10px;
            color: #2199f8;
            font-size: 14px;
            cursor: pointer;
        }
    }

    .add-btn {
        flex-shrink: 0;
        height: 36px;
        padding: 0 12px;
        border-radius: 6px;
        background: #2199f8;
        color: #fff;
        font-size: 14px;
        line-height: 36px;
        white-space: nowrap;
        cursor: pointer;
    }

    .equipment-card {
        background: #fff;
        border-radius: 12px;
        padding: 14px 12px 16px;
        margin-bottom: 12px;
    }

    .section-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 4px;
        font-size: 16px;
        font-weight: 500;
        color: #1a1a1a;

        .title-icon {
            width: 15px;
            height: 15px;
            object-fit: contain;
            flex-shrink: 0;
        }
    }

    .section-desc {
        margin: -2px 0 2px 22px;
        font-size: 12px;
        color: rgba(0, 0, 0, 0.4);
        line-height: 18px;
    }

    .tag-group {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 0 8px;
        font-size: 14px;

        .tag-item {
            margin-top: 10px;
            position: relative;
            border-radius: 6px;
            box-sizing: border-box;
            height: 36px;
            text-align: center;
            line-height: 36px;
            cursor: pointer;
            color: #000;
            background: #f3f4f6;
            border: 1px solid transparent;

            .text {
                display: inline-block;
                max-width: 100%;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                vertical-align: top;
                padding: 0 6px;
            }

            &.selected {
                border: 1px solid #2199f8;
                background: #e8f5ff;
                color: #2199f8;

                &::after {
                    content: "";
                    position: absolute;
                    z-index: 9;
                    top: -1px;
                    right: -1px;
                    width: 18px;
                    height: 14px;
                    background: url("@/assets/img/home/checked-bg-top.png") no-repeat bottom right / 18px 13px;
                }
            }
        }
    }

    .empty-tip {
        padding: 40px 0;
        text-align: center;
        color: rgba(0, 0, 0, 0.35);
        font-size: 14px;
    }

    .custom-bottom-fixed-btns {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
        gap: 10px;
        padding: 12px 12px 0;
        height: 80px;
        background: #fff;
        box-sizing: border-box;
        box-shadow: 2px 2px 5px 0 rgba(0, 0, 0, 0.4);
        .btns-l {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .bottom-btn {
            padding: 0 30px;
            height: 40px;
            line-height: 40px;
            box-sizing: border-box;
            font-size: 14px;
            border-radius: 25px;
            text-align: center;
            white-space: nowrap;

            &.disabled {
                opacity: 0.6;
                pointer-events: none;
            }
        }

        .secondary-btn {
            padding: 0 26px;
            color: #2199f8;
            background: #fff;
            border: 1px solid #2199f8;
        }

        .primary-btn {
            background: #2199f8;
            color: #fff;
        }
    }

    &.is-service-equipment {
        .page-subtitle {
            font-size: 16px;
            font-weight: 600;
            color: #005599;
            line-height: 22px;
        }

        .tag-item {
            height: auto;
            min-height: 36px;
            padding: 6px 4px;
            display: flex;
            align-items: center;
            justify-content: center;
            line-height: 16px;

            .text {
                display: block;
                white-space: normal;
                overflow: visible;
                text-overflow: unset;
                font-size: 13px;
                line-height: 16px;
                padding: 0 4px;
                word-break: break-all;
            }
        }
    }
}
</style>
