package com.pwt.cloud.utils;

import cn.hutool.core.util.StrUtil;
import com.pwt.Globals;
import com.pwt.cloud.domin.Device;
import com.pwt.cloud.params.ChangeFinishParam;
import com.pwt.cloud.params.ChargeFinishParam;
import com.pwt.common.utils.CacheMap;
import com.pwt.common.utils.spring.SpringUtils;
import com.pwt.netty.BusinessException;
import com.pwt.netty.message2.Alarm;
import com.pwt.netty.message2.BatteryStateInfo;
import com.pwt.netty.message2.ChargerGun;
import com.pwt.system.domain.PwtConfig;
import com.pwt.system.service.IPwtConfigService;
import com.pwt.web.domain.PwtHolderBatteryStateCache;
import com.pwt.web.service.ICloudService;
import com.pwt.web.service.impl.CloudServiceImpl;
import lombok.extern.slf4j.Slf4j;

import java.util.Comparator;
import java.util.Objects;
import java.util.Optional;

/**
 * 处理云平台业务工具
 *
 * @author hanshuangxi
 * @date 2023/8/23 15:42
 */
@Slf4j
public class CloudUtil {

    private static final ICloudService cloudService = SpringUtils.getBean(ICloudService.class);

    private static PwtConfig pwtConfig = SpringUtils.getBean(IPwtConfigService.class).selectPwtConfigById(1L);

    private CloudUtil() {
    }

    /**
     * 充电桩开始充电
     *
     * @param vehicleCode 车辆编号
     * @param deviceCode 设备编号【充电桩编号】
     */
    public static boolean chargeStart(String vehicleCode, String deviceCode) {
        try {
            cloudService.chargeStart(vehicleCode, deviceCode);
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    public static void chargeFinish(ChargeFinishParam param) {
        if (Objects.isNull(param)) {
            log.error("缺少参数");
            return;
        }
        try {
            cloudService.chargeFinish(param);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }

    }

    /**
     * 开始换电
     *
     * @param vehicleCode 车辆编号
     */
    public static boolean changeStart(String vehicleCode) {
        try {
            cloudService.changeStart(vehicleCode, pwtConfig.getRobotNo());
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
        return true;
    }

    public static void changeFinish(ChangeFinishParam param) {
        if (Objects.isNull(param)) {
            log.error("缺少参数");
            return;
        }
        param.setDeviceCode(pwtConfig.getRobotNo());
        try {
            cloudService.changeFinish(param);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }

    }


    /**
     * 机组充电开始
     *
     * @param chargerGunId 充电枪号
     */
    public static void powerStart(String chargerGunId) {
        Optional<String> holderIdOptional = Globals.uiData.getChargerGuns().stream()
                .filter(e -> chargerGunId.equals(e.getId()))
                .max(Comparator.comparingLong(ChargerGun::getTimestamp))
                .map(ChargerGun::getHolderId);
        if (holderIdOptional.isPresent()) {
            String holderId = holderIdOptional.get();
            if (StrUtil.isEmpty(holderId)) {
                log.error("缺少仓位信息");
            }
            Optional<String> batterySnOptional = Globals.uiData.getBatteryStates().stream().filter(e -> holderId.equals(e.getHolderId()))
                    .max(Comparator.comparingLong(BatteryStateInfo::getTimestamp)).map(BatteryStateInfo::getBatterySn);
            if (batterySnOptional.isPresent()) {
                String batterySn = batterySnOptional.get();
                //获取机组code
                String deviceCode = getDeviceCodeByHolder(holderId);
                try {
                    cloudService.powerStart(batterySn, deviceCode);
                } catch (BusinessException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    public static void powerStart(String batterySn, String deviceCode) {
        try {
            cloudService.powerStart(batterySn, deviceCode);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 机组充电完成
     *
     * @param cache 缓存信息
     * @param level 充电量
     */
    public static void powerFinish(PwtHolderBatteryStateCache cache, double level) {
        try {
            String deviceCode = getDeviceCodeByHolder(String.valueOf(cache.getHolderId()));
            cloudService.powerFinish(cache.getBatterySn(), deviceCode, level);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 电站告警开始
     *
     * @param alarm 告警信息
     */
    public static void alarmStart(Alarm alarm) {
        try {
            cloudService.alarmStart(pwtConfig.getRobotNo(), alarm.getCode(), String.valueOf(alarm.getLevel()));
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 告警完成
     *
     * @param alarm 告警信息
     */
    public static void alarmFinish(Alarm alarm) {
        try {
            cloudService.alarmFinish(pwtConfig.getRobotNo(), alarm.getCode());
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }
    }

    private static String getDeviceCodeByHolder(String holderId) {
        switch (holderId) {
            case "1":
                return pwtConfig.getCharger1No();
            case "2":
                return pwtConfig.getCharger2No();
            case "3":
                return pwtConfig.getCharger3No();
            case "4":
                return pwtConfig.getCharger4No();
            case "5":
                return pwtConfig.getCharger5No();
            case "6":
                return pwtConfig.getCharger6No();
            case "7":
                return pwtConfig.getCharger7No();
            case "8":
                return pwtConfig.getCharger8No();
            default:
                break;
        }
        return null;
    }

    /**
     * 初始化配置
     */
    public static void initPwtConfig() {
        try {
            CloudServiceImpl.getCloudInfo();
            pwtConfig = SpringUtils.getBean(IPwtConfigService.class).selectPwtConfigById(1L);
        } catch (BusinessException e) {
            throw new RuntimeException(e);
        }
    }
}