package net.northking.cctp.upperComputer.deviceManager;

import com.alibaba.fastjson.JSON;
import net.northking.cctp.upperComputer.entity.CdDeviceModel;
import net.northking.cctp.upperComputer.entity.CdDeviceRegisterDto;
import net.northking.cctp.upperComputer.entity.CdMobileBrand;
import net.northking.cctp.upperComputer.entity.CdMobileDevice;
import net.northking.cctp.upperComputer.enums.BrandEnum;
import net.northking.cctp.upperComputer.enums.PlatformType;
import net.northking.cctp.upperComputer.service.DeviceConnectionService;
import net.northking.cctp.upperComputer.utils.HttpUtils;
import net.northking.cctp.upperComputer.utils.SpringUtils;
import net.northking.cctp.upperComputer.webSocket.thread.MessageHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.util.StringUtils;

import javax.websocket.Session;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URI;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author : yineng.huang
 * @date : 2023/10/16 11:58
 */
public abstract class AbstractDeviceManager extends Thread implements DeviceManager{

    private Logger logger = LoggerFactory.getLogger(AbstractDeviceManager.class);

    @Override
    public void publishDeviceAgentAlready(String serial) {
        SpringUtils.getBean(DeviceConnectionService.class).deviceAgentAlready(serial);
    }

    @Override
    public void setDeviceSystemStatus(String serial, Boolean status) {

    }

    @Override
    public void publishDeviceAgentDead(String serial) {
        SpringUtils.getBean(DeviceConnectionService.class).deviceAgentDead(serial);
    }


    protected void publishDeviceOnlineToWebConnection(String deviceId) {
        MessageHandler handleMessageThread = SpringUtils.getBean(DeviceConnectionService.class).getHandleMessageThread(deviceId);
        if (null != handleMessageThread) {
            logger.debug("前端还有人连着这个设备【{}】,通知一下前端设备行了......................",deviceId);
            handleMessageThread.reConnectDeviceAgent();
        }
    }

    protected void publishDeviceOfflineToWebConnection(String deviceId) {
        MessageHandler handleMessageThread = SpringUtils.getBean(DeviceConnectionService.class).getHandleMessageThread(deviceId);
        if (null != handleMessageThread) {
            logger.debug("前端还有人连着这个设备【{}】,告诉前端设备G了......................",deviceId);
            handleMessageThread.clearAndCloseDeviceAgentConnection();
        }
//        AndroidScreenResponseThread screenResponseThread = screenMap.get(deviceId);
//        if (null != screenResponseThread && screenResponseThread.isAlive() && !screenResponseThread.isInterrupted()) {
//            logger.debug("设备【{}】离线，中断获取屏幕线程...", deviceId);
//            screenResponseThread.stopAndExit();
//        }
    }

    /**
     * 注册设备到服务端
     *
     * @param deviceInfo
     */
    @Override
    public void registerDeviceToDeviceManager(LinkedHashMap<String, Object> deviceInfo) {
        CdDeviceRegisterDto registerDto = new CdDeviceRegisterDto();
        //创建品牌
        String manufacturer = (null == deviceInfo.get("manufacturer") ? "" : deviceInfo.get("manufacturer") + "");
        CdMobileBrand brand = getBrand(manufacturer);
        //创建机型
        CdDeviceModel model = getModel(deviceInfo);
        //创建设备
        CdMobileDevice mobileDevice = getDevice(deviceInfo);
        registerDto.setCdDeviceModel(model);
        registerDto.setCdMobileBrand(brand);
        registerDto.setCdMobileDevice(mobileDevice);
        registerDto.setDeviceInfo(deviceInfo);
        logger.info("注册设备发送数据：{}", JSON.toJSONString(registerDto));
        String result = null;
        try {
            String serverAddress = SpringUtils.getProperties("nk.mobile-computer.serverAddr");
            String registerPath = SpringUtils.getProperties("nk.mobile-computer.mobilePushAddr");
            logger.info("注册设备地址：{}", serverAddress + registerPath);
            URI uri = new URI(serverAddress + registerPath);
            HttpEntity<CdDeviceRegisterDto> entity = new HttpEntity<>(registerDto, null);
            result = HttpUtils.doPost(uri, entity, String.class);
            logger.info("注册设备结果：{}", result);
        } catch (Exception e) {
            logger.error("注册设备失败", e);
        }
    }

    @Override
    public void offlineDeviceFromDeviceManager(String serial) {
        try {
            String serverAddress = SpringUtils.getProperties("nk.mobile-computer.serverAddr");
            String offlinePath = SpringUtils.getProperties("nk.mobile-computer.mobileOfflineAddr").replace("{uuid}",serial);
            logger.info("设备掉线地址：{}", serverAddress + offlinePath);
            URI uri = new URI(serverAddress + offlinePath);
            HttpUtils.doGet(uri, Integer.class);
        } catch (Exception e) {
            logger.error("设备掉线请求失败",e);
        }
        logger.info("掉线设备：{}",serial);

    }

    private CdMobileDevice getDevice(Map<String, Object> deviceInfo) {
        CdMobileDevice device = new CdMobileDevice();
        device.setId(deviceInfo.get("serial") + "");   //设备系统标识

        device.setPlatform(StringUtils.isEmpty(PlatformType.getCode((deviceInfo.get("platform") + "").toLowerCase())) ? "3" : PlatformType.getCode((deviceInfo.get("platform") + "").toLowerCase()));  //平台类型
        //版本，直接存
        device.setPlatformVersion(null == deviceInfo.get("version") ? "" : deviceInfo.get("version") + "");  //平台版本
        device.setCtrlId(UpperComputerManager.getComputerId());
        return device;

    }

    private CdDeviceModel getModel(Map<String, Object> device) {
        CdDeviceModel model = new CdDeviceModel();
        model.setModelName((null == device.get("model") ? "" : device.get("model") + ""));     //机型
        model.setProductName((null == device.get("product") ? "" : device.get("product") + ""));  //产品名称
        BigDecimal size = null;
        try {
            size = new BigDecimal(device.get("size") + "");
            String s = size.setScale(2, RoundingMode.CEILING).toString();
            if ("0.00".equals(s)) {
                model.setScreenSize("");  //屏幕大小
            } else {
                model.setScreenSize(s);  //屏幕大小
            }
        } catch (Exception e) {
            model.setScreenSize("");  //屏幕大小
        }
        Integer width = (Integer) device.get("width");
        Integer height = (Integer) device.get("height");
        model.setResolution(height + "*" + width);  //分辨率
        model.setCreatedBy("system");    //创建人和修改人先默认为系统人员
        model.setUpdatedBy("system");
        model.setCreatedTime(new Date());
        model.setUpdatedTime(model.getCreatedTime());
        model.setCpuModel(null == device.get("cpuPlatform") ? "" : device.get("cpuPlatform") + "");
        try {
            int cores = (int) device.get("cpuCores");
            model.setCpuCoreNum(cores); //核心数
        } catch (Exception e) {
            model.setCpuCoreNum(null); //核心数
        }
        if (null != device.get("cpuName") && StringUtils.isEmpty(device.get("cpuName"))) {
            model.setCpuModel(device.get("cpuName") + "");   //cpu型号
        }
        model.setRamSize(null == device.get("ram") ? "" : (Long.parseLong(device.get("ram") + "") / 1024) + ""); //内存大小
        model.setSystemVersion(device.get("version") + "");
        model.setType("1");  //0-手机，1-平板，2-电视，3-电脑
        return model;
    }

    private CdMobileBrand getBrand(String manufacturer) {
        CdMobileBrand brand = new CdMobileBrand();
        String chnName = BrandEnum.getChnName(manufacturer);
        if (StringUtils.hasText(chnName)) {
            brand.setBrandNameCn(chnName);
        }
        brand.setBrandName(manufacturer.toUpperCase());
        return brand;
    }

    public abstract void stopWebScreen(String udid, Session session);
}
