<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { aesEncrypt } from "@/utils/crypto";
import { useRoute } from "vue-router";

import Authorization from "@/components/Authorization.vue";
import Payment from "@/components/Payment.vue";
import CarNumberInput from "@/components/CarNumberInput.vue";

const route = useRoute();
const router = useRouter();
const showAuthorizationPopup = ref(false);
const authorization = ref(true);
const showPayment = ref(false);
const queryId = ref(null);
const name = ref("");
const nameMan = ref("");
const nameWoman = ref("");
const idCard = ref("");
const idCardMan = ref("");
const idCardWoman = ref("");
const mobile = ref("");
const bankCard = ref("");
const certificateNumber = ref("");
const startDate = ref([]);
const dateVal = ref("");
const showDatePicker = ref(false);
// 新增车架号和行驶证照片
const vinCode = ref("");
const carDrivingPermit = ref("");
const carDrivingPermitFile = ref(null);
// 当前日期
const today = new Date();
const maxDate = today; // 最大日期为当前日期
// 最小日期为2000年1月1日
const minDate = new Date("2000-01-01");
const entName = ref("");
const entCode = ref("");
const verificationCode = ref("");
const agreeToTerms = ref(false);
// 新增特殊API的授权书勾选
const agreeToAuthorization = ref(false);
const isCountingDown = ref(false);
const countdown = ref(60);
const feature = ref(route.params.feature);
const featureData = ref({});
const carLicense = ref("");
const carType = ref("小型汽车");
const carPickerVal = ref([{ value: "02", text: "小型汽车" }]);
const showCarTypePicker = ref(false);
const carTypeColumns = [
    { value: "01", text: "大型汽车" },
    { value: "02", text: "小型汽车" },
    { value: "03", text: "使馆汽车" },
    { value: "04", text: "领馆汽车" },
    { value: "05", text: "境外汽车" },
    { value: "06", text: "外籍汽车" },
    { value: "07", text: "普通摩托车" },
    { value: "08", text: "轻便摩托车" },
    { value: "09", text: "使馆摩托车" },
    { value: "10", text: "领馆摩托车" },
    { value: "11", text: "境外摩托车" },
    { value: "12", text: "外籍摩托车" },
    { value: "13", text: "低速车" },
    { value: "14", text: "拖拉机" },
    { value: "15", text: "挂车" },
    { value: "16", text: "教练汽车" },
    { value: "17", text: "教练摩托车" },
    { value: "20", text: "临时入境汽车" },
    { value: "21", text: "临时入境摩托车" },
    { value: "22", text: "临时行驶车" },
    { value: "23", text: "警用汽车" },
    { value: "24", text: "警用摩托车" },
    { value: "51", text: "新能源大型车" },
    { value: "52", text: "新能源小型车" },
];
const formatterDate = (type, option) => {
    if (type === "year") {
        option.text += "年";
    }
    if (type === "month") {
        option.text += "月";
    }
    if (type === "day") {
        option.text += "日";
    }
    return option;
};
const onConfirmDate = ({ selectedValues, selectedOptions }) => {
    console.log("selectedValues", selectedValues);
    console.log("startDate", startDate.value);
    dateVal.value = selectedOptions.map((item) => item.text).join("");
    showDatePicker.value = false;
};
const carLicenseChange = (e) => {
    console.log("carLicenseChange", e);
    carLicense.value = e;
};
const onConfirmCarType = ({ selectedValues, selectedOptions }) => {
    console.log(
        "selectedValues, selectedOptions",
        selectedValues,
        selectedOptions
    );
    showCarTypePicker.value = false;
    carPickerVal.value = selectedValues;
    carType.value = selectedOptions[0].text;
};

// 用于欺诈赌博查询的字段选择
const fraudGamblingCheckType = ref("mobile"); // 默认选择手机号

onMounted(() => {
    isFinishPayment();
    getProduct();
    initAuthorization();
});
function isFinishPayment() {
    const query = new URLSearchParams(window.location.search);
    let orderNo = query.get("out_trade_no");
    if (orderNo) {
        router.push({ path: "/report", query: { orderNo } });
    }
}
async function getProduct() {
    const { data, error } = await useApiFetch(`/product/en/${feature.value}`)
        .get()
        .json();

    if (data.value) {
        featureData.value = data.value.data;

        // 在获取产品数据后设置授权勾选状态
        setAuthorizationCheckboxes();
    }
}

// 设置授权勾选状态
function setAuthorizationCheckboxes() {
    // 移除默认勾选逻辑，让用户必须手动勾选
    // 仅保留函数作为以后可能需要的扩展点
}
function initAuthorization() {
    if (NeedAuthorization.includes(feature.value)) {
        authorization.value = false;
    }
}
const isPhoneNumberValid = computed(() => {
    return /^1[3-9]\d{9}$/.test(mobile.value);
});
const isIdCardValid = computed(() => /^\d{17}[\dX]$/i.test(idCard.value));
const isIdCardManValid = computed(() => /^\d{17}[\dX]$/i.test(idCardMan.value));
const isIdCardWomanValid = computed(() =>
    /^\d{17}[\dX]$/i.test(idCardWoman.value)
);
const isCreditCodeValid = computed(() => /^.{18}$/.test(entCode.value));
const isCarLicense = computed(() => carLicense.value.trim().length > 6);

// 车架号校验逻辑
const isVinCodeValid = computed(() => {
    // VIN码规则校验：17位，字母数字组合，不包含I、O、Q
    if (!vinCode.value || vinCode.value.length !== 17) {
        return false;
    }

    // 不能包含I、O、Q字母
    if (/[IOQ]/.test(vinCode.value)) {
        return false;
    }

    // 只能包含数字和字母
    if (!/^[A-HJ-NPR-Z0-9]+$/.test(vinCode.value)) {
        return false;
    }

    return true;
});

// 图片压缩和转base64函数
const compressAndConvertToBase64 = (file) => {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (event) => {
            const img = new Image();
            img.src = event.target.result;
            img.onload = () => {
                const MAX_SIZE = 1 * 1024 * 1024; // 1MB

                // 如果文件小于1MB，直接处理不压缩
                if (file.size <= MAX_SIZE) {
                    // 去除base64前缀
                    const base64String = event.target.result.split(",")[1];
                    resolve(base64String);
                    return;
                }

                // 需要压缩
                const canvas = document.createElement("canvas");
                const ctx = canvas.getContext("2d");

                // 计算压缩比例
                let ratio = 1;

                // 如果需要压缩，先尝试0.8的压缩率
                ratio = 0.8;

                const width = img.width * ratio;
                const height = img.height * ratio;

                canvas.width = width;
                canvas.height = height;

                ctx.drawImage(img, 0, 0, width, height);

                // 尝试压缩为JPEG格式（效果更好）
                const compressedBase64 = canvas
                    .toDataURL("image/jpeg", 0.8)
                    .split(",")[1];

                // 如果还是太大，继续压缩
                if (compressedBase64.length * 0.75 > MAX_SIZE) {
                    // 递归尝试更大压缩率，这里简化处理，直接设置更高压缩率
                    const smallerRatio = ratio * 0.7;
                    canvas.width = img.width * smallerRatio;
                    canvas.height = img.height * smallerRatio;
                    ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
                    const moreCompressedBase64 = canvas
                        .toDataURL("image/jpeg", 0.7)
                        .split(",")[1];
                    resolve(moreCompressedBase64);
                } else {
                    resolve(compressedBase64);
                }
            };
            img.onerror = (err) => {
                reject(err);
            };
        };
        reader.onerror = (err) => {
            reject(err);
        };
    });
};

// 处理行驶证照片上传
const handleCarDrivingPermitUpload = async (event) => {
    const file = event.target.files[0];
    if (!file) return;

    // 检查是否是图片
    if (!file.type.match("image.*")) {
        showToast({ message: "请上传图片文件" });
        return;
    }

    try {
        carDrivingPermitFile.value = file;
        const base64String = await compressAndConvertToBase64(file);
        carDrivingPermit.value = base64String;
        showToast({ message: "行驶证上传成功", type: "success" });
    } catch (error) {
        console.error("图片处理失败", error);
        showToast({ message: "图片处理失败，请重试" });
    }
};

const isBankCardValid = computed(() => {
    const card = bankCard.value.replace(/\D/g, ""); // 移除所有非数字字符
    if (card.length < 13 || card.length > 19) {
        return false; // 校验长度
    }

    let sum = 0;
    let shouldDouble = false;

    // 从卡号的右边开始遍历
    for (let i = card.length - 1; i >= 0; i--) {
        let digit = parseInt(card.charAt(i));

        if (shouldDouble) {
            digit *= 2;
            if (digit > 9) {
                digit -= 9;
            }
        }

        sum += digit;
        shouldDouble = !shouldDouble; // 反转是否乘 2
    }

    return sum % 10 === 0; // 如果最终和能被 10 整除，则银行卡号有效
});

// 判断是否包含特殊API ID，需要单独勾选授权书
const needSeparateAuthorization = computed(() => {
    const specialApiIds = [
        "G22SC01",
        "Q03SC01",
        "G37SC01",
        "G36SC01",
        "G05HZ01",
    ];

    if (!featureData.value.features || !featureData.value.features.length) {
        return false;
    }

    return featureData.value.features.some((feature) =>
        specialApiIds.includes(feature.api_id)
    );
});

// 修改验证函数来检查授权书的勾选状态
function handleSubmit() {
    // 基本协议验证
    if (!agreeToTerms.value) {
        // 根据不同情况显示不同的提示信息
        if (NeedAuthorization.includes(feature.value)) {
            // 不需要授权书的产品
            showToast({ message: `请阅读并同意用户协议和隐私政策` });
        } else if (needSeparateAuthorization.value) {
            // 已经有单独的授权书勾选，这里只提示用户协议和隐私政策
            showToast({ message: `请阅读并同意用户协议和隐私政策` });
        } else {
            // 常规情况：需要授权书但不需要单独勾选
            showToast({
                message: `请阅读并同意用户协议、隐私政策和授权书同意书`,
            });
        }
        return;
    }

    // 特殊API需要单独验证授权书勾选状态
    if (needSeparateAuthorization.value && !agreeToAuthorization.value) {
        showToast({ message: `请阅读并同意授权书同意书和他人授权承诺书` });
        return;
    }

    // 欺诈赌博查询的特殊验证
    if (
        feature.value === "toc_FraudGamblingCheck" ||
        feature.value === "toc_MobileDrugFraudRiskCheck"
    ) {
        if (
            fraudGamblingCheckType.value === "mobile" &&
            !isPhoneNumberValid.value
        ) {
            showToast({ message: "请输入有效的手机号" });
            return;
        } else if (
            fraudGamblingCheckType.value === "idCard" &&
            !isIdCardValid.value
        ) {
            showToast({ message: "请输入有效的身份证号码" });
            return;
        } else if (
            fraudGamblingCheckType.value === "bankCard" &&
            !isBankCardValid.value
        ) {
            showToast({ message: "请输入有效的银行卡号码" });
            return;
        }
    } else {
        // 常规验证逻辑
        if (
            !validateField("name", name.value, (v) => v, "请输入姓名") ||
            !validateField(
                "nameMan",
                nameMan.value,
                (v) => v,
                "请输入男方姓名"
            ) ||
            !validateField(
                "nameWoman",
                nameWoman.value,
                (v) => v,
                "请输入女方姓名"
            ) ||
            !validateField(
                "mobile",
                mobile.value,
                (v) => isPhoneNumberValid.value,
                "请输入有效的手机号"
            ) ||
            !validateField(
                "idCard",
                idCard.value,
                (v) => isIdCardValid.value,
                "请输入有效的身份证号码"
            ) ||
            !validateField(
                "idCardMan",
                idCardMan.value,
                (v) => isIdCardManValid.value,
                "请输入有效的男方身份证号码"
            ) ||
            !validateField(
                "idCardWoman",
                idCardWoman.value,
                (v) => isIdCardWomanValid.value,
                "请输入有效的女方身份证号码"
            ) ||
            !validateField(
                "bankCard",
                bankCard.value,
                (v) => isBankCardValid.value,
                "请输入有效的银行卡号码"
            ) ||
            !validateField(
                "verificationCode",
                verificationCode.value,
                (v) => v,
                "请输入验证码"
            ) ||
            !validateField(
                "carPickerVal",
                carPickerVal.value,
                (v) => v,
                "请选择车辆类型"
            ) ||
            !validateField(
                "carLicense",
                carLicense.value,
                (v) => isCarLicense.value,
                "请输入正确的车牌号"
            ) ||
            !validateField(
                "entName",
                entName.value,
                (v) => v,
                "请输入企业名称"
            ) ||
            !validateField(
                "entCode",
                entCode.value,
                (v) => isCreditCodeValid.value,
                "请输入统一社会信用代码"
            ) ||
            !validateField("date", dateVal.value, (v) => v, "请选择日期") ||
            !validateField(
                "certificateNumber",
                certificateNumber.value,
                (v) => v,
                "请输入证书编号"
            ) ||
            !validateField(
                "vinCode",
                vinCode.value,
                (v) => isVinCodeValid.value,
                "请输入有效的车架号"
            ) ||
            !validateField(
                "CarDrivingPermit",
                carDrivingPermit.value,
                (v) => v,
                "请上传行驶证照片"
            )
        ) {
            return;
        }
    }
    submitRequest();
}
const validateField = (field, value, validationFn, errorMessage) => {
    if (isHasInput(field) && !validationFn(value)) {
        showToast({ message: errorMessage });
        return false;
    }
    return true;
};

const defaultInput = ["name", "idCard", "mobile", "verificationCode"];
const specialProduct = {
    toc_EnterpriseLawsuit: ["entName", "entCode", "mobile", "verificationCode"],
    toc_PhoneThreeElements: ["name", "idCard", "mobile"],
    toc_IDCardTwoElements: ["name", "idCard"],
    toc_PhoneTwoElements: ["name", "mobile"],
    toc_DualMarriage: ["nameMan", "idCardMan", "nameWoman", "idCardWoman"],
    toc_BankCardBlacklist: ["name", "idCard", "mobile", "bankCard"],
    toc_BankCardFourElements: ["name", "idCard", "mobile", "bankCard"],
    toc_NaturalLifeStatus: ["name", "idCard"],
    toc_NetworkDuration: ["mobile"],
    toc_PhoneSecondaryCard: ["mobile", "date"],
    toc_PhoneNumberRisk: ["mobile"],
    toc_ExitRestriction: ["name"],
    toc_MonthlyMobileConsumptionLevel: ["mobile"],
    toc_MobileNumberValidation: ["mobile"],
    toc_BankCardLocation: ["bankCard"],
    toc_BankCardNameElementVerification: ["name", "bankCard"],
    toc_BankCardIDElementVerification: ["idCard", "bankCard"],
    toc_BankCardThreeElementsVerification: ["name", "idCard", "bankCard"],
    toc_MobileRiskAssessment: ["mobile"],
    toc_MobileLocation: ["mobile"],
    toc_IDCardLocation: ["idCard"],
    toc_EducationVerification: ["name", "idCard", "certificateNumber"],
    toc_FraudGamblingCheck: ["fraudGamblingCheckType"], // 添加欺诈赌博查询，只用这个特殊字段标记
    toc_MobileDrugFraudRiskCheck: ["fraudGamblingCheckType"], // 药品欺诈风险查询，使用相同的单选框逻辑
    toc_DebtRepayStress: ["name", "idCard", "mobile"],
    toc_EducationInfo: ["name", "idCard"],

    //车辆
    toc_PersonVehicleVerification: ["name", "carType", "carLicense"], // 人车核验
    toc_VehiclesUnderName: ["name", "idCard"], // 名下车辆
    toc_vehicleInsuranceSummary: ["vinCode"], // 车辆出险查询
    toc_vehicleMaintenanceRecord: ["vinCode", "CarDrivingPermit"], // 车辆维保查询
    toc_vehicleValuation: ["vinCode", "carLicense"], // 车辆估价
    toc_chassisNumberCheck: ["vinCode"], // 车辆车架号查车
    toc_vehicleTransferCount: ["vinCode"], // 车辆过户次数
};
const NeedAuthorization = ["toc_Marriage"];
const isHasInput = (input) => {
    if (specialProduct[feature.value]) {
        // 欺诈赌博查询的特殊处理
        if (
            feature.value === "toc_FraudGamblingCheck" ||
            feature.value === "toc_MobileDrugFraudRiskCheck"
        ) {
            if (input === "fraudGamblingCheckType") {
                return true; // 让单选框组显示
            }
            // 根据用户选择决定显示哪个输入框
            if (input === fraudGamblingCheckType.value) {
                return true;
            }
            return false;
        }
        return specialProduct[feature.value].includes(input);
    } else {
        return defaultInput.includes(input);
    }
};
async function submitRequest() {
    const req = {};
    // 针对欺诈赌博查询和药品欺诈风险查询的特殊处理
    if (
        feature.value === "toc_FraudGamblingCheck" ||
        feature.value === "toc_MobileDrugFraudRiskCheck"
    ) {
        // 只添加用户选择的那个字段
        if (fraudGamblingCheckType.value === "mobile") {
            req.mobile = mobile.value;
        } else if (fraudGamblingCheckType.value === "idCard") {
            req.id_card = idCard.value;
        } else if (fraudGamblingCheckType.value === "bankCard") {
            req.bank_card = bankCard.value.replace(/\D/g, "");
        }
    } else {
        // 原有的逻辑
        if (isHasInput("name")) {
            req.name = name.value;
        }
        if (isHasInput("idCard")) {
            req.id_card = idCard.value;
        }
        if (isHasInput("nameMan")) {
            req.name_man = nameMan.value;
        }
        if (isHasInput("idCardMan")) {
            req.id_card_man = idCardMan.value;
        }
        if (isHasInput("nameWoman")) {
            req.name_woman = nameWoman.value;
        }
        if (isHasInput("idCardWoman")) {
            req.id_card_woman = idCardWoman.value;
        }
        if (isHasInput("bankCard")) {
            req.bank_card = bankCard.value.replace(/\D/g, "");
        }
        if (isHasInput("mobile")) {
            req.mobile = mobile.value;
        }
        if (isHasInput("verificationCode")) {
            req.code = verificationCode.value;
        }
        if (isHasInput("carType")) {
            req.car_type = carPickerVal.value[0].value;
        }
        if (isHasInput("carLicense")) {
            req.car_license = carLicense.value.trim();
        }
        if (isHasInput("date")) {
            req.start_date = startDate.value.map((item) => item).join("");
        }
        if (isHasInput("entName")) {
            req.ent_name = entName.value;
        }
        if (isHasInput("entCode")) {
            req.ent_code = entCode.value;
        }
        if (isHasInput("certificateNumber")) {
            req.certificate_number = certificateNumber.value;
        }
        if (isHasInput("vinCode")) {
            req.vin_code = vinCode.value;
        }
        if (isHasInput("CarDrivingPermit")) {
            req.car_driving_permit = carDrivingPermit.value;
        }
    }
    console.log("req", req);
    const reqStr = JSON.stringify(req);
    const encodeData = aesEncrypt(reqStr, "ff83609b2b24fc73196aac3d3dfb874f");
    const { data, error } = await useApiFetch(`/query/service/${feature.value}`)
        .post({ data: encodeData })
        .json();
    if (data.value.code === 200) {
        queryId.value = data.value.data.id;
        if (authorization.value) {
            showPayment.value = true;
        } else {
            showAuthorizationPopup.value = true;
        }
    }
}

async function sendVerificationCode() {
    if (isCountingDown.value || !isPhoneNumberValid.value) return;
    if (!isPhoneNumberValid.value) {
        showToast({ message: "请输入有效的手机号" });
        return;
    }

    const { data, error } = await useApiFetch("/auth/sendSms")
        .post({ mobile: mobile.value, actionType: "query" })
        .json();

    if (!error.value && data.value.code === 200) {
        showToast({ message: "验证码发送成功", type: "success" });
        startCountdown();
    } else {
        showToast({ message: "验证码发送失败，请重试" });
    }
}
let timer = null;

function startCountdown() {
    isCountingDown.value = true;
    countdown.value = 60;
    timer = setInterval(() => {
        if (countdown.value > 0) {
            countdown.value--;
        } else {
            clearInterval(timer);
            isCountingDown.value = false;
        }
    }, 1000);
}
function toUserAgreement() {
    router.push(`/userAgreement`);
}

function toPrivacyPolicy() {
    router.push(`/privacyPolicy`);
}

function toAuthorization() {
    router.push(`/authorization`);
}
function toOthersAuthorization() {
    router.push(`/othersAuthorization`);
}
// 用户同意
const agreed = () => {
    showAuthorizationPopup.value = false;
    authorization.value = true;
    showPayment.value = true;
};

// 用户取消
const cancel = () => {
    showAuthorizationPopup.value = false;
};
const toExample = () => {
    router.push(`/example?feature=${feature.value}`);
};
onUnmounted(() => {
    if (timer) {
        clearInterval(timer);
    }
});
</script>

<template>
    <div class="inquire-bg min-h-screen p-6">
        <div class="mb-6 text-center text-3xl font-bold text-blue-700">
            {{ featureData.product_name }}
        </div>
        <div class="card">
            <div class="mb-4 text-lg font-semibold text-gray-800">基本信息</div>

            <!-- 欺诈赌博查询的单选框组 - 移动到输入框前面并改为并排按钮样式 -->
            <div class="mb-6" v-if="isHasInput('fraudGamblingCheckType')">
                <div class="mb-2 text-sm font-medium text-gray-700">
                    请选择查询对象
                </div>
                <div class="flex space-x-2">
                    <div
                        @click="fraudGamblingCheckType = 'mobile'"
                        class="flex-1 rounded-md py-1 px-2 text-center text-sm cursor-pointer transition-colors"
                        :class="
                            fraudGamblingCheckType === 'mobile'
                                ? 'bg-blue-500 text-white'
                                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                        "
                    >
                        手机号
                    </div>
                    <div
                        @click="fraudGamblingCheckType = 'idCard'"
                        class="flex-1 rounded-md py-1 px-2 text-center text-sm cursor-pointer transition-colors"
                        :class="
                            fraudGamblingCheckType === 'idCard'
                                ? 'bg-blue-500 text-white'
                                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                        "
                    >
                        身份证号
                    </div>
                    <div
                        @click="fraudGamblingCheckType = 'bankCard'"
                        class="flex-1 rounded-md py-1 px-2 text-center text-sm cursor-pointer transition-colors"
                        :class="
                            fraudGamblingCheckType === 'bankCard'
                                ? 'bg-blue-500 text-white'
                                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
                        "
                    >
                        银行卡号
                    </div>
                </div>
            </div>

            <div class="mb-4 flex items-center" v-if="isHasInput('name')">
                <label for="name" class="form-label">姓名</label>
                <input
                    v-model="name"
                    id="name"
                    type="text"
                    placeholder="请输入姓名"
                    class="form-input"
                />
            </div>
            <div class="mb-4 flex items-center" v-if="isHasInput('idCard')">
                <label for="idCard" class="form-label">身份证号</label>
                <input
                    v-model="idCard"
                    id="idCard"
                    type="text"
                    placeholder="请输入身份证号"
                    class="form-input"
                />
            </div>
            <!-- 双人婚姻 -->
            <div class="mb-4 flex items-center" v-if="isHasInput('nameMan')">
                <label for="nameMan" class="form-label">男方姓名</label>
                <input
                    v-model="nameMan"
                    id="nameMan"
                    type="text"
                    placeholder="请输入男方姓名"
                    class="form-input"
                />
            </div>
            <div class="mb-4 flex items-center" v-if="isHasInput('idCardMan')">
                <label for="idCardMan" class="form-label">男方身份证号</label>
                <input
                    v-model="idCardMan"
                    id="idCardMan"
                    type="text"
                    placeholder="请输入男方身份证号"
                    class="form-input"
                />
            </div>
            <div class="mb-4 flex items-center" v-if="isHasInput('nameWoman')">
                <label for="nameWoman" class="form-label">女方姓名</label>
                <input
                    v-model="nameWoman"
                    id="nameWoman"
                    type="text"
                    placeholder="请输入女方姓名"
                    class="form-input"
                />
            </div>
            <div
                class="mb-4 flex items-center"
                v-if="isHasInput('idCardWoman')"
            >
                <label for="idCardWoman" class="form-label">女方身份证号</label>
                <input
                    v-model="idCardWoman"
                    id="idCardWoman"
                    type="text"
                    placeholder="请输入女方身份证号"
                    class="form-input"
                />
            </div>
            <!-- 双人婚姻 -->

            <div class="mb-4 flex items-center" v-if="isHasInput('entName')">
                <label for="entName" class="form-label">企业名称</label>
                <input
                    v-model="entName"
                    id="entName"
                    type="text"
                    placeholder="请输入企业名称"
                    class="form-input"
                />
            </div>
            <div class="mb-4 flex items-center" v-if="isHasInput('entCode')">
                <label for="entCode" class="form-label">统一社会信用代码</label>
                <input
                    v-model="entCode"
                    id="entCode"
                    type="text"
                    placeholder="请输入统一社会信用代码"
                    class="form-input"
                />
            </div>
            <div class="mb-4 flex items-center" v-if="isHasInput('carType')">
                <label for="carType" class="form-label">汽车类型</label>
                <van-field
                    id="carType"
                    v-model="carType"
                    is-link
                    readonly
                    placeholder="点击选择汽车类型"
                    @click="showCarTypePicker = true"
                    class="form-input"
                />
                <van-popup
                    v-model:show="showCarTypePicker"
                    destroy-on-close
                    round
                    position="bottom"
                >
                    <van-picker
                        :model-value="carPickerVal"
                        :columns="carTypeColumns"
                        @cancel="showCarTypePicker = false"
                        @confirm="onConfirmCarType"
                    />
                </van-popup>
            </div>

            <div class="mb-4 flex items-center" v-if="isHasInput('carLicense')">
                <label for="carLicense" class="form-label !w-12">车牌号</label>
                <CarNumberInput
                    class="form-input"
                    @number-input-result="carLicenseChange"
                    :default-str="carLicense"
                >
                </CarNumberInput>
            </div>
            <div class="mb-4 flex items-center" v-if="isHasInput('bankCard')">
                <label for="bankCard" class="form-label">银行卡号</label>
                <input
                    v-model="bankCard"
                    id="bankCard"
                    type="tel"
                    placeholder="请输入银行卡号"
                    class="form-input"
                />
            </div>
            <div class="mb-4 flex items-center" v-if="isHasInput('mobile')">
                <label for="mobile" class="form-label">手机号</label>
                <input
                    v-model="mobile"
                    id="mobile"
                    type="tel"
                    placeholder="请输入手机号"
                    class="form-input"
                />
            </div>
            <div class="mb-4 flex items-center" v-if="isHasInput('date')">
                <label for="date" class="form-label">业务日期</label>
                <van-field
                    id="date"
                    v-model="dateVal"
                    is-link
                    readonly
                    placeholder="点击选择日期"
                    @click="showDatePicker = true"
                    class="form-input"
                />
                <van-popup
                    v-model:show="showDatePicker"
                    destroy-on-close
                    round
                    position="bottom"
                >
                    <van-date-picker
                        v-model="startDate"
                        :formatter="formatterDate"
                        :min-date="minDate"
                        :max-date="maxDate"
                        title="选择日期"
                        @confirm="onConfirmDate"
                        @cancel="showDatePicker = false"
                    />
                </van-popup>
            </div>
            <div
                class="mb-4 flex items-center"
                v-if="isHasInput('certificateNumber')"
            >
                <label for="certificateNumber" class="form-label"
                    >证书编号</label
                >
                <input
                    v-model="certificateNumber"
                    id="certificateNumber"
                    type="text"
                    placeholder="请输入证书编号"
                    class="form-input"
                />
            </div>

            <div class="mb-4 flex items-center" v-if="isHasInput('vinCode')">
                <label for="vinCode" class="form-label">车架号</label>
                <input
                    v-model="vinCode"
                    id="vinCode"
                    type="text"
                    placeholder="请输入17位车架号"
                    class="form-input"
                    maxlength="17"
                />
            </div>

            <div class="mb-4" v-if="isHasInput('CarDrivingPermit')">
                <div class="mb-2">
                    <label class="form-label block mb-2">行驶证照片</label>
                    <div
                        class="relative w-full h-40 border-2 border-dashed border-gray-300 rounded-lg flex flex-col items-center justify-center bg-gray-50 cursor-pointer overflow-hidden"
                        @click="$refs.fileInput.click()"
                    >
                        <!-- 未上传时显示提示 -->
                        <template v-if="!carDrivingPermitFile">
                            <svg
                                class="mx-auto h-12 w-12 text-gray-400"
                                stroke="currentColor"
                                fill="none"
                                viewBox="0 0 48 48"
                            >
                                <path
                                    d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                                    stroke-width="2"
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                />
                            </svg>
                            <p class="mt-2 text-sm text-gray-600">
                                点击或拖拽上传行驶证照片
                            </p>
                            <p class="mt-1 text-xs text-gray-500">
                                (支持JPG、PNG格式)
                            </p>
                        </template>

                        <!-- 上传后显示图片预览 -->
                        <img
                            v-else
                            :src="`data:image/jpeg;base64,${carDrivingPermit}`"
                            class="absolute inset-0 w-full h-full object-contain"
                            alt="行驶证照片"
                        />
                    </div>
                    <input
                        ref="fileInput"
                        type="file"
                        accept="image/*"
                        @change="handleCarDrivingPermitUpload"
                        class="hidden"
                    />
                </div>
                <div
                    v-if="carDrivingPermitFile"
                    class="mt-2 text-xs text-gray-500 flex justify-between"
                >
                    <span>文件: {{ carDrivingPermitFile.name }}</span>
                    <span
                        >{{
                            (carDrivingPermitFile.size / 1024).toFixed(2)
                        }}KB</span
                    >
                </div>
            </div>

            <div
                class="mb-4 flex items-center"
                v-if="isHasInput('verificationCode')"
            >
                <label for="verificationCode" class="form-label">验证码</label>
                <div class="flex-1 flex items-center">
                    <input
                        v-model="verificationCode"
                        id="verificationCode"
                        type="text"
                        placeholder="请输入验证码"
                        class="form-input flex-1"
                    />
                    <button
                        class="ml-2 px-4 py-2 text-sm text-blue-500 disabled:text-gray-400"
                        :disabled="isCountingDown || !isPhoneNumberValid"
                        @click="sendVerificationCode"
                    >
                        {{
                            isCountingDown
                                ? `${countdown}s重新获取`
                                : "获取验证码"
                        }}
                    </button>
                </div>
            </div>

            <div class="mb-4 flex items-center">
                <input type="checkbox" v-model="agreeToTerms" />
                <span class="ml-2 text-xs text-gray-400">
                    我已阅读并同意
                    <span @click="toUserAgreement" class="text-blue-500"
                        >《用户协议》</span
                    >
                    <span @click="toPrivacyPolicy" class="text-blue-500"
                        >《隐私政策》</span
                    >
                    <template
                        v-if="
                            !NeedAuthorization.includes(feature) &&
                            !needSeparateAuthorization
                        "
                    >
                        <span @click="toAuthorization" class="text-blue-500"
                            >《授权书同意书》</span
                        >
                    </template>
                </span>
            </div>

            <!-- 特殊API需要单独勾选授权书 -->
            <div
                class="mb-4 flex items-center"
                v-if="needSeparateAuthorization"
            >
                <input type="checkbox" v-model="agreeToAuthorization" />
                <span class="ml-2 text-xs text-gray-400">
                    我已阅读并同意
                    <span @click="toAuthorization" class="text-blue-500"
                        >《授权书同意书》</span
                    >
                    <span @click="toOthersAuthorization" class="text-blue-500"
                        >《他人授权承诺书》</span
                    >
                </span>
            </div>
            <div class="flex items-center">
                <button
                    class="w-24 rounded-l-xl bg-blue-400 py-2 text-white"
                    @click="toExample"
                >
                    示例报告
                </button>
                <button
                    class="flex-1 rounded-r-xl bg-blue-500 py-2 text-white"
                    @click="handleSubmit"
                >
                    立即查询
                </button>
            </div>
        </div>
        <div class="card mt-4">
            <div class="mb-4 text-xl text-gray-800 font-bold">
                {{ featureData.product_name }}
            </div>
            <div class="mb-4 flex items-start justify-between">
                <div class="text-lg text-gray-500">价格：</div>
                <div>
                    <div class="text-2xl text-red-600 font-semibold">
                        ¥{{ featureData.sell_price }}
                    </div>
                </div>
            </div>
            <div
                class="mb-4 text-gray-600 leading-relaxed"
                v-html="featureData.description"
            ></div>
            <div class="mb-2 text-xs text-red-500 italic">
                为保证用户的隐私以及数据安全，查询的结果生成15天之后将自动清除。
            </div>
            <template
                v-if="featureData.features && featureData.features.length > 1"
            >
                <div class="mb-4 text-lg text-gray-800 font-semibold">
                    报告包含内容
                </div>
                <div class="grid grid-cols-2 gap-4">
                    <div
                        class="rounded-lg py-2 text-center text-sm text-gray-700 font-medium bg-gradient-to-r from-blue-200 via-blue-200 to-blue-100"
                    >
                        分析指数
                    </div>
                    <div
                        class="rounded-lg py-2 text-center text-sm text-gray-700 font-medium bg-gradient-to-r from-sky-200 via-sky-200 to-sky-100"
                    >
                        基本信息
                    </div>
                    <div
                        v-for="(feature, index) in featureData.features"
                        :key="feature.id"
                        class="rounded-lg py-2 text-center text-sm text-gray-700 font-medium"
                        :class="[
                            (Math.floor(index / 2) + (index % 2)) % 2 === 0
                                ? 'bg-gradient-to-r from-blue-200 via-blue-200 to-blue-100'
                                : 'bg-gradient-to-r from-sky-200 via-sky-200 to-sky-100',
                        ]"
                    >
                        {{ feature.name }}
                    </div>
                </div>
            </template>
        </div>
    </div>
    <!-- 底部弹出 -->
    <van-popup
        v-model:show="showAuthorizationPopup"
        position="bottom"
        :style="{ height: '80%' }"
    >
        <Authorization
            :style="{ height: '100%' }"
            :name="name"
            :id-card="idCard"
            :mobile="mobile"
            @agreed="agreed"
            @cancel="cancel"
        />
    </van-popup>
    <Payment
        v-model="showPayment"
        :data="featureData"
        :id="queryId"
        @close="showPayment = false"
    />
</template>

<style scoped>
.form-label {
    @apply w-20 text-sm font-medium text-gray-700 flex-shrink-0;
}

.form-input::placeholder {
    color: var(--van-text-color-3);
}

.form-input {
    @apply w-full border-b border-gray-200 px-2 py-2 focus:outline-none;
}

.inquire-bg {
    background: url("@/assets/images/bg_2.png") no-repeat;
    background-position: center;
    background-size: cover;
}
</style>
