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

import com.alibaba.fastjson2.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.jsowell.common.constant.Constants;
import com.jsowell.common.enums.thirdparty.ThirdPlatformTypeEnum;
import com.jsowell.common.util.PageUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.*;
import com.jsowell.pile.dto.PushStationInfoDTO;
import com.jsowell.pile.dto.QueryStationInfoDTO;
import com.jsowell.pile.service.*;
import com.jsowell.pile.vo.base.MerchantInfoVO;
import com.jsowell.pile.vo.base.ThirdPartyStationRelationVO;
import com.jsowell.pile.vo.web.PileModelInfoVO;
import com.jsowell.thirdparty.lianlian.dto.CommonParamsDTO;
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.lianlian.util.HttpRequestUtil;
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.io.UnsupportedEncodingException;
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 IPileMerchantInfoService pileMerchantInfoService;

    @Autowired
    private IPileConnectorInfoService pileConnectorInfoService;

    @Autowired
    private IThirdPartyStationRelationService thirdPartyStationRelationService;

    /**
     * 获取令牌
     * @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());
    }

    /**
     * 根据充电站id，推送充电站信息
     * @param dto
     */
    @Override
    public String pushStationInfo(PushStationInfoDTO dto) {
        // 通过id查询站点相关信息
        PileStationInfo pileStationInfo = pileStationInfoService.selectPileStationInfoById(dto.getStationId());
        // 通过站点id查询相关配置信息
        ThirdPartyStationRelation relation = new ThirdPartyStationRelation();
        relation.setStationId(dto.getStationId());
        ThirdPartyStationRelationVO relationInfo = thirdPartyStationRelationService.selectRelationInfo(relation);
        // ThirdPartySettingInfo settingInfo = thirdPartySettingInfoService.getInfoByStationId(dto.getStationId());
        if (relationInfo == null) {
            // 新增
            relation.setThirdPartyType(dto.getThirdPartyType());
            thirdPartyStationRelationService.insertThirdPartyStationRelation(relation);

            relationInfo = thirdPartyStationRelationService.selectRelationInfo(relation);
        }
        String operatorId = relationInfo.getOperatorId();
        String operatorSecret = relationInfo.getOperatorSecret();
        String signSecret = relationInfo.getSignSecret();
        String dataSecret = relationInfo.getDataSecret();
        String dataSecretIv = relationInfo.getDataSecretIv();
        String urlAddress = relationInfo.getUrlAddress();

        // 组装中电联平台所需要的数据格式
        ZDLStationInfo info = ZDLStationInfo.builder()
                .stationId(String.valueOf(dto.getStationId()))
                .operatorId(operatorId)
                // .equipmentOwnerId(Constants.OPERATORID_JIANG_SU)
                .stationName(pileStationInfo.getStationName())
                .countryCode(pileStationInfo.getCountryCode())
                .areaCode(pileStationInfo.getAreaCode())
                .address(pileStationInfo.getAddress())
                .serviceTel(pileStationInfo.getStationTel())
                .stationType(Integer.valueOf(pileStationInfo.getStationType()))
                .stationStatus(Integer.valueOf(pileStationInfo.getStationStatus()))
                .parkNums(Integer.valueOf(pileStationInfo.getParkNums()))
                .stationLng(new BigDecimal(pileStationInfo.getStationLng()))
                .stationLat(new BigDecimal(pileStationInfo.getStationLat()))
                .construction(Integer.valueOf(pileStationInfo.getConstruction()))

                .build();
        // 截取运营商组织机构代码(去除最后一位后的最后九位)
        MerchantInfoVO merchantInfo = pileMerchantInfoService.getMerchantInfo(String.valueOf(pileStationInfo.getMerchantId()));
        String organizationCode = merchantInfo.getOrganizationCode();
        if (organizationCode.length() == 18) {
            String equipmentOwnerId = StringUtils.substring(organizationCode, organizationCode.length() - 10, organizationCode.length() - 1);
            info.setEquipmentOwnerId(equipmentOwnerId);
        }

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

        // 调用中电联平台接口
        String url = urlAddress + "notification_stationInfo";

        JSONObject data = new JSONObject();
        data.put("StationInfo", info);

        String jsonString = JSONObject.toJSONString(data);
        System.out.println("jsonString : " + jsonString);

        // 获取令牌
        ZDLGetTokenDTO tokenDTO = ZDLGetTokenDTO.builder()
                .urlAddress(urlAddress)
                .operatorId(operatorId)
                .operatorSecret(operatorSecret)
                .dataSecret(dataSecret)
                .dataSecretIv(dataSecretIv)
                .signSecret(signSecret)
                .build();
        String token = ZDLGetToken(tokenDTO);
        String result = "";
        if (StringUtils.equals(ThirdPlatformTypeEnum.YONG_CHENG_BO_CHE.getCode(), relationInfo.getThirdPartyType())) {
            result = HttpRequestUtil.YCBCSendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        }else {
            result = HttpRequestUtil.sendPost(token, jsonString, url, dataSecret, dataSecretIv, operatorId, signSecret);
        }

        // System.out.println(result);
        return result;
    }

    public static void main(String[] args) {
        String organizationCode = "91310120MAC13L2Q9P";
        String equipmentOwnerId = StringUtils.substring(organizationCode, organizationCode.length() - 10, organizationCode.length() - 1);
        System.out.println(equipmentOwnerId); // MAC13L2Q9
    }

    /**
     * 查询站点信息
     * @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_JIANG_SU); // 组织机构代码
            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.getDataSecret().getBytes(), configInfo.getDataSecretIv().getBytes());
        String encryptData = Encodes.encodeBase64(encryptText);

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

        return resultMap;
    }

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

    /**
     * 设备接口状态查询
     * 此接口用于批量查询设备实时状态
     *
     * @param dto
     * @return
     */
    @Override
    public Map<String, String> queryStationStatus(QueryStationInfoDTO dto) {
        return lianLianService.query_station_status(dto);
    }

    /**
     * 设备状态变化推送
     * @param pileConnectorCode
     * @param status
     * @return
     */
    @Override
    public String notificationStationStatus(String pileConnectorCode, String status) {
        return lianLianService.pushConnectorStatus(pileConnectorCode, status);
    }

    /**
     * 推送充电订单信息
     * @param orderCode
     * @return
     */
    @Override
    public String pushChargeOrderInfo(String orderCode) {
        return lianLianService.pushChargeOrderInfo(orderCode);
    }

    /**
     * 生成令牌
     * @param dto
     * @return
     */
    @Override
    public Map<String, String> generateToken(CommonParamsDTO dto) throws UnsupportedEncodingException {
        return lianLianService.generateToken(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()));
            connectorInfo.setNationalStandard(2);
            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;
    }
}
