package com.goldenwater.slaj.hidd.controller;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.goldenwater.common.core.controller.BaseController;
import com.goldenwater.common.core.domain.AjaxResult;
import com.goldenwater.common.core.page.TableDataInfo;
import com.goldenwater.slaj.hidd.domain.HiddGroupByExportVo;
import com.goldenwater.slaj.hidd.domain.ObjHidd;
import com.goldenwater.slaj.hidd.domain.ObjHiddVo;
import com.goldenwater.slaj.hidd.service.IObjHiddService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import com.goldenwater.common.annotation.Log;
import com.goldenwater.common.enums.BusinessType;
import org.springframework.web.multipart.MultipartFile;
import com.goldenwater.common.utils.poi.ExcelUtil;

/**
 * 隐患对象
 */
@RestController
@RequestMapping("/hidd/objhidd")
public class ObjHiddController extends BaseController {
    @Autowired
    private IObjHiddService objHiddService;

    @GetMapping("/list")
    public TableDataInfo list(ObjHidd objHidd) {
        startPage();
        List<ObjHiddVo> list = objHiddService.selectObjHiddList(objHidd);
        return getDataTable(list);
    }

    @GetMapping("/{guid}")
    public AjaxResult getInfo(@PathVariable String guid) {
        return AjaxResult.success(objHiddService.selectObjHiddByGuid(guid));
    }

    @PostMapping
    public AjaxResult add(@RequestBody ObjHidd objHidd) {
        return toAjax(objHiddService.insertObjHidd(objHidd));
    }

    @PutMapping
    public AjaxResult edit(@RequestBody ObjHidd objHidd) {
        // 校验只能修改自己新增的隐患记录
        ObjHidd original = objHiddService.selectObjHiddByGuid(objHidd.getGuid());
        if (original == null) {
            return AjaxResult.error("隐患记录不存在");
        }
        String currentUserId = String.valueOf(getUserId());
        if (!currentUserId.equals(original.getRecPers())) {
            return AjaxResult.error("只能修改自己新增的隐患记录");
        }
        return toAjax(objHiddService.updateObjHidd(objHidd));
    }

    @DeleteMapping("/{guids}")
    public AjaxResult remove(@PathVariable String[] guids) {
        return toAjax(objHiddService.deleteObjHiddByGuids(guids));
    }

    /**
     * 隐患名称匹配查询
     */
    @GetMapping("/listByName")
    public TableDataInfo listByName(ObjHidd objHidd) {
        startPage();
        List<ObjHiddVo> list = objHiddService.selectObjHiddListByName(objHidd);
        return getDataTable(list);
    }

    /**
     * 下级单位隐患列表
     */
    @GetMapping("/nextDepList")
    public TableDataInfo nextDepList(ObjHidd objHidd) {
        startPage();
        List<ObjHiddVo> list = objHiddService.selectNextDepHiddList(objHidd);
        return getDataTable(list);
    }

    /**
     * 下级隐患保存
     */
    @PostMapping("/saveNextHidd")
    public AjaxResult saveNextHidd(@RequestBody ObjHidd objHidd) {
        return toAjax(objHiddService.insertNextHidd(objHidd));
    }

    @Log(title = "隐患对象管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('hidd:objhidd:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, ObjHidd objHidd) {
        List<ObjHiddVo> list = objHiddService.selectObjHiddList(objHidd);
        ExcelUtil<ObjHiddVo> util = new ExcelUtil<>(ObjHiddVo.class);
        util.exportExcel(response, list, "隐患对象数据");
    }

    /**
     * 隐患导入（Excel批量导入）
     */
    @Log(title = "隐患对象管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('hidd:objhidd:add')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<ObjHidd> util = new ExcelUtil<>(ObjHidd.class);
        List<ObjHidd> list = util.importExcel(file.getInputStream());
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failMsg = new StringBuilder();
        int successCount = 0;
        int failCount = 0;
        for (ObjHidd hidd : list) {
            try {
                objHiddService.insertObjHidd(hidd);
                successCount++;
            } catch (Exception e) {
                failCount++;
                failMsg.append("行").append(successCount + failCount).append(": ").append(e.getMessage()).append("<br/>");
            }
        }
        successMsg.append("导入成功").append(successCount).append("条");
        if (failCount > 0) {
            failMsg.insert(0, "导入失败").append(failCount).append("条<br/>");
        }
        return AjaxResult.success(successMsg.toString() + failMsg.toString());
    }

    /**
     * 工程/非工程隐患聚合查询
     */
    @GetMapping("/groupBy")
    public TableDataInfo groupBy(@RequestParam(required = false) String hiddSort,
                                  @RequestParam(required = false) String engName,
                                  @RequestParam(required = false) String orgName,
                                  @RequestParam(required = false) String collTime) {
        Map<String, Object> params = new java.util.HashMap<>();
        params.put("hiddSort", hiddSort);
        params.put("engName", engName);
        params.put("orgName", orgName);
        params.put("collTime", collTime);
        startPage();
        List<Map<String, Object>> list = objHiddService.selectHiddGroupBy(params);
        return getDataTable(list);
    }

    @Log(title = "隐患查询导出", businessType = BusinessType.EXPORT)
    @PostMapping("/groupBy/export")
    public void groupByExport(HttpServletResponse response,
                               @RequestParam(required = false) String hiddSort,
                               @RequestParam(required = false) String engName,
                               @RequestParam(required = false) String orgName,
                               @RequestParam(required = false) String collTime) {
        Map<String, Object> params = new java.util.HashMap<>();
        params.put("hiddSort", hiddSort);
        params.put("engName", engName);
        params.put("orgName", orgName);
        params.put("collTime", collTime);
        List<Map<String, Object>> list = objHiddService.selectHiddGroupBy(params);
        List<HiddGroupByExportVo> exportList = list.stream().map(m -> {
            HiddGroupByExportVo vo = new HiddGroupByExportVo();
            vo.setEngName((String) m.get("engName"));
            vo.setOrgName((String) m.get("orgName"));
            vo.setTotalCount(String.valueOf(m.getOrDefault("totalCount", "0")));
            vo.setNormalCount(String.valueOf(m.getOrDefault("normalCount", "0")));
            vo.setMajorCount(String.valueOf(m.getOrDefault("majorCount", "0")));
            vo.setSolvedCount(String.valueOf(m.getOrDefault("solvedCount", "0")));
            return vo;
        }).collect(java.util.stream.Collectors.toList());
        ExcelUtil<HiddGroupByExportVo> util = new ExcelUtil<>(HiddGroupByExportVo.class);
        util.exportExcel(response, exportList, "隐患查询数据");
    }

    /**
     * 复合保存隐患（obj_hidd + bis_hidd_inve）
     */
    @Log(title = "隐患保存", businessType = BusinessType.INSERT)
    @PostMapping("/compoundSave")
    public AjaxResult compoundSave(@RequestBody Map<String, Object> params) {
        try {
            return toAjax(objHiddService.compoundSave(params));
        } catch (Exception e) {
            return AjaxResult.error("保存失败：" + e.getMessage());
        }
    }

    /**
     * 隐患上报（批量）
     */
    @Log(title = "隐患上报", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('hidd:objhidd:report')")
    @PutMapping("/report")
    public AjaxResult report(@RequestParam String guids) {
        if (guids == null || guids.isEmpty()) {
            return AjaxResult.error("请选择要上报的隐患");
        }
        String[] guidArr = guids.split(",");
        int count = 0;
        for (String guid : guidArr) {
            ObjHidd hidd = objHiddService.selectObjHiddByGuid(guid);
            if (hidd != null) {
                hidd.setUpdTime(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()));
                count += objHiddService.updateObjHidd(hidd);
            }
        }
        return toAjax(count);
    }

    /**
     * 隐患退回（批量）
     */
    @Log(title = "隐患退回", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('hidd:objhidd:return')")
    @PutMapping("/return")
    public AjaxResult returnHidd(@RequestParam String guids, @RequestParam String returnDesc) {
        if (guids == null || guids.isEmpty()) {
            return AjaxResult.error("请选择要退回的隐患");
        }
        String[] guidArr = guids.split(",");
        int count = 0;
        for (String guid : guidArr) {
            ObjHidd hidd = objHiddService.selectObjHiddByGuid(guid);
            if (hidd != null) {
                hidd.setNote((hidd.getNote() == null ? "" : hidd.getNote()) + " [退回:" + returnDesc + "]");
                hidd.setUpdTime(new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()));
                count += objHiddService.updateObjHidd(hidd);
            }
        }
        return toAjax(count);
    }
}
