package com.xhpc.evcs.cyc.api;

import cn.hutool.core.date.DateUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.xhpc.common.data.redis.CacheRateModel;
import com.xhpc.common.data.redis.CacheRealtimeData;
import com.xhpc.evcs.cyc.dto.CYCChargeChargeStatusResponse;
import com.xhpc.evcs.cyc.dto.CYCChargeOrderInfoResponse;
import com.xhpc.evcs.cyc.dto.CYCConnectorChargeStatusInfo;
import com.xhpc.evcs.cyc.dto.CYCNotificationStartChargeResultRequestData;
import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.DTOJsonHelper;
import com.xhpc.evcs.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.notification.CoreDispatcher;
import com.xhpc.evcs.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.evcs.domain.AuthSecretToken.SECRET_TOKEN_TYPE_OUT;

@Slf4j
@RestController
public class CYCNotificationStationInfoController extends CoreDispatcher {

    @Resource
    AuthSecretTokenRepository authSecretTokenRepository;
    /**
     * 设备充电中状态变化推送(川逸充)  --已推送
     * 订单结束再推送
     */
    @PostMapping("/v20/getCYCNotificationConnectorChargeStatus")
    public void getCYCNotificationConnectorChargeStatus(@RequestBody Map<String, Object> orderMap){
        //System.out.println("==================设备充电中状态变化推送(川逸充) ==========================");
        //System.out.println("==================设备充电中状态变化推送(川逸充) =============orderMap============="+orderMap.toString());
        //先查订单号 在查实时数据 最后计算金额
        try {
            String orderNo = orderMap.get("orderNo").toString();
            CacheRealtimeData lord = REDIS.getCacheObject("order:"+orderNo+".lord");
            String formatTime = DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss");
            Map<String, Object> cacheMap =REDIS.getCacheMap("order:"+orderNo+".notification");
            if(cacheMap==null || cacheMap.get("startTime")==null || "".equals(cacheMap.get("startTime"))){
                cacheMap.put("lastPushTime", formatTime);
            }else{
                cacheMap.put("lastPushTime", cacheMap.get("pushTime"));
            }
            cacheMap.put("pushTime", formatTime);
            CYCConnectorChargeStatusInfo cdConnectorChargeStatusInfo = new CYCConnectorChargeStatusInfo();
            Map<String, Object> cacheMapOrder = REDIS.getCacheMap("order:"+orderNo);
            if(cacheMap.get("startTime")==null ){
                if(cacheMapOrder !=null && cacheMapOrder.get("startTime")!=null){
                    cdConnectorChargeStatusInfo.setStartTime(cacheMapOrder.get("startTime").toString());
                    cacheMap.put("startTime", cacheMapOrder.get("startTime").toString());
                }
            }else{
                cdConnectorChargeStatusInfo.setStartTime(cacheMap.get("startTime").toString());
            }
            if(cacheMapOrder !=null && cacheMapOrder.get("status")!=null){
                if("已结束".equals(cacheMapOrder.get("status").toString())){
                    cdConnectorChargeStatusInfo.setConnectorStatus(1);
                    cdConnectorChargeStatusInfo.setStartChargeSeqStat(4);
                    //cdConnectorChargeStatusInfo.setSoc((double)cacheMapOrder.get("endSoc"));
                }else{
                    cdConnectorChargeStatusInfo.setConnectorStatus(3);
                    cdConnectorChargeStatusInfo.setStartChargeSeqStat(2);
                }
            }
            REDIS.setCacheMap("order:"+orderNo+".notification",cacheMap);

            Map<String, Object> pushOrder = REDIS.getCacheMap("pushOrder:"+orderNo);
            cdConnectorChargeStatusInfo.setStartChargeSeq((String) pushOrder.get("internetSerialNumber"));
            cdConnectorChargeStatusInfo.setConnectorID(lord.getPileNo()+lord.getGunId());
            cdConnectorChargeStatusInfo.setCurrentA((double)(lord.getWorkingCurrent()/10));
            cdConnectorChargeStatusInfo.setVoltageA((double)(lord.getWorkingVoltage()/10));

            cdConnectorChargeStatusInfo.setEndTime(formatTime);

            BigDecimal chargingDegree = new BigDecimal(lord.getChargingDegree()).divide(new BigDecimal(10000).setScale(2, BigDecimal.ROUND_UP));
            cdConnectorChargeStatusInfo.setTotalPower(chargingDegree.setScale(2,BigDecimal.ROUND_CEILING).doubleValue());

            Map<String, Object> cacheOrder = REDIS.getCacheMap("order:" + orderNo);

            if(cacheOrder !=null && cacheOrder.get("rateModelId") !=null){

                cdConnectorChargeStatusInfo.setElecMoney(new BigDecimal(orderMap.get("elecMoney").toString()).doubleValue());
                cdConnectorChargeStatusInfo.setSeviceMoney(new BigDecimal(orderMap.get("seviceMoney").toString()).doubleValue());
                cdConnectorChargeStatusInfo.setTotalMoney(new BigDecimal(orderMap.get("totalMoney").toString()).doubleValue());
                AuthSecretToken authSecretTokenOut = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType("MA6CC2LK7", SECRET_TOKEN_TYPE_OUT).orElse(null);
                //Map<String, Object> map =new HashMap<>();
                //map.put("ConnectorChargeStatusInfo",cdConnectorChargeStatusInfo);
                String data = JSONUtil.toJSONString(cdConnectorChargeStatusInfo);
               // System.out.println("===川逸充设备充电中状态变化推送====data========"+data);
                CommonRequest<Object> commonRequest = new CommonRequest<>();
                commonRequest.setData(data);
                String result = ok(commonRequest, "/notification_equip_charge_status", authSecretTokenOut);
              //  System.out.println("===川逸充设备充电中状态变化推送====result========"+result);
                CYCChargeChargeStatusResponse chargeStatusResponse = DTOJsonHelper.parseResponseData(result, CYCChargeChargeStatusResponse.class, authSecretTokenOut);

              //  System.out.println("===川逸充设备充电中状态变化推送====cycChargeOrderInfoResponse========"+chargeStatusResponse.toString());
            }
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
    }


    @PostMapping("/v20/getCYCNotificationStartChargeResult")
    public void getCYCNotificationStartChargeResult(@RequestBody Map<String, Object> orderMap)throws Exception {

        Optional<AuthSecretToken> authSecretToken =
                authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType("MA6CC2LK7",SECRET_TOKEN_TYPE_OUT);

        if(authSecretToken !=null){
            String orderNo = orderMap.get("orderNo").toString();

            Map<String, Object> pushOrder = REDIS.getCacheMap("pushOrder:"+orderNo);
            if (authSecretToken.isPresent()) {
                CYCNotificationStartChargeResultRequestData notificationStartChargeResultRequestData =
                        new CYCNotificationStartChargeResultRequestData();
                notificationStartChargeResultRequestData.setStartChargeSeq((String) pushOrder.get("internetSerialNumber"));
                notificationStartChargeResultRequestData.setStartChargeSeqStat((Integer) pushOrder.get("startChargeSeqStat"));
                notificationStartChargeResultRequestData.setConnectorId((String) pushOrder.get("connectorID"));
                notificationStartChargeResultRequestData.setStartTime((String) pushOrder.get("startTime"));
                notificationStartChargeResultRequestData.setMobile((String) pushOrder.get("phone"));

                String data = JSONUtil.toJSONString(notificationStartChargeResultRequestData);
                CommonRequest<CYCNotificationStartChargeResultRequestData> commonRequest = new CommonRequest<>();
                commonRequest.setOperatorId("MA6DFCTD5");

                commonRequest.setData(data);

                String result = ok(commonRequest, "/notification_start_charge_result", authSecretToken.get());

               // System.out.println("===川逸充启动结果推送====result========"+result);
                CYCChargeOrderInfoResponse cycChargeOrderInfoResponse = DTOJsonHelper.parseResponseData(result, CYCChargeOrderInfoResponse.class, authSecretToken.get());

               // System.out.println("===川逸充设备充电中状态变化推送====cycChargeOrderInfoResponse========"+cycChargeOrderInfoResponse.toString());
            }
        }else{
           // System.out.println("===川逸充启动结果失败====result========");
        }
    }


    @PostMapping("/v20/token")
    public void token(@RequestBody Map<String, Object> orderMap)throws Exception {

        Optional<AuthSecretToken> authSecretToken = authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType("MA6CC2LK7",SECRET_TOKEN_TYPE_OUT);

//        if(authSecretToken !=null){
//                Map<String,Object> map =new HashMap<>();
//                map.put("OperatorID","MA6DFCTD5");
//                map.put("OperatorSecret","9jG8qysc5RxdbjvnvdmuRYQg6J82FwjL");
//                String data = JSONUtil.toJSONString(map);
//                CommonRequest commonRequest = new CommonRequest<>();
//                commonRequest.setOperatorId("MA6DFCTD5");
//                commonRequest.setData(data);
//                String result = ok(commonRequest, "/query_token", authSecretToken.get());
//                System.out.println("===川逸充获取token====result========"+result);
//        }else{
//            System.out.println("===川逸充获取token====result========");
//        }

        String result="{\"Ret\":0,\"Msg\":\"\",\"Data\":\"pCA3UNQO1CqxRS6KvcNDpw==\",\"Sig\":\"FCCCA9489FAD972722FB00E4E207F581\"}";

        //String result="pCA3UNQO1CqxRS6KvcNDpw==";
        CYCChargeOrderInfoResponse cycChargeOrderInfoResponse = DTOJsonHelper.parseResponseData(result, CYCChargeOrderInfoResponse.class, authSecretToken.get());

       // System.out.println("===川逸充设备充电中状态变化推送====cycChargeOrderInfoResponse========"+cycChargeOrderInfoResponse.toString());


    }






}
