<script setup>
import { ref, reactive, computed, onMounted, onUnmounted } from "vue";
import { aesEncrypt } from "@/utils/crypto";
import { useRoute } from "vue-router";
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 startDate = ref([])
const dateVal = ref("")
const showDatePicker = ref(false)
// 当前日期
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);
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 }) => {
    dateVal.value = selectedOptions.map(item => item.text).join('');
    showDatePicker.value = false
}
const carLicenseChange = (e) => {
    carLicense.value = e;
};
const onConfirmCarType = ({ selectedValues, selectedOptions }) => {
    showCarTypePicker.value = false;
    carPickerVal.value = selectedValues;
    carType.value = selectedOptions[0].text;
};




onMounted(() => {
    isFinishPayment()
    getProduct();
    initAuthorization();
});
const discountPrice = ref(false)  // 是否应用折扣

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;
    }
}
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 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 整除，则银行卡号有效
});

function handleSubmit() {
    if (!agreeToTerms.value) {
        showToast({ message: `请阅读并同意用户协议、隐私政策${!NeedAuthorization.includes(feature.value) ? '和授权书' : ''}` });
        return;
    }
    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,
            "请选择日期"
        )

    ) {
        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_PersonVehicleVerification: ["name", "carType", "carLicense"],
    toc_VehiclesUnderName: ["name", "idCard"],
    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"],
};
const NeedAuthorization = [
    "toc_Marriage",
    "marriage"
];
const isHasInput = (input) => {
    if (specialProduct[feature.value]) {
        return specialProduct[feature.value].includes(input);
    } else {
        return defaultInput.includes(input);
    }
};
async function submitRequest() {
    const req = {};
    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;
    }
    const reqStr = JSON.stringify(req);
    const encodeData = aesEncrypt(reqStr, "3a7f1e9d4c2b8a05e6f0d3c7b2a9845d");
    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`)
}
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="card">
            <div class="mb-4 text-lg font-semibold text-gray-800">基本信息</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="entCode" class="form-label">车牌号</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('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)">
                        <span @click="toAuthorization" class="text-blue-500 ">、授权书</span>
                    </template>
                </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>

</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;
}
</style>
