package com.jsowell.thirdparty.nanrui;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jsowell.common.annotation.Anonymous;
import com.jsowell.common.core.controller.BaseController;
import com.jsowell.common.core.domain.ykc.RealTimeMonitorData;
import com.jsowell.common.enums.ykc.ReturnCodeEnum;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.JWTUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.dto.PushStationInfoDTO;
import com.jsowell.pile.dto.QueryStationInfoDTO;
import com.jsowell.pile.dto.nanrui.GetTokenDTO;
import com.jsowell.pile.dto.nanrui.NRQueryOrderDTO;
import com.jsowell.pile.dto.nanrui.PushAlarmInfoDTO;
import com.jsowell.thirdparty.lianlian.common.CommonResult;
import com.jsowell.thirdparty.lianlian.dto.CommonParamsDTO;
import com.jsowell.thirdparty.lianlian.util.Cryptos;
import com.jsowell.thirdparty.lianlian.util.Encodes;
import com.jsowell.thirdparty.nanrui.service.NRService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 江苏平台 controller
 *
 * @author Lemon
 * @Date 2023/10/11 13:26
 */
@Anonymous
@RestController
@RequestMapping("/jiangsu")
public class NRController extends BaseController {

    @Autowired
    private NRService nrService;

    /**
     * 查询充电站信息
     * @param dto
     */
    @RequestMapping("/v1/query_stations_info")
    public CommonResult<?> query_stations_info(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("江苏平台查询充电站信息 params:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(token)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            Map<String, String> resultMap = nrService.checkoutSign(dto);
            if (resultMap == null) {
                // 签名错误
                return CommonResult.failed("签名校验错误");
            }
            String operatorSecret = resultMap.get("OperatorSecret");
            String dataString = resultMap.get("Data");
            String dataSecret = resultMap.get("DataSecret");
            String dataSecretIV = resultMap.get("DataSecretIV");
            // 解密data
            byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(dataString), dataSecret.getBytes(), dataSecretIV.getBytes());
            String dataStr = new String(plainText, StandardCharsets.UTF_8);
            // 转换成相应对象
            QueryStationInfoDTO queryStationInfoDTO = JSONObject.parseObject(dataStr, QueryStationInfoDTO.class);
            Map<String, String> map = nrService.query_stations_info(queryStationInfoDTO);
            return CommonResult.success(0, "查询充电站信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("江苏平台查询充电站信息 error", e);
        }
        return CommonResult.failed("查询充电站信息异常");
    }


    /**
     * 查询设备接口状态
     * @param dto
     */
    @RequestMapping("/v1/query_station_status")
    public CommonResult<?> query_station_status(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("江苏平台查询设备接口状态 params:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(token)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            Map<String, String> resultMap = nrService.checkoutSign(dto);
            if (resultMap == null) {
                // 签名错误
                return CommonResult.failed("签名校验错误");
            }
            String operatorSecret = resultMap.get("OperatorSecret");
            String dataString = resultMap.get("Data");
            String dataSecret = resultMap.get("DataSecret");
            String dataSecretIV = resultMap.get("DataSecretIV");
            // 解密data
            byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(dataString), dataSecret.getBytes(), dataSecretIV.getBytes());
            String dataStr = new String(plainText, StandardCharsets.UTF_8);
            // 转换成相应对象
            QueryStationInfoDTO queryStationInfoDTO = JSONObject.parseObject(dataStr, QueryStationInfoDTO.class);
            queryStationInfoDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = nrService.query_station_status(queryStationInfoDTO);
            return CommonResult.success(0, "查询设备接口状态成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("江苏平台查询设备接口状态 error", e);
            e.printStackTrace();
        }
        return CommonResult.failed("查询设备接口状态异常");
    }


    /**
     * 查询充电电量信息
     * @param dto
     */
    @RequestMapping("/v1/query_order_info")
    public CommonResult<?> query_order_info(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("江苏平台查询充电电量信息 params:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(token)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 校验签名
            Map<String, String> resultMap = nrService.checkoutSign(dto);
            if (resultMap == null) {
                // 签名错误
                return CommonResult.failed("签名校验错误");
            }
            String operatorSecret = resultMap.get("OperatorSecret");
            String dataString = resultMap.get("Data");
            String dataSecret = resultMap.get("DataSecret");
            String dataSecretIV = resultMap.get("DataSecretIV");
            // 解密data
            byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(dataString), dataSecret.getBytes(), dataSecretIV.getBytes());
            String dataStr = new String(plainText, StandardCharsets.UTF_8);
            // 转换成相应对象
            NRQueryOrderDTO nrQueryOrderDTO = JSONObject.parseObject(dataStr, NRQueryOrderDTO.class);
            nrQueryOrderDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = nrService.query_order_info(nrQueryOrderDTO);
            return CommonResult.success(0, "查询充电电量信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("江苏平台查询充电电量信息 error", e);
        }
        return CommonResult.failed("查询充电电量信息异常");
    }

    /**
     * 获取token接口
     * http://localhost:8080/nanrui/v1/query_token
     */
    @PostMapping("/v1/query_token")
    public CommonResult<?> queryToken(@RequestBody CommonParamsDTO dto) {
        logger.info("江苏平台请求令牌 params:{}", JSONObject.toJSONString(dto));
        try {
            Map<String, String> map = nrService.generateToken(dto);
            logger.info("江苏平台请求令牌 result:{}", JSONObject.toJSONString(map));
            return CommonResult.success(0, "请求令牌成功！", map.get("Data"), map.get("Sig"));
        } catch (UnsupportedEncodingException e) {
            logger.error("获取token接口 异常");
            return CommonResult.failed("获取token发生异常");
        }
    }


    @RequestMapping("/v1/getToken")
    public String getToken(@RequestBody GetTokenDTO dto) {
        String token = nrService.getToken(dto.getUrlAddress(), dto.getOperatorId(), dto.getOperatorSecret(),
                dto.getDataSecretIv(), dto.getSignSecret(), dto.getDataSecret());
        return token;
    }


    /**
     * 推送充电站信息
     * @param dto
     * @return
     */
    @PostMapping("/v1/pushStationInfo")
    public RestApiResponse<?> pushStationInfo(@RequestBody PushStationInfoDTO dto) {
        logger.info("推送江苏平台充电站信息 params:{}", JSONObject.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            if (StringUtils.isBlank(String.valueOf(dto.getStationId()))) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            String s = nrService.pushStationInfo(dto);
            response = new RestApiResponse<>(s);
        }catch (BusinessException e) {
            logger.error("推送江苏平台充电站信息 error",e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        }catch (Exception e) {
            logger.error("推送江苏平台充电站信息 error", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("推送江苏平台充电站信息 result:{}", response);
        return response;
    }


    /**
     * 推送告警信息
     * @param dto
     * @return
     */
    @PostMapping("/v1/pushAlarmInfo")
    public RestApiResponse<?> pushAlarmInfo(@RequestBody PushAlarmInfoDTO dto) {
        logger.info("推送江苏平台告警信息 params:{}", JSONObject.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            if (StringUtils.isBlank(String.valueOf(dto.getStationId()))) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            String s = nrService.pushAlarmInfo(dto);
            response = new RestApiResponse<>(s);
        }catch (BusinessException e) {
            logger.error("推送江苏平台告警信息 error",e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        }catch (Exception e) {
            logger.error("推送江苏平台告警信息 error", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("推送江苏平台告警信息 result:{}", response);
        return response;
    }

    /**
     * 设备状态变化推送
     * @param data
     * @return
     */
    @PostMapping("/v1/pushPileStatus")
    public RestApiResponse<?> pushPileStatus(@RequestBody RealTimeMonitorData data) {
        logger.info("推送江苏平台设备状态变化推送 params:{}", JSONObject.toJSONString(data));
        RestApiResponse<?> response = null;
        try {
            String s = nrService.pushPileStatus(data);
            response = new RestApiResponse<>(s);
        }catch (BusinessException e) {
            logger.error("推送江苏平台设备状态变化推送 error",e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        }catch (Exception e) {
            logger.error("推送江苏平台设备状态变化推送 error", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("推送江苏平台设备状态变化推送 result:{}", response);
        return response;
    }


    /**
     * 充电电量信息推送
     * @param orderCode
     * @return
     */
    @GetMapping("/v1/pushOrderInfo/{orderCode}")
    public RestApiResponse<?> pushOrderInfo(@PathVariable("orderCode") String orderCode) {
        logger.info("江苏平台充电电量信息推送 params:{}", orderCode);
        RestApiResponse<?> response = null;
        try {
            String s = nrService.pushOrderInfo(orderCode);
            response = new RestApiResponse<>(s);
        }catch (BusinessException e) {
            logger.error("江苏平台充电电量信息推送 error",e);
            response = new RestApiResponse<>(e.getCode(), e.getMessage());
        }catch (Exception e) {
            logger.error("江苏平台充电电量信息推送 error", e);
            response = new RestApiResponse<>(e);
        }
        logger.info("江苏平台充电电量信息推送 result:{}", response);
        return response;
    }
}