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.WindStationDataEntity;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.impl.WindStationDataServiceImpl;
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.WindStationDataVO;
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 FDZJCServiceImpl implements IJXDZService {
    @Autowired
    JXDZUtils jxdzUtils;
    @Autowired
    WindStationDataServiceImpl windStationDataService;

    @Override
    public void backupData(List list, Long dateTime) {
        if (CollectionUtil.isNotEmpty(list)) {
            List<WindStationDataEntity> windStationDataEntityList = new ArrayList<>();
            list.forEach(item -> {
                WindStationDataEntity windStationDataEntity = BeanUtil.copyProperties(item, WindStationDataEntity.class);
                windStationDataEntity.setDateTime(dateTime);
                windStationDataEntityList.add(windStationDataEntity);
            });
            windStationDataService.saveBatch(windStationDataEntityList);
        }
    }

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

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

    /**
     * 补充部盾提供的数据
     * @param windStationDataVO
     */
    private void supplementBDData(WindStationDataVO windStationDataVO, String code) {
        JSONObject jsonObject = new JSONObject();
        if (JXDZCodeEnum.XZ.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=1701779143491878913&station_type=FAN";
            jsonObject = jxdzUtils.sendCoreGetRequest(url);
        }
        if (0 == jsonObject.getInteger("status")) {
            JSONObject data = jsonObject.getJSONObject("data");
            if (!Objects.isNull(data)) {
                windStationDataVO.setLossElectricity(data.getDouble("loss_of_electricity_day"));
                windStationDataVO.setOnGridEnergyDaily(data.getDouble("on_grid_energy_day"));
                windStationDataVO.setOnGridEnergyMonth(data.getDouble("on_grid_energy_month"));
                windStationDataVO.setOnGridEnergyYear(data.getDouble("on_grid_energy_year")/10000);
                windStationDataVO.setOnGridEnergyGross(data.getDouble("on_grid_energy")/10000);
                windStationDataVO.setGenerationGross(data.getDouble("generating_capacity")/10000);
            }
        }
    }

    /**
     * 补充电站数据
     * @param result
     * @param windStationDataVO
     */
    private void supplementStationData(JSONArray result, WindStationDataVO windStationDataVO) {
        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)) {
                        windStationDataVO.setGenerationPower(jsonObject.getDouble("value"));
                    }
                    if ("瞬时平均风速".equals(pointName)) {
                        windStationDataVO.setWindSpeed(jsonObject.getDouble("value"));
                    }
                    if ("风向".equals(pointName)) {
                        windStationDataVO.setWindDirection(jsonObject.getDouble("value"));
                    }
                    if ("日发电量总和".equals(pointName)) {
                        windStationDataVO.setGenerationDaily(jsonObject.getDouble("value"));
                    }
                    if ("月发电量总和".equals(pointName)) {
                        windStationDataVO.setGenerationMonth(jsonObject.getDouble("value"));
                    }
                    if ("年发电量总和".equals(pointName)) {
                        windStationDataVO.setGenerationYear(jsonObject.getDouble("value"));
                    }
                    if ("日利用小时数".equals(pointName)) {
                        windStationDataVO.setUtilizeHours(jsonObject.getDouble("value"));
                    }
                }
            }
        }
    }

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