package com.zcxk.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zcxk.common.EasyExcelUtil;
import com.zcxk.dto.AlarmDetailsDto;
import com.zcxk.dto.AlarmDetailsHistoryDto;
import com.zcxk.dto.AlarmDetailsRealTimeDto;
import com.zcxk.entity.AlarmDetailsEntity;
import com.zcxk.model.AjaxMessage;
import com.zcxk.model.Pagination;
import com.zcxk.model.ResultStatus;
import com.zcxk.service.AlarmDetailsService;
import com.zcxk.service.SceneService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description
 * @auto wangli
 * @data 2020-11-16 11:05
 */
@RestController
@RequestMapping("/AlarmDetails")
@Api(tags = "报警详情信息管理")
@Slf4j
public class AlarmDetailsController {

    @Autowired
    private AlarmDetailsService alarmDetailsService;

    @Autowired
    private SceneService sceneService;

    @Value("${SMS.sys_excel_path}")
    private String baseDir;

    @RequestMapping(value="get" , method = RequestMethod.GET)
    @ApiOperation(value = "查询单个报警详情信息")
    public AjaxMessage<AlarmDetailsEntity> get( @ApiParam(value = "报警详情信息id") @RequestParam Integer id){
        return new AjaxMessage<>(ResultStatus.OK, alarmDetailsService.selectById(id));
    }

    @RequestMapping(value="selectPage" , method = RequestMethod.GET)
    @ApiOperation(value = "分页查询报警详情信息")
    public AjaxMessage<Pagination<AlarmDetailsDto>> selectPage(
            @ApiParam(value = "查询：设备名称") @RequestParam(required = false) String condition,
            @ApiParam(value = "报警类型") @RequestParam(required = false) String alarmType,
            @ApiParam(value = "处理状态") @RequestParam(required = false) Integer opState,
            @ApiParam(value = "所属场景id") @RequestParam(required = false)  Integer sceneId,
            @ApiParam(value = "查询：开始时间") @RequestParam(required = false) String startTime,
            @ApiParam(value = "查询：结束时间") @RequestParam(required = false) String endTime,
            @ApiParam(value = "数据类型：1 实时报警 0 历史报警") @RequestParam(required = false) Integer state,
            @ApiParam(value = "页数,非必传，默认第一页",  defaultValue = "1") @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @ApiParam(value = "条数，非必传，默认10条",  defaultValue = "10") @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ){
        AlarmDetailsDto alarmDetailsDto = new AlarmDetailsDto();
        alarmDetailsDto.setCondition(condition);
        alarmDetailsDto.setAlarmType(alarmType);
        alarmDetailsDto.setOpState(opState);
        alarmDetailsDto.setState(state);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");

        try {
            if(StringUtils.isNotBlank(startTime)){
                alarmDetailsDto.setStartTime(f.parse(startTime));
            }
            if(StringUtils.isNotBlank(endTime)){
                alarmDetailsDto.setEndTime(f.parse(endTime));
            }
        }catch (ParseException e){
            log.error("报警信息查询时间转换错误，原数据：beginTime：{}，endTime：{}，异常信息：{}",startTime,endTime,e.getMessage());
            alarmDetailsDto.setStartTime(new Date());
            alarmDetailsDto.setEndTime(new Date());
        }

        IPage<AlarmDetailsDto> iPage = new Page<>(pageNum, pageSize);
        if(iPage.orders().size() == 0){
            OrderItem orderItem =new OrderItem();
            orderItem.setAsc(false);
            orderItem.setColumn("t.date_create");
            iPage.orders().add(orderItem);
        }
        if(sceneId != null && sceneId != 0) {
            alarmDetailsDto.setSceneIds(sceneService.findByParentIdsLike(sceneId.longValue()));
            if(alarmDetailsDto.getSceneIds() == null || alarmDetailsDto.getSceneIds().size() == 0){
                return new AjaxMessage<>(ResultStatus.OK, new Pagination<>(iPage));
            }
        }
        iPage = alarmDetailsService.selectPage(iPage,alarmDetailsDto);
        Pagination<AlarmDetailsDto> pages = new Pagination<>(iPage);
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @RequestMapping(value="add" , method = RequestMethod.POST)
    @ApiOperation(value = "新增报警详情信息")
    public AjaxMessage<Integer> add(@ApiParam(value = "报警详情信息") @RequestBody AlarmDetailsEntity alarmDetailsEntity){
        return new AjaxMessage<>(ResultStatus.OK, alarmDetailsService.insert(alarmDetailsEntity));
    }

    @RequestMapping(value="edit" , method = RequestMethod.POST)
    @ApiOperation(value = "修改报警详情信息")
    public AjaxMessage<Integer> edit( @ApiParam(value = "报警详情信息") @RequestBody AlarmDetailsEntity alarmDetailsEntity){
        return new AjaxMessage<>(ResultStatus.OK, alarmDetailsService.update(alarmDetailsEntity));
    }

    @RequestMapping(value="delete" , method = RequestMethod.DELETE)
    @ApiOperation(value = "单个删除报警详情信息")
    public AjaxMessage<Integer> delete( @ApiParam(value = "报警详情信息id") @RequestParam Integer id){
        return new AjaxMessage<>(ResultStatus.OK, alarmDetailsService.deleteById(id));
    }

    @RequestMapping(value="suspendedById" , method = RequestMethod.POST)
    @ApiOperation(value = "挂起报警信息")
    public AjaxMessage<Integer> suspendedById( @ApiParam(value = "报警详情信息id") @RequestParam Integer id){
        return new AjaxMessage<>(ResultStatus.OK, alarmDetailsService.suspendedById(id,0));
    }

    @RequestMapping(value="renewById" , method = RequestMethod.POST)
    @ApiOperation(value = "恢复挂起报警信息")
    public AjaxMessage<Integer> renewById( @ApiParam(value = "报警详情信息id") @RequestParam Integer id){
        return new AjaxMessage<>(ResultStatus.OK, alarmDetailsService.suspendedById(id,1));
    }



    @RequestMapping(value="selectHistoryPage" , method = RequestMethod.GET)
    @ApiOperation(value = "分页查询报历史警详情信息")
    public AjaxMessage<Pagination<AlarmDetailsHistoryDto>> selectHistoryPage(
            @ApiParam(value = "查询：场景名称/设备名称") @RequestParam(required = false) String condition,
            @ApiParam(value = "报警类型") @RequestParam(required = false) String alarmType,
            @ApiParam(value = "处理状态") @RequestParam(required = false) Integer opState,
            @ApiParam(value = "所属场景id") @RequestParam(required = false)  Integer sceneId,
            @ApiParam(value = "查询：开始时间yyyy-MM-dd") @RequestParam(required = false) String startTime,
            @ApiParam(value = "查询：结束时间yyyy-MM-dd") @RequestParam(required = false) String endTime,
            @ApiParam(value = "页数,非必传，默认第一页",  defaultValue = "1") @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @ApiParam(value = "条数，非必传，默认10条",  defaultValue = "10") @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ){
        AlarmDetailsDto alarmDetailsDto = new AlarmDetailsDto();
        alarmDetailsDto.setCondition(condition);
        alarmDetailsDto.setAlarmType(alarmType);
        alarmDetailsDto.setOpState(opState);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if(StringUtils.isNotBlank(startTime)){
                alarmDetailsDto.setStartTime(f.parse(startTime));
            }
            if(StringUtils.isNotBlank(endTime)){
                alarmDetailsDto.setEndTime(f.parse(endTime));
            }
        }catch (ParseException e){
            log.error("报警信息查询时间转换错误，原数据：beginTime：{}，endTime：{}，异常信息：{}",startTime,endTime,e.getMessage());
            alarmDetailsDto.setStartTime(new Date());
            alarmDetailsDto.setEndTime(new Date());
        }

        IPage<AlarmDetailsHistoryDto> iPage = new Page<>(pageNum, pageSize);
        if(iPage.orders().size() == 0){
            OrderItem orderItem =new OrderItem();
            orderItem.setAsc(false);
            orderItem.setColumn("a.ALARM_START_TIME");
            iPage.orders().add(orderItem);
        }
        if(sceneId != null && sceneId != 0) {
            alarmDetailsDto.setSceneIds(sceneService.findByParentIdsLike(sceneId.longValue()));
            if(alarmDetailsDto.getSceneIds() == null || alarmDetailsDto.getSceneIds().size() == 0){
                return new AjaxMessage<>(ResultStatus.OK, new Pagination<>(iPage));
            }
        }
        iPage = alarmDetailsService.selectHistoryPage(iPage,alarmDetailsDto);
        Pagination<AlarmDetailsHistoryDto> pages = new Pagination<>(iPage);
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @RequestMapping(value="exportHistory" , method = RequestMethod.GET)
    @ApiOperation(value = "导出历史报警信息")
    public AjaxMessage<String> exportHistory(
            @ApiParam(value = "查询：场景名称/设备名称") @RequestParam(required = false) String condition,
            @ApiParam(value = "报警类型") @RequestParam(required = false) String alarmType,
            @ApiParam(value = "处理状态") @RequestParam(required = false) Integer opState,
            @ApiParam(value = "所属场景id") @RequestParam(required = false)  Integer sceneId,
            @ApiParam(value = "报警信息id") @RequestParam(required = false)  List<Integer> ids,
            @ApiParam(value = "查询：开始时间yyyy-MM-dd") @RequestParam(required = false) String startTime,
            @ApiParam(value = "查询：结束时间yyyy-MM-dd") @RequestParam(required = false) String endTime

    ){
        if(ids != null && ids.size()>0){
            String filePath = EasyExcelUtil.excelWrite(baseDir, AlarmDetailsHistoryDto.class, "历史报警记录",alarmDetailsService.selectHistoryByIds(ids) );
            return new AjaxMessage<>(ResultStatus.OK, filePath);
        }
        AlarmDetailsDto alarmDetailsDto = new AlarmDetailsDto();
        alarmDetailsDto.setCondition(condition);
        alarmDetailsDto.setAlarmType(alarmType);
        alarmDetailsDto.setOpState(opState);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if(StringUtils.isNotBlank(startTime)){
                alarmDetailsDto.setStartTime(f.parse(startTime));
            }
            if(StringUtils.isNotBlank(endTime)){
                alarmDetailsDto.setEndTime(f.parse(endTime));
            }
        }catch (ParseException e){
            log.error("报警信息查询时间转换错误，原数据：beginTime：{}，endTime：{}，异常信息：{}",startTime,endTime,e.getMessage());
            alarmDetailsDto.setStartTime(new Date());
            alarmDetailsDto.setEndTime(new Date());
        }
        if(sceneId != null && sceneId != 0) {
            alarmDetailsDto.setSceneIds(sceneService.findByParentIdsLike(sceneId.longValue()));
            if(alarmDetailsDto.getSceneIds() == null || alarmDetailsDto.getSceneIds().size() == 0){
                String filePath = EasyExcelUtil.excelWrite(baseDir, AlarmDetailsHistoryDto.class, "历史报警记录", new ArrayList<>());
                return new AjaxMessage<>(ResultStatus.OK, filePath);
            }
        }
        String filePath = EasyExcelUtil.excelWrite(baseDir, AlarmDetailsHistoryDto.class, "历史报警记录", alarmDetailsService.selectHistoryList(alarmDetailsDto));
        return new AjaxMessage<>(ResultStatus.OK, filePath);
    }




    @RequestMapping(value="selectRealTimePage" , method = RequestMethod.GET)
    @ApiOperation(value = "分页查询实时报警详情信息")
    public AjaxMessage<Pagination<AlarmDetailsRealTimeDto>> selectRealTimePage(
            @ApiParam(value = "查询：场景名称/设备名称") @RequestParam(required = false) String condition,
            @ApiParam(value = "报警类型") @RequestParam(required = false) String alarmType,
            @ApiParam(value = "处理状态") @RequestParam(required = false) Integer opState,
            @ApiParam(value = "所属场景id") @RequestParam(required = false)  Integer sceneId,
            @ApiParam(value = "查询：开始时间yyyy-MM-dd") @RequestParam(required = false) String startTime,
            @ApiParam(value = "查询：结束时间yyyy-MM-dd") @RequestParam(required = false) String endTime,
            @ApiParam(value = "页数,非必传，默认第一页",  defaultValue = "1") @RequestParam(required = false, defaultValue = "1") Integer pageNum,
            @ApiParam(value = "条数，非必传，默认10条",  defaultValue = "10") @RequestParam(required = false, defaultValue = "10") Integer pageSize
    ){
        AlarmDetailsDto alarmDetailsDto = new AlarmDetailsDto();
        alarmDetailsDto.setCondition(condition);
        alarmDetailsDto.setAlarmType(alarmType);
        alarmDetailsDto.setOpState(opState);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");

        try {
            if(StringUtils.isNotBlank(startTime)){
                alarmDetailsDto.setStartTime(f.parse(startTime));
            }
            if(StringUtils.isNotBlank(endTime)){
                alarmDetailsDto.setEndTime(f.parse(endTime));
            }
        }catch (ParseException e){
            log.error("报警信息查询时间转换错误，原数据：beginTime：{}，endTime：{}，异常信息：{}",startTime,endTime,e.getMessage());
            alarmDetailsDto.setStartTime(new Date());
            alarmDetailsDto.setEndTime(new Date());
        }

        IPage<AlarmDetailsRealTimeDto> iPage = new Page<>(pageNum, pageSize);
        if(iPage.orders().size() == 0){
            OrderItem orderItem =new OrderItem();
            orderItem.setAsc(false);
            orderItem.setColumn("a.ALARM_START_TIME");
            iPage.orders().add(orderItem);
        }
        if(sceneId != null && sceneId != 0) {
            alarmDetailsDto.setSceneIds(sceneService.findByParentIdsLike(sceneId.longValue()));
            if(alarmDetailsDto.getSceneIds() == null || alarmDetailsDto.getSceneIds().size() == 0){
                return new AjaxMessage<>(ResultStatus.OK, new Pagination<>(iPage));
            }
        }
        iPage = alarmDetailsService.selectRealTimePage(iPage,alarmDetailsDto);
        Pagination<AlarmDetailsRealTimeDto> pages = new Pagination<>(iPage);
        return new AjaxMessage<>(ResultStatus.OK, pages);
    }

    @RequestMapping(value="exportRealTime" , method = RequestMethod.GET)
    @ApiOperation(value = "导出实时报警信息")
    public AjaxMessage<String> exportRealTime(
            @ApiParam(value = "查询：场景名称/设备名称") @RequestParam(required = false) String condition,
            @ApiParam(value = "报警类型") @RequestParam(required = false) String alarmType,
            @ApiParam(value = "处理状态") @RequestParam(required = false) Integer opState,
            @ApiParam(value = "所属场景id") @RequestParam(required = false)  Integer sceneId,
            @ApiParam(value = "报警信息id") @RequestParam(required = false)  List<Integer>  ids,
            @ApiParam(value = "查询：开始时间yyyy-MM-dd") @RequestParam(required = false) String startTime,
            @ApiParam(value = "查询：结束时间yyyy-MM-dd") @RequestParam(required = false) String endTime
    ){

        if(ids != null && ids.size() >0){
            String filePath = EasyExcelUtil.excelWrite(baseDir, AlarmDetailsRealTimeDto.class, "实时报警记录",alarmDetailsService.selectRealTimeByIds(ids));
            return new AjaxMessage<>(ResultStatus.OK, filePath);
        }
        AlarmDetailsDto alarmDetailsDto = new AlarmDetailsDto();
        alarmDetailsDto.setCondition(condition);
        alarmDetailsDto.setAlarmType(alarmType);
        alarmDetailsDto.setOpState(opState);
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if(StringUtils.isNotBlank(startTime)){
                alarmDetailsDto.setStartTime(f.parse(startTime));
            }
            if(StringUtils.isNotBlank(endTime)){
                alarmDetailsDto.setEndTime(f.parse(endTime));
            }
        }catch (ParseException e){
            log.error("报警信息查询时间转换错误，原数据：beginTime：{}，endTime：{}，异常信息：{}",startTime,endTime,e.getMessage());
            alarmDetailsDto.setStartTime(new Date());
            alarmDetailsDto.setEndTime(new Date());
        }
        if(sceneId != null && sceneId != 0) {
            alarmDetailsDto.setSceneIds(sceneService.findByParentIdsLike(sceneId.longValue()));
            if(alarmDetailsDto.getSceneIds() == null || alarmDetailsDto.getSceneIds().size() == 0){
                String filePath = EasyExcelUtil.excelWrite(baseDir, AlarmDetailsHistoryDto.class, "历史报警记录", new ArrayList<>());
                return new AjaxMessage<>(ResultStatus.OK, filePath);
            }
        }
        String filePath = EasyExcelUtil.excelWrite(baseDir, AlarmDetailsRealTimeDto.class, "实时报警记录",alarmDetailsService.selectRealTimeList(alarmDetailsDto) );
        return new AjaxMessage<>(ResultStatus.OK, filePath);
    }
    @RequestMapping(value="batchDelete" , method = RequestMethod.DELETE)
    @ApiOperation(value = "批量删除")
    public AjaxMessage<Integer> batchDelete( @ApiParam(value = "报警信息ids") @RequestParam List<Integer> ids){
        return new AjaxMessage<>(ResultStatus.OK, alarmDetailsService.batchDelete(ids));
    }


}
