package com.xhpc.pp.controller;

import com.xhpc.common.api.dto.ChargingStationDto;
import com.xhpc.common.core.domain.R;
import com.xhpc.pp.utils.HexUtils;
import lombok.extern.slf4j.Slf4j;
import org.quickserver.net.server.ClientHandler;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.pp.server.ChargingPileServer.getHandler;
import static com.xhpc.pp.server.ChargingPileServer.removeHandler;

@RestController
@Slf4j
public class PileController {

    @PostMapping("pile/whitelist/add/{stationId}/{version}")
    public Object addWhitelist(@PathVariable("stationId") Long stationId,
                               @PathVariable("version") String version,
                               @RequestBody Set<String> pileNoSet) {

        Set<String> pileWhitelist = REDIS.getCacheSet("PILE_WHITELIST");
        pileWhitelist.addAll(pileNoSet);
        REDIS.setCacheSet("PILE_WHITELIST", pileWhitelist);
        String stationKey = "station:".concat(stationId.toString());
        ChargingStationDto cacheStation = REDIS.getCacheObject(stationKey);
        if (cacheStation == null) {
            cacheStation = new ChargingStationDto();
            cacheStation.setStationId(stationId);
        }
        Set<String> stationPiles = cacheStation.getPiles();
        if (stationPiles == null) {
            cacheStation.setPiles(pileNoSet);
        } else {
            cacheStation.getPiles().addAll(pileNoSet);
        }
        REDIS.setCacheObject(stationKey, cacheStation);
        for (String pileNo : pileNoSet) {
            String pkey = "pile:".concat(pileNo);
            Map<String, Object> cachePile = REDIS.getCacheMap(pkey);
            cachePile.put("stationId", stationId);
            cachePile.put("version", version);
            REDIS.setCacheMap(pkey, cachePile);
        }
        return R.ok();
    }

    @DeleteMapping("pile/whitelist/delete/{stationId}")
    public Object deleteWhitelist(@PathVariable("stationId") Long stationId, @RequestBody Set<String> pileNoSet) {

//        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
//        System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        REDIS.deleteSetVal("PILE_WHITELIST", pileNoSet.toArray());
        String stationKey = "station:".concat(stationId.toString());
//        System.out.println(">>>>>>>>>>>>>>>>>>pileNoSet.toArray()>>>>>>>>>>>>>>>>"+stationKey);
        ChargingStationDto cacheStation = REDIS.getCacheObject(stationKey);
        cacheStation.getPiles().removeAll(pileNoSet);
        REDIS.setCacheObject(stationKey, cacheStation);
        return R.ok();
    }

    @PostMapping("native/pile/{pileNo}/rateModel")
    public Object configRateModel(@PathVariable("pileNo") String pileNo, @RequestBody String msg) {

        ClientHandler handler = getHandler(pileNo);
        R r;
        if (handler != null) {
            if (!handler.isOpen()) {
                log.error("send message failed. [{}]({}) connection lost", handler.getName(), pileNo);
                removeHandler(pileNo);
                r = R.fail("充电桩连接已断开,请稍后再试");
            } else {
                try {
                    log.debug("[{}] - server send msg >>>> ({}) |{}|", handler.getName(), pileNo, msg);
                    handler.sendClientBinary(HexUtils.toBytes(msg));
                    r = R.ok(null, "网络延迟,请重试");
                } catch (IOException e) {
                    log.error("费率模型下发失败[{}]:".concat(e.getMessage()).concat(".无法启动充电"), pileNo);
                    removeHandler(pileNo);
                    r = R.fail("电桩网络通信失败,请重试");
                }
            }
        } else {
            log.error("费率模型下发失败[{}].无法启动充电", pileNo);
            r = R.fail("启动失败,请稍后重试");
        }
        return r;
    }

}
