package com.xhpc.evcs.api;

import com.xhpc.common.data.redis.CacheRateModel;
import com.xhpc.common.data.redis.CacheRealtimeData;
import com.xhpc.evcs.domain.EtOrderMapping;
import com.xhpc.evcs.dto.ChargeInfoRequest;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.CommonResponse;
import com.xhpc.evcs.dto.EquipChargeStatus;
import com.xhpc.evcs.encryption.EvcsConst;
import com.xhpc.evcs.jpa.OrderMappingRepository;
import com.xhpc.evcs.jpa.XhpcHistoryOrderRepository;
import com.xhpc.evcs.utils.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;
import static com.xhpc.evcs.notification.NotificationEquipChargeStatusTask.calculateEm;
import static com.xhpc.evcs.utils.DateUtil.orderNo2DateStr;

@Slf4j
@RestController()
public class QueryEquipChargeStatusController {

    @Autowired
    XhpcHistoryOrderRepository xhpcHistoryOrderRepository;
    @Autowired
    OrderMappingRepository orderMappingRepository;

    /**
     * 查询充电状态
     * @param commonRequest
     * @return
     * @throws IOException
     */
    @PostMapping("/v1/query_equip_charge_status")
    public CommonResponse queryEquipChargeStatus(@RequestBody CommonRequest<ChargeInfoRequest> commonRequest) throws IOException {
        //创建数据实体类
        EquipChargeStatus equipChargeStatus = new EquipChargeStatus();
        //充电订单号 三方传进来都是27位
        String data = commonRequest.getData();
        ChargeInfoRequest chargeInfoRequest = JSONUtil.readParams(data, ChargeInfoRequest.class);
        CommonResponse response = new CommonResponse();
        if (chargeInfoRequest == null) {
            response.setRet(EvcsConst.RET_FAIL);
            response.setMsg("Request or token params validation failed");
        } else {
            String startChargeSeq = chargeInfoRequest.getStartChargeSeq();
            equipChargeStatus.setStartChargeSeq(startChargeSeq);
            //充电订单状态
            EtOrderMapping etOrderMapping = orderMappingRepository.findByEvcsOrderNo(startChargeSeq).orElse(null);
            if (etOrderMapping == null) {
                response.setRet(EvcsConst.RET_FAIL);
                response.setMsg("Order not found/started");
                log.error("3rdpty order[{}] not found", startChargeSeq);
                return response;
            }
            String internalOrderNum = etOrderMapping.getXhOrderNo();
            Map<String, Object> cacheOrder = REDIS.getCacheMap("order:" + internalOrderNum);
            if (cacheOrder == null) {
                response.setRet(EvcsConst.RET_FAIL);
                response.setMsg("Order cache data not found");
            } else {
                String orderStatus = (String) cacheOrder.get("status");
                int startChargeSeqStat;
                if (orderStatus == null) {
                    startChargeSeqStat = 5;
                } else switch (orderStatus) {
                    case "启动中":
                        startChargeSeqStat = 1;
                        break;
                    case "充电中":
                        startChargeSeqStat = 2;
                        break;
                    case "停止中":
                        startChargeSeqStat = 3;
                        break;
                    case "已结束":
                        startChargeSeqStat = 4;
                        break;
                    default:
                        startChargeSeqStat = 5;
                        break;
                }
                equipChargeStatus.setStartChargeSeqStat(startChargeSeqStat);
                //充电设备接口编码
                String connectorId = internalOrderNum.substring(0, 16);
                equipChargeStatus.setConnectorID(connectorId);
                //充电设备接口状态
                Map<String, Object> cacheGunData = REDIS.getCacheMap("gun:" + connectorId);
                String gunStatus = (String) cacheGunData.get("status");
                int connectorStatus = 0;
                switch (gunStatus) {
                    case "空闲":
                        connectorStatus = 1;
                        break;
                    case "离线":
                        connectorStatus = 2;
                        break;
                    case "故障":
                        connectorStatus = 255;
                        break;
                    default:
                        connectorStatus = 3;
                        break;
                }
                equipChargeStatus.setConnectorStatus(connectorStatus);
                //A相电流
                Double current = (Double) cacheGunData.get("current");
                equipChargeStatus.setCurrentA(current);
                //A相电压
                Double voltage = (Double) cacheGunData.get("voltage");
                equipChargeStatus.setVoltageA(voltage);
                //电池剩余电量
                Integer endSoc = (Integer) cacheOrder.get("endSoc");
                Double soc = Double.valueOf(endSoc == null ? 0 : endSoc);
                equipChargeStatus.setSoc(soc);
                //开始充电时间
                String startTime = (String) cacheOrder.get("startTime");
                if (startTime == null) startTime = orderNo2DateStr(internalOrderNum);
                equipChargeStatus.setStartTime(startTime);
                //本次采样时间 直接new一个当前时间的Date就可以了
                CacheRealtimeData lord = REDIS.getCacheObject("order:" + internalOrderNum + ".lord");
                if (lord != null) {
                    equipChargeStatus.setEndTime(lord.getCreateTime());
                    equipChargeStatus.setTotalMoney(lord.getAmountCharged() / 10000.0);
                    equipChargeStatus.setTotalPower(lord.getChargingDegree() / 10000.0);
                } else {
                    equipChargeStatus.setEndTime(equipChargeStatus.getStartTime());
                    equipChargeStatus.setTotalMoney(0.0);
                    equipChargeStatus.setTotalPower(0.0);
                }
                Integer chargeModel = (Integer) cacheOrder.get("chargeModel");
                equipChargeStatus.setChargeModel(chargeModel == null ? 0 : chargeModel);
                final Long rateModelId = REDIS.getCacheMapValue("pile:".concat(connectorId.substring(0, 14)), "rateModelId");
                final CacheRateModel cacheRateModel = REDIS.getCacheObject("rateModel:" + rateModelId);
                calculateEm(equipChargeStatus, cacheRateModel);
                response.setRet(EvcsConst.RET_SUCC);
                response.setData(JSONUtil.toJSONString(equipChargeStatus));
                response.setMsg("success");
            }
        }
        return response;
    }
}
