package com.ruoyi.project.reliability.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.reliability.domain.TQualitativeAnalysis;
import com.ruoyi.project.reliability.domain.TRiskMatrixVo;
import com.ruoyi.project.reliability.service.ITQualitativeAnalysisService;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定性分析Controller
 *
 * @author ssy
 * @date 2024-03-04
 */
@RestController
@RequestMapping("/reliability/analysis")
public class TQualitativeAnalysisController extends BaseController {
    @Autowired
    private ITQualitativeAnalysisService tQualitativeAnalysisService;

    /**
     * 查询定性分析列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:analysis:list')")
    @GetMapping("/list")
    public TableDataInfo list(TQualitativeAnalysis tQualitativeAnalysis) {
        startPage();
        List<TQualitativeAnalysis> list = tQualitativeAnalysisService.selectTQualitativeAnalysisList(tQualitativeAnalysis);
        return getDataTable(list);
    }

    /**
     * 导出定性分析列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:analysis:export')")
    @Log(title = "定性分析", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TQualitativeAnalysis tQualitativeAnalysis) {
        List<TQualitativeAnalysis> list = tQualitativeAnalysisService.selectTQualitativeAnalysisList(tQualitativeAnalysis);
        ExcelUtil<TQualitativeAnalysis> util = new ExcelUtil<TQualitativeAnalysis>(TQualitativeAnalysis.class);
        return util.exportExcel(list, "analysis");
    }

    /**
     * 获取定性分析详细信息
     */
    @PreAuthorize("@ss.hasPermi('reliability:analysis:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tQualitativeAnalysisService.selectTQualitativeAnalysisById(id));
    }

    /**
     * 新增定性分析
     */
    @PreAuthorize("@ss.hasPermi('reliability:analysis:add')")
    @Log(title = "定性分析", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TQualitativeAnalysis tQualitativeAnalysis) {
        return toAjax(tQualitativeAnalysisService.insertTQualitativeAnalysis(tQualitativeAnalysis));
    }

    /**
     * 修改定性分析
     */
    @PreAuthorize("@ss.hasPermi('reliability:analysis:edit')")
    @Log(title = "定性分析", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TQualitativeAnalysis tQualitativeAnalysis) {
        return toAjax(tQualitativeAnalysisService.updateTQualitativeAnalysis(tQualitativeAnalysis));
    }

    /**
     * 删除定性分析
     */
    @PreAuthorize("@ss.hasPermi('reliability:analysis:remove')")
    @Log(title = "定性分析", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tQualitativeAnalysisService.deleteTQualitativeAnalysisByIds(ids));
    }

    @GetMapping("/riskMatrixData")
    public AjaxResult riskMatrixData() {

        TRiskMatrixVo vo = tQualitativeAnalysisService.selectTRiskMatrixVoData();
        double ecSum = vo.getEchb() +
                vo.getEcha() +
                vo.getEcmc() +
                vo.getEcmmb() +
                vo.getEcmhb() +
                vo.getEcld() +
                vo.getEclc() +
                vo.getEclb();
        vo.setOmr(vo.getOmr() - vo.getNr());
        vo.setOpr(vo.getOpr() - vo.getNr());
        if (ecSum == 0) {
            vo.setTotalA("0%");
            vo.setTotalB("0%");
            vo.setTotalC("0%");
            vo.setTotalD("0%");
        } else {
            vo.setTotalA(String.format("%.0f",(vo.getCountA() / ecSum) * 100) + "%");
            vo.setTotalB(String.format("%.0f",(vo.getCountB() / ecSum) * 100) + "%");
            vo.setTotalC(String.format("%.0f",(vo.getCountC() / ecSum) * 100) + "%");
            vo.setTotalD(String.format("%.0f",(vo.getCountD() / ecSum) * 100) + "%");
        }
        return AjaxResult.success(vo);
    }

    @PreAuthorize("@ss.hasPermi('reliability:analysis:add')")
    @Log(title = "定性分析", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TQualitativeAnalysis> list = new ArrayList<>();
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TQualitativeAnalysis entity = new TQualitativeAnalysis();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    //  cell.setCellType(CellType.STRING);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    if (cell.getCellType()== CellType.FORMULA){
                        FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
                        CellValue evaluate = evaluator.evaluate(cell);
                        cellValue=evaluate.formatAsString();
                        cellValue=cellValue.replace("\"","");
                    }
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        entity.setLocation(cellValue);
                    } else if (j == 1) {
                        entity.setTagNo(cellValue);
                    } else if (j == 2) {
                        entity.setDescription(cellValue);
                    } else if (j == 3) {
                        entity.setObjectType(cellValue);
                    } else if (j == 4) {
                        entity.setCatalogProfile(cellValue);
                    } else if (j == 5) {
                        entity.setSpecificationMode(cellValue);
                    } else if (j == 6) {
                        entity.setMaterialSpecification(cellValue);
                    } else if (j == 7) {
                        entity.setRelevant(cellValue);
                    } else if (j == 8) {
                        entity.setFrequencyFailure(cellValue);
                    } else if (j == 9) {
                        entity.setMaintenanceCost(cellValue);
                    } else if (j == 10) {
                        entity.setProductionLoss(cellValue);
                    } else if (j == 11) {
                        entity.setMaintenanceRisk(cellValue);
                    } else if (j == 12) {
                        entity.setProductionRisk(cellValue);
                    } else if (j == 13) {
                        entity.setEquipmentCategory(cellValue);
                    } else if (j == 14) {
                        entity.setRiskCriticality(cellValue);
                    } else if (j == 15) {
                        entity.setQuantitativeAnalysis(cellValue);
                    } else if (j == 16) {
                        entity.setMaintenanceStrategy(cellValue);
                    } else if (j == 17) {
                        entity.setMsDescription(cellValue);
                    } else if (j == 18) {
                        entity.setSparepartStrategy(cellValue);
                    } else if (j == 19) {
                        entity.setSsDescription(cellValue);
                    } else if (j == 20) {
                        entity.setNeedClarification(cellValue);
                    } else if (j == 21) {
                        entity.setRemarks(cellValue);
                    }
                }
                entity.setCreaterCode(getUserId().toString());
                entity.setCreatedate(new Date());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TQualitativeAnalysis t : list
        ) {
            failNum++;
            try {
                tQualitativeAnalysisService.insertTQualitativeAnalysis(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                failRow.add(failNum + 1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" + String.valueOf(successNumber));
        logger.info("failNumber:" + String.valueOf(failNumber));
        logger.info("failRow:" + String.valueOf(failRow));
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }
}
