<template>
    <popup class="offer-popup" teleport="body" :overlay-style="{'z-index': 9999}" v-model:show="show" :close-on-click-overlay="false" :closeable="stepIndex === 2">
        <div class="step-1" v-if="stepIndex === 1">
            <div class="title">
                <div class="text">
                    <div>请输入</div>
                    <div class="blue">实际交易金额</div>
                </div>
                <img src="@/assets/img/home/offer-icon.png" alt="" />
            </div>
            <!-- <div class="tips">注：本次成本不对外公开，仅作为投入产出比的计算</div> -->
            <el-form ref="formRef" :model="formData" :rules="rules" label-width="0">
                <div class="inputs-wrap">
                    <div class="input-row">
                        <el-form-item prop="agriculturalInput" class="input-item">
                            <div class="input-header">农资投入</div>
                            <el-input
                                class="input-field"
                                type="number"
                                v-model="formData.agriculturalInput"
                                placeholder="请输入数字"
                            >
                                <template #suffix>
                                    <span class="unit">元</span>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="serviceInput" class="input-item">
                            <div class="input-header">农服投入</div>
                            <el-input
                                class="input-field"
                                type="number"
                                v-model="formData.serviceInput"
                                placeholder="请输入数字"
                            >
                                <template #suffix>
                                    <span class="unit">元</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </div>
                    <div class="input-row total-row">
                        <div class="total-label">总金额</div>
                        <el-form-item prop="totalAmount" class="total-form-item">
                            <el-input
                                class="input-field total-input"
                                type="number"
                                v-model="formData.totalAmount"
                                placeholder="请输入数字"
                            >
                                <template #suffix>
                                    <span class="unit">元</span>
                                </template>
                            </el-input>
                        </el-form-item>
                    </div>
                </div>
            </el-form>
        </div>
        <div class="step-2" v-else>
            <div class="upload-wrap" :class="{ 'upload-cont': fileList.length }">
                <div class="name"><span class="required">*</span>请上传执行照片（至少两张）</div>
                <uploader
                    class="uploader"
                    v-model="fileList"
                    multiple
                    :max-count="5"
                    :after-read="afterRead"
                    @click="handleClick('rg')"
                >
                    <img class="img" v-show="!fileList.length" src="@/assets/img/home/example-4.png" alt="" />
                    <img class="plus" src="@/assets/img/home/plus.png" alt="" />
                </uploader>
            </div>

            <div class="time-wrap">
                <div class="name"><span class="required">*</span>请选择 {{ executionData.farmWorkName }} 实际执行时间</div>
                <div class="time-input">
                    <el-date-picker
                        v-model="executeTime"
                        popper-style="z-index: 99999 !important;"
                        :disabled-date="disabledDate"
                        size="large"
                        style="width: 100%"
                        type="date"
                        placeholder="请选择日期"
                        :editable="false"
                    />
                </div>
            </div>
        </div>
        <div class="tips-text">注：交易信息保密不公开</div>
        <div class="button-wrap" v-if="stepIndex === 1">
            <div class="button second" @click="handleCancel">取消</div>
            <div
                @click="handleNextStep"
                class="button primary"
                :class="{ 'btn-color': formData.totalAmount && formData.totalAmount.length > 0 }"
            >
                下一步
            </div>
        </div>
        <div class="button-wrap" v-if="stepIndex === 2">
            <div class="button second" @click="toggleStep(1)">上一步</div>
            <div v-if="stepIndex === 2" @click="closeTask" class="button primary btn-color">确认上传</div>
        </div>
    </popup>
</template>

<script setup>
import { Popup, Uploader } from "vant";
import { ref, watch, reactive } from "vue";
import { useStore } from "vuex";
import { getFileExt } from "@/utils/util";
import UploadFile from "@/utils/upliadFile";
import { base_img_url2 } from "@/api/config";
import { ElMessage, ElMessageBox } from "element-plus";
import wx from "weixin-js-sdk";
import { useRouter } from "vue-router";
const router = useRouter();

const store = useStore();
const miniUserId = store.state.home.miniUserId;
const show = ref(false);
const formRef = ref(null);

const formData = reactive({
    agriculturalInput: "",
    serviceInput: "",
    totalAmount: "",
});

const rules = {
    agriculturalInput: [
        { required: false, message: "请输入农资投入", trigger: "blur" },
        {
            validator: (rule, value, callback) => {
                if (isNaN(value) || Number(value) < 0) {
                    callback(new Error("请输入有效的数字"));
                } else {
                    callback();
                }
            },
            trigger: "blur",
        },
    ],
    serviceInput: [
        { required: false, message: "请输入农服投入", trigger: "blur" },
        {
            validator: (rule, value, callback) => {
                if (isNaN(value) || Number(value) < 0) {
                    callback(new Error("请输入有效的数字"));
                } else {
                    callback();
                }
            },
            trigger: "blur",
        },
    ],
    totalAmount: [
        { required: true, message: "请输入总金额", trigger: "blur" },
        {
            validator: (rule, value, callback) => {
                if (!value || value.trim() === "") {
                    callback(new Error("请输入总金额"));
                } else if (isNaN(value) || Number(value) < 0) {
                    callback(new Error("请输入有效的数字"));
                } else {
                    callback();
                }
            },
            trigger: "blur",
        },
    ],
};

const stepIndex = ref(1);
const executeTime = ref("");
const fileList = ref([]);
const fileArr = ref([]);

const imgType = ref("");
const handleClick = (type) => {
    imgType.value = type;
};

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

const uploadFileObj = new UploadFile();
const afterRead = (file) => {
    // 处理多张照片的情况：file 可能是数组
    const files = Array.isArray(file) ? file : [file];
    
    files.forEach((item) => {
        // 将文件上传至服务器
        let fileVal = item.file;
        if (!fileVal) return; // 如果没有 file 属性，跳过
        
        item.status = "uploading";
        item.message = "上传中...";
        let ext = getFileExt(fileVal.name);
        let key = `birdseye-look-mini/${miniUserId}/${new Date().getTime()}.${ext}`;
        uploadFileObj.put(key, fileVal).then((resFilename) => {
            item.status = "done";
            item.message = "";
            fileArr.value.push(resFilename);
        }).catch(() => {
            item.status = 'failed';
            item.message = '上传失败';
            ElMessage.error('图片上传失败，请稍后再试！')
        });
    });
};

function toggleStep(val) {
    stepIndex.value = val;
}

function resetForm() {
    // 重置表单验证状态
    if (formRef.value) {
        formRef.value.clearValidate();
        formRef.value.resetFields();
    }
}

function handleNextStep() {
    if (!formRef.value) return;

    formRef.value.validate((valid) => {
        if (valid) {
            toggleStep(2);
        } else {
            ElMessage.warning("请完善信息");
        }
    });
}

function formatDate(date) {
    let year = date.getFullYear();
    let month = String(date.getMonth() + 1).padStart(2, "0");
    let day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
}

const emit = defineEmits(['uploadSuccess']);
function closeTask() {
    // stepIndex.value = 2
    if (!fileArr.value.length || fileArr.value.length < 2) return ElMessage.warning('请上传至少两张图片')
    if (!executeTime.value) return ElMessage.warning('请选择实际执行时间')
    const params = {
        recordId: executionData.value.id,
        executeDate: formatDate(executeTime.value),
        executeEvidence: fileArr.value,
        actualAgriculturalInput: formData.agriculturalInput,
        actualFarmServiceInput: formData.serviceInput,
        actualTotalInput: formData.totalAmount,
    }
    VE_API.z_farm_work_record.addExecuteImgAndComplete(params).then((res) => {
        if (res.code === 0) {
            ElMessage.success('上传成功')
            show.value = false
            emit('uploadSuccess')
        }
    })
    // show.value = false;

    // router.push("/review_work");

    // if(!input.value.length) return ElMessage.warning('请上传图片')
    // const params = {
    //     ...props.executionData,
    //     orderStatus: 4,
    //     farmWorkservicecost: input.value,
    //     confirmPicture: fileArr.value
    // }
    // VE_API.order.confirm(params).then(({ code }) => {
    //     if (code === 0) {
    //         ElMessage({
    //             message: "操作成功",
    //             type: "success",
    //         });
    //         setTimeout(() => {
    //             // wx.miniProgram.navigateBack()
    //             router.replace("/feature_home_album?list=true");
    //         }, 500)
    //     }
    // })
}

// 计算总金额
function calculateTotalAmount() {
    const agricultural = parseFloat(formData.agriculturalInput) || 0;
    const service = parseFloat(formData.serviceInput) || 0;
    
    if (agricultural > 0 || service > 0) {
        const total = agricultural + service;
        formData.totalAmount = total > 0 ? total.toString() : "";
        formRef.value.validateField("totalAmount");
    } else {
        formData.totalAmount = "";
    }
}

// 监听农资投入和农服投入的变化，自动计算总金额
watch(
    () => [formData.agriculturalInput, formData.serviceInput],
    () => {
        calculateTotalAmount();
    }
);

const executionData = ref(null);
function openPopup(item) {
    show.value = true;
    executionData.value = item;
    stepIndex.value = 1;
    fileArr.value = [];
    fileList.value = [];
    // 重置表单数据
    formData.agriculturalInput = "";
    formData.serviceInput = "";
    formData.totalAmount = "";
}

const disabledDate = (time) => {
    // 获取今天的开始时间（00:00:00）
    const today = new Date();
    today.setHours(0, 0, 0, 0);
    
    // 获取明天的开始时间（00:00:00）
    const tomorrow = new Date(today);
    tomorrow.setDate(tomorrow.getDate() + 1);
    
    // 如果时间 >= 明天的开始时间，则禁用（不能选今天之后）
    // 可以选择今天及之前的时间
    return time.getTime() >= tomorrow.getTime();
}

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

<style lang="scss" scoped>
.offer-popup {
    z-index: 9999 !important;
    width: 90%;
    padding: 10px 12px;
    border-radius: 8px;
    background: linear-gradient(360deg, #ffffff 74.2%, #d1ebff 100%);
    ::v-deep {
        .van-popup__close-icon {
            color: #000;
        }
    }
    .step-1 {
        .tips {
            color: #2199f8;
            padding: 4px;
            font-family: "PangMenZhengDao";
            background: rgba(33, 153, 248, 0.1);
            border-radius: 4px;
            text-align: center;
            margin-bottom: 8px;
        }
    }
    .title {
        margin: 10px 0 12px 0;
        display: flex;
        align-items: stretch;
        justify-content: space-between;
        .text {
            font-size: 30px;
            div {
                font-family: "PangMenZhengDao";
                line-height: 38px;
            }
            .blue {
                color: #2199f8;
                margin-top: -5px;
            }
        }
        img {
            width: 96px;
            height: 96px;
        }
    }
    .input {
        width: 100%;
        ::v-deep {
            .el-input__inner {
                text-align: center;
            }
            --el-input-placeholder-color: rgba(33, 153, 248, 0.43);
        }
    }
    .inputs-wrap {
        ::v-deep {
            .el-form-item {
                margin-bottom: 0;
                .el-form-item__error {
                    position: absolute;
                    bottom: -18px;
                    left: 0;
                    font-size: 12px;
                    color: #f56c6c;
                    line-height: 1;
                    padding-top: 2px;
                }
            }
            .el-input__wrapper {
                border-radius: 6px;
                border: 1px solid rgba(162, 213, 253, 0.8);
                box-shadow: none;
                padding: 7px 12px;
                background: #fff;
                &.is-error {
                    border-color: #f56c6c;
                }
            }
            .el-input__inner {
                text-align: left;
                color: #000000;
                font-size: 16px;
            }
            .el-input__suffix {
                .unit {
                    color: rgba(0, 0, 0, 0.2);
                    font-size: 16px;
                }
            }
        }
        .input-row {
            display: flex;
            gap: 12px;
            margin-bottom: 20px;
            position: relative;
            .input-item {
                flex: 1;
                position: relative;
                .input-header {
                    background: #2199f8;
                    color: #fff;
                    padding: 0 12px;
                    border-radius: 6px 6px 0 0;
                    font-size: 16px;
                    text-align: center;
                    line-height: 28px;
                    width: 100%;
                }
                .input-field {
                    ::v-deep {
                        .el-input__wrapper {
                            border-radius: 0 0 6px 6px;
                            border-top: none;
                        }
                    }
                }
            }
            &.total-row {
                align-items: center;
                margin-bottom: 0;
                .total-label {
                    color: #2199f8;
                    font-size: 16px;
                    min-width: 60px;
                }
                .total-form-item {
                    flex: 1;
                    position: relative;
                }
                .total-input {
                    flex: 1;
                }
            }
        }
    }
    .tips-text {
        font-size: 14px;
        color: #b0b0b0;
        text-align: center;
        margin-top: 16px;
    }
    .button-wrap {
        display: flex;
        padding: 16px 0 10px 0;
    }

    .button {
        border-radius: 20px;
        color: #fff;
        padding: 7px 0;
        text-align: center;
        font-size: 16px;
        &.primary {
            margin-left: 12px;
            flex: 1;
            background: #2199f8;
            color: #fff;
            &.btn-color {
                background: #2199f8;
            }
        }
        &.second {
            color: #666666;
            text-align: center;
            font-size: 16px;
            width: 100px;
            border: 1px solid #bbbbbb;
        }
    }
}
.upload-wrap {
    ::v-deep {
        .avatar-uploader .el-upload {
            width: 100%;
            border: 1px dashed #dddddd;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }

        .van-uploader,
        .van-uploader__wrapper,
        .van-uploader__input-wrapper {
            width: 100%;
        }

        .el-icon.avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 100%;
            height: 128px;
            text-align: center;
            background: #f6f6f6;
        }
    }
}
.step-2 {
    .title {
        margin: 0;
        .text {
            margin: 0 auto;
        }
        text-align: center;
    }
    .tips {
        font-family: "PangMenZhengDao";
        color: #9a9a9a;
        font-size: 14px;
        background: linear-gradient(0deg, #ffffff 55%, rgba(33, 153, 248, 0.25) 100%);
        border: 1px solid rgba(33, 153, 248, 0.4);
        border-radius: 25px;
        width: 80%;
        margin: 5px auto 20px auto;
        text-align: center;
        span {
            color: #269fff;
        }
    }
    .name {
        color: #000000;
        font-size: 16px;
        font-weight: 500;
        padding-bottom: 12px;
        .required {
            color: #ff4d4f;
            margin-right: 2px;
        }
    }
    .upload-wrap {
        // position: relative;
        // border: 1px dashed #2199F8;
        // background: rgba(33, 153, 248, 0.1);
        border-radius: 10px;
        padding: 14px 0 10px 0;
        &.upload-cont {
            ::v-deep {
                .van-uploader__wrapper {
                    flex-wrap: nowrap;
                }
            }
        }
        .img {
            width: 80px;
            height: 80px;
            margin-right: 12px;
        }
        .plus {
            margin-right: 12px;
            width: 80px;
            height: 80px;
        }
    }
    .upload-wrap + .upload-wrap {
        margin-top: 12px;
    }
}
</style>
