package com.usky.fire.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.Arith;
import com.usky.common.mybatis.core.AbstractCrudService;
import com.usky.fire.domain.*;
import com.usky.fire.mapper.BscEnterpriseAutonomyMapper;
import com.usky.fire.service.*;
import com.usky.fire.service.util.OnlineMethod;
import com.usky.fire.service.vo.DataCountVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 企业自主管理大屏统计（全部） 服务实现类
 * </p>
 *
 * @author JCB
 * @since 2022-10-09
 */
@Service
public class BscEnterpriseAutonomyServiceImpl extends AbstractCrudService<BscEnterpriseAutonomyMapper, BscEnterpriseAutonomy> implements BscEnterpriseAutonomyService {

    @Autowired
    private DemBuildScoreService demBuildScoreService;

    @Autowired
    private BaseCompanyService baseCompanyService;

    @Autowired
    private DemBuildScoreRecordService demBuildScoreRecordService;

    @Autowired
    private PatrolInspectionPlanService patrolInspectionPlanService;

    @Autowired
    private PatrolInspectionPlanSonService patrolInspectionPlanSonService;

    @Autowired
    private PatrolInspectionPlanSiteSonService patrolInspectionPlanSiteSonService;

    @Autowired
    private BaseDeviceService baseDeviceService;

    @Autowired
    private BaseDeviceStatusService baseDeviceStatusService;

    @Autowired
    private AlarmFireService alarmFireService;

    @Autowired
    private BscEnterpriseStreetTownService bscEnterpriseStreetTownService;

    @Autowired
    private BaseCompanyPersonService baseCompanyPersonService;

    @Autowired
    private BaseCompanyAttach1Service baseCompanyAttach1Service;

    @Autowired
    private AlarmElectricalFireService alarmElectricalFireService;

    @Autowired
    private AlarmSprayWaterService alarmSprayWaterService;

    @Autowired
    private AlarmHydrantWaterService alarmHydrantWaterService;

    @Autowired
    private AlarmSmokeControlService alarmSmokeControlService;

    @Autowired
    private AlarmVideoService alarmVideoService;

    @Autowired
    private DemReportGradeService demReportGradeService;

    @Autowired
    private DemFireReformService demFireReformService;

    @Autowired
    private DemReformReviewService demReformReviewService;

    @Autowired
    private ReportIndexResultService reportIndexResultService;


    @Override
    public Object enterprise(String moduleType, String dataType, String streetTown){
        Object list = null;
        if (StringUtils.isNotBlank(streetTown)){
            list = bscEnterpriseStreetTownService.enterpriseStreetTown(moduleType, dataType, streetTown);
        }else {
            list = this.enterpriseAutonomy(moduleType, dataType);
        }
        return list;
    }


    @Override
    public Object enterpriseAutonomy(String moduleType, String dataType) {
        LambdaQueryWrapper<BscEnterpriseAutonomy> queryWrapper = Wrappers.lambdaQuery();
        switch (moduleType) {
            case "enterpriseAutonomy":
                queryWrapper.select(BscEnterpriseAutonomy::getEnterpriseAutonomy);
                break;
            case "iotDevice":
                queryWrapper.select(BscEnterpriseAutonomy::getIotDevice);
                break;
            case "patrolInspection":
                queryWrapper.select(BscEnterpriseAutonomy::getPatrolInspection);
                break;
            case "streetCompany":
                queryWrapper.select(BscEnterpriseAutonomy::getStreetCompany);
                break;
            default:
                throw new BusinessException("参数错误");
        }
        queryWrapper.orderByDesc(BscEnterpriseAutonomy::getId)
                .last(" limit 1");
        List<BscEnterpriseAutonomy> list = this.list(queryWrapper);
        Object data = null;
        if (CollectionUtils.isNotEmpty(list)) {
            switch (moduleType) {
                case "enterpriseAutonomy":
                    data = list.get(0).getEnterpriseAutonomy();
                    break;
                case "iotDevice":
                    data = list.get(0).getIotDevice();
                    break;
                case "patrolInspection":
                    data = list.get(0).getPatrolInspection();
                    break;
                case "streetCompany":
                    data = list.get(0).getStreetCompany();
                    break;
            }
        }
        JSONObject jsonObject = JSONObject.parseObject(data.toString());
        Object disparateData = jsonObject.get(dataType);
        return disparateData;
    }

    @Transactional
    @Override
    public void enterpriseAutonomyTask() {
        Map<String, Object> enterpriseAutonomy = this.enterpriseAutonomyData();
        Object iotDevice = this.iotDevice();
        Object patrolInspection = this.patrolInspection();
        Object streetCompany = this.streetCompany();
        BscEnterpriseAutonomy bscEnterpriseAutonomy = new BscEnterpriseAutonomy();
        bscEnterpriseAutonomy.setEnterpriseAutonomy(JSON.toJSONString(enterpriseAutonomy));
        bscEnterpriseAutonomy.setIotDevice(JSON.toJSONString(iotDevice));
        bscEnterpriseAutonomy.setPatrolInspection(JSON.toJSONString(patrolInspection));
        bscEnterpriseAutonomy.setStreetCompany(JSON.toJSONString(streetCompany));
        bscEnterpriseAutonomy.setRpn(enterpriseAutonomy.get("data4").toString());
        bscEnterpriseAutonomy.setCreateTime(LocalDateTime.now());
        this.save(bscEnterpriseAutonomy);
    }


    @Override
    public List<Map<String, Object>> erpData(String companyId) {
        LambdaQueryWrapper<BaseCompany> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.select(BaseCompany::getId, BaseCompany::getCompanyId, BaseCompany::getCompanyName, BaseCompany::getFoundTime,
                BaseCompany::getCompanyType, BaseCompany::getLinkPhone, BaseCompany::getAddress, BaseCompany::getOrganization,
                BaseCompany::getCompanyNature)
                .eq(BaseCompany::getEnable, 0)
                .eq(BaseCompany::getCompanyId, companyId)
                .orderByDesc(BaseCompany::getId);
        List<BaseCompany> list1 = baseCompanyService.list(queryWrapper1);
        List<Map<String, Object>> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list1)) {
            LambdaQueryWrapper<BaseCompanyPerson> queryWrapper2 = Wrappers.lambdaQuery();
            queryWrapper2.select(BaseCompanyPerson::getCompanyId, BaseCompanyPerson::getDelegateName, BaseCompanyPerson::getFireManageName,
                    BaseCompanyPerson::getFireDutyName)
                    .eq(BaseCompanyPerson::getCompanyId, companyId);
            List<BaseCompanyPerson> list2 = baseCompanyPersonService.list(queryWrapper2);

            LambdaQueryWrapper<BaseCompanyAttach1> queryWrapper3 = Wrappers.lambdaQuery();
            queryWrapper3.select(BaseCompanyAttach1::getCompanyId, BaseCompanyAttach1::getBuildArea, BaseCompanyAttach1::getEmployeeNum,
                    BaseCompanyAttach1::getRegisteredCapital, BaseCompanyAttach1::getBusinessStatus, BaseCompanyAttach1::getPaidCapital,
                    BaseCompanyAttach1::getRegistrar, BaseCompanyAttach1::getCompletedTime, BaseCompanyAttach1::getFireRating,
                    BaseCompanyAttach1::getBuildingHeight, BaseCompanyAttach1::getBuildingStructure, BaseCompanyAttach1::getConstruction)
                    .eq(BaseCompanyAttach1::getCompanyId, companyId);
            List<BaseCompanyAttach1> list3 = baseCompanyAttach1Service.list(queryWrapper3);
            for (int i = 0; i < list1.size(); i++) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", list1.get(i).getId());
                map.put("companyId", list1.get(i).getCompanyId());
                map.put("companyName", list1.get(i).getCompanyName());
                map.put("foundTime", list1.get(i).getFoundTime());
                map.put("companyType", list1.get(i).getCompanyType());
                map.put("linkPhone", list1.get(i).getLinkPhone());
                map.put("address", list1.get(i).getAddress());
                map.put("organization", list1.get(i).getOrganization());
                map.put("companyNature", list1.get(i).getCompanyNature());

                map.put("delegateName", null);
                map.put("fireManageName", null);
                map.put("fireDutyName", null);

                map.put("buildArea", null);
                map.put("employeeNum", null);
                map.put("registeredCapital", null);
                map.put("businessStatus", null);
                map.put("paidCapital", null);
                map.put("registrar", null);
                map.put("completedTime", null);
                map.put("fireRating", null);
                map.put("buildingHeight", null);
                map.put("buildingStructure", null);
                map.put("construction", null);

                for (int j = 0; j < list2.size(); j++) {
                    if (list1.get(i).getCompanyId().equals(list2.get(j).getCompanyId())) {
                        map.put("delegateName", list2.get(j).getDelegateName());
                        map.put("fireManageName", list2.get(j).getFireManageName());
                        map.put("fireDutyName", list2.get(j).getFireDutyName());
                    }
                }

                for (int j = 0; j < list3.size(); j++) {
                    if (list1.get(i).getCompanyId().equals(list3.get(j).getCompanyId())) {
                        map.put("buildArea", list3.get(j).getBuildArea());
                        map.put("employeeNum", list3.get(j).getEmployeeNum());
                        map.put("registeredCapital", list3.get(j).getRegisteredCapital());
                        map.put("businessStatus", list3.get(j).getBusinessStatus());
                        map.put("paidCapital", list3.get(j).getPaidCapital());
                        map.put("registrar", list3.get(j).getRegistrar());
                        map.put("completedTime", list3.get(j).getCompletedTime());
                        map.put("fireRating", list3.get(j).getFireRating());
                        map.put("buildingHeight", list3.get(j).getBuildingHeight());
                        map.put("buildingStructure", list3.get(j).getBuildingStructure());
                        map.put("construction", list3.get(j).getConstruction());
                    }
                }
                list.add(map);
            }
        }
        return list;
    }


    @Override
    public Map<String, Object> enterpriseAutonomyData() {
        String LastMonthDate = OnlineMethod.getLastMonth(new Date());
        DecimalFormat df = new DecimalFormat("0.00");
        int deviceDamageCount = 20;
        int fireCount = 0;
        int rectificationCount = 40;
        int buildTypeCount = 10;
        int highRiskCount = 30;
        int hiddenDangerCount = 0;

        List<String> alarmTypeList = new ArrayList<>();
        alarmTypeList.add("2");
        List<String> companyIdList1 = new ArrayList<>();
        fireCount = alarmFireService.fireCount(companyIdList1, 0, alarmTypeList, null, null, null);
        hiddenDangerCount = bscEnterpriseStreetTownService.hiddenCount(companyIdList1);

        List<DemBuildScore> list1 = demBuildScoreService.buildScoreListOne();
        int companyScoreCount1 = demBuildScoreRecordService.demBuildScoreRecordCount(LastMonthDate, null, 85, null);
        int companyScoreCount2 = demBuildScoreRecordService.demBuildScoreRecordCount(LastMonthDate, 85, 60, null);
        int companyScoreCount3 = demBuildScoreRecordService.demBuildScoreRecordCount(LastMonthDate, 60, null, null);
        int companyScoreRatio = companyScoreCount3 / (companyScoreCount1 + companyScoreCount2 + companyScoreCount3);
        int companyCount = baseCompanyService.companyCount();
        Double companyCount1 = Double.valueOf(companyCount);
        Double deviceDamageRieo = 0.00;
        Double fireRieo = 0.00;
        Double rectificationRieo = 0.00;
        Double buildTypeRieo = 0.00;
        Double highRiskRieo = 0.00;
        Double hiddenDangerRieo = 0.00;

//        Double deviceDamageScore = 0.00;
//        Double fireScore = 0.00;
//        Double rectificationScore = 0.00;
//        Double buildTypeScore = 0.00;
//        Double highRiskScore = 0.00;
//        Double hiddenDangerScore = 0.00;

        Double deviceDamageScore1 = 0.00;
        Double fireScore1 = 0.00;
        Double rectificationScore1 = 0.00;
        Double buildTypeScore1 = 0.00;
        Double highRiskScore1 = 0.00;
        Double hiddenDangerScore1 = 0.00;

        List<Object> data1 = new ArrayList<>();
        for (int i = 0; i < list1.size(); i++) {
            Map<String, Object> map1 = new HashMap<>();
//            double sub = 0.0;
//            double div = 0.0;
            int riskMax = Integer.parseInt(list1.get(i).getRiskMax());
//            int weightProportion = Integer.parseInt(list1.get(i).getWeightProportion());
            switch (list1.get(i).getRiskId()) {
                case 1:
                    deviceDamageRieo = Double.valueOf(df.format((float) deviceDamageCount / riskMax * 100));
//                    sub = Arith.sub(100, deviceDamageRieo);
//                    div = Arith.div(weightProportion, 100);
//                    deviceDamageScore = Arith.mul(sub, div);
                    deviceDamageScore1 = Arith.div(deviceDamageRieo, companyCount1, 2);
                    map1.put("name", "设备状况指数");
                    map1.put("value", deviceDamageRieo);
                    break;
                case 2:
                    fireRieo = Double.valueOf(df.format((float) fireCount / riskMax * 100));
//                    sub = Arith.sub(100, fireRieo);
//                    div = Arith.div(weightProportion, 100);
//                    fireScore = Arith.mul(sub, div);
                    fireScore1 = Arith.div(fireRieo, companyCount1, 2);
                    map1.put("name", "历史火灾指数");
                    map1.put("value", fireScore1);
                    break;
                case 3:
                    rectificationRieo = Double.valueOf(df.format((float) rectificationCount / riskMax * 100));
//                    sub = Arith.sub(100, rectificationRieo);
//                    div = Arith.div(weightProportion, 100);
//                    rectificationScore = Arith.mul(sub, div);
                    rectificationScore1 = Arith.div(rectificationRieo, companyCount1, 2);
                    map1.put("name", "执法监管安全指数");
                    map1.put("value", rectificationScore1);
                    break;
                case 4:
                    buildTypeRieo = Double.valueOf(df.format((float) buildTypeCount / riskMax * 100));
//                    sub = Arith.sub(100, buildTypeRieo);
//                    div = Arith.div(weightProportion, 100);
//                    buildTypeScore = Arith.mul(sub, div);
                    buildTypeScore1 = Arith.div(buildTypeRieo, companyCount1, 2);
                    map1.put("name", "建筑整体风险指");
                    map1.put("value", buildTypeScore1);
                    break;
                case 5:
                    highRiskRieo = Double.valueOf(df.format((float) highRiskCount / riskMax * 100));
//                    sub = Arith.sub(100, highRiskRieo);
//                    div = Arith.div(weightProportion, 100);
//                    highRiskScore = Arith.mul(sub, div);
                    highRiskScore1 = Arith.div(highRiskRieo, companyCount1, 2);
                    map1.put("name", "场所行业风险指数");
                    map1.put("value", highRiskScore1);
                    break;
                case 6:
                    hiddenDangerRieo = Double.valueOf(df.format((float) hiddenDangerCount / riskMax * 100));
//                    sub = Arith.sub(100, hiddenDangerRieo);
//                    div = Arith.div(weightProportion, 100);
//                    hiddenDangerScore = Arith.mul(sub, div);
                    hiddenDangerScore1 = Arith.div(hiddenDangerRieo, companyCount1, 2);
                    map1.put("name", "隐患状况指数");
                    map1.put("value", hiddenDangerScore1);
                    break;
            }
            map1.put("mark", "分");
            data1.add(map1);
        }
        List<Object> data2 = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            Map<String, Object> map2 = new HashMap<>();
            switch (i) {
                case 0:
                    map2.put("name", "85分以上");
                    map2.put("value", companyScoreCount1);
                    map2.put("mark", "家");
                    break;
                case 1:
                    map2.put("name", "60~85分");
                    map2.put("value", companyScoreCount2);
                    map2.put("mark", "家");
                    break;
                case 2:
                    map2.put("name", "60分以下");
                    map2.put("value", companyScoreCount3);
                    map2.put("mark", "家");
                    break;
                case 3:
                    map2.put("name", "综合风险率");
                    map2.put("value", companyScoreRatio);
                    map2.put("mark", "%");
                    break;
            }
            data2.add(map2);
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<BscEnterpriseAutonomy> list = this.enterpriseAutonomyList();
        List<Object> data3 = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> map3 = new HashMap<>();
            if (!formatter.format(LocalDateTime.now()).equals(formatter.format(list.get(list.size() - 1 - i).getCreateTime()))) {
                map3.put("time", formatter.format(list.get(list.size() - 1 - i).getCreateTime()));
                map3.put("value", list.get(list.size() - 1 - i).getRpn());
                data3.add(map3);
            }
        }

        double value1 = Arith.add(deviceDamageScore1, fireScore1);
        double value2 = Arith.add(value1, rectificationScore1);
        double value3 = Arith.add(value2, buildTypeScore1);
        double value4 = Arith.add(value3, highRiskScore1);
        double value = Arith.add(value4, hiddenDangerScore1);

        Map<String, Object> map4 = new HashMap<>();
        map4.put("time", formatter.format(LocalDateTime.now()));
        map4.put("value", value);
        data3.add(map4);

        Map<String, Object> map = new HashMap<>();
        map.put("data1", data1);
        map.put("data2", data2);
        map.put("data3", data3);
        map.put("data4", value);
        return map;
    }

    @Override
    public List<BscEnterpriseAutonomy> enterpriseAutonomyList() {
        LambdaQueryWrapper<BscEnterpriseAutonomy> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(BscEnterpriseAutonomy::getRpn, BscEnterpriseAutonomy::getCreateTime)
                .orderByDesc(BscEnterpriseAutonomy::getId)
                .last(" limit 6");
        List<BscEnterpriseAutonomy> list = this.list(queryWrapper);
        return list;
    }


    @Override
    public Object iotDevice() {
        Integer typeCount1 = 0;
        Integer typeCount2 = 0;
        Integer typeCount6 = 0;
        Integer typeCount7 = 0;
        Integer typeCount9 = 0;
        Integer typeOffCount1 = 0;
        Integer typeOffCount2 = 0;
        Integer typeOffCount6 = 0;
        Integer typeOffCount7 = 0;
        Integer typeOffCount9 = 0;
        LambdaQueryWrapper<BaseDevice> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(BaseDevice::getDeviceCode, BaseDevice::getDeviceType)
                .eq(BaseDevice::getEnable, 1)
                .ne(BaseDevice::getDeviceType, 16);
        List<BaseDevice> list1 = baseDeviceService.list(queryWrapper);
        Integer deviceCount = list1.size();
        if (CollectionUtils.isNotEmpty(list1)) {
            List<String> deviceCode1 = new ArrayList<>();
            List<String> deviceCode2 = new ArrayList<>();
            List<String> deviceCode6 = new ArrayList<>();
            List<String> deviceCode7 = new ArrayList<>();
            List<String> deviceCode9 = new ArrayList<>();
            for (int i = 0; i < list1.size(); i++) {
                switch (list1.get(i).getDeviceType()) {
                    case 1:
                    case 3:
                        deviceCode1.add(list1.get(i).getDeviceCode());
                        break;
                    case 2:
                    case 5:
                        deviceCode2.add(list1.get(i).getDeviceCode());
                        break;
                    case 6:
                        deviceCode6.add(list1.get(i).getDeviceCode());
                        break;
                    case 7:
                        deviceCode7.add(list1.get(i).getDeviceCode());
                        break;
                    default:
                        deviceCode9.add(list1.get(i).getDeviceCode());
                        break;
                }
            }
            if (CollectionUtils.isNotEmpty(deviceCode1)) {
                typeCount1 = deviceCode1.size();
                typeOffCount1 = this.deviceStateCount(deviceCode1, 0);
            }

            if (CollectionUtils.isNotEmpty(deviceCode2)) {
                typeCount2 = deviceCode2.size();
                typeOffCount2 = this.deviceStateCount(deviceCode2, 0);
            }

            if (CollectionUtils.isNotEmpty(deviceCode6)) {
                typeCount6 = deviceCode6.size();
                typeOffCount6 = this.deviceStateCount(deviceCode6, 0);
            }

            if (CollectionUtils.isNotEmpty(deviceCode7)) {
                typeCount7 = deviceCode7.size();
                typeOffCount7 = this.deviceStateCount(deviceCode7, 0);
            }

            if (CollectionUtils.isNotEmpty(deviceCode9)) {
                typeCount9 = deviceCode9.size();
                typeOffCount9 = this.deviceStateCount(deviceCode9, 0);
            }
        }
        List<Object> data2 = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Map<String, Object> map2 = new HashMap<>();
            switch (i) {
                case 0:
                    map2.put("name", "火系统");
                    map2.put("on_line", typeCount1 - typeOffCount1);
                    map2.put("off_line", typeOffCount1);
                    if ((typeCount1 - typeOffCount1) != 0 && typeCount1 != 0) {
                        map2.put("ratio", (typeCount1 - typeOffCount1) / typeCount1 * 100 + "%");
                    } else {
                        map2.put("ratio", "0%");
                    }
                    break;
                case 1:
                    map2.put("name", "水系统");
                    map2.put("on_line", typeCount2 - typeOffCount2);
                    map2.put("off_line", typeOffCount2);
                    if ((typeCount2 - typeOffCount2) != 0 && typeCount2 != 0) {
                        map2.put("ratio", (typeCount2 - typeOffCount2) / typeCount2 * 100 + "%");
                    } else {
                        map2.put("ratio", "0%");
                    }
                    break;
                case 2:
                    map2.put("name", "RTU");
                    map2.put("on_line", typeCount6 - typeOffCount6);
                    map2.put("off_line", typeOffCount6);
                    if ((typeCount6 - typeOffCount6) != 0 && typeCount6 != 0) {
                        map2.put("ratio", (typeCount6 - typeOffCount6) / typeCount6 * 100 + "%");
                    } else {
                        map2.put("ratio", "0%");
                    }
                    break;
                case 3:
                    map2.put("name", "电气火灾");
                    map2.put("on_line", typeCount7 - typeOffCount7);
                    map2.put("off_line", typeOffCount7);
                    if ((typeCount7 - typeOffCount7) != 0 && typeCount7 != 0) {
                        map2.put("ratio", (typeCount7 - typeOffCount7) / typeCount7 * 100 + "%");
                    } else {
                        map2.put("ratio", "0%");
                    }
                    break;
                case 4:
                    map2.put("name", "其他");
                    map2.put("on_line", typeCount9 - typeOffCount9);
                    map2.put("off_line", typeOffCount9);
                    if ((typeCount9 - typeOffCount9) != 0 && typeCount9 != 0) {
                        map2.put("ratio", (typeCount9 - typeOffCount9) / typeCount9 * 100 + "%");
                    } else {
                        map2.put("ratio", "0%");
                    }
                    break;
            }
            data2.add(map2);
        }
        List<Object> data1 = new ArrayList<>();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("name", "累计接入设备");
        map1.put("value", deviceCount);
        data1.add(map1);
        Map<String, Object> map = new HashMap<>();
        map.put("data1", data1);
        map.put("data2", data2);
        return map;
    }

    @Override
    public Integer deviceStateCount(List<String> deviceCodeList, Integer state) {
        LambdaQueryWrapper<BaseDeviceStatus> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.in(BaseDeviceStatus::getDeviceCode, deviceCodeList)
                .eq(BaseDeviceStatus::getDeviceStatus, state);
        int count = baseDeviceStatusService.count(queryWrapper);
        return count;
    }


    @Override
    public Object patrolInspection() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String sameDay = format.format(new Date());
        Integer completedCount = 0;
        Integer undoneCount = 0;
        String startTime = null;
        String endTime = null;
        List<Object> data1 = new ArrayList<>();
        List<Object> data2 = new ArrayList<>();
        List<Object> data3 = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            if (i == 0) {
                startTime = sameDay;
                endTime = sameDay;
            } else if (i == 1) {
                long timeStamp = OnlineMethod.getLastPeroid(1, new Date());
                startTime = format.format(timeStamp);
                endTime = sameDay;
            } else if (i == 2) {
                long timeStamp = OnlineMethod.getLastPeroid(2, new Date());
                startTime = format.format(timeStamp);
                endTime = sameDay;
            }
            List<Integer> planSonIdList1 = this.planSonIdList(startTime, endTime);
            if (CollectionUtils.isNotEmpty(planSonIdList1)) {
                undoneCount = patrolInspectionPlanSiteSonService.siteCount(planSonIdList1, 1);
                completedCount = patrolInspectionPlanSiteSonService.siteCount(planSonIdList1, 2);
            }

            for (int j = 0; j < 4; j++) {
                Map<String, Object> map1 = new HashMap<>();
                switch (j) {
                    case 0:
                        if (i == 0) {
                            map1.put("name", "今日巡检次数");
                        } else if (i == 1) {
                            map1.put("name", "近七日巡检次数");
                        } else if (i == 2) {
                            map1.put("name", "近一月巡检次数");
                        }
                        map1.put("value", undoneCount + completedCount);
                        map1.put("mark", "");
                        break;
                    case 1:
                        map1.put("name", "巡检率");
                        if (undoneCount == 0 && completedCount == 0) {
                            map1.put("value", 0);
                        } else {
//                            completedCount = 1;
//                            undoneCount = 3;
                            double Ratio = Arith.div(completedCount, undoneCount + completedCount, 2) * 100;
                            map1.put("value", Ratio);
//                            map1.put("value", completedCount / (undoneCount + completedCount) * 100);
                        }

                        map1.put("mark", "%");
                        break;
                    case 2:
                        map1.put("name", "合格数");
                        map1.put("value", completedCount);
                        map1.put("mark", "");
                        break;
                    case 3:
                        map1.put("name", "漏检数");
                        map1.put("value", undoneCount);
                        map1.put("mark", "");
                        break;
                }
                if (i == 0) {
                    data1.add(map1);
                } else if (i == 1) {
                    data2.add(map1);
                } else if (i == 2) {
                    data3.add(map1);
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("data1", data1);
        map.put("data2", data2);
        map.put("data3", data3);
        return map;
    }


    @Override
    public List<Integer> planSonIdList(String startDate, String endDate) {
        List<Integer> planSonIdList = new ArrayList<>();
        LambdaQueryWrapper<PatrolInspectionPlan> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.select(PatrolInspectionPlan::getId)
//                .eq(PatrolInspectionPlan::getTenantId, SecurityUtils.getTenantId())
                .eq(PatrolInspectionPlan::getEnable, 1);
        List<PatrolInspectionPlan> planList = patrolInspectionPlanService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(planList)) {
            List<Integer> planIdList = new ArrayList<>();
            for (int i = 0; i < planList.size(); i++) {
                planIdList.add(planList.get(i).getId());
            }
            List<PatrolInspectionPlanSon> planSonList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(planIdList)) {
                LambdaQueryWrapper<PatrolInspectionPlanSon> queryWrapper1 = Wrappers.lambdaQuery();
                queryWrapper1.select(PatrolInspectionPlanSon::getId)
                        .in(PatrolInspectionPlanSon::getPlanId, planIdList)
                        .between(PatrolInspectionPlanSon::getInspectionDate, startDate, endDate);
                planSonList = patrolInspectionPlanSonService.list(queryWrapper1);
            }
            for (int i = 0; i < planSonList.size(); i++) {
                planSonIdList.add(planSonList.get(i).getId());
            }
        }
        return planSonIdList;
    }

    @Override
    public Object streetCompany() {
        List<String> streetTownList = new ArrayList<>();
        streetTownList.add("华漕镇");
        streetTownList.add("新虹街道");
        streetTownList.add("七宝镇");
        streetTownList.add("虹桥镇");
        streetTownList.add("古美路街道");
        streetTownList.add("莘庄镇");
        streetTownList.add("梅陇镇");
        streetTownList.add("颛桥镇");
        streetTownList.add("马桥镇");
        streetTownList.add("江川路街道");
        streetTownList.add("吴泾镇");
        streetTownList.add("浦锦街道");
        streetTownList.add("浦江镇");
        QueryWrapper<BaseCompany> query = Wrappers.query();
        query.select("street_town as streetTown", "company_type as companyType", "count(id) as count")
                .eq("enable", 0)
//                .ne("street_town", "")
                .in("street_town", streetTownList)
                .groupBy("street_town,company_type");
        List<Map<String, Object>> list1 = baseCompanyService.listMaps(query);

        QueryWrapper<BaseCompany> query1 = Wrappers.query();
        query1.select("street_town as streetTown")
                .eq("enable", 0)
//                .ne("street_town", "")
                .in("street_town", streetTownList)
                .groupBy("street_town");
        List<Map<String, Object>> list2 = baseCompanyService.listMaps(query1);

        List<Map<String, Object>> stressList = new ArrayList<>();
        List<Map<String, Object>> generalList = new ArrayList<>();
        List<Map<String, Object>> otherList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list1)) {
            for (int i = 0; i < list1.size(); i++) {
                switch (list1.get(i).get("companyType").toString()) {
                    case "1":
                        stressList.add(list1.get(i));
                        break;
                    case "2":
                        generalList.add(list1.get(i));
                        break;
                    default:
                        otherList.add(list1.get(i));
                        break;
                }
            }
        }

        List<Object> data = new ArrayList<>();
        for (int i = 0; i < list2.size(); i++) {
            Map<String, Object> map1 = new HashMap<>();
            map1.put("name", list2.get(i).get("streetTown"));
            map1.put("stress", 0);
            map1.put("general", 0);
            map1.put("other", 0);
            for (int j = 0; j < stressList.size(); j++) {
                if (list2.get(i).get("streetTown").equals(stressList.get(j).get("streetTown"))) {
                    map1.put("stress", stressList.get(j).get("count"));
                }
            }

            for (int j = 0; j < generalList.size(); j++) {
                if (list2.get(i).get("streetTown").equals(generalList.get(j).get("streetTown"))) {
                    map1.put("general", generalList.get(j).get("count"));
                }
            }
            for (int j = 0; j < otherList.size(); j++) {
                if (list2.get(i).get("streetTown").equals(otherList.get(j).get("streetTown"))) {
                    map1.put("other", otherList.get(j).get("count"));
                }
            }
            data.add(map1);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("data", data);
        return map;
    }

    @Override
    public Map<String, Object> iotDisposal(String streetTown, String startDate, String endDate) {
        List<String> companyIdList = new ArrayList<>();
        if (StringUtils.isNotBlank(streetTown)) {
            companyIdList = baseCompanyService.companyIdList(streetTown);
        }
        int alarmUntreatedCount = this.alarmCount(companyIdList, 0, startDate, endDate);
        int alarmProcessedCount = this.alarmCount(companyIdList, 1, startDate, endDate);
        int alarmCount = alarmUntreatedCount + alarmProcessedCount;
        double alarmProcessedRate = Arith.div(alarmProcessedCount, alarmCount, 2) * 100;
        Map<String, Object> map = new HashMap<>();
        map.put("alarmCount", alarmCount);
        map.put("alarmProcessedCount", alarmProcessedCount);
        map.put("alarmProcessedRate", alarmProcessedRate + "%");
        return map;
    }

    @Override
    public int alarmCount(List<String> companyIdList, Integer handlingStatus, String startDate, String endDate) {
        int count1 = alarmElectricalFireService.electricalFireCount(companyIdList, handlingStatus, null, startDate, endDate);
        int count2 = alarmSprayWaterService.sprayWaterCount(companyIdList, handlingStatus, null, startDate, endDate);
        int count3 = alarmHydrantWaterService.hydrantWaterCount(companyIdList, handlingStatus, null, startDate, endDate);
        int count4 = alarmSmokeControlService.smokeCount(companyIdList, handlingStatus, null, startDate, endDate);
        int count5 = alarmVideoService.videoCount(companyIdList, handlingStatus, null, startDate, endDate);
        int count6 = alarmFireService.fireCount(companyIdList, handlingStatus, null, null, startDate, endDate);
        int count = count1 + count2 + count3 + count4 + count5 + count6;
        return count;
    }

    @Override
    public List<Map<String, Object>> streetDynamic() {
        List<Map<String, Object>> list = new ArrayList<>();
        List<String> streetTownList = new ArrayList<>();
        streetTownList.add("华漕镇");
        streetTownList.add("新虹街道");
        streetTownList.add("七宝镇");
        streetTownList.add("虹桥镇");
        streetTownList.add("古美路街道");
        streetTownList.add("莘庄镇");
        streetTownList.add("梅陇镇");
        streetTownList.add("颛桥镇");
        streetTownList.add("马桥镇");
        streetTownList.add("江川路街道");
        streetTownList.add("吴泾镇");
        streetTownList.add("浦锦街道");
        streetTownList.add("浦江镇");
        List<DataCountVo> dataCountVos = baseMapper.deviceStatusCount(streetTownList);
        for (int i = 0; i < streetTownList.size(); i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("streetTown", streetTownList.get(i));
            map.put("processedRate", "0%");
            List<String> companyIdList = baseCompanyService.companyIdList(streetTownList.get(i));
            if (CollectionUtils.isNotEmpty(companyIdList)) {
                int alarmUntreatedCount = this.alarmCount(companyIdList, 0, null, null);
                int alarmProcessedCount = this.alarmCount(companyIdList, 1, null, null);
                double alarmProcessedRate = Arith.div(alarmProcessedCount, alarmUntreatedCount + alarmProcessedCount, 2) * 100;
                map.put("processedRate", alarmProcessedRate + "%");
            }
            int deviceCount = 0;
            int onLineCount = 0;
            for (int j = 0; j < dataCountVos.size(); j++) {
                if (streetTownList.get(i).equals(dataCountVos.get(j).getListName())) {
                    deviceCount = deviceCount + dataCountVos.get(j).getListCount();
                    if (dataCountVos.get(j).getListType() == 1) {
                        onLineCount = onLineCount + dataCountVos.get(j).getListCount();
                    }
                }
            }
            map.put("deviceCount", deviceCount);
            map.put("onLineCount", onLineCount);
            double onLineRate = Arith.div(onLineCount, deviceCount, 2) * 100;
            map.put("onLineRate", onLineRate + "%");
            list.add(map);
        }
        return list;
    }
    @Override
    public List<Map<String, Object>> scatterData(String companyId) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<BaseCompany> list2 = new ArrayList<>();
        LambdaQueryWrapper<BaseCompany> queryWrapper1 = Wrappers.lambdaQuery();
        queryWrapper1.select(BaseCompany::getId, BaseCompany::getCompanyName, BaseCompany::getCompanyType,
                BaseCompany::getLinkPhone,BaseCompany::getAddress,
                BaseCompany::getCompanyId)
                .eq(BaseCompany::getCompanyId, companyId);
        list2 = baseCompanyService.list(queryWrapper1);
        List<ReportIndexResult> list3 = new ArrayList<>();
        LambdaQueryWrapper<ReportIndexResult> queryWrapper2 = Wrappers.lambdaQuery();
        queryWrapper2.select(ReportIndexResult::getId, ReportIndexResult::getIndexCode, ReportIndexResult::getIndexName,
                ReportIndexResult::getIndexScore,ReportIndexResult::getCreateDate,
                ReportIndexResult::getIndexData,ReportIndexResult::getIndexData,ReportIndexResult::getScoreDesc)
                .eq(ReportIndexResult::getObjectId, list2.get(0).getId())
                .orderByDesc(ReportIndexResult::getId).last(" limit 74");
        list3 = reportIndexResultService.list(queryWrapper2);
        List<DemFireReform> list4 = new ArrayList<>();
        LambdaQueryWrapper<DemFireReform> queryWrapper3 = Wrappers.lambdaQuery();
        queryWrapper3.select(DemFireReform::getId, DemFireReform::getCompanyId, DemFireReform::getReformPart,
                DemFireReform::getSendTime,DemFireReform::getReformStatus,
                DemFireReform::getLimitTime,DemFireReform::getReformCode)
                .eq(DemFireReform::getCompanyId, companyId)
                .orderByDesc(DemFireReform::getId).last(" limit 1");
        list4 = demFireReformService.list(queryWrapper3);
        List<DemReformReview> list5 = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list4)) {
            LambdaQueryWrapper<DemReformReview> queryWrapper4 = Wrappers.lambdaQuery();
            queryWrapper4.select(DemReformReview::getId, DemReformReview::getReformId, DemReformReview::getReformTime,
                    DemReformReview::getReviewTime)
                    .eq(DemReformReview::getReformId, list4.get(0).getId())
                    .orderByDesc(DemReformReview::getId).last(" limit 1");
            list5 = demReformReviewService.list(queryWrapper4);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("companyName", list2.get(0).getCompanyName());
        map.put("companyType", list2.get(0).getCompanyType());
        map.put("linkPhone", list2.get(0).getLinkPhone());
        map.put("address", list2.get(0).getAddress());
        if (CollectionUtils.isNotEmpty(list3)) {
            for (int i = 0; i < list3.size(); i++) {
                if (list3.get(i).getIndexCode().equals("10001")){
                    map.put("buildIntegrity", list3.get(i).getIndexScore());
                }else if (list3.get(i).getIndexCode().equals("10003")){
                    map.put("facilityStatus", list3.get(i).getIndexScore());
                }else if (list3.get(i).getIndexCode().equals("10004")){
                    map.put("selfManage", list3.get(i).getIndexScore());
                }else if (list3.get(i).getIndexCode().equals("10005")){
                    map.put("lawEnforce", list3.get(i).getIndexScore());
                }else if (list3.get(i).getIndexCode().equals("10006")){
                    map.put("fireRisk", list3.get(i).getIndexScore());
                }
            }
        }else {
            map.put("buildIntegrity", 0);
            map.put("facilityStatus", 0);
            map.put("selfManage", 0);
            map.put("lawEnforce", 0);
            map.put("fireRisk", 0);
        }
        if (CollectionUtils.isNotEmpty(list4)) {
            map.put("reformCode", list4.get(0).getReformCode());
            map.put("limitTime", list4.get(0).getLimitTime());
            Object data = null;
            data = list4.get(0).getReformPart();
            JSONObject jsonObject = JSONObject.parseObject(data.toString());
            map.put("reformPart", jsonObject);
            map.put("receivedTime", list4.get(0).getSendTime());
            map.put("reformStatus", list4.get(0).getReformStatus());
        }else {
            map.put("reformCode", "");
            map.put("limitTime", "");
            map.put("reformPart", null);
            map.put("receivedTime", "");
            map.put("reformStatus", "");
        }
        if (CollectionUtils.isNotEmpty(list5)) {
            map.put("reformTime", list5.get(0).getReformTime());
            map.put("reviewTime", list5.get(0).getReviewTime());
        }else {
            map.put("reformTime", "");
            map.put("reviewTime", "");
        }
        list.add(map);
        return list;
    }
}
