package com.ruoyi.project.sems.controller;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.sems.domain.TReportThird;
import com.ruoyi.project.sems.service.ITReportThirdService;
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.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.sems.domain.TReportYlrq;
import com.ruoyi.project.sems.service.ITReportYlrqService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 压力容器年检报告Controller
 *
 * @author ruoyi
 * @date 2021-09-02
 */
@RestController
@RequestMapping("/sems/reportYlrq")
public class TReportYlrqController extends BaseController {

    @Autowired
    private ITReportYlrqService tReportYlrqService;

    @Autowired
    private ITReportThirdService itReportYlrqThirdService;

    /**
     * 同步数据
     */
    @GetMapping("/sync")
    public AjaxResult syncData() {
        this.tReportYlrqService.deleteTReportYlrqByIds();
        this.tReportYlrqService.insertByTSpecdevYlrq();
        this.tReportYlrqService.updateByTSpecdevYlrq();
        return AjaxResult.success();
    }

    /**
     * 查询压力容器年检报告列表
     */
    @PreAuthorize("@ss.hasPermi('sems:reportYlrq:list')")
    @GetMapping("/list")
    public TableDataInfo list(TReportYlrq tReportYlrq) {
        startPage();
        List<TReportYlrq> list = tReportYlrqService.selectTReportYlrqList(tReportYlrq);
        return getDataTable(list);
    }

    /**
     * 导出压力容器年检报告列表
     */
    @PreAuthorize("@ss.hasPermi('sems:reportYlrq:export')")
    @Log(title = "压力容器年检报告", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TReportYlrq tReportYlrq) {
        List<TReportYlrq> list = tReportYlrqService.selectTReportYlrqList(tReportYlrq);
        ExcelUtil<TReportYlrq> util = new ExcelUtil<TReportYlrq>(TReportYlrq.class);
        return util.exportExcel(list, "reportYlrq");
    }

    /**
     * 第三方数据导入
     *
     * @param file 导入文件
     * @return
     * @throws IOException
     */
    @PostMapping("/importForThird")
    public AjaxResult importForThird(@RequestParam("file") MultipartFile file, @RequestParam("plantCode") String plantCode,
                                     @RequestParam("year") String year) throws IOException, ParseException {
        //获取操作人员ID
        Long userId = getUserId();
        //文件保存至服务器下
        String fileName = file.getOriginalFilename();
        //文件存放路径
        String filePath = RuoYiConfig.getProfile() + "/sems/reportYlrqThird";
        String upload = FileUploadUtils.upload(filePath, file);
        // 文件路径保存至数据库
        TReportThird tReportYlrqThird = new TReportThird();
        tReportYlrqThird.setPlantCode(plantCode);
        tReportYlrqThird.setYear(year);
        tReportYlrqThird.setFileName(fileName);
        tReportYlrqThird.setFilePath(upload);
        tReportYlrqThird.setCreateBy(userId + "");
        tReportYlrqThird.setCreateTime(new Date());
        tReportYlrqThird.setType("1");
        int i = this.itReportYlrqThirdService.insertTReportThird(tReportYlrqThird);
        return AjaxResult.success(i);
    }

    /**
     * 批量导入
     */
    @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>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TReportYlrq> list = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 2; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TReportYlrq entity = new TReportYlrq();
                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.setUseno(cellValue);
                    } else if (j == 1) {
                        //注册编号
                        entity.setRegno(cellValue);
                    } else if (j == 2) {
                        //位号
                        entity.setDevno(cellValue);
                    } else if (j == 3) {
                        //容器管理1
                        entity.setPj1(cellValue);
                    } else if (j == 4) {
                        //容器管理2
                        entity.setPj2(cellValue);
                    } else if (j == 5) {
                        //容器管理3
                        entity.setPj3(cellValue);
                    } else if (j == 6) {
                        //容器管理4
                        entity.setPj4(cellValue);
                    } else if (j == 7) {
                        //容器管理5
                        entity.setPj5(cellValue);
                    } else if (j == 8) {
                        //容器管理6
                        entity.setPj6(cellValue);
                    } else if (j == 9) {
                        //容器管理7
                        entity.setPj7(cellValue);
                    } else if (j == 10) {
                        //本体及运行情况8
                        entity.setPj8(cellValue);
                    } else if (j == 11) {
                        //本体及运行情况9
                        entity.setPj9(cellValue);
                    } else if (j == 12) {
                        //本体及运行情况10
                        entity.setPj10(cellValue);
                    } else if (j == 13) {
                        //本体及运行情况11
                        entity.setPj11(cellValue);
                    } else if (j == 14) {
                        //本体及运行情况12
                        entity.setPj12(cellValue);
                    } else if (j == 15) {
                        //本体及运行情况13
                        entity.setPj13(cellValue);
                    } else if (j == 16) {
                        //本体及运行情况14
                        entity.setPj14(cellValue);
                    } else if (j == 17) {
                        //本体及运行情况15
                        entity.setPj15(cellValue);
                    } else if (j == 18) {
                        //本体及运行情况16
                        entity.setPj16(cellValue);
                    } else if (j == 19) {
                        //本体及运行情况17
                        entity.setPj17(cellValue);
                    } else if (j == 20) {
                        //本体及运行情况18
                        entity.setPj18(cellValue);
                    } else if (j == 21) {
                        //本体及运行情况19
                        entity.setPj19(cellValue);
                    } else if (j == 22) {
                        //本体及运行情况20
                        entity.setPj20(cellValue);
                    } else if (j == 23) {
                        //本体及运行情况21
                        entity.setPj21(cellValue);
                    } else if (j == 24) {
                        //本体及运行情况22
                        entity.setPj22(cellValue);
                    } else if (j == 25) {
                        //本体及运行情况23
                        entity.setPj23(cellValue);
                    } else if (j == 26) {
                        //本体及运行情况24
                        entity.setPj24(cellValue);
                    } else if (j == 27) {
                        //安全附件及设施25
                        entity.setPj25(cellValue);
                    } else if (j == 28) {
                        //安全附件及设施26
                        entity.setPj26(cellValue);
                    } else if (j == 29) {
                        //安全附件及设施27
                        entity.setPj27(cellValue);
                    } else if (j == 30) {
                        //安全附件及设施28
                        entity.setPj28(cellValue);
                    } else if (j == 31) {
                        //安全附件及设施29
                        entity.setPj29(cellValue);
                    } else if (j == 32) {
                        //安全附件及设施30
                        entity.setPj30(cellValue);
                    } else if (j == 33) {
                        //安全附件及设施31
                        entity.setPj31(cellValue);
                    } else if (j == 34) {
                        //其他32
                        entity.setPj32(cellValue);
                    } else if (j == 35) {
                        //备注
                        entity.setRemarks(cellValue);
                    } else if (j == 36) {
                        //检查日期
                        entity.setCheckDate(cellValue != null ? sdf.parse(cellValue) : null);
                    } else if (j == 37) {
                        //下次年度检查日期
                        entity.setNextCheckDate(cellValue != null ? sdf.parse(cellValue) : null);
                    } else if (j == 38) {
                        //问题及处理
                        entity.setProblem(cellValue);
                    } else if (j == 39) {
                        //检查结论
                        entity.setCon(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 (TReportYlrq t : list
        ) {
            failNum++;
            try {
                //根据使用证、注册编号、位号，进行数据更新
                this.tReportYlrqService.updateForImport(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                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);
    }

    /**
     * 获取压力容器年检报告详细信息
     */
    @PreAuthorize("@ss.hasPermi('sems:reportYlrq:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tReportYlrqService.selectTReportYlrqById(id));
    }

    /**
     * 新增压力容器年检报告
     */
    @PreAuthorize("@ss.hasPermi('sems:reportYlrq:add')")
    @Log(title = "压力容器年检报告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TReportYlrq tReportYlrq) {
        return toAjax(tReportYlrqService.insertTReportYlrq(tReportYlrq));
    }

    /**
     * 修改压力容器年检报告
     */
    @PreAuthorize("@ss.hasPermi('sems:reportYlrq:edit')")
    @Log(title = "压力容器年检报告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TReportYlrq tReportYlrq) {
        return toAjax(tReportYlrqService.updateTReportYlrq(tReportYlrq));
    }

    /**
     * 删除压力容器年检报告
     */
    @PreAuthorize("@ss.hasPermi('sems:reportYlrq:remove')")
    @Log(title = "压力容器年检报告", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tReportYlrqService.deleteTReportYlrqByIds(ids));
    }
}
