package com.fastbee.data.controller.anfang.controller;

import com.fastbee.common.annotation.Log;
import com.fastbee.common.config.RuoYiConfig;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.page.TableDataInfo;
import com.fastbee.common.enums.BusinessType;
import com.fastbee.common.exception.ServiceException;
import com.fastbee.common.model.bto.DoorAlertBto;
import com.fastbee.common.utils.RotateImageUtils;
import com.fastbee.common.utils.file.FileUploadUtils;
import com.fastbee.common.utils.poi.ExcelUtil;
import com.fastbee.data.controller.anfang.service.IUploadedPhotosService;
import com.fastbee.iot.model.anfang.UploadedPhotos;
import com.fastbee.iot.service.impl.DeviceServiceImpl;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

import static com.fastbee.common.utils.StringUtils.isEmpty;

/**
 * 设备告警上传Controller
 *
 * @author Dunxi Zang
 * @date 2024-06-19
 */
@RestController
@RequestMapping("/iot/photos")
@Api(tags = "安防小板")
public class UploadedPhotosController extends BaseController {
    @Autowired
    private IUploadedPhotosService uploadedPhotosService;

    /**
     * 查询设备告警上传列表
     */
    @PreAuthorize("@ss.hasPermi('iot:photos:list')")
    @GetMapping("/list")
    public TableDataInfo list(UploadedPhotos uploadedPhotos) {
        startPage();
        List<UploadedPhotos> list = uploadedPhotosService.selectUploadedPhotosList(uploadedPhotos);
        return getDataTable(list);
    }

    /**
     * 导出设备告警上传列表
     */
    @PreAuthorize("@ss.hasPermi('iot:photos:export')")
    @Log(title = "设备告警上传", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, UploadedPhotos uploadedPhotos) {
        List<UploadedPhotos> list = uploadedPhotosService.selectUploadedPhotosList(uploadedPhotos);
        ExcelUtil<UploadedPhotos> util = new ExcelUtil<UploadedPhotos>(UploadedPhotos.class);
        util.exportExcel(response, list, "设备告警上传数据");
    }

    /**
     * 获取设备告警上传详细信息
     */
    @PreAuthorize("@ss.hasPermi('iot:photos:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(uploadedPhotosService.selectUploadedPhotosById(id));
    }

    /**
     * 新增设备告警上传
     */
    @PostMapping
    public AjaxResult uploadPhoto(
            @RequestParam("fileToUpload") MultipartFile photo,
            @RequestParam("imei") String imei,
            @RequestParam("sn") String sn,
            @RequestParam("lat") String lat,
            @RequestParam("lng") String lng,
            @RequestParam("temp") String temp,
            @RequestParam("cpuTemp") Double cpuTemp,
            @RequestParam("eventType") String eventType,
            @RequestParam("doorState") String doorState,
            @RequestParam("anFangStatus") String anFangStatus,
            @RequestParam("time") String time) {

        if (photo.isEmpty()) {
            throw new ServiceException("照片为空，上传失败");
        }

        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            String fileName = FileUploadUtils.uploadByAngle(filePath, photo, 180);
//            BufferedImage src = ImageIO.read(photo.getInputStream());
//            BufferedImage rotate = RotateImageUtils.Rotate(src, 180);
//            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//            ImageIO.write(rotate, "png",byteArrayOutputStream);
//            InputStream input = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
//            String name = photo.getName();
//            String originalFilename = photo.getOriginalFilename();
//            MultipartFile multipartFile = new MockMultipartFile("file",photo.getOriginalFilename(),"text/plain", input);
//            // 上传并返回新文件名称
//            String fileName = FileUploadUtils.upload(filePath, multipartFile);
            // 处理可能为空的字段
            Double latitude = isEmpty(lat) ? 0.0 : Double.valueOf(lat);
            Double longitude = isEmpty(lng) ? 0.0 : Double.valueOf(lng);
            Double temperature = isEmpty(temp) ? 0.0 : convertAndRoundTemperature(temp);
            String shakeState = "0";
            // 处理时间戳
            long timestamp = Long.parseLong(time + "000");
            Date date = new Date(timestamp);
            //抓拍监控，并返回路径
            String monitorPath = uploadedPhotosService.captureMonitorPhoto(sn);
            //推送告警短信通知
            uploadedPhotosService.sendAlarmMessage(sn, doorState, shakeState, eventType);
            UploadedPhotos uploadedPhotos = new UploadedPhotos(
                    null, fileName, monitorPath, imei, sn, latitude, longitude,
                    temperature, doorState, shakeState, cpuTemp, eventType, anFangStatus, date
            );
            return toAjax(uploadedPhotosService.insertUploadedPhotos(uploadedPhotos));
        } catch (IOException e) {
            throw new ServiceException("设备告警信息上传失败");
        }
    }

    /**
     * 箱门告警
     *
     * @return
     */
    @PostMapping("doorAlert")
    public AjaxResult doorAlert(DoorAlertBto doorAlertBto) throws Exception {
        return toAjax(uploadedPhotosService.doorAlert(doorAlertBto));
    }

    /**
     * 新增设备告警上传不带图片
     */
    @PostMapping("eventNotPic")
    public AjaxResult uploadEvent(
            @RequestParam("imei") String imei,
            @RequestParam("sn") String sn,
            @RequestParam("lat") String lat,
            @RequestParam("lng") String lng,
            @RequestParam("temp") String temp,
            @RequestParam("doorState") String doorState,
            @RequestParam("cpuTemp") Double cpuTemp,
            @RequestParam("eventType") String eventType,
            @RequestParam("anFangStatus") String anFangStatus,
            @RequestParam("time") String time) {
        // 处理可能为空的字段
        Double latitude = isEmpty(lat) ? 0.0 : Double.valueOf(lat);
        Double longitude = isEmpty(lng) ? 0.0 : Double.valueOf(lng);
        Double temperature = isEmpty(temp) ? 0.0 : convertAndRoundTemperature(temp);
        String shakeState = "0";
        // 处理时间戳
        long timestamp = Long.parseLong(time + "000");
        Date date = new Date(timestamp);
        //抓拍监控，并返回路径
        String monitorPath = uploadedPhotosService.captureMonitorPhoto(sn);
        //推送告警短信通知
        uploadedPhotosService.sendAlarmMessage(sn, doorState, shakeState, eventType);
        UploadedPhotos uploadedPhotos = new UploadedPhotos(
                null, "", monitorPath, imei, sn, latitude, longitude, temperature, doorState, shakeState, cpuTemp, eventType, anFangStatus, date
        );
        return toAjax(uploadedPhotosService.insertUploadedPhotos(uploadedPhotos));
    }

    /**
     * 只上传告警图片
     */
    @PostMapping("uploadPicByTime")
    public AjaxResult uploadPicByTime(
            @RequestParam("fileToUpload") MultipartFile photo,
            @RequestParam("sn") String sn,
            @RequestParam("time") String time) {
        // 处理时间戳
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, photo);
            // 处理时间戳
            long timestamp = Long.parseLong(time + "000");
            Date date = new Date(timestamp);
            //推送告警短信通知
            UploadedPhotos uploadedPhotos = new UploadedPhotos();
            uploadedPhotos.setSn(sn);
            uploadedPhotos.setPhotoPath(fileName);
            uploadedPhotos.setUploadTime(date);
            return toAjax(uploadedPhotosService.uploadPicByTime(uploadedPhotos));
        } catch (IOException e) {
            throw new ServiceException("设备告警信息上传失败");
        }
    }

    /**
     * 修改设备告警上传
     */
    @PreAuthorize("@ss.hasPermi('iot:photos:edit')")
    @Log(title = "设备告警上传", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody UploadedPhotos uploadedPhotos) {
        return toAjax(uploadedPhotosService.updateUploadedPhotos(uploadedPhotos));
    }

    /**
     * 删除设备告警上传
     */
    @PreAuthorize("@ss.hasPermi('iot:photos:remove')")
    @Log(title = "设备告警上传", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(uploadedPhotosService.deleteUploadedPhotosByIds(ids));
    }

    public static Double convertAndRoundTemperature(String tempStr) {
        // 将字符串转换为double
        double temp = Double.parseDouble(tempStr);

        // 使用BigDecimal进行四舍五入，保留两位小数
        BigDecimal bd = BigDecimal.valueOf(temp);
        bd = bd.setScale(2, RoundingMode.HALF_UP);

        // 返回转换后的double值
        return bd.doubleValue();
    }
}
