<template>
    <div class="main-container">
        <div class="detail-head">
            <div class="left" @click="back()">
                <span class="iconfont iconxiangzuojiantou !text-xs"></span>
                <span class="ml-[1px]">{{t('returnToPreviousPage')}}</span>
            </div>
            <span class="adorn">|</span>
            <span class="right">{{ pageName }}</span>
        </div>
        <el-card class="box-card !border-none" shadow="never">
            <el-form :model="formData" label-width="90px" ref="formRef" :rules="formRules" class="page-form">
                <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="item['id']"
                        />
                    </el-select>
                </el-form-item>
                
                <el-form-item :label="t('title')" prop="title">
                    <el-input v-model="formData.title" clearable :placeholder="t('titlePlaceholder')" class="input-width" />
                </el-form-item>
                
                <el-form-item :label="t('content')" >
                    <editor v-model="formData.content" />
                </el-form-item>
                <el-form-item :label="t('fileData')">
                    <upload-file v-model="formData.file_data" />
                </el-form-item>
                
                <el-form-item :label="t('startDate')"  class="input-width">
                    <el-date-picker 
                        class="flex-1 !flex"
                        v-model="formData.start_date"
                        clearable
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        :placeholder="t('startDatePlaceholder')">
                    </el-date-picker>
                </el-form-item>
                <el-form-item :label="t('endDate')"  class="input-width">
                    <el-date-picker 
                        class="flex-1 !flex"
                        v-model="formData.end_date"
                        clearable
                        type="datetime"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        :placeholder="t('endDatePlaceholder')">
                    </el-date-picker>
                </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>
        </el-card>
         <div class="fixed-footer-wrap">
            <div class="fixed-footer">
                <el-button type="primary" @click="onSave(formRef)">{{ t('save') }}</el-button>
                <el-button @click="back()">{{ t('cancel') }}</el-button>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch } from 'vue'
import { t } from '@/lang'
import { useDictionary } from '@/app/api/dict'
import type { FormInstance } from 'element-plus'
import { getContractsInfo,addContracts,editContracts, getWithStudentsList } from '@/addon/zhjw/api/contracts';
import { useRoute } from 'vue-router'

const route = useRoute()
const id:number = parseInt(route.query.id);
const loading = ref(false)
const pageName = route.meta.title



/**
 * 表单数据
 */
const initialFormData = {
    id: 0,
    student_id: '',
    title: '',
    content: '',
    file_data: '',
    start_date: '',
    end_date: '',
    status: '',

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

const setFormData = async (id:number = 0) => {
    Object.assign(formData, initialFormData)
    const data = await (await getContractsInfo(id)).data
    Object.keys(formData).forEach((key: string) => {
        if (data[key] != undefined) formData[key] = data[key]
    })
}
if(id) setFormData(id);

const formRef = ref<FormInstance>()
// 选中数据
const selectData = ref<any[]>([])

// 字典数据
    let statusList = ref([])
    const statusDictList = async () => {
    statusList.value = await (await useDictionary('zhjw_contracts_status')).data.dictionary
    }
    statusDictList();
    watch(() => statusList.value, () => { formData.status = statusList.value[0].value })
    let is_deletedList = ref([])
    const is_deletedDictList = async () => {
    is_deletedList.value = await (await useDictionary('is_radio')).data.dictionary
    }
    is_deletedDictList();
    watch(() => is_deletedList.value, () => { formData.is_deleted = is_deletedList.value[0].value })


    
    const studentIdList = ref([] as any[])
    const setStudentIdList = async () => {
    studentIdList.value = await (await getWithStudentsList({})).data
    }
    setStudentIdList()
// 表单验证规则
const formRules = computed(() => {
    return {
    student_id: [
        { required: true, message: t('studentIdPlaceholder'), trigger: 'blur' },
        
    ]
,
    title: [
        { required: true, message: t('titlePlaceholder'), trigger: 'blur' },
        
    ]
,
    content: [
        { required: true, message: t('contentPlaceholder'), trigger: 'blur' },
        
    ]
,
    file_data: [
        { required: true, message: t('fileDataPlaceholder'), trigger: 'blur' },
        
    ]
,
    start_date: [
        { required: true, message: t('startDatePlaceholder'), trigger: 'blur' },
        
    ]
,
    end_date: [
        { required: true, message: t('endDatePlaceholder'), trigger: 'blur' },
        
    ]
,
    status: [
        { required: true, message: t('statusPlaceholder'), trigger: 'blur' },
        
    ]
,
    }
})

const onSave = async (formEl: FormInstance | undefined) => {
    if (loading.value || !formEl) return
    await formEl.validate(async (valid) => {
       if (valid) {
           loading.value = true
           let data = formData

           const save = id ? editContracts : addContracts
           save(data).then(res => {
               loading.value = false
               history.back()
           }).catch(err => {
               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()
    }
}
const back = () => {
    history.back()
}
</script>

<style lang="scss" scoped></style>
