package com.ruoyi.web.controller.drill;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.DeletedEnum;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.drill.domain.DrillAnnualEmergency;
import com.ruoyi.drill.dto.DrillAnnualEmergencyDto;
import com.ruoyi.drill.service.IDrillAnnualEmergencyService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
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 org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;

/**
 * 年度演习计划Controller
 *
 * @author ruoyi
 * @date 2023-08-03
 */
@Api(tags = "年度演习计划")
@RestController
@RequestMapping("/drill/emergency")
public class DrillAnnualEmergencyController extends BaseController {

    @Resource
    private IDrillAnnualEmergencyService drillAnnualEmergencyService;
    @Resource
    private ISysUserService userService;

    /**
     * 查询年度演习计划列表
     */
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('drill:emergency:list')")
    @GetMapping("/list")
    @ApiOperation("查询年度演习计划列表")
    public TableDataInfo list(DrillAnnualEmergency drillAnnualEmergency) {
        startPage();
        LambdaQueryWrapper<DrillAnnualEmergency> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(drillAnnualEmergency.getPlanName())) {
            wrapper.like(DrillAnnualEmergency::getPlanName, drillAnnualEmergency.getPlanName());
        }
        if (Objects.nonNull(drillAnnualEmergency.getPlanYear())) {
            wrapper.eq(DrillAnnualEmergency::getPlanYear, drillAnnualEmergency.getPlanYear());
        }
        wrapper.eq(DrillAnnualEmergency::getIsDel, DeletedEnum.VALID.getValue());
        wrapper.orderByDesc(DrillAnnualEmergency::getFinishTime);
        wrapper.orderByDesc(DrillAnnualEmergency::getPlanYear);
        wrapper.orderByAsc(DrillAnnualEmergency::getSortdNum);
        List<DrillAnnualEmergency> list = drillAnnualEmergencyService.list(wrapper);
        for (DrillAnnualEmergency annualEmergency : list) {
            if (StringUtils.isNotBlank(annualEmergency.getFinishBy())) {
                SysUser sysUser = userService.selectUserById(Long.valueOf(annualEmergency.getFinishBy()));
                annualEmergency.setFinishBy(Objects.nonNull(sysUser) ? sysUser.getNickName() : "");
            }
            if (StringUtils.isNotBlank(annualEmergency.getDirectorBy())) {
                SysUser sysUser = userService.selectUserById(Long.valueOf(annualEmergency.getDirectorBy()));
                annualEmergency.setDirectorBy(Objects.nonNull(sysUser) ? sysUser.getNickName() : "");
            }
        }
        return getDataTable(list);
    }

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

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<DrillAnnualEmergencyDto> util = new ExcelUtil<DrillAnnualEmergencyDto>(DrillAnnualEmergencyDto.class);
        util.importTemplateExcel(response, "模板");
    }

    /**
     * 导入年度演习计划
     */
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('drill:emergency:add')")
    @Log(title = "导入年度演习计划", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation("导入年度演习计划")
    public AjaxResult saveAnnualEmergency(@RequestParam("file") @ApiParam(name = "file", value = "上传文件") MultipartFile file, Long year, Long directorBy) {
        try {
            return drillAnnualEmergencyService.saveAnnualEmergency(year, file, directorBy);
        } catch (RuntimeException e) {
            return error("导入模板错误");
        }
    }

    /**
     * 修改年度演习计划
     */
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('drill:emergency:edit')")
    @Log(title = "修改年度演习计划", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("修改年度演习计划")
    public AjaxResult edit(@RequestBody DrillAnnualEmergency drillAnnualEmergency) {
        if (StringUtils.isEmpty(drillAnnualEmergency.getId())) {
            return warn("必填参数不能为空");
        }
        if (StringUtils.isEmpty(drillAnnualEmergency.getPlanName())) {
            return warn("演习名称不能为空");
        }
        if (Objects.isNull(drillAnnualEmergency.getPlanYear())) {
            return warn("演习年度不能为空");
        }
        if (null == drillAnnualEmergency.getPlanMonth()) {
            return warn("演习月份不能为空");
        }
        long count = drillAnnualEmergencyService.count(Wrappers.<DrillAnnualEmergency>lambdaQuery()
                .ne(DrillAnnualEmergency::getId, drillAnnualEmergency.getId())
                .eq(DrillAnnualEmergency::getPlanName, drillAnnualEmergency.getPlanName())
                .eq(DrillAnnualEmergency::getIsDel, DeletedEnum.VALID.getValue()));
        if (count > 0) {
            return warn("项目内容重复:" + drillAnnualEmergency.getPlanName());
        }
        drillAnnualEmergency.setUpdateDefault();
        return toAjax(drillAnnualEmergencyService.updateById(drillAnnualEmergency));
    }

    /**
     * 删除年度演习计划
     */
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('drill:emergency:remove')")
    @Log(title = "删除年度演习计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    @ApiOperation("删除年度演习计划")
    public AjaxResult remove(String ids) {
        String regex = ",";
        List<String> list = Collections.singletonList(ids);
        if (StringUtils.isNotBlank(ids) && ids.contains(regex)) {
            String[] split = ids.split(regex);
            list = Arrays.asList(split);
        }
        return toAjax(drillAnnualEmergencyService.removeBatchByIds(list));
    }

    /**
     * 查询全部演习种类配置列表
     */
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('drill:emergency:list')")
    @GetMapping("/allTypeList")
    @ApiOperation("查询演习种类列表")
    public AjaxResult allTypeList() {
        LambdaQueryWrapper<DrillAnnualEmergency> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(DrillAnnualEmergency::getIsDel, DeletedEnum.VALID.getValue());
        List<DrillAnnualEmergency> list = drillAnnualEmergencyService.list(wrapper);
        Set<String> set = new HashSet<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (DrillAnnualEmergency drillAnnualEmergency : list) {
                set.add(drillAnnualEmergency.getPlanName());
            }
        }
        return success(set);
    }
}
