package com.ruoyi.web.controller.drill;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.DeletedEnum;
import com.ruoyi.common.constant.DrillEnum;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.drill.domain.DrillAnnualEmergency;
import com.ruoyi.drill.domain.DrillContingent;
import com.ruoyi.drill.domain.DrillPic;
import com.ruoyi.drill.domain.DrillPlan;
import com.ruoyi.drill.dto.DrillPlanDto;
import com.ruoyi.drill.dto.DrillPlanListDto;
import com.ruoyi.drill.dto.DrillPlanResultDto;
import com.ruoyi.drill.service.IDrillAnnualEmergencyService;
import com.ruoyi.drill.service.IDrillContingentService;
import com.ruoyi.drill.service.IDrillPicService;
import com.ruoyi.drill.service.IDrillPlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 演习计划Controller
 *
 * @author ruoyi
 * @date 2023-08-04
 */
@Api(tags = "演习计划")
@RestController
@RequestMapping("/drill/plan")
public class DrillPlanController extends BaseController {

    @Resource
    private IDrillPlanService drillPlanService;
    @Resource
    private IDrillPicService drillPicService;
    @Resource
    private IDrillAnnualEmergencyService drillAnnualEmergencyService;
    @Resource
    private IDrillContingentService drillContingentService;

    /**
     * 查询演习计划列表
     */
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('drill:plan:list')")
    @GetMapping("/list")
    @ApiOperation("查询演习计划列表")
    public TableDataInfo planList(DrillPlan drillPlan) {
        startPage();
        drillPlan.setDrillStatus(DrillEnum.DRILL_STATUS_NO.getValue());
        return getDataTable(drillPlanService.findList(drillPlan));
    }

    /**
     * 查询演习总览列表
     */
    //TODO 20230920PreAuthorize("@ss.hasPermi('drill:plan:list')")
    @GetMapping("/overviewList")
    @ApiOperation("查询演习总览列表")
    public TableDataInfo overviewList(DrillPlan drillPlan) {
        startPage();

        drillPlan.setDrillStatus(DrillEnum.DRILL_STATUS_YES.getValue());
        return getDataTable(drillPlanService.findList(drillPlan));
    }

    /**
     * 导出演习计划列表
     */
    //TODO 20230920PreAuthorize("@ss.hasPermi('drill:plan:export')")
    @Log(title = "演习计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation("导出演习计划列表")
    public void export(HttpServletResponse response, DrillPlan drillPlan) {
        ExcelUtil<DrillPlanListDto> util = new ExcelUtil<>(DrillPlanListDto.class);
        util.exportExcel(response, drillPlanService.findList(drillPlan), "演习计划数据");
    }

    /**
     * 获取演习计划详细信息
     */
    //TODO 20230920PreAuthorize("@ss.hasPermi('drill:plan:query')")
    @GetMapping(value = "/getInfo")
    @ApiOperation("获取演习计划详细信息")
    public AjaxResult getInfo(String id) {
//        return drillPlanService.getInfo(id);
        return drillPlanService.getInfoPC(id);
    }

    /**
     * 新增演习计划
     */
    //TODO 20230920PreAuthorize("@ss.hasPermi('drill:plan:add')")
    @Log(title = "新增演习计划", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("新增演习计划")
    public AjaxResult add(@Valid @RequestBody DrillPlanDto drillPlan) {
        return drillPlanService.saveAndUpdateDrillPlan(drillPlan);
    }

    /**
     * 修改演习计划
     */
    //TODO 20230920PreAuthorize("@ss.hasPermi('drill:plan:edit')")
    @Log(title = "修改演习计划", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改演习计划")
    public AjaxResult edit(@Valid @RequestBody DrillPlanDto drillPlan) {
        if (StringUtils.isEmpty(drillPlan.getId())) {
            return AjaxResult.warn("id不能为空");
        }
        return drillPlanService.saveAndUpdateDrillPlan(drillPlan);
    }

    /**
     * 删除演习计划
     */
    //TODO 20230920PreAuthorize("@ss.hasPermi('drill:plan:remove')")
    @Log(title = "删除演习计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    @ApiOperation("删除演习计划")
    public AjaxResult remove(String ids) {
        return drillPlanService.removePlan(ids);
    }

    /**
     * 演习总览审核
     *
     * @author matianxiang
     * @date 2023/8/9 16:23
     */
    //TODO 20230920PreAuthorize("@ss.hasPermi('drill:plan:edit')")
    @Log(title = "演习总览审核", businessType = BusinessType.UPDATE)
    @PostMapping("/process")
    @ApiOperation("演习总览审核")
    public AjaxResult process(@RequestBody DrillPlan drillPlan) {
        if (StringUtils.isEmpty(drillPlan.getId())) {
            return AjaxResult.warn("id不能为空");
        }
        Long processStatus = drillPlan.getProcessStatus();
        if (Objects.isNull(processStatus)) {
            return AjaxResult.warn("审核状态不能为空");
        }
        if (processStatus != 2L && processStatus != 3L) {
            return AjaxResult.warn("审核状态不正确");
        }
        DrillPlan plan = drillPlanService.getById(drillPlan.getId());
        if (Objects.isNull(plan) || Objects.equals(plan.getIsDel(), DeletedEnum.INVALID.getValue())) {
            return AjaxResult.warn("您无权查看");
        }
        if (Objects.equals(plan.getProcessStatus(), DrillEnum.PROCESS_STATUS_YES.getValue())) {
            return AjaxResult.warn("不允许再次审核");
        }
        DrillPlan dp = new DrillPlan();
        dp.setId(drillPlan.getId());
        dp.setProcessStatus(processStatus);
        dp.setProcessBy(SecurityUtils.getUserId());
        dp.setProcessOpinion(dp.getProcessOpinion());
        dp.setUpdateDefault();

        return toAjax(drillPlanService.updateById(dp));
    }

    /**
     * 演习图片
     *
     * @author matianxiang
     * @date 2023/8/9 16:25
     */
    //TODO 20230920PreAuthorize("@ss.hasPermi('drill:plan:list')")
    @GetMapping("/picList")
    @ApiOperation("演习图片")
    public AjaxResult picList(String planId) {
        List<DrillPic> list = drillPicService.list(Wrappers.<DrillPic>lambdaQuery().eq(DrillPic::getPlanId, planId));
        return success(list);
    }

    /**
     * 演习总结
     *
     * @author matianxiang
     * @date 2023/8/9 16:23
     */
    //TODO 20230920PreAuthorize("@ss.hasPermi('drill:plan:edit')")
    @Log(title = "演习总结", businessType = BusinessType.UPDATE)
    @PostMapping("/summary")
    @ApiOperation("演习总结")
    public AjaxResult summary(@RequestBody DrillPlanResultDto drillPlan) {
        if (StringUtils.isEmpty(drillPlan.getId())) {
            return AjaxResult.warn("id不能为空");
        }
        if (StringUtils.isEmpty(drillPlan.getDrillSummary())) {
            return AjaxResult.warn("演习总结不能为空");
        }
        return drillPlanService.summaryPlan(drillPlan);
    }

    /**
     * 完成进度统计
     *
     * @author matianxiang
     * @date 2023/8/9 15:38
     */
    //TODO 20230920PreAuthorize("@ss.hasPermi('drill:statistics:list')")
    @GetMapping("/statistics")
    @ApiOperation("完成进度统计")
    public AjaxResult statistics(@RequestParam("year") String year) {
        return drillPlanService.statistics(year);
    }

    /**
     * 消息的定时任务
     *
     * @author matianxiang
     * @date 2023/8/9 17:21
     */
    @GetMapping("/checkPlan")
    @ApiOperation("消息的定时任务")
    public AjaxResult checkPlan() {
        return drillPlanService.checkPlan();
    }

    @GetMapping("/homeStatistics")
    @ApiOperation("首页统计")
    public AjaxResult homeStatistics() {
        Map<String, Long> map = new HashMap<>();
        int year = Calendar.getInstance().get(Calendar.YEAR);
        long total = drillAnnualEmergencyService.count(Wrappers.<DrillAnnualEmergency>lambdaQuery()
                .eq(DrillAnnualEmergency::getIsDel, DeletedEnum.VALID.getValue())
                .eq(DrillAnnualEmergency::getPlanYear, year));
        long finished = drillPlanService.count(Wrappers.<DrillPlan>lambdaQuery()
                .eq(DrillPlan::getIsDel, DeletedEnum.VALID.getValue())
                .eq(DrillPlan::getDrillStatus, DrillEnum.DRILL_STATUS_YES.getValue())
                .eq(DrillPlan::getPlanYear, year));
        long team = drillContingentService.count(Wrappers.<DrillContingent>lambdaQuery()
                .eq(DrillContingent::getIsDel, DeletedEnum.VALID.getValue()));

        map.put("total", total);
        map.put("finished", finished);
        map.put("enter", finished);
        map.put("team", team);

        return success(map);
    }
}
