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.response.RestApiResponse;
import com.jsowell.common.util.JWTUtils;
import com.jsowell.pile.dto.ThirdPartyCommonStartChargeDTO;
import com.jsowell.pile.dto.huawei.*;
import com.jsowell.pile.vo.huawei.QueryChargeStatusVO;
import com.jsowell.pile.vo.huawei.QueryEquipAuthVO;
import com.jsowell.pile.vo.huawei.QueryStartChargeVO;
import com.jsowell.thirdparty.common.CommonService;
import com.jsowell.thirdparty.huawei.HuaweiServiceV2;
import com.jsowell.thirdparty.lianlian.common.CommonResult;
import com.jsowell.thirdparty.lianlian.domain.ConnectorStatusInfo;
import com.jsowell.pile.thirdparty.CommonParamsDTO;
import com.jsowell.thirdparty.platform.util.Cryptos;
import com.jsowell.thirdparty.platform.util.Encodes;
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.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 华为 Controller V2
 *
 * @author Lemon
 * @Date 2024/2/2 14:34:56
 */
@Anonymous
@RestController
@RequestMapping("/huawei")
public class HuaWeiControllerV2 extends BaseController {

    @Autowired
    private HuaweiServiceV2 huaweiServiceV2;

    @Autowired
    private CommonService commonService;

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

    /**
     * 华为设备接口状态变化推送
     * @param dto
     * @return
     */
    @PostMapping("/v2/notification_stationStatus")
    public CommonResult<?> receiveNotificationStationStatus(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("华为设备接口状态变化推送 params:{}", JSON.toJSONString(dto));
        String dataStr = checkAuth(request, dto);
        // 转换成相应对象
        ConnectorStatusInfo connectorStatusInfo = JSONObject.parseObject(dataStr, ConnectorStatusInfo.class);
        connectorStatusInfo.setOperatorId(dto.getOperatorID());
        Map<String, String> map = huaweiServiceV2.receiveNotificationStationStatus(connectorStatusInfo);
        logger.info("华为设备接口状态变化推送 result:{}", map);
        return CommonResult.success(0, "设备接口状态变化推送成功！", map.get("Data"), map.get("Sig"));
    }


    /**
     * 请求设备计费信息
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v2/request_equip_business_policy")
    public CommonResult<?> requestEquipBusinessPolicy(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("华为请求设备计费信息 params:{}", JSON.toJSONString(dto));
        String dataStr = checkAuth(request, dto);
        // 转换成相应对象
        RequestEquipBusinessPolicyDTO requestEquipBusinessPolicyDTO = JSONObject.parseObject(dataStr, RequestEquipBusinessPolicyDTO.class);
        requestEquipBusinessPolicyDTO.setOperatorId(dto.getOperatorID());
        Map<String, String> map = huaweiServiceV2.requestEquipBusinessPolicy(requestEquipBusinessPolicyDTO);
        logger.info("华为请求设备计费信息 result:{}", map);
        return CommonResult.success(0, "请求设备计费信息成功！", map.get("Data"), map.get("Sig"));
    }


    /**
     * 接收启动充电结果
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v2/notification_start_charge_result")
    public CommonResult<?> receiveStartChargeResult(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("接收华为启动充电结果 params:{}", JSON.toJSONString(dto));
        String dataStr = checkAuth(request, dto);
        // 转换成相应对象
        ReceiveStartChargeResultDTO receiveStartChargeResultDTO = JSONObject.parseObject(dataStr, ReceiveStartChargeResultDTO.class);
        // receiveStartChargeResultDTO.setOperatorId(dto.getOperatorID());
        Map<String, String> map = huaweiServiceV2.receiveStartChargeResult(receiveStartChargeResultDTO);
        logger.info("接收华为启动充电结果 result:{}", map);
        return CommonResult.success(0, "推送启动充电结果成功！", map.get("Data"), map.get("Sig"));
    }


    /**
     * 接收设备充电状态
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v2/notification_equip_charge_status")
    public CommonResult<?> receiveEquipChargeStatus(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("接收华为设备充电状态 params:{}", JSON.toJSONString(dto));
        String dataStr = checkAuth(request, dto);
        // 转换成相应对象
        ReceiveEquipChargeStatusDTO receiveEquipChargeStatusDTO = JSONObject.parseObject(dataStr, ReceiveEquipChargeStatusDTO.class);
        // receiveEquipChargeStatusDTO.setOperatorId(dto.getOperatorID());
        Map<String, String> map = huaweiServiceV2.receiveEquipChargeStatus(receiveEquipChargeStatusDTO);
        logger.info("接收华为设备充电状态 result:{}", map);
        return CommonResult.success(0, "接收设备充电状态成功！", map.get("Data"), map.get("Sig"));
    }


    /**
     * 接收华为所推送的停止充电结果
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v2/notification_stop_charge_result")
    public CommonResult<?> receiveStopChargeResult(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("接收华为停止充电结果 params:{}", JSON.toJSONString(dto));
        String dataStr = checkAuth(request, dto);
        // 转换成相应对象
        ReceiveStopChargeResultVO receiveStopChargeResultVO = JSONObject.parseObject(dataStr, ReceiveStopChargeResultVO.class);
        // receiveStopChargeResultVO.setOperatorId(dto.getOperatorID());
        Map<String, String> map = huaweiServiceV2.receiveStopChargeResult(receiveStopChargeResultVO);
        logger.info("接收华为停止充电结果 result:{}", map);
        return CommonResult.success(0, "接收停止充电结果成功！", map.get("Data"), map.get("Sig"));
    }

    /**
     * 接收订单信息
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v2/notification_charge_order_info")
    public CommonResult<?> receiveOrderInfo(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("接收华为订单信息 params:{}", JSON.toJSONString(dto));
        String dataStr = checkAuth(request, dto);
        // 转换成相应对象
        ReceiveOrderInfoDTO receiveOrderInfoDTO = JSONObject.parseObject(dataStr, ReceiveOrderInfoDTO.class);
        // receiveOrderInfoDTO.setOperatorId(dto.getOperatorID());
        Map<String, String> map = huaweiServiceV2.receiveOrderInfo(receiveOrderInfoDTO);
        logger.info("接收华为订单信息 result:{}", map);
        return CommonResult.success(0, "接收订单信息成功！", map.get("Data"), map.get("Sig"));
    }

    /**
     * vin启动充电
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v2/insert_start_charge")
    public CommonResult<?> vinStartCharge(HttpServletRequest request, @RequestBody CommonParamsDTO dto) {
        logger.info("华为vin启动充电 params:{}", JSON.toJSONString(dto));
        String dataStr = checkAuth(request, dto);
        // 转换成相应对象
        VinStartChargeDTO vinStartChargeDTO = JSONObject.parseObject(dataStr, VinStartChargeDTO.class);
        // receiveOrderInfoDTO.setOperatorId(dto.getOperatorID());
        Map<String, String> resultMap = null;
        try {
            resultMap = huaweiServiceV2.vinStartCharge(vinStartChargeDTO);
        } catch (Exception e) {
            logger.error("华为vin启动充电 error", e);
        }
        logger.info("华为vin启动充电 resultMap:{}", resultMap);
        if (resultMap != null) {
            return CommonResult.success(0, "vin启动充电结果", resultMap.get("Data"), resultMap.get("Sig"));
        }else {
            return CommonResult.failed("vin启动充电 error");
        }
    }

    /**
     * 下发计费策略响应
     * @param request
     * @param dto
     * @return
     */
    @PostMapping("/v2/notification_deliver_equip_business_policy_result")
    public CommonResult<?> receiveDeliverEquipBusinessPolicyResult(HttpServletRequest request, @RequestBody CommonParamsDTO dto){
        logger.info("华为下发计费策略响应 params:{}", JSON.toJSONString(dto));
        String dataStr = checkAuth(request, dto);
        // 转换成相应对象
        DeliverBusinessPolicyResponseDTO deliverPolicyResponseDTO = JSONObject.parseObject(dataStr, DeliverBusinessPolicyResponseDTO.class);
        // receiveOrderInfoDTO.setOperatorId(dto.getOperatorID());
        Map<String, String> map = huaweiServiceV2.receiveDeliverEquipBusinessPolicyResult(deliverPolicyResponseDTO);
        logger.info("华为下发计费策略响应 result:{}", map);
        return CommonResult.success(0, "接收下发计费策略响应信息成功！", map.get("Data"), map.get("Sig"));
    }


    // ======================== 以上为  华为 --> 万车充 ========================
    // ======================== 下面为  万车充 --> 华为 ========================


    /**
     * 平台充电设备编码同步
     * @param stationId
     * @return
     */
    @GetMapping("/v2/notification_operation_system_info/{stationId}")
    public RestApiResponse<?> notificationOperationSystemInfo(@PathVariable("stationId") String stationId) {
        // logger.info("华为平台充电设备编码同步 stationId:{}", stationId);
        RestApiResponse<?> response = null;
        String result = null;
        try {
            result = huaweiServiceV2.notificationOperationSystemInfo(stationId);
            response = new RestApiResponse<>(result);
        } catch (Exception e) {
            logger.error("华为平台充电设备编码同步 error", e);
        }
        logger.info("华为平台充电设备编码同步 stationId:{}, result:{}", stationId, result);
        return response;
    }

    /**
     * 设备接口状态查询
     * @param stationIds
     * @return
     */
    @PostMapping("/v2/query_station_status")
    public RestApiResponse<?> queryStationStatus(@RequestBody List<String> stationIds) {
        // logger.info("查询华为设备接口状态 stationIds:{}", stationIds);
        RestApiResponse<?> response = null;
        Map<String, String> map = new LinkedHashMap<>();
        try {
            map = huaweiServiceV2.queryStationStatus(stationIds);
            response = new RestApiResponse<>(map);
        } catch (Exception e) {
            logger.error("查询华为设备接口状态 error", e);
        }
        logger.info("查询华为设备接口状态 stationIds:{}, result:{}", stationIds, map);
        return response;
    }

    /**
     * 请求设备认证
     * @param connectorId
     * @return
     */
    @PostMapping("/v2/query_equip_auth")
    public RestApiResponse<?> queryEquipAuth(@RequestBody String connectorId) {
        // logger.info("请求华为设备认证 connectorId:{}", connectorId);
        RestApiResponse<?> response = null;
        QueryEquipAuthVO vo = null;
        try {
            vo = huaweiServiceV2.queryEquipAuth(connectorId);
            response = new RestApiResponse<>(vo);
        } catch (Exception e) {
            logger.error("请求华为设备认证 error", e);
        }
        logger.info("请求华为设备认证 connectorId:{}, result:{}", connectorId, JSON.toJSONString(vo));
        return response;
    }

    /**
     * 请求启动充电
     * @param dto
     * @return
     */
    @PostMapping("/v2/query_start_charge")
    public RestApiResponse<?> queryStartCharge(@RequestBody HWQueryStartChargeDTO dto) {
        // logger.info("请求华为启动充电 param:{}", JSON.toJSONString(dto));
        RestApiResponse<?> response = null;
        QueryStartChargeVO vo = null;
        try {
            vo = huaweiServiceV2.queryStartCharge(dto);
            response = new RestApiResponse<>(vo);
        } catch (Exception e) {
            logger.error("请求华为启动充电 error", e);
        }
        logger.info("请求华为启动充电 param:{}, result:{}", JSON.toJSONString(dto), JSON.toJSONString(vo));
        return response;
    }


    /**
     * 查询充电状态
     * @param startChargeSeq
     * @return
     */
    @PostMapping("/v2/query_equip_charge_status")
    public RestApiResponse<?> queryChargeStatus(@RequestBody String startChargeSeq) {
        // logger.info("查询华为充电状态 startChargeSeq:{}", startChargeSeq);
        RestApiResponse<?> response = null;
        QueryChargeStatusVO vo = null;
        try {
            vo = huaweiServiceV2.queryChargeStatus(startChargeSeq);
            response = new RestApiResponse<>(vo);
        } catch (Exception e) {
            logger.error("查询华为充电状态 error", e);
        }
        logger.info("查询华为充电状态 startChargeSeq:{}, result:{}", startChargeSeq, JSON.toJSONString(vo));
        return response;
    }


    /**
     * 请求停止充电
     * @param startChargeSeq
     * @return
     */
    @PostMapping("/v2/query_stop_charge")
    public RestApiResponse<?> queryStopCharge(@RequestBody String startChargeSeq) {
        // logger.info("请求华为停止充电 startChargeSeq:{}", startChargeSeq);
        RestApiResponse<?> response = null;
        QueryStartChargeVO vo = null;
        try {
            vo = huaweiServiceV2.queryStopCharge(startChargeSeq);
            response = new RestApiResponse<>(vo);
        }catch (Exception e) {
            logger.error("请求华为停止充电 error", e);
        }
        logger.info("请求华为停止充电 startChargeSeq:{}, result:{}", startChargeSeq, JSON.toJSONString(vo));
        return response;
    }



    @PostMapping("/commonStartCharge")
    public RestApiResponse<?> commonStartCharge(@RequestBody ThirdPartyCommonStartChargeDTO dto) {
        RestApiResponse<?> response = null;
        try {
            String result = commonService.commonQueryStartCharge(dto);
            response = new RestApiResponse<>(result);
        } catch (Exception e) {
            logger.error("统一启动充电接口 error", e);
        }
        logger.info("统一启动充电接口 params:{}, result:{}", JSON.toJSONString(dto), response);
        return response;
    }





    /**
     * 校验令牌
     * @param request
     * @param dto
     * @return
     */
    private String checkAuth(HttpServletRequest request, CommonParamsDTO dto) {
        // 校验令牌
        String token = request.getHeader("Authorization");
        if (!JWTUtils.checkThirdPartyToken(token)) {
            // 校验失败
            logger.error("令牌校验错误");
            return null;
        }
        // 校验签名
        Map<String, String> resultMap = huaweiServiceV2.checkoutSign(dto);
        if (resultMap == null) {
            // 签名错误
            logger.error("令牌校验错误");
            return null;
        }
        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);
        return dataStr;
    }


}
