package com.xhpc.evcs.api;

import com.xhpc.common.api.PileOrderService;
import com.xhpc.common.core.domain.R;
import com.xhpc.evcs.domain.AuthSecretToken;
import com.xhpc.evcs.domain.EtOrderMapping;
import com.xhpc.evcs.dto.CommonRequest;
import com.xhpc.evcs.dto.CommonResponse;
import com.xhpc.evcs.dto.StartChargeRequest;
import com.xhpc.evcs.dto.StartChargeResponse;
import com.xhpc.evcs.encryption.EvcsConst;
import com.xhpc.evcs.jpa.AuthSecretTokenRepository;
import com.xhpc.evcs.jpa.OrderMappingRepository;
import com.xhpc.evcs.utils.JSONUtil;
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.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static com.xhpc.common.data.redis.StaticBeanUtil.REDIS;

@RestController
public class QueryStartChargeController {

    @Autowired
    AuthSecretTokenRepository authSecretTokenRepository;
    @Autowired
    private OrderMappingRepository etOrderMappingRepo;
    @Autowired
    private PileOrderService pileOrderService;

    @PostMapping(value = "/v1/query_start_charge")
    public CommonResponse queryStartCharge(@RequestBody CommonRequest<StartChargeRequest> commonRequest) throws Exception {

        CommonResponse resp = new CommonResponse();
        StartChargeResponse startChargeResponse = new StartChargeResponse();
        StartChargeRequest startChargeRequest = JSONUtil.readParams(commonRequest.getData(), StartChargeRequest.class);
        String startChargeSeq = startChargeRequest.getStartChargeSeq();
        String connectorID = startChargeRequest.getConnectorId();
        String operatorId = startChargeSeq.substring(0, 9);
        Optional<AuthSecretToken> authSecretTokenIn =
                authSecretTokenRepository.findByOperatorId3irdptyAndSecretTokenType(operatorId, "IN");
        if (!authSecretTokenIn.isPresent()) {
            startChargeResponse.setSuccStat(1);
            startChargeResponse.setFailReason(3);
            startChargeResponse.setStartChargeSeqStat(5);
            resp.setMsg("This 3rd has no token");
        } else {
            Map<String, Object> cacheGun = REDIS.getCacheMap("gun:".concat(connectorID));
            String terminalStatus = (String) cacheGun.get("vehicleGunStatus");
            String status = (String) cacheGun.get("status");
            if (!"空闲".equals(status)) {
                resp.setMsg("终端状态异常:[".concat(status == null ? "未注册" : status).concat("]"));
                resp.setRet("500");
            } else if ("否".equals(terminalStatus)) {
                resp.setMsg("未插枪");
                resp.setRet("500");
            } else {
                String plateNum = startChargeRequest.getPlateNum();
                plateNum = plateNum == null ? startChargeRequest.getPlateNum2() : plateNum;
                R res = pileOrderService.pileStartUpBy3rd(startChargeSeq, startChargeRequest.getDriverId(),
                        startChargeRequest.getChargingAmt(), plateNum, 0, connectorID);
                startChargeResponse.setStartChargeSeq(startChargeSeq);
                startChargeResponse.setConnectorID(connectorID);
                if (res.getCode() != 200) {
                    if (res.getCode() != 500) {
                        startChargeResponse.setFailReason(res.getCode());
                    } else {
                        startChargeResponse.setFailReason(3);
                    }
                    startChargeResponse.setSuccStat(1);
                    startChargeResponse.setStartChargeSeqStat(4);
                } else {
                    Map<String, Object> etOrderData = (Map<String, Object>) res.getData();
                    EtOrderMapping etOrderMapping = new EtOrderMapping();
                    etOrderMapping.setEvcsOrderNo(startChargeSeq);
                    etOrderMapping.setXhOrderNo(String.valueOf(etOrderData.get("orderNo")));
                    etOrderMappingRepo.save(etOrderMapping);
                    startChargeResponse.setStartChargeSeqStat(1);
                    startChargeResponse.setSuccStat(0);
                    startChargeResponse.setFailReason(0);
                    //insert a gunStatusData to redis
                    Map<String, Object> pushOrder = new HashMap<>();
                    //1 means starting.
                    pushOrder.put("startChargeSeqStat", 1);
                    String orderNo = String.valueOf(etOrderData.get("orderNo"));
                    pushOrder.put("internetSerialNumber", startChargeRequest.getStartChargeSeq());
                    pushOrder.put("connectorID", connectorID);
                    pushOrder.put("startTime", etOrderData.get("startTime"));
                    //0 means needs to be notified.
                    pushOrder.put("startChargeNotificationStat", 0);
                    //0 means needs to be notified.
                    pushOrder.put("chargeOrderInfoNotificationStat", 0);
                    pushOrder.put("operatorId3rdpty", startChargeSeq.substring(0, 9));
                    REDIS.setCacheMap("pushOrder:".concat(orderNo), pushOrder);
                }
                if (res.getCode() != 200) {
                    resp.setRet(EvcsConst.RET_FAIL);
                } else {
                    resp.setRet(EvcsConst.RET_SUCC);
                }
                resp.setMsg(res.getMsg());
            }
        }
        resp.setData(JSONUtil.toJSONString(startChargeResponse));
        return resp;
    }
}
