package com.project.zcustom.tools;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.project.common.utils.StringUtils;
import com.project.common.utils.http.HttpUtils;
import com.project.zcustom.domain.addional.LargeBuilding;
import com.project.zcustom.domain.addional.LargeBuildingControl;
import com.project.zcustom.domain.addional.LargeBuildingControlAmmeterDetail;
import com.project.zcustom.domain.addional.LargeBuildingLoadDetail;
import com.project.zcustom.domain.plat.PlatApiRecord;
import com.project.zcustom.mapper.unit.PlatBuildingMapper;
import com.project.zcustom.service.plat.IPlatApiRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description 楼宇运行监控接口
 * @Author bqyang
 * @Date 2025/2/10 16:58
 * @Version 1.0
 */
@Service
public class BuildingService {

    @Autowired
    private PlatBuildingMapper platBuildingMapper;
    @Resource
    IPlatApiRecordService iPlatApiRecordService;

    /**
     *  楼宇中控 接口数据同步
     */
    public void getLeftBuildingData(){
        String controlEquipment = repeat(ApiUrlConfig.getControlEquipment(), null);
        JSONObject jsonObject = JSONObject.parseObject(controlEquipment);
        Long normalNum = 0L;
        Long abnormalNum = 0L;
        String encodedParamValue = "";
        String encodedParamValue2 = "";
        String encodedParamValue3 = "";
        String encodedParamValue4 = "";

        String encodedPointValue = "";
        String encodedPointValue2 = "";
        String encodedPointValue3 = "";
        String encodedPointValue4 = "";
        try {
            normalNum = Long.valueOf(jsonObject.getJSONObject("sj").getString("zcdw"));
            abnormalNum = Long.valueOf(jsonObject.getJSONObject("sj").getString("ycdw"));

            encodedParamValue = URLEncoder.encode("一号配电室", "UTF-8");
            encodedParamValue2 = URLEncoder.encode("二号配电室", "UTF-8");
            encodedParamValue3 = URLEncoder.encode("三号配电室", "UTF-8");
            encodedParamValue4 = URLEncoder.encode("负二", "UTF-8");

            encodedPointValue = URLEncoder.encode("电表", "UTF-8");
            encodedPointValue2 = URLEncoder.encode("水浸", "UTF-8");
            encodedPointValue3 = URLEncoder.encode("烟雾", "UTF-8");
            encodedPointValue4 = URLEncoder.encode("液位", "UTF-8");
        }catch (Exception e){

        }


        try {
            LargeBuildingControl largeBuildingControl = new LargeBuildingControl(
                    repeat(ApiUrlConfig.getControlElectricity(), null),
                    repeat(ApiUrlConfig.getControlElevator(), null),
                    repeat(ApiUrlConfig.getControlElectricityRoom(), null),
                    repeat(ApiUrlConfig.getControlTodaySum(), null),
                    repeat(ApiUrlConfig.getControlMonthSum(), "type="+encodedParamValue),
                    repeat(ApiUrlConfig.getControlMonthSum(), "type="+encodedParamValue2),
                    repeat(ApiUrlConfig.getControlMonthSum(), "type="+encodedParamValue3),
                    repeat(ApiUrlConfig.getControlImportantSum(), "type="+encodedParamValue),
                    repeat(ApiUrlConfig.getControlImportantSum(), "type="+encodedParamValue2),
                    repeat(ApiUrlConfig.getControlImportantSum(), "type="+encodedParamValue3),
                    repeat(ApiUrlConfig.getControlEquipment(), null),
                    normalNum,
                    abnormalNum,
                    repeat(ApiUrlConfig.getControlAlarm(), null),
                    repeat(ApiUrlConfig.getControlWater(), "position=23F"),
                    repeat(ApiUrlConfig.getControlWater(), "position="+encodedParamValue4),
                    repeat(ApiUrlConfig.getPhotovoltaicPower(), null)
            );

            largeBuildingControl.setAbnormalPointOne(repeat(ApiUrlConfig.getControlAlertDetails(), "type="+encodedPointValue));
            largeBuildingControl.setAbnormalPointTwo(repeat(ApiUrlConfig.getControlAlertDetails(), "type="+encodedPointValue2));
            largeBuildingControl.setAbnormalPointThree(repeat(ApiUrlConfig.getControlAlertDetails(), "type="+encodedPointValue3));
            largeBuildingControl.setAbnormalPointFour(repeat(ApiUrlConfig.getControlAlertDetails(), "type="+encodedPointValue4));

            if (platBuildingMapper.getExist() > 0){
                platBuildingMapper.updateBuildingControl(largeBuildingControl);
            } else {
                largeBuildingControl.setWaterDeviceAirNum(0L);
                platBuildingMapper.addBuildingControl(largeBuildingControl);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 电表、异常、负载明细
     */
    public void getLeftBuildingDataDetail(){

        String[] arr = {
                "制冷机组",
                "公共照明",
                "生活水泵",
                "楼外设备",
                "消防",
                "供热设备",
                "冷源泵",
                "充电桩",
                "电梯",
                "厨房",
                "热源泵",
                "地下室",
                "办公",
                "通信辅助设备",
                "信息UPS",
                "信息空调",
                "调度UPS",
                "调度空调",
                "通信UPS",
                "通信空调",
                "交易机房",
                "管控机房空调"
        };

        try {
            List<LargeBuildingControlAmmeterDetail> list = new ArrayList<>();
            for (int i=0; i<arr.length; i++){
                LargeBuildingControlAmmeterDetail largeBuildingControlAmmeterDetail = new LargeBuildingControlAmmeterDetail();
                // 对参数值进行URL编码
                String type = URLEncoder.encode(arr[i], "UTF-8");
                largeBuildingControlAmmeterDetail.setAmmeterDetail(repeat(ApiUrlConfig.getControlElectricityDetail(), "type=" + type));
                largeBuildingControlAmmeterDetail.setType(arr[i]);
                list.add(largeBuildingControlAmmeterDetail);
            }
            platBuildingMapper.deleteAmmeterDetails();
            platBuildingMapper.addAmmeterDetails(list);
        }catch (Exception e){}



        try {
            platBuildingMapper.deleteLoadDetails();
            String[] type = {"一号配电室", "二号配电室", "三号配电室"};
            String[] state = {"重载", "轻载", "过载", "空载", "正常"};
            for (int i = 0; i < 3; i++){
                for (int j = 0; j < 5; j++){
                    String typeEncode = URLEncoder.encode(type[i], "UTF-8");
                    String stateEncode = URLEncoder.encode(state[j], "UTF-8");
                    String res = repeat(ApiUrlConfig.getControlImportantDetails(), "type=" + typeEncode + "&" + "state=" + stateEncode);
                    if (StringUtils.isBlank(res)){
                        break;
                    }
                    List<LargeBuildingLoadDetail> load = JSON.parseArray(res, LargeBuildingLoadDetail.class);
                    for (LargeBuildingLoadDetail it : load){
                        it.setState(j + 1);
                        it.setKind(i + 1);
                    }
                    platBuildingMapper.addLoadDetails(load);
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    /**
     *  办公能耗 / 大楼安防 接口数据同步
     */
    public void getRightBuildingDataFirstHalf(){
        LargeBuilding largeBuilding = new LargeBuilding();
        largeBuilding.setJsonFrequency(repeat(ApiUrlConfig.getJsonFrequency(), null));
        largeBuilding.setJsonPatrol(repeat(ApiUrlConfig.getJsonPatrol(), null));
        largeBuilding.setJsonPatrolPoint(repeat(ApiUrlConfig.getJsonPatrolPoint(), null));
        largeBuilding.setJsonPowerWaterMonth((repeat(ApiUrlConfig.getJsonPowerWaterMonth(), null)));
        largeBuilding.setJsonTarget(repeat(ApiUrlConfig.getJsonTarget(), null));
        largeBuilding.setJsonUseElectricity(repeat(ApiUrlConfig.getJsonUseElectricity(), null));
        largeBuilding.setJsonGreenElectricity(repeat(ApiUrlConfig.getJsonGreenElectricity(), null));
        largeBuilding.setJsonCarbon(repeat(ApiUrlConfig.getJsonCarbon(), null));
        largeBuilding.setJsonEnergyYear(repeat(ApiUrlConfig.getJsonEnergyYear(), null));
        largeBuilding.setJsonPowerYear(repeat(ApiUrlConfig.getJsonPowerYear(), null));
        largeBuilding.setJsonWaterYear(repeat(ApiUrlConfig.getJsonWaterYear(), null));
        if (platBuildingMapper.getCount() > 0){
            platBuildingMapper.updateBuilding(largeBuilding);
        }
        else {
            platBuildingMapper.insertBuilding(largeBuilding);
        }
    }

    /**
     * 办公能耗 空气概况
     *  该接口请求频率 5分钟一次
     */
    public void getRightBuildingDataSecondHalf(){
        LargeBuilding largeBuilding = new LargeBuilding();
        largeBuilding.setJsonAir(repeat(ApiUrlConfig.getJsonAir(), null));
        if (platBuildingMapper.getCount() > 0){
            platBuildingMapper.updateBuilding(largeBuilding);
        }
        else {
            platBuildingMapper.insertBuilding(largeBuilding);
        }
    }

    public String repeat(String url, String params){
        String result = null;
        try {
            if (StringUtils.isNotBlank(params)){
                String res = HttpUtils.sendGet(url, params);
                if (StringUtils.isNotBlank(res)){
                    JSONObject jsonObject = JSONObject.parseObject(res);
                    result = jsonObject.getString("data");
                }
            } else {
                String res = HttpUtils.sendGet(url);
                if (StringUtils.isNotBlank(res)){
                    JSONObject jsonObject = JSONObject.parseObject(res);
                    result = jsonObject.getString("data");
                }
            }

        } catch (Exception e){
            // 添加接口请求记录
            PlatApiRecord platApiRecord = new PlatApiRecord();
            platApiRecord.setApiUrl(url);
            platApiRecord.setApiResult(e.getMessage());
            iPlatApiRecordService.save(platApiRecord);
            return result;
        }
        // 添加接口请求记录
        PlatApiRecord platApiRecord = new PlatApiRecord();
        platApiRecord.setApiUrl(url);
        platApiRecord.setApiResult(result);
        iPlatApiRecordService.save(platApiRecord);
        return result;
    }
}
