package com.fastbee.data.controller.sse;

import cn.hutool.json.JSONUtil;
import com.fastbee.common.core.controller.BaseController;
import com.fastbee.common.core.domain.AjaxResult;
import com.fastbee.common.core.domain.AjaxResultPro;
import com.fastbee.iot.domain.DeviceReportInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.IOException;
import java.time.LocalDate;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 设备审核前上电基本信息
 */
@RestController
@RequestMapping("/sse")
@Slf4j
@CrossOrigin(origins = "*")
public class DeviceReportSSEController extends BaseController {
    private final Map<String, SseEmitter> emitters = new ConcurrentHashMap<>();//用户消息推送集合

    /**
     * 与客户端建立http长链接
     */
    @PostMapping(value = "/device/init",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter getReport() throws IOException {
        SseEmitter emitter= new SseEmitter(0L);
        emitters.put("device-init",emitter);
        emitter.send(JSONUtil.toJsonStr(Message.builder().event(1).content("连接成功！").build()));
        return emitter;
    }

    @PostMapping("/device/init/new")
    public AjaxResultPro sendMsg(@RequestBody DeviceReportInfo reportInfo)  {
        try{
            SseEmitter emitter = emitters.get("device-init");
            if(emitter==null){
                return AjaxResultPro.error("审核员离线！请到管理后台打开设备初始化页面！");
            }
            //生成设备默认编号
//            reportInfo.setDeviceId("10086");
            String deviceNumber = generateDeviceNumber();
            emitter.send(JSONUtil.toJsonStr(Message.builder().event(2).content("新的消息").data(reportInfo).build()));
            return AjaxResultPro.success();
        }catch (Exception e){
            log.error("发送消息失败",e);
            return AjaxResultPro.error("系统错误！");
        }
    }

    @PostMapping("/device/init/new/remove")
    public AjaxResultPro removeMsg()  {
        emitters.clear();
      return AjaxResultPro.success();
    }

    @PostMapping("/device/init/new/text")
    public void sendMsgText(@RequestBody DeviceReportInfo reportInfo) throws IOException {
        SseEmitter emitter = emitters.get("device-init");
        DeviceReportInfo deviceReportInfo = new DeviceReportInfo();
        deviceReportInfo.setImei("10086");
        deviceReportInfo.setIccid("10086");
        deviceReportInfo.setMcuId("wqewqewq");
        deviceReportInfo.setBspType("iwqjriqw");
        deviceReportInfo.setLteType("rui");
        deviceReportInfo.setMcuType("mcu");
        deviceReportInfo.setMcuFw("1.0.0");
        deviceReportInfo.setLteFw("opodaojdao");
        deviceReportInfo.setLcdManufacturer(1L);
        deviceReportInfo.setVoiceManufacturer(1L);
        deviceReportInfo.setFramModel("BTOOO");
        deviceReportInfo.setReplaceManufacturer(1L);
        deviceReportInfo.setTestRecord("test");
        if(emitter!=null){
            emitter.send(JSONUtil.toJsonStr(Message.builder().event(2).content("新的消息").data(deviceReportInfo).build()));
        }
    }





    /**
     * 生成当前批次的设备编码
     */
    @GetMapping("/device/init/deviceNumber")
    public AjaxResultPro getDeviceNumber() {
        return AjaxResultPro.success(generateDeviceNumber());
    }




    /**
     * 根据给定规则生成当前批次的起始设备编号
     * @return 生成的设备编号字符串
     */
    public  String generateDeviceNumber() {
        StringBuilder deviceNumber = new StringBuilder();
        // 添加固定的第一个字符'H'
        deviceNumber.append("H");
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        int year = currentDate.getYear();
        int month = currentDate.getMonthValue();
        // 根据年份确定对应的字符，以2024年对应'A'为起始，依次往后按字母顺序
        char yearChar = (char) ('A' + (year - 2024));
        deviceNumber.append(yearChar);
        // 月份转换为两位字符串格式，不足两位前面补0
        String monthStr = String.format("%02d", month);
        deviceNumber.append(monthStr);
        return deviceNumber.toString()+"00001";
    }
}
