<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="projectManager" :required="true">
                <user-select v-model="inputForm.projectManager" :disabled="testFlag"></user-select>
            </u-form-item>
            <u-form-item label="备注" borderBottom prop="remarks">
                <u--textarea  placeholder='请填写备注' :maxlength="500" v-model="inputForm.remarks" :disabled="testFlag"></u--textarea>
            </u-form-item>
        </u--form>
        <u--form :model="inputForm" labelWidth="100px" class="u-form" labelPosition="left" :rules="rules" ref="inputForm" v-else-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="projectManager" :required="true" v-if="!testFlag">
                <user-select v-model="inputForm.projectManager" ></user-select>
            </u-form-item>
            <u-form-item label="项目经理" borderBottom prop="projectManagerName" :required="true" v-else-if="testFlag">
                <u--input v-model="inputForm.projectManagerName" disabled></u--input>
            </u-form-item>
            <u-form-item label="备注" borderBottom prop="remarks">
                <u--textarea  placeholder='请填写备注' :maxlength="500" v-model="inputForm.remarks" :disabled="testFlag"></u--textarea>
            </u-form-item>
        </u--form>
    </view>
</template>

<script>
    import userSelect from '@/components/user-select/user-select-radio.vue'
    import handoverService from '@/api/human/depart/HandoverService'
    import CommonApi from '@/api/common/CommonApi'
    import {mapState, mapMutations, mapActions} from 'vuex'
    export default {
        components: {
            userSelect,
        },
        computed: mapState({
            userInfo: (state) => state.user.userInfo,
            avatar: (state) => state.user.avatar
        }),
        data () {
            return {
                inputForm: {
                    name:'',
                    department:'',
                    departmentName:'',
                    projectManager:'',
                    projectManagerName:'',
                    id: '',
                    procInsId: '',
                    type: '',
                    remarks: '',
                    draftAdministrator: '',
                },
                rules: {
                    'projectManager': [
                        {
                            required: true,
                            message: '项目经理不能为空',
                            trigger: ['blur', 'change']
                        }
                    ],
                },
                nodeFlag: false,
                testFlag: 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) {
                    handoverService.findById(id).then((data) => {
                        // 只有从我发起的还有已办事项抄送给我 进入流程页面的时候才会有这个值
                        if (this.status === 'testSee') {
                            this.nodeFlag = true
                        } else {
                            this.commonApi.getTaskNameByProcInsId(data.procInsId).then((data) => {
                                if (this.isNotEmpty(data)) {
                                    if (data === '调整重新申请' || this.isEmpty(data)) {
                                        this.nodeFlag = false
                                    } else if (data === '部门主任审批'){
                                        this.testFlag = true
                                        this.nodeFlag = true
                                    } else {
                                        this.nodeFlag = true
                                    }
                                }
                            })

                            if (this.userInfo.id === data.projectManager) {
                                this.testFlag = true
                            } else {
                                this.testFlag = false
                            }
                        }




                        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}`;
            },
            saveForm(callback) {

                // 所有验证通过，执行保存操作

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

                    let errors = [];

                    //查询数据库中是否已经有了离职的申请数据，有则不能发起
                    await handoverService.selectComplete().then((data) => {
                        if (data) {
                            errors.push('已存在离职交接 或 离职申请未审批，无法发起申请！');
                        }
                    })


                    if (errors.length > 0) {
                        // 存在错误，显示提示信息
                        errors.forEach(error => {
                            uni.showToast({
                                title: error,
                                icon: 'none',
                                duration: 1500
                            });
                        });
                        reject('Form validation failed');
                    } else {

                        // 如果正在提交中，则直接返回，避免重复提交
                        if (this.submitting) return;

                        // 设置提交状态为 true
                        this.submitting = true;

                        this.$refs.inputForm.validate().then(res => {
                            this.inputForm.type = '2'
                            this.inputForm.userId = this.userInfo.id
                            handoverService.save(this.inputForm).then((data) => {
                                this.inputForm.id = data.businessId
                                this.inputForm.assignee = this.inputForm.projectManager
                                callback(data.businessTable, data.businessId, this.inputForm)
                                this.$refs.inputForm.resetFields()
                                this.loading = false

                                // 重置提交状态为 false
                                this.submitting = false;
                            }).catch(() => {
                                this.$refs.inputForm.resetFields()
                                // 重置提交状态为 false
                                this.submitting = false;
                            }).catch((e) => {
                                // 重置提交状态为 false
                                this.submitting = false;
                            })
                        })
                    }
                });
            },

            // 修改状态
            async updateStatusById (type, callback) {
                if (type === 'reject') {
                    handoverService.findById(this.inputForm.id).then((data) => {
                        if (data.type !== '2') { // status的值不等于“审核中”，就弹出提示
                            this.loading = false
                            this.$message.error('任务数据已发生改变或不存在，请在待办任务中确认此任务是否存在')
                            throw new Error()
                        } else {
                            this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((name) => {
                                if (this.isNotEmpty(name)) {
                                    if (name === '项目经理审批' || name === '项目经理重新审批') {
                                        this.inputForm.type = '4'
                                    }
                                }
                                handoverService.updateStatusById(this.inputForm).then(() => {
                                    this.loading = false
                                    callback()
                                })
                            })
                        }
                    })
                } else if (type === 'hold') {
                    handoverService.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}
                            handoverService.updateStatusById(param).then(() => {
                                this.loading = false
                                callback()
                            })
                        }
                    })
                }
            },
            reapplyForm (callback) {
                this.loading = true
                handoverService.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) {

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

                    let errors = [];

                    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'
                            handoverService.save(this.inputForm).then((data) => {
                                console.log('data', data)
                                this.inputForm.id = data.businessId
                                this.inputForm.assignee = this.inputForm.projectManager
                                callback(data.businessTable, data.businessId, this.inputForm)
                                this.$refs.inputForm.resetFields()
                                this.loading = false
                            }).catch(() => {
                                this.$refs.inputForm.resetFields()
                            }).catch((e) => {

                            })
                        })
                    }
                });
            },
            // 通过
            async agreeForm (callback) {
                this.$refs.inputForm.validate().then(res => {
                    this.commonApi.getTaskNameByProcInsId(this.inputForm.procInsId).then((data) => {
                        if (this.isNotEmpty(data)) {
                            if (data === '部门主任审批') {
                                this.inputForm.type = '5'
                            } else {
                                this.inputForm.type = '2'
                            }
                        }
                        handoverService.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()
                        })
                    })
                })
            },
        }
    }
</script>

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