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.api.mapper.MockStationDailyDataMapper;
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.MockStationDailyDataEntity;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.entity.StationDailyDataEntity;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.impl.StationDailyDataServiceImpl;
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.StationDailyDataVO;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.JXDZMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
public class DZMTSJServiceImpl implements IJXDZService {
    @Autowired
    JXDZUtils jxdzUtils;
    @Autowired
    StationDailyDataServiceImpl stationDailyDataService;
    @Autowired
    JXDZMapper jxdzMapper;
    @Autowired
    MockStationDailyDataMapper  mockStationDailyDataMapper;

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List buildData(Integer accessType, Long dateTime) {
        List<StationDailyDataVO> list = new ArrayList<>();
        if (JXDZAccessTypeEnum.BULU.getCode().equals(accessType)) {
            List<StationDailyDataEntity> stationDailyDataEntityList = stationDailyDataService.list(new LambdaQueryWrapper<StationDailyDataEntity>().eq(StationDailyDataEntity::getDateTime, dateTime));
            list = BeanUtil.copyToList(stationDailyDataEntityList, StationDailyDataVO.class);
        } else {
            list.add(getBusinessData(JXDZCodeEnum.XZ.getCode(), JXDZCodeEnum.XZ.getRemark()));
            list.add(getBusinessData(JXDZCodeEnum.GF.getCode(), JXDZCodeEnum.GF.getRemark()));
        }
        return list;
    }

    /**
     * 获取业务数据
     * @param code
     * @param name
     * @return
     */
    private StationDailyDataVO getBusinessData(String code, String name) {
        StationDailyDataVO stationDailyDataVO = new StationDailyDataVO();
        if(JXDZCodeEnum.XZ.getCode().equals(code)){
            stationDailyDataVO.setCode(JXDZUtils.XZ_CODE);
        }else if(JXDZCodeEnum.GF.getCode().equals(code)){
            stationDailyDataVO.setCode(JXDZUtils.GF_CODE);
        }else {
            stationDailyDataVO.setCode(code);
        }
        stationDailyDataVO.setName(name);
        stationDailyDataVO.setWorkTicketTotalNums(jxdzMapper.countWorkTicketTotalByCode(code).doubleValue());
        stationDailyDataVO.setWorkTicketProcessingNums(jxdzMapper.countWorkTicketProcessingByCode(code).doubleValue());
        stationDailyDataVO.setWorkTicketInvalidatedNums(jxdzMapper.countWorkTicketInvalidatedByCode(code).doubleValue());
        stationDailyDataVO.setWorkTicketExecutingNums(Double.valueOf(0));
        stationDailyDataVO.setWorkTicketTerminatedNums(jxdzMapper.countWorkTicketTerminatedByCode(code).doubleValue());
        stationDailyDataVO.setRegularTasksNums(jxdzMapper.countRegularTasksByCode(code).doubleValue());
        stationDailyDataVO.setInspectionTasksNums(jxdzMapper.countInspectionTasksByCode(code).doubleValue());
        stationDailyDataVO.setWorkOrderTotalNums(jxdzMapper.countWorkOrderTotalByCode(code).doubleValue());
        stationDailyDataVO.setWorkOrderInvalidatedNums(jxdzMapper.countWorkOrderInvalidatedByCode(code).doubleValue());
        stationDailyDataVO.setWorkOrderToBeOpenedNums(jxdzMapper.countWorkOrderToBeOpenedByCode(code).doubleValue());
        stationDailyDataVO.setWorkOrderTerminatedNums(jxdzMapper.countWorkOrderTerminatedByCode(code).doubleValue());
        stationDailyDataVO.setWorkOrderStartNums(jxdzMapper.countWorkOrderStartByCode(code).doubleValue());

        LocalDateTime today = LocalDateTime.now();
        int day =today.getDayOfMonth();
        MockStationDailyDataEntity mockStationDailyDataEntity= mockStationDailyDataMapper.selectOne(new LambdaQueryWrapper<MockStationDailyDataEntity>()
                .eq(MockStationDailyDataEntity::getName,name).eq(MockStationDailyDataEntity::getDay,day));
        stationDailyDataVO.setCo2EmissionReduction(mockStationDailyDataEntity.getCo2EmissionReduction());
        stationDailyDataVO.setStandardCoalSaving(mockStationDailyDataEntity.getStandardCoalSaving());
        stationDailyDataVO.setSo2EmissionReduction(mockStationDailyDataEntity.getSo2EmissionReduction());
        stationDailyDataVO.setCarbonDustEmissionReduction(mockStationDailyDataEntity.getCarbonDustEmissionReduction());
        stationDailyDataVO.setGenerationEfficiency(mockStationDailyDataEntity.getGenerationEfficiency());


        //        //调用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);
//        } else 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"), stationDailyDataVO);
//            supplementBDData(stationDailyDataVO, code);
//            //补充其他信息
//        }
        return stationDailyDataVO;
    }

    /**
     * 补充部盾提供的数据
     * @param stationDailyDataVO
     */
    private void supplementBDData(StationDailyDataVO stationDailyDataVO, String code) {
        if (JXDZCodeEnum.GF.getCode().equals(code)) {
            try {
                String yesterday = DateUtils.dateFormat(Date.from(LocalDate.now().minusDays(1).atStartOfDay(ZoneId.systemDefault()).toInstant()), "yyyy-MM-dd");
                String url = "/screen_api?method=scene_screen.large_screen.get_loss_of_electricity&reporting_data=" + yesterday + "&source_station_id=1701778419827638274&station_type=PV";
                JSONObject jsonObject = jxdzUtils.sendCoreGetRequest(url);
                if (0 == jsonObject.getInteger("status")) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (!Objects.isNull(data)) {
                        stationDailyDataVO.setGenerationEfficiency(data.getDouble("comprehensive_efficiency"));
                    }
                }
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 补充场站数据
     * @param result
     * @param stationDailyDataVO
     */
    private void supplementStationData(JSONArray result, StationDailyDataVO stationDailyDataVO) {
        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 ("二氧化碳排放量（t）".equals(pointName)) {
                        stationDailyDataVO.setCo2EmissionReduction(jsonObject.getDouble("value"));
                    }
                    if ("节约标准煤（t）".equals(pointName)) {
                        stationDailyDataVO.setStandardCoalSaving(jsonObject.getDouble("value"));
                    }
                    if ("二氧化硫排放量（t）".equals(pointName)) {
                        stationDailyDataVO.setSo2EmissionReduction(jsonObject.getDouble("value"));
                    }
                    if ("碳粉尘减排量（t）".equals(pointName)) {
                        stationDailyDataVO.setCarbonDustEmissionReduction(jsonObject.getDouble("value"));
                    }
                    if ("发电效率".equals(pointName)) {
                        stationDailyDataVO.setGenerationEfficiency(jsonObject.getDouble("value"));
                    }
                }
            }
        }
    }

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