<template>
    <view>
        <cu-custom :backUrl="'/pages/index/index'" :isBack="true" bgColor="bg-gradual-blue" >
            <block slot="content">离职申请</block>
        </cu-custom>
        <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-if="!nodeFlag">
            <u-form-item label="姓名" borderBottom prop="name">
                <u--input placeholder='请填写请假人'  v-model="inputForm.name" disabled></u--input>
            </u-form-item>
            <u-form-item label="所属部门" borderBottom prop="departmentName">
                <u--input placeholder='请选择所属部门'  v-model="inputForm.departmentName" disabled></u--input>
            </u-form-item>
            <u-form-item label="到岗日期" borderBottom prop="arrivalDate" :required="true">
                <el-date-picker
                        v-model="inputForm.arrivalDate"
                        type="date"
                        placeholder="请选择到岗日期"
                        style="width:100%"
                        size="default"
                        placement="bottom-start"
                        @change="validateDepartureDate2"
                        clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="预定离职日期" borderBottom prop="departResignationDate" :required="true">
                <el-date-picker
                        v-model="inputForm.departResignationDate"
                        type="date"
                        placeholder="请选择预定离职日期"
                        style="width:100%"
                        size="default"
                        placement="bottom-start"
                        @change="validateDepartureDate"
                        clearable>
                </el-date-picker>
            </u-form-item>
            <u-form-item label="备注" borderBottom prop="remarks">
                <u--textarea  placeholder='请填写备注' :maxlength="500" v-model="inputForm.remarks" ></u--textarea>
            </u-form-item>
        </u--form>
    </view>
</template>

<script>
    import departRegistrationService from '@/api/human/depart/DepartRegistrationService'
    import CommonApi from '@/api/common/CommonApi'
    import {mapState, mapMutations, mapActions} from 'vuex'
    export default {
        components: {
        },
        computed: mapState({
            userInfo: (state) => state.user.userInfo,
            avatar: (state) => state.user.avatar
        }),
        data () {
            return {
                inputForm: {
                    name:'',
                    department:'',
                    departmentName:'',
                    arrivalDate:'',
                    departResignationDate:'',
                    id: '',
                    procInsId: '',
                    type: '',
                },
                rules: {
                    'arrivalDate': [
                        {
                            required: true,
                            message: '到岗日期不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],
                    'departResignationDate': [
                        {
                            required: true,
                            message: '预定离职日期不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],
                },
                nodeFlag: false,
            }
        },
        commonApi: null,
        // 页面加载时执行
        created() {
            this.commonApi = new CommonApi()
            this.inputForm.name = this.userInfo.name
            this.inputForm.department = this.userInfo.officeDTO.id
            this.inputForm.departmentName = this.userInfo.officeDTO.name
        },
        props: {
            businessId: {
                type: String,
                default: ''
            },
            formReadOnly: {
                type: Boolean,
                default: false
            },
            status: {
                type: String,
                default: ''
            }
        },
        watch: {
            'businessId': {
                handler (newVal) {
                    if (this.businessId) {
                        this.init(this.businessId)
                    } else {
                        this.$nextTick(() => {
                            // this.$refs.inputForm.reset()
                        })
                    }
                },
                immediate: true,
                deep: false
            }
        },
        methods: {
            init (id) {
                this.nodeFlag = true
                this.inputForm.id = id
                if (id) {
                    departRegistrationService.findById(id).then((data) => {

                        // this.commonApi.getTaskNameByProcInsId(data.procInsId).then((data) => {
                        //     if (this.isNotEmpty(data)) {
                        //         if (data === '调整重新发起' || this.isEmpty(data)) {
                        //             this.nodeFlag = false
                        //         } else {
                        //             this.nodeFlag = true
                        //         }
                        //     }
                        // })
                        this.inputForm = this.recover(this.inputForm, data)
                    })
                }
            },
            isEmpty(value) {
                let result = false;
                if (value == null || value == undefined) {
                    result = true;
                }
                if (typeof value == 'string' && (value.replace(/\s+/g, "") == "" || value == "")) {
                    result = true;
                }
                if (typeof value == "object" && value instanceof Array && value.length === 0) {
                    result = true;
                }
                return result;
            },
            isNotEmpty (value) {
                return !this.isEmpty(value)
            },
            /**
             * 判断是否为空
             */
            isNull(val) {
                if (val instanceof Array) {
                    if (val.length === 0) return true;
                } else if (val instanceof Object) {
                    if (JSON.stringify(val) === "{}") return true;
                } else {
                    if (
                        val === "null" ||
                        val == null ||
                        val === "undefined" ||
                        val === undefined ||
                        val === ""
                    )
                        return true;
                    return false;
                }
                return false;
            },
            formatDateNew(date) {
                const year = date.getFullYear();
                const month = (date.getMonth() + 1).toString().padStart(2, '0');
                const day = date.getDate().toString().padStart(2, '0');
                const hours = date.getHours().toString().padStart(2, '0');
                const minutes = date.getMinutes().toString().padStart(2, '0');
                const seconds = date.getSeconds().toString().padStart(2, '0');

                return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
            },
            formatDate(date) {
                const dateNew = new Date(date); // 将日期字符串转换为 Date 对象
                const year = dateNew.getFullYear();
                const month = (dateNew.getMonth() + 1).toString().padStart(2, '0');
                const day = dateNew.getDate().toString().padStart(2, '0');
                return `${year}-${month}-${day}`;
            },
            saveForm(callback) {

                // 所有验证通过，执行保存操作
                if (this.isNotEmpty(this.inputForm.arrivalDate)) {
                    this.inputForm.arrivalDate = this.formatDate(this.inputForm.arrivalDate);
                }
                if (this.isNotEmpty(this.inputForm.departResignationDate)) {
                    this.inputForm.departResignationDate = this.formatDate(this.inputForm.departResignationDate);
                }

                return new Promise(async (resolve, reject) => {

                    let errors = [];

                    if (this.isEmpty(this.inputForm.arrivalDate)){
                        errors.push('请选择到岗日期');
                    }
                    if (this.isEmpty(this.inputForm.departResignationDate)){
                        errors.push('请选择预定离职日期');
                    }

                    //查询数据库中是否已经有了离职的申请数据，有则不能发起
                    await departRegistrationService.selectComplete().then((data) => {
                        if (data) {
                            console.log('data', data)
                            errors.push('已存在离职申请，无法多次提交');
                        }
                    })


                    if (errors.length > 0) {
                        // 存在错误，显示提示信息
                        errors.forEach(error => {
                            uni.showToast({
                                title: error,
                                icon: 'none',
                                duration: 1500
                            });
                        });
                        reject('Form validation failed');
                    } else {
                        this.$refs.inputForm.validate().then(res => {
                            this.inputForm.type = '2'
                            this.inputForm.userId = this.userInfo.id
                            departRegistrationService.save(this.inputForm).then((data) => {
                                this.inputForm.id = data.businessId
                                callback(data.businessTable, data.businessId, this.inputForm)
                                this.$refs.inputForm.resetFields()
                                this.loading = false
                            }).catch(() => {
                                this.$refs.inputForm.resetFields()
                            }).catch((e) => {

                            })
                        })
                    }
                });
            },

            // 修改状态
            async updateStatusById (type, callback) {
                if (type === 'reject' || type === 'reback') {
                    departRegistrationService.findById(this.inputForm.id).then((data) => {
                        if (data.type !== '2') { // status的值不等于“审核中”，就弹出提示
                            this.loading = false
                            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                            throw new Error()
                        } else {
                            if (type === 'reject') {
                                // 驳回
                                this.inputForm.type = '4'
                            }
                            if (type === 'reback') {
                                // 撤回
                                this.inputForm.type = '3'
                            }
                            if (type === 'reject' || type === 'reback') {
                                let param = {status: this.inputForm.type, id: this.inputForm.id}
                                departRegistrationService.updateStatusById(param).then(() => {
                                    this.loading = false
                                    callback()
                                })
                            }
                        }
                    })
                } else if (type === 'hold') {
                    departRegistrationService.findById(this.inputForm.id).then((data) => {
                        if (data.type !== '4') { // status的值不等于“驳回”就弹出提示
                            this.loading = false
                            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                            throw new Error()
                        } else {
                            // 终止
                            let param = {status: '1', id: this.inputForm.id}
                            departRegistrationService.updateStatusById(param).then(() => {
                                this.loading = false
                                callback()
                            })
                        }
                    })
                }
            },
            reapplyForm (callback) {
                this.loading = true
                departRegistrationService.findById(this.inputForm.id).then((data) => {
                    if (data.type !== '4') { // 审核状态不是“驳回”，就弹出提示
                        this.loading = false
                        this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                        throw new Error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                    } else {
                        this.startFormTrue(callback)
                    }
                })
            },
            // 送审
            async startFormTrue (callback) {

                if (this.isNotEmpty(this.inputForm.arrivalDate)) {
                    this.inputForm.arrivalDate = this.formatDate(this.inputForm.arrivalDate);
                }
                if (this.isNotEmpty(this.inputForm.departResignationDate)) {
                    this.inputForm.departResignationDate = this.formatDate(this.inputForm.departResignationDate);
                }

                return new Promise((resolve, reject) => {

                    let errors = [];

                    if (this.isEmpty(this.inputForm.arrivalDate)){
                        errors.push('请选择到岗日期');
                    }
                    if (this.isEmpty(this.inputForm.departResignationDate)){
                        errors.push('请选择预定离职日期');
                    }

                    if (errors.length > 0) {
                        // 存在错误，显示提示信息
                        errors.forEach(error => {
                            uni.showToast({
                                title: error,
                                icon: 'none',
                                duration: 2000
                            });
                        });
                        reject('Form validation failed');
                    } else {
                        this.$refs.inputForm.validate().then(res => {
                            this.inputForm.type = '2'
                            departRegistrationService.save(this.inputForm).then((data) => {
                                console.log('data', data)
                                this.inputForm.id = data.businessId
                                callback(data.businessTable, data.businessId, this.inputForm)
                                this.$refs.inputForm.resetFields()
                                this.loading = false
                            }).catch(() => {
                                this.$refs.inputForm.resetFields()
                            }).catch((e) => {

                            })
                        })
                    }
                });
            },
            // 通过
            async agreeForm (callback) {
                console.log('this.inputForm', this.inputForm)
                this.$refs.inputForm.validate().then(res => {
                    if (this.inputForm.days >1) {
                        this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data) => {
                            if (this.isNotEmpty(data)) {
                                if (data === '办公室主任审批') {
                                    this.inputForm.type = '5'
                                } else {
                                    this.inputForm.type = '2'
                                }
                            }
                            departRegistrationService.save(this.inputForm).then((data) => {
                                callback(data.businessTable, data.businessId, this.inputForm)
                                this.$refs.inputForm.resetFields()
                                this.loading = false
                            }).catch(() => {
                                this.loading = false
                                this.$refs.inputForm.resetFields()
                            })
                        })
                    } else {
                        this.inputForm.type = '5'
                        departRegistrationService.save(this.inputForm).then((data) => {
                            callback(data.businessTable, data.businessId, this.inputForm)
                            this.$refs.inputForm.resetFields()
                            this.loading = false
                        }).catch(() => {
                            this.loading = false
                            this.$refs.inputForm.resetFields()
                        })
                    }
                })
            },
            // 自定义验证函数
            validateDepartureDate() {
                if (this.isNotEmpty(this.inputForm.arrivalDate)){
                    if (this.inputForm.departResignationDate <= this.inputForm.arrivalDate) {
                        this.inputForm.departResignationDate = ''
                        uni.showToast({
                            title: '离职日期必须晚于到岗日期',
                            icon: "none",
                            duration:2000
                        })
                    }
                }

            },
            validateDepartureDate2() {
                if (this.isNotEmpty(this.inputForm.departResignationDate)) {
                    if (this.inputForm.arrivalDate >= this.inputForm.departResignationDate) {
                        this.inputForm.arrivalDate = ''
                        uni.showToast({
                            title: '到岗日期必须早于离职日期',
                            icon: "none",
                            duration:2000
                        })
                    }
                }

            },
        }
    }
</script>

<style>
    .cu-form-group .title {
        min-width: calc(4em + 40px);
    }
</style>
