package com.xhpc.evcs.ykc.api;

import com.xhpc.common.data.redis.CacheRateModel;
import com.xhpc.evcs.dto.*;
import com.xhpc.evcs.jpa.XhpcTerminalRepository;
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.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

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

/**
 * 云快充
 *
 * @author yuyang
 * @Date 2026-03-17 13:35
 */
@Slf4j
@RestController
public class YKCQueryEquipBusinessPolicyController {
    @Autowired
    private XhpcTerminalRepository xhpcTerminalRepository;

    /**
     * 查询业务策略信息结果
     * @param commonRequest
     * @return
     * @throws IOException
     */
    @PostMapping("/v50/query_equip_business_policy")
    public CommonResponse queryEquipBusinessPolicy(@RequestBody CommonRequest<EquipBizRequest> commonRequest) throws IOException {
        //获取充电设备接口编码（枪编码）
        EquipBizRequest equipBizRequest = JSONUtil.readParams(commonRequest.getData(), EquipBizRequest.class);
        CommonResponse commonResponse = new CommonResponse();
        if (equipBizRequest == null) {
            commonResponse.setRet("500");
            commonResponse.setMsg("Request or token params validation failed");
        } else {
            String connectorId = equipBizRequest.getConnectorId();
            //获取枪所对应的桩编码
            String pileSerialNumber = xhpcTerminalRepository.selectBySql(connectorId);
            Map<String, Object> cachePile = REDIS.getCacheMap("pile:" + pileSerialNumber);
            if (pileSerialNumber == null || cachePile == null) {
                commonResponse.setMsg("ConnectorID not found");
                commonResponse.setRet("500");
                return commonResponse;
            }
            ArrayList<String> modelTypes = new ArrayList<>();
            //存储时段个数
            ArrayList<Integer> modelCount = new ArrayList<>();
            Long rateModelId = (Long) cachePile.get("rateModelId");
            CacheRateModel rateModel = REDIS.getCacheObject("rateModel:" + rateModelId);
            PolicyInfos[] policyInfosArr = new PolicyInfos[0];
            if (rateModel != null) {
                String[] tfPricesSeq = rateModel.getTfPricesSeq();
                //存储时段
                //建立对应时段的映射Map集合，存放其对应的价格和服务费
                Map<String, Object> timeMap = new HashMap<>();
                //个数计数器
                int count = 0;
                //最后一个时段的前一个时段的下标索引
                int index = 0;
                //遍历获取每一个时段
                for (int i = 0; i < tfPricesSeq.length - 1; i++) {
                    count++;
                    //如果当前时段与后面的时段不相同，则表示当前时段已经结束，添加当前时段到list中,并将其坐标存放到另一个集合中。
                    if (!tfPricesSeq[i].equals(tfPricesSeq[i + 1])) {
                        //将每段时间的索引，赋值
                        index = i;
                        modelTypes.add(tfPricesSeq[i]);
                        modelCount.add(count);
                        //如果这段时段结束，则重置计数器
                        count = 0;
                    }
                }
                //获取最后一个时段的费率值
                String lastModelType = tfPricesSeq[tfPricesSeq.length - 1];
                //放入到类型list中
                modelTypes.add(lastModelType);
                //获取最后一个时段的费率的个数
                int lastCount = (tfPricesSeq.length - 1) - index;
                //放入到个数List中
                modelCount.add(lastCount);

                //获取各个类型的时段的时间区间，并将其存放至timeList集合中。
                //定义一个初始时间段
                String initTime = "000000";
                //添加临时存储变量
                int temp = -1;
                ArrayList<String> timeList = new ArrayList<>();
                //放入必有初始时间
                timeList.add(initTime);
                //根据出现的时段个数确定他们的时间区间,然后存放至List集合中
                int cumulativeHalfHours = 0;
                for (int i = 0; i < modelCount.size() - 1; i++) {
                    cumulativeHalfHours += modelCount.get(i);
                    int hour = cumulativeHalfHours / 2;
                    int minute = (cumulativeHalfHours % 2) * 30;
                    String startTime = String.format("%02d%02d%02d", hour, minute, 0);
                    timeList.add(startTime);
                }
                policyInfosArr = new PolicyInfos[timeList.size()];
                for (int i = 0; i <= timeList.size() - 1; i++) {
                    PolicyInfos policyInfos = new PolicyInfos();
                    policyInfos.setStartTime(timeList.get(i));
                    String modelType = modelTypes.get(i);
                    switch (modelType) {
                        case "00":
                            policyInfos.setServicePrice(BigDecimal.valueOf((long) rateModel.getT1SvcPrice()).divide(BigDecimal.valueOf(100000L)).setScale(4).doubleValue());
                            policyInfos.setElecPrice(BigDecimal.valueOf((long) rateModel.getT1Price()).divide(BigDecimal.valueOf(100000L)).setScale(4).doubleValue());
                            break;
                        case "01":
                            policyInfos.setServicePrice(BigDecimal.valueOf((long) rateModel.getT2SvcPrice()).divide(BigDecimal.valueOf(100000L)).setScale(4).doubleValue());
                            policyInfos.setElecPrice(BigDecimal.valueOf((long) rateModel.getT2Price()).divide(BigDecimal.valueOf(100000L)).setScale(4).doubleValue());
                            break;
                        case "02":
                            policyInfos.setServicePrice(BigDecimal.valueOf((long) rateModel.getT3SvcPrice()).divide(BigDecimal.valueOf(100000L)).setScale(4).doubleValue());
                            policyInfos.setElecPrice(BigDecimal.valueOf((long) rateModel.getT3Price()).divide(BigDecimal.valueOf(100000L)).setScale(4).doubleValue());
                            break;
                        case "03":
                            policyInfos.setServicePrice(BigDecimal.valueOf((long) rateModel.getT4SvcPrice()).divide(BigDecimal.valueOf(100000L)).setScale(4).doubleValue());
                            policyInfos.setElecPrice(BigDecimal.valueOf((long) rateModel.getT4Price()).divide(BigDecimal.valueOf(100000L)).setScale(4).doubleValue());
                            break;
                        default:
                            break;
                    }
                    policyInfosArr[i] = policyInfos;
                }
            }

            //封装数据
            EquipBizResponse equipBizResponse = new EquipBizResponse();
            //业务查询流水号
            equipBizResponse.setEquipBizSeq(equipBizRequest.getEquipBizSeq());
            //充电设备接口编码
            equipBizResponse.setConnectorId(connectorId);
            //操作结果
            equipBizResponse.setSuccStat(0);
            //失败原因
            equipBizResponse.setFailReason(0);
            //总时段数
            equipBizResponse.setSumPeriod(modelTypes.size());
            //计费信息
            equipBizResponse.setPolicyInfos(policyInfosArr);

            //塞入包装类
            commonResponse.setMsg("Query equipment business policy success");
            commonResponse.setRet("0");
            commonResponse.setData(JSONUtil.toJSONString(equipBizResponse));
        }
        return commonResponse;
    }
}
