package com.testor.module.globalAlarm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.biz.sys.org.model.domain.SysOrg;
import com.testor.biz.sys.org.service.SysOrgService;
import com.testor.common.constant.DefaultRule;
import com.testor.module.globalAlarm.dao.TGlobalAlarmDao;
import com.testor.module.globalAlarm.model.domain.TGlobalAlarm;
import com.testor.module.globalAlarm.model.dto.TGlobalAlarmParam;
import com.testor.module.globalAlarm.service.TGlobalAlarmService;
import com.tongtech.tfw.backend.common.biz.constants.BizConstants;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.context.ContextUtils;
import com.tongtech.tfw.backend.common.models.supers.SuperServiceImpl;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 全局报警Service业务层处理
 *
 * @author testor-framework
 * @date 2023-02-08 11:09:19
 */
@Service
public class TGlobalAlarmServiceImpl extends SuperServiceImpl<TGlobalAlarmDao, TGlobalAlarm> implements TGlobalAlarmService {
    @Autowired(required = false)
    private TGlobalAlarmDao tGlobalAlarmDao;
    @Autowired
    private SysRuleService sysRuleService;


    @Autowired
    private SysOrgService sysOrgService;

    @Override
    public BaseResponse<List<TGlobalAlarmParam>> getTimeFrame(TGlobalAlarmParam tGlobalAlarmParam) {
        BaseResponse<List<TGlobalAlarmParam>> response = new BaseResponse<>();
        List<TGlobalAlarmParam> alarmParams = new ArrayList<>();
        String orgId = tGlobalAlarmParam.getOrgId();
        QueryWrapper<TGlobalAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(TGlobalAlarm.DISPOSE_STATUS, "1");
        queryWrapper.ne(TGlobalAlarm.DISPOSE_STATUS, "2");


        if (StringHelper.isEmpty(orgId)) {
            orgId = ContextUtils.getLoginUser().getOrgId();
            SysOrg one = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, orgId));
            String rule = "";
            if ("3".equals(one.getTreeLevel().toString())) {
                // 获取本级及一下数据
                rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_SUB.name());
            } else {
                rule = sysRuleService.dataRuleScope(DefaultRule.SUB_ORG.name());
            }
            if (StringUtils.isNotEmpty(rule)) {
                queryWrapper.apply(rule);
            }
        } else {
            SysOrg one = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, orgId));
            QueryWrapper<SysOrg> sysOrgQueryWrapper = new QueryWrapper<>();
            sysOrgQueryWrapper.apply("FIND_IN_SET ('" + orgId + "',parent_ids)");
            if ("3".equals(one.getTreeLevel().toString())) {
                sysOrgQueryWrapper.or().eq(SysOrg.ORG_ID, orgId);
            }
            List<String> collect = sysOrgService.list(sysOrgQueryWrapper).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
//            List<String> collect = sysOrgService.list(new QueryWrapper<SysOrg>().apply("FIND_IN_SET ('" + orgId + "',parent_ids)")
//                    .or().eq(SysOrg.ORG_ID, orgId)
//            ).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            queryWrapper.in(TGlobalAlarm.ORG_ID, collect);
        }
        if (StringHelper.isNotEmpty(tGlobalAlarmParam.getStartTime()) &&
                StringHelper.isNotEmpty(tGlobalAlarmParam.getEndTime())) {
            queryWrapper.between(TGlobalAlarm.SJ_DATE, tGlobalAlarmParam.getStartTime(), tGlobalAlarmParam.getEndTime());
        }
        List<TGlobalAlarm> list = this.list(queryWrapper);

        Map<Integer, List<TGlobalAlarm>> listMap = list.stream().collect(Collectors.groupingBy(e -> {
            String sjDate = e.getSjDate();
            Date parse = null;
            try {
                parse = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sjDate);
            } catch (ParseException parseException) {
                parseException.printStackTrace();
            }
            SimpleDateFormat format = new SimpleDateFormat("HH");

            String hour = format.format(parse);
            return Integer.valueOf(hour);
        }));

        for (int i = 0; i < 24; i = i + 2) {
            TGlobalAlarmParam alarmParam = new TGlobalAlarmParam();
            if (i % 4 == 0) {
                alarmParam.setEndTime(i + "时~" + (i + 2) + "时");
            } else {
                alarmParam.setEndTime("");
            }
            List<TGlobalAlarm> tGlobalAlarms = listMap.get(i);
            List<TGlobalAlarm> tGlobalAlarms1 = listMap.get(i + 1);

            //数量相加
            alarmParam.setNum((long) ((CollectionUtils.isNotEmpty(tGlobalAlarms) ? tGlobalAlarms.size() : 0)
                    + (CollectionUtils.isNotEmpty(tGlobalAlarms1) ? tGlobalAlarms1.size() : 0)));
            alarmParams.add(alarmParam);
        }
        List<TGlobalAlarmParam> params = new ArrayList<>();
        TGlobalAlarmParam globalAlarmParam = new TGlobalAlarmParam();
        globalAlarmParam.setGlobalAlarms(alarmParams);
        params.add(globalAlarmParam);
        globalAlarmParam.setJgName("报警时段统计");
        response.setData(params);
        return response;
    }

    @Override
    public BaseResponse<List<TGlobalAlarmParam>> getAlarmType(TGlobalAlarmParam tGlobalAlarmParam) {
        BaseResponse<List<TGlobalAlarmParam>> response = new BaseResponse<>();
        String orgId = tGlobalAlarmParam.getOrgId();
        QueryWrapper<TGlobalAlarm> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne(TGlobalAlarm.DISPOSE_STATUS, "1");
        queryWrapper.ne(TGlobalAlarm.DISPOSE_STATUS, "2");


        if (StringHelper.isEmpty(orgId)) {
            orgId = ContextUtils.getLoginUser().getOrgId();
            SysOrg one = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, orgId));
            String rule = "";
            if ("3".equals(one.getTreeLevel().toString())) {
                // 获取本级及一下数据
                rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_SUB.name());
            } else {
                rule = sysRuleService.dataRuleScope(DefaultRule.SUB_ORG.name());
            }
            if (StringUtils.isNotEmpty(rule)) {
                queryWrapper.apply(rule);
            }
        } else {
            SysOrg one = sysOrgService.getOne(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, orgId));
            QueryWrapper<SysOrg> sysOrgQueryWrapper = new QueryWrapper<>();
            sysOrgQueryWrapper.apply("FIND_IN_SET ('" + orgId + "',parent_ids)");
            if ("3".equals(one.getTreeLevel().toString())) {
                sysOrgQueryWrapper.or().eq(SysOrg.ORG_ID, orgId);
            }
//            List<String> collect = sysOrgService.list(new QueryWrapper<SysOrg>().apply("FIND_IN_SET ('" + orgId + "',parent_ids)")
//                    .or().eq(SysOrg.ORG_ID, orgId)
//            ).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            List<String> collect = sysOrgService.list(sysOrgQueryWrapper).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            queryWrapper.in(TGlobalAlarm.ORG_ID, collect);
        }
        if (StringHelper.isNotEmpty(tGlobalAlarmParam.getStartTime()) &&
                StringHelper.isNotEmpty(tGlobalAlarmParam.getEndTime())) {
            queryWrapper.between(TGlobalAlarm.SJ_DATE, tGlobalAlarmParam.getStartTime(), tGlobalAlarmParam.getEndTime());
        }
        List<TGlobalAlarm> list = this.list(queryWrapper);
        Map<String, List<TGlobalAlarm>> map = list.stream().filter(item -> StringUtils.isNotBlank(item.getEventType())).collect(Collectors.groupingBy(TGlobalAlarm::getEventType));
//        HashMap<String, Integer> hashMap = new HashMap<>();

        List<TGlobalAlarmParam> alarms = new ArrayList<>();
        for (Map.Entry<String, List<TGlobalAlarm>> entry : map.entrySet()) {
            TGlobalAlarmParam globalAlarm = new TGlobalAlarmParam();
            globalAlarm.setEventType(entry.getKey());
            globalAlarm.setNum((long) entry.getValue().size());
            alarms.add(globalAlarm);
//            hashMap.put(entry.getKey(), entry.getValue().size());
        }
        tGlobalAlarmParam.setGlobalAlarms(alarms);
        tGlobalAlarmParam.setJgName("报警类型统计");
        List<TGlobalAlarmParam> alarmArrayList = new ArrayList<>();
        alarmArrayList.add(tGlobalAlarmParam);
        response.setData(alarmArrayList);
        return response;
    }

    @Override
    public BaseResponse<List<TGlobalAlarmParam>> quantityStatistics(TGlobalAlarmParam tGlobalAlarmParam) {
        BaseResponse<List<TGlobalAlarmParam>> response = new BaseResponse<>();
        List<TGlobalAlarmParam> alarmParams = getGlobalAlarmData(tGlobalAlarmParam);
        response.setData(alarmParams);
        return response;
    }

    private List<TGlobalAlarmParam> getGlobalAlarmData(TGlobalAlarmParam tGlobalAlarmParam) {
        String orgId = tGlobalAlarmParam.getOrgId();
        if (StringHelper.isEmpty(orgId)) {
            orgId = ContextUtils.getLoginUser().getOrgId();
        }
        SysOrg org = sysOrgService.getById(orgId);
        List<String> orgIds = getIds(org);
        List<TGlobalAlarmParam> globalAlarmParamArrayList = new ArrayList<>();

        orgIds.stream().forEach(item -> {
            TGlobalAlarmParam alarmParam = new TGlobalAlarmParam();
            List<String> ids = new ArrayList<>();
            if ("1".equals(org.getTreeLevel().toString())) {
                ids = sysOrgService.list(new QueryWrapper<SysOrg>().like(SysOrg.PARENT_IDS, item).or().eq(SysOrg.ORG_ID, item)
                        .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0)).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            }
            if ("2".equals(org.getTreeLevel().toString()) || "3".equals(org.getTreeLevel().toString())) {
                ids = sysOrgService.list(new QueryWrapper<SysOrg>().like(SysOrg.ORG_ID, item)
                        .ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0)).stream().map(SysOrg::getOrgId).collect(Collectors.toList());
            }

            QueryWrapper<TGlobalAlarm> queryWrapper = new QueryWrapper<>();
            if (StringHelper.isNotEmpty(tGlobalAlarmParam.getStartTime()) &&
                    StringHelper.isNotEmpty(tGlobalAlarmParam.getEndTime())) {
                queryWrapper.between(TGlobalAlarm.SJ_DATE, tGlobalAlarmParam.getStartTime(), tGlobalAlarmParam.getEndTime());
            }
            if (ids.size() <= 0) {
                ids.add("11111111111");
            }

            queryWrapper.in(TGlobalAlarm.ORG_ID, ids);

            List<TGlobalAlarm> list = this.list(queryWrapper);
            long count = list.stream().filter(TG -> !TG.getDisposeStatus().equals("1")
                    && !TG.getDisposeStatus().equals("2")).count();

            alarmParam.setOrgId(item);
            alarmParam.setOrgName(sysOrgService.getById(item).getOrgName());
            alarmParam.setNum(count);
            globalAlarmParamArrayList.add(alarmParam);
        });

        return globalAlarmParamArrayList;
    }


    private List<String> getIds(SysOrg org) {
        List<String> orgIds = new ArrayList<>();
        if (!"3".equals(org.getTreeLevel().toString())) {
            orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.PARENT_ID, org.getOrgId()).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0))
                    .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
        } else {
            orgIds = sysOrgService.list(new QueryWrapper<SysOrg>().eq(SysOrg.ORG_ID, org.getOrgId()).ne(SysOrg.STATUS, BizConstants.STATUS_DELETE).eq(SysOrg.IS_DEPT, 0))
                    .stream().map(SysOrg::getOrgId).collect(Collectors.toList());
        }
        return orgIds;
    }
}
