<template>
    <popup class="price-sheet-popup" :overlay-style="{'z-index': 9999}" v-model:show="showPopup" teleport="body">
        <div class="price-sheet-content">
            <div class="price-sheet-content-inner" ref="contentEl">
                <!-- 顶部标题区域 -->
                <div class="header-section">
                    <div class="header-left">
                        <div class="main-title">服务报价单</div>
                    </div>
                    <div class="header-right">
                        <div class="qr-icon">
                            <img src="@/assets/img/home/qrcode.png" alt="" />
                        </div>
                        <div class="qr-text">扫码查看详情</div>
                    </div>
                </div>
                <div class="sheet-content" v-loading="loading">
                    <!-- 报价详情区域 -->
                    <div class="quotation-info">
                        <div class="info-item">
                            <span class="info-label">报价组织</span>
                            <span class="info-value">{{ priceData.agriculturalName || '--' }}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">报价农事</span>
                            <span class="info-value">{{ priceData?.name || '--' }}</span>
                        </div>
                        <div class="info-item">
                            <span class="info-label">执行时间</span>
                            <span class="info-value">{{ priceData?.executeDate || quotationData?.executeDate || '--' }}</span>
                        </div>
                        <div class="info-item catalog-label">
                            <span class="info-label">报价目录</span>

                            <div class="edit-btn-box">
                                <div class="edit-btn" @click="handleEdit">编辑报价</div>
                            </div>
                        </div>
                        <div class="total-bar">
                            <span class="total-label">报价合计：</span>
                            <span class="total-value">{{ totalCost ? formatArea(totalCost) : "--" }}</span>
                            <span class="total-unit">元</span>
                        </div>
                    </div>
    
                    <!-- 药肥费用区域 -->
                    <div class="fertilizer-cost-section">
                        <div class="section-header">
                            <div class="section-title">药肥费用</div>
                            <div class="section-total">{{ pesticideCostTotal ? formatArea(pesticideCostTotal) : "--" }}<span class="unit-text">元</span></div>
                        </div>
                        <div class="cost-table">
                            <div class="table-header">
                                <div class="col-1">类型</div>
                                <div class="col-2">名称</div>
                                <div class="col-3">品牌</div>
                                <div class="col-4">单价</div>
                                <div class="col-5">用量</div>
                                <div class="col-6">总价</div>
                            </div>
                            <div 
                                class="table-row"
                                v-for="(item, index) in priceData?.prescription?.pesticideFertilizerList || []"
                                :key="index"
                            >
                                <div class="col-1">{{ item.typeName || '--' }}</div>
                                <div class="col-2">{{ item.name || item.pesticideFertilizerName || '--' }}</div>
                                <div class="col-3">{{ item.brand || '--' }}</div>
                                <div class="col-4">{{ item.price || '--' }}</div>
                                <div class="col-5">{{ item.dosage ? item.dosage + item.unit : '--' }}</div>
                                <div class="col-6">{{ getTotal(item) }}</div>
                            </div>
                        </div>
                    </div>
    
                    <!-- 服务费用区域 -->
                    <div class="service-cost-section">
                        <div class="section-header">
                            <div class="section-title">服务费用</div>
                            <div class="section-total">{{ priceData?.serviceMuPrice ? serviceCostTotal : '--' }}<span class="unit-text">元</span></div>
                        </div>
                        <div class="service-details">
                            <div class="detail-item">
                                <div class="detail-value">{{ priceData?.executionMethodName || '人工' }}</div>
                                <div class="detail-label">执行方式</div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-value">{{ (priceData?.serviceMuPrice ? priceData?.serviceMuPrice + '元/亩' : '--') }}</div>
                                <div class="detail-label">亩单价</div>
                            </div>
                            <div class="detail-item">
                                <div class="detail-value">{{ priceData?.farm?.mianji ? (formatArea(priceData?.farm?.mianji) + '亩') : '--' }}</div>
                                <div class="detail-label">亩数</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 底部操作按钮 -->
            <div class="bottom-actions" @click.stop="showPopup = false">
                <div class="action-buttons">
                    <!-- <div class="action-btn blue-btn" @click.stop="handleShare">
                        <div class="icon-circle">
                            <img src="@/assets/img/home/bird.png" alt="" />
                        </div>
                        <span class="btn-label">飞鸟用户</span>
                    </div> -->
                    <div class="action-btn green-btn" @click.stop="handleWechat">
                        <div class="icon-circle">
                            <img src="@/assets/img/home/wechat.png" alt="" />
                        </div>
                        <span class="btn-label">微信</span>
                    </div>
                    <div class="action-btn orange-btn" @click.stop="handleSaveImage">
                        <div class="icon-circle">
                            <el-icon :size="24"><Download /></el-icon>
                        </div>
                        <span class="btn-label">保存图片</span>
                    </div>
                </div>
                <div class="cancel-btn" @click="handleCancel">取消</div>
            </div>
        </div>
    </popup>
</template>

<script setup>
import { Popup } from "vant";
import { ref, computed, onActivated, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import wx from "weixin-js-sdk";
import html2canvas from "html2canvas";
import { formatArea } from "@/common/commonFun";

const router = useRouter();
const route = useRoute();
const showPopup = ref(false);
const contentEl = ref(null);

// 报价数据
const quotationData = ref({});
const priceData = ref({});

onActivated(() => {
    if (ids.value?.id) {
        getDetail();
    }
})

const getTotal = (item) => {
    const price = Number(item?.price ?? 0);
    const dosage = Number(item?.dosage ?? 0);
    const area = Number(priceData.value?.farm?.mianji ?? 0);
    if (!price || !dosage || !area) return '--';
    return (price * dosage * area).toFixed(2);
}


// 药肥费用总计：∑(单价 * 单亩用量 * 亩数)
const pesticideCostTotal = computed(() => {
    const list = priceData.value?.prescription?.pesticideFertilizerList || [];
    const area = Number(priceData.value?.farm?.mianji || 0);
    if (!list.length || !area) return 0;

    const sum = list.reduce((acc, item) => {
        const price = Number(item?.price || 0);
        const dosage = Number(item?.dosage || 0);
        if (!price || !dosage) return acc;
        return acc + price * dosage * area;
    }, 0);

    return Number(sum.toFixed(2));
});

// 报价合计 = 药肥费用 + 服务费用
const totalCost = computed(() => {
    const pesticide = Number(pesticideCostTotal.value || 0);
    const service = Number(serviceCostTotal.value || 0);
    if (!pesticide && !service) return '--';
    return Number((pesticide + service).toFixed(2));
});


const ids = ref({});
const handleShowPopup = ({id, farmId}) => {
    if (id) {
        loading.value = true;
        ids.value = {id, farmId};
        getDetail();
    }
    showPopup.value = true;
};

const loading = ref(false);
function fetchPriceData(id) {
    
    // VE_API.z_farm_work_record_cost.getByRecordId({ farmWorkRecordId: quotationData.value.id }).then(({ data }) => {
    //     priceData.value = data;
    // }).catch(() => {
    //     // 获取价格数据失败
    // }).finally(() => {
    //     loading.value = false;
    // });
}

const userInfoStr = localStorage.getItem("localUserInfo");
const userInfo = userInfoStr ? JSON.parse(userInfoStr) : {};

const getDetail = async () => {
    const { id, farmId } = ids.value;
    const { data, code } = await VE_API.farm.getFarmWorkLib({ id, farmId, agriculturalId: userInfo?.agriculturalId });
    if(code === 0) {
        priceData.value = data;
        const pesticideFertilizerCodes = data?.prescription?.pesticideFertilizerList.map(item => item.code);
        getPriceList(data.schemeId, pesticideFertilizerCodes);
        loading.value = false;
    }
}

const getPriceList = async (schemeId, pesticideFertilizerCodes) => {
    const { data } = await VE_API.farm.getPriceList({ schemeId, pesticideFertilizerCodes });
    if (!data || !Array.isArray(data)) return;

    priceData.value.prescription.pesticideFertilizerList.forEach((item) => {
        const priceInfo = data.find((p) => p.pesticideFertilizerCode === item.code);
        if (!priceInfo) return;
        item.price = priceInfo.price ?? item.price;
        item.brand = priceInfo.brand ?? item.brand;
    });
};

// 检查 itemsList 是否都有价格和品牌
function checkItemsListHasPrice() {
    if (!priceData.value?.prescription?.pesticideFertilizerList || !Array.isArray(priceData.value.prescription.pesticideFertilizerList) || priceData.value.prescription.pesticideFertilizerList.length === 0) {
        return false;
    }
    // 检查所有项是否都有 price 且 price 不为 0，以及 brand 有值
    return priceData.value.prescription.pesticideFertilizerList.every(item => {
        const hasPrice = item.price != null && item.price !== '' && item.price !== 0;
        const hasBrand = item.brand && item.brand.trim() !== '';
        return hasPrice && hasBrand;
    });
}

async function checkOrder() {
    // 如果没有 id，需要检查 itemsList 是否都有价格
    if (!checkItemsListHasPrice()) {
        return false; // 没有价格，返回 false
    }
    
    // 有 id 且都有价格，返回 true
    return true;
}

const handleShare = async () => {
    // 检查订单状态，如果返回 false 说明数据不完整
    const canProceed = await checkOrder();
    if (!canProceed) {
        ElMessage.warning('请补全报价数据');
        setTimeout(() => {
            handleEdit();
        }, 1000);
        return;
    }
    const userId = priceData.value.farmMiniUserId;
    const parmasPage = {
        farmWorkOrderId:priceData.value.orderId,
        farmMiniUserId:userId,
        farmMiniUserName:priceData.value.farmMiniUserName,
        farmId:priceData.value.farmId,
        farmWorkName:priceData.value.farmWorkName,
        id:priceData.value.id,
        type:'quotation'
    }
    if(userId){
        router.push(`/chat_frame?userId=${userId}&farmId=${parmasPage.farmId}&pageParams=${JSON.stringify(parmasPage)}`);
    }else{
        ElMessage.warning('尚未绑定用户,暂时无法分享')
    }   
};

const handleWechat = async () => {
    // 检查订单状态，如果返回 false 说明数据不完整
    const canProceed = await checkItemsListHasPrice();
    if (!canProceed) {
        ElMessage.warning('请补全报价数据');
        return;
    }
    // router.push({
    //     path: "/completed_work",
    //     query: { id: quotationData.value.id, farmWorkOrderId: quotationData.value.orderId, isAssign: true },
    // });
    const query = { askInfo: {title: "服务报价单", content: "是否分享该服务报价单给好友"}, shareText: "向您发送了一张 服务报价单", id: quotationData.value.id, farmWorkOrderId: quotationData.value.orderId, isAssign: true }

    wx.miniProgram.navigateTo({
        url: `/pages/subPages/share_page/index?pageParams=${JSON.stringify(query)}&type=priceSheet`,
    });
};

// 服务费用总计（数值）：亩单价 * 亩数
const serviceCostTotal = computed(() => {
    const price = Number(priceData.value?.serviceMuPrice || 0);
    const area = Number(priceData.value?.farm?.mianji || 0);
    if (!price || !area) return 0;
    return Number((price * area).toFixed(2));
});

const handleSaveImage = async () => {
    try {
        if (!contentEl.value) return;
        const element = contentEl.value;
        const scroller = element.querySelector('.sheet-content');

        // 记录原样式
        const prev = {
            elementOverflow: element.style.overflow,
            elementMaxHeight: element.style.maxHeight,
            elementHeight: element.style.height,
            scrollerOverflow: scroller ? scroller.style.overflow : undefined,
            scrollerMaxHeight: scroller ? scroller.style.maxHeight : undefined,
            scrollerHeight: scroller ? scroller.style.height : undefined,
        };

        // 展开内容，去除滚动限制，确保截图包含全部内容
        element.style.overflow = 'visible';
        element.style.maxHeight = 'none';
        element.style.height = 'auto';
        if (scroller) {
            scroller.style.overflow = 'visible';
            scroller.style.maxHeight = 'none';
            scroller.style.height = 'auto';
        }

        // 计算完整尺寸
        const width = element.scrollWidth;
        const height = element.scrollHeight;

        const canvas = await html2canvas(element, {
            backgroundColor: '#ffffff',
            useCORS: true,
            allowTaint: true,
            scale: Math.min(2, window.devicePixelRatio || 2),
            width,
            height,
            windowWidth: width,
            windowHeight: height,
            scrollX: 0,
            scrollY: 0,
        });
        const dataUrl = canvas.toDataURL('image/png');
        const link = document.createElement('a');
        link.href = dataUrl;
        link.download = '服务报价单.png';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        // 还原样式
        element.style.overflow = prev.elementOverflow;
        element.style.maxHeight = prev.elementMaxHeight;
        element.style.height = prev.elementHeight;
        if (scroller) {
            scroller.style.overflow = prev.scrollerOverflow;
            scroller.style.maxHeight = prev.scrollerMaxHeight;
            scroller.style.height = prev.scrollerHeight;
        }
    } catch (e) {
        // 保存图片失败
    }
};

const handleEdit = () => {
    // 编辑报价逻辑
    // 可以触发编辑事件或打开编辑页面
    const queryData = route.query?.miniJson ? JSON.parse(route.query?.miniJson) : {};
    router.push({
        path: "/modify",
        query: {
            isEdit: true,
            onlyPrice: true,
            farmId: priceData.value.farm.id,
            arrangeId: queryData.arrangeId,
            farmWorkId: priceData.value.id,
        },
    });
    // router.push({
    //     path: "/price_detail",
    //     query: { data: JSON.stringify(quotationData.value), priceData: JSON.stringify(priceData.value) },
    // });
};

// 清空数据
const clearData = () => {
    // quotationData.value = {};
    // priceData.value = {};
};

// 监听弹窗关闭，清空数据
// watch(showPopup, (newVal) => {
//     if (!newVal) {
//         clearData();
//     }
// });

const handleCancel = () => {
    showPopup.value = false;
};

defineExpose({
    handleShowPopup,
});
</script>

<style lang="scss" scoped>
.price-sheet-popup {
    z-index: 9999 !important;
    width: 90%;
    max-height: 90vh;
    background: none;
    border-radius: 12px;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    backdrop-filter: 4px;

    ::v-deep {
        .van-popup__close-icon {
            color: #000;
            font-size: 18px;
            top: 12px;
            right: 12px;
        }
    }
}

.price-sheet-content {
    display: flex;
    flex-direction: column;
    max-height: 90vh;
    // height: 95vh;
    .price-sheet-content-inner {
        background: #fff;
        border-radius: 12px;
        display: flex;
        flex-direction: column;
        height: 100%;
        overflow: hidden;
    }
}

// 顶部标题区域
.header-section {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 10px 12px 16px;
    // background: linear-gradient(180deg, rgba(33, 153, 248, 0) 8%, rgba(139, 199, 252, 0.519) 94%, rgba(237, 241, 255, 1) 100%);
    background: linear-gradient(180deg, rgba(33, 153, 248, 0) 2%, rgba(139, 199, 252, 0.519) 50%, #c4e3fd);
    flex-shrink: 0;

    .header-left {
        flex: 1;

        .main-title {
            font-family: "PangMenZhengDao";
            font-size: 28px;
            color: #0387EF;
        }
    }

    .header-right {
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-left: 16px;

        .qr-icon {
            color: #2199F8;
            margin-bottom: 4px;
            img {
                width: 40px;
                height: 40px;
            }
        }

        .qr-text {
            font-size: 12px;
            color: #171717;
        }
    }
}

.sheet-content {
    padding: 24px 16px 12px 16px;
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
    position: relative;
}

// 报价详情区域
.quotation-info {
    margin-bottom: 12px;

    .info-item {
        font-size: 16px;
        color: #000;
        margin-bottom: 8px;

        .info-label {
            padding-right: 8px;
            color: rgba(0, 0, 0, 0.5);
        }

        .info-value {
            color: #000;
        }

        &.catalog-label {
            font-weight: bold;
            margin-top: 10px;
            margin-bottom: 10px;
            position: relative;

            .info-label {
                color: #000;
            }
        }
    }

    .total-bar {
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(33, 153, 248, 0.1);
        border: 1px solid rgba(33, 153, 248, 0.5);
        height: 38px;
        border-radius: 4px;

        .total-label {
            font-size: 14px;
            color: #000000;
        }

        .total-value {
            font-size: 22px;
            font-weight: bold;
            color: #2199F8;
        }

        .total-unit {
            font-size: 14px;
            color: #000;
            margin-left: 4px;
        }
    }
}

// 药肥费用区域
.fertilizer-cost-section {
    margin-bottom: 10px;

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .section-title {
            font-size: 14px;
            color: #000;
        }

        .section-total {
            font-size: 16px;
            font-weight: bold;
            color: #000;

            .unit-text {
                padding-left: 2px;
                font-size: 12px;
                font-weight: normal;
            }
        }
    }

    .cost-table {
        border: 1px solid rgba(225, 225, 225, 0.5);
        border-radius: 5px;
        overflow: hidden;

        .table-header {
            display: flex;
            background: rgba(241, 241, 241, 0.4);
            padding: 8px 6px;
            font-size: 12px;
            color: #767676;
            border-bottom: 1px solid rgba(225, 225, 225, 0.5);

            .col-1 {
                width: 40px;
                text-align: center;
            }

            .col-2 {
                flex: 1;
                text-align: center;
            }

            .col-3 {
                width: 52px;
                text-align: center;
            }

            .col-4 {
                width: 56px;
                text-align: center;
            }

            .col-5 {
                width: 52px;
                text-align: center;
            }

            .col-6 {
                width: 52px;
                text-align: center;
            }
        }

        .table-row {
            display: flex;
            padding: 8px 6px;
            font-size: 11px;
            color: rgba(0, 0, 0, 0.6);
            background: #fff;
            border-bottom: 1px solid rgba(225, 225, 225, 0.3);

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

            .col-1,
            .col-2,
            .col-3,
            .col-4,
            .col-5,
            .col-6 {
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .col-1 {
                width: 40px;
            }

            .col-2 {
                flex: 1;
            }

            .col-3 {
                width: 52px;
            }

            .col-4 {
                width: 56px;
            }

            .col-5 {
                width: 52px;
            }

            .col-6 {
                width: 52px;
            }
        }
    }
}

// 服务费用区域
.service-cost-section {
    position: relative;

    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12px;

        .section-title {
            font-size: 14px;
            color: #000;
        }

        .section-total {
            font-size: 16px;
            font-weight: bold;
            color: #000;

            .unit-text {
                padding-left: 2px;
                font-size: 12px;
                font-weight: normal;
            }
        }
    }

    .service-details {
        display: flex;
        align-items: center;
        border: 1px solid rgba(206, 206, 206, 0.5);
        padding: 8px 0;
        border-radius: 4px;
        margin-bottom: 10px;

        .detail-item {
            font-size: 14px;
            flex: 1;
            text-align: center;

            .detail-label {
                color: rgba(0, 0, 0, 0.2);
                margin-top: 6px;
            }

            .detail-value {
                color: rgba(0, 0, 0, 0.8);
            }
        }
        .detail-item + .detail-item {
            position: relative;
            &::before {
                content: '';
                position: absolute;
                left: 0;
                top: 50%;
                transform: translateY(-50%);
                width: 1px;
                height: 20px;
                background: rgba(0, 0, 0, 0.1);
            }
        }
    }
}
.edit-btn-box {
    display: flex;
    justify-content: end;
    position: absolute;
    right: 0;
    top: -8px;
    z-index: 10;
}
.edit-btn {
    background: rgba(33, 153, 248, 0.1);
    color: #2199F8;
    padding: 6px 16px;
    border-radius: 20px;
    font-size: 14px;
    width: fit-content;
    cursor: pointer;
    font-weight: 500;
}

// 底部操作按钮
.bottom-actions {
    flex-shrink: 0;

    .action-buttons {
        padding: 16px;
        display: flex;
        justify-content: space-around;

        .action-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            cursor: pointer;

            .icon-circle {
                width: 48px;
                height: 48px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                color: #fff;
                margin-bottom: 4px;

                .el-icon {
                    color: #fff;
                }
                img {
                    width: 50px;
                }
            }

            &.blue-btn .icon-circle {
                background: #2199F8;
            }

            &.green-btn .icon-circle {
                background: #07C160;
            }

            &.orange-btn .icon-circle {
                background: #FF790B;
            }

            .btn-label {
                font-size: 12px;
                color: #fff;
            }
        }
    }

    .cancel-btn {
        text-align: center;
        font-size: 18px;
        color: #fff;
        cursor: pointer;
    }
}
</style>