package com.ruoyi.project.sems.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
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.sems.domain.TMeasureRecord;
import com.ruoyi.project.sems.domain.TMeasureThickness;
import com.ruoyi.project.sems.mapper.TMeasureThicknessMapper;
import com.ruoyi.project.sems.service.ITMeasureRecordService;
import com.ruoyi.project.sems.service.ITMeasureThicknessService;
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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 测厚记录Controller
 *
 * @author ruoyi
 * @date 2021-07-08
 */
@RestController
@RequestMapping("/sems/measure-record")
public class TMeasureRecordController extends BaseController {
    @Autowired
    private ITMeasureRecordService tMeasureRecordService;
    @Autowired
    private ITMeasureThicknessService tMeasureThicknessService;
    @Resource
    private TMeasureThicknessMapper tMeasureThicknessMapper;

    /**
     * 查询测厚记录列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TMeasureRecord tMeasureRecord) {
        startPage();
        List<TMeasureRecord> list = tMeasureRecordService.selectTMeasureRecordList(tMeasureRecord);
        TMeasureThickness thickness = tMeasureThicknessMapper.selectTMeasureThicknessById(Long.valueOf(tMeasureRecord.getMeasureId()));
        for (TMeasureRecord t : list
        ) {
            t.setLoopNo(thickness.getLoopNo());
        }
        return getDataTable(list);
    }

    /**
     * 导出测厚记录列表
     */
    @Log(title = "测厚记录", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TMeasureRecord tMeasureRecord) {
        List<TMeasureRecord> list = tMeasureRecordService.selectTMeasureRecordList(tMeasureRecord);
        ExcelUtil<TMeasureRecord> util = new ExcelUtil<TMeasureRecord>(TMeasureRecord.class);
        return util.exportExcel(list, "measure-record");
    }

    /**
     * 获取测厚记录详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tMeasureRecordService.selectTMeasureRecordById(id));
    }

    /**
     * 新增测厚记录
     */
    @Log(title = "测厚记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TMeasureRecord tMeasureRecord) {
        tMeasureRecordService.insertTMeasureRecord(tMeasureRecord);
        String measureId = tMeasureRecord.getMeasureId();
        try {
            updateMeasure(measureId);
        } catch (Exception e) {
            logger.error(JSON.toJSONString(e));
        }
        return toAjax(1);
    }

    /**
     * 修改测厚记录
     */
    @Log(title = "测厚记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TMeasureRecord tMeasureRecord) {
        tMeasureRecordService.updateTMeasureRecord(tMeasureRecord);
        String measureId = tMeasureRecord.getMeasureId();
        try {
            updateMeasure(measureId);
        } catch (Exception e) {
            logger.error(JSON.toJSONString(e));
        }
        return toAjax(1);
    }

    /**
     * 删除测厚记录
     */
    @Log(title = "测厚记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        int res = tMeasureRecordService.deleteTMeasureRecordByIds(ids);
        try {
            for (Long id : ids
            ) {
                TMeasureRecord tMeasureRecord = tMeasureRecordService.selectTMeasureRecordById(id);
                String measureId = tMeasureRecord.getMeasureId();
                updateMeasure(measureId);
            }
        } catch (Exception e) {
            logger.error(JSON.toJSONString(e));
        }
        return toAjax(res);
    }

    public void updateMeasure(String id) {
        TMeasureThickness thickness = tMeasureThicknessService.selectTMeasureThicknessById(Long.parseLong(id));
        TMeasureRecord t = new TMeasureRecord();
        t.setMeasureId(id);
        List<TMeasureRecord> list = tMeasureRecordService.selectTMeasureRecordList(t);
        logger.info("查询数量" + list.size());
        if (list != null) {
            if (list.size() > 1) {
                logger.info(JSON.toJSONString(list));
                //短期速率
                TMeasureRecord r1 = list.get(0);
                TMeasureRecord r2 = list.get(1);
                BigDecimal i = new BigDecimal(r2.getMeasureValue()).setScale(4, BigDecimal.ROUND_HALF_DOWN).subtract(new BigDecimal(r1.getMeasureValue()).setScale(4, BigDecimal.ROUND_HALF_DOWN));
                int day = formatDate(r1.getMeasureDate(), r2.getMeasureDate());
                if (day == 0) {
                    day = day + 1;
                }
                logger.info(i + "-i--day-" + day);
                BigDecimal di = new BigDecimal(day).divide(new BigDecimal(365), 4, BigDecimal.ROUND_HALF_DOWN);
                logger.info(di + "--di--");
                BigDecimal st = i.divide(di, 3, BigDecimal.ROUND_HALF_DOWN);
                logger.info(st + "--st--");
                if (st.compareTo(new BigDecimal("0")) <= 0) { //速率不可小于0
                    st = new BigDecimal("0.01");
                }

                thickness.setStCorrosion(String.valueOf(st));
                //长期速率
                TMeasureRecord r3 = list.get(list.size() - 1);
                BigDecimal i1 = new BigDecimal(r3.getMeasureValue()).setScale(4, BigDecimal.ROUND_HALF_DOWN).subtract(new BigDecimal(r1.getMeasureValue()).setScale(4, BigDecimal.ROUND_HALF_DOWN));
                int day1 = formatDate(r1.getMeasureDate(), r3.getMeasureDate());
                logger.info(i1 + "--i1--" + day1);
                BigDecimal di2 = new BigDecimal(day1).divide(new BigDecimal(365), 4, BigDecimal.ROUND_HALF_DOWN);
                BigDecimal lt = i1.divide(di2, 3, BigDecimal.ROUND_HALF_DOWN);
                logger.info(lt + "--lt--");
                if (lt.compareTo(new BigDecimal("0")) <= 0) { //速率不可小于0
                    lt = new BigDecimal("0.01");
                }
                thickness.setLtCorrosion(String.valueOf(lt));
                //预估寿命
                if (thickness.getThicknessMin() != null) {
                    BigDecimal e;
                    if (lt.compareTo(st) > 0) {
                        e = lt;
                    } else {
                        e = st;
                    }
                    if (e.compareTo(new BigDecimal("0")) == 0) {
                        e = new BigDecimal("1");
                    }
                    BigDecimal cc = new BigDecimal(r1.getMeasureValue()).subtract(new BigDecimal(thickness.getThicknessMin().replaceAll("-", "")));
                    logger.info(cc + "----cc");
                    BigDecimal est = cc.divide(e, 2, BigDecimal.ROUND_HALF_DOWN);
                    thickness.setEstRemain(String.valueOf(est));
                }
            }
            //计算下次侧厚日期
            try {
                if (list.size() > 0 && StringUtils.isNotEmpty(thickness.getMeasureCycle())) {
                    int monthCycle = Integer.parseInt(thickness.getMeasureCycle());
                    int dayCycel = monthCycle * 30;
                    TMeasureRecord r1 = list.get(0);
                    Calendar calendar = new GregorianCalendar();
                    calendar.setTime(r1.getMeasureDate());
                    calendar.add(calendar.DATE, dayCycel);
                    logger.info("计算下次侧厚日期", calendar.getTime());
                    thickness.setNextWarnDate(calendar.getTime());
                    thickness.setRecorder(r1.getRecorder());
                }
            } catch (Exception e) {
                logger.error("计算下次侧厚日期出错", JSON.toJSONString(e));
                e.printStackTrace();
            }
        }
        thickness.setIsSend(0);
        tMeasureThicknessService.updateTMeasureThickness(thickness);
    }

    private int formatDate(Date nowDate, Date sqlDate) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String newDate = df.format(nowDate);
        String sqlDate1 = df.format(sqlDate);
        try {
            nowDate = df.parse(newDate);
            sqlDate = df.parse(sqlDate1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Long time = nowDate.getTime();
        Long time2 = sqlDate.getTime();
        int day = (int) ((time - time2) / (24 * 3600 * 1000));
        return day;
    }

    /**
     * 批量导入
     */
    @Log(title = "定点测厚批量导入更新", businessType = BusinessType.INSERT)
    @PostMapping("/importForUpdate")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<Integer>();
        //异常
        List<Integer> abnormalRow = new ArrayList<Integer>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TMeasureRecord> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        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();
                TMeasureRecord entity = new TMeasureRecord();
                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) { //装置
                        entity.setPlantCode(cellValue);
                    } else if (j == 1) {//单元
                        entity.setUnitCode(cellValue);
                    } else if (j == 2) {//单位内编号
                        entity.setTagno(cellValue);
                    } else if (j == 3) {//侧厚部位
                        entity.setPosition(cellValue);
                    } else if (j == 4) {//检测编号
                        entity.setMeasureNo(cellValue);
                    } else if (j == 5) {//数值
                        entity.setMeasureValue(Double.parseDouble(cellValue));
                    } else if (j == 6) {//时间
                        entity.setMeasureDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));
                    } else if (j == 7) {//记录人
                        entity.setRecorder(cellValue);
                    }
                }
                entity.setCreaterCode(userId);
                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 (TMeasureRecord t : list) {
            failNum++;
            try {
                //保存测厚记录
                Long id = this.tMeasureThicknessMapper.selectByRecord(t);
                t.setMeasureId(id.toString());
                this.tMeasureRecordService.deleteTMeasureRecordByDate(t);
                this.tMeasureRecordService.insertTMeasureRecord(t);
                //判断波动过大
                TMeasureRecord param = new TMeasureRecord();
                param.setMeasureId(id + "");
                List<TMeasureRecord> recordlist = tMeasureRecordService.selectTMeasureRecordList(param);
                if (recordlist.size() > 1) {
                    logger.info("侧厚数据1:", recordlist.get(0).getMeasureValue());
                    logger.info("侧厚数据2:", recordlist.get(1).getMeasureValue());
                    if (recordlist.get(0).getMeasureValue() - recordlist.get(1).getMeasureValue() >= 0.1) {
                        //当本次测厚值比上次测厚值大于等于0.1mm 时，提醒工程师可能存在测量偏差，应进行复验。
                        abnormalRow.add(failNum + 1);
                    }
                }

                try {
                    logger.info("更新速率id:", id);

                    this.updateMeasure(id + "");
                } catch (Exception e) {
                    logger.error("更新速率错误e:" + e);
                    e.printStackTrace();
                }
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.error("e:" + e);
                e.printStackTrace();
                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));
        logger.info("abnormalRow:" + String.valueOf(abnormalRow));
        Map map = new HashMap();
        map.put("failRow" , failRow);
        map.put("abnormalRow" , abnormalRow);
        return AjaxResult.success(String.valueOf(successNumber), map);
    }
}
