package com.zcxk.charge.web.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.charge.api.dto.AlarmDetailsDto;
import com.zcxk.charge.api.dto.AlarmDetailsHistoryDto;
import com.zcxk.charge.api.dto.AlarmDetailsRealTimeDto;
import com.zcxk.charge.api.dto.query.AlarmDetailsPageDto;
import com.zcxk.charge.api.vo.AlarmDetailsHistoryVo;
import com.zcxk.charge.api.vo.AlarmDetailsRealTimeVo;
import com.zcxk.charge.core.entity.AlarmDetailsEntity;
import com.zcxk.charge.web.common.Pagination;
import com.zcxk.charge.web.service.AlarmDetailsService;
import com.zcxk.charge.web.service.SceneService;
import com.zcxk.core.common.pojo.AjaxMessage;
import com.zcxk.core.mongo.utils.StringUtil;
import com.zcxk.core.utils.ZoniotIntegerUtils;
import com.zcxk.core.utils.export.EasyExcelUtil;
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.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description
 * @author andy
 * @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 get(@ApiParam(value = "报警详情信息id") @RequestParam Integer id){
        return AjaxMessage.success(alarmDetailsService.selectById(id));
    }

    @RequestMapping(value="selectPage" , method = RequestMethod.POST)
    @ApiOperation(value = "分页查询报警详情信息")
    public AjaxMessage selectPage(@RequestBody @Valid AlarmDetailsPageDto dto){
        AlarmDetailsDto alarmDetailsDto = coverAlarmDetailsDto(dto);
        IPage iPage = getPage(dto.getPageNum(), dto.getPageSize(), false, "t.date_create");
        if (ZoniotIntegerUtils.isNotEmpty(dto.getSceneId()) || StringUtil.isNotEmpty(dto.getSceneTypeName())) {
            alarmDetailsDto.setSceneIds(sceneService.findByParentIdsSceneTypeName(dto.getSceneId().longValue(), dto.getSceneTypeName()));
            if (!CollectionUtils.isEmpty(alarmDetailsDto.getSceneIds())){
                return AjaxMessage.success(new Pagination<>(alarmDetailsService.selectPage(iPage, alarmDetailsDto)));
            }
        }
        return AjaxMessage.success(new Pagination<>(iPage));
    }

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

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

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

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

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

    @RequestMapping(value="selectHistoryPage" , method = RequestMethod.POST)
    @ApiOperation(value = "分页查询报历史警详情信息")
    public AjaxMessage selectHistoryPage(@RequestBody @Valid AlarmDetailsPageDto dto){
        AlarmDetailsDto alarmDetailsDto = coverAlarmDetailsDto(dto);
        IPage iPage = getPage(dto.getPageNum(), dto.getPageSize(), false, "a.ALARM_START_TIME");
        if (ZoniotIntegerUtils.isNotEmpty(dto.getSceneId()) || StringUtil.isNotEmpty(dto.getSceneTypeName())) {
            alarmDetailsDto.setSceneIds(sceneService.findByParentIdsSceneTypeName(dto.getSceneId().longValue(), dto.getSceneTypeName()));
            if (CollectionUtils.isEmpty(alarmDetailsDto.getSceneIds())){
                return AjaxMessage.success(new Pagination<>(iPage));
            }
        }
        Pagination<AlarmDetailsHistoryVo> pages = new Pagination<>(alarmDetailsService.selectHistoryPage(iPage, alarmDetailsDto));
        return AjaxMessage.success(pages);
    }

    @RequestMapping(value="exportHistory" , method = RequestMethod.GET)
    @ApiOperation(value = "导出历史报警信息")
    public void exportHistory(AlarmDetailsPageDto dto, HttpServletResponse response) throws Exception {
        if (!CollectionUtils.isEmpty(dto.getIds())){
            EasyExcelUtil.excelWrite(response, AlarmDetailsHistoryDto.class, "历史报警记录", alarmDetailsService.selectHistoryByIds(dto.getIds()));
            return ;
        }
        AlarmDetailsDto alarmDetailsDto = coverAlarmDetailsDto(dto);
        if (ZoniotIntegerUtils.isNotEmpty(dto.getSceneId()) || StringUtil.isNotEmpty(dto.getSceneTypeName())) {
            alarmDetailsDto.setSceneIds(sceneService.findByParentIdsSceneTypeName(dto.getSceneId().longValue(), dto.getSceneTypeName()));
            if (CollectionUtils.isEmpty(alarmDetailsDto.getSceneIds())){
                EasyExcelUtil.excelWrite(response, AlarmDetailsHistoryDto.class, "历史报警记录", new ArrayList<>());
                return ;
            }
        }
        EasyExcelUtil.excelWrite(response, AlarmDetailsHistoryDto.class, "历史报警记录", alarmDetailsService.selectHistoryList(alarmDetailsDto));
    }


    @RequestMapping(value="selectRealTimePage" , method = RequestMethod.POST)
    @ApiOperation(value = "分页查询实时报警详情信息")
    public AjaxMessage selectRealTimePage(@RequestBody @Valid AlarmDetailsPageDto dto ){
        AlarmDetailsDto alarmDetailsDto = coverAlarmDetailsDto(dto);
        IPage iPage = getPage(dto.getPageNum(), dto.getPageSize(), false, "a.ALARM_START_TIME");
        if (ZoniotIntegerUtils.isNotEmpty(dto.getSceneId()) ||StringUtil.isNotEmpty(dto.getSceneTypeName())) {
            alarmDetailsDto.setSceneIds(sceneService.findByParentIdsSceneTypeName(dto.getSceneId().longValue(), dto.getSceneTypeName()));
            if (alarmDetailsDto.getSceneIds() == null || alarmDetailsDto.getSceneIds().size() == 0 ){
                return AjaxMessage.success(new Pagination<>(iPage));
            }
        }
        Pagination<AlarmDetailsRealTimeVo> pages = new Pagination<>(alarmDetailsService.selectRealTimePage(iPage,alarmDetailsDto));
        return AjaxMessage.success(pages);
    }

    @RequestMapping(value="exportRealTime" , method = RequestMethod.GET)
    @ApiOperation(value = "导出实时报警信息")
    public void exportRealTime(AlarmDetailsPageDto dto, HttpServletResponse response) throws Exception {
        if (!CollectionUtils.isEmpty(dto.getIds())){
            EasyExcelUtil.excelWrite(response, AlarmDetailsRealTimeDto.class, "实时报警记录", alarmDetailsService.selectRealTimeByIds(dto.getIds()));
            return;
        }
        AlarmDetailsDto alarmDetailsDto = coverAlarmDetailsDto(dto);
        if (ZoniotIntegerUtils.isNotEmpty(dto.getSceneId()) || StringUtil.isNotEmpty(dto.getSceneTypeName()))  {
            List<Long> ids = sceneService.findByParentIdsSceneTypeName(dto.getSceneId().longValue(), dto.getSceneTypeName());
            alarmDetailsDto.setSceneIds(ids);
            if (CollectionUtils.isEmpty(ids)){
                EasyExcelUtil.excelWrite(response, AlarmDetailsHistoryDto.class, "历史报警记录", new ArrayList<>());
                return;
            }
        }
        EasyExcelUtil.excelWrite(response, AlarmDetailsRealTimeDto.class, "实时报警记录", alarmDetailsService.selectRealTimeList(alarmDetailsDto));
    }


    @RequestMapping(value="batchDelete" , method = RequestMethod.POST)
    @ApiOperation(value = "批量删除")
    public AjaxMessage<Integer> batchDelete( @ApiParam(value = "报警信息ids") @RequestBody List<Integer> ids){
        return AjaxMessage.success(alarmDetailsService.batchDelete(ids));
    }

    /**
    * 转化数据
    * @author Andy
    * @date 16:01 2021/8/16
    * @param dto:
    * @return com.zcxk.charge.api.dto.AlarmDetailsDto
    **/
    private AlarmDetailsDto coverAlarmDetailsDto(AlarmDetailsPageDto dto){
        AlarmDetailsDto alarmDetailsDto = new AlarmDetailsDto();
        alarmDetailsDto.setCondition(dto.getCondition());
        alarmDetailsDto.setAlarmType(dto.getAlarmType());
        alarmDetailsDto.setOpState(dto.getOpState());
        alarmDetailsDto.setSceneTypeName(dto.getSceneTypeName());
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        try {
            if(StringUtils.isNotBlank(dto.getStartTime())){
                alarmDetailsDto.setStartTime(f.parse(dto.getStartTime()));
            }
            if(StringUtils.isNotBlank(dto.getEndTime())){
                alarmDetailsDto.setEndTime(f.parse(dto.getEndTime()));
            }
        }catch (ParseException e){
            alarmDetailsDto.setStartTime(new Date());
            alarmDetailsDto.setEndTime(new Date());
        }
        return  alarmDetailsDto;
    }

    /**
    * 获取分页
    * @author Andy
    * @date 16:01 2021/8/16
    * @param pageNum:
    * @param pageSize:
    * @param asc:
    * @param column:
    * @return com.baomidou.mybatisplus.core.metadata.IPage
    **/
    private IPage getPage(Integer pageNum, Integer pageSize, boolean asc, String column){
        IPage iPage = new Page<>(pageNum, pageSize);
        if (iPage.orders().size() == 0){
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(asc);
            orderItem.setColumn(column);
            iPage.orders().add(orderItem);
        }
        return iPage;
    }

}
