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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
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.PvDeviceDataEntity;
import com.yeejoin.amos.boot.module.jxiop.biz.jxdz.impl.PvDeviceDataServiceImpl;
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.PvDeviceDataVO;
import com.yeejoin.amos.boot.module.jxiop.biz.mapper2.JXDZMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class GFDZSBJCServiceImpl implements IJXDZService {
    @Autowired
    JXDZUtils jxdzUtils;
    @Autowired
    PvDeviceDataServiceImpl pvDeviceDataService;
    @Autowired
    JXDZMapper jxdzMapper;

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

    @Override
    public List buildData(Integer accessType, Long dateTime) {
        List<PvDeviceDataVO> list = new ArrayList<>();
        if (JXDZAccessTypeEnum.BULU.getCode().equals(accessType)) {
            List<PvDeviceDataEntity> windStationDataEntityList = pvDeviceDataService.list(new LambdaQueryWrapper<PvDeviceDataEntity>().eq(PvDeviceDataEntity::getDateTime, dateTime));
            list = BeanUtil.copyToList(windStationDataEntityList, PvDeviceDataVO.class);
        } else {
            JSONArray zzBusinessData = getZZBusinessData();
            if (CollectionUtil.isNotEmpty(zzBusinessData)) {
                for (Object o : zzBusinessData) {
                    if (o instanceof Map) {
                        Map map = (Map) o;
                        JSONObject jsonObject = new JSONObject(map);
                        if (jsonObject.getString("name").contains("子阵")) {
                            list.add(getPvDeviceDataVO(jsonObject));
                        }
                    }

                }
            }
        }
        return list;
    }

    /**
     * 获取光伏设备数据
     * @param jsonObject
     * @return
     */
    private PvDeviceDataVO getPvDeviceDataVO(JSONObject jsonObject) {
        PvDeviceDataVO pvDeviceDataVO = new PvDeviceDataVO();
        String sequenceNbr = jsonObject.getString("sequenceNbr");
        pvDeviceDataVO.setName(jsonObject.getString("name"));
        pvDeviceDataVO.setCode(getPvDeviceCode(jsonObject.getString("name")));
        //开始调用具体列表接口
        JSONArray windDeviceJSONArray = getPvDeviceDataBySequenceNbr(sequenceNbr);
        if (CollectionUtil.isNotEmpty(windDeviceJSONArray)) {
            for (Object o : windDeviceJSONArray) {
                if (o instanceof Map) {
                    Map map = (Map) o;
                    JSONObject result = new JSONObject(map);
                    String pointLocation = result.getString("pointLocation");
                    Boolean flag = checkPvDevice(pointLocation, jsonObject.getString("name"));
                    if (flag) {
                        String pointName = (String) map.get("pointName");
                        if (pointName.contains("日发电量")) {
                            pvDeviceDataVO.setGenerationDaily(result.getDouble("value")/100000);
                        }
                        if (pointName.contains("月发电量")) {
                            pvDeviceDataVO.setGenerationMonth(result.getDouble("value")/10000);
                        }
                        if (pointName.contains("年发电量")) {
                            pvDeviceDataVO.setGenerationYear(result.getDouble("value")/100000000);
                        }
                        if (pointName.contains("总发电量")) {
                            pvDeviceDataVO.setGenerationGross(result.getDouble("value")/100000000);
                        }
                    }
                }
            }
        }
        return pvDeviceDataVO;
    }

    /**
     * 校验路径是否是子阵的     路径倒数第三位为子阵
     * @param pointLocation
     * @param name
     * @return
     */
    private Boolean checkPvDevice(String pointLocation, String name) {
        if (!StrUtil.isEmpty(pointLocation)) {
            String[] split = pointLocation.split("/");
            if (!Objects.isNull(split)) {
                String zdName = split[split.length - 3];
                if (zdName.equals(name)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取光伏设备数据根据主键
     * @param sequenceNbr
     * @return
     */
    private JSONArray getPvDeviceDataBySequenceNbr(String sequenceNbr) {
        JSONObject jsonObject = jxdzUtils.sendCoreGetRequest("/core/datastorage/gateway/point/list?groupId=" + sequenceNbr + "&dataType=accumulator");
        if (!Objects.isNull(jsonObject)) {
            if (jsonObject.getInteger("status") == HttpStatus.OK.value()) {
                return jsonObject.getJSONArray("result");
            }
        }
        return new JSONArray();
    }

    /**
     * 获取光伏设备Code
     * @param name
     * @return
     */
    private String getPvDeviceCode(String name) {
        String replaceString = name.replace("子阵", "");
        Integer value = Integer.valueOf(replaceString);
        String field = "%#" + value + "光伏阵区系统%";
        String replaceField = "%#" + replaceString + "光伏阵区系统%";
        return jxdzMapper.getDeviceCode(JXDZCodeEnum.GF.getCode(), field, replaceField);
    }

    private JSONArray getZZBusinessData() {
        JSONObject jsonObject = jxdzUtils.sendCoreGetRequest("/core/front-gateway-device/tree?gatewayId=1762633785632919553");
        if (!Objects.isNull(jsonObject)) {
            if (jsonObject.getInteger("status") == HttpStatus.OK.value()) {
                JSONArray result = jsonObject.getJSONArray("result");
                if (CollectionUtil.isNotEmpty(result)) {
                    JSONObject firstObject = result.getJSONObject(0).getJSONArray("children").getJSONObject(0);
                    if (!Objects.isNull(firstObject)) {
                        JSONArray children = firstObject.getJSONArray("children");
                        if (CollectionUtil.isNotEmpty(children)) {
                            for (Object child : children) {
                                if (child instanceof Map) {
                                    Map map = (Map) child;
                                    JSONObject childJSON = new JSONObject(map);
                                    if ("装置测点".equals(childJSON.getString("name"))) {
                                        return childJSON.getJSONArray("children");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return new JSONArray();
    }

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