<template>
    <div class="record-item">
        <div class="record-title">
            <!-- 内置标题模板 -->
            <div v-if="titleMode === 'default'" class="box-title">
                <div class="title-l">
                    {{ recordItemData.farmWorkName || recordItemData.name }}
                    <span class="parent-text" v-if="recordItemData.type || recordItemData.farmWorkType">
                        {{ getFarmTypeText(recordItemData.type || recordItemData.farmWorkType) }}
                    </span>
                </div>
                <!-- 按钮样式 -->
                <div
                    v-if="titleRightText && titleRightType !== 'dot'"
                    class="title-r title-r-button"
                    @click.stop="handleTitleRightClick(recordItemData)"
                >
                    {{ titleRightText }}
                </div>
                <!-- 点样式 -->
                <div v-if="titleRightDotText && titleRightType === 'dot'" class="title-r title-r-dot">
                    <span class="r-dot"></span>
                    {{ titleRightDotText }}
                </div>
            </div>
            <!-- 自定义标题插槽 -->
            <slot v-else name="title"></slot>
        </div>
        <!-- 服务详情模式的内容 -->
        <div v-if="contentMode === 'serviceDetail'" class="record-content service-detail-content">
            <div class="content-info">
                <div class="info-line">
                    药物处方：<span class="info-val">{{ getPrescriptionInfo(recordItemData) }}</span>
                </div>
                <div class="review-image" v-if="showFarmImage && recordItemData.executeEvidence.length">
                    <!-- <div class="image-wrapper" v-if="currentImageUrl">
                        <span class="image-label">执行照片</span>
                        <img :src="currentImageUrl" alt="" />
                    </div> -->
                    <div class="image-wrapper">
                        <span class="image-label">执行照片</span>
                        <img :src="base_img_url2 + recordItemData.executeEvidence[0]" alt="" />
                    </div>
                    <div class="image-wrapper">
                        <span class="image-label">执行照片</span>
                        <img :src="base_img_url2 + recordItemData.executeEvidence[1]" alt="" />
                    </div>
                </div>
            </div>
        </div>
        <!-- 自定义内容插槽 -->
        <slot name="content" v-else-if="showContent"></slot>
        <!-- 默认内容 -->
        <div class="record-content" v-else>
            <div class="info-item">
                推荐时间：
                <span class="info-val">{{ recordItemData?.executeDate || "--" }}</span>
            </div>
            <div
                class="info-item recipe-name"
                v-if="onlyRecipeName && recordItemData?.prescriptionList && recordItemData?.prescriptionList.length"
            >
                <span class="name-text">药物处方：</span>
                <div class="rescription info-val">
                    <span v-for="(fertilizer, fertilizerI) in recordItemData.prescriptionList" :key="fertilizerI">
                        <span v-for="(pest, pestI) in fertilizer.pesticideFertilizerList" :key="'sub' + pestI">
                            {{ pest.defaultName || pest.pesticideFertilizerName }}
                            <span
                                v-if="
                                    pestI !== fertilizer.pesticideFertilizerList.length - 1 ||
                                    fertilizerI !== recordItemData.prescriptionList.length - 1
                                "
                            >
                                +
                            </span>
                        </span>
                    </span>
                </div>
            </div>
            <div
                class="info-item"
                v-if="
                    !onlyRecipeName &&
                    recordItemData?.farmWorkDetail?.prescription &&
                    recordItemData?.farmWorkDetail?.prescription
                "
            >
                药物处方
                <div class="info-table">
                    <div class="table">
                        <div class="th">
                            <div class="td">类型</div>
                            <div class="td width">名称</div>
                            <div class="td">配比</div>
                            <div class="td">方式</div>
                        </div>
                        <div>
                            <div
                                class="tr"
                                v-for="(subP, subI) in recordItemData.farmWorkDetail.prescription
                                    .pesticideFertilizerList"
                                :key="subI"
                            >
                                <div class="td">{{ subP.typeName }}</div>
                                <div class="td width">{{ subP.name }}</div>
                                <div class="td">{{ subP.ratio }}</div>
                                <div class="td">人工</div>
                            </div>
                        </div>
                        <!-- <div class="tr">
                            <div class="td width">80%代森锰锌</div>
                            <div class="td">山德生</div>
                            <div class="td">1:2000</div>
                            <div class="td">人工</div>
                        </div> -->
                    </div>
                </div>
            </div>
            <!-- <div class="info-item">
                触发条件：
                <span class="info-val">{{
                    recordItemData?.farmWorkDetail?.condition || recordItemData?.condition || "暂无触发条件"
                }}</span>
            </div> -->
            <div class="info-item one-text">
                农事编号：
                <span class="info-val">{{
                    recordItemData?.farmWorkDetail?.code || recordItemData.farmWorkCode || recordItemData.code
                }}</span>
            </div>
            <div class="info-item" v-if="recordItemData?.attention">
                巡园提醒：
                <span class="info-val">{{ recordItemData?.attention || "暂无巡园提醒" }}</span>
            </div>
        </div>
        <slot name="footer"></slot>
    </div>
</template>

<script setup>
import { ref, computed, watch } from "vue";
import { base_img_url2 } from "@/api/config";
const emit = defineEmits(["titleRightClick"]);
const props = defineProps({
    onlyRecipeName: {
        type: Boolean,
        default: false,
    },
    showFarmImage: {
        type: Boolean,
        default: false,
    },
    recordItemData: {
        type: Object,
        default: () => ({}),
    },
    showContent: {
        type: Boolean,
        default: false,
    },
    contentMode: {
        type: String,
        default: "",
        validator: (value) => ["", "serviceDetail"].includes(value),
    },
    titleMode: {
        type: String,
        default: "",
        validator: (value) => ["", "default"].includes(value),
    },
    titleRightText: {
        type: String,
        default: "",
    },
    titleRightType: {
        type: String,
        default: "button",
        validator: (value) => ["button", "dot"].includes(value),
    },
    titleRightDotText: {
        type: String,
        default: "",
    },
});

const getPrescriptionInfo = (section) => {
    // 将 prescriptionList 中所有 pesticideFertilizerName 用 + 连接
    if (section && Array.isArray(section.prescriptionList)) {
        const names = section.prescriptionList
            .flatMap((item) => (Array.isArray(item?.pesticideFertilizerList) ? item.pesticideFertilizerList : []))
            .map((sub) => sub?.pesticideFertilizerName)
            .filter((name) => typeof name === "string" && name.trim().length > 0);
        if (names.length > 0) {
            return names.join("+");
        }
    }
    return "";
};

const getFarmTypeText = (type) => {
    const value = typeof type === "string" ? type.trim() : type;
    if (value === 0 || value === "0") return "预警农事";
    if (value === 1 || value === "1") return "标准农事";
    if (value === 2 || value === "2") return "建议农事";
    return "";
};

// 使用响应式对象存储图片 URL
const imageUrlMap = ref({});
// 存储正在加载的 ID，避免重复请求
const loadingIds = ref(new Set());

// 获取图片 URL 的函数
const fetchImageUrl = (id) => {
    // 如果 id 不存在或已经在加载中，直接返回
    if (!id || loadingIds.value.has(id)) {
        return;
    }

    // 如果已经有缓存的 URL，直接返回
    if (imageUrlMap.value[id]) {
        return;
    }

    // 标记为加载中
    loadingIds.value.add(id);

    // 发起异步请求获取图片 URL
    VE_API.z_farm_work_record
        .getTriggerImg({ farmWorkRecordId: id })
        .then(({ data }) => {
            if (data && data.length > 0) {
                const url = base_img_url2 + data[data.length - 1].cloudFilename;
                // 更新响应式数据，这样模板会自动更新
                imageUrlMap.value[id] = url;
            } else {
                imageUrlMap.value[id] = "";
            }
        })
        .catch(() => {
            // 请求失败时，设置为空字符串避免重复请求
            imageUrlMap.value[id] = "";
        })
        .finally(() => {
            // 清除加载标记
            loadingIds.value.delete(id);
        });
};

// 计算属性：根据 recordItemData.id 获取图片 URL（响应式）
// const currentImageUrl = computed(() => {
//     const id = props.recordItemData?.id;
//     if (id) {
//         // 触发获取图片 URL（如果还没有获取过）
//         fetchImageUrl(id);
//         // 直接返回响应式数据，Vue 会自动追踪变化
//         return imageUrlMap.value[id] || "";
//     }
//     return "";
// });

// 监听 recordItemData.id 的变化，确保 ID 变化时重新获取
// watch(
//     () => props.recordItemData?.id,
//     (newId) => {
//         if (props.showFarmImage) {
//             if (newId && !imageUrlMap.value[newId] && !loadingIds.value.has(newId)) {
//                 fetchImageUrl(newId);
//             }
//         }
//     },
//     { immediate: true }
// );

const handleTitleRightClick = (recordItemData) => {
    emit("titleRightClick", recordItemData);
};
</script>

<style lang="scss" scoped>
.record-item {
    background: #ffffff;
    border-radius: 8px;
    padding: 12px;
    margin-bottom: 10px;
    .record-title {
        font-size: 16px;
        color: #333333;
        .box-title {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding-bottom: 8px;
            .title-l {
                font-size: 16px;
                font-weight: 600;
                color: #000;
                display: flex;
                align-items: center;
                .parent-text {
                    margin-left: 5px;
                    font-size: 12px;
                    font-weight: normal;
                    padding: 4px 6px;
                    border-radius: 14px;
                    background: rgba(119, 119, 119, 0.1);
                }
            }
            .title-btn {
                width: 24px;
                height: 24px;
                border-radius: 50%;
                background: #2199f8;
                display: flex;
                align-items: center;
                justify-content: center;
            }
            .title-r {
                font-size: 12px;
                &.title-r-button {
                    padding: 5px 10px;
                    border-radius: 20px;
                    border: 1px solid #ff953d;
                    color: #ff953d;
                }
                &.title-r-dot {
                    display: flex;
                    align-items: center;
                    color: #393939;
                    .r-dot {
                        width: 6px;
                        height: 6px;
                        border-radius: 50%;
                        background: #393939;
                        margin-right: 5px;
                    }
                }
            }
        }
    }
    .record-content {
        font-size: 12px;
        .info-item {
            color: #bbbbbb;
            margin-bottom: 4px;
            .info-val {
                color: #666666;
            }
            &.one-text {
                width: 100%;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
        .recipe-name {
            display: flex;
            .name-text {
                flex: none;
            }

            .rescription {
                max-width: 100%;
                white-space: nowrap;
                overflow: hidden;
                text-overflow: ellipsis;
            }
        }
        .info-table {
            margin-top: 8px;

            .table {
                border: 1px solid rgba(196, 196, 196, 0.8);
                border-radius: 4px;
                font-size: 13px;
                .th {
                    background: #f6f6f6;
                    color: #999999;
                    display: flex;
                    justify-content: space-between;
                    border-radius: 4px 4px 0 0;
                    padding: 4px 0;
                }
                .tr {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    color: #333333;
                    padding: 10px 0;
                }

                .tr + .tr {
                    border-top: 1px solid rgba(0, 0, 0, 0.08);
                }
                .td {
                    width: 25%;
                    padding: 0 2px;
                    text-align: center;
                }
                .width {
                    width: 55%;
                }
            }
        }
    }
    // 服务详情模式样式
    .service-detail-content {
        .content-info {
            .info-line {
                font-size: 12px;
                color: #bbbbbb;
                margin-bottom: 8px;
                line-height: 1.4;
                .info-val {
                    color: #666666;
                }
            }
            .review-title {
                .info-val {
                    margin-top: 5px;
                }
            }
            .review-image {
                display: flex;
                align-items: center;
                gap: 8px;
                .image-wrapper {
                    position: relative;
                    flex: 1;
                    img {
                        width: 100%;
                        height: 105px;
                        object-fit: cover;
                        border-radius: 8px;
                    }
                    .image-label {
                        position: absolute;
                        top: 0;
                        left: 0;
                        padding: 4px 10px;
                        background: rgba(54, 52, 52, 0.6);
                        color: #fff;
                        font-size: 12px;
                        border-radius: 8px 0 8px 0;
                        z-index: 1;
                        backdrop-filter: blur(4px);
                    }
                }
            }
        }
        .content-info + .content-info {
            margin-top: 8px;
        }
    }
}
</style>
