// 所有用户注册相关model,rules集中管理
// 因为不同的功能场景有时候需要的字段有差异，这里分割成了多个版块，但使用模式均保持一致
import {computed, ref} from 'vue'
import {injectLocal, provideLocal} from "@vueuse/core";
import {mobile} from "@/uni_modules/uv-ui-tools/libs/function/test";
import _ from "lodash";

const key = Symbol('FORM_DATA')

export const useProvideFormData = function (pureModel, overrideRules = {}) {
    const transform = (v) => v + '' // 有时纯数值检验需要转化一下才能起效
    const model = ref(pureModel)
    const allRules = ref({
        mobile: [
            {required: true, message: '请输入手机号码', trigger: 'error-change'},
            {
                validator: (r, v, cb) => {
                    if (mobile(v)) cb()
                    else cb(r.message)
                },
                message: '手机号码格式不正确',
                trigger: 'error-change'
            }
        ],
        smsCode: [{required: true, message: '请输入验证码', trigger: 'error-change'}],
        username: [{required: true, message: '请输入手机号/卡号', trigger: 'error-change'}],
        password: [{required: true, message: '请输入密码', trigger: 'error-change'}],
        oldPassword: [{required: true, message: '请输入旧密码', trigger: 'error-change'}],
        newPassword: [
            {required: true, message: '请输入新密码', trigger: 'error-change'},
            {
                min: 6,
                max: 20,
                message: '新密码长度在6-20个字符之间',
                trigger: 'error-change'
            }
        ],
        newPwdRepeat: [
            {required: true, message: '请输入确认密码', trigger: 'error-change'},
            {
                validator: (r, v, cb) => {
                    const valid = v == model.value.newPassword
                    const params = valid ? undefined : new Error(r.message)
                    cb(params)
                },
                message: '确认密码与新密码不一致',
                trigger: 'error-change'
            }
        ],
        nickName: [{required: true, message: '请输入学生姓名', trigger: 'error-change'}],
        sex: [{required: true, message: '请选择学生性别', trigger: 'error-change'}],
        location: [{required: true, message: '请选择所在省份', trigger: 'error-change'}],
        examType: [{required: true, message: '请选择考生类别', trigger: 'error-change'}],
        examMajor: [{required: true, message: '请选择专业类别', trigger: 'error-change'}],
        schoolId: [{required: true, message: '请选择学校', transform, trigger: 'error-change'}],
        customSchoolName: [{required: true, message: '请输入学校名称', trigger: 'error-change'}],
        customClassName: [{required: true, message: '请输入班级名称', trigger: 'error-change'}],
        ...overrideRules
    })
    const rules = computed(() => _.pick(allRules.value, _.keys(model.value)))
    const provide = [model, rules]
    provideLocal(key, provide)
    return provide
}

export const useInjectFormData = function () {
    return injectLocal(key)
}