<template>
    <el-dialog v-model="showDialog" :title="formData.id ? t('updateAssignment') : t('addAssignment')" 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('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('courseId')" prop="course_id">
                    <el-select class="input-width" v-model="formData.course_id" clearable :placeholder="t('courseIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in courseIdList"
                            :key="index"
                            :label="item['course_name']"
                            :value="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('personnelId')" prop="personnel_id">
                    <el-select class="input-width" v-model="formData.personnel_id" clearable :placeholder="t('personnelIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in personnelIdList"
                            :key="index"
                            :label="item['name']"
                            :value="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('studentId')" prop="student_id">
                    <el-select class="input-width" v-model="formData.student_id" clearable :placeholder="t('studentIdPlaceholder')">
                       <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in studentIdList"
                            :key="index"
                            :label="item['name']"
                            :value="Number(item['id'])"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('description')" >
                    <el-input v-model="formData.description" type="textarea" rows="4" clearable :placeholder="t('descriptionPlaceholder')" class="input-width"/>
                </el-form-item>
<!--                <el-form-item :label="t('contentType')" prop="content_type">
                    <el-select class="input-width"  v-model="formData.content_type" clearable :placeholder="t('contentTypePlaceholder')">
                    <el-option label="请选择" value=""></el-option>
                        <el-option
                            v-for="(item, index) in content_typeList"
                            :key="index"
                            :label="item.name"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('contentText')" >
                    <el-input v-model="formData.content_text" clearable :placeholder="t('contentTextPlaceholder')" class="input-width" />
                </el-form-item> -->
                
<!--                <el-form-item :label="t('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="item.value"
                        />
                    </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 { addAssignment, editAssignment, getAssignmentInfo, getWithClassGradeList, getWithCourseList, getWithPersonnelList, getWithStudentList } from '@/app/api/assignment'

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

/**
 * 表单数据
 */
const initialFormData = {
    id: '',
    class_id: '',
    course_id: '',
    personnel_id: '',
    student_id: '',
    description: '',
    content_type: '',
    content_text: '',
    status: '',

}
const formData: Record<string, any> = reactive({ ...initialFormData })

const formRef = ref<FormInstance>()

// 表单验证规则
const formRules = computed(() => {
    return {
    class_id: [
        { required: true, message: t('classIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    course_id: [
        { required: true, message: t('courseIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    personnel_id: [
        { required: true, message: t('personnelIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    student_id: [
        { required: true, message: t('studentIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    description: [
        { required: true, message: t('descriptionPlaceholder'), trigger: 'blur' },
        
    ]
,
    content_type: [
        { required: true, message: t('contentTypePlaceholder'), trigger: 'blur' },
        
    ]
,
    content_text: [
        { required: true, message: t('contentTextPlaceholder'), trigger: 'blur' },
        
    ]
,
    status: [
        { required: true, message: t('statusPlaceholder'), trigger: 'blur' },
        
    ]
,
    }
})

const emit = defineEmits(['complete'])

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

    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 content_typeList = ref([])
    const content_typeDictList = async () => {
    content_typeList.value = await (await useDictionary('content_type')).data.dictionary
    }
    content_typeDictList();
    watch(() => content_typeList.value, () => { formData.content_type = content_typeList.value[0].value })
    let statusList = ref([])
    const statusDictList = async () => {
    statusList.value = await (await useDictionary('assignment_status')).data.dictionary
    }
    statusDictList();
    watch(() => statusList.value, () => { formData.status = statusList.value[0].value })


    
    const classIdList = ref([] as any[])
    const setClassIdList = async () => {
    classIdList.value = await (await getWithClassGradeList({})).data
    }
    setClassIdList()
    const courseIdList = ref([] as any[])
    const setCourseIdList = async () => {
    courseIdList.value = await (await getWithCourseList({})).data
    }
    setCourseIdList()
    const personnelIdList = ref([] as any[])
    const setPersonnelIdList = async () => {
    personnelIdList.value = await (await getWithPersonnelList({})).data
    }
    setPersonnelIdList()
    const studentIdList = ref([] as any[])
    const setStudentIdList = async () => {
    studentIdList.value = await (await getWithStudentList({})).data
    }
    setStudentIdList()
const setFormData = async (row: any = null) => {
    Object.assign(formData, initialFormData)
    loading.value = true
    if(row){
        const data = await (await getAssignmentInfo(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>
