package com.testor.module.globalAlarm.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.testor.biz.rule.service.SysRuleService;
import com.testor.common.constant.DefaultRule;
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.biz.models.BaseResponseList;
import com.tongtech.tfw.backend.common.biz.models.BizGeneralResponse;
import com.tongtech.tfw.backend.common.models.supers.SuperController;
import com.tongtech.tfw.backend.core.helper.ObjectHelper;
import com.tongtech.tfw.backend.core.helper.StringHelper;
import com.tongtech.tfw.backend.core.helper.TypeHelper;
import com.tongtech.tfw.backend.core.helper.bean.BeanHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 全局报警Controller
 *
 * @author testor-framework
 * @date 2023-02-08 11:09:19
 */
@RestController
@RequestMapping("/alarm")
@Api(value = "TGlobalAlarm", tags = "全局报警")
@Slf4j
public class TGlobalAlarmController extends SuperController {
    @Autowired
    private TGlobalAlarmService tGlobalAlarmService;

    @Autowired
    private SysRuleService sysRuleService;


    @ApiOperation(value = "报警时段统计")
    @GetMapping("/getTimeFrame")
    public BaseResponse<List<TGlobalAlarmParam>> getTimeFrame(TGlobalAlarmParam tGlobalAlarmParam) {
        return tGlobalAlarmService.getTimeFrame(tGlobalAlarmParam);
    }

    @ApiOperation(value = "报警类型统计")
    @GetMapping("/getAlarmType")
    public BaseResponse<List<TGlobalAlarmParam>> getAlarmType(TGlobalAlarmParam tGlobalAlarmParam) {
        return tGlobalAlarmService.getAlarmType(tGlobalAlarmParam);
    }

    @ApiOperation(value = "报警数量统计柱状图")
    @GetMapping("/quantityStatistics")
    public BaseResponse<List<TGlobalAlarmParam>> quantityStatistics(TGlobalAlarmParam tGlobalAlarmParam) {
        return tGlobalAlarmService.quantityStatistics(tGlobalAlarmParam);
    }


    @ApiOperation(value = "修改 全局报警 ", notes = "Update TGlobalAlarm By Id")
    @PostMapping(value = "/update")
    public BaseResponse<BizGeneralResponse> updateEntity(@RequestBody TGlobalAlarm updateRequest) {
        BaseResponse<BizGeneralResponse> baseResponse = new BaseResponse<>();
        if (ObjectHelper.isNotEmpty(updateRequest) && StringHelper.isNotEmpty(updateRequest.getId())) {
            TGlobalAlarm data = BeanHelper.beanToBean(updateRequest, TGlobalAlarm.class);
            UpdateWrapper<TGlobalAlarm> wrapper = new UpdateWrapper<>();
            wrapper.eq(TGlobalAlarm.ID, data.getId()).set(TGlobalAlarm.DISPOSE_STATUS, data.getDisposeStatus());
            boolean result = tGlobalAlarmService.update(wrapper);
            baseResponse.setData(
                    BizGeneralResponse.builder().result(TypeHelper.castToString(result)).build());
        }
        return baseResponse;
    }


    @ApiOperation(value = "获取 全局报警 分页列表", notes = "List TGlobalAlarm with page")
    @PostMapping(value = "/list")
    public BaseResponse<BaseResponseList<TGlobalAlarm>> listEntity(@RequestBody TGlobalAlarmParam param) {
        BaseResponse<BaseResponseList<TGlobalAlarm>> baseResponse = new BaseResponse<>();
        Long page =
                StringHelper.isEmpty(param.getPage()) ? BizConstants.PAGE : Long.valueOf(param.getPage());
        Long limit =
                StringHelper.isEmpty(param.getLimit()) ? BizConstants.LIMIT : Long.valueOf(param.getLimit());
        Page<TGlobalAlarm> resultPage = new Page<>(page, limit);
        List<String> orgIds = param.getOrgIds();
        QueryWrapper<TGlobalAlarm> queryWrapper = this.createQuery(param);
        if (ObjectHelper.isNotEmpty(orgIds) && orgIds.size() > 0) {
            queryWrapper.in(TGlobalAlarm.ORG_ID, orgIds);
        } else {
            // 获取本级及一下数据
            String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_SUB.name());
            if (StringUtils.isNotEmpty(rule)) {
                queryWrapper.apply(rule);
            }
        }
        Page<TGlobalAlarm> resultList = tGlobalAlarmService.page(resultPage, queryWrapper);
        BaseResponseList<TGlobalAlarm> baseResponseList = new BaseResponseList<>();
        List<TGlobalAlarm> records = resultList.getRecords();
        records.stream().forEach(item->{
            if(StringUtils.isNotBlank(item.getAlarmPicture())){
                String[] split = item.getAlarmPicture().split(",");
                item.setAlarmPictures(split);
            }
        });

        baseResponseList.setData(records);
        baseResponseList.setTotal(resultList.getTotal());
        baseResponse.setData(baseResponseList);
        return baseResponse;
    }

    @ApiOperation(value = "报警数量统计", notes = "List TGlobalAlarm all")
    @PostMapping(value = "/datas")
    public BaseResponse<Map<String, Long>> listAllEntity(@RequestBody TGlobalAlarmParam param) {
        HashMap<String, Long> hashMap = new HashMap<>();
        BaseResponse<Map<String, Long>> baseResponse = new BaseResponse<>();
        QueryWrapper<TGlobalAlarm> queryWrapper = this.createQuery(param);
        List<String> orgIds = param.getOrgIds();
        if (ObjectHelper.isNotEmpty(orgIds) && orgIds.size() > 0) {
            queryWrapper.in(TGlobalAlarm.ORG_ID, orgIds);
        } else {
            // 获取本级及一下数据
            String rule = sysRuleService.dataRuleScope(DefaultRule.DEPT_SUB.name());
            if (StringUtils.isNotEmpty(rule)) {
                queryWrapper.apply(rule);
            }
        }

        List<TGlobalAlarm> resultList = tGlobalAlarmService.list(queryWrapper);
        // 报警总数
        int size = resultList.size();
        long cc = size;
        hashMap.put("alarmsNum", cc);
        // 报警待处理总数
        long count = resultList.stream().filter(item -> item.getDisposeStatus().equals("0")).count();
        hashMap.put("pending", count);
        // 已处理总数
        long count1 = resultList.stream().filter(item -> !(item.getDisposeStatus().equals("0"))).count();
        hashMap.put("processed", count1);
        // 误报
        long count2 = resultList.stream().filter(item -> item.getDisposeStatus().equals("2")).count();
        hashMap.put("misinformation", count2);
        // 重复
        long count3 = resultList.stream().filter(item -> item.getDisposeStatus().equals("1")).count();
        hashMap.put("repetition", count3);
        // 转工单
        long count4 = resultList.stream().filter(item -> item.getDisposeStatus().equals("3")).count();
        hashMap.put("hiddendanger", count4);
        long num = cc - count2 - count3;
        hashMap.put("count", num);

        baseResponse.setData(hashMap);

        return baseResponse;
    }

    /* Private Methods */

    /**
     * 列表查询条件及查询参数
     */
    private QueryWrapper<TGlobalAlarm> createQuery(TGlobalAlarmParam queryParam) {
        QueryWrapper<TGlobalAlarm> queryWrapper = new QueryWrapper<>();
        if (StringHelper.isNotEmpty(queryParam.getOrgId())) {
            queryWrapper.eq(TGlobalAlarm.ORG_ID, queryParam.getOrgId());
        }
        if (StringHelper.isNotEmpty(queryParam.getStartTime()) && StringHelper.isNotEmpty(queryParam.getEndTime())) {
            queryWrapper.between(TGlobalAlarm.SJ_DATE, queryParam.getStartTime() + " 00:00:00", queryParam.getEndTime() + " 23:59:59");
        }
        if (StringHelper.isNotEmpty(queryParam.getOrgName())) {
            queryWrapper.like(TGlobalAlarm.ORG_NAME, queryParam.getOrgName());
        }
        if (StringHelper.isNotEmpty(queryParam.getRegion())) {
            queryWrapper.eq(TGlobalAlarm.REGION, queryParam.getRegion());
        }
        if (StringHelper.isNotEmpty(queryParam.getEventType())) {
            queryWrapper.eq(TGlobalAlarm.EVENT_TYPE, queryParam.getEventType());
        }
        if (StringHelper.isNotEmpty(queryParam.getAlarmPicture())) {
            queryWrapper.eq(TGlobalAlarm.ALARM_PICTURE, queryParam.getAlarmPicture());
        }
        if (StringHelper.isNotEmpty(queryParam.getSjDate())) {
            queryWrapper.eq(TGlobalAlarm.SJ_DATE, queryParam.getSjDate());
        }
        if (StringHelper.isNotEmpty(queryParam.getDisposeStatus())) {
            queryWrapper.eq(TGlobalAlarm.DISPOSE_STATUS, queryParam.getDisposeStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getEventLevel())) {
            queryWrapper.eq(TGlobalAlarm.EVENT_LEVEL, queryParam.getEventLevel());
        }
        if (StringHelper.isNotEmpty(queryParam.getGbId())) {
            queryWrapper.eq(TGlobalAlarm.GB_ID, queryParam.getGbId());
        }
        if (StringHelper.isNotEmpty(queryParam.getEventSource())) {
            queryWrapper.eq(TGlobalAlarm.EVENT_SOURCE, queryParam.getEventSource());
        }
        if (StringHelper.isNotEmpty(queryParam.getJgName())) {
            queryWrapper.like(TGlobalAlarm.JG_NAME, queryParam.getJgName());
        }
        if (StringHelper.isNotEmpty(queryParam.getBm())) {
            queryWrapper.eq(TGlobalAlarm.BM, queryParam.getBm());
        }
        if (StringHelper.isNotEmpty(queryParam.getGroupId())) {
            queryWrapper.eq(TGlobalAlarm.GROUP_ID, queryParam.getGroupId());
        }
        if (StringHelper.isNotEmpty(queryParam.getRefId())) {
            queryWrapper.eq(TGlobalAlarm.REF_ID, queryParam.getRefId());
        }
        if (StringHelper.isNotEmpty(queryParam.getParentId())) {
            queryWrapper.eq(TGlobalAlarm.PARENT_ID, queryParam.getParentId());
        }
        if (StringHelper.isNotEmpty(queryParam.getTenantId())) {
            queryWrapper.eq(TGlobalAlarm.TENANT_ID, queryParam.getTenantId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessId())) {
            queryWrapper.eq(TGlobalAlarm.PROCESS_ID, queryParam.getProcessId());
        }
        if (StringHelper.isNotEmpty(queryParam.getProcessStatus())) {
            queryWrapper.eq(TGlobalAlarm.PROCESS_STATUS, queryParam.getProcessStatus());
        }
        if (StringHelper.isNotEmpty(queryParam.getStatus())) {
            queryWrapper.eq(TGlobalAlarm.STATUS, queryParam.getStatus());
        } else {
            queryWrapper.ne(TGlobalAlarm.STATUS, BizConstants.STATUS_DELETE);
        }
        if (StringHelper.isNotEmpty(queryParam.getOrderBy())) {
            if (StringHelper.isNotEmpty(queryParam.getOrderType())
                    && BizConstants.ASC.equals(queryParam.getOrderType())) {
                queryWrapper.orderByAsc(queryParam.getOrderBy());
            } else {
                queryWrapper.orderByDesc(queryParam.getOrderBy());
            }
        } else {
            queryWrapper.orderByDesc(TGlobalAlarm.UPDATE_DATE);
        }
        return queryWrapper;
    }
}
