<template>
    <div class="task-page" :style="{ height: `calc(100vh - ${tabBarHeight}px - 50px)` }">
        <div class="task-top">
            <div class="map-container" ref="mapContainer"></div>
            <div class="calendar-wrap">
                <calendar ref="calendarRef"></calendar>
            </div>
        </div>
        <div class="task-list">
            <div class="list-filter">
                <div class="filter-item" :class="{ active: activeIndex === 0 }" @click="handleActiveFilter(0)">
                    待确认({{ taskCounts[0] || 0 }})
                </div>
                <div class="filter-item" :class="{ active: activeIndex === 1 }" @click="handleActiveFilter(1)">
                    已确认({{ taskCounts[1] || 0 }})
                </div>
                <div class="filter-item" :class="{ active: activeIndex === 2 }" @click="handleActiveFilter(2)">
                    待完成({{ taskCounts[2] || 0 }})
                </div>
                <div class="filter-item" :class="{ active: activeIndex === 3 }" @click="handleActiveFilter(3)">
                    已完成({{ taskCounts[3] || 0 }})
                </div>
            </div>
            <div class="select-group">
                <el-select class="select-item" v-model="dateValue" placeholder="Select">
                    <el-option v-for="item in dateOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select class="select-item" v-model="areaValue" placeholder="Select">
                    <el-option v-for="item in areaOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select class="select-item" v-model="areaValue1" placeholder="Select">
                    <el-option v-for="item in areaOptions1" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </div>
            <!-- <div class="task-content-loading" v-if="loading && noData" v-loading="loading">
            </div> -->
            <div class="task-content" v-loading="loading">
                <div class="task-item" v-for="item in taskList" :key="item.id || item.workRecordId">
                    <task-item :status="activeIndex === 3 ? 1 : 0" :item-data="item">
                        <template #footer>
                            <div class="item-footer" v-if="activeIndex === 0 || activeIndex === 2">
                                <div class="footer-l" @click="toDetail(item)">
                                    查看详情
                                </div>
                                <div class="footer-r">
                                    <div class="btn second" @click="handleAction(item)">
                                        {{ activeIndex === 0 ? "忽略" : "转发给客户" }}
                                    </div>
                                    <div class="btn primary" @click="toPage(item)">
                                        {{ activeIndex === 0 ? "下发农事" : "请求确认" }}
                                    </div>
                                </div>
                            </div>
                            <div v-else-if="activeIndex === 1" class="item-footer">
                                <div class="footer-l" @click="toDetail(item)">
                                    查看详情
                                </div>
                                <div class="footer-r">
                                    <div class="btn second" @click="handleForward(item)">
                                        转发给客户
                                    </div>
                                    <div class="btn primary" @click="showPriceSheetPopup(item)">
                                        生成报价单
                                    </div>
                                </div>
                            </div>
                        </template>
                    </task-item>
                </div>
                <div class="empty-data" v-if="noData">暂无数据</div>
            </div>
        </div>
    </div>
    <upload-execute ref="uploadExecuteRef" :onlyShare="onlyShare" />

    <popup v-model:show="showTaskPopup" round class="task-tips-popup">
        <template v-if="taskPopupType === 'warning'">
            <img  class="create-farm-icon" src="@/assets/img/home/create-farm-icon.png" alt="" />
            <div class="create-farm-text">
                <div>您确认忽略 <span class="main-text">{{ currentTask?.farmName }}</span> 的 <span class="main-text">{{ currentTask?.farmWorkName }}</span> 农事吗</div>
            </div>
        </template>
        <template v-else>
            <img class="farm-check-icon" src="@/assets/img/home/right.png" alt="">
            <div class="create-farm-text success-text">农事已下发成功</div>
        </template>
        <div class="create-farm-btn" @click="handlePopupBtn">{{ taskPopupType === 'warning' ? '确认忽略' : '我知道了' }}</div>
    </popup>
    <!-- 服务报价单 -->
    <price-sheet-popup ref="priceSheetPopupRef"></price-sheet-popup>
</template>

<script setup>
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useStore } from "vuex";
import { Popup } from "vant";
import IndexMap from "../../farm_manage/map/index";
import taskItem from "@/components/taskItem.vue";
import calendar from "./calendar.vue"
import { useRouter } from "vue-router";
import uploadExecute from "./uploadExecute.vue";
import priceSheetPopup from "@/components/popup/priceSheetPopup.vue";
import wx from "weixin-js-sdk";
import { ElMessage } from "element-plus";

const store = useStore();
const router = useRouter();
const indexMap = new IndexMap();
const mapContainer = ref(null);
const tabBarHeight = computed(() => store.state.home.tabBarHeight);
const uploadExecuteRef = ref(null);
const dateValue = ref("1");
const calendarRef = ref(null);
const dateOptions = [
    { value: "1", label: "农事类型" },
    { value: "2", label: "2" },
    { value: "3", label: "3" },
];
const areaValue = ref("1");
const areaOptions = [
    { value: "1", label: "距离" },
    { value: "2", label: "2" },
    { value: "3", label: "3" },
];
const areaValue1 = ref("1");
const areaOptions1 = [
    { value: "1", label: "区域筛选" },
    { value: "2", label: "2" },
    { value: "3", label: "3" },
];

// 任务列表数据
const taskList = ref([]);
// 各状态任务数量
const taskCounts = ref([0, 0, 0]);
// 当前选中的筛选索引
const activeIndex = ref(0);
const noData = ref(false);
const loading = ref(false);

const showTaskPopup = ref(false);
const taskPopupType = ref('warning');

// 根据 activeIndex 计算 startFlowStatus
const getStartFlowStatus = (index) => {
    const statusMap = {
        0: 0, // 待确认
        1: '1,2,3', // 待完成
        2: 4, // 待完成
        3: 5  // 已完成
    };
    return statusMap[index] ?? 0;
};

// 获取单个状态的任务数量
function getTaskCount(flowStatus, index) {
    const location = store.state.home.miniUserLocationPoint;
    return VE_API.z_farm_work_record.getSimpleList({ role: 2, location, flowStatus }).then(({data}) => {
        if (Array.isArray(data)) {
            taskCounts.value[index] = data.length;
            calendarRef.value && calendarRef.value.setCounts(index, taskCounts.value[index])
            
            if (index === 2) {
                calendarRef.value && calendarRef.value.setSolarTerm(data)
                indexMap.initData(data)
            }
        } else if (data?.total !== undefined) {
            taskCounts.value[index] = data.total;
        } else {
            taskCounts.value[index] = 0;
        }
    }).catch((error) => {
        console.error(`获取状态${index}任务数量失败:`, error);
        taskCounts.value[index] = 0;
    });
}

// 初始化时获取所有状态的任务数量
function initTaskCounts() {
    const location = store.state.home.miniUserLocationPoint;
    // 并行请求三个状态的数量
    Promise.all([
        getTaskCount(0, 0),  // 待确认
        getTaskCount('1,2,3', 1),  // 待确认
        getTaskCount(4, 2),  // 待完成
        getTaskCount(5, 3)   // 已完成
    ]);
}

onMounted(() => {
    // 初始化时获取所有状态的数量
    initTaskCounts();
    // 加载当前选中状态的数据列表
    getSimpleList();
    const point = store.state.home.miniUserLocationPoint;
    nextTick(() => {
        indexMap.initMap(point, mapContainer.value, true);
    });
});

// 监听 activeIndex 变化，重新加载数据
watch(activeIndex, () => {
    getSimpleList();
});

function getSimpleList() {
    loading.value = true;
    noData.value = false;
    const location = store.state.home.miniUserLocationPoint;
    const startFlowStatus = getStartFlowStatus(activeIndex.value);
    VE_API.z_farm_work_record.getSimpleList({ role: 2, location, flowStatus: startFlowStatus }).then(({data}) => {
        loading.value = false;
        // 假设返回的数据结构是 { list: [], total: 0 } 或者直接是数组
        if (Array.isArray(data) && data.length > 0) {
            taskList.value = data;
            // 更新当前状态的数量
            taskCounts.value[activeIndex.value] = data.length;
            if (activeIndex.value === 2) {
                calendarRef.value && calendarRef.value.setSolarTerm(taskList.value)
                indexMap.initData(taskList.value)
            }
        } else {
            taskList.value = [];
            taskCounts.value[activeIndex.value] = 0;
            if (activeIndex.value === 2) {
                indexMap.initData(taskList.value)
                calendarRef.value && calendarRef.value.setSolarTerm(taskList.value)
            }
            noData.value = true;
        }
    }).catch((error) => {
        console.error('获取任务列表失败:', error);
        loading.value = false;
        taskList.value = [];
        noData.value = true;
    });
}

function handleActiveFilter(i) {
    activeIndex.value = i;
}

function toPage(item) {
    // router.push("/servicZes_agri")
    if (activeIndex.value === 2) {
        if (item?.executeEvidence?.length) {
            onlyShare.value = true;
        } else {
            onlyShare.value = false;
        }
        if(item.farmMiniUserId){
            setTimeout(() => {
                uploadExecuteRef.value.showPopup(item,'share-sheet');
            }, 10);
        }else{
            ElMessage.warning('尚未绑定用户,暂时无法分享')
        }
    } else {
        // 下发农事请求
        const data = {
            id: item.id,
        };
        VE_API.z_farm_work_record.issueFarmWorkRecord(data).then((res) => {
            if (res.code === 0) {
                taskPopupType.value = 'success';
                showTaskPopup.value = true;
                getSimpleList()
            }
        })
        // router.push("/service_agri");
    }
}

function toDetail(item) {
    if (activeIndex.value === 0) {
        router.push({
            path: "/modify_work",
            query: { json: JSON.stringify({ id: item.id }) }
        });
    } else {
        router.push({
            path: "/completed_work",
            query: { json: JSON.stringify({ id: item.id }) }
        });
    }
}

const priceSheetPopupRef = ref(null);
const showPriceSheetPopup = (item) => {
    VE_API.z_farm_work_record.getDetail({ id: item.id }).then(({ data }) => {
        const res = data[0];
        priceSheetPopupRef.value.handleShowPopup(res);
    });
};

const onlyShare = ref(false);
const currentTask = ref(null);
function handleAction(item) {
    if (activeIndex.value === 0) {
        taskPopupType.value = 'warning';
        showTaskPopup.value = true;
        currentTask.value = item;
    }else{
        onlyShare.value = true;
        if(item.farmMiniUserId){
            setTimeout(() => {
                uploadExecuteRef.value.showPopup(item,'share-sheet');
            }, 10);
        }else{
            ElMessage.warning('尚未绑定用户,暂时无法分享')
        }
    }
}

function handlePopupBtn() {
    showTaskPopup.value = false;
    if (taskPopupType.value === 'warning') {
        // 确认忽略
    } else {
        // 待确认
        getTaskCount('1,2,3', 1)
    }
}

function handleForward(item) {
    onlyShare.value = true;
    if(item.farmMiniUserId){
        setTimeout(() => {
            uploadExecuteRef.value.showPopup({...item, type:'quotation'},'share-sheet');
        }, 10);
    }else{
        ElMessage.warning('尚未绑定用户,暂时无法分享')
    }
}

</script>

<style lang="scss" scoped>
.task-page {
    width: 100%;
    height: calc(100vh - 50px - 50px);
    overflow: auto;
    box-sizing: border-box;
    background: #f5f7fb;
    .map-container {
        width: 100%;
        height: 162px;
        clip-path: inset(0px round 8px);
    }

    .select-group {
        display: flex;
        padding: 0 12px;
        .select-item {
            width: 100%;
            ::v-deep {
                .el-select__wrapper {
                    text-align: center;
                    gap: 2px;
                    box-shadow: none;
                    justify-content: center;
                    background: none;
                }
                .el-select__selection {
                    flex: none;
                    width: fit-content;
                }
                .el-select__placeholder {
                    position: static;
                    transform: none;
                    width: fit-content;
                    color: rgba(0, 0, 0, 0.2);
                }
                .el-select__caret {
                    color: rgba(0, 0, 0, 0.2);
                }
            }
        }
    }

    .calendar-wrap {
        padding: 10px 0 4px 0;
    }

    .task-top {
        padding: 10px 12px;
    }

    .task-content-loading {
        height: 80px;
        border-radius: 8px;
        position: absolute;
        top: 60px;
        left: 0;
        width: 100%;
    }

    .task-content {
        min-height: 80px;
    }

    .empty-data {
        text-align: center;
        font-size: 14px;
        color: #6F7274;
        padding: 20px 0;
    }
    .task-list {
        position: relative;
        background: #fff;
        padding: 8px 12px;
    }
    .list-filter {
        display: flex;
        align-items: center;
        justify-content: space-around;
        .filter-item {
            padding: 0 12px;
            height: 28px;
            color: rgba(0, 0, 0, 0.5);
            font-size: 14px;
            line-height: 28px;
            border-radius: 20px;
            &.active {
                color: #2199f8;
                background: rgba(33, 153, 248, 0.2);
            }
        }
    }

    .task-item + .task-item {
        margin-top: 10px;
    }
    
    .item-footer {
        margin-top: 10px;
        padding-top: 11px;
        border-top: 1px solid rgba(0, 0, 0, 0.1);
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 12px;
        .footer-l {
            color: #8B8B8B;
            font-size: 12px;
            &.primary-btn {
                display: inline-flex;
                align-items: center;
                border: 1px solid #2199F8;
                background: rgba(33, 153, 248, 0.1);
                padding: 0 12px;
                height: 32px;
                box-sizing: border-box;
                display: flex;
                align-items: center;
                border-radius: 20px;
                color: #2199F8;
                .share-icon {
                    width: 12px;
                    padding-right: 4px;
                }
            }
            &.farm-name-text {
                font-size: 14px;
                color: #6F7274;
                .name-text {
                    padding-left: 4px;
                }
            }
        }
        .footer-r {
            display: flex;
            align-items: center;
            .btn {
                height: 32px;
                line-height: 32px;
                padding: 0 12px;
                border-radius: 20px;
                display: flex;
                align-items: center;
                box-sizing: border-box;
                &.second {
                    // border: 1px solid #8B8B8B;
                    // color: #8B8B8B;
                    color: #2199F8;
                    background: rgba(33, 153, 248, 0.1);
                }
                &.primary {
                    background: #2199F8;
                    color: #fff;
                }
                .btn-icon {
                    padding-right: 4px;
                }
                &.warning {
                    color: #FF953D;
                    background: #fff;
                    border: 1px solid #FF953D;
                }
                &.secondary-text {
                    color: #2199F8;
                    border: 1px solid #2199F8;
                }
            }
            .btn + .btn {
                margin-left: 8px;
            }
        }
    }
}


.task-tips-popup {
    width: 75%;
    padding: 28px 28px 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    .create-farm-icon{
        width: 40px;
        height: 40px;
        margin-bottom: 12px;
    }
    .farm-check-icon{
        width: 68px;
        height: 68px;
        margin-bottom: 12px;
    }
    .create-farm-text{
        font-size: 20px;
        font-weight: 500;
        line-height: 40px;
        margin-bottom: 32px;
        text-align: center;
        &.success-text{
            font-size: 23px;
            font-weight: 400;
        }
    }
    .main-text {
        color: #2199F8;
    }
    .create-farm-btn{
        width: 100%;
        box-sizing: border-box;
        padding: 8px;
        border-radius: 25px;
        font-size: 16px;
        background: #2199F8;
        color: #fff;
        text-align: center;
    }
}
</style>
