package com.jsowell.thirdparty.zhongdianlian.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.enums.lianlian.LianLianPileStatusEnum;
import com.jsowell.common.enums.ykc.PileStatusEnum;
import com.jsowell.common.util.DateUtils;
import com.jsowell.common.util.PageUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.PileBasicInfo;
import com.jsowell.pile.domain.PileConnectorInfo;
import com.jsowell.pile.domain.PileStationInfo;
import com.jsowell.pile.domain.ThirdPartyPlatformConfig;
import com.jsowell.pile.dto.QueryStationInfoDTO;
import com.jsowell.pile.service.*;
import com.jsowell.pile.vo.web.PileModelInfoVO;
import com.jsowell.thirdparty.lianlian.domain.ConnectorInfo;
import com.jsowell.thirdparty.lianlian.domain.EquipmentInfo;
import com.jsowell.thirdparty.lianlian.domain.StationInfo;
import com.jsowell.thirdparty.lianlian.service.LianLianService;
import com.jsowell.thirdparty.lianlian.util.Cryptos;
import com.jsowell.thirdparty.lianlian.util.Encodes;
import com.jsowell.thirdparty.lianlian.util.GBSignUtils;
import com.jsowell.thirdparty.zhongdianlian.domain.ZDLConnectorInfo;
import com.jsowell.thirdparty.zhongdianlian.domain.ZDLEquipmentInfo;
import com.jsowell.thirdparty.zhongdianlian.domain.ZDLStationInfo;
import com.jsowell.thirdparty.zhongdianlian.dto.ZDLGetTokenDTO;
import com.jsowell.thirdparty.zhongdianlian.service.ZDLService;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 中电联 Service
 *
 * @author Lemon
 * @Date 2023/9/2 13:54
 */
@Service
public class ZDLServiceImpl implements ZDLService {

    @Autowired
    private LianLianService lianLianService;

    @Autowired
    private IPileStationInfoService pileStationInfoService;

    @Autowired
    private IThirdPartyPlatformConfigService thirdPartyPlatformConfigService;

    @Autowired
    private IPileBasicInfoService pileBasicInfoService;

    @Autowired
    private IPileModelInfoService pileModelInfoService;

    @Autowired
    private IPileConnectorInfoService pileConnectorInfoService;

    /**
     * 获取令牌
     * @param dto
     * @return
     */
    @Override
    public String ZDLGetToken(ZDLGetTokenDTO dto) {
        if (dto == null) {
            return null;
        }
        return lianLianService.getToken(dto.getUrlAddress(), dto.getOperatorId(),
                dto.getOperatorSecret(), dto.getDataSecretIv(), dto.getSignSecret(), dto.getDataSecret());
    }

    /**
     * 查询站点信息
     * @return
     */
    @Override
    public Map<String, String> queryStationsInfo(QueryStationInfoDTO dto) {
        List<ZDLStationInfo> resultList = new ArrayList<>();
        int pageNo = dto.getPageNo() == null ? 1 : dto.getPageNo();
        int pageSize = dto.getPageSize() == null ? 10 : dto.getPageSize();

        PageUtils.startPage(pageNo, pageSize);
        List<PileStationInfo> stationInfos = pileStationInfoService.getStationInfosByThirdParty();
        if (CollectionUtils.isEmpty(stationInfos)) {
            // 未查到数据
            return null;
        }
        ThirdPartyPlatformConfig configInfo = thirdPartyPlatformConfigService.getInfoByOperatorId(dto.getOperatorId());
        if (configInfo == null) {
            return null;
        }
        PageInfo<PileStationInfo> pageInfo = new PageInfo<>(stationInfos);
        for (PileStationInfo pileStationInfo : pageInfo.getList()) {
            ZDLStationInfo stationInfo = new ZDLStationInfo();
            stationInfo.setStationId(String.valueOf(pileStationInfo.getId()));
            stationInfo.setOperatorId(Constants.OPERATORID_LIANLIAN); // 组织机构代码
            stationInfo.setEquipmentOwnerId(String.valueOf(pileStationInfo.getMerchantId()));
            stationInfo.setStationName(pileStationInfo.getStationName());
            stationInfo.setCountryCode(pileStationInfo.getCountryCode());
            stationInfo.setAreaCode(pileStationInfo.getAreaCode());
            stationInfo.setAddress(pileStationInfo.getAddress());
            stationInfo.setServiceTel(pileStationInfo.getStationTel());
            stationInfo.setStationType(Integer.parseInt(pileStationInfo.getStationType()));
            stationInfo.setStationStatus(Integer.parseInt(pileStationInfo.getStationStatus()));
            stationInfo.setParkNums(Integer.parseInt(pileStationInfo.getParkNums()));
            stationInfo.setStationLng(new BigDecimal(pileStationInfo.getStationLng()));
            stationInfo.setStationLat(new BigDecimal(pileStationInfo.getStationLat()));
            stationInfo.setConstruction(Integer.parseInt(pileStationInfo.getConstruction()));

            List<ZDLEquipmentInfo> pileList = getPileList(pileStationInfo);
            if (CollectionUtils.isNotEmpty(pileList)) {
                stationInfo.setEquipmentInfos(pileList); // 充电设备信息列表
            }

            resultList.add(stationInfo);
        }
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("PageNo", pageInfo.getPageNum());
        map.put("PageCount", pageInfo.getPages());
        map.put("ItemSize", resultList.size());
        map.put("StationInfos", resultList);

        // 加密
        Map<String, String> resultMap = Maps.newLinkedHashMap();
        // 加密数据
        byte[] encryptText = Cryptos.aesEncrypt(JSONObject.toJSONString(map).getBytes(),
                configInfo.getOperatorSecret().getBytes(), configInfo.getDataSecretIv().getBytes());
        String encryptData = Encodes.encodeBase64(encryptText);

        resultMap.put("Data", encryptData);
        // 生成sig
        String resultSign = GBSignUtils.sign(resultMap, configInfo.getOperatorSecret());
        resultMap.put("Sig", resultSign);

        return resultMap;
    }

    /**
     * 查询统计信息
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, String> queryStationStats(QueryStationInfoDTO dto) {
        return lianLianService.query_station_stats(dto);
    }

    /**
     * 获取桩列表信息
     *
     * @param pileStationInfo
     * @return
     */
    private List<ZDLEquipmentInfo> getPileList(PileStationInfo pileStationInfo) {
        List<ZDLEquipmentInfo> resultList = new ArrayList<>();
        // 通过站点id查询桩基本信息
        List<PileBasicInfo> list = pileBasicInfoService.getPileListByStationId(String.valueOf(pileStationInfo.getId()));
        // 封装成中电联平台对象
        for (PileBasicInfo pileBasicInfo : list) {
            ZDLEquipmentInfo equipmentInfo = new ZDLEquipmentInfo();
            String pileSn = pileBasicInfo.getSn();

            equipmentInfo.setEquipmentId(pileSn);

            PileModelInfoVO modelInfo = pileModelInfoService.getPileModelInfoByPileSn(pileSn);
            equipmentInfo.setEquipmentType(Integer.parseInt(modelInfo.getSpeedType()));
            equipmentInfo.setPower(new BigDecimal(modelInfo.getRatedPower()).setScale(1, BigDecimal.ROUND_HALF_UP));

            List<ZDLConnectorInfo> connectorList = getConnectorList(pileBasicInfo);
            equipmentInfo.setConnectorInfos(connectorList);

            resultList.add(equipmentInfo);
        }
        return resultList;
    }

    /**
     * 获取枪口列表
     *
     * @param pileBasicInfo
     * @return
     */
    private List<ZDLConnectorInfo> getConnectorList(PileBasicInfo pileBasicInfo) {
        List<ZDLConnectorInfo> resultList = new ArrayList<>();

        List<PileConnectorInfo> list = pileConnectorInfoService.selectPileConnectorInfoList(pileBasicInfo.getSn());
        for (PileConnectorInfo pileConnectorInfo : list) {
            ZDLConnectorInfo connectorInfo = new ZDLConnectorInfo();

            connectorInfo.setConnectorId(pileConnectorInfo.getPileConnectorCode());
            String pileSn = pileConnectorInfo.getPileSn();
            PileModelInfoVO modelInfo = pileModelInfoService.getPileModelInfoByPileSn(pileSn);
            int connectorType = StringUtils.equals("1", modelInfo.getSpeedType()) ? 4 : 3;

            connectorInfo.setConnectorType(connectorType);
            // 车位号
            if (StringUtils.isNotBlank(pileConnectorInfo.getParkNo())) {
                connectorInfo.setParkNo(pileConnectorInfo.getParkNo());
            }
            connectorInfo.setVoltageUpperLimits(Integer.valueOf(modelInfo.getRatedVoltage()));
            connectorInfo.setVoltageLowerLimits(Integer.valueOf(modelInfo.getRatedVoltage()));
            connectorInfo.setCurrent(Integer.valueOf(modelInfo.getRatedCurrent()));
            if (!StringUtils.equals(modelInfo.getConnectorNum(), "1")) {
                // 如果不是单枪，则枪口功率需要除以枪口数量
                String ratedPowerStr = modelInfo.getRatedPower();
                BigDecimal ratedPower = new BigDecimal(ratedPowerStr);
                connectorInfo.setPower(ratedPower.divide(new BigDecimal(modelInfo.getConnectorNum()), 1, BigDecimal.ROUND_HALF_UP));
            }else {
                connectorInfo.setPower(new BigDecimal(modelInfo.getRatedPower()).setScale(1, BigDecimal.ROUND_HALF_UP));
            }

            resultList.add(connectorInfo);
        }

        return resultList;
    }
}
