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.exception.BusinessException;
import com.jsowell.common.response.RestApiResponse;
import com.jsowell.common.util.JWTUtils;
import com.jsowell.pile.domain.ThirdPartyPlatformConfig;
import com.jsowell.pile.dto.PushRealTimeInfoDTO;
import com.jsowell.pile.dto.QueryStartChargeDTO;
import com.jsowell.pile.dto.QueryStationInfoDTO;
import com.jsowell.pile.service.ThirdPartyPlatformConfigService;
import com.jsowell.pile.thirdparty.CommonParamsDTO;
import com.jsowell.thirdparty.lianlian.common.CommonResult;
import com.jsowell.thirdparty.platform.service.ThirdPartyPlatformService;
import com.jsowell.thirdparty.platform.util.Cryptos;
import com.jsowell.thirdparty.platform.util.Encodes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;

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

/**
 * 青海平台Controller
 *
 * @author Lemon
 * @Date 2024/4/18 13:46:26
 */
@Anonymous
@RestController
@RequestMapping("/qinghai/evcs")
public class QingHaiController extends BaseController {

    @Autowired
    @Qualifier("qingHaiPlatformServiceImpl")
    private ThirdPartyPlatformService qingHaiPlatformServiceImpl;

    @Autowired
    private ThirdPartyPlatformConfigService thirdPartyPlatformConfigService;


    /**
     * 获取token接口
     */
    @PostMapping("/v1/query_token")
    public CommonResult<?> queryToken(@RequestBody CommonParamsDTO dto) {
        logger.info("青海平台请求令牌 params:{}", JSON.toJSONString(dto));
        try {
            // Map<String, String> map = lianLianService.generateToken(dto);
            Map<String, String> map = qingHaiPlatformServiceImpl.queryToken(dto);
            logger.info("青海平台请求令牌 result:{}", JSON.toJSONString(map));
            return CommonResult.success(Integer.parseInt(map.get("Ret")), map.get("Msg"), map.get("Data"), map.get("Sig"));
        }catch (BusinessException e) {
            logger.error("青海平台请求令牌 error:{}, {}", e.getCode(), e.getMessage());
            return CommonResult.failed("获取token发生异常");
        } catch (Exception e) {
            logger.error("青海平台请求令牌接口 异常");
            return CommonResult.failed("获取token发生异常");
        }
    }

    /**
     * 查询充电站信息
     * @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("令牌校验错误");
            }

            // 查询配置信息
            ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
            String operatorSecret = platformConfig.getOperatorSecret();
            String dataString = dto.getData();
            String dataSecret = platformConfig.getDataSecret();
            String dataSecretIV = platformConfig.getDataSecretIv();

            // 校验签名
            boolean verifyResult = qingHaiPlatformServiceImpl.verifySignature(dto, platformConfig.getSignSecret());
            if (!verifyResult) {
                // 验签失败
                return CommonResult.failed("签名错误");
            }
            // 解密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.QING_HAI_PLATFORM.getTypeCode());
            Map<String, String> map = qingHaiPlatformServiceImpl.queryStationsInfo(queryStationInfoDTO);
            return CommonResult.success(Integer.parseInt(map.get("Ret")), map.get("Msg"), map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("青海平台查询充电站信息 error", e);
        }
        return CommonResult.failed("查询充电站信息异常");
    }

    /**
     * 查询业务策略信息
     * @param dto
     */
    @RequestMapping("/v1/query_equip_business_policy")
    public CommonResult<?> query_equip_business_policy(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("青海平台查询业务策略信息 params:{}", JSON.toJSONString(dto));
        try {
            // 校验令牌
            String token = request.getHeader("Authorization");
            if (!JWTUtils.checkThirdPartyToken(token)) {
                // 校验失败
                return CommonResult.failed("令牌校验错误");
            }
            // 查询配置信息
            ThirdPartyPlatformConfig platformConfig = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorID());
            String operatorSecret = platformConfig.getOperatorSecret();
            String dataString = dto.getData();
            String dataSecret = platformConfig.getDataSecret();
            String dataSecretIV = platformConfig.getDataSecretIv();

            // 校验签名
            boolean verifyResult = qingHaiPlatformServiceImpl.verifySignature(dto, platformConfig.getSignSecret());
            if (!verifyResult) {
                // 验签失败
                return CommonResult.failed("签名错误");
            }
            // 解密data
            byte[] plainText = Cryptos.aesDecrypt(Encodes.decodeBase64(dataString), dataSecret.getBytes(), dataSecretIV.getBytes());
            String dataStr = new String(plainText, StandardCharsets.UTF_8);
            // 转换成相应对象
            QueryStartChargeDTO queryStartChargeDTO = JSONObject.parseObject(dataStr, QueryStartChargeDTO.class);
            queryStartChargeDTO.setOperatorId(dto.getOperatorID());
            Map<String, String> map = qingHaiPlatformServiceImpl.queryEquipBusinessPolicy(queryStartChargeDTO);
            return CommonResult.success(Integer.parseInt(map.get("Ret")), map.get("Msg"), map.get("Data"), map.get("Sig"));
        } catch (Exception e) {
            logger.error("青海平台查询业务策略信息 error", e);
        }
        return CommonResult.failed("查询业务策略信息异常");
    }

    /**
     * 推送站点功率
     * @param stationIds
     * @return
     */
    @PostMapping("/pushStationPower")
    public RestApiResponse<?> pushStationPower(@RequestBody List<String> stationIds) {
        RestApiResponse<?> response = null;
        try {
            String result = qingHaiPlatformServiceImpl.notificationPowerInfo(stationIds);
            response = new RestApiResponse<>(result);
        }catch (Exception e) {
            logger.error("青海平台推送站点功率 error", e);
        }
        logger.info("青海平台推送站点功率 result:{}", response);
        return response;
    }

    /**
     * 推送设备状态变化
     * @param dto
     * @return
     */
    @PostMapping("/pushRealTimeInfo")
    public RestApiResponse<?> pushStationPower(@RequestBody PushRealTimeInfoDTO dto) {
        RestApiResponse<?> response = null;
        try {
            String result = qingHaiPlatformServiceImpl.notificationStationStatus(dto);
            response = new RestApiResponse<>(result);
        }catch (Exception e) {
            logger.error("青海平台推送设备状态变化 error", e);
        }
        logger.info("青海平台推送设备状态变化 result:{}", response);
        return response;
    }

    /**
     * 推送充电状态
     * @param orderCode
     * @return
     */
    @GetMapping("/notificationEquipChargeStatus/{orderCode}")
    public RestApiResponse<?> notificationEquipChargeStatus(@PathVariable("orderCode") String orderCode) {
        RestApiResponse<?> response = null;
        try {
            String result = qingHaiPlatformServiceImpl.notificationEquipChargeStatus(orderCode);
            response = new RestApiResponse<>(result);
        }catch (Exception e) {
            logger.error("青海平台推送充电状态 error", e);
        }
        logger.info("青海平台推送充电状态 result:{}", response);
        return response;
    }

    /**
     * 推送订单
     * @param orderCode
     * @return
     */
    @GetMapping("/pushOrderInfo/{orderCode}")
    public RestApiResponse<?> pushOrderInfo(@PathVariable("orderCode") String orderCode) {
        RestApiResponse<?> response = null;
        try {
            String result = qingHaiPlatformServiceImpl.notificationChargeOrderInfo(orderCode);
            response = new RestApiResponse<>(result);
        }catch (Exception e) {
            logger.error("青海平台推送订单信息 error", e);
        }
        logger.info("青海平台推送订单信息 result:{}", response);
        return response;
    }

}
