package com.ruoyi.project.check.controller;

import com.alibaba.fastjson2.JSON;
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.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.project.base.domain.TBasePlant;
import com.ruoyi.project.base.domain.TBaseRegion;
import com.ruoyi.project.base.service.ITBasePlantService;
import com.ruoyi.project.check.domain.TCheckCalibration;
import com.ruoyi.project.check.domain.TCheckEnvironment;
import com.ruoyi.project.check.domain.TCheckInstrument;
import com.ruoyi.project.check.service.ITCheckCalibrationService;
import com.ruoyi.project.check.service.ITCheckEnvironmentService;
import com.ruoyi.project.check.service.ITCheckInstrumentService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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 javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 环境本底值记录Controller
 *
 * @author ruoyi
 * @date 2022-11-24
 */
@RestController
@RequestMapping("/check/environment")
public class TCheckEnvironmentController extends BaseController {
    @Autowired
    private ITCheckEnvironmentService tCheckEnvironmentService;

    @Autowired
    private ITCheckCalibrationService tCheckCalibrationService;

    @Autowired
    private ITCheckInstrumentService tCheckInstrumentService;

    @Autowired
    private ITBasePlantService tBasePlantService;

    /**
     * 查询环境本底值记录列表
     */
    @PreAuthorize("@ss.hasPermi('check:environment:list')")
    @GetMapping("/list")
    public TableDataInfo list(TCheckEnvironment tCheckEnvironment) {
        startPage();
        List<TCheckEnvironment> list = tCheckEnvironmentService.selectTCheckEnvironmentList(tCheckEnvironment);
        return getDataTable(list);
    }

    /**
     * 导出环境本底值记录列表
     */
    @PreAuthorize("@ss.hasPermi('check:environment:export')")
    @Log(title = "环境本底值记录导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TCheckEnvironment tCheckEnvironment) {
        List<TCheckEnvironment> list = tCheckEnvironmentService.selectTCheckEnvironmentList(tCheckEnvironment);
        ExcelUtil<TCheckEnvironment> util = new ExcelUtil<TCheckEnvironment>(TCheckEnvironment.class);
        util.exportExcel(response, list, "环境本底值记录数据");
    }

    /**
     * 获取环境本底值记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('check:environment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tCheckEnvironmentService.selectTCheckEnvironmentById(id));
    }

    /**
     * 新增环境本底值记录
     */
    @PreAuthorize("@ss.hasPermi('check:environment:add')")
    @Log(title = "环境本底值记录新增", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TCheckEnvironment tCheckEnvironment) {
        TCheckCalibration calibration = new TCheckCalibration();
        calibration.setInstrumentId(tCheckEnvironment.getInstrumentId());
        calibration.setCalibrationTime(tCheckEnvironment.getTestTime());
        List<TCheckCalibration> tCheckCalibrations = tCheckCalibrationService.selectTCheckCalibrationList(calibration);
        if (CollectionUtils.isEmpty(tCheckCalibrations)){
            return AjaxResult.error("根据仪器和检测时间未查询到对应仪器校准记录");
        }
        tCheckEnvironment.setUpdatedate(new Date());
        tCheckEnvironment.setUpdaterCode(getUserId());
        tCheckEnvironment.setCreaterCode(getUserId());
        return toAjax(tCheckEnvironmentService.insertTCheckEnvironment(tCheckEnvironment));
    }

    /**
     * 修改环境本底值记录
     */
    @PreAuthorize("@ss.hasPermi('check:environment:edit')")
    @Log(title = "环境本底值记录修改", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TCheckEnvironment tCheckEnvironment) {
        tCheckEnvironment.setUpdatedate(new Date());
        tCheckEnvironment.setUpdaterCode(getUserId());
        return toAjax(tCheckEnvironmentService.updateTCheckEnvironment(tCheckEnvironment));
    }

    /**
     * 删除环境本底值记录
     */
    @PreAuthorize("@ss.hasPermi('check:environment:remove')")
    @Log(title = "环境本底值记录删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tCheckEnvironmentService.deleteTCheckEnvironmentByIds(ids));
    }


    @Log(title = "环境本底值导入", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TCheckEnvironment> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 1; i < rowNum; i++) {
            BigDecimal bv = new BigDecimal("0");
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TCheckEnvironment entity = new TCheckEnvironment();
                Long plantId = 0L;
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    if (cell == null) {
                        continue;
                    }
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        //装置名称
                        TBasePlant tBasePlant = tBasePlantService.selectTBasePlantByName(cellValue);
                        if (tBasePlant == null || StringUtils.isEmpty(cellValue)) {
                            failNumber++;
                            logger.info("未找到装置");
                            failRow.add(i + 1);
                            continue;
                        }
                        plantId = tBasePlant.getPlantId();
                        entity.setPlantId(plantId);
                    } else if (j == 1) {
                        //  组件编码
                        entity.setAssemblyCode(cellValue);
                    } else if (j == 2) {
                        // 仪器id
                        TCheckInstrument tCheckInstrument = new TCheckInstrument();
                        tCheckInstrument.setCode(cellValue);
                        List<TCheckInstrument> tCheckInstruments = tCheckInstrumentService.selectTCheckInstrumentList(tCheckInstrument);
                        if (CollectionUtils.isEmpty(tCheckInstruments)) {
                            failNumber++;
                            logger.info("未找到仪器");
                            failRow.add(i + 1);
                            continue;
                        }
                        entity.setInstrumentId(tCheckInstruments.get(0).getId());
                    } else if (j == 4) {
                        // 大气压
                        entity.setAtmos(cellValue);
                    } else if (j == 5) {
                        // 环境温度
                        entity.setAmbientTemp(cellValue);
                    } else if (j == 6) {
                        // 环境湿度
                        entity.setAmbientHumidity(cellValue);
                    } else if (j == 7) {
                        // 凤向
                        entity.setWindDirection(cellValue);
                    } else if (j == 8) {
                        // 凤速
                        entity.setWindDirection(cellValue);
                    } else if (j == 9) {
                        // 检测人员
                        entity.setTester(cellValue);
                    } else if (j == 10) {
                        // 检测日期
                        entity.setTestTime(sdf.parse(cellValue));
                    } else if (j == 11) {
                        bv = bv.add(new BigDecimal(StringUtils.isEmpty(cellValue) ? "0" : cellValue));
                        // 检测位置1
                        entity.setPosition1(cellValue);
                    } else if (j == 12) {
                        bv = bv.add(new BigDecimal(StringUtils.isEmpty(cellValue) ? "0" : cellValue));
                        // 检测位置1
                        entity.setPosition2(cellValue);
                    } else if (j == 13) {
                        bv = bv.add(new BigDecimal(StringUtils.isEmpty(cellValue) ? "0" : cellValue));
                        // 检测位置1
                        entity.setPosition3(cellValue);
                    } else if (j == 14) {
                        bv = bv.add(new BigDecimal(StringUtils.isEmpty(cellValue) ? "0" : cellValue));
                        // 检测位置1
                        entity.setPosition4(cellValue);
                    } else if (j == 15) {
                        bv = bv.add(new BigDecimal(StringUtils.isEmpty(cellValue) ? "0" : cellValue));
                        // 检测位置1
                        entity.setPosition5(cellValue);
                    } else if (j == 16) {
                        // 检测位置1
                        entity.setRemarks(cellValue);
                    }
                }
                entity.setBackgroundValue(bv.divide(new BigDecimal(5), 1, RoundingMode.HALF_UP).toString());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + JSON.toJSONString(e));
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TCheckEnvironment t : list) {
            failNum++;
            try {
                add(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" + successNumber);
        logger.info("failNumber:" + failNumber);
        logger.info("failRow:" + failRow);
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }

}
