<template>
    <div class="farm-card-page">
        <custom-header name="种植方案"></custom-header>
        <div class="system-generated">
            <div class="tip-box">
                <el-icon size="18"><CircleCheckFilled /></el-icon>
                <span>系统已生成多套方案，请选择最佳方案</span>
            </div>
            <tab-list
                type="light"
                v-model="active"
                :tabs="tabs"
                @change="handleTabChange"
                class="tabs-list"
            />
            <farm-work-plan-timeline
                class="timeline-wrap"
                pageType="plant"
                :containerId="containerId"
                :disableClick="true"
            />
        </div>
    </div>
    <div class="custom-bottom-fixed-btns">
        <div class="bottom-btn primary-btn" @click="handleConfirmPlan">确认方案</div>
    </div>

    <tip-popup
        v-model:show="showFarmPopup"
        type="success"
        text="农场创建成功"
        buttonText="分享微信"
        @confirm="handleShareFarm"
        @handleClickOverlay="handleClickOverlay"
    />
</template>

<script setup>
import customHeader from "@/components/customHeader.vue";
import { onActivated, ref, onDeactivated } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Tab, Tabs } from "vant";
import FarmWorkPlanTimeline from "@/components/pageComponents/FarmWorkPlanTimeline.vue";
import wx from "weixin-js-sdk";
import tabList from "@/components/pageComponents/TabList.vue";
import tipPopup from "@/components/popup/tipPopup.vue";
import { ElMessage } from "element-plus";

const router = useRouter();
const route = useRoute();

const tabs = ref([]);
const active = ref(null);
const containerId = ref(null);
const handleTabChange = (id, item) => {
    containerId.value = item.containerId;
    active.value = id;
};

onActivated(() => {
    containerId.value = route.query.containerId;
    getListMySchemes();
});

onDeactivated(() => {
    active.value = null;
    containerId.value = null;
});

const getListMySchemes = () => {
    VE_API.home.listMySchemes({containerId: route.query.containerId}).then(({ data }) => {
        if (data.length) {
            tabs.value = data || [];
            const index = data.findIndex((item) => item.containerId == route.query.containerId);
            active.value = route.query.schemeId || data[index].id;
            containerId.value = route.query.containerId;
        }
    });
};

const showFarmPopup = ref(false);
const shareData = ref({});
const handleConfirmPlan = () => {
    // 从路由参数中获取农场数据
    let geomValue = route.query.geom;

    // 处理 geom 参数，可能是 JSON 字符串或数组
    if (typeof geomValue === "string") {
        try {
            // 尝试解析 JSON 字符串
            const parsed = JSON.parse(geomValue);
            if (Array.isArray(parsed)) {
                geomValue = parsed;
            }
        } catch (e) {
            // 如果不是 JSON 字符串，保持原值
            console.warn("geom 参数解析失败，使用原值:", e);
        }
    }

    const farmParams = {
        ...route.query,
        containerId: containerId.value,
        schemeId: active.value,
        geom: geomValue,
        defaultFarm: Boolean(route.query.defaultFarm),
        agriculturalCreate: route.query.agriculturalCreate * 1,
    };

    // 验证必填字段
    if (
        !farmParams.wkt ||
        !farmParams.speciesId ||
        !farmParams.containerId ||
        !farmParams.address ||
        !farmParams.mu ||
        !farmParams.name ||
        !farmParams.fzr ||
        !farmParams.tel
    ) {
        ElMessage.error("农场信息不完整，请返回重新填写");
        return;
    }

    delete farmParams.from;
    // 调用创建农场接口
    VE_API.farm
        .saveFarm(farmParams)
        .then((res) => {
            if (res.code === 0) {
                shareData.value = res.data;
                ElMessage.success("创建成功");
                setTimeout(() => {
                    handleClickOverlay();
                }, 1000);
            } else {
                ElMessage.error(res.msg || "创建失败");
            }
        })
        .catch((err) => {
            console.error("创建农场失败:", err);
            ElMessage.error("创建失败，请稍后重试");
        });
};

const handleShareFarm = () => {
    const query = {
        agriculturalStoreId: shareData.value.agriculturalStoreId,
        farmId: shareData.value.id,
        speciesName: route.query.speciesName,
        containerId: shareData.value.containerId,
    };
    wx.miniProgram.navigateTo({
        url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=shareFarm`,
    });
};

const handleClickOverlay = () => {
    // 根据 from 参数跳转回原页面
    const fromPage = route.query.from;
    if (fromPage) {
        router.replace(`/${fromPage}`);
    } else {
        // 如果没有 from 参数，默认跳转到首页
        router.replace("/home");
    }
};
</script>

<style scoped lang="scss">
.farm-card-page {
    width: 100%;
    height: 100vh;
    background: #f5f7fb;
    .system-generated {
        padding: 17px 10px 10px;
        height: calc(100vh - 150px);
        .tip-box {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 10px;
            background: rgba(33, 153, 248, 0.1);
            border-radius: 8px;
            color: #2199f8;
            box-sizing: border-box;
            margin-bottom: 10px;
            span {
                margin-left: 5px;
            }
        }
        .tabs-list {
            margin-bottom: 10px;
        }
        .timeline-wrap{
            height: calc(100vh - 150px - 50px);
        }
    }
    .tabs-wrap {
        ::v-deep {
            .van-tabs__line {
                width: 24px;
                height: 4px;
            }
            .van-tab {
                width: 100px;
                flex: none;
            }
            .van-tabs__nav {
                justify-content: center;
            }
        }
    }
}
.custom-bottom-fixed-btns {
    justify-content: center;
    .bottom-btn {
        padding: 10px 40px;
    }
}
</style>
