<script setup lang="ts">
import {ref, reactive} from 'vue';
import {MessagePlugin, FormProps, FormInstanceFunctions, InputProps, CustomValidateObj} from 'tdesign-vue-next';
import {useUserStore} from "@/store";

function passwordValidator(val: any): CustomValidateObj {
    if (val as string !== formData!.password)
        return {result: false, message: '两次密码不一致', type: 'error'};
    return {result: true, message: '', type: 'success'};
}

const FORM_RULES: FormProps['rules'] = {
    code: [
        {
            required: true,
            message: '账号必填',
        }
    ],
    password: [
        {
            required: true,
            message: '密码必填',
        }
    ],
    anotherPassword: [
        {
            required: true,
            message: '密码必填',
        },
        {
            validator: passwordValidator
        }
    ],
    department: [
        {
            required: true,
            message: '单位必填',
        }
    ],
    name: [
        {
            required: true,
            message: '名字必填',
        }
    ]
};
const formData: FormProps['data'] = reactive({
    code: '',
    password: '',
    anotherPassword: '',
    department: '',
    name: '',
    identity: []
});
const form = ref<FormInstanceFunctions>(null!);
const userStore = useUserStore();
const onSubmit: FormProps['onSubmit'] = async ({validateResult, firstError}) => {
    if (validateResult === true) {
        await register();
    } else {
        console.log('Validate Errors: ', firstError, validateResult);
        await MessagePlugin.warning(firstError!);
    }
};

async function register() {
    let identity = 0;
    formData!.identity.forEach((value:string) => {
        switch (value) {
            case '借用人':
                identity |= 1;
                break;
            case '购买者':
                identity |= 2;
                break;
            case '管理员':
                identity |= 4;
                break;
            case '批准者':
                identity |= 8;
                break;
        }
    });
    console.log(identity);
    userStore.user = {
        Id: "",
        Code: formData!.code,
        Password: formData!.password,
        Name: formData!.name,
        Department: formData!.department,
        Identity: identity,
        ApprovalStatus: 0,
        ApproverId: "",
        Approver: undefined,
        MiscellaneousConfiguration: ""
    }
    try {
        await userStore.register();
        MessagePlugin.info('已提交审核');
    } catch (e: any) {
        console.log(e);
        MessagePlugin.error(e.message);
        return;
    }
}

// 禁用 Input 组件，按下 Enter 键时，触发 submit 事件
const onEnter: InputProps['onEnter'] = (_, {e}) => {
    e.preventDefault();
};
</script>


<template>
    <t-form :class="{form:true}" ref="form" :rules="FORM_RULES" :data="formData" :colon="true" :required-mark=false
            @submit="onSubmit">
        <t-form-item name="code">
            <t-input v-model="formData.code" size='large' placeholder="请输入编号" @enter="onEnter"/>
        </t-form-item>
        <t-form-item name="password">
            <t-input v-model="formData.password" size='large' placeholder="请输入密码" @enter="onEnter"
                     type="password"/>
        </t-form-item>
        <t-form-item name="anotherPassword">
            <t-input v-model="formData.anotherPassword" size='large' placeholder="请再次输入密码" @enter="onEnter"
                     type="password"/>
        </t-form-item>
        <t-form-item name="department">
            <t-input v-model="formData.department" size='large' placeholder="请输入部门" @enter="onEnter"/>
        </t-form-item>
        <t-form-item name="name">
            <t-input v-model="formData.name" size='large' placeholder="请输入姓名" @enter="onEnter"/>
        </t-form-item>
        <t-form-item>
            <t-checkbox-group v-model="formData.identity" :options="['借用人','购买者','管理员','批准者']">
                <t-checkbox >1</t-checkbox>
                <t-checkbox >管理员</t-checkbox>
            </t-checkbox-group>
        </t-form-item>
        <t-form-item>
            <t-space size="small">
                <t-button theme="primary" type="submit" size="large">注册</t-button>
            </t-space>
        </t-form-item>
    </t-form>
</template>


<style scoped>
.form {
    margin-right: 10vh;
}
</style>