package com.ruoyi.web.controller.ehs;

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.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.ehsRescueTeam.domain.EhsRescueTeam;
import com.ruoyi.ehsRescueTeam.service.IEhsRescueTeamService;
import com.ruoyi.ehsRescueTeamWorker.domain.EhsRescueTeamWorker;
import com.ruoyi.ehsRescueTeamWorker.service.IEhsRescueTeamWorkerService;
import com.ruoyi.system.service.ISysDictDataService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 应急救援队伍管理Controller
 *
 * @author ruoyi
 * @date 2023-12-11
 */
@Api(tags = "应急救援队伍管理管理")
@RestController
@RequestMapping("/ehs/ehsRescueTeam")
public class EhsRescueTeamController extends BaseController {
    @Autowired
    private IEhsRescueTeamService ehsRescueTeamService;

    @Autowired
    private IEhsRescueTeamWorkerService ehsRescueTeamWorkerService;

    @Autowired
    private ISysDictDataService dictDataService;

    /**
     * 查询应急救援队伍管理列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:ehsRescueTeam:list')")
    @GetMapping("/list")
    public TableDataInfo list(EhsRescueTeam ehsRescueTeam) {
        startPage();
        List<EhsRescueTeam> list = ehsRescueTeamService.selectEhsRescueTeamList(ehsRescueTeam);
        return getDataTable(list);
    }

    /**
     * 导出应急救援队伍管理列表
     */
    /*@PreAuthorize("@ss.hasPermi('ehs:ehsRescueTeam:export')")
    @Log(title = "应急救援队伍管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EhsRescueTeam ehsRescueTeam) {
        List<EhsRescueTeam> list = ehsRescueTeamService.selectEhsRescueTeamList(ehsRescueTeam);
        ExcelUtil<EhsRescueTeam> util = new ExcelUtil<>(EhsRescueTeam.class);
        util.exportExcel(response, list, "应急救援队伍管理数据");
    }*/

    /**
     * 要求队导出表格内容包含：队伍名称，队长，队员信息
     * @param response
     * @param ehsRescueTeam
     */
    //@PreAuthorize("@ss.hasPermi('ehs:ehsRescueTeam:export')")
    @Log(title = "应急救援队伍管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, EhsRescueTeam ehsRescueTeam) {
        List<EhsRescueTeam> list = ehsRescueTeamService.selectEhsRescueTeamList(ehsRescueTeam);
        // Map的key为队伍id,map的value为负责人
        Map<Long, String> map = list.stream().collect(Collectors.toMap(
                EhsRescueTeam::getId,
                item -> item.getDutyer() == null ? "" : item.getDutyer()
        ));
        List<Long> teamIds = list.stream().map(EhsRescueTeam::getId).collect(Collectors.toList());
        // 根据teamIdList查询人员表
        List<EhsRescueTeamWorker> teamWorkerList = ehsRescueTeamWorkerService.listWorkerByTeamIds(teamIds);
        teamWorkerList.forEach(item -> {
            // 给每个人员的负责人属性赋值
            item.setDutyer(map.get(item.getRescueTeamId()));
        });
        ExcelUtil<EhsRescueTeamWorker> util = new ExcelUtil<>(EhsRescueTeamWorker.class);
        util.exportExcel(response, teamWorkerList, "应急救援队伍管理数据");
    }

    /**
     * 下载批量导入模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws Exception {
        ExcelUtil<EhsRescueTeam> util = new ExcelUtil<>(EhsRescueTeam.class);
        util.importComboTemplateExcel(response, "应急救援队伍信息数据");
    }

    /**
     * 批量导入
     */
    @PostMapping("/importData")
    public AjaxResult importHubManage(MultipartFile file, Boolean updateSupport) throws Exception {
        ExcelUtil<EhsRescueTeam> util = new ExcelUtil<>(EhsRescueTeam.class);
        List<EhsRescueTeam> list = util.importExcel(file.getInputStream());
        String message = ehsRescueTeamService.importRescueTeam(list, updateSupport);
        return AjaxResult.success(message);
    }

    /**
     * 获取应急救援队伍管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('ehs:ehsRescueTeam:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(ehsRescueTeamService.selectEhsRescueTeamById(id));
    }

    /**
     * 新增应急救援队伍管理
     */
    @ApiOperation("新增应急救援队伍管理")
    @PreAuthorize("@ss.hasPermi('ehs:ehsRescueTeam:add')")
    @Log(title = "应急救援队伍管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional
    public AjaxResult add(@RequestBody EhsRescueTeam ehsRescueTeam) {
        String teamLevel = DictUtils.getDictLabel("team_level", ehsRescueTeam.getTeamLevel());
        if (StringUtils.isBlank(teamLevel)) {
            // 字典表中不存在该队伍级别就创建
            SysDictData dictData = new SysDictData();
            dictData.setDictLabel(ehsRescueTeam.getTeamLevel());
            dictData.setDictValue(ehsRescueTeam.getTeamLevel());
            dictData.setDictType("team_level");
            dictData.setListClass("default");
            dictData.setCreateTime(new Date());
            dictData.setCreateBy(getUsername());
            dictDataService.insertDictData(dictData);
        }

        return toAjax(ehsRescueTeamService.save(ehsRescueTeam));
    }

    /**
     * 修改应急救援队伍管理
     */
    @ApiOperation("修改应急救援队伍管理")
    @PreAuthorize("@ss.hasPermi('ehs:ehsRescueTeam:edit')")
    @Transactional
    @Log(title = "应急救援队伍管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody EhsRescueTeam ehsRescueTeam) {
        // 更新应急救援队伍信息
        boolean result = ehsRescueTeamService.updateById(ehsRescueTeam);
        // 更新应急救援队伍人员信息
        ehsRescueTeamWorkerService.updateWorkerByTeamId(ehsRescueTeam);
        return toAjax(result);
    }

    /**
     * 删除应急救援队伍管理
     */
    @ApiOperation("删除应急救援队伍管理")
    @PreAuthorize("@ss.hasPermi('ehs:ehsRescueTeam:remove')")
    @Log(title = "应急救援队伍管理", businessType = BusinessType.DELETE)
    @Transactional
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        // 根据队伍ids删除队伍
        boolean result = ehsRescueTeamService.removeByIds(Arrays.asList(ids));
        // 根据队伍ids删除队伍中的队员
        ehsRescueTeamWorkerService.removeWorkerByTeamIds(Arrays.asList(ids));
        return toAjax(result);
    }
}
