package com.ruoyi.ss.record.time.service.impl;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.LoginType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.ss.device.domain.vo.DeviceVO;
import com.ruoyi.ss.record.time.domain.RecordTime;
import com.ruoyi.ss.record.time.domain.enums.OperatorType;
import com.ruoyi.ss.record.time.service.RecordTimeConverter;
import com.ruoyi.ss.user.domain.SmUserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author wjh
 * 2024/6/6
 */
@Service
@Slf4j
public class RecordTimeConverterImpl implements RecordTimeConverter {
    @Override
    public RecordTime toRecordTime(Long deviceId, long amount, String reason, String type) {
        RecordTime record = new RecordTime();
        record.setDeviceId(deviceId);
        record.setAmount(amount);
        record.setReason(reason);
        record.setType(type);

        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null) {
                record.setOperatorId(loginUser.getUserId());
                record.setOperatorName(loginUser.getUsername());
                record.setOperatorType(toOperatorType(loginUser.getLoginType()));
            }
        } catch (Exception e) {
            log.warn(e.getMessage());
        }

        record.setOperatorTime(LocalDateTime.now());

        return record;
    }

    @Override
    public RecordTime toRecordTime(DeviceVO device, long seconds, String reason, SmUserVO user, String type) {
        RecordTime record = new RecordTime();
        record.setDeviceId(device == null ? null : device.getDeviceId());
        record.setAmount(seconds);
        record.setReason(reason);
        record.setType(type);
        if (user != null) {
            record.setOperatorId(user.getUserId());
            record.setOperatorName(user.getUserName());
            record.setOperatorType(OperatorType.USER.getType());
        }
        record.setOperatorTime(LocalDateTime.now());
        return record;
    }

    private String toOperatorType(LoginType loginType) {
        return OperatorType.parse(loginType).getType();
    }
}
