package com.ruoyi.web.controller.system;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.web.domain.dto.event.EventAddRequest;
import com.ruoyi.web.domain.dto.event.EventHandleRequest;
import com.ruoyi.web.domain.dto.event.EventQueryRequest;
import com.ruoyi.web.domain.dto.event.EventReassignRequest;
import com.ruoyi.web.domain.entity.*;
import com.ruoyi.web.domain.vo.event.EventVO;
import com.ruoyi.web.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.aspectj.weaver.ast.Var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

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

/**
 * 事件管理控制器
 */
@Api(tags = "事件管理")
@RestController
@RequestMapping("/system/event")
public class EventController extends BaseController {

    @Autowired
    private EventService eventService;

    /**
     * 添加事件
     */
    @ApiOperation("添加事件(村民提交事件)")
    @PostMapping("/add")
    public AjaxResult addEvent(@RequestBody EventAddRequest eventAddRequest) {
        if (eventAddRequest == null) {
            return error("请求参数为空");
        }
        Integer id = eventService.addEvent(eventAddRequest);
        return success(id);
    }

    /**
     * 删除事件
     */
    @ApiOperation("删除事件")
    @PostMapping("/delete")
    public AjaxResult deleteEvent(@RequestBody Map<String, String> paramsMap) {
        String ids = paramsMap.get("ids");
        if (StrUtil.isBlank(ids)) {
            return error("请求参数为空");
        }
        boolean b = eventService.deleteEvent(ids);
        if (b) {
            return success("删除成功");
        }
        return error("删除失败");
    }

//    /**
//     * 编辑事件
//     */
//    @ApiOperation("编辑事件")
//    @PostMapping("/edit")
//    public AjaxResult editEvent(@RequestBody EventEditRequest eventEditRequest) {
//        if (eventEditRequest == null) {
//            return error("请求参数为空");
//        }
//        eventService.editEvent(eventEditRequest);
//        return AjaxResult.success();
//    }

    /**
     * 根据ID查询事件详情(支持管理员和负责人查询)
     */
    @ApiOperation("根据ID查询事件详情(支持管理员和负责人查询)")
    @GetMapping("/get")
    public AjaxResult getEventById(@RequestParam Integer id) {
        if (ObjectUtil.isEmpty(id)) {
            return error("请求参数为空");
        }
        EventVO eventVO = eventService.getEventById(id);
        return success(eventVO);
    }

    /**
     * 分页查询事件列表(支持管理员和负责人查询)
     */
    @ApiOperation("分页查询事件列表")
    @PostMapping("/list/page")
    public AjaxResult listEventByPage(@RequestBody EventQueryRequest eventQueryRequest) {
        if (eventQueryRequest == null) {
            return error("请求参数为空");
        }
        Page<EventVO> listEventVOByPage = eventService.getListEventByPage(eventQueryRequest);
        return AjaxResult.success(listEventVOByPage);
    }

    /**
     * 分页查询事件列表(村民查询)
     */
    @ApiOperation("村民分页获取自己事件列表")
    @PostMapping("/list/pageCunMin")
    public AjaxResult pageCunMin(@RequestBody EventQueryRequest eventQueryRequest) {
        if (eventQueryRequest == null) {
            return error("请求参数为空");
        }
        Page<Event> listEventVOByPage = eventService.pageCunMin(eventQueryRequest);
        return AjaxResult.success(listEventVOByPage);
    }


//    /**
//     * 根据事件类型获取负责人列表(管理员)
//     */
//    @ApiOperation("根据事件类型获取负责人列表(管理员)")
//    @GetMapping("/list/user")
//    @PreAuthorize("@ss.hasPermi('system:role:admin')")
//    public AjaxResult listSysUserByType(@RequestParam Integer type) {
//        if (type == null) {
//            return error("请求参数为空");
//        }
//        List<PersonInfoVO> personInfoVOByEventType = eventService.getPersonInfoVOByEventType(type);
//        return AjaxResult.success(personInfoVOByEventType);
//    }


    /**
     * 处理事件
     */
    @ApiOperation("处理事件")
    @PostMapping("/handle")
    public AjaxResult handleEvent(@RequestBody EventHandleRequest eventHandleRequest) {
        try {
            Integer eventId = eventHandleRequest.getEventId();
            String processResult = eventHandleRequest.getProcessResult();
            Date processTime = eventHandleRequest.getProcessTime();
            Event event = eventService.getById(eventId);
            if(ObjectUtil.isEmpty(event)){
                return error("事件不存在");
            }
            boolean result = eventService.handleEvent(eventId, processResult,processTime);
            if (result) {
                return success("事件处理成功");
            } else {
                return error("事件已被他人处理");
            }
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 重新派发事件
     */
    @ApiOperation("重新派发事件")
    @PostMapping("/reassign")
    public AjaxResult reassignEvent(@RequestBody EventReassignRequest eventReassignRequest) {
        try {
            Integer eventId = eventReassignRequest.getEventId();
            List<Integer> personIds = eventReassignRequest.getPersonIds();
            eventService.reassignEvent(eventId, personIds);
            return success("重新派发成功");
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    @Autowired
    private DrowningWarningService drowningWarningService;
    @Autowired
    private EarthquakeWarningService earthquakeWarningService;
    @Autowired
    private EnvironmentWarningService environmentWarningService;
    @Autowired
    private EmergencyService emergencyService;

    @ApiOperation("事件数量等")
    @GetMapping("/countEvent")
    public AjaxResult countEvent() {
        DateTime dateTime = DateUtil.beginOfDay(new Date());
        Map map = new HashMap();
        map.put("envetNum",   eventService.count(new QueryWrapper<Event>().ge("occur_time",dateTime)));
        map.put("daiBanNum",   eventService.count(new QueryWrapper<Event>().eq("status",0)));

        map.put("warningNum",
                drowningWarningService.count(new QueryWrapper<DrowningWarning>().ge("create_time", dateTime))
        +  earthquakeWarningService.count(new QueryWrapper<EarthquakeWarning>().ge("create_time", dateTime))
        + environmentWarningService.count(new QueryWrapper<EnvironmentWarning>().ge("create_time", dateTime)));

        map.put("emergencyNum",
                emergencyService.count(new QueryWrapper<Emergency>().ge("create_time", dateTime))
                        );
        return success(map);
    }

} 