<template>
    <el-dialog v-model="showDialog" :title="formData.id ? t('updateStudent') : t('addStudent')" width="50%" class="diy-dialog-wrap" :destroy-on-close="true">
        <el-form :model="formData" label-width="120px" ref="formRef" :rules="formRules" class="page-form" v-loading="loading">
                <el-form-item :label="t('userId')" prop="user_id">
                    <el-select class="input-width" v-model="formData.user_id" clearable :placeholder="t('userIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in userIdList"
                            :key="index"
                            :label="item['name']"
                            :value="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('campusId')" >
                    <el-select class="input-width" v-model="formData.campus_id" clearable :placeholder="t('campusIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in campusIdList"
                            :key="index"
                            :label="item['campus_name']"
                            :value="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('classId')" prop="class_id">
                    <el-select class="input-width" v-model="formData.class_id" clearable :placeholder="t('classIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in classIdList"
                            :key="index"
                            :label="item['class_name']"
                            :value="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('name')" prop="name">
                    <el-input v-model="formData.name" clearable :placeholder="t('namePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('gender')" prop="gender">
                    <el-select class="input-width"  v-model="formData.gender" clearable :placeholder="t('genderPlaceholder')">
                    <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in genderList"
                            :key="index"
                            :label="item.name"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('age')" >
                    <el-input v-model="formData.age" clearable :placeholder="t('agePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('birthday')"  class="input-width">
                    <el-date-picker 
                        class="flex-1 !flex"
                        v-model="formData.birthday"
                        clearable
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        :placeholder="t('birthdayPlaceholder')">
                    </el-date-picker>
                </el-form-item>
                <el-form-item :label="t('emergencyContact')" >
                    <el-input v-model="formData.emergency_contact" clearable :placeholder="t('emergencyContactPlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('contactPhone')" >
                    <el-input v-model="formData.contact_phone" clearable :placeholder="t('contactPhonePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('note')" >
                    <el-input v-model="formData.note" clearable :placeholder="t('notePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('status')" prop="status">
                    <el-select class="input-width"  v-model="formData.status" clearable :placeholder="t('statusPlaceholder')">
                    <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in statusList"
                            :key="index"
                            :label="item.name"
                            :value="Number(item.value)"
                        />
                    </el-select>
                </el-form-item>
				
				<el-form-item label="学员标签">
				  <el-select
				    v-model="formData.member_label"
				    multiple
				    collapse-tags
				    placeholder="请选择学员标签"
				    class="input-width"
				  >
				    <el-option
				      :label="item['label_name']"
				      :value="item['label_id']"
				      v-for="(item, index) in labelSelectData"
				      :key="index"
				    />
				  </el-select>
				</el-form-item>
                

        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="showDialog = false">{{ t('cancel') }}</el-button>
                <el-button type="primary" :loading="loading" @click="confirm(formRef)">{{
                    t('confirm')
                }}</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { useDictionary } from '@/app/api/dict'
import { t } from '@/lang'
import type { FormInstance } from 'element-plus'
import { addStudent, editStudent, getStudentInfo, getWithCustomerResourcesList, getWithCampusList, getWithClassGradeList,getMemberLabelAll } from '@/app/api/student'

let showDialog = ref(false)
const loading = ref(false)

/**
 * 表单数据
 */
const initialFormData = {
    id: '',
    user_id: '',
    campus_id: '',
    class_id: '',
    name: '',
    gender: '',
    age: '',
    birthday: '',
    emergency_contact: '',
    contact_phone: '',
    note: '',
    status: '',
	member_label:''
}
const formData: Record<string, any> = reactive({ ...initialFormData })

const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = computed(() => {
    return {
    user_id: [
        { required: true, message: t('userIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    campus_id: [
        { required: true, message: t('campusIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    class_id: [
        { required: true, message: t('classIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    name: [
        { required: true, message: t('namePlaceholder'), trigger: 'blur' },
        
    ]
,
    gender: [
        { required: true, message: t('genderPlaceholder'), trigger: 'blur' },
        
    ]
,
    age: [
        { required: true, message: t('agePlaceholder'), trigger: 'blur' },
        
    ]
,
    birthday: [
        { required: true, message: t('birthdayPlaceholder'), trigger: 'blur' },
        
    ]
,
    emergency_contact: [
        { required: true, message: t('emergencyContactPlaceholder'), trigger: 'blur' },
        
    ]
,
    contact_phone: [
        { required: true, message: t('contactPhonePlaceholder'), trigger: 'blur' },
        
    ]
,
    note: [
        { required: true, message: t('notePlaceholder'), trigger: 'blur' },
        
    ]
,
    status: [
        { required: true, message: t('statusPlaceholder'), trigger: 'blur' },
        
    ]
,
    }
})

const emit = defineEmits(['complete'])


const labelSelectData: any = ref(null)
// 获取全部标签
const getMemberLabelAllFn = async () => {
  labelSelectData.value = await (await getMemberLabelAll()).data
}
getMemberLabelAllFn()

/**
 * 确认
 * @param formEl
 */
const confirm = async (formEl: FormInstance | undefined) => {
    if (loading.value || !formEl) return
    let save = formData.id ? editStudent : addStudent

    await formEl.validate(async (valid) => {
        if (valid) {
            loading.value = true

            let data = formData

            save(data).then(res => {
                loading.value = false
                showDialog.value = false
                emit('complete')
            }).catch(err => {
                loading.value = false
            })
        }
    })
}

// 获取字典数据
    let genderList = ref([])
    const genderDictList = async () => {
    genderList.value = await (await useDictionary('gender')).data.dictionary
    }
    genderDictList();
    watch(() => genderList.value, () => { formData.gender = genderList.value[0].value })
    let statusList = ref([])
    const statusDictList = async () => {
    statusList.value = await (await useDictionary('xy_status')).data.dictionary
    }
    statusDictList();
    watch(() => statusList.value, () => { formData.status = statusList.value[0].value })


    
    const userIdList = ref([] as any[])
    const setUserIdList = async () => {
    userIdList.value = await (await getWithCustomerResourcesList({})).data
    }
    setUserIdList()
    const campusIdList = ref([] as any[])
    const setCampusIdList = async () => {
    campusIdList.value = await (await getWithCampusList({})).data
    }
    setCampusIdList()
    const classIdList = ref([] as any[])
    const setClassIdList = async () => {
    classIdList.value = await (await getWithClassGradeList({})).data
    }
    setClassIdList()
const setFormData = async (row: any = null) => {
    Object.assign(formData, initialFormData)
    loading.value = true
    if(row){
        const data = await (await getStudentInfo(row.id)).data
        if (data) Object.keys(formData).forEach((key: string) => {
            if (data[key] != undefined) formData[key] = data[key]
        })
    }
    loading.value = false
}

// 验证手机号格式
const mobileVerify = (rule: any, value: any, callback: any) => {
    if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error(t('generateMobile')))
    } else {
        callback()
    }
}

// 验证身份证号
const idCardVerify = (rule: any, value: any, callback: any) => {
    if (value && !/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/.test(value)) {
        callback(new Error(t('generateIdCard')))
    } else {
        callback()
    }
}

// 验证邮箱号
const emailVerify = (rule: any, value: any, callback: any) => {
    if (value && !/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/.test(value)) {
        callback(new Error(t('generateEmail')))
    } else {
        callback()
    }
}

// 验证请输入整数
const numberVerify = (rule: any, value: any, callback: any) => {
    if (!Number.isInteger(value)) {
        callback(new Error(t('generateNumber')))
    } else {
        callback()
    }
}

defineExpose({
    showDialog,
    setFormData
})
</script>

<style lang="scss" scoped></style>
<style lang="scss">
.diy-dialog-wrap .el-form-item__label{
    height: auto  !important;
}
</style>
