<template>
    <div class="farm-dynamics">
        <tab-list v-model="activePlanIndex" :tabs="filterType" @change="handlePlanClick" />
        <div class="task-content">
            <div class="expert-content">
                <empty
                    v-if="contentData.length === 0"
                    image="https://birdseye-img.sysuimars.com/birdseye-look-mini/custom-empty-image.png"
                    image-size="80"
                    description="暂无数据"
                    class="empty-state"
                />
                <div v-for="(section, index) in contentData" :key="index" class="content-section">
                    <div class="section-id" :id="section.targetId"></div>
                    <record-item
                        :record-item-data="section"
                        title-mode="default"
                        onlyRecipeName
                        titleRightDotText="全区"
                        titleRightType="dot"
                        class="recipe-item"
                        :showFarmImage="activePlanIndex == 5 ? true : false"
                        :content-mode="activePlanIndex == 5 ? 'serviceDetail' : ''"
                        @click="handleClick(section)"
                    >
                        <template #footer>
                            <div class="action-group">
                                <div class="action-l">查看详情</div>
                                <div class="action-r" v-if="section.farmWorkDetail?.flowStatus === 0 && !section.isPublic">
                                    <div class="action-item warning-item" @click.stop="handleApply(section)">
                                        发起需求
                                    </div>
                                    <div class="action-item primary-item" @click.stop="handleConfirmComplete(section)">确认并完成</div>
                                </div>
                                <div class="action-r" v-else-if="section.farmWorkDetail?.flowStatus === 0 && section.isPublic">
                                    <div
                                        class="action-item second-item"
                                        @click.stop="handleOperation(section, 'cancel')"
                                    >
                                        取消发起
                                    </div>
                                </div>
                                <div class="action-r" v-else-if="section.farmWorkDetail?.flowStatus === 4">
                                    <div class="action-item warning-item has-applied">已锁单</div>
                                    <div
                                        v-if="section.executeEvidence?.length"
                                        class="action-item primary-item"
                                        @click.stop="handleOperation(section, 'confirmComplete')"
                                    >
                                        确认执行完成
                                    </div>
                                    <div
                                        v-else
                                        class="action-item primary-item"
                                        @click.stop="handleApply(section, 'remindExecute')"
                                    >
                                        提醒对方执行
                                    </div>
                                </div>
                                <div class="action-r" v-else-if="activePlanIndex == 5">
                                    <!-- <div
                                        class="action-item warning-item"
                                        :class="{ 'has-applied': section.hasApplied }"
                                        @click="handleApply(section, index)"
                                    >
                                        {{ section.hasApplied ? "已发起需求" : "发起需求" }}
                                    </div> -->
                                    <div
                                        class="action-item primary-item"
                                        v-if="!section.farmWorkDetail?.reviewImage?.length"
                                        @click.stop="handleUploadPhoto(section)"
                                    >
                                        上传照片
                                    </div>
                                </div>
                            </div>
                        </template>
                    </record-item>
                </div>
            </div>
        </div>
    </div>
    <!-- 需求发送成功弹窗 -->
    <tip-popup v-model:show="showApplyPopup" type="success" text="需求发送成功" />
    <!-- 发起需求成功弹窗 -->
    <fn-share-sheet :class="type === 'manage' ? '' : 'share-sheet'" v-model:show="showShare" @select="onSelect" :options="options" />
    <!-- 提醒对方执行弹窗 -->
    <upload-execute ref="uploadExecuteRef" onlyShare />
    <!-- 上传照片弹窗 -->
    <review-upload-popup v-model="showUpload" :record-id="sectionId" @success="getContentData" />
</template>
<script setup>
import { ref, onActivated ,onMounted} from "vue";
import recordItem from "@/components/recordItem.vue";
import tabList from "@/components/pageComponents/TabList.vue";
import { Popup, Empty } from "vant";
import { useRouter } from "vue-router";
import wx from "weixin-js-sdk";
import uploadExecute from "@/views/old_mini/task_condition/components/uploadExecute.vue";
import tipPopup from "@/components/popup/tipPopup.vue";
import FnShareSheet from "@/components/pageComponents/FnShareSheet.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { base_img_url2 } from "@/api/config";
import reviewUploadPopup from "@/components/popup/reviewUploadPopup.vue";
const router = useRouter();

const props = defineProps({
    type: {
        type: String,
        default: "",
    },
    active: {
        type: Number,
        default: 0,
    },
});

const handleConfirmComplete = (section) => {
    ElMessage.warning("该功能正在升级中，敬请期待");
};

const showApplyPopup = ref(false);
const uploadExecuteRef = ref(null);

const showShare = ref(false);
const options = ref([
    {
        name: "需求大厅",
        icon: "https://birdseye-img.sysuimars.com/birdseye-look-mini/xuqiu-icon.png",
        type: "demandHall",
    },
    { name: "微信", icon: "wechat", type: "wechat" },
]);

// 获取触发图片
const triggerImg = ref([]);
const getTriggerImg = async () => {
    const { data } = await VE_API.z_farm_work_record.getTriggerImg({ farmWorkRecordId: currentSection.value.id });
    triggerImg.value = data || [];
}

const onSelect = async (option) => {
    if (option.type === "wechat") {
        await getTriggerImg();
        const query = {
            askInfo: { title: "农事需求", content: "是否分享该农事需求给好友" },
            shareText: `发起了 ${currentSection.value.farmWorkName} 的接单需求 请查看！`,
            id: currentSection.value.id,
            farmWorkOrderId: currentSection.value.orderId,
            postImg: triggerImg.value.length ? base_img_url2 + triggerImg.value[triggerImg.value.length - 1].cloudFilename : ''
        };
        wx.miniProgram.navigateTo({
            url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=priceSheet`,
        });
    } else {
        updatePublicStatus(1);
    }
};

const updatePublicStatus = (isPublic) => {
    return VE_API.z_farm_work_record.updatePublicStatus({ recordId: currentSection.value.id, isPublic }).then((res) => {
        if (res.code === 0) {
            getContentData();
        }
    });
};

const updateFlowStatus = (targetFlowStatus) => {
    return VE_API.z_farm_work_record.updateFlowStatus({ id: currentSection.value.id, targetFlowStatus }).then((res) => {
        if (res.code === 0) {
            if (targetFlowStatus === 2) {
                showApplyPopup.value = true;
            }
            getContentData();
        }
    });
};

// 取消发起需求/确认执行完成
const handleOperation = (section, type) => {
    currentSection.value = section;
    ElMessageBox.confirm(type === "cancel" ? "确认取消发起需求吗?" : "确认执行完成吗?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
    })
        .then(() => {
            if (type === "cancel") {
                updatePublicStatus(0);
            }else{
                updateFlowStatus(5);
            }
        })
        .catch(() => {});
};

const showUpload = ref(false);
const sectionId = ref(null);
// 上传照片处理函数
const handleUploadPhoto = ({ id }) => {
    showUpload.value = true;
    sectionId.value = id;
};

const filterType = ref([
    {
        title: "待确认",
        value: '0',
    },
    {
        title: "待完成",
        value: 4,
    },
    {
        title: "已完成",
        value: 5,
    },
]);

const activePlanIndex = ref('0');
const handlePlanClick = (value) => {
    activePlanIndex.value = value;
    getContentData();
};

onMounted(() => {
    getContentData();
});

onActivated(() => { 
    if(props.active == 0){
        getContentData();
    }
});

const contentData = ref([]);
const getContentData = async () => {
    const res = await VE_API.z_farm_work_record.getSimpleList({
        role: localStorage.getItem("SET_USER_CUR_ROLE"),
        flowStatus:activePlanIndex.value,
    });
    contentData.value = res.data;

    // 遍历数组，获取每一项的详情并合并
    if (res.data && res.data.length > 0) {
        const detailPromises = res.data.map((item) => getItemDetail(item.id));
        const detailResults = await Promise.all(detailPromises);

        // 将详情数据合并到对应的数组项中
        contentData.value = res.data.map((item, index) => {
            return {
                ...item,
                farmWorkDetail: detailResults[index][0],
                prescriptionList: detailResults[index][0]?.prescriptionList,
                reviewImage: detailResults[index][0]?.reviewImage,
            };
        });
    }
};

defineExpose({
    getContentData,
});

async function getItemDetail(id) {
    const { data } = await VE_API.z_farm_work_record.getDetail({ id });
    return data || {};
}

const currentSection = ref({});
const handleApply = (section, type) => {
    currentSection.value = section;
    if (type === "remindExecute") {
        const params = {
            id: section.id,
            farmMiniUserId: section.farmWorkDetail?.users[0]?.userId,
            farmWorkOrderId: section?.orderId,
            farmId: section?.farmId,
            farmWorkName: section?.farmWorkName,
            type: "remindExecute",
        };
        uploadExecuteRef.value.showPopup(params);
    } else {
        showShare.value = true;
    }
};

const handleClick = (section) => {
    if (activePlanIndex.value == 5) {
        router.push(`/review_work?json=${JSON.stringify({ id: section.id, goBack: true })}`);
    } else {
        router.push({
            path: "/completed_work",
            query: { json: JSON.stringify({ id: section.id }) },
        });
    }
};
</script>
<style lang="scss" scoped>
.farm-dynamics {
    width: 100%;
    height: 100vh;
    background: #f5f7fb;
    .task-content {
        display: flex;
        height: calc(100% - 140px);
        .expert-content {
            width: 100%;
            height: 100%;
            overflow: auto;
            padding: 10px;
            box-sizing: border-box;
            .empty-state {
                ::v-deep .van-empty {
                    padding: 40px 0;
                }
            }
            .content-section {
                position: relative;
                .section-id {
                    position: absolute;
                    top: 0;
                    width: 100%;
                    height: 1px;
                }
                .recipe-item {
                    border: 1px solid rgba(0, 0, 0, 0.1);
                }
            }
            .box-title {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding-bottom: 8px;
                .title-l {
                    font-size: 16px;
                    font-weight: 600;
                    color: #000;
                    .parent-text {
                        margin-left: 5px;
                        font-size: 12px;
                        font-weight: normal;
                        padding: 4px 6px;
                        border-radius: 14px;
                        background: rgba(119, 119, 119, 0.1);
                    }
                }
                .title-btn {
                    width: 24px;
                    height: 24px;
                    border-radius: 50%;
                    background: #2199f8;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                }
                .title-r {
                    display: flex;
                    align-items: center;
                    color: #393939;
                    font-size: 12px;
                    .r-dot {
                        width: 6px;
                        height: 6px;
                        border-radius: 50%;
                        background: #393939;
                        margin-right: 5px;
                    }
                }
            }
            .content-info {
                padding-top: 8px;
                .info-line {
                    font-size: 12px;
                    color: #bbbbbb;
                    margin-bottom: 8px;
                    line-height: 1.4;
                    .info-val {
                        color: #666666;
                    }
                }
                .review-title {
                    .info-val {
                        margin-top: 5px;
                    }
                }
                .review-image {
                    display: flex;
                    align-items: center;
                    gap: 8px;
                    img {
                        flex: 1;
                        height: 82px;
                        object-fit: cover;
                        border-radius: 4px;
                    }
                }
                .reminder-box {
                    background: linear-gradient(90deg, #d9ebfc, transparent);
                    border-radius: 4px;
                    padding: 6px 8px;
                    font-size: 12px;
                    color: #2e2e2e;
                    line-height: 1.4;
                    margin-top: 8px;
                    .highlight-number {
                        color: #2199f8;
                        font-weight: 500;
                    }
                }
            }
            .action-r {
                color: #1d2129;
            }
            .action-group {
                display: flex;
                align-items: center;
                justify-content: space-between;
                padding-top: 8px;
                margin-top: 8px;
                border-top: 1px solid #f5f5f5;
                .action-l {
                    font-size: 12px;
                }
            }
            .action-group {
                .action-r {
                    display: flex;
                    align-items: center;
                    .action-item {
                        padding: 0 11px;
                        height: 30px;
                        line-height: 30px;
                        border-radius: 20px;
                        font-size: 12px;
                        &.second-item {
                            background: rgba(137, 137, 137, 0.1);
                            color: #898989;
                        }
                        &.primary-item {
                            background: #2199f8;
                            color: #fff;
                        }
                        &.warning-item {
                            background: rgba(255, 131, 29, 0.1);
                            color: #ff831d;
                            &.has-applied {
                                background: transparent;
                                color: #afafaf;
                            }
                        }
                        &.cancel-item {
                            color: #676767;
                            border: 1px solid rgba(103, 103, 103, 0.2);
                        }
                    }
                    .action-item + .action-item {
                        margin-left: 5px;
                    }
                }
                .apply-action {
                    justify-content: flex-end;
                    .default-item {
                        border: 1px solid rgba(0, 0, 0, 0.4);
                        color: rgba(0, 0, 0, 0.4);
                    }
                }
            }
        }
    }
}
</style>
