package com.ruoyi.web.controller.doubleDefense;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson2.JSON;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.utils.ImageUtil;
import com.ruoyi.common.utils.file.ImageUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.doubledefense.dto.RiskUnitDTO;
import com.ruoyi.doubledefense.dto.res.RiskUnitResultDTO;
import com.ruoyi.doubledefense.dtoGov.*;
import com.ruoyi.doubledefense.service.*;
import com.ruoyi.doubledefense.service.impl.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeansException;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
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.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.doubledefense.domain.RiskUnit;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 风险分析单元Controller
 *
 * @author ruoyi
 * @date 2023-08-03
 */
@Api(tags = "风险分析单元")
@RestController
@RequestMapping("/doubledefense/unit")
public class RiskUnitController extends BaseController {
    @Autowired
    private IRiskUnitService riskUnitService;

    /**
     * 查询风险分析单元列表
     */
    @ApiOperation("查询风险分析单元列表")
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('doubledefense:unit:list')")
    @GetMapping("/list")
    public TableDataInfo list(RiskUnitDTO riskUnit) {
        startPage();
        List<RiskUnitResultDTO> list = riskUnitService.selectRiskUnitList(riskUnit);
        return getDataTable(list);
    }

    /**
     * 导出风险分析单元列表
     */
    @ApiOperation("导出风险分析单元列表")
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('doubledefense:unit:export')")
    @Log(title = "风险分析单元", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, RiskUnitDTO riskUnit) {
        List<RiskUnitResultDTO> list = riskUnitService.selectRiskUnitList(riskUnit);
        ExcelUtil<RiskUnitResultDTO> util = new ExcelUtil<RiskUnitResultDTO>(RiskUnitResultDTO.class);
        util.exportExcel(response, list, "风险分析单元数据");
    }

    /**
     * 获取风险分析单元详细信息
     */
    @ApiOperation("获取分析单元详细信息")
    @ApiImplicitParam(name = "id", value = "分析单元ID", required = true, dataType = "String", paramType = "path", dataTypeClass = String.class)
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('doubledefense:unit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {

        Map<String, Object> dataMap = new HashMap<>();
//        List<Object> dataList = new ArrayList<>();


        //1、企业安全风险空间分布接口->四色图
        IFourColorDiagramService fourColorDiagramService = SpringUtils.getBean(FourColorDiagramServiceImpl.class);
        FourColorDiagramDTOGov fourColorDiagramDTOGov = new FourColorDiagramDTOGov();
        fourColorDiagramDTOGov.setPageNo(1);
        fourColorDiagramDTOGov.setPageSize(20);//一个企业做多上传20张
        PageInfo<FourColorDiagramDTOGov> govSelectFourColorDiagramList = fourColorDiagramService.govSelectFourColorDiagramList(fourColorDiagramDTOGov);
        List<FourColorDiagramDTOGov> fourColorDiagramDTOGovList = govSelectFourColorDiagramList.getList();
        Iterator<FourColorDiagramDTOGov> fourColorDiagramDTOGovIterator = fourColorDiagramDTOGovList.iterator();
        while (fourColorDiagramDTOGovIterator.hasNext()) {
            FourColorDiagramDTOGov colorDiagramDTOGov = fourColorDiagramDTOGovIterator.next();
            String colorImg = colorDiagramDTOGov.getColorImg();
            String imageToBase64Str = null;
            try {
                imageToBase64Str = ImageUtil.convertImageToBase64Str(colorImg);

                byte[] imageBytes = Base64.getDecoder().decode(imageToBase64Str.split(",")[1]);
                InputStream in = new ByteArrayInputStream(imageBytes);
                BufferedImage image = ImageIO.read(in);
                if (image != null) {
                    // 校验成功
                    System.out.println("SUCCESS----------");
                } else {
                    fourColorDiagramDTOGovIterator.remove();
                    // 校验失败
                    System.out.println("ERROR-----");
                }
            } catch (Exception e) {
                fourColorDiagramDTOGovIterator.remove();
                e.printStackTrace();
            }
            colorDiagramDTOGov.setColorImg(imageToBase64Str);
        }
        dataMap.put("1、四色图", govSelectFourColorDiagramList);

        //2、测试分析单元
        RiskUnitDTOGov ristUnit = new RiskUnitDTOGov();
        ristUnit.setPageNo(1);
        ristUnit.setPageSize(10);
        PageInfo<RiskUnitDTOGov> govSelectRiskUnitList = riskUnitService.govSelectRiskUnitList(ristUnit);
        dataMap.put("2、测试分析单元", govSelectRiskUnitList);
//        List<RiskUnitDTOGov> list = govSelectRiskUnitList.getList();
//        for (RiskUnitDTOGov data : list) {
//            System.out.println();
//            System.out.println(data);
//            System.out.println(JSON.toJSONString(data));
//            System.out.println();
//        }

        //3、测试风险事件
        IRiskEventService riskEventService = SpringUtils.getBean(RiskEventServiceImpl.class);
        RiskEventDTOGov riskEvent = new RiskEventDTOGov();
        riskEvent.setPageNo(1);
        riskEvent.setPageSize(10);
        PageInfo<RiskEventDTOGov> govSelectRiskEventList = riskEventService.govSelectRiskEventList(riskEvent);
        dataMap.put("3、测试风险事件", govSelectRiskEventList);

        //4、安全风险管控措施
        IRiskMeasureService riskMeasureService = SpringUtils.getBean(RiskMeasureServiceImpl.class);
        RiskMeasureDTOGov riskMeasureDTOGov = new RiskMeasureDTOGov();
        riskMeasureDTOGov.setPageNo(1);
        riskMeasureDTOGov.setPageSize(10);
        PageInfo<RiskMeasureDTOGov> govSelectRiskMeasureList = riskMeasureService.govSelectRiskMeasureList(riskMeasureDTOGov);
        dataMap.put("4、安全风险管控措施", govSelectRiskMeasureList);

        //5、隐患排查任务 -> 隐患排查要求
        ICheckTaskService checkTaskService = SpringUtils.getBean(CheckTaskServiceImpl.class);
        CheckTaskDTOGov checkTaskDTOGov = new CheckTaskDTOGov();
        checkTaskDTOGov.setPageNo(1);
        checkTaskDTOGov.setPageSize(10);
        PageInfo<CheckTaskDTOGov> govSelectCheckTaskList = checkTaskService.govSelectCheckTaskList(checkTaskDTOGov);
        dataMap.put("5、隐患排查任务 -> 隐患排查要求", govSelectCheckTaskList);

        //6、隐患排查记录 -> 巡检记录
        ICheckTaskInventoryRecordService checkTaskInventoryRecordService = SpringUtils.getBean(CheckTaskInventoryRecordServiceImpl.class);
        CheckTaskInventoryRecordDTOGov checkTaskInventoryRecordDTOGov = new CheckTaskInventoryRecordDTOGov();
        checkTaskInventoryRecordDTOGov.setPageNo(1);
        checkTaskInventoryRecordDTOGov.setPageSize(20);
        PageInfo<CheckTaskInventoryRecordDTOGov> govSelectCheckTaskInventoryRecordList = checkTaskInventoryRecordService.govSelectCheckTaskInventoryRecordList(checkTaskInventoryRecordDTOGov);
        dataMap.put("6、隐患排查记录 -> 巡检记录", govSelectCheckTaskInventoryRecordList);

        //7、隐患排查信息->隐患列表（APP和PC都可以添加隐患）
        IDangerService dangerService = SpringUtils.getBean(DangerServiceImpl.class);
        DangerDTOGov dangerDTOGov = new DangerDTOGov();
        dangerDTOGov.setPageNo(1);
        dangerDTOGov.setPageSize(10);
        PageInfo<DangerDTOGov> govSelectDangerList = dangerService.govSelectDangerList(dangerDTOGov);
        dataMap.put("7、隐患排查信息->隐患列表（APP和PC都可以添加隐患）", govSelectDangerList);


        return success(dataMap);

//        return success(riskUnitService.selectRiskUnitById(id));
    }

    /**
     * 新增风险分析单元
     */
    @ApiOperation("新增分析单元")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "hazardId", value = "风险分析对象ID", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "riskUnitName", value = "风险分析单元名称", dataType = "String", dataTypeClass = String.class),
    })
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('doubledefense:unit:add')")
    @Log(title = "风险分析单元", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody RiskUnitDTO riskUnit) {
        return toAjax(riskUnitService.insertRiskUnit(riskUnit));
    }

    /**
     * 修改风险分析单元
     */
    @ApiOperation("修改分析单元")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "风险分析单元ID", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "hazardId", value = "风险分析对象ID", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "riskUnitName", value = "风险分析单元名称", dataType = "String", dataTypeClass = String.class),
    })//TODO 20230920PreAuthorize("@("@ss.hasPermi('doubledefense:unit:edit')")
    @Log(title = "风险分析单元", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody RiskUnitDTO riskUnit) {
        return toAjax(riskUnitService.updateRiskUnit(riskUnit));
    }

    /**
     * 删除风险分析单元
     */
    @ApiOperation("删除分析单元")
    //TODO 20230920PreAuthorize("@("@ss.hasPermi('doubledefense:unit:remove')")
    @Log(title = "风险分析单元", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(riskUnitService.deleteRiskUnitByIds(ids));
    }
}
