package com.jsowell.api.thirdparty;

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.enums.thirdparty.ThirdPlatformTypeEnum;
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.PushInfoParamDTO;
import com.jsowell.pile.dto.PushRealTimeInfoDTO;
import com.jsowell.pile.dto.PushStationInfoDTO;
import com.jsowell.pile.dto.QueryStationInfoDTO;
import com.jsowell.thirdparty.lianlian.common.CommonResult;
import com.jsowell.pile.thirdparty.CommonParamsDTO;
import com.jsowell.thirdparty.lianlian.service.LianLianService;
import com.jsowell.thirdparty.platform.util.Cryptos;
import com.jsowell.thirdparty.platform.util.Encodes;
import com.jsowell.thirdparty.zhongdianlian.service.ZDLService;
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/9/14 15:31
 */
@Anonymous
@RestController
@RequestMapping("/zdl")
public class ZDLController extends BaseController {
    @Autowired
    private ZDLService zdlService;

    @Autowired
    private LianLianService lianLianService;

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

    /**
     * 中电联平台查询充电站信息
     * http://localhost:8080/zdl/v1/query_stations_info
     * @param dto
     * @return
     */
    @PostMapping("/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 = lianLianService.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());
            queryStationInfoDTO.setThirdPlatformType(ThirdPlatformTypeEnum.NING_BO_PLATFORM.getTypeCode());
            Map<String, String> map = zdlService.queryStationsInfo(queryStationInfoDTO);
            logger.info("中电联平台查询充电站信息 result:{}", JSON.toJSONString(map));
            return CommonResult.success(0, "查询充电站信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("中电联平台查询充电站信息 error:", e);
            e.printStackTrace();
        }
        return CommonResult.failed("查询充电站信息发生异常");
    }

    /**
     * 中电联平台查询统计信息
     * http://localhost:8080/zdl/v1/query_stations_stats
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_station_stats")
    public CommonResult<?> queryStationStats(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 = lianLianService.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 = zdlService.queryStationStats(queryStationInfoDTO);
            logger.info("中电联平台查询统计信息 result:{}", JSON.toJSONString(map));
            return CommonResult.success(0, "查询统计信息成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("中电联平台查询统计信息 error:", e);
            e.printStackTrace();
        }
        return CommonResult.failed("查询统计信息发生异常");
    }

    /**
     * 中电联平台设备接口状态查询
     * http://localhost:8080/zdl/v1/query_stations_status
     * @param dto
     * @return
     */
    @PostMapping("/v1/query_station_status")
    public CommonResult<?> queryStationStatus(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 = lianLianService.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");

            // String dataString = "L31IkD83nw7bm+eWcvfB1U27uIqSBg29+CHyZu6+qlQ=";
            // String dataSecret = "vj3RWNsWIxT5MC2K";
            // String dataSecretIV = "jjkySnGlM3pbOUki";

            // 解密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 = zdlService.queryStationStatus(queryStationInfoDTO);
            logger.info("中电联平台设备接口状态查询 result:{}", JSON.toJSONString(map));
            return CommonResult.success(0, "设备接口状态查询成功！", map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.info("中电联平台设备接口状态查询 error:", e);
            e.printStackTrace();
        }
        return CommonResult.failed("设备接口状态查询发生异常");
    }


    /**
     * 推送充电站信息 notification_stationInfo
     * http://localhost:8080/zdl/v1/pushStationInfo
     * @param dto
     * @return
     */
    @PostMapping("/pushStationInfo")
    public RestApiResponse<?> pushStationInfo(@RequestBody PushStationInfoDTO dto) {
        logger.info("推送中电联平台充电站信息 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            if (StringUtils.isBlank(String.valueOf(dto.getStationId()))) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            zdlService.pushStationInfo(dto);
            response = new RestApiResponse<>();
        }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;
    }

    /**
     * 中电联平台设备状态变化推送
     * http://localhost:8080/zdl/v1/pushStationStatus
     * @param dto
     * @return
     */
    @PostMapping("/pushStationStatus")
    public RestApiResponse<?> pushStationStatus(@RequestBody PushInfoParamDTO dto) {
        logger.info("中电联平台设备状态变化推送 params:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        try {
            if (StringUtils.isBlank(String.valueOf(dto.getPileConnectorCode())) ||
                    StringUtils.isBlank(String.valueOf(dto.getStatus()))) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            PushRealTimeInfoDTO pushRealTimeInfoDTO = new PushRealTimeInfoDTO();
            pushRealTimeInfoDTO.setStatus(dto.getStatus());
            pushRealTimeInfoDTO.setPileConnectorCode(dto.getPileConnectorCode());
            pushRealTimeInfoDTO.setThirdPartyType(ThirdPlatformTypeEnum.NING_BO_PLATFORM.getTypeCode());
            String result = zdlService.notificationStationStatus(pushRealTimeInfoDTO);
            response = new RestApiResponse<>(result);
        }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("/pushOrderInfo/{orderCode}")
    public RestApiResponse<?> pushOrderInfo(@PathVariable("orderCode")String orderCode) {
        logger.info("中电联平台推送订单信息 params:{}", orderCode);
        RestApiResponse<?> response = null;
        try {
            if (StringUtils.isBlank(orderCode)) {
                throw new BusinessException(ReturnCodeEnum.CODE_PARAM_NOT_NULL_ERROR);
            }
            String result = zdlService.pushChargeOrderInfo(orderCode);
            response = new RestApiResponse<>(result);
        }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;
    }
}
