<template>
    <div class="survey-entry-page">
        <custom-header :name="t('workExecute.surveyEntryTitle')" bgColor="#fff" />

        <div class="survey-entry-body">
            <div class="hero">
                <div class="hero-l">
                    <div class="hero__text">{{ t("workExecute.surveyEntryHint") }}</div>
                    <div class="hero__text">{{ t("workExecute.surveyEntryHint2") }}<span class="text-tip">（可多选）</span></div>
                </div>
                <img class="hero__illust" src="@/assets/img/agricultural/enter.png" alt="" />
            </div>

            <div class="search-bar">
                <el-icon class="search-bar__icon"><Search /></el-icon>
                <input
                    v-model="searchKeyword"
                    class="search-bar__input"
                    type="text"
                    :placeholder="t('workExecute.surveySearchPlaceholder')"
                    @keyup.enter="handleSearch"
                />
                <div class="search-bar__btn" @click="handleSearch">{{ t("workExecute.surveySearch") }}</div>
            </div>

            <div class="category-panel" v-loading="loading">
                <div v-for="group in displayGroups" :key="group.name" class="category-card">
                    <div class="section-title">
                        <span class="title-icon"></span>
                        <span>{{ group.name }}</span>
                    </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">
                    {{ t("workExecute.surveyNoMatch") }}
                </div>
            </div>
        </div>

        <div class="survey-entry-footer">
            <div class="submit-btn" @click="handleSubmit">{{ t("workExecute.surveySubmit") }}</div>
        </div>
    </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Search } from "@element-plus/icons-vue";
import customHeader from "@/components/customHeader.vue";
import { useI18n } from "@/i18n";

const { t } = useI18n();
const router = useRouter();

const SESSION_KEY = "SURVEY_SELECTED_WORK_TYPES";

const loading = ref(false);
const categoryGroups = ref([]);
const searchKeyword = ref("");
const appliedKeyword = ref("");
const selectedIds = reactive(new Set());

const DEFAULT_GROUPS = [
    {
        name: "建园与土壤管理",
        items: [
            { id: 101, name: "整地类" },
            { id: 102, name: "除草" },
            { id: 103, name: "清园" },
            { id: 104, name: "清沟修渠" },
        ],
    },
    {
        name: "肥水管理",
        items: [
            { id: 201, name: "根部肥" },
            { id: 202, name: "根部灌水" },
            { id: 203, name: "根部灌药" },
            { id: 204, name: "飞防叶面肥" },
            { id: 205, name: "叶面喷水" },
        ],
    },
    {
        name: "打药管理",
        items: [
            { id: 301, name: "飞防打药" },
            { id: 302, name: "内膛打药" },
        ],
    },
    {
        name: "树体管理",
        items: [
            { id: 401, name: "整形修剪" },
            { id: 402, name: "嫁接" },
            { id: 403, name: "环割环剥" },
        ],
    },
    {
        name: "花果管理",
        items: [
            { id: 501, name: "疏花疏果" },
            { id: 502, name: "果实套袋" },
        ],
    },
];

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

const allCategoryItems = computed(() =>
    categoryGroups.value.flatMap((group) => group.items)
);

const normalizeGroups = (list) => {
    if (!Array.isArray(list) || !list.length) return [];
    // 已是分组结构
    if (list[0]?.items) {
        return list
            .map((group, gIndex) => ({
                name: group.name || group.category_name || `分类${gIndex + 1}`,
                items: (group.items || group.list || [])
                    .map((item, index) => ({
                        id: item.id ?? item.type ?? item.code ?? `${gIndex}-${index + 1}`,
                        name: item.name || item.type_name || item.label || "",
                    }))
                    .filter((item) => item.name),
            }))
            .filter((group) => group.items.length);
    }
    // 扁平列表兜底：按 category / group 字段分组
    const map = new Map();
    list.forEach((item, index) => {
        const name = item.name || item.type_name || item.label || "";
        if (!name) return;
        const groupName = item.category_name || item.group_name || item.category || "其他";
        if (!map.has(groupName)) map.set(groupName, []);
        map.get(groupName).push({
            id: item.id ?? item.type ?? item.code ?? index + 1,
            name,
        });
    });
    return Array.from(map.entries()).map(([name, items]) => ({ name, items }));
};

const restoreSelection = () => {
    try {
        const raw = sessionStorage.getItem(SESSION_KEY);
        if (!raw) return;
        const ids = JSON.parse(raw).map((item) => String(item.id));
        ids.forEach((id) => selectedIds.add(id));
    } catch {
        // ignore
    }
};

const fetchCategories = async () => {
    loading.value = true;
    try {
        categoryGroups.value = DEFAULT_GROUPS;
        // const res = await VE_API.z_farm_work_record.getFarmWorkTypeList();
        // const groups = normalizeGroups(res?.data);
        // categoryGroups.value = groups.length ? groups : DEFAULT_GROUPS;
    } catch {
        categoryGroups.value = DEFAULT_GROUPS;
    } finally {
        loading.value = false;
    }
};

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

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

const handleSubmit = () => {
    const selected = allCategoryItems.value.filter((item) => selectedIds.has(String(item.id)));
    if (!selected.length) {
        ElMessage.warning(t("workExecute.surveyPleaseSelect"));
        return;
    }
    sessionStorage.setItem(SESSION_KEY, JSON.stringify(selected));
    ElMessage.success(t("workExecute.surveySubmitSuccess"));
    router.back();
};

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

<style lang="scss" scoped>
.survey-entry-page {
    height: 100vh;
    display: flex;
    flex-direction: column;
    // background: linear-gradient(90deg, #57B5FF 0%, #BBE1FF 11.5%, #F6F6F6 100%);
    background: linear-gradient(270deg, rgba(218, 195, 255, 0.59) 0%, #E6F2FF 0.01%, #8FC5FE 100%);

    // background: linear-gradient(180deg, #d7ecff 0%, #eaf5ff 42%, #f5f9fc 100%);
    overflow: hidden;
}

.survey-entry-body {
    padding: 0 10px;
    flex: 1;
    min-height: 0;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.hero {
    padding: 20px 0px;
    position: relative;

    &__text {
        flex: 1;
        min-width: 0;
        font-size: 19px;
        line-height: 24px;
        color: #005599;
        font-family: "PangMenZhengDao";
        &.text-tip {
            font-size: 16px;
        }
    }

    &__illust {
        position: absolute;
        top: 4px;
        right: 0px;
        width: 106px;
        height: auto;
        flex-shrink: 0;
    }
}

.search-bar {
    display: flex;
    align-items: center;
    height: 36px;
    margin-bottom: 10px;
    padding: 0 12px;
    border-radius: 10px;
    background: rgba(255, 255, 255, 0.5);
    backdrop-filter: blur(4px);
    border: 1px solid rgba(33, 153, 248, 0.5);
    // box-shadow: 0 2px 8px rgba(33, 153, 248, 0.12);
    box-sizing: border-box;

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

    &__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);
        }
    }

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

.category-panel {
    flex: 1;
    min-height: 0;
    overflow-y: auto;
    -webkit-overflow-scrolling: touch;
    padding-bottom: 8px;
}

.category-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: 600;
    color: #1a1a1a;

    .title-icon {
        position: relative;
        width: 14px;
        height: 14px;
        flex-shrink: 0;

        &::before,
        &::after {
            content: "";
            position: absolute;
            width: 10px;
            height: 10px;
            border-radius: 50%;
        }

        &::before {
            left: 0;
            top: 2px;
            background: #2199f8;
            opacity: 0.85;
        }

        &::after {
            right: 0;
            top: 0;
            background: #7ec8ff;
            opacity: 0.9;
        }
    }
}

.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: 48px 0;
    text-align: center;
    color: rgba(0, 0, 0, 0.35);
    font-size: 14px;
}

.survey-entry-footer {
    flex-shrink: 0;
    padding: 10px 16px 24px;
    background: #fff;
    box-shadow: 2px 2px 4.5px 0px rgba(0, 0, 0, 0.4);

    .submit-btn {
        margin: 0 auto;
        width: fit-content;
        padding: 0 30px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-radius: 25px;
        background: #2199f8;
        color: #fff;
    }
}
</style>
