package com.yeejoin.amos.boot.module.jxiop.biz.jxdz.factory;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.Enum.JXDZAccessTypeEnum;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.Enum.JXDZCodeEnum;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.entity.PvStationDataEntity;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.impl.PvStationDataServiceImpl;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.utils.JXDZUtils;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.vo.NeedDataVO;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.vo.PvStationDataVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;

@Service
public class GFDZJCServiceImpl implements IJXDZService {
    @Autowired
    JXDZUtils jxdzUtils;
    @Autowired
    PvStationDataServiceImpl pvStationDataService;

    @Override
    public void backupData(List list, Long dateTime) {
        Date date = new Date();
        if (CollectionUtil.isNotEmpty(list)) {
            List<PvStationDataEntity> pvStationDataEntityList = new ArrayList<>();
            list.forEach(item -> {
                PvStationDataEntity pvStationDataEntity = BeanUtil.copyProperties(item, PvStationDataEntity.class);
                pvStationDataEntity.setDateTime(dateTime);
                pvStationDataEntity.setRecDate(date);
                pvStationDataEntityList.add(pvStationDataEntity);
            });
            pvStationDataService.saveBatch(pvStationDataEntityList);
        }
    }

    @Override
    public List buildData(Integer accessType, Long dateTime) {
        List<PvStationDataVO> list = new ArrayList<>();
        if (JXDZAccessTypeEnum.BULU.getCode().equals(accessType)) {
            List<PvStationDataEntity> windStationDataEntityList = pvStationDataService.list(new LambdaQueryWrapper<PvStationDataEntity>().eq(PvStationDataEntity::getDateTime, dateTime));
            list = BeanUtil.copyToList(windStationDataEntityList, PvStationDataVO.class);
        } else {
            list.add(getBusinessData(JXDZCodeEnum.GF.getCode(), JXDZCodeEnum.GF.getRemark()));
        }
        return list;
    }

    private PvStationDataVO getBusinessData(String code, String name) {
        PvStationDataVO pvStationDataVO = new PvStationDataVO();
        if (JXDZCodeEnum.GF.getCode().equals(code)) {
            pvStationDataVO.setCode(JXDZUtils.GF_CODE);
        } else {
            pvStationDataVO.setCode(code);
        }
        pvStationDataVO.setName(name);
        //调用core 接口
        JSONObject jsonObject = new JSONObject();
        if (JXDZCodeEnum.GF.getCode().equals(code)) {
            String url = "/core/datastorage/gateway/point/list?groupId=1770308721235230721&dataType=analog";
            jsonObject = jxdzUtils.sendCoreGetRequest(url);
        }
        if (jsonObject.getInteger("status") == HttpStatus.OK.value()) {
            //补充电站测点信息
            supplementStationData(jsonObject.getJSONArray("result"), pvStationDataVO);
            supplementBDData(pvStationDataVO, code);
        }
        return pvStationDataVO;
    }

    /**
     * 补充损失电量
     * @param pvStationDataVO
     * @param code
     */
    private void supplementBDData(PvStationDataVO pvStationDataVO, String code) {
        JSONObject jsonObject = new JSONObject();
        if (JXDZCodeEnum.GF.getCode().equals(code)) {
            String yesterday = null;
            try {
                yesterday = DateUtils.dateFormat(Date.from(LocalDate.now().minusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant()), "yyyy-MM-dd");
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
            String url = "/screen_api?method=scene_screen.large_screen.get_loss_of_electricity&reporting_data=" + yesterday + "&source_station_id=1701778419827638274&station_type=PV";
            jsonObject = jxdzUtils.sendCoreGetRequest(url);

        }
        if (0 == jsonObject.getInteger("status")) {
            JSONObject data = jsonObject.getJSONObject("data");
            if (!Objects.isNull(data)) {
                pvStationDataVO.setLossElectricity(data.getDouble("loss_of_electricity_day"));
                pvStationDataVO.setOnGridEnergyDaily(data.getDouble("on_grid_energy_day"));
                pvStationDataVO.setOnGridEnergyMonth(data.getDouble("on_grid_energy_month"));
                pvStationDataVO.setOnGridEnergyYear(data.getDouble("on_grid_energy_year")/10000);
                pvStationDataVO.setOnGridEnergyGross(data.getDouble("on_grid_energy")/10000);
                pvStationDataVO.setGenerationGross(data.getDouble("generating_capacity")/10000);
            }
        }
    }

    /**
     * 补充场站数据
     * @param result
     * @param pvStationDataVO
     */
    private void supplementStationData(JSONArray result, PvStationDataVO pvStationDataVO) {
        if (CollectionUtil.isNotEmpty(result)) {
            for (Object o : result) {
                if (o instanceof Map) {
                    Map map = (Map) o;
                    JSONObject jsonObject = new JSONObject(map);
                    String pointName = (String) map.get("pointName");
                    if ("发电功率".equals(pointName)) {
                        pvStationDataVO.setGenerationPower((Double) map.get("value"));
                    }
                    if ("总辐射".equals(pointName)) {
                        pvStationDataVO.setTotalRadiation(jsonObject.getDouble("value"));
                    }
                    if ("直接辐射".equals(pointName)) {
                        pvStationDataVO.setDirectRadiation(jsonObject.getDouble("value"));
                    }
                    if ("散射辐射".equals(pointName)) {
                        pvStationDataVO.setScatterRadiation(jsonObject.getDouble("value"));
                    }
                    if ("直接辐照度".equals(pointName)) {
                        pvStationDataVO.setDirectIrradiance(jsonObject.getDouble("value"));
                    }
                    if ("总辐照度".equals(pointName)) {
                        pvStationDataVO.setTotalIrradiance(jsonObject.getDouble("value"));
                    }
                    if ("散射辐照度".equals(pointName)) {
                        pvStationDataVO.setScatterIrradiance(jsonObject.getDouble("value"));
                    }
                    if ("日发电量".equals(pointName)) {
                        pvStationDataVO.setGenerationDaily(jsonObject.getDouble("value"));
                    }
                    if ("月发电量".equals(pointName)) {
                        pvStationDataVO.setGenerationMonth(jsonObject.getDouble("value"));
                    }
                    if ("年发电量".equals(pointName)) {
                        pvStationDataVO.setGenerationYear(jsonObject.getDouble("value"));
                    }
                    if ("利用小时数".equals(pointName)) {
                        pvStationDataVO.setUtilizeHours(jsonObject.getDouble("value"));
                    }
                }
            }
        }
    }


    @Override
    public void sendData(Integer accessType, NeedDataVO needDataVO, List list) {
        if (CollectionUtil.isNotEmpty(list)) {
            jxdzUtils.sendJXDZPostRequest("/ngnsyncjiangxiyw/accesshourdata/pvStationData", accessType, needDataVO, list);
        }
    }

}
