package com.cxyxiaomo.epp.common.vo;

import com.cxyxiaomo.epp.common.pojo.AccessLog;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

// 数据库关系映射

@Data
@NoArgsConstructor
@Accessors(chain = true) // 链式写法
// 微服务必须要实现Serializable
public class AccessLogVO implements Serializable {

    private String id;
    private Long timestamp;
    private Integer userId;
    private String userRealName;
    private String gateId;
    private String type;

    public static AccessLogVO convertFrom(AccessLog accessLog) {
        if (accessLog == null) {
            return null;
        }
        AccessLogVO accessLogVO = new AccessLogVO();
        BeanUtils.copyProperties(accessLog, accessLogVO);
        Date time = accessLog.getTime();
        accessLogVO.setTimestamp(time.getTime());
        if (Objects.nonNull(accessLog.getId())) {
            accessLogVO.setId(String.valueOf(accessLog.getId()));
        }
        if (Objects.nonNull(accessLog.getGateId())) {
            accessLogVO.setGateId(String.valueOf(accessLog.getGateId()));
        }
        return accessLogVO;
    }

    public static List<AccessLogVO> convertFrom(List<AccessLog> accessLogList) {
        if (accessLogList == null) {
            return null;
        }
        List<AccessLogVO> accessLogVOList = accessLogList.stream()
                .map(AccessLogVO::convertFrom).collect(Collectors.toList());
        return accessLogVOList;
    }

    public static AccessLog convertTo(AccessLogVO accessLogVO) {
        if (accessLogVO == null) {
            return null;
        }
        AccessLog accessLog = new AccessLog();
        BeanUtils.copyProperties(accessLogVO, accessLog);

        Long timestamp = accessLogVO.getTimestamp();
        if (timestamp != null) {
            Date date = new Date(timestamp);
            accessLog.setTime(date);
        }

        try {
            if (Objects.nonNull(accessLogVO.getId())) {
                Long accessLogId = Long.valueOf(accessLogVO.getId());
                accessLog.setId(accessLogId);
            } else {
                accessLog.setId(null);
            }
        } catch (Exception e) {
            accessLog.setId(null);
        }

        try {
            if (Objects.nonNull(accessLogVO.getGateId())) {
                Long gateId = Long.valueOf(accessLogVO.getGateId());
                accessLog.setGateId(gateId);
            } else {
                accessLog.setGateId(null);
            }
        } catch (Exception e) {
            accessLog.setGateId(null);
        }
        return accessLog;
    }
}
