package com.skr.mdm.service.impl.equipment;

import cn.hutool.core.io.file.FileNameUtil;
import com.skr.mdm.constant.MinIoMessageConstants;
import com.skr.mdm.dao.ClientDebugLogDao;
import com.skr.mdm.dao.DeviceEquipmentDao;
import com.skr.mdm.dto.LoginUserDTO;
import com.skr.mdm.entity.ClientDebugLogDO;
import com.skr.mdm.entity.DeviceEquipmentDO;
import com.skr.mdm.manager.oss.MinIoManager;
import com.skr.mdm.result.ResponseResult;
import com.skr.mdm.util.MdmIdUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Objects;

/**
 * @author nfq
 * @date 2020/11/10 16:12
 */
@Slf4j
@Service
public class DeviceDebugLogServiceImpl {

    @Autowired
    private ClientDebugLogDao debugLogDao;
    @Autowired
    private DeviceEquipmentDao equipmentDao;
    @Autowired
    private MinIoManager minIoManager;

    public ResponseResult upload(LoginUserDTO loginUserDTO, String info, MultipartFile file) {
        try {
            String type = FileNameUtil.extName(file.getOriginalFilename());
            String fileId = String.valueOf(MdmIdUtil.getSnowflakeNextId());
            String filename = fileId + "." + type;
            String filePath = MinIoMessageConstants.DEBUG_LOG + filename;
            String fileUrl = minIoManager.putObjectMinIo(loginUserDTO.getCompanyId(), filePath, file, false);
            DeviceEquipmentDO equipmentDO = equipmentDao.selectById(loginUserDTO.getId());
            if (!Objects.isNull(equipmentDO)) {
                ClientDebugLogDO clientDebugLogDO = ClientDebugLogDO.builder()
                        .deviceId(loginUserDTO.getId())
                        .address(fileUrl)
                        .type(type)
                        .info(info)
                        .companyId(loginUserDTO.getCompanyId())
                        .source(filePath)
                        .operationTime(new Date())
                        .build();
                debugLogDao.insert(clientDebugLogDO);
            }
            return ResponseResult.success();
        } catch (Exception e) {
            log.error("设备调试日志上报异常：" + loginUserDTO.getId(), e);
            return ResponseResult.failure();
        }
    }
}