<script lang="ts" setup>
import { ref, reactive, defineExpose, defineEmits } from 'vue'
import { ElMessage, formatter, type ComponentSize, type FormInstance, type FormRules } from 'element-plus'
import { leaveRecordApi, subLeaveApi, updateLeaveApi } from '@/api/login';
//格式化时间格式
import { format } from 'date-fns/format';
const leave_visible = ref<boolean>(false)

const emit = defineEmits(['search'])

//返回的数据
const detailData = ref<any>({})
const open = (val: any) => {
    detailData.value = val
    leave_visible.value = true;
    //回显数据
    ruleForm.leaveType = val.leaveType
    ruleForm.userPhone = val.userPhone
    ruleForm.monitorName = val.monitorName
    ruleForm.dormitory = val.dormitory
    ruleForm.destination = val.destination
    ruleForm.reason = val.reason
    ruleForm.isKnow = val.isKnow
    ruleForm.companionsPhone = val.companionsPhone
    ruleForm.motherPhone = val.motherPhone
    ruleForm.fatherPhone = val.fatherPhone
    ruleForm.travelMode = val.travelMode
    ruleForm.startTime = val.startTime
    ruleForm.endTime = val.endTime
    ruleFormRef.value.clearValidate()
}

const type = ref<string>('1')

//************表单数据******************/
//设置表单大小
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<any>()

const ruleForm = reactive<any>({
    //是否离郑
    leaveType: '0',
    //本人手机号
    userPhone: '',
    //班长姓名
    monitorName: '',
    //宿舍：
    dormitory: '',
    //出行方式
    destination: '',
    //请假原因
    reason: '',
    //父母是否知情
    isKnow: '1',
    //同行人电话
    companionsPhone: '',
    //母亲电话
    montherPhone: '',
    //父亲电话
    fatherPhone: '',
    //出行方式
    travelMode: '',
    //请假时间
    startTime: '',
    //返校时间
    endTime: ''

})
const rules = reactive<FormRules<any>>({
    leaveType: [
        { required: true, message: '请填写是否离郑', trigger: 'blur' },
    ],
    userPhone: [
        { required: true, message: '请填写手机号', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
    ],

    monitorName: [
        { required: false, message: '请填写班长姓名', trigger: 'blur' },
    ],
    dormitory: [
        { required: true, message: '请填写宿舍信息', trigger: 'blur' },
    ],
    destination: [
        { required: true, message: '请填写出行目的', trigger: 'blur' },
    ],
    reason: [
        { required: true, message: '请填写请假原因', trigger: 'blur' },
    ],
    isKnow: [
        { required: true, message: '请填写父母是否知情', trigger: 'blur' },
    ],

    companionsPhone: [
        { required: false, message: '请填写同行人电话', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
    ],

    motherPhone: [
        { required: true, message: '请填写母亲电话', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
    ],
    fatherPhone: [
        { required: true, message: '请填写父亲电话', trigger: 'blur' },
        { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
    ],
    travelMode: [
        { required: true, message: '请填写出行方式', trigger: 'blur' },
    ],
    startTime: [
        { required: true, message: '请填写请假时间', trigger: 'change' },
        {
            validator: function (rule, value, callback) {
                if (value !== '' && ruleForm.endTime !== '') {
                    let startTime = new Date(value).getTime();
                    let endTime = new Date(ruleForm.endTime).getTime()
                    //先判断都不为空


                    if (startTime >= endTime) {
                        callback(new Error('请假时间应小于返校时间'))
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }
            }, trigger: 'change'
        },

    ],
    endTime: [
        { required: true, message: '请填写返校时间', trigger: 'change' },
        {
            validator: function (rule, value, callback) {
                if (value !== '' && ruleForm.startTime !== '') {
                    let startTime = new Date(ruleForm.startTime).getTime();

                    let endTime = new Date(value).getTime()
                    if (endTime <= startTime) {
                        callback(new Error('返校时间应大于请假时间'))
                    } else {
                        callback()
                    }
                } else {
                    callback()
                }
            }, trigger: 'change'
        },
    ],
})
//提交表单
//按钮状态改变
const buttonStatus = ref<boolean>(false)
const submitForm = async (formEl: FormInstance | undefined) => {
    buttonStatus.value = true
    //设置单独校验的字段
    if (!formEl) {
        buttonStatus.value = false
        return
    }
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            console.log('submit!')
            //调用用户提交信息的代码
            subLeaveInfo()
        } else {
            buttonStatus.value = false
            console.log('error submit!', fields)
        }
    })
}

//时间格式化



//提交表单信息
const subLeaveInfo = async () => {
    //提交表单信息
    //组装该用户需要提交的信息
    let params = {}
    let tmpData = detailData.value
    //判断当前的状态是否离郑
    //1是不离郑
    if (ruleForm.leaveType == '0') {
        tmpData.userPhone = ruleForm.userPhone;
        tmpData.destination = ruleForm.destination;
        tmpData.dormitory = ruleForm.dormitory;
        tmpData.endTime = format(ruleForm.endTime, 'yyyy-MM-dd HH:mm:ss');
        tmpData.fatherPhone = ruleForm.fatherPhone;
        tmpData.isKnow = ruleForm.isKnow
        tmpData.leaveType = ruleForm.leaveType
        tmpData.motherPhone = ruleForm.motherPhone
        tmpData.reason = ruleForm.reason
        tmpData.startTime = format(ruleForm.startTime, 'yyyy-MM-dd HH:mm:ss')
        tmpData.travelMode = ruleForm.travelMode
        params = {
            ...tmpData
            // userPhone: ruleForm.userPhone, //本人手机号
            // destination: ruleForm.destination,//出行目的地
            // dormitory: ruleForm.dormitory,//宿舍
            // endTime: format(ruleForm.endTime, 'yyyy-MM-dd HH:mm:ss'),//返校时间
            // fatherPhone: ruleForm.fatherPhone,//父亲手机号
            // isKnow: ruleForm.isKnow,//父母是否知情
            // leaveType: ruleForm.leaveType,//请假类型--离郑不离郑
            // // monitorName: ruleForm.monitorName,//班长名字
            // motherPhone: ruleForm.motherPhone,//母亲电话
            // reason: ruleForm.reason,//请假原因
            // startTime: format(ruleForm.startTime, 'yyyy-MM-dd HH:mm:ss'),//请假开始时间
            // travelMode: ruleForm.travelMode,//出行方式
            // companionsPhone: ruleForm.companionsPhone, //同行人电话

        }
    } else {
        tmpData.userPhone = ruleForm.userPhone;
        tmpData.destination = ruleForm.destination;
        tmpData.dormitory = ruleForm.dormitory;
        tmpData.endTime = format(ruleForm.endTime, 'yyyy-MM-dd HH:mm:ss');
        tmpData.fatherPhone = ruleForm.fatherPhone;
        tmpData.isKnow = ruleForm.isKnow
        tmpData.leaveType = ruleForm.leaveType
        tmpData.monitorName = ruleForm.monitorName
        tmpData.motherPhone = ruleForm.motherPhone
        tmpData.companionsPhone = ruleForm.companionsPhone
        tmpData.reason = ruleForm.reason
        tmpData.startTime = format(ruleForm.startTime, 'yyyy-MM-dd HH:mm:ss')
        tmpData.travelMode = ruleForm.travelMode
        params = {
            ...tmpData
            // userPhone: ruleForm.userPhone, //本人手机号
            // destination: ruleForm.destination,//出行目的地
            // dormitory: ruleForm.dormitory,//宿舍
            // endTime: format(ruleForm.endTime, 'yyyy-MM-dd HH:mm:ss'),//返校时间
            // fatherPhone: ruleForm.fatherPhone,//父亲手机号
            // isKnow: ruleForm.isKnow,//父母是否知情
            // leaveType: ruleForm.leaveType,//请假类型--离郑不离郑
            // monitorName: ruleForm.monitorName,//班长名字
            // motherPhone: ruleForm.motherPhone,//母亲电话
            // reason: ruleForm.reason,//请假原因
            // startTime: format(ruleForm.startTime, 'yyyy-MM-dd HH:mm:ss'),//请假开始时间
            // travelMode: ruleForm.travelMode,//出行方式
            // companionsPhone: ruleForm.companionsPhone, //同行人电话

        }

    }

    let res: any = await updateLeaveApi(params)
    console.log(res)
    //跳转测试记录
    if (res.code == 200) {
        //结束了
        buttonStatus.value = false

        ElMessage({
            type: 'success',
            message: '修改成功'
        })
        //跳转到请假记录
        //要关闭自己
        leave_visible.value = false
        emit('search')
        //开始查询请假记录的字段
        //

    } else {
        buttonStatus.value = false

    }
}

//清除表单的校验
const resetData = (formEl: any) => {
    // if (!formEl) return
    ruleForm.leaveType = ''
    ruleForm.userPhone = ''
    ruleForm.monitorName = ''
    ruleForm.dormitory = ''
    ruleForm.destination = ''
    ruleForm.reason = ''
    ruleForm.isKnow = ''
    ruleForm.companionsPhone = ''
    ruleForm.motherPhone = ''
    ruleForm.fatherPhone = ''
    ruleForm.travelMode = ''
    ruleForm.startTime = ''
    ruleForm.endTime = ''
    formEl.clearValidate()

}
//是否离郑状态改变 
const leaveStatus = (val: string) => {
    // resetData(ruleFormRef)


    if (val == '1') {
        rules.monitorName = [
            { required: true, message: '请填写班长姓名', trigger: 'blur' },
        ]
        rules.companionsPhone = [
            { required: true, message: '请填写同行人电话', trigger: 'blur' },
            { pattern: /^1[3456789]\d{9}$/, message: '手机号码格式不正确', trigger: 'blur' }
        ]
        //这样回触发校验
        // rules!.monitorName[0].required = true;
        // rules!.companionsPhone[0].required = true
    }
    ruleFormRef.value.clearValidate()
}






defineExpose({ open })


</script>

<template>

    <el-dialog v-model="leave_visible" :show-close="true" width="80%" height="1000px" top="5vh"
        style="border-radius: 40px;  ">
        <template #header="{ close, titleId, titleClass }">
            <div class="leave_title">请假编辑</div>
            <div v-show="type == '1'" class="leave">
                <el-form ref="ruleFormRef" style="display: flex;flex-wrap: wrap;" :model="ruleForm" :rules="rules"
                    :validate-on-rule-change=false label-width="auto" class="demo-ruleForm" :size="formSize"
                    status-icon>
                    <el-form-item label="是否离郑" prop="leaveType">
                        <el-radio-group v-model="ruleForm.leaveType" @change="leaveStatus">
                            <el-radio value="0">不离郑</el-radio>
                            <el-radio value="1">离郑</el-radio>
                        </el-radio-group>
                    </el-form-item>

                    <el-form-item label="本人手机号码" prop="userPhone">
                        <el-input v-model="ruleForm.userPhone" placeholder="请输入本人手机号码" />
                    </el-form-item>

                    <el-form-item label="班长姓名" prop="monitorName" v-if="ruleForm.leaveType == '1'">
                        <el-input v-model="ruleForm.monitorName" placeholder="请输入班长姓名" />
                    </el-form-item>

                    <el-form-item label="宿舍" prop="dormitory">
                        <el-input v-model="ruleForm.dormitory" placeholder="例如松15-XXX" />
                    </el-form-item>
                    <el-form-item label="请假原因" prop="reason">
                        <el-input v-model="ruleForm.reason" type="textarea" placeholder="一定要写清楚，例如拔牙" />
                    </el-form-item>
                    <el-form-item label="出行目的地" prop="destination">
                        <el-input v-model="ruleForm.destination" type="textarea"
                            placeholder="一定要写清楚，例如郑州市中原区高新区郑州中心医院" />
                    </el-form-item>

                    <el-form-item label="父母是否知情" prop="isKnow">

                        <el-radio-group v-model="ruleForm.isKnow">
                            <el-radio value="1">知情</el-radio>
                            <el-radio value="0">不知情</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="同行人电话" prop="companionsPhone" v-if="ruleForm.leaveType == '1'">
                        <el-input v-model="ruleForm.companionsPhone" placeholder="请输入同行人电话" />
                    </el-form-item>

                    <el-form-item label="母亲电话" prop="motherPhone">
                        <el-input v-model="ruleForm.motherPhone" placeholder="请输入母亲电话" />
                    </el-form-item>
                    <el-form-item label="父亲电话" prop="fatherPhone">
                        <el-input v-model="ruleForm.fatherPhone" placeholder="请输入父亲电话" />
                    </el-form-item>
                    <el-form-item label="出行方式" prop="travelMode">
                        <el-input v-model="ruleForm.travelMode" placeholder="请输入出行方式" />
                    </el-form-item>
                    <el-form-item label="请假时间" prop="startTime">
                        <el-date-picker v-model="ruleForm.startTime" type="datetime" placeholder="请输入请假时间"
                            style="width: 100%;" />
                    </el-form-item>
                    <el-form-item label="返校时间" prop="endTime">
                        <el-date-picker v-model="ruleForm.endTime" type="datetime" placeholder="请输入返校时间"
                            style="width: 100%;" />
                    </el-form-item>

                </el-form>
                <div class="reset_sub">
                    <el-button @click="resetData(ruleFormRef)">重置</el-button>
                    <el-button type="success" @click="submitForm(ruleFormRef)" :disabled="buttonStatus">提交</el-button>
                </div>
                <div class="leave_tip"> 温馨提示：（天气寒冷，晚上行人少，为保证大家安全，返校时间尽量在21:00之前）
                </div>
            </div>
        </template>
    </el-dialog>

</template>

<style lang="scss" scoped>
.leave {
    :deep(.el-form-item) {
        width: 50% !important;
        margin-top: 10px;
    }

    :deep(.el-input__wrapper) {
        align-items: center;
        background-color: #F7F7F7 !important;
        border-radius: 40px !important;

        // border: none;
        // outline: none !important;
        box-shadow: none;
    }

    :deep(.el-form-item__content) {
        align-items: flex-start !important;
    }
}



.reset_sub {
    display: flex;
    justify-content: space-around;
}

.leave_tip {
    margin-top: 20px;
    color: #5c5c5c;
    text-align: center;
    font-size: 12px;
}




.leave_title {
    text-align: center;
    color: #333333;
    font-weight: 700;
    font-size: 16px;
    margin-bottom: 20px;

}
</style>