<template>
    <div class="work-wrap">
        <custom-header name="农事成效"></custom-header>
        <div class="work-content recheck-title">
            <div class="tabs-content-item">
                <div class="common-card-title">
                    <img class="icon" src="@/assets/img/home/label-icon.png" alt="" />
                    <span>农事信息</span>
                </div>
                <div class="info-box">
                    <div class="info-l">
                        <img class="farm-img" src="@/assets/img/gallery/farm-img.png" alt="" />
                    </div>
                    <div class="info-r">
                        <div class="farm-name">{{ workItem.farmName }}</div>
                        <div class="info-item">
                            <div class="info-name">农事名称：</div>
                            <div class="info-value">{{ workItem.farmWorkName }} ({{ workItem.executeDate }})</div>
                        </div>
                        <div class="info-item">
                            <div class="info-name">农事目的：</div>
                            <div class="info-value">{{ workItem.farmWorkTypeName || workItem.condition }}</div>
                        </div>
                        <div class="info-item">
                            <div class="info-name">肥药处方：</div>
                            <div class="info-value">
                                <div class="rescription" v-if="workItem?.prescriptionList">
                                    <span
                                        v-for="(fertilizer, fertilizerI) in workItem.prescriptionList"
                                        :key="fertilizerI"
                                    >
                                        <span
                                            v-for="(pest, pestI) in fertilizer.pesticideFertilizerList"
                                            :key="'sub' + pestI"
                                        >
                                            {{ pest.defaultName }}
                                            <span
                                                v-if="
                                                    pestI !== fertilizer.pesticideFertilizerList.length - 1 ||
                                                    fertilizerI !== workItem.prescriptionList.length - 1
                                                "
                                            >
                                                +
                                            </span>
                                        </span>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="info-box subject-content">
                    <div class="subject-box">
                        <div class="subject-item cost-l">
                            <img class="subject-img" src="@/assets/img/gallery/capital.png" alt="" />
                            <div class="subject-tag">
                                {{ workItem.executeMain }}
                                <el-icon class="right-icon" size="10"><ArrowRight /></el-icon>
                            </div>
                        </div>
                        <div class="subject-item cost-l">
                            <img class="subject-img" src="@/assets/img/gallery/capital.png" alt="" />
                            <div class="subject-tag">
                                {{ workItem.serviceMain }}
                                <el-icon class="right-icon" size="10"><ArrowRight /></el-icon>
                            </div>
                        </div>
                        <div class="subject-item">
                            <img class="subject-img" :src="workItem.expertIcon" alt="" />
                            <div class="subject-tag">
                                {{ workItem.expertName }}
                                <el-icon class="right-icon" size="10"><ArrowRight /></el-icon>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="tabs-content-item">
                <div class="common-card-title">
                    <img class="icon" src="@/assets/img/home/label-icon.png" alt="" />
                    <span>复核成效</span>
                </div>
                <div class="info-box bottom-box">
                    <div class="result-box">
                        <div class="result-text">
                            通过精准农业技术的应用，作物产量实现了两位数的增长，病虫害的发生率大幅下降，土壤肥力的提升
                        </div>
                        <!-- <div class="result-text time-text">
                            距离农事执行已 15 天，请抓紧时间上传照片！系统为您生成农事成效分析！
                        </div> -->
                    </div>
                    <div class="recheck-box" v-if="workItem?.farmId">
                        <div class="recheck-ablum">
                            <!-- <div class="img-list over-img-box">
                                <album-carousel7d
                                    :key="1"
                                    :farmId="workItem.farmId"
                                    :farmWork="{
                                        beforeExecuteDate: workItem.beforeExecuteDate,
                                        executeDate: workItem.executeDate,
                                    }"
                                ></album-carousel7d>
                            </div> -->
                            <div class="img-list">
                                <div
                                    class="recheck-text-wrap no-events"
                                    :class="{
                                        active: !diffInDays(workItem.reviewDate) > 0 && curRole === '0',
                                        'yse-events': curRole === '0' && !diffInDays(workItem.reviewDate) > 0,
                                        'center-wrap': !imageArr.length,
                                    }"
                                >
                                    <div class="date" v-show="workItem.reviewDate">{{ workItem.reviewDate }}</div>
                                    <upload
                                        exampleImg
                                        @handleUpload="handleUpload"
                                        class="upload-wrap"
                                        :style="{
                                            height:
                                                imageArr.length && !diffInDays(workItem.reviewDate) > 0
                                                    ? 'auto'
                                                    : '254px',
                                        }"
                                    >
                                        <template
                                            v-if="
                                                diffInDays(workItem.reviewDate) == 0 ||
                                                diffInDays(workItem.reviewDate) == null
                                            "
                                        >
                                            <img
                                                class="img-icon"
                                                :src="
                                                    require(`@/assets/img/gallery/img-icon${
                                                        curRole === '0' ? '-act' : ''
                                                    }.png`)
                                                "
                                                alt=""
                                            />
                                            <div class="recheck-text">
                                                {{ curRole === "2" ? "等待农户上传" : "点击上传照片" }}
                                            </div>
                                            <div
                                                class="recheck-desc"
                                                v-show="curRole === '2' && diffInDays(workItem.reviewDate) != 0"
                                            >
                                                <!-- （已逾期{{ diffInDays(workItem.reviewDate, "add") }}天） -->
                                            </div>
                                        </template>
                                        <template v-else>
                                            <img class="img-icon" src="@/assets/img/gallery/img-icon.png" alt="" />
                                            <div class="recheck-text">等待复核</div>
                                            <div class="recheck-desc">
                                                （剩余{{ diffInDays(workItem.reviewDate) }}天）
                                            </div>
                                        </template>
                                    </upload>
                                    <div
                                        class="submit"
                                        v-show="imageArr.length && !diffInDays(workItem.reviewDate) > 0"
                                        @click="handleSubmit('reviewImage')"
                                    >
                                        确认上传
                                    </div>
                                </div>
                            </div>
                            <div class="img-list over-img-box" v-if="workItem.reviewImage.length">
                                <album-carousel
                                    :key="2"
                                    :farmId="workItem.farmId"
                                    :lock="false"
                                    :images="handleConversion(workItem.reviewImage)"
                                ></album-carousel>
                            </div>
                            <div class="img-list" v-if="!workItem.reviewImage2.length && workItem.activeStatus === 0">
                                <div
                                    class="recheck-text-wrap no-events"
                                    :class="{
                                        active: !diffInDays(workItem.reviewDate2) > 0 && curRole === '0',
                                        'yse-events': curRole === '0' && !diffInDays(workItem.reviewDate2) > 0,
                                        'center-wrap': !imageArr2.length,
                                    }"
                                >
                                    <div class="date" v-show="workItem.reviewDate2">{{ workItem.reviewDate2 }}</div>
                                    <upload
                                        exampleImg
                                        @handleUpload="handleUpload2"
                                        class="upload-wrap"
                                        :style="{
                                            height:
                                                imageArr2.length && !diffInDays(workItem.reviewDate2) > 0
                                                    ? 'auto'
                                                    : '254px',
                                        }"
                                    >
                                        <template
                                            v-if="
                                                diffInDays(workItem.reviewDate2) == 0 ||
                                                diffInDays(workItem.reviewDate2) == null
                                            "
                                        >
                                            <img
                                                class="img-icon"
                                                :src="
                                                    require(`@/assets/img/gallery/img-icon${
                                                        curRole === '0' ? '-act' : ''
                                                    }.png`)
                                                "
                                                alt=""
                                            />
                                            <div class="recheck-text">
                                                {{ curRole === "2" ? "等待农户上传" : "点击上传照片" }}
                                            </div>
                                            <div
                                                class="recheck-desc"
                                                v-show="curRole === '2' && diffInDays(workItem.reviewDate2) != 0"
                                            >
                                                <!-- （已逾期{{ diffInDays(workItem.reviewDate2, "add") }}天） -->
                                            </div>
                                        </template>
                                        <template v-else>
                                            <img class="img-icon" src="@/assets/img/gallery/img-icon.png" alt="" />
                                            <div class="recheck-text">等待复核</div>
                                            <div class="recheck-desc" v-show="diffInDays(workItem.reviewDate2) >= 0">
                                                （剩余{{ diffInDays(workItem.reviewDate2) }}天）
                                            </div>
                                        </template>
                                    </upload>
                                    <div
                                        class="submit"
                                        v-show="imageArr2.length && !diffInDays(workItem.reviewDate2) > 0"
                                        @click="handleSubmit('reviewImage2')"
                                    >
                                        确认上传
                                    </div>
                                </div>
                            </div>
                            <div class="img-list over-img-box" v-if="workItem.reviewImage2.length">
                                <album-carousel
                                    :key="2"
                                    :farmId="workItem.farmId"
                                    :lock="false"
                                    :images="handleConversion(workItem.reviewImage2)"
                                ></album-carousel>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 按钮 -->
            <div class="up-btn-group" v-show="isPlan">
                <template v-if="curRole === '2'">
                    <div
                        class="up-btn"
                        :class="{ btn: workItem.executeEvidence && workItem.executeEvidence.length }"
                        v-show="workItem.reviewImage && !workItem.reviewImage.length"
                    >
                        提醒农户拍照
                    </div>
                    <div
                        class="up-btn orange"
                        @click="toUpload"
                        :class="{ btn: workItem.reviewImage && workItem.reviewImage.length }"
                        v-show="workItem.executeEvidence && !workItem.executeEvidence.length"
                    >
                        上传农事凭证
                    </div>
                </template>
                <template v-else>
                    <div
                        class="up-btn btn"
                        @click="handleContact"
                        v-show="workItem.reviewImage && workItem.reviewImage.length && !imageArr2.length"
                    >
                        联系专家
                    </div>
                </template>
            </div>
        </div>
        <!-- 上传图片弹窗 -->
        <upload-popup :executionData="workItem"></upload-popup>
    </div>
</template>

<script setup>
import { Tab, Tabs } from "vant";
import customHeader from "@/components/customHeader.vue";
import { onMounted, ref, onDeactivated,onActivated } from "vue";
import { useRoute, useRouter } from "vue-router";
import upload from "@/components/upload";
import AlbumCarousel7d from "@/components/album_compoents/albumCarousel7d";
import AlbumCarousel from "@/components/album_compoents/albumCarousel";
import eventBus from "@/api/eventBus";
import { ElMessage } from "element-plus";
import uploadPopup from "@/components/popup/uploadPopup.vue";
import { deepClone } from "@/common/commonFun";
const route = useRoute();

const workItem = ref({
    farmName: "测试农场",
    farmWorkName: "测试农事",
    executeDate:'2025-09-01',
    farmWorkTypeName: "测试农事类型",
    condition: "测试农事类型",
    farmWorkType: "叶面施",
    prescriptionList: [
        {
            defaultName: "营养",
            pesticideFertilizerList: [
                {
                    defaultName: "尿素",
                },
            ],
        },
    ],
    executeMain: "叶面施",
    serviceMain: "广州泽秾丰农资有限公司",
    expertName: "测试专家",
    expertIcon: "https://birdseye-img.sysuimars.com/birdseye-look-mini/Group%201321316260.png",
    cost: {
        pesticideFertilizerCost: 1125,
        farmWorkServiceCost: 35,
    },
    reviewImage: [],
    reviewImage2: [],
    reviewDate: "2025-09-01",
    reviewDate2: "2025-09-01",
    activeStatus: 0,
    executeEvidence: [],
    farmId: 1,
    libId: 1,
    uniqueId: 1,
    isPlan: false,
    curRole: "",
    farmId: 766,
    libId: 1,
    uniqueId: null,
});
const curRole = ref("");
const farmId = ref(null);
const libId = ref(null);
const uniqueId = ref(null);
// 农事规划页面-显示上传农事凭证按钮
const isPlan = ref(false);
const id = route.query.json ? JSON.parse(route.query.json).id : null;

const diffInDays = (date, type = "minus") => {
    const targetDate = new Date(date);
    const currentDate = new Date(); // 获取当前系统时间
    let diffInMs;
    if (type === "minus") {
        diffInMs = targetDate - currentDate;
    } else {
        diffInMs = currentDate - targetDate;
    }
    const day = Math.floor(diffInMs / (1000 * 60 * 60 * 24));
    return day + 1 >= 0 ? day + 1 : null;
};

onMounted(() => {
    window.scrollTo(0, 0);
    curRole.value = localStorage.getItem("SET_USER_CUR_ROLE");
    farmId.value = route.query.farmId;
    libId.value = route.query.libId;
    uniqueId.value = route.query.id;
    isPlan.value = route.query.isPlan ? true : false;

    getDetail(true);

    eventBus.on("confirm:callback", confirmCallback);
});

const handleConversion = (data) => {
    const arr = data.map((item) => {
        return {
            ...item,
            filename: item.imgUrl,
            uploadDate: item.date,
            district: "",
        };
    });
    return arr;
};

const defaultWorkData = ref({});
const getDetail = (isUpdate) => {
    if (!id) return;
    VE_API.z_farm_work_record.getDetail({ id }).then(({ data }) => {
        workItem.value = data[0];
        defaultWorkData.value = deepClone(data[0]);
        if (isUpdate) {
            eventBus.emit("chart:updateOption", "");
        }
    });
};

//确认上传
const handleSubmit = (image) => {
    const params = {
        ...defaultWorkData.value,
        orderStatus: 6,
    };
    if (image === "reviewImage") {
        params.reviewImage = imageArr.value;
    } else {
        params.reviewImage2 = imageArr2.value;
    }
    VE_API.order.confirm(params).then(({ code }) => {
        if (code === 0) {
            getDetail();
            ElMessage.success("您已上传成功");
            imageArr.value = [];
            imageArr2.value = [];
        }
    });
};

onDeactivated(() => {
    workItem.value = {};
    eventBus.off("confirm:callback", confirmCallback);
});

function confirmCallback() {
    getDetail();
}

//联系专家
const handleContact = () => {
    router.push(`/dialogue?userId=${workItem.value.expert}&name=${workItem.value.expertUserName}`);
};

const imageArr = ref([]);
const handleUpload = ({ imgArr }) => {
    imageArr.value = imgArr.map((item) => {
        return {
            imgUrl: item,
        };
    });
};

const imageArr2 = ref([]);
const handleUpload2 = ({ imgArr }) => {
    imageArr2.value = imgArr.map((item) => {
        return {
            imgUrl: item,
        };
    });
};

const router = useRouter();

// 上传照片
function toUpload() {
    eventBus.emit("uploadUopup:show", { isPlanVal: true });
}
</script>

<style lang="scss" scoped>
.work-wrap {
    .center-wrap {
        ::v-deep {
            .van-uploader__wrapper {
                justify-content: center;
            }
        }
    }
    .work-content {
        padding-top: 1px;
        background: #f5f5f5;
        padding-bottom: 12px;
        font-size: 14px;
        height: calc(100vh - 40px);
        box-sizing: border-box;
        overflow: auto;
        &.recheck-title {
            padding-bottom: 26px;
            .common-card-title {
                font-size: 16px;
                display: flex;
                align-items: center;
                .icon {
                    width: 14px;
                    height: 8px;
                    padding-right: 6px;
                }
            }
        }
        .up-btn-group {
            position: fixed;
            bottom: 80px;
            left: 12px;
            display: flex;
            justify-content: center;
            width: calc(100% - 24px);
            .up-btn {
                background: linear-gradient(45deg, #9fd5ff, #2199f8);
                flex: 1;
                height: 40px;
                border: 2px solid rgba(255, 255, 255, 0.66);
                color: #fff;
                font-size: 14px;
                border-radius: 40px;
                line-height: 38px;
                text-align: center;
                box-sizing: border-box;
            }
            .orange {
                margin-left: 12px;
                background: linear-gradient(45deg, #ffd887, #ed9e1e);
            }
            .btn {
                width: 200px;
                flex: none;
            }
        }
        .tabs-content-item {
            padding: 12px 12px 16px 12px;
            margin: 0 12px;
            border-radius: 8px;
            background: #fff;
            margin-top: 12px;
            position: relative;
            .card-title {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding-bottom: 10px;
                .card-title-l {
                    display: flex;
                    align-items: center;
                    font-size: 16px;

                    .icon {
                        width: 14px;
                        height: 8px;
                        padding-right: 6px;
                    }
                }
                .card-title-r {
                    font-size: 14px;
                    color: #2199f8;
                }
            }
            .info-box {
                &.subject-content {
                    border: none;
                }
                &.cost-wrap {
                    padding-top: 8px;
                }
                &.bottom-box {
                    flex-direction: column;
                }
                // margin-top: 12px;
                border-top: 1px solid #f5f5f5;
                padding-top: 12px;
                display: flex;
                align-items: center;
                .info-l {
                    .farm-img {
                        width: 78px;
                        width: 78px;
                        border-radius: 8px;
                        object-fit: scale-down;
                    }
                }
                .info-r {
                    padding-left: 12px;
                }
                .farm-name {
                    font-weight: bold;
                    font-size: 14px;
                    color: #000;
                    padding-bottom: 4px;
                }
                .info-item {
                    display: flex;
                    font-size: 12px;
                    .info-name {
                        color: #bbbbbb;
                        flex: none;
                    }
                    .info-value {
                        color: #666666;
                    }
                }
                .info-item + .info-item {
                    margin-top: 4px;
                }
            }
            .subject-box {
                width: 100%;
                display: flex;
                align-items: center;
                justify-content: space-around;
                background: #fafafa;
                .subject-item {
                    border-radius: 8px;
                    padding: 4px 4px;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;
                    width: 33%;
                    .subject-img {
                        width: 30px;
                        height: 30px;
                        object-fit: cover;
                        border-radius: 50%;
                        padding-bottom: 4px;
                    }
                    .subject-tag {
                        font-size: 12px;
                        padding: 2px 3px 3px 8px;
                        background: #e0efff;
                        color: #2199f8;
                        border-radius: 4px;

                        &.cost-text {
                            margin-left: 8px;
                            font-size: 16px;
                            color: #2199f8;
                            padding: 1px 8px;
                        }
                    }
                }
                .subject-item + .subject-item {
                    margin-left: 6px;
                }

                .cost-l {
                    position: relative;
                    &::after {
                        content: "";
                        position: absolute;
                        right: 0;
                        top: 16px;
                        height: calc(100% - 32px);
                        width: 1px;
                        background: rgba(0, 0, 0, 0.05);
                    }
                }
            }
            .cost-box {
                border-radius: 5px;
                background: none;
                .cost-item {
                    display: flex;
                    align-items: center;
                    flex-direction: row;
                }
                .subject-item {
                    background: none;
                    width: 50%;
                }
                .cost-l {
                    position: relative;
                    &::after {
                        content: "";
                        position: absolute;
                        right: 0;
                        top: 0;
                        height: 100%;
                        width: 1px;
                        background: rgba(0, 0, 0, 0.05);
                    }
                }
                .cost-text {
                    font-size: 16px;
                    color: #2199f8;
                    padding-bottom: 5px;
                }
            }
            .recheck-box,
            .recheck-ablum {
                width: 100%;
            }
            .evaluate {
                background: #fff;
                border-radius: 5px;
                padding: 4px 8px 10px 8px;
                margin-right: 8px;
                .evaluate-title {
                    font-size: 16px;
                    font-weight: 500;
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                    margin-bottom: 8px;
                    .more {
                        font-size: 14px;
                        color: #999999;
                        font-weight: 400;
                        display: flex;
                        align-items: center;
                    }
                }
                .rate {
                    display: flex;
                    justify-content: space-between;
                    ::v-deep {
                        .el-rate {
                            --el-rate-icon-margin: 0;
                        }
                        .el-rate--small .el-rate__icon {
                            font-size: 12px;
                        }
                    }
                    .rate-item {
                        display: flex;
                        align-items: center;
                        border-radius: 4px;
                        padding: 4px 0px;
                        font-size: 11px;
                        .name {
                            margin-right: 2px;
                            color: #666666;
                            position: relative;
                            top: 2px;
                        }
                        .num {
                            color: #f3c11d;
                            margin-left: 2px;
                        }
                    }
                    .line {
                        width: 1px;
                        height: 12px;
                        background: #cdd7e1;
                        position: relative;
                        top: 13px;
                        margin: 0 3px;
                    }
                }
                .comment {
                    .user-info {
                        display: flex;
                        align-items: center;
                        margin-bottom: 2px;
                        .user-name {
                            font-weight: 500;
                            margin-left: 8px;
                            span {
                                font-weight: 400;
                                font-size: 12px;
                                color: #999999;
                            }
                        }
                    }
                }
            }
            .result-text {
                font-size: 12px;
                color: #666666;
                line-height: 18px;
            }
            .time-text{
                color: #FF953D;
                padding: 4px 12px;
                border-radius: 5px;
                background: rgba(255, 149, 61, 0.1);
            }
            .img-list + .img-list,
            .upload-wrap {
                margin-top: 12px;
            }
            .over-img-box {
                ::v-deep {
                    img {
                        border-radius: 8px;
                    }
                }
            }
            .img-list {
                width: 100%;
            }
            .upload-wrap {
                display: flex;
                flex-direction: column;
                justify-content: center;
                height: 254px;
                width: 100%;
                padding: 25px 0 12px 10px;
                box-sizing: border-box;
            }
            .recheck-text-wrap {
                width: 100%;
                border-radius: 8px;
                background: #f2f3f5;
                color: #666666;
                font-size: 14px;
                position: relative;
                &.active {
                    background: rgba(33, 153, 248, 0.1);
                    border: 1px solid #2199f8;
                    color: #2199f8;
                    .date {
                        background: linear-gradient(170deg, #9fd5ff, #2199f8);
                    }
                    .recheck-desc {
                        color: #2199f8;
                    }
                }
                .submit {
                    background: #2199f8;
                    border-radius: 4px;
                    padding: 8px;
                    font-size: 16px;
                    color: #fff;
                    margin: 0 10px 16px;
                    text-align: center;
                }
                .date {
                    position: absolute;
                    top: 0;
                    left: 0;
                    background: #bebebe;
                    border-radius: 8px 0 8px 0;
                    color: #fff;
                    font-size: 12px;
                    padding: 3px 6px;
                    font-family: "PangMenZhengDao";
                }
                .recheck-text {
                    padding: 8px 0 2px 0;
                }
                .recheck-desc {
                    font-size: 12px;
                    color: #999999;
                }
                .img-icon {
                    width: 40px;
                    height: 40px;
                }
            }
            .sub-title {
                display: flex;
                align-items: center;
                justify-content: center;
                .sub-line {
                    width: 12px;
                    height: 2px;
                    border-radius: 1px;
                    background: #d9d9d9;
                }
                .sub-name {
                    padding: 0 5px;
                    font-size: 14px;
                    color: #666666;
                }
            }
        }
    }
}
</style>
