package com.ruoyi.web.controller.zhdd;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.zhdd.domain.Incident;
import com.ruoyi.zhdd.domain.IncidentProcess;
import com.ruoyi.zhdd.domain.IncidentTask;
import com.ruoyi.zhdd.domain.IncidentTaskPerson;
import com.ruoyi.zhdd.domain.Plan;
import com.ruoyi.zhdd.domain.bo.IncidentTaskBo;
import com.ruoyi.zhdd.domain.bo.IncidentTasksBo;
import com.ruoyi.zhdd.domain.vo.PlanVo;
import com.ruoyi.zhdd.domain.vo.ResourceVo;
import com.ruoyi.zhdd.service.IIncidentProcessService;
import com.ruoyi.zhdd.service.IIncidentTaskPersonService;
import com.ruoyi.zhdd.service.IIncidentTaskService;
import com.ruoyi.zhdd.service.IPlanService;
import com.ruoyi.zhdd.service.IPlanTaskService;
import lombok.RequiredArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.core.validate.QueryGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.zhdd.domain.vo.IncidentVo;
import com.ruoyi.zhdd.domain.bo.IncidentBo;
import com.ruoyi.zhdd.service.IIncidentService;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 事件基础Controller
 *
 * @author xitong
 * @date 2021-09-28
 */
@Validated
@Api(value = "事件基础控制器", tags = {"事件基础管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/zhdd/incident")
public class IncidentController extends BaseController {

    private final IIncidentService iIncidentService;

    private final IIncidentTaskService incidentTaskService;

    private final IIncidentTaskPersonService incidentTaskPersonService;

    private final IIncidentProcessService iIncidentProcessService;

    private final IPlanTaskService planTaskService;

    private final IPlanService planService;

    /**
     * 查询事件基础列表
     */
    @ApiOperation("查询事件基础列表")
//    @PreAuthorize("@ss.hasPermi('zhdd:incident:list')")
    @GetMapping("/list")
    public TableDataInfo<IncidentVo> list(@Validated(QueryGroup.class) IncidentBo bo) {
        return iIncidentService.queryPageList(bo);
    }

    /**
     * 导出事件基础列表
     */
    @ApiOperation("导出事件基础列表")
//    @PreAuthorize("@ss.hasPermi('zhdd:incident:export')")
    @Log(title = "事件基础", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public void export(@Validated IncidentBo bo, HttpServletResponse response) {
        List<IncidentVo> list = iIncidentService.queryList(bo);
        ExcelUtil.exportExcel(list, "事件基础", IncidentVo.class, response);
    }

    /**
     * 获取事件基础详细信息
     */
    @ApiOperation("获取事件基础详细信息")
//    @PreAuthorize("@ss.hasPermi('zhdd:incident:query')")
    @GetMapping("/{id}")
    public AjaxResult<Map<String, Object>> getInfo(@NotNull(message = "主键不能为空")
                                                   @PathVariable("id") String id) {
        Map<String, Object> map = new HashMap<>();
        IncidentVo incidentVo = iIncidentService.queryById(id);
        map.put("baseInfo", incidentVo);
        // 查询所属预案
        List<PlanVo> voOne = planService.listVo(Wrappers.<Plan>lambdaQuery().eq(Plan::getType, incidentVo.getType()).eq(Plan::getCreateDept, incidentVo.getCreateDept()));
        if (voOne != null && voOne.size() > 0) {
            map.put("baseTask", planTaskService.queryPlanTaskByPlanId(voOne.get(0).getId()));
        } else {
            map.put("baseTask", null);
        }
        // 查询处置方案
        map.put("task", incidentTaskService.listTaskInfo(id));
        map.put("process", iIncidentProcessService.list(Wrappers.<IncidentProcess>lambdaQuery()
            .eq(IncidentProcess::getIncidentId, id).orderByAsc(IncidentProcess::getCreateTime)));
        return AjaxResult.success(map);
    }

    /**
     * 新增事件基础
     */
    @ApiOperation("新增事件基础")
//    @PreAuthorize("@ss.hasPermi('zhdd:incident:add')")
    @Log(title = "事件基础", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody IncidentBo bo) {
        // 新增初始化为预警状态
        bo.setStatus(1);
        return toAjax(iIncidentService.insertByBo(bo) ? 1 : 0);
    }

    /**
     * 修改事件基础
     */
    @ApiOperation("修改事件基础")
//    @PreAuthorize("@ss.hasPermi('zhdd:incident:edit')")
    @Log(title = "事件基础", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody IncidentBo bo) {
        return toAjax(iIncidentService.updateByBo(bo) ? 1 : 0);
    }

    /**
     * 删除事件基础
     */
    @ApiOperation("删除事件基础")
//    @PreAuthorize("@ss.hasPermi('zhdd:incident:remove')")
    @Log(title = "事件基础", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空")
                                   @PathVariable String[] ids) {
        return toAjax(iIncidentService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    @ApiOperation("新增事件方案")
    @Log(title = "事件方案", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/task")
    public AjaxResult<Void> addTask(@Validated(AddGroup.class) @RequestBody IncidentTasksBo bo) {
        return toAjax(incidentTaskService.insertByBo(bo) ? 1 : 0);
    }

    @ApiOperation("删除事件方案")
    @Log(title = "事件方案", businessType = BusinessType.DELETE)
    @DeleteMapping("/task/{ids}")
    public AjaxResult<Void> removeTask(@NotEmpty(message = "主键不能为空")
                                       @PathVariable String[] ids) {
        return toAjax(incidentTaskService.deleteWithValidByIds(Arrays.asList(ids), true) ? 1 : 0);
    }

    @ApiOperation("查询事件-用于首页地图展示")
    @GetMapping("/location")
    public AjaxResult<Map<String, List<IncidentVo>>> queryIncidentLocation() {
        List<IncidentVo> list = iIncidentService.listVo(Wrappers.<Incident>lambdaQuery().in(Incident::getStatus, 1, 2, 3));
        Map<Integer, List<IncidentVo>> collect = list.stream().collect(Collectors.groupingBy(IncidentVo::getStatus, Collectors.mapping(a -> a, Collectors.toList())));
        Map<String, List<IncidentVo>> result = new HashMap<>();
        result.put("预警事件", CollUtil.defaultIfEmpty(collect.get(1), new ArrayList<>()));
        result.put("待派发", CollUtil.defaultIfEmpty(collect.get(2), new ArrayList<>()));
        result.put("待处置", CollUtil.defaultIfEmpty(collect.get(3), new ArrayList<>()));
        return AjaxResult.success(result);
    }


}
