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

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

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();
const showPayment = ref(false);
const queryId = ref(null);
const name = ref("");
const idCard = ref("");
const mobile = ref("");
const verificationCode = ref("");
const agreeToTerms = ref(false);
const isCountingDown = ref(false);
const countdown = ref(60);
const feature = ref(route.params.feature);
const featureData = ref({});

onMounted(() => {
    isFinishPayment();
    getProduct();
});

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;
        // 确保 FLXG0V4B 排在首位
        if (
            featureData.value.features &&
            featureData.value.features.length > 0
        ) {
            featureData.value.features.sort((a, b) => {
                if (a.api_id === "FLXG0V4B") return -1;
                if (b.api_id === "FLXG0V4B") return 1;
                return 0;
            });
        }
    }
}

const isPhoneNumberValid = computed(() => {
    return /^1[3-9]\d{9}$/.test(mobile.value);
});
const isIdCardValid = computed(() => /^\d{17}[\dX]$/i.test(idCard.value));

// 检查登录状态
const isLoggedIn = computed(() => userStore.isLoggedIn);

// 处理输入框点击事件
const handleInputClick = async () => {
    if (!isLoggedIn.value) {
        try {
            await showConfirmDialog({
                title: '提示',
                message: '您需要登录后才能进行查询，是否前往登录？',
                confirmButtonText: '前往登录',
                cancelButtonText: '取消',
            });
            // 用户点击确认，跳转到登录页面
            router.push('/login');
        } catch {
            // 用户点击取消，什么都不做
        }
    }
};

function handleSubmit() {
    // 如果未登录，跳转到登录页面
    if (!isLoggedIn.value) {
        router.push('/login');
        return;
    }

    // 基本协议验证
    if (!agreeToTerms.value) {
        showToast({ message: `请阅读并同意用户协议和隐私政策` });
        return;
    }

    if (
        !validateField("name", name.value, (v) => v, "请输入姓名") ||
        !validateField(
            "mobile",
            mobile.value,
            (v) => isPhoneNumberValid.value,
            "请输入有效的手机号"
        ) ||
        !validateField(
            "idCard",
            idCard.value,
            (v) => isIdCardValid.value,
            "请输入有效的身份证号码"
        ) ||
        !validateField(
            "verificationCode",
            verificationCode.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 isHasInput = (input) => {
    return defaultInput.includes(input);
};
async function submitRequest() {
    const req = {
        name: name.value,
        id_card: idCard.value,
        mobile: mobile.value,
        code: verificationCode.value
    };
    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;
        showPayment.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();
        // 聚焦到验证码输入框
        nextTick(() => {
            const verificationCodeInput = document.getElementById('verificationCode');
            if (verificationCodeInput) {
                verificationCodeInput.focus();
            }
        });
    } 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`);
}

const toExample = () => {
    router.push(`/example?feature=${feature.value}`);
};
// 获取功能图标
const getFeatureIcon = (apiId) => {
    const iconMap = {
        JRZQ4AA8: "/inquire_icons/huankuanyali.svg", // 还款压力
        QCXG7A2B: "/inquire_icons/mingxiacheliang.svg", // 名下车辆
        BehaviorRiskScan: "/inquire_icons/fengxianxingwei.svg", // 风险行为扫描
        IVYZ5733: "/inquire_icons/hunyinzhuangtai.svg", // 婚姻状态
        PersonEnterprisePro: "/inquire_icons/renqiguanxi.svg", // 人企关系加强版
        JRZQ0A03: "/inquire_icons/jiedaishenqing.svg", // 借贷申请记录
        FLXG3D56: "/inquire_icons/jiedaiweiyue.svg", // 借贷违约失信
        FLXG0V4B: "/inquire_icons/sifasheyu.svg", // 司法涉诉
        JRZQ8203: "/inquire_icons/jiedaixingwei.svg", // 借贷行为记录
        JRZQ09J8: "/inquire_icons/beijianguanrenyuan.svg", // 收入评估
        JRZQ4B6C: "/inquire_icons/fengxianxingwei.svg", // 探针C风险评估
    };
    return iconMap[apiId] || "/inquire_icons/default.svg";
};

// 处理图标加载错误
const handleIconError = (event) => {
    // 如果图标加载失败，显示默认图标或隐藏
    event.target.style.display = "none";
};

// 获取卡片样式类
const getCardClass = (index) => {
    const colorIndex = index % 4;
    const colorClasses = [
        'bg-gradient-to-br from-blue-50 via-blue-25 to-white ',
        'bg-gradient-to-br from-green-50 via-green-25 to-white ',
        'bg-gradient-to-br from-purple-50 via-purple-25 to-white ',
        'bg-gradient-to-br from-orange-50 via-orange-25 to-white '
    ];
    return colorClasses[colorIndex];
};

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" style="color: var(--van-theme-primary);">
            {{ featureData.product_name }}
        </div>
        <div class="card">
            <div class="mb-4 text-lg font-semibold" style="color: var(--van-text-color);">基本信息</div>
            <div class="mb-4">
                <label for="name" class="form-label block mb-2">姓名</label>
                <input v-model="name" id="name" type="text" placeholder="请输入姓名" class="form-input"
                    @click="handleInputClick" />
            </div>
            <div class="mb-4">
                <label for="idCard" class="form-label block mb-2">身份证号</label>
                <input v-model="idCard" id="idCard" type="text" placeholder="请输入身份证号" class="form-input"
                    @click="handleInputClick" />
            </div>
            <div class="mb-4">
                <label for="mobile" class="form-label block mb-2">手机号</label>
                <input v-model="mobile" id="mobile" type="tel" placeholder="请输入手机号" class="form-input"
                    @click="handleInputClick" />
            </div>
            <div class="mb-4">
                <label for="verificationCode" class="form-label block mb-2">验证码</label>
                <div class="flex items-center gap-2">
                    <input v-model="verificationCode" id="verificationCode" placeholder="请输入验证码" maxlength="6"
                        class="form-input flex-1 min-w-0" @click="handleInputClick" />
                    <button
                        class="px-4 py-2 text-sm whitespace-nowrap flex-shrink-0 rounded-lg border transition-colors"
                        :class="isCountingDown || !isPhoneNumberValid
                            ? 'text-gray-400 border-gray-300 bg-gray-50'
                            : 'text-white border-transparent'" :style="isCountingDown || !isPhoneNumberValid
                                ? ''
                                : 'background-color: var(--van-theme-primary);'"
                        :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" style="color: var(--van-text-color-2);">
                    我已阅读并同意
                    <span @click="toUserAgreement" class="cursor-pointer hover:underline"
                        style="color: var(--van-theme-primary);">《用户协议》</span>
                    <span @click="toPrivacyPolicy" class="cursor-pointer hover:underline"
                        style="color: var(--van-theme-primary);">《隐私政策》</span>
                    <span @click="toAuthorization" class="cursor-pointer hover:underline"
                        style="color: var(--van-theme-primary);">《授权书》</span>
                </span>
            </div>
            <div class="flex flex-col sm:flex-row gap-2">
                <button
                    class="flex-1 sm:w-24 rounded-xl sm:rounded-l-xl sm:rounded-r-none py-3 text-white text-base border transition-colors"
                    style="background-color: var(--van-theme-primary-light); color: var(--van-theme-primary); border-color: var(--van-theme-primary);"
                    @click="toExample">
                    示例报告
                </button>
                <button
                    class="flex-1 rounded-xl sm:rounded-l-none sm:rounded-r-xl py-3 text-white text-base transition-colors"
                    style="background-color: var(--van-theme-primary);" @click="handleSubmit">
                    {{ isLoggedIn ? '立即查询' : '前往登录' }}
                </button>
            </div>
        </div>
        <div class="card mt-3" v-if="featureData.features && featureData.features.length > 0">
            <div class="mb-3 text-base font-semibold flex items-center" style="color: var(--van-text-color);">
                <div class="w-1 h-5 rounded-full mr-2"
                    style="background: linear-gradient(to bottom, var(--van-theme-primary), var(--van-theme-primary-dark));">
                </div>
                报告包含内容
            </div>
            <div class="grid grid-cols-4 gap-2">
                <template v-for="(feature, index) in featureData.features" :key="feature.id">
                    <!-- FLXG0V4B 特殊处理：显示8个独立的案件类型 -->
                    <template v-if="feature.api_id === 'FLXG0V4B'">
                        <div v-for="(caseType, caseIndex) in [
                            { name: '管辖案件', icon: 'beijianguanrenyuan.svg' },
                            { name: '刑事案件', icon: 'xingshi.svg' },
                            { name: '民事案件', icon: 'minshianjianguanli.svg' },
                            { name: '失信被执行', icon: 'shixinren.svg' },
                            { name: '行政案件', icon: 'xingzhengfuwu.svg' },
                            { name: '赔偿案件', icon: 'yuepeichang.svg' },
                            { name: '执行案件', icon: 'zhixinganjian.svg' },
                            { name: '限高被执行', icon: 'xianzhigaoxiaofei.svg' },
                        ]" :key="`${feature.id}-${caseIndex}`"
                            class="aspect-square text-center text-sm text-gray-700 font-medium flex flex-col items-center justify-center">
                            <div class="mb-1">
                                <img :src="`/inquire_icons/${caseType.icon}`" :alt="caseType.name"
                                    class="w-6 h-6 drop-shadow-sm mx-auto" @error="handleIconError" />
                            </div>
                            <div class="text-xs leading-tight font-medium"
                                style="word-break: break-all; line-height: 1.1; min-height: 28px; display: flex; align-items: center; justify-content: center;">
                                {{ caseType.name }}
                            </div>
                        </div>
                    </template>

                    <!-- DWBG8B4D 特殊处理：显示拆分模块 -->
                    <template v-else-if="feature.api_id === 'DWBG8B4D'">
                        <div v-for="(module, moduleIndex) in [
                            { name: '要素核查', icon: 'beijianguanrenyuan.svg' },
                            { name: '运营商核验', icon: 'mingxiacheliang.svg' },
                            { name: '公安重点人员检验', icon: 'xingshi.svg' },
                            { name: '逾期风险综述', icon: 'huankuanyali.svg' },
                            // { name: '法院曝光台信息', icon: 'sifasheyu.svg' },
                            { name: '借贷评估', icon: 'jiedaishenqing.svg' },
                            { name: '租赁风险评估', icon: 'jiedaixingwei.svg' },
                            { name: '关联风险监督', icon: 'renqiguanxi.svg' },
                            { name: '规则风险提示', icon: 'fengxianxingwei.svg' },
                        ]" :key="`${feature.id}-${moduleIndex}`"
                            class="aspect-squaretext-center text-sm text-gray-700 font-medium flex flex-col items-center justify-center">
                            <div class="text-xl mb-1 flex items-center justify-center">
                                <img :src="`/inquire_icons/${module.icon}`" :alt="module.name"
                                    class="w-6 h-6 drop-shadow-sm" @error="handleIconError" />
                            </div>
                            <div class="text-xs leading-tight px-1 font-medium text-center"
                                style="word-break: break-all; line-height: 1.2">
                                {{ module.name }}
                            </div>
                        </div>
                    </template>

                    <!-- CJRZQ5E9F 特殊处理：显示拆分模块 -->
                    <template v-else-if="feature.api_id === 'JRZQ5E9F'">
                        <div v-for="(module, moduleIndex) in [
                            { name: '信用评分', icon: 'huankuanyali.svg' },
                            { name: '贷款行为分析', icon: 'jiedaixingwei.svg' },
                            { name: '机构分析', icon: 'jiedaishenqing.svg' },
                            { name: '时间趋势分析', icon: 'zhixinganjian.svg' },
                            { name: '风险指标详情', icon: 'fengxianxingwei.svg' },
                            { name: '专业建议', icon: 'yuepeichang.svg' },
                        ]" :key="`${feature.id}-${moduleIndex}`"
                            class="aspect-square text-center text-sm text-gray-700 font-medium flex flex-col items-center justify-center">
                            <div class="text-xl mb-1 flex items-center justify-center">
                                <img :src="`/inquire_icons/${module.icon}`" :alt="module.name"
                                    class="w-6 h-6 drop-shadow-sm" @error="handleIconError" />
                            </div>
                            <div class="text-xs leading-tight px-1 font-medium text-center"
                                style="word-break: break-all; line-height: 1.2">
                                {{ module.name }}
                            </div>
                        </div>
                    </template>

                    <!-- PersonEnterprisePro/CQYGL3F8E 特殊处理：显示拆分模块 -->
                    <template v-else-if="feature.api_id === 'PersonEnterprisePro' || feature.api_id === 'QYGL3F8E'">
                        <div v-for="(module, moduleIndex) in [
                            { name: '投资企业记录', icon: 'renqiguanxi.svg' },
                            { name: '高管任职记录', icon: 'beijianguanrenyuan.svg' },
                            { name: '涉诉风险', icon: 'sifasheyu.svg' },
                            { name: '对外投资历史', icon: 'renqiguanxi.svg' },
                            { name: '融资历史', icon: 'huankuanyali.svg' },
                            { name: '行政处罚', icon: 'xingzhengfuwu.svg' },
                            { name: '经营异常', icon: 'fengxianxingwei.svg' },
                        ]" :key="`${feature.id}-${moduleIndex}`"
                            class="aspect-square text-center text-sm text-gray-700 font-medium flex flex-col items-center justify-center">
                            <div class="text-xl mb-1 flex items-center justify-center">
                                <img :src="`/inquire_icons/${module.icon}`" :alt="module.name"
                                    class="w-6 h-6 drop-shadow-sm" @error="handleIconError" />
                            </div>
                            <div class="text-xs leading-tight px-1 font-medium text-center"
                                style="word-break: break-all; line-height: 1.2">
                                {{ module.name }}
                            </div>
                        </div>
                    </template>

                    <!-- DWBG6A2C 特殊处理：显示拆分模块 -->
                    <template v-else-if="feature.api_id === 'DWBG6A2C'">
                        <div v-for="(module, moduleIndex) in [
                            { name: '命中风险标注', icon: 'fengxianxingwei.svg' },
                            { name: '公安重点人员核验', icon: 'beijianguanrenyuan.svg' },
                            { name: '涉赌涉诈人员核验', icon: 'xingshi.svg' },
                            { name: '风险名单', icon: 'jiedaiweiyue.svg' },
                            { name: '历史借贷行为', icon: 'jiedaixingwei.svg' },
                            { name: '近24个月放款情况', icon: 'jiedaishenqing.svg' },
                            { name: '履约情况', icon: 'huankuanyali.svg' },
                            { name: '历史逾期记录', icon: 'jiedaiweiyue.svg' },
                            { name: '授信详情', icon: 'huankuanyali.svg' },
                            { name: '租赁行为', icon: 'mingxiacheliang.svg' },
                            { name: '关联风险监督', icon: 'renqiguanxi.svg' },
                            // { name: '法院风险信息', icon: 'sifasheyu.svg' },
                        ]" :key="`${feature.id}-${moduleIndex}`"
                            class="aspect-square text-center text-sm text-gray-700 font-medium flex flex-col items-center justify-center">
                            <div class="text-xl mb-1 flex items-center justify-center">
                                <img :src="`/inquire_icons/${module.icon}`" :alt="module.name"
                                    class="w-6 h-6 drop-shadow-sm" @error="handleIconError" />
                            </div>
                            <div class="text-xs leading-tight px-1 font-medium text-center"
                                style="word-break: break-all; line-height: 1.2">
                                {{ module.name }}
                            </div>
                        </div>
                    </template>

                    <!-- 其他功能正常显示 -->
                    <div v-else
                        class="aspect-square text-center text-sm text-gray-700 font-medium flex flex-col items-center justify-between">
                        <div class="flex items-center justify-center flex-1">
                            <img :src="getFeatureIcon(feature.api_id)" :alt="feature.name"
                                class="w-6 h-6 drop-shadow-sm" @error="handleIconError" />
                        </div>
                        <div class="text-xs leading-tight font-medium h-8 flex items-center justify-center text-center"
                            style="word-break: break-all; line-height: 1.1">
                            {{ feature.name }}
                        </div>
                    </div>
                </template>
            </div>
            <div class="mt-3 text-center">
                <div class="inline-flex items-center px-3 py-1.5 rounded-full border transition-all"
                    style="background: linear-gradient(135deg, var(--van-theme-primary-light), rgba(255,255,255,0.8)); border-color: var(--van-theme-primary);">
                    <div class="w-1.5 h-1.5 rounded-full mr-1.5" style="background-color: var(--van-theme-primary);">
                    </div>
                    <span class="text-xs font-medium" style="color: var(--van-theme-primary);">更多信息请解锁报告</span>
                </div>
            </div>
        </div>
        <div class="card mt-4">
            <div class="mb-4 text-xl font-bold" style="color: var(--van-text-color);">
                {{ featureData.product_name }}
            </div>
            <div class="mb-4 flex items-start justify-between">
                <div class="text-lg" style="color: var(--van-text-color-2);">价格：</div>
                <div>
                    <div class="text-2xl font-semibold" style="color: var(--van-theme-primary);">
                        ¥{{ featureData.sell_price }}
                    </div>
                </div>
            </div>

            <div class="mb-4 leading-relaxed" style="color: var(--van-text-color-2);" v-html="featureData.description">
            </div>
            <div class="mb-2 text-xs italic" style="color: var(--van-theme-primary);">
                为保证用户的隐私以及数据安全，查询的结果生成30天之后将自动清除。
            </div>
        </div>
    </div>
    <Payment v-model="showPayment" :data="featureData" :id="queryId" type="query" @close="showPayment = false" />
</template>

<style scoped>
.form-label {
    @apply text-sm font-medium;
    color: var(--van-text-color);
}

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

.form-input {
    @apply w-full border-b px-2 py-3 focus:outline-none text-base transition-colors;
    min-height: 44px;
    border-color: var(--van-border-color);
    color: var(--van-text-color);
    background-color: transparent;
}

.form-input:focus {
    border-color: var(--van-theme-primary);
}

/* 移动端优化 */
@media (max-width: 768px) {
    .form-input {
        font-size: 16px;
        /* 防止iOS缩放 */
        padding: 12px 8px;
    }

    .form-label {
        font-size: 14px;
        margin-bottom: 8px;
    }
}

.inquire-bg {
    /* 优雅的渐变背景 - 增强对比度 */
    background: linear-gradient(135deg,
            #f0f4f8 0%,
            #e2e8f0 25%,
            #cbd5e1 50%,
            #e2e8f0 75%,
            #f0f4f8 100%) !important;

    /* 优化性能的纹理效果 - 减少层数 */
    background-image:
        /* 主要圆形纹理 */
        radial-gradient(circle at 25% 75%, rgba(162, 37, 37, 0.15) 0%, transparent 65%),
        radial-gradient(circle at 75% 25%, rgba(162, 37, 37, 0.12) 0%, transparent 60%),

        /* 简化网格纹理 */
        linear-gradient(45deg, rgba(162, 37, 37, 0.06) 25%, transparent 25%, transparent 75%, rgba(162, 37, 37, 0.06) 75%) !important;

    /* 优化尺寸和位置 */
    background-size:
        500px 500px,
        450px 450px,
        80px 80px !important;

    background-position:
        0 0,
        200px 200px,
        0 0 !important;

    /* 确保背景覆盖整个视口 */
    min-height: 100vh;
    position: relative;

    /* 性能优化 */
    background-attachment: fixed;
    will-change: auto;
    transform: translateZ(0);
    /* 启用硬件加速 */
}

/* 优化性能的叠加纹理层 */
.inquire-bg::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background:
        /* 简化圆形纹理 */
        radial-gradient(circle at 20% 30%, rgba(162, 37, 37, 0.10) 0%, transparent 60%),
        radial-gradient(circle at 80% 70%, rgba(162, 37, 37, 0.08) 0%, transparent 55%),

        /* 简化线条纹理 */
        linear-gradient(45deg, rgba(162, 37, 37, 0.05) 0%, transparent 50%, rgba(162, 37, 37, 0.05) 100%);

    background-size:
        400px 400px,
        350px 350px,
        200px 2px;

    background-position:
        0 0,
        200px 200px,
        0 0;

    pointer-events: none;
    z-index: -1;

    /* 性能优化 */
    will-change: auto;
    transform: translateZ(0);
    /* 启用硬件加速 */
}

/* 卡片样式优化 */
.card {
    @apply shadow-lg rounded-xl p-6 transition-all hover:shadow-xl;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border: 1px solid rgba(255, 255, 255, 0.2);
    box-shadow:
        0 4px 6px -1px rgba(0, 0, 0, 0.1),
        0 2px 4px -1px rgba(0, 0, 0, 0.06),
        0 0 0 1px rgba(255, 255, 255, 0.05);
}

/* 按钮悬停效果 */
button:hover {
    transform: translateY(-1px);
}

button:active {
    transform: translateY(0);
}
</style>
