package com.tuoheng.admin.service.airData.syncdata;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tuoheng.admin.entity.domain.AirData;
import com.tuoheng.admin.entity.domain.Inspection;
import com.tuoheng.admin.entity.request.inspection.AirportLineRequest;
import com.tuoheng.admin.entity.third.LingXiuDataResponse;
import com.tuoheng.admin.enums.AirportLineEnum;
import com.tuoheng.admin.enums.InspectionStatusEnum;
import com.tuoheng.admin.enums.MarkEnum;
import com.tuoheng.admin.mapper.AirDataMapper;
import com.tuoheng.admin.mapper.InspectionMapper;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.DateUtils;
import com.tuoheng.common.core.utils.JsonResult;
import com.tuoheng.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @Author ChengWang
 * @Date 2023/5/24
 */
@Service
@Slf4j
public class SyncAirDataService {

    @Autowired
    private InspectionMapper inspectionMapper;

    @Autowired
    private AirDataMapper airDataMapper;

    public JsonResult sync(LingXiuDataResponse response) {
        log.info("收到灵嗅设备推送数据");
        //校验参数值
        JsonResult jsonResult = this.check(response);
        if(jsonResult.getCode() != 0){
            log.info("校验失败：{}",jsonResult.getMsg());
            return jsonResult;
        }
        Inspection inspection = (Inspection) jsonResult.getData();

        AirData airData = new AirData();
        airData.setInspectionId(inspection.getId());   // 任务ID
        airData.setTenantId(inspection.getTenantId());   // 租户ID
        airData.setSateNum(response.getSateNum());   // 卫星编号
        airData.setSequence(response.getSequence());   // 序号
        airData.setSerial(response.getSerial());   // 序列号
        airData.setAltitude(response.getAltitude());   // 高度
        airData.setLatitude(response.getLatitude());   // 纬度
        airData.setLongitude(response.getLongitude());   // 经度
        airData.setTemperature(response.getTemperature());   // 温度
        airData.setHumidity(response.getHumidity());   // 湿度
        airData.setHdop(response.getHdop());   // 水平精度因子
        airData.setPressure(response.getPressure());   // 大气压
        airData.setCUtcTime(DateUtils.convert(DateUtils.YYYY_MM_DD_HH_MM_SS_2, DateUtils.YYYY_MM_DD_HH_MM_SS, response.getUtcTime()));   // UTC时间

        Map<String, Object> airDataMap = response.getAirData();
        String cl2 = this.getValue(airDataMap,"CL2(ppm)");   // 氯气(单位ppm)
        String co = this.getValue(airDataMap,"CO(ppm)");   // 一氧化碳(单位ppm)
        String co2 = this.getValue(airDataMap, "CO2(ppm)");   // 二氧化碳(单位ppm)
        String cxhy = this.getValue(airDataMap, "CxHy(%)");   // 碳氢化合物(单位%)
        String h2 = this.getValue(airDataMap, "H2(ppm)");   // 氢气(单位ppm)
        String h2s = this.getValue(airDataMap, "H2S(ppm)");   // 硫化氢(单位ppm)
        String hcl = this.getValue(airDataMap, "HCL(ppm)");   // 氯化氢(单位ppm)
        String hcn = this.getValue(airDataMap, "HCN(ppm)");   // 氰化氢(单位ppm)
        String nh3 = this.getValue(airDataMap, "NH3(ppm)");   // 氨气(单位ppm)
        String ox = this.getValue(airDataMap, "Ox(ppm)");   // 邻二甲苯(单位ppm)
        String ph3 = this.getValue(airDataMap, "PH3(ppm)");   // 磷化氢(单位ppm)
        String pm_1_0 = this.getValue(airDataMap, "PM1.0(ug/m3)");   // PM1.0(单位ug/m3)
        String pm_10 = this.getValue(airDataMap, "PM10(ug/m3)");   // PM10(单位ug/m3)
        String pm_2_5 = this.getValue(airDataMap, "PM2.5(ug/m3)");   // PM2.5(单位ug/m3)
        String so2 = this.getValue(airDataMap, "SO2(ppm)");   // 二氧化硫(单位ppm)
        String tsp = this.getValue(airDataMap, "TSP(mgm3)");   // 磷酸三钠(单位mg/m3)
        String vocs = this.getValue(airDataMap, "VOCs(ppm)");   // 挥发性有机物(单位ppm)
        String wrSo2 = this.getValue(airDataMap, "[WR]SO2(ppm)");   // WR二氧化硫(单位ppm)
        String no2 = this.getValue(airDataMap, "NO2(ppm)");   // 二氧化氮(单位ppm)
        String o2 = this.getValue(airDataMap, "O2(%)");   // 氧气(单位%)
        String ionizingRadiation = this.getValue(airDataMap, "Ionizing Radiation(uSv/h)");   // 电离辐射(uSv/h)
        String no = this.getValue(airDataMap, "NO(ppm)");   // 一氧化氮(ppm)
        String odorOu = this.getValue(airDataMap, "Odor OU");   // 恶臭气体
        String hrch4 = this.getValue(airDataMap, "[HR]CH4(ppm)");   // [HR]甲烷(ppm)

        airData.setCl2(cl2);
        airData.setCo(co);
        airData.setCo2(co2);
        airData.setCxhy(cxhy);
        airData.setH2(h2);
        airData.setH2s(h2s);
        airData.setHcl(hcl);
        airData.setHcn(hcn);
        airData.setNh3(nh3);
        airData.setOx(ox);
        airData.setPh3(ph3);
        airData.setPm_1_0(pm_1_0);
        airData.setPm10(pm_10);
        airData.setPm25(pm_2_5);
        airData.setSo2(so2);
        airData.setTsp(tsp);
        airData.setVocs(vocs);
        airData.setWrSo2(wrSo2);
        airData.setNo2(no2);
        airData.setO2(o2);
        airData.setIonizingRadiation(ionizingRadiation);
        airData.setNo(no);
        airData.setOdorOu(odorOu);
        airData.setHrch4(hrch4);
        airData.setO3(this.getO3(ox, no2));
        airData.setCreateTime(DateUtils.now());
        airData.setCreateUser("0");
        Integer count = airDataMapper.insert(airData);
        if (count <= 0) {
            log.info("拉取灵嗅设备推送数据，插入失败");
        }
        return JsonResult.success();
    }

    /**
     *
     * @param response
     * @return
     */
    private JsonResult check(LingXiuDataResponse response) {
        if (ObjectUtil.isEmpty(response)) {
            log.info("灵嗅设备推送数据为空");
            return JsonResult.error("灵嗅设备推送数据为空");
        }
        if (StringUtils.isEmpty(response.getSerial())) {
            log.info("灵嗅设备推送数据，serial为空");
            return JsonResult.error("灵嗅设备推送数据，serial为空");
        }
        Inspection inspection = this.getInspection(response.getSerial());
        if (ObjectUtil.isNull(inspection)) {
            log.info("没有正在飞行的任务，无法关联推送的灵嗅数据，serial={}", response.getSerial());
            return JsonResult.error("没有正在飞行的任务");
        }
        return JsonResult.success();
    }

    private Inspection getInspection(String serial) {
        Inspection inspection = inspectionMapper.selectOne(new LambdaQueryWrapper<Inspection>()
//                .eq(Inspection::getEquipmentMountCode, serial)
                .eq(Inspection::getStatus, InspectionStatusEnum.IN_FLIGHT.getCode())
                .eq(Inspection::getMark, MarkEnum.VALID.getCode())
                .orderByDesc(Inspection::getCreateTime)
                .last(" limit 1"));
        if (ObjectUtil.isNull(inspection)) {
            return null;
        }
        return inspection;
    }

    private String getValue(Map<String, Object> airDataMap, String key) {
        if (airDataMap.containsKey(key)) {
            return airDataMap.get(key) == null ? "" : (String) airDataMap.get(key).toString();
        } else {
            return "";
        }
    }

    private String getO3(String ox, String no2) {
        String o3 = "";
        if (StringUtils.isEmpty(ox)) {
            if (StringUtils.isNotEmpty(no2)) {
                o3 = "-" + no2;
            }
        } else {
            if (StringUtils.isNotEmpty(no2)) {
                Double o3d = Double.parseDouble(ox) - Double.parseDouble(no2);
                o3 = String.valueOf(o3d);
            } else {
                o3 = ox;
            }
        }
        return o3;
    }
}
