<template>
    <Popup v-model:show="show" class="problem-reminder-popup">
        <div class="problem-reminder">
            <!-- 标题区域 -->
            <div class="problem-reminder-header">
                <div class="title-section">
                    <div class="main-title">填写以下问题</div>
                    <div class="sub-title">为您定制农事提醒</div>
                </div>
                <img class="header-icon" src="@/assets/img/home/file-icon.png" alt="" />
            </div>
            <div class="question-section-wrapper">
                <div class="question-text">请问 <span style="color: #2199f8;">{{ farmName }}</span> {{ questPopupData.quest }}</div>
                <div class="img">
                    <img :src="questPopupData.backgroundImage" alt="" />
                </div>
                <div class="options-section">
                    <span class="options-label">您可以选择</span>
                    <div class="options-buttons">
                        <div class="option-btn" @click="toUpload">拍照识别</div>
                        <div class="option-btn" @click="toPage" v-if="curRole == 0">咨询专家</div>
                    </div>
                </div>
            </div>
            <!-- 底部按钮区域 -->
            <div class="bottom-buttons">
                <div
                    v-for="(opt, idx) in bottomAnswerOptions"
                    :key="idx"
                    class="bottom-btn"
                    :class="{ 'yes-btn': isYesOption(opt), 'no-btn': !isYesOption(opt) }"
                    @click="onBottomOptionClick(opt)"
                >
                    {{ getOptionLabel(opt) }}
                </div>
            </div>
            <!-- <div class="forward-btn bottom-btn" v-if="curRole == 2" @click="handleForward">转发给客户</div> -->
        </div>
    </Popup>
    <Popup v-model:show="noShow" class="no-popup">
        <div class="no-popup-title">
            <span>感谢您的配合</span>
            <div class="no-popup-title-sub">飞鸟将会记录下您当前的农场情况</div>
        </div>
        <div class="no-popup-btn" @click="noShow = false">我知道了</div>
    </Popup>
    <!-- 农事信息弹窗 -->
    <detail-dialog ref="detailDialogRef" showSuccessOnly @triggerFarmWork="triggerFarmWork" @noPopupBtn="noPopupBtn"></detail-dialog>
    <!-- 新增：激活上传弹窗 -->
    <active-upload-popup ref="activeUploadPopupRef" @handleUploadSuccess="handleUploadSuccess"></active-upload-popup>
</template>
<script setup>
import { Popup } from "vant";
import { ref,onActivated } from "vue";
import wx from "weixin-js-sdk";
import { base_img_url2 } from "@/api/config";
import activeUploadPopup from "@/components/popup/activeUploadPopup.vue";
import detailDialog from "@/components/detailDialog.vue";
import eventBus from "@/api/eventBus";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
const router = useRouter();

const show = ref(false);
const noShow = ref(false);
const dropdownGardenItem = ref({
    organId: 93490,
    periodId: 1,
    wktVal: "wktVal",
    address: "address",
    district: "district",
    name: "荔博园",
});
const toUpload = () => {
    if(curRole == 0){
        wx.miniProgram.navigateTo({
            url: `/pages/subPages/carmera/index?gardenData=${JSON.stringify(dropdownGardenItem.value)}`,
        });
    }else{
        ElMessage.warning("该功能正在升级中，敬请期待");
    }
};

function toPage() {
    const expertId = sessionStorage.getItem('expertId');
    if(expertId){
        router.push(`/chat_frame?userId=${expertId}`);
    }else{
        ElMessage.warning("专家信息不存在，请联系管理员");
    }
}
const detailDialogRef = ref(null);

const curRole = localStorage.getItem("SET_USER_CUR_ROLE");

const farmName = ref('');
const farmIdVal = ref(null);

onActivated(() => {
    if(curRole == 0){
        if(localStorage.getItem('selectedFarmId')){
            farmIdVal.value = localStorage.getItem('selectedFarmId');
            fetchQuestPopup();
        }
    }else{
        fetchQuestPopup();
    }
});


const questPopupData = ref({});
const bottomAnswerOptions = ref([]);
//弹出问卷接口
const fetchQuestPopup = () => {
    const api = curRole == 0 ? VE_API.home.fetchQuestPopup({ farmId: farmIdVal.value }) : VE_API.home.popupByAgriculturalUserFarms();
    api.then(({ data }) => {
        if (Array.isArray(data) && data.length > 0) {
            show.value = true;
            farmName.value = data[0].farm?.name;
            farmIdVal.value = data[0].farm?.id;
            questPopupData.value = data[0];
            bottomAnswerOptions.value = transformAnswerOptions(questPopupData.value?.answerOptions);
        }
    })
    .catch(() => {});
};

function transformAnswerOptions(raw) {
    let parsed = raw;
    if (typeof raw === "string") {
        try {
            parsed = JSON.parse(raw);
        } catch (e) {
            parsed = [raw];
        }
    }
    if (Array.isArray(parsed)) {
        return parsed.map((item) => {
            if (item && typeof item === "object") {
                const label = item.name;
                const value = item.value;
                return { label, value };
            }
            return { label: String(item), value: item };
        });
    }
    return [];
}

function getOptionLabel(opt) {
    return opt?.label ?? String(opt ?? "");
}

function isYesOption(opt) {
    const label = (opt?.label ?? "").toString();
    const value = opt?.value;
    if (typeof value === "boolean") return value === true;
    if (typeof value === "number") return value === 1;
    if (typeof value === "string") {
        const v = value.trim().toLowerCase();
        if (v === "1" || v === "true" || v === "yes") return true;
    }
    const yesKeywords = ["是", "yes", "确认", "同意", "有", "发生"];
    return yesKeywords.some((k) => label.toLowerCase().includes(k.toLowerCase()));
}

const optValue = ref(null);
function onBottomOptionClick(opt) {
    show.value = false;
    optValue.value = opt.value;
    if (opt.value == 1) {
        eventBus.emit("activeUpload:show", {
            gardenIdVal: farmIdVal.value,
            arrangeIdVal: questPopupData.value.arrangeId,
            problemTitleVal: `请选择您出现${questPopupData.value.phenologyName}的时间`,
            typeVal: "question",
        });
    } else {
        saveQuestPopup(opt.label);
    }
}

function saveQuestPopup(label) {
    const agriDate = getTodayStr();
    const params = {
        farmId: farmIdVal.value,
        phenologyId: questPopupData.value.phenologyId,
        indicatorId: questPopupData.value.indicatorId,
        answerValue: optValue.value,
        agriDate: agriDate,
    };
    params.imagePaths = images.value;
    VE_API.home.saveQuestPopup(params).then((res) => {
        if (res.code === 0) {
            show.value = false;
            if (optValue.value != 1 && label != '未知') {
                noShow.value = true;
            }
        }
    });
}

function getTodayStr() {
    const d = new Date();
    const y = d.getFullYear();
    const m = String(d.getMonth() + 1).padStart(2, "0");
    const day = String(d.getDate()).padStart(2, "0");
    return `${y}-${m}-${day}`;
}
const images = ref([]);
const currentParams = ref({});
function handleUploadSuccess(params) {
    currentParams.value = params;
    images.value = params.imagePaths;
    detailDialogRef.value.showDialog(questPopupData.value.farmWorkLibId, "转发");
}

const activeUploadPopupRef = ref(null);
function triggerFarmWork() {
    activeUploadPopupRef.value.triggerFarmWork(currentParams.value);
    saveQuestPopup();
}

// 获取触发图片
const triggerImg = ref([]);
const getTriggerImg = async () => {
    const { data } = await VE_API.z_farm_work_record.getTriggerImg({ farmWorkRecordId: questPopupData.value.id });
    triggerImg.value = data || [];
}
const noPopupBtn = async () => {
    // await getTriggerImg();
    // const query = {
    //     askInfo: { title: "分享农事", content: "是否分享该农事给好友" },
    //     shareText: `您的农事要做${questPopupData.value.farm}了 请查看！`,
    //     id: questPopupData.value?.farmWorkLibId,
    //     farmWorkOrderId: questPopupData.value?.farm?.orderId,
    //     postImg: triggerImg.value.length ? base_img_url2 + triggerImg.value[triggerImg.value.length - 1].cloudFilename : ''
    // };
    // wx.miniProgram.navigateTo({
    //     url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=priceSheet`,
    // });
};

const handleForward = () => {
    // noPopupBtn();
};

</script>
<style lang="scss" scoped>
.problem-reminder-popup {
    width: 100%;
    border-radius: 14px;
    padding: 20px 15px;
    box-sizing: border-box;
    background-image: linear-gradient(180deg, #d1e7fd 0%, #ffffff 25%);
    .problem-reminder {
        display: flex;
        flex-direction: column;
        // 标题区域样式
        .problem-reminder-header {
            display: flex;
            justify-content: space-between;
            align-items: flex-start;
            gap: 15px;

            .title-section {
                flex: 1;
                font-size: 22px;
                color: #1d1e1f;
                line-height: 1.2;
                div {
                    font-family: "PangMenZhengDao";
                }
            }

            .header-icon {
                width: 88px;
                height: 88px;
                margin-top: -10px;
                margin-right: -5px;
            }
        }
        .question-section-wrapper {
            border: 1px solid #ececec;
            border-radius: 8px;
            padding: 10px 8px;
            margin-top: -10px;
            background-color: #fff;
            .question-text {
                font-size: 16px;
                color: #252525;
                font-weight: 500;
            }
            .img {
                margin: 12px 0;
                width: 100%;
                height: 140px;
                img {
                    width: 100%;
                    height: 100%;
                    border-radius: 6px;
                    object-fit: cover;
                }
            }
            .options-section {
                display: flex;
                align-items: center;
                justify-content: space-between;
                background-color: rgba(33, 153, 248, 0.1);
                border-radius: 8px;
                padding: 7px 8px;
                font-weight: 500;
                .options-label {
                    font-size: 14px;
                    color: #2199f8;
                }

                .options-buttons {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 10px;
                    .option-btn {
                        padding: 5px 14px;
                        border-radius: 20px;
                        background: #fff;
                        color: #252525;
                        flex: 1;
                    }
                }
            }
        }
        // 底部按钮区域样式
        .bottom-buttons {
            display: flex;
            gap: 12px;
            margin-top: 10px;
        }
        .forward-btn{
            margin-top: 10px;
        }
        .bottom-btn {
            flex: 1;
            padding: 8px 0;
            border-radius: 25px;
            font-size: 16px;
            text-align: center;
            background: #fff;
            border: 1px solid #e5e5e5;

            &.yes-btn {
                background-image: linear-gradient(180deg, #76c3ff 0%, #2199f8 100%);
                color: #fff;
                border: none;
            }
        }
    }
}

.no-popup {
    width: 76%;
    border-radius: 14px;
    padding: 28px 15px 20px;
    box-sizing: border-box;
    .no-popup-title {
        font-size: 24px;
        font-weight: 500;
        text-align: center;
        .no-popup-title-sub {
            font-size: 16px;
            margin-top: 8px;
        }
    }
    .no-popup-btn {
        background-color: #2199f8;
        padding: 8px;
        border-radius: 20px;
        color: #fff;
        font-size: 16px;
        margin-top: 32px;
        text-align: center;
    }
}
</style>
