package com.ozs.web.controller.accountmanagment;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ozs.common.annotation.Log;
import com.ozs.common.core.controller.BaseController;
import com.ozs.common.core.domain.AjaxResult;
import com.ozs.common.enums.BusinessType;
import com.ozs.common.utils.AppendUtils;
import com.ozs.common.utils.StringUtils;
import com.ozs.common.utils.poi.ExcelUtil;
import com.ozs.entity.BaseUser;
import com.ozs.entity.BaseTerminal;
import com.ozs.entity.BaseVehicle;
import com.ozs.entity.vo.*;
import com.ozs.service.*;
import com.ozs.system.service.ISysDictDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.NumberFormat;
import java.util.*;

/**
 * @author wyy
 * @subject
 * @creat 2023/4/13
 */
@RestController
@RequestMapping("/service/dataStatistic")
public class DataStatisticController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(DataStatisticController.class);
    @Resource
    private MsgAlarmService msgAlarmService;
    @Resource
    private BaseUserService baseUserService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private BaseVehicleService baseVehicleService;
    @Autowired
    private BaseCameraManagementService baseCameraManagementService;
    @Autowired
    private BaseTerminalService baseTerminalService;

    /**
     * 首页-信息统计
     *
     * @param
     * @return
     */
    @PostMapping("/getMessageStatistics")
    @Log(title = "首页-信息统计", businessType = BusinessType.SELECT)
    public AjaxResult getMessageStatistics() {
        Map<String, Integer> cameraCount = baseCameraManagementService.getMessageStatisticsCamera();
        Map<String, Integer> terminalCount = baseTerminalService.getMessageStatisticsTerminal();
        Map<String, Integer> mapAll = new HashMap<>();
        mapAll.putAll(cameraCount);
        mapAll.putAll(terminalCount);
        return AjaxResult.success(mapAll);
    }

    /**
     * web数据统计
     *
     * @param alarmStatisticResVo
     * @return
     */
    @Log(title = "报警数据详情", businessType = BusinessType.SELECT)
    @PostMapping("/dataStatistic")
    public AjaxResult dataStatistic(@RequestBody AlarmStatisticResVo alarmStatisticResVo) {
        Integer pageNum = alarmStatisticResVo.getPageNum().intValue();
        Integer pageSize = alarmStatisticResVo.getPageSize().intValue();
        List<AlarmStatisticDto> list = msgAlarmService.list(alarmStatisticResVo.getRailwayCode(), alarmStatisticResVo.getCurrentYear(),
                alarmStatisticResVo.getCurrentMonth(), pageNum, pageSize);
        if (!ObjectUtils.isEmpty(list)) {
            list.forEach(l -> {
                if (!ObjectUtils.isEmpty(l.getAlarmMile())) {
                    l.setAlarmMiles(AppendUtils.stringAppend(Integer.valueOf(l.getAlarmMile())));
                }
                if (StringUtils.isNotEmpty(l.getReleasedBy())) {
                    BaseUser buser = baseUserService.getUser(l.getReleasedBy());
                    l.setReleasedByName(buser.getNickName());
                }

                if (!ObjectUtils.isEmpty(l.getLineDir())) {
                    l.setLineDirName(l.getLineDir() == 1 ? "上行" : "下行");
                }
                if (!ObjectUtils.isEmpty(l.getAlarmType())) {
                    l.setAlarmTypeName(dictDataService.selectDictLabel("sys_alarm_type", String.valueOf(l.getAlarmType())));
                }
                if (!ObjectUtils.isEmpty(l.getIsRelease())) {
                    l.setIsReleaseName(l.getIsRelease() == 1 ? "已解除" : "未解除");
                }
            });
        }
        IPage page = msgAlarmService.listToPage(list, pageNum, pageSize);
        return AjaxResult.success(page);
    }

    /**
     * web数据统计
     *
     * @param
     * @return
     */
    @Log(title = "报警月统计", businessType = BusinessType.SELECT)
    @PostMapping("/alarmMonthStatistic")
    public AjaxResult alarmMonthStatistic(@RequestBody AlarmStatisticResVo alarmStatisticResVo) {
        List<Integer> numbs = new ArrayList<>();
        Integer listSize;
        List<AlarmStatisticMonthDto> list = null;
        if (ObjectUtils.isEmpty(alarmStatisticResVo.getCurrentMonth())) {
            list = msgAlarmService.getCount(alarmStatisticResVo.getRailwayCode(), alarmStatisticResVo.getCurrentYear(),
                    alarmStatisticResVo.getCurrentMonth());
            listSize = 12;
        } else {
            if (alarmStatisticResVo.getCurrentMonth().equals(2)) {//2
                listSize = 28;
            } else if (alarmStatisticResVo.getCurrentMonth().equals(4) || alarmStatisticResVo.getCurrentMonth().equals(6) ||
                    alarmStatisticResVo.getCurrentMonth().equals(9) || alarmStatisticResVo.getCurrentMonth().equals(11)) {//4,6,9,11
                listSize = 30;
            } else {//1,3,5,7,8,10,12
                listSize = 31;
            }
            list = msgAlarmService.getDayCount(alarmStatisticResVo.getRailwayCode(), alarmStatisticResVo.getCurrentYear(),
                    alarmStatisticResVo.getCurrentMonth());
        }
        for (int i = 1; i <= listSize; i++) {
            numbs.add(i);
        }

        List<Integer> list1 = new ArrayList<>();
        if (!CollectionUtils.isEmpty(list) && Objects.nonNull(list.get(0))) {
            list.forEach(l -> {
                list1.add(l.getMonthsta());
            });
        }
        AlarmStatisticMonthDto dto;
        for (int i = 0; i < numbs.size(); i++) {
            if (!list1.contains(numbs.get(i))) {
                dto = new AlarmStatisticMonthDto();
                dto.setMonthsta(numbs.get(i));
                dto.setFrequency(0);
                list.add(dto);
            }
        }
        if (!CollectionUtils.isEmpty(list) && Objects.nonNull(list.get(0))) {
            Collections.sort(list, new Comparator<AlarmStatisticMonthDto>() {
                @Override
                public int compare(AlarmStatisticMonthDto o1, AlarmStatisticMonthDto o2) {

                    return o1.getMonthsta().compareTo(o2.getMonthsta());
                }
            });
        }
        return AjaxResult.success(list);
    }

    /**
     * web数据统计
     *
     * @param
     * @return
     */
    @Log(title = "灾害类型统计", businessType = BusinessType.SELECT)
    @PostMapping("/alarmTypeStatistic")
    public AjaxResult alarmTypeStatistic(@RequestBody AlarmStatisticResVo alarmStatisticResVo) {
        List<AlarmStatisticMonthDto> list = msgAlarmService.getAlarmTypeCount(alarmStatisticResVo.getRailwayCode(), alarmStatisticResVo.getCurrentYear(),
                alarmStatisticResVo.getCurrentMonth());
        Integer sum = list.stream().mapToInt((x) -> Integer.parseInt(String.valueOf(x.getFrequency()))).sum();
        NumberFormat numberFormat = NumberFormat.getPercentInstance();
        numberFormat.setMinimumFractionDigits(2);
        if (!CollectionUtils.isEmpty(list) && list.size() != 0) {
            list.forEach(l -> {
                if (!ObjectUtils.isEmpty(l.getAlarmType())) {
                    l.setAlarmTypeValue(dictDataService.selectDictLabel("sys_alarm_type", String.valueOf(l.getAlarmType())));
                }
                l.setPercent(numberFormat.format(l.getFrequency() * 1.0 / sum));
            });
        }
        return AjaxResult.success(list);
    }

    /**
     * web数据统计
     *
     * @param
     * @return
     */
    @Log(title = "频繁出现灾害地点排名", businessType = BusinessType.SELECT)
    @PostMapping("/alarmTypeAreaCount")
    public AjaxResult alarmTypeAreaCount(@RequestBody AlarmStatisticResVo alarmStatisticResVo) {
        Integer pageNum = alarmStatisticResVo.getPageNum().intValue();
        Integer pageSize = alarmStatisticResVo.getPageSize().intValue();
        List<AlarmFreqArea> list = msgAlarmService.alarmTypeAreaCount(alarmStatisticResVo.getRailwayCode(), alarmStatisticResVo.getCurrentYear(),
                alarmStatisticResVo.getCurrentMonth());
        if (!CollectionUtils.isEmpty(list) && Objects.nonNull(list.get(0))) {
            list.forEach(l -> {
                if (!ObjectUtils.isEmpty(l.getAlarmMile())) {
                    l.setAlarmMiles(AppendUtils.stringAppend(Integer.valueOf(l.getAlarmMile())));
                }
                if (!ObjectUtils.isEmpty(l.getLineDir())) {
                    l.setLineDirStr(l.getLineDir() == 1 ? "上行" : "下行");
                }
            });
        }
        IPage page = msgAlarmService.listToPage(list, pageNum, pageSize);
        if (!ObjectUtils.isEmpty(page) && !ObjectUtils.isEmpty(page.getRecords())) {
            return AjaxResult.success(page);
        }
        return AjaxResult.success(null);
    }

    /**
     * web数据统计
     *
     * @param
     * @return
     */
    @Log(title = "频繁出现灾害地点排导出", businessType = BusinessType.EXPORT)
    @PostMapping("/alarmTypeAreaCountExport")
    public void alarmTypeAreaCountExport(HttpServletResponse response, @RequestBody AlarmStatisticResVo alarmStatisticResVo) {
        List<AlarmFreqArea> list = msgAlarmService.alarmTypeAreaCount(alarmStatisticResVo.getRailwayCode(), alarmStatisticResVo.getCurrentYear(),
                alarmStatisticResVo.getCurrentMonth());
        if (!CollectionUtils.isEmpty(list) && Objects.nonNull(list.get(0))) {
            list.forEach(l -> {
                if (!ObjectUtils.isEmpty(l.getAlarmMile())) {
                    l.setAlarmMiles(AppendUtils.stringAppend(Integer.valueOf(l.getAlarmMile())));
                }
                if (!ObjectUtils.isEmpty(l.getLineDir())) {
                    l.setLineDirStr(l.getLineDir() == 1 ? "上行" : "下行");
                }
            });
            ExcelUtil<AlarmFreqArea> util = new ExcelUtil<>(AlarmFreqArea.class);
            util.exportExcel(response, list, "频繁出现灾害地点排导出");
        }
    }

    /**
     * web数据统计 数据导出
     *
     * @param
     * @return
     */
    @Log(title = "报警详情导出管理", businessType = BusinessType.EXPORT)
    @PostMapping("/exportDataStatistic")
    public void exportDataStatistic(HttpServletResponse response, @RequestBody AlarmStatisticResVo alarmStatisticResVo) {
        try {
            List<AlarmStatisticDto> list = msgAlarmService.exportExcel(alarmStatisticResVo);
            if (!CollectionUtils.isEmpty(list) && Objects.nonNull(list.get(0))) {
                list.forEach(l -> {
                    if (!ObjectUtils.isEmpty(l.getAlarmMile())) {
                        l.setAlarmMiles(AppendUtils.stringAppend(Integer.valueOf(l.getAlarmMile())));
                    }
                    if (StringUtils.isNotEmpty(l.getReleasedBy())) {
                        BaseUser buser = baseUserService.getUser(l.getReleasedBy());
                        l.setReleasedByName(buser.getNickName());
                    }
                    if (!ObjectUtils.isEmpty(l.getAlarmType())) {
                        String alarmType = l.getAlarmType();
                        String alarmTypeName = dictDataService.selectDictLabel("sys_alarm_type", alarmType);
                        l.setAlarmTypeName(alarmTypeName);
                    }
                    if (!ObjectUtils.isEmpty(l.getLineDir())) {
                        l.setLineDirName(l.getLineDir() == 1 ? "上行" : "下行");
                    }
                    if (!ObjectUtils.isEmpty(l.getIsRelease())) {
                        l.setIsReleaseName(l.getIsRelease() == 1 ? "已解除" : "未解除");
                    }
                    if (!ObjectUtils.isEmpty(l.getAlarmAttr())) {
                        String[] split1 = l.getAlarmAttr().split(",");
                        String stringBuilder = "画面,大小为" + split1[0] + "×" + split1[1] + "," +
                                "泥石流范围为左上角坐标(" + split1[2] + "," + split1[3] + ")" +
                                "大小" + split1[4] + "×" + split1[5];
                        l.setAlarmAttrString(stringBuilder);
                    }
                });
            }

            ExcelUtil<AlarmStatisticDto> util = new ExcelUtil<>(AlarmStatisticDto.class);
            util.exportExcel(response, list, "报警数据详情");
        } catch (Exception e) {
            e.printStackTrace();
            log.info(e.getMessage());
        }
    }

    /**
     * web数据统计 报警月统计数据导出
     *
     * @param
     * @return
     */
    @Log(title = "报警月统计数据导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportDataStatisticMonth")
    public void exportDataStatisticMonth(HttpServletResponse response, @RequestBody AlarmStatisticResVo alarmStatisticResVo) {
        List<AlarmStatisticMonthDto> list = null;
        if (ObjectUtils.isEmpty(alarmStatisticResVo.getCurrentMonth())) {
            list = msgAlarmService.getCount(alarmStatisticResVo.getRailwayCode(), alarmStatisticResVo.getCurrentYear(),
                    alarmStatisticResVo.getCurrentMonth());
        } else {
            list = msgAlarmService.getDayCount(alarmStatisticResVo.getRailwayCode(), alarmStatisticResVo.getCurrentYear(),
                    alarmStatisticResVo.getCurrentMonth());
        }
        ExcelUtil<AlarmStatisticMonthDto> util = new ExcelUtil<>(AlarmStatisticMonthDto.class);
        util.exportExcel(response, list, "报警月统计数据");
    }

    /**
     * 查询终端数、机车数、相机数、预警数
     *
     * @param
     * @return
     */
    @PostMapping("/getNum")
    @Log(title = "查询终端数、机车数、相机数、预警数", businessType = BusinessType.SELECT)
    public AjaxResult getNum() {
        Long alarmNum = msgAlarmService.getAlarmNum();
        Long vehicleNum = baseVehicleService.count(new LambdaQueryWrapper<BaseVehicle>().groupBy(BaseVehicle::getVehicleCode));
        QueryWrapper<BaseTerminal> wrapper = new QueryWrapper<BaseTerminal>();
        wrapper.lambda().eq(BaseTerminal::getStatus, 1);
        Long terminalNum = baseTerminalService.count(new LambdaQueryWrapper<BaseTerminal>().groupBy(BaseTerminal::getTerminalCode));
        Long cameraNum = baseCameraManagementService.count();
        DataStatisticNum dataStatisticNum = new DataStatisticNum();
        if (!ObjectUtils.isEmpty(alarmNum)) {
            dataStatisticNum.setAlarmNum(alarmNum);
        }
        if (!ObjectUtils.isEmpty(vehicleNum)) {
            dataStatisticNum.setVehicleNum(vehicleNum);
        }
        if (!ObjectUtils.isEmpty(terminalNum)) {
            dataStatisticNum.setTerminalNum(terminalNum);
        }
        if (!ObjectUtils.isEmpty(cameraNum)) {
            dataStatisticNum.setCameraNum(cameraNum);
        }
        return AjaxResult.success(dataStatisticNum);
    }
}
