<template>
    <el-form ref="formRef" :model="form" label-width="120px">
        <el-form-item label="开启验证" prop="openVerify">
            <el-switch v-model="form.openVerify" />
        </el-form-item>

        <el-form-item label="验证模式" prop="verifyModel">
            <el-radio-group v-model="form.verifyModel" :disabled="!form.openVerify">
                <el-radio-button value="1">图形</el-radio-button>
                <el-radio-button value="2">短信</el-radio-button>
                <el-radio-button value="3">邮箱</el-radio-button>
                <el-radio-button value="4">极验3.0</el-radio-button>
                <el-radio-button value="5">极验4.0</el-radio-button>
            </el-radio-group>
        </el-form-item>

        <template v-if="form.verifyModel === '4'">
            <el-form-item label="极验ID" prop="geetest3ID">
                <el-input v-model="form.geetest3ID" />
            </el-form-item>
            <el-form-item label="极验KEY" prop="geetest3KEY">
                <el-input v-model="form.geetest3KEY" />
            </el-form-item>
        </template>

        <template v-if="form.verifyModel === '5'">
            <el-form-item label="极验ID" prop="geetest4ID">
                <el-input v-model="form.geetest4ID" />
            </el-form-item>
            <el-form-item label="极验KEY" prop="geetest4KEY">
                <el-input v-model="form.geetest4KEY" />
            </el-form-item>
        </template>

        <el-form-item>
            <el-button type="primary" @click="handleSave">保存</el-button>
            <el-button @click="formRef?.resetFields()">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup lang="ts">
import { ref, reactive } from "vue";
import { ElMessage } from "element-plus";
import { getVerifyInfos, saveVerifyInfos } from "@/api/sitesettings";

const formRef = ref();
const form = reactive({
    openVerify: false,
    verifyModel: "1",
    geetest3ID: "",
    geetest3KEY: "",
    geetest4ID: "",
    geetest4KEY: ""
});

const init = async () => {
    const { code, data } = await getVerifyInfos();
    if (code === 200 && Array.isArray(data)) {
        const formData = {};
        data.forEach(item => {
            if (item.label === 'openVerify') {
                formData[item.label] = item.value === '1';
            } else {
                formData[item.label] = item.value;
            }
        });

        Object.assign(form, formData);
    }
};

const handleSave = async () => {
    const { code } = await saveVerifyInfos(form);
    if (code === 200) ElMessage.success("保存成功");
};

init();

defineExpose({ form, init });
</script>