<template>
    <div class="farm-details-page">
        <custom-header name="农场详情"></custom-header>
        <div class="farm-details-content">
            <farm-info-card
                v-if="farmDetail.name"
                :data="{
                    farmName: farmDetail.name || '',
                    userType: farmDetail.userType || '托管客户',
                    variety: farmDetail.typeName || '',
                    address: farmDetail.address || '',
                }"
                @click="handleFarmInfo"
            >
                <!-- <template #right>
                    <div @click="handleFarmInfo">基本信息</div>
                </template> -->
                <template #footerData>
                    <div class="footer-data">
                        <div class="footer-l">
                            <div class="farm-info-footer-item">
                                <div class="farm-info-footer-item-label">农事服务</div>
                                <div class="farm-info-footer-item-value">10<span class="unit">次</span></div>
                            </div>
                            <div class="farm-info-footer-item">
                                <div class="farm-info-footer-item-label">总收益</div>
                                <div class="farm-info-footer-item-value">1450<span class="unit">元</span></div>
                            </div>
                        </div>
                        <div class="footer-action" @click.stop="handleDetail('plan')">农事规划</div>
                    </div>
                </template>
            </farm-info-card>
            <tabs v-model:active="activeTab" class="custom-tabs" scrollspy sticky offset-top="40" background="#F2F3F5">
                <tab title="作物档案" class="tab-item">
                    <common-box title="作物档案">
                        <template #right>
                            <span @click="handleDetail('crop_record')">查看详情</span>
                        </template>
                        <template v-if="farmWorkData.length">
                            <div class="farm-work-timeline">
                                <div
                                    class="farm-work-item"
                                    v-for="(item, index) in farmWorkData"
                                    :key="item.time"
                                    :class="{ 'is-estimated': index === farmWorkData.length - 1 }"
                                >
                                    <div class="timeline-left">
                                        <div class="timeline-dot"></div>
                                        <div class="timeline-line"></div>
                                    </div>
                                    <div class="timeline-right">
                                        <div class="farm-work-card" :class="['card-' + item.recordType, { 'is-future': item.isFuture }]">
                                            <div class="type-box">{{ getRecordTypeText(item.recordType) }}</div>
                                            <div class="farm-work-date">{{ item.time }}</div>
                                            <div class="farm-work-desc">
                                                <span class="farm-work-action">{{ item.action }}</span>
                                                <span class="farm-work-content">{{ item.content }}</span>
                                                <span>{{ item.text }}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </template>
                        <empty
                            v-else
                            image="https://birdseye-img.sysuimars.com/birdseye-look-mini/custom-empty-image.png"
                            image-size="80"
                            description="暂无数据"
                            class="empty-state"
                        />
                    </common-box>
                </tab>
                <tab title="农事服务" class="tab-item">
                    <common-box title="农事服务">
                        <template #right>
                            <span @click="handleDetail('service_list')">查看详情</span>
                        </template>
                        <tab-list
                            type="light"
                            v-model="farmServiceActiveTab"
                            :tabs="farmServiceTabs"
                            @change="handleFarmServiceTabChange"
                        />
                        <stats-box :stats-data="serviceStatsData" />
                        <div v-for="(section, index) in detailList" :key="index" class="content-section">
                            <record-item
                                :record-item-data="section"
                                onlyRecipeName
                                :content-mode="farmServiceActiveTab === 0 ? 'serviceDetail' : ''"
                                title-mode="default"
                                :title-right-text="farmServiceActiveTab === 0 ? '分享成果' : ''"
                                :title-right-type="farmServiceActiveTab === 1 ? 'dot' : null"
                                :title-right-dot-text="farmServiceActiveTab === 1 ? '2区' : ''"
                                class="recipe-item"
                            />
                        </div>
                        <empty
                            v-if="detailList.length === 0"
                            image="https://birdseye-img.sysuimars.com/birdseye-look-mini/custom-empty-image.png"
                            image-size="80"
                            description="暂无数据"
                            class="empty-state"
                        />
                    </common-box>
                </tab>
                <tab title="作物相册" class="tab-item">
                    <common-box title="作物相册">
                        <template #right>
                            <span @click="handleShareReport()">查看更多</span>
                        </template>
                        <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>
                    </common-box>
                </tab>
            </tabs>
        </div>
        <div class="custom-bottom-fixed-btns">
            <div class="bottom-btn secondary-btn" @click="handleShareFarm">分享农场</div>
            <div class="bottom-btn primary-btn" @click="handleChatFarm">在线沟通</div>
        </div>
    </div>
    <fn-share-sheet v-model:show="showShare" @select="onSelect" :options="[{ name: '微信', icon: 'wechat' }]" />
    <!-- 农场信息 -->
    <farm-info-popup
        ref="farmInfoRef"
        :farmId="farmIdVal"
        :showEditBtn="!farmDetail.farmersMiniUserId"
        :showBtn="true"
    ></farm-info-popup>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Tab, Tabs, Empty } from "vant";
import { base_img_url2, resize_300 } from "@/api/config";
import wx from "weixin-js-sdk";
import customHeader from "@/components/customHeader.vue";
import FarmInfoCard from "@/components/pageComponents/FarmInfoCard.vue";
import tabList from "@/components/pageComponents/TabList.vue";
import commonBox from "@/components/pageComponents/CommonBox.vue";
import StatsBox from "@/components/pageComponents/StatsBox.vue";
import recordItem from "@/components/recordItem.vue";
import farmInfoPopup from "../home/components/farmInfoPopup.vue";
import FnShareSheet from "@/components/pageComponents/FnShareSheet.vue";
import config from "@/api/config";
import { ElMessage } from "element-plus";
const router = useRouter();
const route = useRoute();
const activeTab = ref(0);
const farmServiceTabs = ["过往服务", "未来服务"];
const farmServiceActiveTab = ref(0);

const farmInfoRef = ref(null);
const handleFarmInfo = () => {
    farmInfoRef.value.handleShow();
};

const handleFarmServiceTabChange = (index) => {
    if (index === 0) {
        getFarmPastServiceCost();
        getDetailList();
    } else {
        getFutureFarmWorkList();
        serviceStatsData.value = [
            { value: "1258", unit: "元", desc: "预计收益" },
            { value: "1258", unit: "元", desc: "预计成本" },
        ];
    }
};

const serviceStatsData = ref([]);

onMounted(() => {
    farmIdVal.value = route.query.farmId;
    paramsPage.value = {
        farmId: farmIdVal.value,
        limit: 1,
        page: 1,
    };
    getFarmDetail();
    getFarmWorkList();
    getDetailList();
    getFarmPastServiceCost();
});

const farmIdVal = ref(null);
const farmDetail = ref({});
const paramsPage = ref({});
const getFarmDetail = () => {
    VE_API.user.getFarmDetail({ farmId: farmIdVal.value }).then(({ data }) => {
        farmDetail.value = data || {};
        console.log(farmDetail.value);
    });
};

const farmWorkData = ref([]);
const typeObj = {
    1: '物候进程',
    2: '农事',
    3: '异常',
}

const getRecordTypeText = (recordType) => {
    return typeObj[recordType];
}
const getFarmWorkList = () => {
    // VE_API.user.getFarmWorkList(paramsPage.value).then(({ data }) => {
    //     if (data && data.length > 0) {
    //         farmWorkData.value = data[0] || {};
    //     }
    // });
    farmWorkData.value = [
        {
            time: "8/8",
            action: "进入",
            content: "花芽分化期",
            recordType: 1,
        },
        {
            time: "8/1",
            action: "做了",
            content: "杀虫",
            text: "农事",
            recordType: 2,
        },
        {
            time: "7/30",
            action: "出现",
            content: "蒂蛀虫",
            recordType: 3,
        },
        {
            time: "7/25",
            action: "预计进入",
            content: "果实膨大期",
            isFuture: true,
            recordType: 1,
        },
    ];
};

const cropAlbum = ref([
    {
        district: "",
        filename: "birdseye-look-mini/91429/1765361542408.png",
        fosterCode: "",
        gardenId: null,
        gardenName: "",
        growText: "",
        id: "786656608116543488",
        localPath: "",
        localResPath: "",
        location: "POINT(113.407189 23.032344)",
        treeCode: "",
        treeGeoHash: "ws0eh8utt204",
    },
    {
        address: "",
        angle: "",
        baseMap: "",
        blueZoneId: null,
        district: "",
        filename: "birdseye-look-mini/91429/1763371316207.jpg",
        fosterCode: "",
        gardenId: null,
        gardenName: "",
        growText: "",
        id: "778308963891417088",
        localPath: "",
        localResPath: "",
        location: "POINT(113.407189 23.032344)",
        miniUserId: null,
        miniUserName: "",
        modelId: null,
        phenologyId: "39",
        treeCode: "",
        treeGeoHash: "ws0eh8utt204",
        treeId: 223920,
        uploadDate: "2025-11-17",
    },
    {
        filename: "birdseye-look-mini/91754/1763367875786.jpg",
        fosterCode: "",
        gardenId: null,
        gardenName: "",
        growText: "",
        id: "778294553688936448",
        localPath: "",
        localResPath: "",
        location: "POINT(113.407189 23.032344)",
        treeCode: "",
        treeGeoHash: "ws0eh8utt204",
        treeId: 223920,
        uploadDate: "2025-11-17",
    },
]);

const detailList = ref([]);
const getDetailList = () => {
    const params = {
        ...paramsPage.value,
        flowStatus: "4,5",
    };
    VE_API.user.getDetailList(params).then(({ data }) => {
        detailList.value = data || [];
    });
};
const getFutureFarmWorkList = () => {
    VE_API.user.getFutureFarmWorkList(paramsPage.value).then(({ data }) => {
        detailList.value = data || [];
    });
};

const getFarmPastServiceCost = () => {
    VE_API.user.getFarmPastServiceCost({ farmId: farmIdVal.value }).then(({ data }) => {
        serviceStatsData.value = [
            { value: data?.totalCost, unit: "元", desc: "总收益" },
            { value: data?.totalCost, unit: "元", desc: "投入成本" },
            { value: data?.serviceCount, unit: "次", desc: "服务次数" },
        ];
    });
};
const handleDetail = (path) => {
    router.push(`/${path}?farmId=${farmIdVal.value}`);
};

const handleShareReport = () => {
    router.push({
        path: "/farm_report",
        query: {
            miniJson: JSON.stringify({ farmId: farmIdVal.value }),
        },
    });
};

const showShare = ref(false);
const handleShareFarm = () => {
    showShare.value = true;
};

const handleChatFarm = () => {
    if (route.query.receiveUserId != "null") {
        router.push(`/chat_frame?userId=${route.query.receiveUserId}&farmId=${farmIdVal.value}`);
    } else {
        ElMessage.warning("尚未绑定用户,暂时无法沟通");
    }
};

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

<style scoped lang="scss">
.farm-details-page {
    width: 100%;
    height: 100vh;
    background: #F2F3F5;
    .farm-details-content {
        box-sizing: border-box;
        padding: 10px 12px 70px 12px;
        overflow: auto;
        height: calc(100% - 40px);
        box-sizing: border-box;
        .custom-tabs {
            ::v-deep {
                .van-tabs__wrap {
                    height: auto;
                }
                .van-tabs__nav {
                    .van-tab {
                        color: #8b8b8b;
                        background: #F7F8FA;
                        height: 34px;
                        font-weight: 400;
                        border-radius: 25px;
                        width: fit-content;
                        flex: none;
                        padding: 0 12px;
                        margin-right: 8px;
                    }
                    .van-tab--active {
                        color: #fff;
                        background: #2199f8;
                        font-weight: 400;
                    }
                }

                .van-tabs__line {
                    display: none;
                }
                .van-tabs__nav--line {
                    padding: 12px 0;
                }
            }
            .tab-item + .tab-item {
                margin-top: 12px;
            }

            .photo-img-wrap {
                display: flex;
                flex-wrap: wrap;
                gap: 10px;
                ::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;
                    }
                }
            }
        }
        .question-header {
            display: flex;
            align-items: center;
            margin-bottom: 6px;
            gap: 8px;
            font-weight: 500;
            .question-icon {
                width: 22px;
                height: 20px;
            }
        }
        .answer-content {
            color: #333333;
            margin: 6px 0 10px 0;
        }
        .answer-img {
            display: flex;
            gap: 5px;
            img {
                flex: 1;
                max-width: 105px;
                height: 105px;
                border-radius: 5px;
                object-fit: cover;
            }
        }
        .content-section {
            .recipe-item {
                border: 1px solid rgba(0, 0, 0, 0.1);
                margin: 12px 0 0 0;
            }
        }
        .plan-tab-item {
            .recipe-item {
                padding: 0;
            }
        }
        .plan-list-wrapper {
            height: 500px;
            margin-top: 12px;
        }
        .report-content {
            font-size: 13px;
        }
        .answer-btn {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-top: 10px;
            > div {
                display: flex;
                gap: 10px;
            }
        }
        .answer-btn-item {
            padding: 7px 12px;
            border-radius: 25px;
            font-size: 12px;
            text-align: center;
            background: rgba(33, 153, 248, 0.1);
            color: #2199f8;
            min-width: 52px;
            box-sizing: border-box;
            &.primary {
                background: #2199f8;
                color: #ffffff;
            }
        }
        .empty-state {
            ::v-deep .van-empty {
                padding: 40px 0;
            }
        }
        .footer-data {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 12px;
            margin-top: 12px;
            .footer-l {
                display: flex;
                gap: 8px;
                flex: 1;
                .farm-info-footer-item {
                    display: flex;
                    border: 0.4px solid rgba(215, 215, 215, 0.5);
                    padding: 8px 5px 5px;
                    box-sizing: border-box;
                    .farm-info-footer-item-label {
                        font-size: 12px;
                        color: rgba(32, 32, 32, 0.4);
                        margin-bottom: 4px;
                    }
                    .farm-info-footer-item-value {
                        font-size: 16px;
                        color: #202020;
                        padding-left: 2px;
                        .unit {
                            font-size: 12px;
                            padding-left: 2px;
                            color: rgba(32, 32, 32, 0.4);
                        }
                    }
                }
            }
            .footer-action {
                border: 0.5px solid #888B8D;
                border-radius: 20px;
                padding: 5px 12px;
                font-size: 12px;
                color: #888B8D;
                white-space: nowrap;
                cursor: pointer;
                flex-shrink: 0;
            }
        }
        .farm-work-timeline {
            padding: 10px 0;
            .farm-work-item {
                display: flex;
                align-items: flex-start;
                position: relative;
                &:not(:last-child) {
                    margin-bottom: 20px;
                }
                .timeline-left {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    margin-right: 12px;
                    position: relative;
                    .timeline-dot {
                        width: 6px;
                        height: 6px;
                        border-radius: 50%;
                        border: 1px solid #2199f8;
                        flex-shrink: 0;
                        z-index: 1;
                    }
                    .timeline-line {
                        width: 1px;
                        height: 48px;
                        background: #e5e6eb;
                        position: absolute;
                        top: 8px;
                    }
                }
                .timeline-right {
                    flex: 1;
                    .farm-work-card {
                        border: 1px solid #8bccff;
                        border-radius: 4px;
                        background: #f8fcff;
                        padding: 12px;
                        display: flex;
                        align-items: center;
                        color: #1d2129;
                        font-size: 14px;
                        line-height: 22px;
                        display: flex;
                        align-items: center;
                        &.card-1 {
                            border: 1px solid #8BCCFF;
                            .type-box {
                                background: #2199F8;
                            }
                            .farm-work-content {
                                color: #2199F8;
                            }
                        }
                        &.card-2 {
                            border: 1px solid #FFBB83;
                            .type-box {
                                background: #FF953D;
                            }
                            .farm-work-content {
                                color: #FF953D;
                            }
                        }
                        &.card-3 {
                            border: 1px solid #FF9C9C;
                            .type-box {
                                background: #FD7676;
                            }
                            .farm-work-content {
                                color: #FD7676;
                            }
                        }
                        &.is-future {
                            // opacity: 0.5;
                            background: rgba(246, 250, 255, 0.5);
                            .type-box {
                                background: rgba(33, 153, 248, 0.5);
                            }
                            .farm-work-content {
                                color: rgba(29, 33, 41, 0.5);
                            }
                        }
                        .type-box {
                            margin-right: 12px;
                            padding: 0 5px;
                            height: 20px;
                            line-height: 20px;
                            font-size: 12px;
                            color: #fff;
                            border-radius: 0 4px 0 4px;
                        }
                        .farm-work-date {
                            padding-right: 4px;
                        }
                        .farm-work-desc {
                            .farm-work-action {
                                padding-right: 4px;
                            }
                            .farm-work-content {
                                padding-right: 4px;
                            }
                        }
                    }
                }
                &.is-estimated {
                    .timeline-right {
                        .farm-work-card {
                            background: rgba(246, 250, 255, 0.5);
                            border: 1px solid rgba(190, 218, 255, 0.5);
                            .farm-work-date,
                            .farm-work-desc {
                                color: rgba(29, 33, 41, 0.5);
                            }
                        }
                    }
                }
            }
        }
    }
}
</style>
