package com.yfd.platform.uavsystem.conf.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.SneakyThrows;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;

/**
 * @author Admin
 * @version 1.0
 * @Description:
 * @date 2022/7/5 14:13
 */
//@Component
public class MyBatisPlusFillHandler implements MetaObjectHandler {

    private final static String NEW_DATE_TYPE_DATE_TIME="java.time.LocalDateTime";
    private final static String NEW_DATE_TYPE_DATE="java.time.LocalDate";
    private final static String NEW_DATE_TYPE_TIME="java.time.LocalTime";
    private final static String OLD_DATE_TYPE="java.util.Date";



    public Object addDate(MetaObject metaObject,String name) throws NoSuchFieldException {
        String recCreateTime="";
        try {
            recCreateTime = metaObject.getOriginalObject().getClass().getDeclaredField(name).getType().getName();
        }catch (Exception e){
            return null;
        }

        switch (recCreateTime){
            case NEW_DATE_TYPE_DATE_TIME:
                return LocalDateTime.now();
            case NEW_DATE_TYPE_DATE:
                return LocalDate.now();
            case NEW_DATE_TYPE_TIME:
                return LocalTime.now();
            case OLD_DATE_TYPE:
                return new Date();
            default:
                return new Date();
        }
    }

    @SneakyThrows
    @Override
    public void insertFill(MetaObject metaObject) {
        this.setFieldValByName("recCreateTime",addDate(metaObject,"recCreateTime"),metaObject);
        this.setFieldValByName("recReviseTime",addDate(metaObject,"recCreateTime"),metaObject);

            this.setFieldValByName("recCreator","system",metaObject);
            this.setFieldValByName("recReviser", "system",metaObject);

        //this.setFieldValByName("seqNo",seqNoService.getNextCode().toString(),metaObject);

        this.setFieldValByName("createDate",addDate(metaObject,"createDate"),metaObject);
        this.setFieldValByName("updateDate",addDate(metaObject,"updateDate"),metaObject);
            this.setFieldValByName("createBy","system",metaObject);
            this.setFieldValByName("updateBy", "system",metaObject);
    }

    @SneakyThrows
    @Override
    public void updateFill(MetaObject metaObject) {
        this.setFieldValByName("recReviseTime",addDate(metaObject,"recReviseTime"),metaObject);
        this.setFieldValByName("updateDate",addDate(metaObject,"updateDate"),metaObject);
            this.setFieldValByName("recReviser","system",metaObject);
            this.setFieldValByName("updateBy", "system",metaObject);

    }
}
