<template>
    <div class="warning-detail">
        <custom-header name="查看详情" :isClose="route.query.miniJson ? true : false"></custom-header>
        <div class="article-content" :class="{ 'is-link': isLink }">
            <div class="article-header">
                <div class="title">{{ warningDetail.title }}</div>
                <div class="author-info">
                    <el-avatar :size="16" :src="warningDetail.icon" />
                    <span class="author-name">{{ warningDetail.name }}</span>
                    <span class="qa-date">{{
                        warningDetail?.createTime && warningDetail?.createTime?.slice(0, 10)
                    }}</span>
                </div>
            </div>

            <div class="article-image" v-if="showImage">
                <img :src="warningDetail?.media && warningDetail?.media[0]" alt="荔枝开花图片" />
            </div>

            <div class="article-box" v-if="pageParams.questTitle">
                <div class="box-top">
                    <img class="icon" src="@/assets/img/home/ask-icon.png" alt="" />
                    <div class="title">{{ pageParams.questTitle }}</div>
                </div>
                <div class="answer-text" v-if="pageParams.answer != null">
                    <span v-if="pageParams.answer == 0">答：暂未出现{{ pageParams.expectedRisk }}</span>
                    <template v-else>
                        <div>答：{{ pageParams.occurrenceTime }}已出现{{ pageParams.expectedRisk }}</div>
                        <div class="photo-img-wrap">
                            <photo-provider :photo-closable="true">
                                <photo-consumer
                                    v-for="(src, index) in pageParams.imagePaths"
                                    intro="风险照片"
                                    :key="index"
                                    :src="base_img_url2 + src"
                                >
                                    <div class="photo-img">
                                        <img :src="base_img_url2 + src + resize_300" />
                                    </div>
                                </photo-consumer>
                            </photo-provider>
                        </div>
                    </template>
                </div>
                <div v-else class="box-bottom" :style="{ justifyContent: !isLink ? 'center' : 'flex-end' }">
                    <template v-if="!isLink"> 
                        <div v-has-permission="'农事规划'" class="edit-btn" @click="handleEditQuestion">编辑问题</div>
                    </template>
                    <template v-else>
                        <div class="edit-btn" @click="handleAnswerClick(0)">否</div>
                        <div class="edit-btn primary-btn" @click="handleAnswerClick(1)">是</div>
                    </template>
                </div>
            </div>

            <div class="photo-img-wrap-container" v-if="cropAlbum.length">
                <div class="photo-img-wrap-title">
                    <div class="title-text">
                        <span>作物相册</span>
                        <span class="count">({{ cropAlbum.length }})</span>
                    </div>
                    <span class="more" @click="handleSeeMore">查看更多</span>
                </div>
                <div class="photo-img-wrap">
                    <photo-provider :photo-closable="true">
                        <photo-consumer
                            v-for="(src, index) in cropAlbum"
                            intro="执行照片"
                            :key="index"
                            :src="base_img_url2 + src.filename"
                        >
                            <div class="photo-img">
                                <img :src="base_img_url2 + src.filename + resize_300" />
                            </div>
                        </photo-consumer>
                    </photo-provider>
                </div>
            </div>

            <div class="article-text">
                <span v-html="warningDetail.content"></span>
            </div>

            <div class="custom-bottom-fixed-btns" v-if="!isLink">
                <div class="bottom-btn primary-btn" @click="showShareSheet = true">转发</div>
            </div>
        </div>
    </div>
    <active-upload-popup ref="activeUploadPopupRef" @handleUploadSuccess="handleUploadSuccess"></active-upload-popup>
    <fn-share-sheet v-model:show="showShareSheet" :options="shareOptions" @select="handleShareSelect" />

    <Popup v-model:show="showQuestionPopup" class="copy-plan-popup" round closeable :close-on-click-overlay="false">
        <div class="copy-plan-content">
            <div class="label">问题描述</div>
            <el-input
                v-model="interactionQuestion"
                size="large"
                placeholder="请输入问题描述"
                type="textarea"
                :rows="3"
                maxlength="35"
                show-word-limit
                class="copy-plan-input"
            />
        </div>
        <div class="copy-plan-footer">
            <div class="btn btn-cancel" @click="showQuestionPopup = false">取消修改</div>
            <div class="btn btn-confirm" @click="handleEdit">确认修改</div>
        </div>
    </Popup>
</template>

<script setup>
import customHeader from "@/components/customHeader.vue";
import { ref, onActivated, computed } from "vue";
import { base_img_url2, resize_300 } from "@/api/config";
import FnShareSheet from "@/components/pageComponents/FnShareSheet.vue";
import activeUploadPopup from "@/components/popup/activeUploadPopup.vue";
import { useRoute, useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { Popup } from "vant";
import wx from "weixin-js-sdk";

const showQuestionPopup = ref(false);
const handleEdit = () => {
    VE_API.monitor
        .updateFarmWorkArrange({
            id:pageParams.value.arrangeId,
            interactionQuestion: interactionQuestion.value,
        })
        .then((res) => {
            if (res.code === 0) {
                ElMessage.success("修改成功");
                showQuestionPopup.value = false;
                getAnswer();
                getWarningDetail();
            } else {
                ElMessage.error(res.message || "修改失败");
            }
        })
        .catch(() => {
            ElMessage.error("修改失败，请重试");
        })
        .finally(() => {
            showQuestionPopup.value = false;
        });
};
const interactionQuestion = ref("");

const route = useRoute();
const router = useRouter();
const showShareSheet = ref(false);
const shareOptions = ref([{ name: "微信", icon: "wechat", type: "wechat" }]);
const handleShareSelect = () => {
    const query = {
        askInfo: { title: "提醒客户", content: "是否分享该提醒给好友" },
        shareText: warningDetail.value.title,
        targetUrl: `warning_detail`,
        paramsPage: JSON.stringify(route.query),
        imageUrl: warningDetail.value.media[0],
    };
    wx.miniProgram.navigateTo({
        url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=sharePage`,
    });
};

const isLink = ref(true);
const warningDetail = ref({});
const showImage = ref(false);
const pageParams = ref({});

onActivated(() => {
    showImage.value = route.query.showImage === "true" ? true : false;
    isLink.value = localStorage.getItem("SET_USER_CUR_ROLE") == 2 ? false : true;
    // isLink.value = true;
    if (route.query.miniJson) {
        const miniJson = JSON.parse(route.query.miniJson);
        pageParams.value = JSON.parse(miniJson.paramsPage);
    } else {
        pageParams.value = route.query;
    }
    getAnswer();
    // 获取图片数据
    getFarmPhoto();
    getWarningDetail();
});

const getAnswer = () => {
    VE_API.farm
        .getFarmWorkArrangeDetail({
            id: pageParams.value.arrangeId,
        })
        .then((res) => {
            if (res.code === 0) {
                pageParams.value.answer = res.data.answer;
                pageParams.value.expectedRisk = res.data.expectedRisk;
                pageParams.value.imagePaths = res.data.imagePaths;
                pageParams.value.occurrenceTime = res.data.occurrenceTime;
                pageParams.value.questTitle = res.data.interactionQuestion;
            }
        });
};

const getWarningDetail = () => {
    const params = {
        id: pageParams.value.id,
    };
    VE_API.home.warningDetail(params).then((res) => {
        warningDetail.value = res.data || {};
    });
};

const activeUploadPopupRef = ref(null);
const handleAnswerClick = (value) => {
    if (value) {
        activeUploadPopupRef.value.showPopup({
            gardenIdVal: pageParams.value.farmId,
            problemTitleVal: pageParams.value.questTitle,
            typeVal: "question",
            arrangeIdVal: route.query.arrangeId,
        });
    } else {
        handleAnswer(0);
    }
};

const uploadParams = ref({});
const handleUploadSuccess = (data) => {
    uploadParams.value = {
        occurrenceTime: data.executeDate,
        imagePaths: data.imagePaths,
    };
    handleAnswer(1);
};

const handleAnswer = (value) => {
    VE_API.home
        .answerQuestion({
            ...uploadParams.value,
            arrangeId: pageParams.value.arrangeId,
            answer: value,
            farmId: pageParams.value.farmId,
        })
        .then((res) => {
            if (res.code === 0) {
                ElMessage.success("回答成功");
                getAnswer();
            }
        });
};

const cropAlbum = ref([]);
// 获取作物相册的三张照片（参考 patrolPhoto 的获取逻辑）
const getFarmPhoto = async () => {
    try {
        // 先获取有图片的日期列表
        const dateParams = {
            farmId: pageParams.value.farmId,
            pageIndex: 0,
            limit: 10,
        };
        const { data: dateData } = await VE_API.farm.findHasImagesDate(dateParams);
        const dateList = Array.isArray(dateData) ? dateData : [];
        if (!dateList.length) {
            cropAlbum.value = [];
            return;
        }

        const result = [];
        let dateIndex = 0;

        // 按日期依次取图片，直到凑够 3 张或没有更多日期
        while (result.length < 3 && dateIndex < dateList.length) {
            const currentDate = dateList[dateIndex];
            const imgParams = {
                farmId: pageParams.value.farmId,
                date: currentDate,
            };
            const { data } = await VE_API.farm.getImageInfo(imgParams);
            const images = data && Array.isArray(data.images) ? data.images : [];

            images.forEach((item) => {
                if (result.length < 3) {
                    // 统一存成 filename 字段，供模板使用
                    result.push({
                        ...item,
                        filename: item.resFilename || item.filename,
                    });
                }
            });

            dateIndex += 1;
        }

        cropAlbum.value = result;
    } catch (e) {
        console.error("获取农场相册失败", e);
        cropAlbum.value = [];
    }
};

const handleSeeMore = () => {
    router.push(`/farm_photo?farmId=${pageParams.value.farmId}`);
};

const handleEditQuestion = () => {
    interactionQuestion.value = pageParams.value.questTitle;
    showQuestionPopup.value = true;
};
</script>

<style scoped lang="scss">
.warning-detail {
    position: relative;
    width: 100%;
    height: 100vh;
    .article-content {
        padding: 8px 16px;
        overflow-y: auto;
        height: calc(100% - 40px - 60px);
        box-sizing: border-box;
        &.is-link {
            height: calc(100% - 40px);
        }
        .article-header {
            .title {
                font-size: 18px;
                font-weight: bold;
                margin-bottom: 6px;
                text-align: left;
            }

            .author-info {
                display: flex;
                align-items: center;
                gap: 10px;
                padding-bottom: 12px;
                border-bottom: 1px solid #f5f5f5;

                .author-name,
                .qa-date {
                    font-size: 14px;
                    color: #666;
                    font-weight: normal;
                }
            }
        }

        .article-image {
            width: 100%;
            margin: 12px 0 20px 0;

            img {
                width: 100%;
                height: 175px;
                border-radius: 5px;
                object-fit: cover;
            }
        }
        .article-text {
            ::v-deep {
                img {
                    width: 100%;
                    height: 175px;
                    border-radius: 5px;
                    object-fit: cover;
                }
            }
        }

        .photo-img-wrap-container {
            padding: 10px;
            border-radius: 5px;
            border: 1px solid rgba(233, 233, 233, 0.5);
            .photo-img-wrap-title {
                display: flex;
                align-items: center;
                justify-content: space-between;
                font-size: 16px;
                .title-text {
                    display: flex;
                    align-items: center;
                    gap: 4px;
                }
                .more {
                    color: rgba(0, 0, 0, 0.6);
                    font-size: 12px;
                }
            }
        }
        .photo-img-wrap {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            margin-top: 8px;
            ::v-deep {
                .PhotoConsumer {
                    width: 31%;
                    height: 92px;
                }
            }
            .photo-img {
                width: 100%;
                height: 100%;
                position: relative;
                box-sizing: border-box;
                border: 2px solid transparent;
                border-radius: 8px;
                overflow: hidden;
                img {
                    width: 100%;
                    height: 100%;
                    border-radius: 8px;
                    object-fit: cover;
                }
            }
        }

        .article-box {
            margin-bottom: 12px;
            border-radius: 8px;
            border: 1px solid #2199f8;
            padding: 10px;
            .box-top {
                display: flex;
                align-items: center;
                gap: 8px;

                .icon {
                    width: 20px;
                    height: 20px;
                }

                .title {
                    font-size: 16px;
                    font-weight: 600;
                }
            }
            .answer-text {
                color: #333333;
                margin-top: 6px;
            }
            .box-bottom {
                display: flex;
                justify-content: flex-end;
                gap: 10px;
                .edit-btn {
                    padding: 7px 20px;
                    background: rgba(33, 153, 248, 0.1);
                    color: #2199f8;
                    border-radius: 25px;
                    font-size: 12px;
                    text-align: center;
                    margin-top: 10px;
                    &.primary-btn {
                        background: #2199f8;
                        color: #fff;
                    }
                }
            }
        }
    }
    .custom-bottom-fixed-btns {
        justify-content: center;
        .primary-btn {
            padding: 10px 34px;
        }
    }
}

.copy-plan-popup {
    width: 100%;
    padding: 50px 12px 20px 12px;
    .copy-plan-content {
        display: flex;
        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;
            }
        }
    }
}
</style>
