<template>
    <div>
        <div v-if="loading" class="row">
            <div class="col-12 tx-semibold text-center text-default">
                <span class="spinner-border spinner-border-sm"></span>
            </div>
        </div>
        <Form v-if="!loading" @submit="onSubmit" :validation-schema="schema" v-slot="{ errors, isSubmitting }" class="row">

            <div class="row">
                <div class="col-12">
                    <div class="form-group mb-3">
                        <label>Mật khẩu</label>
                        <Field v-model="setPasswordModel.Password" name="Password" type="password" placeholder="mật khẩu"
                            class="form-control" :class="{ 'is-invalid': errors.Password }" />
                        <div class="invalid-feedback">{{ errors.Password }}</div>
                    </div>
                </div>

            </div>


            <div class="col-12 ">
                <div class="d-flex flex-row-reverse">
                    <button @click="cancel" type="button" class="btn btn-main-default mg-l-15">
                        Bỏ qua
                    </button>
                    <button type="submit" class="btn btn-main-primary" :disabled="isSubmitting">
                        <span v-show="isSubmitting" class="spinner-border spinner-border-sm"></span>
                        Xác nhận
                    </button>
                </div>
            </div>
        </Form>
    </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import userService from "@/services/userService";
const emit = defineEmits(['cancel']);

import { Form, Field } from 'vee-validate';
import * as Yup from 'yup';


import { useToast } from "vue-toastification";
const toast = useToast();
const loading = ref(false);


const props = defineProps({
    id: Number
});

let setPasswordModel = reactive({
    Id: 0,
    Password: ''
});

const schema = Yup.object().shape({
    Password: Yup.string().required('Mật khẩu không để trống').matches(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).{6,30}$/, "Mật khẩu có độ dài từ 6-30 ký tự, có ít nhất 1 chữ cái thường, 1 chữ cái hoa và 1 chữ số")

});


async function onSubmit() {
    var setPassResult = null;
    setPassResult = await userService.setPassword(setPasswordModel);
    cancel();
    if (setPassResult != null && setPassResult.Result === 1) {
        toast.success('Thành công!');
    } else {
        if (setPassResult.ErrorList != null && setPassResult.ErrorList.length > 0) {
            toast.error('Thất bại: ' + setPassResult.ErrorList.join("\n"));
        } else {
            toast.error('Thất bại: ' + setPassResult.Message);
        }
    }

}

function cancel() {
    emit('cancel');
}



onMounted(() => {
    setPasswordModel.Id = props.id;
})


</script>