<template>
    <div class="work-detail">
        <custom-header name="农事详情" :showClose="false" isGoBack @goback="handleBack" />

        <div class="work-detail-content">
            <!-- 顶部状态 -->
            <div class="content-status" :class="'status-' + detail?.flowStatus">
                <div class="status-l" v-if="userInfo?.appType === 2">
                    <div class="status-title">{{ statusText }}</div>
                    <div class="status-sub" v-if="triggerDateText && detail?.flowStatus === 0">
                        预计触发时间 {{ triggerDateText }}
                    </div>
                    <div class="status-sub" v-if="detail?.flowStatus === 1">
                        任务进度：1/2
                    </div>
                </div>
                <div class="status-l" v-else>
                    <div class="status-title">{{ statusText }}</div>
                    <div class="status-sub" v-if="triggerDateText && detail?.flowStatus === 0">
                        预计触发时间 {{ triggerDateText }}
                    </div>
                    <div class="status-sub" v-if="detail?.flowStatus === 1">
                        距离执行时间还差 {{ daysDiff }} 天
                    </div>
                </div>
            </div>

            <div class="work-wrap">
                <!-- 农事组信息 -->
                <!-- <div class="box-wrap group-info group-box">
                    <div class="group-name">
                        农事组：
                        <span class="group-name-text">{{ detail.farmWorkName || detail.farmWorkLibName || "--" }}</span>
                    </div>
                </div> -->

                <!-- 每一段农事 -->
                <div v-for="(prescription, index) in stageList" :key="index" class="box-wrap stage-card"
                    :class="'status-' + prescription.tagType">
                    <div class="stage-header">
                        <div class="stage-title">{{ detail.farmWorkName }}</div>
                        <div class="title-tag" :class="'tag-' + prescription.tagType">{{ prescription.tagType === 0 ?
                            "待完成" : "已完成" }}</div>
                    </div>

                    <div class="stage-info">
                        <div class="form-item">
                            <div class="item-name">农事目的</div>
                            <div class="item-text">
                                {{ detail.purpose || prescription.name || "--" }}
                            </div>
                        </div>
                        <div class="form-item">
                            <div class="item-name">农事时间</div>
                            <div class="item-text">
                                {{ detail.intervelTime ? `间隔 ${detail.intervelTime} 天后 执行` : "--" }}
                            </div>
                        </div>
                        <div class="form-item">
                            <div class="item-name">执行区域</div>
                            <div class="item-text light-text">
                                桂味种植区域
                            </div>
                        </div>
                        <div class="form-item">
                            <div class="item-name">注意事项</div>
                            <div class="item-text">
                                {{ detail.remark || "--" }}
                            </div>
                        </div>
                        <div class="form-item">
                            <div class="item-name">药肥处方</div>
                        </div>
                    </div>

                    <!-- 执行方式 -->
                    <div class="stage-tabs">
                        <div v-for="tab in executionTabs" :key="tab.value" class="tab-pill"
                            :class="{ active: getStageExecutionMethod(index) === tab.value }"
                            @click="changeExecutionMethod(index, tab.value)">
                            {{ tab.label }}
                        </div>
                    </div>

                    <!-- 药物处方表 -->
                    <div class="prescription-wrap"
                        v-if="prescription.pesticideList && prescription.pesticideList.length">
                        <div class="prescription-table">
                            <div class="table-header">
                                <div class="col col-type">使用功效</div>
                                <div class="col col-name">药肥名称</div>
                                <div class="col col-ratio">药肥配比</div>
                            </div>

                            <div v-for="(item, i) in prescription.pesticideList" :key="i" class="table-row">
                                <div class="col col-type">
                                    {{ item.typeName || "--" }}
                                </div>
                                <div class="col col-name">
                                    {{ item.name || item.pesticideFertilizerName || "--" }}
                                </div>
                                <div class="col col-ratio">
                                    {{ getPesticideParam(item, index)?.ratio || "--" }}倍
                                </div>
                            </div>
                        </div>

                        <div v-if="hasRemark(prescription, index)" class="prescription-remark">
                            <span v-for="(item, idx) in [prescription.pesticideList[0]]" :key="idx">
                                <template v-if="getParamRemark(item, index)">
                                    {{ getParamRemark(item, index) }}
                                    <br />
                                </template>
                            </span>
                        </div>
                    </div>


                    <!-- 执行照片 -->
                    <div class="photo-box" v-if="prescription.cropAlbum && prescription.cropAlbum.length">
                        <div class="photo-title">执行照片</div>
                        <div class="photo-img-wrap">
                            <photo-provider :photo-closable="true">
                                <photo-consumer v-for="(src, index) in prescription.cropAlbum" intro="执行照片" :key="index"
                                    :src="base_img_url2 + src.filename">
                                    <div class="photo-img">
                                        <img :src="base_img_url2 + src.filename" />
                                    </div>
                                </photo-consumer>
                            </photo-provider>
                        </div>
                    </div>

                    <!-- 执行操作 -->
                    <div class="execute-action" v-if="info?.appType === 1 && prescription.tagType === 0">
                        <div class="action-item second" @click="handleRemind">稍后执行</div>
                        <div class="action-item primary" @click="handleExecute">我已完成</div>
                    </div>
                </div>

                <!-- 底部按钮 -->
                <div class="fixed-btn-wrap" v-if="info?.appType === 2">
                    <div class="fixed-btn" @click="handleConvert">
                        转发农事
                    </div>
                </div>
            </div>
        </div>
        <ExecutePopup ref="executePopupRef" />
    </div>
</template>

<script setup>
import wx from "weixin-js-sdk";
import customHeader from "@/components/customHeader.vue";
import { ref, computed, onActivated } from "vue";
import { useRoute, useRouter } from "vue-router";
import { formatDate } from "@/common/commonFun";
import ExecutePopup from "./components/executePopup.vue";
import { base_img_url2, resize_300 } from "@/api/config";

const route = useRoute();
const router = useRouter();
// const info = JSON.parse(localStorage.getItem("localUserInfo") || "{}");
const info = { appType: 1 };

const detail = ref({
    "consequenceText": "",
    "id": null,
    "reCheckText": "",
    "orderId": null,
    "farmWorkArrangeId": null,
    "farmName": "",
    "farmPoint": "",
    "area": null,
    "expert": null,
    "orderStatus": null,
    "activeStatus": null,
    "flowStatus": 1,
    "farmId": null,
    "regionId": null,
    "farmMiniUserId": null,
    "farmMiniUserName": "",
    "speciesId": "1",
    "speciesName": "",
    "agriculturalId": null,
    "agriculturalIcon": "",
    "farmWorkId": "793434539249635329",
    "farmWorkLibId": "793434539249635329",
    "farmWorkLibName": "第一段蒂蛀虫防治",
    "farmWorkName": "第一段蒂蛀虫防治",
    "expertName": "",
    "expertUserName": "",
    "expertIcon": "",
    "expertUserIcon": "",
    "icon": null,
    "indexName": "",
    "indexChart": [],
    "executeDate": "2026-03-15",
    "intervelTime": 10,
    "executeDeadlineDate": null,
    "expectedExecuteDate": null,
    "finishDate": null,
    "checkDate": null,
    "beforeExecuteDate": null,
    "indexJson": "",
    "expertPrescription": "",
    "code": "793434539249635328",
    "condition": "",
    "solarName": "",
    "reCheck": null,
    "remark": "严禁低温寒潮、霜冻、倒春寒前24小时内追肥，避免根系、叶片受刺激引发冻害、肥害。",
    "menu": null,
    "num": null,
    "purpose": "营养",
    "type": 1,
    "farmWorkType": 2,
    "farmWorkTypeName": "",
    "execute": null,
    "updateDate0": null,
    "updateDate1": null,
    "updateDate2": null,
    "updateDate3": null,
    "updateDate4": null,
    "updateDate5": null,
    "updateDate6": null,
    "confirmPicture": [],
    "executeEvidence": [],
    "reviewImage": [],
    "reviewImage2": [],
    "reviewDate": null,
    "reviewDate2": null,
    "serviceRegion": "",
    "usageMode": "",
    "serviceMain": "",
    "executeMain": "",
    "storeShortName": "",
    "weatherWarningMsg": "",
    "userEvaluation": null,
    "executeBlueZones": [],
    "isMaster": null,
    "isEdit": null,
    "selfExec": null,
    "defaultFarmWork": null,
    "isPublic": null,
    "users": [],
    "groupList": [
        {
            "name": "蒂蛀虫防治",
            "tagType": 1,
            "cropAlbum": [
                {
                    "filename": "6e707c1f-7095-409e-8b3a-2633e7b36bd5/1e2dc0e7-6f8b-4952-a574-8e8e0713529c/DJI_202601251415_001_1e2dc0e7-6f8b-4952-a574-8e8e0713529c/DJI_20260125141713_0003_V_code-ws0gefwtn5n4.jpeg"
                },
                {
                    "filename": "dfb387fa-e7d3-4f49-a40c-fcbb9be2baf9/c727d4e9-f5bb-4e40-be2d-efdec3b91702/DJI_202511270800_001_c727d4e9-f5bb-4e40-be2d-efdec3b91702/DJI_20251127080720_0056_V_code-ws0gefyb37kp.jpeg"
                }
            ],
            "pesticideList": [
                {
                    "code": "1009",
                    "name": "化学水溶肥",
                    "typeName": "氮肥",
                    "params": [
                        {
                            "dosage": "50",
                            "executionMethod": 1,
                            "ratio": "30000",
                            "remark": "飞行参数设置为***，飞行速度设置为飞行参数设置为***，飞行速度设置为"
                        },
                        {
                            "dosage": "21",
                            "executionMethod": 2,
                            "ratio": "221",
                            "remark": "rengong"
                        },
                        {
                            "dosage": "11",
                            "executionMethod": 3,
                            "ratio": "111",
                            "remark": "dimian"
                        }
                    ]
                },
                {
                    "code": "1010",
                    "name": "化学水溶肥2",
                    "typeName": "营养",
                    "params": [
                        {
                            "dosage": "0.5",
                            "executionMethod": 1,
                            "ratio": "30000",
                            "remark": "zhibaoji"
                        },
                        {
                            "dosage": "22",
                            "executionMethod": 2,
                            "ratio": "222",
                            "remark": "rengong"
                        },
                        {
                            "dosage": "12",
                            "executionMethod": 3,
                            "ratio": "112",
                            "remark": "dimian"
                        }
                    ]
                },
                {
                    "code": "1011",
                    "name": "化学水溶肥3",
                    "typeName": "营养",
                    "params": [
                        {
                            "dosage": "60",
                            "executionMethod": 1,
                            "ratio": "30000",
                            "remark": "zhibaoji"
                        },
                        {
                            "dosage": "23",
                            "executionMethod": 2,
                            "ratio": "223",
                            "remark": "rengong"
                        },
                        {
                            "dosage": "13",
                            "executionMethod": 3,
                            "ratio": "113",
                            "remark": "dimian"
                        }
                    ]
                }
            ],
        },
        {
            "name": "蒂蛀虫防治",
            "tagType": 0,
            "pesticideList": [
                {
                    "code": "1009",
                    "name": "化学水溶肥22",
                    "typeName": "氮肥",
                    "params": [
                        {
                            "dosage": "50",
                            "executionMethod": 1,
                            "ratio": "30000",
                            "remark": "zhibaoji"
                        },
                        {
                            "dosage": "21",
                            "executionMethod": 2,
                            "ratio": "221",
                            "remark": "rengong"
                        },
                        {
                            "dosage": "11",
                            "executionMethod": 3,
                            "ratio": "111",
                            "remark": "dimian"
                        }
                    ]
                },
                {
                    "code": "1010",
                    "name": "化学水溶肥222",
                    "typeName": "营养",
                    "params": [
                        {
                            "dosage": "0.5",
                            "executionMethod": 1,
                            "ratio": "30000",
                            "remark": "zhibaoji"
                        },
                        {
                            "dosage": "22",
                            "executionMethod": 2,
                            "ratio": "222",
                            "remark": "rengong"
                        },
                        {
                            "dosage": "12",
                            "executionMethod": 3,
                            "ratio": "112",
                            "remark": "dimian"
                        }
                    ]
                },
                {
                    "code": "1011",
                    "name": "化学水溶肥223",
                    "typeName": "营养",
                    "params": [
                        {
                            "dosage": "60",
                            "executionMethod": 1,
                            "ratio": "30000",
                            "remark": "zhibaoji"
                        },
                        {
                            "dosage": "23",
                            "executionMethod": 2,
                            "ratio": "223",
                            "remark": "rengong"
                        },
                        {
                            "dosage": "13",
                            "executionMethod": 3,
                            "ratio": "113",
                            "remark": "dimian"
                        }
                    ]
                }
            ],
        },
    ],
    "needReview": null,
    "conditionList": [],
    "actualAgriculturalInput": null,
    "actualFarmServiceInput": null,
    "actualTotalInput": null,
    "executeName": "",
    "executorIcon": "",
    "executorUserId": null,
    "postId": "806490699515039744"
});


// 计算距离执行时间的天数差
const daysDiff = computed(() => {
    if (!detail.value?.executeDate) {
        return 0;
    }

    const executeDate = new Date(detail.value.executeDate);
    const today = new Date();

    // 将时间设置为 00:00:00，只比较日期
    executeDate.setHours(0, 0, 0, 0);
    today.setHours(0, 0, 0, 0);

    // 计算天数差（毫秒转天数）
    const diffTime = executeDate.getTime() - today.getTime();
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

    return diffDays;
});

// 执行方式 Tab 配置
const executionTabs = [
    { label: "植保机", value: 1 },
    { label: "人工手持", value: 2 },
    { label: "地面机械", value: 3 }
];
// 每一段农事的当前执行方式（索引 -> 执行方式），默认 1：植保机
const stageExecutionMethods = ref({});
const executePopupRef = ref(null);
const statusText = computed(() => {
    // 简单根据 flowStatus 判断，默认“待触发”
    if (detail.value.flowStatus === 1) return "待完成";
    if (detail.value.flowStatus === 2) return "已完成";
    return "待触发";
});

const triggerDateText = computed(() => {
    if (!detail.value.executeDate) return "";
    const d = formatDate(detail.value.executeDate);
    return d.replace(/-/g, ".");
});

const stageList = computed(() => detail.value.groupList || []);


const hasRemark = (prescription, stageIndex) => {
    if (!prescription?.pesticideList || !Array.isArray(prescription.pesticideList)) return false;
    const currentMethod = getStageExecutionMethod(stageIndex);
    return prescription.pesticideList.some((item) => {
        if (!item.params || !Array.isArray(item.params)) return false;
        const p = item.params.find((param) => param.executionMethod === currentMethod);
        return !!(p && p.remark);
    });
};

const handleExecute = () => {
    executePopupRef.value.openPopup();
};

const handleRemind = () => {
    executePopupRef.value.showRemindPopup();
};

const handleBack = () => {
    router.back();
};

const handleConvert = () => {
    const query = {
        askInfo: { title: "农情互动", content: "是否分享该互动给好友" },
        shareText: '邀请您农情互动，精准匹配种植方案',
        targetUrl: `interaction`,
        paramsPage: JSON.stringify({ id: detail.value.id }),
        imageUrl: 'https://birdseye-img.sysuimars.com/birdseye-look-mini/work_cover.png',
    };
    wx.miniProgram.navigateTo({
        url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=sharePage`,
    });
};

// 获取当前段的执行方式
const getStageExecutionMethod = (stageIndex) => {
    const val = stageExecutionMethods.value[stageIndex];
    return val || 1;
};

// 根据当前执行方式，获取对应的参数（配比、单亩用量、备注）
const getPesticideParam = (item, stageIndex) => {
    if (!item?.params || !Array.isArray(item.params)) return null;
    const currentMethod = getStageExecutionMethod(stageIndex);
    return (
        item.params.find((param) => param.executionMethod === currentMethod) || null
    );
};

const getParamRemark = (item, stageIndex) => {
    const param = getPesticideParam(item, stageIndex);
    return param?.remark || item.remark || "";
};

const changeExecutionMethod = (stageIndex, value) => {
    stageExecutionMethods.value = {
        ...stageExecutionMethods.value,
        [stageIndex]: value
    };
};
</script>

<style scoped lang="scss">
.work-detail {
    height: 100vh;
    background: #f2f3f5;
    display: flex;
    flex-direction: column;

    .work-detail-content {
        flex: 1;
        overflow: auto;
    }
}

.content-status {
    position: relative;
    padding: 21px 12px 0 12px;
    color: #fff;
    z-index: 1;
    height: 100px;
    box-sizing: border-box;

    &::after {
        content: "";
        z-index: -1;
        position: absolute;
        left: 0;
        top: 0;
        height: 100px;
        background: #C7C7C7;
        // background: #FF953D;
        width: 100%;
    }

    &.status-1 {
        &::after {
            background: #FF953D;
        }
    }

    .status-l {
        .status-title {
            font-size: 22px;
        }

        .status-sub {
            font-size: 14px;
        }
    }
}

.work-wrap {
    position: relative;
    top: -16px;
    padding: 0 12px 12px;
    z-index: 2;
    margin-bottom: 60px;
}

.box-wrap {
    background: #ffffff;
    border-radius: 8px;
    padding: 14px 10px 10px 10px;
    box-shadow: 0 2px 8px rgba(15, 35, 52, 0.06);
    border: 1px solid transparent;

    &.status-0 {
        border: 1px solid #FF953D;
    }
}

.photo-box {
    margin-top: 10px;
    border: 0.5px dashed #2199F8;
    border-radius: 5px;
    padding: 11px 10px;
    .photo-title {
        font-size: 14px;
        color: #000;
        padding-bottom: 8px;
    }
}

.group-info {
    margin-bottom: 10px;

    &.group-box {
        padding: 16px 10px;

        .group-name {
            font-size: 16px;
            color: #000;

            .group-name-text {
                color: #000;
            }
        }
    }

    .group-name {
        font-size: 14px;
        color: rgba(0, 0, 0, 0.2);

        .group-name-text {
            color: #767676;
        }
    }

    .group-sub {
        margin-top: 6px;
        font-size: 12px;
        color: rgba(0, 0, 0, 0.45);
        line-height: 1.5;
    }
}

.stage-card+.stage-card {
    margin-top: 10px;
}

.stage-card {

    .stage-header {
        padding-bottom: 12px;
        display: flex;
        align-items: center;
        gap: 5px;

        .stage-title {
            font-size: 16px;
            color: #000;
        }

        .title-tag {
            width: fit-content;
            font-size: 12px;
            height: 26px;
            line-height: 26px;
            color: #2199F8;
            background: rgba(33, 153, 248, 0.1);
            border-radius: 20px;
            padding: 0 8px;
        }

        .tag-0 {
            color: #FF953D;
            background: rgba(255, 149, 61, 0.1);
        }
    }

    .stage-info {
        padding: 8px 0 2px;
        border-top: 1px solid #f5f5f5;
    }
}

.form-item {
    display: flex;
    font-size: 14px;
    color: #767676;
    margin-top: 4px;

    .item-name {
        padding-right: 26px;
        color: rgba(0, 0, 0, 0.2);
    }

    .item-text {
        flex: 1;
        line-height: 21px;

        &.light-text {
            color: #2199F8;
        }
    }
}

.stage-tabs {
    display: inline-flex;
    gap: 8px;
    margin-top: 8px;

    .tab-pill {
        padding: 0 8px;
        font-size: 14px;
        text-align: center;
        border-radius: 2px;
        height: 28px;
        line-height: 28px;
        color: #767676;
        background: rgba(171, 171, 171, 0.1);

        &.active {
            background: rgba(33, 153, 248, 0.1);
            color: #2199F8;
        }
    }
}

.prescription-wrap {
    margin-top: 10px;
    overflow: hidden;

    .prescription-title {
        padding: 8px 10px;
        font-size: 13px;
        font-weight: 500;
        border-bottom: 1px solid rgba(225, 225, 225, 0.6);
    }
}

.prescription-table {
    font-size: 12px;
    text-align: center;
    border-radius: 6px;
    border: 1px solid rgba(225, 225, 225, 0.6);

    .table-header {
        display: flex;
        background: rgba(171, 171, 171, 0.1);
        padding: 9px 6px;
        color: #767676;
    }

    .table-row {
        display: flex;
        padding: 12px 6px;
        border-bottom: 1px solid rgba(0, 0, 0, 0.08);
        color: rgba(0, 0, 0, 0.76);

        &:last-child {
            border-bottom: none;
        }
    }

    .col {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 2px;
    }

    .col-type {
        width: 56px;
    }

    .col-name {
        flex: 1;
    }

    .col-ratio {
        width: 64px;
    }

    .col-dose {
        width: 64px;
    }
}

.prescription-remark {
    margin-top: 8px;
    padding: 7px 10px;
    border-radius: 6px;
    color: #767676;
    background: rgba(171, 171, 171, 0.1);
    line-height: 21px;
}


.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;
        }
    }
}

.execute-action {
    margin-top: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 16px;

    .action-item {
        padding: 0 16px;
        height: 32px;
        line-height: 32px;
        border-radius: 16px;
        box-sizing: border-box;
        font-size: 14px;

        &.second {
            background: #ffffff;
            border: 0.5px solid rgba(153, 153, 153, 0.5);
            color: #999999;
        }

        &.primary {
            background: linear-gradient(180deg, #8ACBFF 0%, #2199F8 100%);
            color: #ffffff;
        }
    }
}

.fixed-btn-wrap {
    display: flex;
    justify-content: center;
    position: fixed;
    bottom: 0px;
    left: 0;
    right: 0;
    background: #fff;
    padding: 10px 12px;
    box-sizing: border-box;
    // box-shadow: 0 -2px 8px rgba(15, 35, 52, 0.06);
    box-shadow: 2px 2px 4.5px 0px #00000066;

    .fixed-btn {
        min-width: 110px;
        height: 40px;
        line-height: 40px;
        text-align: center;
        border-radius: 20px;
        background: linear-gradient(180deg, #70bffe, #2199f8);
        color: #ffffff;
        font-size: 14px;
    }
}
</style>
