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

const leave_visible = ref<boolean>(false)



const open = () => {
    leave_visible.value = true;
}

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

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

interface RuleForm {
    leaveType: string
    userPhone: string
    monitorName: string
    dormitory: string
    destination: string
    reason: string
    isKnow: string
    companionsPhone: string
    motherPhone: string
    fatherPhone: string
    travelMode: string

    startTime: string
    endTime: string
}

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

})
const rules = reactive<FormRules<RuleForm>>({
    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!')
            //调用用户提交信息的代码
            //判断返校时间是否大于请假时间
            let leaveTime = new Date()


            subLeaveInfo()
        } else {
            buttonStatus.value = false
            console.log('error submit!', fields)
        }
    })
}

//时间格式化



//提交表单信息
const subLeaveInfo = async () => {
    //提交表单信息
    //组装该用户需要提交的信息
    let params = {}
    //判断当前的状态是否离郑
    //1是不离郑
    if (ruleForm.leaveType == '0') {
        params = {
            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 {
        params = {
            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 subLeaveApi(params)
    console.log(res)
    //跳转测试记录
    if (res.code == 200) {
        //结束了
        buttonStatus.value = false

        ElMessage({
            type: 'success',
            message: '提交成功'
        })
        //跳转到请假记录
        type.value = '2'
        leaveRecord()
        //开始查询请假记录的字段
        //

    } else {
        buttonStatus.value = false

    }
}

//清除表单的校验
const resetData = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()

}
//是否离郑状态改变 
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()
}

//类型方法
const typeFun = (val: string) => {
    if (val == '1') {
        //清空表单
        ruleFormRef.value.clearValidate()
        ruleFormRef.value.resetFields()
    } else {
        //查询记录列表
        leaveRecord()
    }
}
//请假记录列表
let tableData = ref<any>([])
//第几页
const pageNum = ref<number>(1)
//每页多少条
const pageSize = ref<number>(10)

//总条数
const total = ref<number>(0)
const leaveRecord = async () => {
    //leaveRecordApi
    let params = {
        pageNum: pageNum.value,
        pageSize: pageSize.value
    }
    let res: any = await leaveRecordApi(params)
    tableData.value = res.data.content
    total.value = res.data.totalElements
}
//格式化是否离郑

const leaveTypeFormatter = (val: any) => {
    if (val.leaveType == '0') {
        return '不离郑'
    } else {
        return '离郑'
    }
}
//格式化父母是否知情
const isKnowFormatter = (val: any) => {
    if (val.isKnow == '1') {
        return '知情'
    } else {
        return '不知情'
    }
}

//格式审核状态状态
const auditStatusFormatter = (val: any) => {
    if (val.auditStatus == '0') {
        return '待审批'
    } else {
        return '已审批'
    }
}

//审核结果
const auditResultFormatter = (val: any) => {
    if (val.auditResult == null) {
        return ''
    } else {
        if (val.auditResult == '0') {
            return '驳回'
        } else {
            return '通过'
        }
    }

}

//分页显示
const handleCurrentChange = (val: number) => {
    pageNum.value = val
    leaveRecord()
}

//需要重新编辑操作
const editFun = (val: any) => {

    editFlag.value.open(val)
}
const listFun = () => {
    //刷新列表
    leaveRecord()
}
defineExpose({ open })


</script>

<template>

    <el-dialog v-model="leave_visible" :show-close="true" width="80%" top="5vh" style="border-radius: 40px;  ">
        <template #header="{ close, titleId, titleClass }">
            <div class="leave_title">请假</div>
            <el-radio-group v-model="type" size="large" @change="typeFun">
                <el-radio-button label="我要请假" value="1" />
                <el-radio-button label="请假记录" value="2" />
            </el-radio-group>
            <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>
            <div v-show="type == '2'">
                <el-table :data="tableData" style="width: 100%;height: 60vh;"
                    :header-cell-style="{ background: '#F8F8F8', color: '#606266' }">
                    <el-table-column fixed prop="leaveType" label="是否离郑" width="" :formatter="leaveTypeFormatter" />
                    <el-table-column prop="userPhone" label="本人手机号码" width="" />
                    <el-table-column prop="monitorName" label="班长姓名" width="" />
                    <el-table-column prop="dormitory" label="宿舍" width="" />
                    <el-table-column prop="reason" label="请假原因" width="" />
                    <el-table-column prop="destination" label="出行目的地" width="" />
                    <el-table-column prop="isKnow" label="父母是否知情" width="" :formatter="isKnowFormatter" />
                    <el-table-column prop="companionsPhone" label="同行人电话" width="" />
                    <el-table-column prop="motherPhone" label="母亲电话" width="" />
                    <el-table-column prop="fatherPhone" label="父亲电话" width="" />
                    <el-table-column prop="travelMode" label="出行方式" width="" />
                    <el-table-column prop="startTime" label="请假时间" width="" />
                    <el-table-column prop="endTime" label="返校时间" width="" />
                    <el-table-column fixed="right" prop="auditSuggest" label="审核建议" width="" />
                    <el-table-column fixed="right" prop="auditStatus" label="审核状态" width=""
                        :formatter="auditStatusFormatter" />
                    <el-table-column fixed="right" prop="auditResult" label="审核结果" width=""
                        :formatter="auditResultFormatter" />
                    <el-table-column fixed="right" label="操作" min-width="">
                        <template #default="scoped">

                            <el-button v-show="scoped.row.auditResult == null" link type="primary" size="small"
                                @click="editFun(scoped.row)">重新编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination background v-model:current-page="pageNum" :page-size="pageSize"
                    layout="total, prev, pager, next" :total="total" @current-change="handleCurrentChange" />
            </div>
        </template>
        <CpdmLeaveEdit ref="editFlag" @search='listFun' />
    </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>