<template>
    <div class="plan-page">
        <custom-header :name="pageType === 'plant' ? '种植方案' : '农事规划'"></custom-header>
        <div class="plan-content">
            <div class="plan-content-header" v-if="pageType === 'plant'">
                <el-select class="select-item" v-model="value" placeholder="选择品类">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <tab-list type="light" v-model="active" :tabs="tabs" @change="handleTabChange" />
            </div>
            <farm-work-plan-timeline
                class="timeline-container"
                :class="{
                    'timeline-container-plant': pageType == 'plant',
                    'timeline-container-no-permission': !hasPlanPermission
                }"
                :pageType="pageType"
                :farmId="route.query.farmId"
                @row-click="handleRowClick"
                @edit="handleEdit"
                :disableClick="!hasPlanPermission"
            />
        </div>
        <div class="custom-bottom-fixed-btns" v-has-permission="'农事规划'">
            <div class="bottom-btn-group">
                <div class="bottom-btn secondary-btn" @click="handlePhenologySetting">物候期设置</div>
                <div class="bottom-btn secondary-btn" v-if="pageType === 'plant'" @click="openCopyPlanPopup">
                    {{ active === 1 ? "复制方案" : "方案设置" }}
                </div>
            </div>
            <div class="bottom-btn primary-btn" @click="addNewTask">新增农事</div>
        </div>
    </div>
    <!-- 农事信息弹窗 -->
    <detail-dialog ref="detailDialogRef" @triggerFarmWork="triggerFarmWork"></detail-dialog>
    <!-- 互动设置弹窗 -->
    <interact-popup
        ref="interactPopupRef"
        @handleSaveSuccess="getFarmWorkPlanForPhenology"
        @handleDeleteInteract="handleDeleteInteract"
    ></interact-popup>
    <!-- 复制方案弹窗 -->
    <Popup v-model:show="showCopyPlan" class="copy-plan-popup" round closeable :close-on-click-overlay="false">
        <div class="copy-plan-content">
            <div class="label">{{ active === 1 ? "复制为" : "方案名称" }}</div>
            <el-input v-model="copyPlanName" size="large" placeholder="请输入方案名称" class="copy-plan-input" />
        </div>
        <div class="copy-plan-footer">
            <div class="btn btn-cancel" @click="handleCancelCopyPlan">{{ active === 1 ? "取消复制" : "删除方案" }}</div>
            <div class="btn btn-confirm" @click="handleConfirmCopyPlan">
                {{ active === 1 ? "确定复制" : "确定设置" }}
            </div>
        </div>
    </Popup>
    <!-- 物候期设置弹窗 -->
    <Popup
        v-model:show="showPhenologySetting"
        class="copy-plan-popup phenology-popup"
        round
        closeable
        :close-on-click-overlay="false"
    >
        <div class="phenology-header">物候期时间设置</div>
        <div class="phenology-list">
            <div
                class="phenology-item"
                v-for="(item, index) in mergedReproductiveList"
                :key="item.id || index"
            >
                <div class="item-label">
                    <span class="label-text">{{ item.name }}</span>
                    <span>起始时间</span>
                </div>
                <div class="item-value">
                    <el-date-picker
                        style="width: 100%"
                        size="large"
                        value-format="YYYY-MM-DD"
                        v-model="item.startDate"
                        type="date"
                        placeholder="选择日期"
                    />
                </div>
            </div>
        </div>
        <div class="phenology-footer" @click="handleConfirmPhenologySetting">确认设置</div>
    </Popup>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { Popup } from "vant";
import customHeader from "@/components/customHeader.vue";
import tabList from "@/components/pageComponents/TabList.vue";
import FarmWorkPlanTimeline from "@/components/pageComponents/FarmWorkPlanTimeline.vue";
import { useRouter, useRoute } from "vue-router";
import detailDialog from "@/components/detailDialog.vue";
import eventBus from "@/api/eventBus";
import interactPopup from "@/components/popup/interactPopup.vue";
import { ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute();

// 检查是否有"农事规划"权限
const hasPlanPermission = computed(() => {
    try {
        const userInfoStr = localStorage.getItem("localUserInfo");
        if (!userInfoStr) return false;
        const userInfo = JSON.parse(userInfoStr);
        const permissions = userInfo.agriculturalPermissions || [];
        return permissions.includes("农事规划");
    } catch (error) {
        console.error("解析用户信息失败:", error);
        return false;
    }
});

const active = ref(1);
const tabs = ref([
    {
        id: 1,
        name: "标准化方案",
    },
    {
        id: 2,
        name: "全托管方案",
    },
    {
        id: 3,
        name: "半托管方案",
    },
]);
const handleTabChange = (id, item) => {
    active.value = id;
    console.log(id, item);
};

const value = ref("1");
const options = ref([
    {
        value: "1",
        label: "荔枝",
    },
    {
        value: "2",
        label: "全托管方案",
    },
]);

const pageType = ref("");
onMounted(() => {
    pageType.value = route.query.pageType || "";
    getFarmWorkPlanForPhenology();
});

const mergedReproductiveList = ref([]);
const containerSpaceTimeId = ref(null);

const getPhenologyList = async (containerSpaceTimeIdVal) => {
    if (!containerSpaceTimeIdVal) return;
    const res = await VE_API.monitor.listPhenology({
        containerSpaceTimeId: containerSpaceTimeIdVal,
        farmId: route.query.farmId,
    });
    if (res.code === 0) {
        mergedReproductiveList.value = res.data || [];
    }
};

// 获取农事规划数据以获取 containerSpaceTimeId
const getFarmWorkPlanForPhenology = async () => {
    try {
        const { data, code } = await VE_API.monitor.farmWorkPlan({
            farmId: route.query.farmId,
        });
        if (code === 0 && data?.phenologyList?.[0]?.containerSpaceTimeId) {
            containerSpaceTimeId.value = data.phenologyList[0].containerSpaceTimeId;
            await getPhenologyList(containerSpaceTimeId.value);
        }
    } catch (error) {
        console.error("获取农事规划数据失败:", error);
    }
};

// 复制方案弹窗相关
const showCopyPlan = ref(false);
const showPhenologySetting = ref(false);
const copyPlanName = ref("");
const openCopyPlanPopup = () => {
    copyPlanName.value = "";
    showCopyPlan.value = true;
};

// 物候期设置弹窗
const handlePhenologySetting = () => {
    showPhenologySetting.value = true;
};

/**
 * 确认物候期设置
 */
const handleConfirmPhenologySetting = async () => {
    console.log(mergedReproductiveList.value);
    const params = {
        farmId: route.query.farmId,
        items: mergedReproductiveList.value.map((item) => ({
            phenologyId: item.id,
            startDate: item.startDate,
        })),
    };
    const res = await VE_API.monitor.batchSaveFarmPhenologyTime(params);
    if (res.code === 0) {
        ElMessage.success("设置成功");
        showPhenologySetting.value = false;
        getFarmWorkPlanForPhenology();
    }
};
// 取消复制方案
const handleCancelCopyPlan = () => {
    showCopyPlan.value = false;
};

// 确定复制方案
const handleConfirmCopyPlan = () => {
    if (!copyPlanName.value.trim()) {
        ElMessage.warning("请输入方案名称");
        return;
    }
    // TODO: 在此处调用复制方案的接口
    ElMessage.success("复制成功");
    showCopyPlan.value = false;
};


// 新增农事
const addNewTask = () => {
    ElMessage.warning("该功能正在升级中，敬请期待");
};

const triggerFarmWork = () => {
    eventBus.emit("activeUpload:show", {
        gardenIdVal: route.query.farmId,
        problemTitleVal: "请选择您出现" + curFarmObj.value.farmWorkName + "的时间",
        arrangeIdVal: curFarmObj.value.id,
        needExecutorVal: true,
    });
};

const curFarmObj = ref({});
const handleRowClick = (item) => {
    curFarmObj.value = item;
    router.push({
        path: "/modify",
        query: { id: item.id, farmId: route.query.farmId, farmWorkId: item.farmWorkId, containerSpaceTimeId: item.containerSpaceTimeId, agriculturalStoreId: route.query.agriculturalStoreId },
    });
};

const interactPopupRef = ref(null);

const handleEdit = (item) => {
    console.log(item);
    if (interactPopupRef.value) {
        interactPopupRef.value.showPopup(item);
    }
};

const handleDeleteInteract = (params) => {
    getFarmWorkPlanForPhenology();
};
</script>

<style scoped lang="scss">
.plan-page {
    width: 100%;
    height: 100vh;
    background: #f5f7fb;
    .plan-content {
        padding: 12px 0;
        .plan-content-header {
            display: flex;
            align-items: center;
            gap: 12px;
            margin-bottom: 10px;
            margin-left: 12px;
            .select-item {
                width: 82px;
                ::v-deep {
                    .el-select__wrapper {
                        box-shadow: none;
                        border-radius: 25px;
                        border: 0.5px solid rgba(153, 153, 153, 0.5);
                    }
                }
            }
        }

        .timeline-container {
            height: calc(100vh - 40px - 73px);
            padding: 0 12px;
            &.timeline-container-plant {
                height: calc(100vh - 40px - 73px - 38px);
            }
            &.timeline-container-plant {
                height: calc(100vh - 40px - 38px);
            }
            // 没有权限时，底部按钮不显示，高度增加 73px
            &.timeline-container-no-permission {
                height: calc(100vh - 40px - 58px);
            }
        }
    }
    // 控制区域样式
    .custom-bottom-fixed-btns {
        .bottom-btn-group {
            display: flex;
            gap: 12px;
        }
    }
}
.copy-plan-popup {
    width: 100%;
    padding: 50px 12px 20px 12px;
    &::before {
        content: "";
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 136px;
        background: url("@/assets/img/monitor/popup-header-bg.png") no-repeat center center / 100% 100%;
    }
    .copy-plan-content {
        display: flex;
        align-items: center;
        gap: 12px;
        .label {
            font-size: 16px;
            font-weight: 500;
        }
        .copy-plan-input {
            width: calc(100% - 80px);
        }
    }
    .copy-plan-footer {
        display: flex;
        gap: 12px;
        margin-top: 20px;
        .btn {
            flex: 1;
            color: #666666;
            border: 1px solid #999999;
            border-radius: 25px;
            padding: 10px 0;
            font-size: 16px;
            text-align: center;
            &.btn-confirm {
                color: #fff;
                border: 1px solid #2199f8;
                background: #2199f8;
            }
        }
    }
}

.phenology-popup {
    padding: 28px 20px 20px;
    .phenology-header {
        font-size: 24px;
        text-align: center;
        margin-bottom: 20px;
        font-family: "PangMenZhengDao";
    }
    .phenology-list {
        width: 100%;
        .phenology-item {
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: space-between;
            .item-label {
                display: flex;
                align-items: center;
                gap: 4px;
                font-size: 15px;
                color: rgba(0, 0, 0, 0.4);
                .label-text {
                    color: #000;
                    font-size: 16px;
                    font-weight: 500;
                }
            }
            .item-value {
                width: calc(100% - 156px);
            }
        }
        .phenology-item + .phenology-item {
            margin-top: 10px;
        }
    }
    .phenology-footer{
        width: 100%;
        text-align: center;
        font-size: 16px;
        margin-top: 20px;
        color: #fff;
        background: #2199f8;
        border-radius: 25px;
        padding: 10px 0;
    }
}
</style>
