<template>
    <div class="agricultural-dynamics">
        <!-- 任务列表 -->
        <div class="task-list">
            <div v-for="(task, index) in taskList" :key="index" class="task-item">
                <div class="task-content" @click="handleTaskAction(task)">
                    <div class="task-header">
                        <div class="task-status-tag">{{ task.flowStatus === 4 ? '待完成' : '待复核' }}</div>
                        <div class="task-title">{{ task.farmWorkName }}</div>
                    </div>
                    <div class="task-time" v-if="task.flowStatus === 5">
                        复核时间 
                    {{ task.reviewDate }}</div>
                    <div class="task-time" v-if="task.flowStatus === 4 && task.expectedExecuteDate">执行时间 {{ task.expectedExecuteDate }}</div>
                    <div class="task-time deadline" v-if="task.flowStatus === 4 && !task.expectedExecuteDate">截止时间 {{ task.executeDeadlineDate }}</div>
                </div>
                <div v-if="task.flowStatus === 5" class="task-action" :class="{ 'call-text': getButtonText(task) }" @click="handleAction(task)">
                    {{ getButtonText(task) ? '提醒复核' : '上传复核照片' }}
                </div>
                <div v-else-if="task.flowStatus === 4 && task.expectedExecuteDate" class="task-action" :class="{ 'call-text': getButtonText(task) }" @click="showOfferPopup(task)">
                    {{ getButtonText(task) ? "提醒执行" : "上传照片" }}
                </div>
                <div v-else-if="task.flowStatus === 4 && !task.expectedExecuteDate" class="task-action orange" :class="{ 'call-text': getButtonText(task) }" @click="selectExecuteTime(task)">
                    {{ getButtonText(task) ? "提醒确认执行时间" : "确认执行时间" }}
                </div>
            </div>
        </div>

        <div class="title">农情互动</div>
        <!-- 内容区域 -->
        <div class="agricultural-list">
            <div v-if="!unansweredList.length" class="empty-block">暂无数据</div>
            <template v-else>
                <div class="agricultural-item" v-for="(item, index) in unansweredList" :key="index">
                    <!-- 头部区域 -->
                    <div class="header-section">
                        <div class="header-left">
                            <div class="farm-name van-ellipsis">{{ item.farmName }}</div>
                            <div class="tag-group">
                                <div class="tag tag-blue">{{ item.typeName }}</div>
                                <div class="tag" :class="{'tag-orange': item.userType === 2}">{{ item.userType === 1 ? '普通客户' : '托管客户' }}</div>
                            </div>
                        </div>
                        <div class="remind-btn" @click="handleRemind(item)">提醒客户</div>
                    </div>
                    <!-- 警告通知块 -->
                    <div
                        class="warning-block"
                        v-if="item.latestPhenologyProgressBroadcast"
                        v-html="item.latestPhenologyProgressBroadcast?.content"
                    ></div>

                    <!-- 时间轴组件，只负责时间轴区域 -->
                    <AgriculturalInteractionCard :item="item" @updateList="updateAllData" />
                </div>
            </template>
        </div>
    </div>
    <offer-popup ref="offerPopupRef" @uploadSuccess="getTaskList"></offer-popup>

    <!-- 确认执行时间 -->
    <calendar
        teleport="#app"
        v-model:show="showCalendar"
        @confirm="onConfirmExecuteTime"
        :min-date="minDate"
        :max-date="maxDate"
    />

    <!-- 上传复核照片 -->
    <upload-execute ref="uploadExecuteRef" :onlyShare="false" @uploadSuccess="handleUploadSuccess" />
</template>

<script setup>
import router from "@/router";
import { ref, onMounted, onActivated } from "vue";
import { Calendar } from "vant";
import wx from "weixin-js-sdk";
import { ElMessage } from "element-plus";
import offerPopup from "@/components/popup/offerPopup.vue";
import AgriculturalInteractionCard from "@/components/pageComponents/AgriculturalInteractionCard.vue";
import { formatDate } from "@/common/commonFun";
import uploadExecute from "@/views/old_mini/task_condition/components/uploadExecute.vue";
// 任务列表数据
const taskList = ref([]);

const handleTaskAction = (item) => {
    router.push({
        path: "/completed_work",
        query: { miniJson: JSON.stringify({ id: item.id }) },
    });
};

// 计算复核时间：executeDate + reviewIntervalDays
const calculateReviewDate = (task) => {
    if (!task?.executeDate) {
        return "--";
    }

    const executeDate = new Date(task.executeDate);
    const reviewIntervalDays = Number(task?.reviewIntervalDays || 0);

    // 将执行日期加上间隔天数
    executeDate.setDate(executeDate.getDate() + reviewIntervalDays);

    // 格式化为 YYYY-MM-DD
    const year = executeDate.getFullYear();
    const month = String(executeDate.getMonth() + 1).padStart(2, "0");
    const day = String(executeDate.getDate()).padStart(2, "0");

    return `${year}-${month}-${day}`;
};

onMounted(() => {
    const userInfo = JSON.parse(localStorage.getItem("localUserInfo"));
    agriculturalRole.value = userInfo.agriculturalRole;
    userId.value = userInfo.id;
});

const agriculturalRole = ref(null);
const userId = ref(null);

const offerPopupRef = ref(null);
const showOfferPopup = (item) => {
    if(getButtonText(item)) {
        const query = {
            askInfo: { title: "农事提醒", content: "是否分享该农事提醒给好友" },
            shareText: '向您分享了一条农事执行提醒，请您尽快执行',
            targetUrl: `completed_work`,
            paramsPage: JSON.stringify({id: item.id}),
            imageUrl: 'https://birdseye-img.sysuimars.com/birdseye-look-mini/invite_bg.png',
        };
        wx.miniProgram.navigateTo({
            url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=sharePage`,
        });
    }else{
        offerPopupRef.value.openPopup(item);
    }
};

const uploadExecuteRef = ref(null);
function handleAction(item) {
    if(getButtonText(item)) {
        const query = {
            askInfo: { title: "农事提醒", content: "是否分享该农事提醒给好友" },
            shareText: '向您分享了一条农事复核提醒，请您尽快复核',
            targetUrl: `review_work`,
            paramsPage: JSON.stringify({id: item.id}),
            imageUrl: 'https://birdseye-img.sysuimars.com/birdseye-look-mini/invite_bg.png',
        };
        wx.miniProgram.navigateTo({
            url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=sharePage`,
        });
    }else{
        setTimeout(() => {
            uploadExecuteRef.value.showPopup(item, "share-sheet");
        }, 10);
    }
}

function handleUploadSuccess() {
    getTaskList();
}

const selectExecuteTime = (item) => {
    if (getButtonText(item)) {
        const query = {
            askInfo: { title: "农事提醒", content: "是否分享该农事提醒给好友" },
            shareText: '向您分享了一条农事提醒，请您尽快确认执行时间',
            targetUrl: `completed_work`,
            paramsPage: JSON.stringify({id: item.id}),
            imageUrl: 'https://birdseye-img.sysuimars.com/birdseye-look-mini/invite_bg.png',
        };
        wx.miniProgram.navigateTo({
            url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=sharePage`,
        });
    } else {
        executeItem.value = item;
        maxDate.value = new Date(item.executeDeadlineDate);
        showCalendar.value = true;
    }
};

// 获取上传按钮的文本（计算属性方式）
const getButtonText = (item) => {
    return agriculturalRole.value === 1 || (agriculturalRole.value === 2 && item.executorUserId != userId.value);
};

const showCalendar = ref(false);
const maxDate = ref();
// 最小日期设置为今天，今天可以选择
const minDate = new Date();
const executeItem = ref(null);

const onConfirmExecuteTime = (date) => {
    showCalendar.value = false;
    VE_API.z_farm_work_record
        .updateExpectedExecuteDate({ recordId: executeItem.value.id, expectedExecuteDate: formatDate(date) })
        .then((res) => {
            if (res.code === 0) {
                ElMessage.success("操作成功");
                getTaskList();
            }
        });
};

const handleRemind = (item) => {
    router.push(`/remind_customer?farmId=${item.farmId}`);
};

onActivated(() => {
    updateAllData();
});

const updateAllData = () => {
    getUnansweredFarms();
    getTaskList();
};
//农情互动的农场列表接口（分页）
const getTaskList = async () => {
    // 同时获取待完成(4)和待复核(5)的任务
    const [res4, res5] = await Promise.all([
        VE_API.z_farm_work_record.generalPendingFarmWork({ role: 2, flowStatus: 4 }),
        VE_API.z_farm_work_record.generalPendingFarmWork({ role: 2, flowStatus: 5 })
    ]);
    
    const tasks4 = (res4.data || []).map(task => ({
        ...task,
        reviewDate: calculateReviewDate(task)
    }));
    
    const tasks5 = (res5.data || []).map(task => ({
        ...task,
        reviewDate: calculateReviewDate(task)
    }));
    
    // 合并两种状态的任务，总共取前2个
    taskList.value = [...tasks4, ...tasks5].slice(0, 2);
};

const unansweredList = ref([]);
const getUnansweredFarms = async () => {
    const params = {
        page: 0,
        limit: 3,
        flowStatus: 5,
    };
    const res = await VE_API.home.listUnansweredFarms(params);
    unansweredList.value = (res.data || []).map((item) => ({
        ...item,
        timelineList: [],
    }));

    // 串行请求，一个完成后再请求下一个
    if (unansweredList.value.length) {
        for (let i = 0; i < unansweredList.value.length; i++) {
            await getFutureFarmWorkWarning(unansweredList.value[i]);
        }
    }

    unansweredList.value = unansweredList.value.filter(item => item.timelineList.length > 0);
};

//查询未来农事预警
const getFutureFarmWorkWarning = async (item) => {
    const res = await VE_API.home.listFutureFarmWorkWarning({ farmId: item.farmId });
    item.timelineList = res.data || [];
};
</script>

<style scoped lang="scss">
.agricultural-dynamics {
    padding: 0 10px;

    // 任务列表样式
    .task-list {
        .task-item {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background-color: #ffffff;
            border-radius: 8px;
            padding: 12px;
            margin-top: 10px;
            position: relative;
            overflow: hidden;
            &::after {
                content: "";
                position: absolute;
                top: -10px;
                right: 0;
                width: 72px;
                height: 72px;
                pointer-events: none;
                background: url("@/assets/img/home/task-icon.png") no-repeat center center / 100% 100%;
            }

            .task-content {
                flex: 1;
                .task-header {
                    display: flex;
                    align-items: center;
                    margin-bottom: 4px;
                    gap: 8px;
                }

                .task-status-tag {
                    background-color: rgba(33, 153, 248, 0.1);
                    color: #2199f8;
                    font-size: 12px;
                    padding: 1px 6px;
                    border-radius: 2px;
                }

                .task-title {
                    font-size: 16px;
                    font-weight: 500;
                    color: #1d2129;
                }

                .task-time {
                    font-size: 12px;
                    color: rgba(78, 89, 105, 0.5);
                    &.deadline {
                        color: rgba(255, 85, 85, 0.7);
                    }
                }
            }

            .task-action {
                flex: none;
                background-color: rgba(33, 153, 248, 0.1);
                color: #2199f8;
                border-radius: 25px;
                padding: 0px 14px;
                font-size: 12px;
                height: 28px;
                box-sizing: border-box;
                line-height: 28px;
                &.orange {
                    color: #ff953d;
                    background: rgba(255, 149, 61, 0.1);
                }
                &.call-text {
                    color: #868686;
                    background: none;
                    border: 0.5px solid #D1D1D1;
                }
            }
        }
    }

    .title {
        font-size: 16px;
        font-weight: 500;
        color: #1d2129;
        margin-top: 10px;
    }

    .agricultural-list {
        .empty-block {
            display: flex;
            align-items: center;
            justify-content: center;
            height: 120px;
            color: #a0a0a0;
            font-size: 14px;
            background-color: #ffffff;
            border-radius: 8px;
            margin-top: 8px;
        }

        .agricultural-item {
            background-color: #ffffff;
            border-radius: 8px;
            padding: 8px 12px;
            margin-top: 8px;

            // 头部区域样式
            .header-section {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding-bottom: 5px;
                border-bottom: 0.5px solid rgba(0, 0, 0, 0.1);

                .header-left {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    width: calc(100% - 80px);
                    .farm-name {
                        font-size: 16px;
                        font-weight: 500;
                        color: #1d2129;
                        max-width: calc(100% - 130px);
                    }

                    .tag-group {
                        display: flex;
                        gap: 4px;
                        .tag {
                            padding: 2px 8px;
                            border-radius: 2px;
                            font-size: 12px;
                            color: #848282;
                            background-color: rgba(148, 148, 148, 0.1);

                            &.tag-blue {
                                background-color: #e8f3ff;
                                color: #2199f8;
                            }

                            &.tag-orange {
                                background-color: rgba(255, 149, 61, 0.1);
                                color: #ff953d;
                            }
                        }
                    }
                }

                .remind-btn {
                    background-color: #2199f8;
                    color: #ffffff;
                    border-radius: 25px;
                    padding: 7px 12px;
                    font-size: 12px;
                }
            }

            // 警告通知块样式
            .warning-block {
                background-color: rgba(33, 153, 248, 0.1);
                border-radius: 5px;
                padding: 5px;
                margin-top: 8px;
                font-size: 12px;
                color: #252525;
                ::v-deep {
                    p {
                        padding: 0;
                        margin: 0;
                    }
                }
            }
        }
    }
}
</style>

<style lang="scss">
.van-calendar__popup {
    z-index: 9999 !important;
}
</style>
