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

import com.alibaba.fastjson.JSONObject;
import com.jsowell.common.exception.BusinessException;
import com.jsowell.common.util.PageUtils;
import com.jsowell.common.util.StringUtils;
import com.jsowell.pile.domain.OrderBasicInfo;
import com.jsowell.pile.domain.PileBasicInfo;
import com.jsowell.pile.domain.PileStationInfo;
import com.jsowell.pile.dto.amap.GetStationInfoDTO;
import com.jsowell.pile.service.*;
import com.jsowell.pile.vo.base.ConnectorInfoVO;
import com.jsowell.pile.vo.uniapp.BillingPriceVO;
import com.jsowell.pile.vo.uniapp.PileConnectorDetailVO;
import com.jsowell.pile.vo.web.PileModelInfoVO;
import com.jsowell.thirdparty.amap.domain.*;
import com.jsowell.thirdparty.amap.service.AMapService;
import com.jsowell.thirdparty.amap.util.AMapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

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

/**
 * 高德地图Service
 *
 * @author Lemon
 * @Date 2023/6/14 13:54
 */
@Service
public class AMapServiceImpl implements AMapService {

    @Autowired
    private IPileStationInfoService pileStationInfoService;

    @Autowired
    private IPileConnectorInfoService pileConnectorInfoService;

    @Autowired
    private IPileBillingTemplateService pileBillingTemplateService;

    @Autowired
    private IPileBasicInfoService pileBasicInfoService;

    @Autowired
    private IPileModelInfoService pileModelInfoService;

    @Autowired
    private IOrderBasicInfoService orderBasicInfoService;

    /**
     * 高德拉取充电站静态数据
     * @param dto
     * @return
     */
    @Override
    public List<AMapStationInfo> getStationInfos(GetStationInfoDTO dto) {
        List<AMapStationInfo> resultList = new ArrayList<>();

        if (StringUtils.equals("page", dto.getType())) {
            int pageNo = dto.getCurrentPage() == null ? 1 : dto.getCurrentPage();
            int pageSize = dto.getPageSize() == null ? 10 : dto.getPageSize();
            // 设置分页参数
            PageUtils.startPage(pageNo, pageSize);
        }
        // 查询站点信息
        List<PileStationInfo> stationInfos = pileStationInfoService.getStationInfosByThirdParty();
        if (CollectionUtils.isEmpty(stationInfos)) {
            return new ArrayList<>();
        }
        AMapStationInfo aMapInfo;
        // 拼装高德格式数据
        for (PileStationInfo stationInfo : stationInfos) {
            aMapInfo = new AMapStationInfo();

            aMapInfo.setStationID(String.valueOf(stationInfo.getId()));
            aMapInfo.setOperatorID("");
            aMapInfo.setEquipmentOwnerID("");
            aMapInfo.setOperatorName("");
            aMapInfo.setStationName(stationInfo.getStationName());
            aMapInfo.setCountryCode(stationInfo.getCountryCode());
            aMapInfo.setAreaCode(stationInfo.getAreaCode());
            aMapInfo.setAddress(stationInfo.getAddress());
            aMapInfo.setServiceTel(stationInfo.getServiceTel());
            aMapInfo.setStationType(Integer.parseInt(stationInfo.getStationType()));
            aMapInfo.setStationStatus(Integer.parseInt(stationInfo.getStationStatus()));
            Integer openType = Integer.parseInt(stationInfo.getPublicFlag()) == 0 ? 7 : 0;
            aMapInfo.setOpenType(openType);
            aMapInfo.setParkNums(0);
            aMapInfo.setStationLng(new BigDecimal(stationInfo.getStationLng()).setScale(6, BigDecimal.ROUND_HALF_UP));
            aMapInfo.setStationLat(new BigDecimal(stationInfo.getStationLat()).setScale(6, BigDecimal.ROUND_HALF_UP));
            String construction = stationInfo.getConstruction();
            if (StringUtils.equals("12", construction) || StringUtils.equals("13", construction) ||
                    StringUtils.equals("14", construction) || StringUtils.equals("15", construction)) {
                construction = "255";
            }
            aMapInfo.setConstruction(Integer.parseInt(construction));
            aMapInfo.setBusineHours(stationInfo.getBusinessHours());

            List<AMapPriceChargingInfo> priceList = getPriceInfoByStationId(String.valueOf(stationInfo.getId()));
            aMapInfo.setPriceChargingInfo(priceList);

            Map<String, Integer> pileNumMap = pileConnectorInfoService.getPileTypeNum(stationInfo.getId());
            aMapInfo.setFastEquipmentNum(pileNumMap.get("fastTotal"));
            aMapInfo.setSlowEquipmentNum(pileNumMap.get("slowTotal"));

            List<AMapEquipmentInfo> aMapEquipmentInfos = getPileListByStationId(String.valueOf(stationInfo.getId()));
            aMapInfo.setEquipmentInfos(aMapEquipmentInfos);

            resultList.add(aMapInfo);
        }

        return resultList;
    }

    /**
     * 商家推送充电设备动态数据
     * @param pileConnectorCode
     * @return
     * @throws Exception
     */
    @Override
    public String pushChargingDeviceDynamics(String pileConnectorCode) throws Exception {

        // 根据枪口号查出桩信息
        PileConnectorDetailVO pileConnectorDetailVO = pileBasicInfoService.queryPileConnectorDetail(pileConnectorCode);
        if (pileConnectorDetailVO == null) {
            throw new BusinessException("", "");
        }
        String stationId = pileConnectorDetailVO.getStationId();
        Map<String, Integer> pileNumMap = pileConnectorInfoService.getPileTypeNum(Long.parseLong(stationId));

        AMapConnectorStatusInfo info = new AMapConnectorStatusInfo();
        info.setConnectorID(pileConnectorCode);
        info.setEquipmentID(pileConnectorDetailVO.getPileSn());
        info.setStatus(pileConnectorDetailVO.getConnectorStatus());

        // 拼装业务参数
        JSONObject json = new JSONObject();
        json.put("stationID", stationId);
        json.put("fast_free", pileNumMap.get("fastFree"));
        json.put("fast_total", pileNumMap.get("fastTotal"));
        json.put("slow_free", pileNumMap.get("slowFree"));
        json.put("slow_total", pileNumMap.get("slowTotal"));
        json.put("connectorStatusInfo", info);

        String SPI = "amap.charging.pushStationStatus";

        Map<String, String> map = AMapUtils.generateParamMap(json, SPI);

        // 调用高德接口
        return AMapUtils.sendPost(map);
    }

    /**
     * 商家推送充电订单信息
     * @param orderCode
     * @return
     */
    @Override
    public String pushChargingOrderInfo(String orderCode) {
        // 根据订单编号查询信息
        OrderBasicInfo orderBasicInfo = orderBasicInfoService.getOrderInfoByOrderCode(orderCode);

        // 拼装业务参数
        JSONObject json = new JSONObject();
        json.put("", "");


        return null;
    }


    /**
     * 根据站点id查询计费模板
     * @param StationId
     * @return
     */
    private List<AMapPriceChargingInfo> getPriceInfoByStationId(String StationId) {
        List<AMapPriceChargingInfo> priceList = new ArrayList<>();
        // 查询计费模板
        List<BillingPriceVO> billingPriceList = pileBillingTemplateService.queryBillingPrice(StationId);
        for (BillingPriceVO billingPriceVO : billingPriceList) {
            AMapPriceChargingInfo info = new AMapPriceChargingInfo();
            info.setFeeTime(billingPriceVO.getStartTime() + "-" + billingPriceVO.getEndTime()); // 时间段
            info.setElectricityFee(new BigDecimal(billingPriceVO.getElectricityPrice()).setScale(4, BigDecimal.ROUND_HALF_UP)); // 电费
            info.setServiceFee(new BigDecimal(billingPriceVO.getServicePrice()).setScale(4, BigDecimal.ROUND_HALF_UP)); // 服务费

            priceList.add(info);
        }
        return priceList;
    }


    /**
     * 根据站点查询站点下所有桩
     * @param stationId
     * @return
     */
    private List<AMapEquipmentInfo> getPileListByStationId(String stationId) {
        List<AMapEquipmentInfo> pileList = new ArrayList<>();
        // 根据站点查询站点下所有桩
        List<PileBasicInfo> pileBasicInfoList = pileBasicInfoService.getPileListByStationId(String.valueOf(stationId));
        if (CollectionUtils.isEmpty(pileBasicInfoList)) {
            return new ArrayList<>();
        }
        for (PileBasicInfo pileBasicInfo : pileBasicInfoList) {
            AMapEquipmentInfo info = new AMapEquipmentInfo();

            info.setEquipmentID(pileBasicInfo.getSn());
            info.setManufacturerName("举视");
            // 查询型号
            PileModelInfoVO modelInfo = pileModelInfoService.getPileModelInfoByPileSn(pileBasicInfo.getSn());

            info.setEquipmentType(Integer.parseInt(modelInfo.getSpeedType()));
            info.setPower(new BigDecimal(modelInfo.getRatedPower()).setScale(1, BigDecimal.ROUND_HALF_UP));

            List<AMapConnectorInfo> aMapConnectorInfos = getConnectorListBySN(pileBasicInfo.getSn());

            info.setConnectorInfos(aMapConnectorInfos);

            pileList.add(info);
        }
        return pileList;
    }


    /**
     * 根据桩号查询枪口列表
     * @param pileSn
     * @return
     */
    private List<AMapConnectorInfo> getConnectorListBySN(String pileSn) {
        List<AMapConnectorInfo> list = new ArrayList<>();

        // 根据桩号查询枪口列表
        List<ConnectorInfoVO> connectorInfoList = pileConnectorInfoService.selectConnectorInfoList(pileSn);
        if (CollectionUtils.isEmpty(connectorInfoList)) {
            return new ArrayList<>();
        }

        for (ConnectorInfoVO connectorInfoVO : connectorInfoList) {
            AMapConnectorInfo aMapConnectorInfo = new AMapConnectorInfo();

            aMapConnectorInfo.setConnectorID(connectorInfoVO.getPileConnectorCode());

            Integer connectorType = Integer.parseInt(connectorInfoVO.getChargingType()) == 1 ? 4 : 3;
            aMapConnectorInfo.setConnectorType(connectorType);
            aMapConnectorInfo.setVoltageLowerLimits(0);
            aMapConnectorInfo.setVoltageUpperLimits(Integer.parseInt(connectorInfoVO.getRatedVoltage()));
            aMapConnectorInfo.setCurrent(Integer.parseInt(connectorInfoVO.getRatedCurrent()));
            aMapConnectorInfo.setPower(new BigDecimal(connectorInfoVO.getRatedPower()).setScale(1, BigDecimal.ROUND_HALF_UP));
            aMapConnectorInfo.setNationalStandard(2);
            aMapConnectorInfo.setBrandDesc("举视");

            list.add(aMapConnectorInfo);
        }
        return list;
    }
}
