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.TReportYlgd;
import com.ruoyi.project.sems.service.ITReportYlgdService;
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/reportYlgd")
public class TReportYlgdController extends BaseController {

    @Autowired
    private ITReportYlgdService tReportYlgdService;

    @Autowired
    private ITReportThirdService itReportYlrqThirdService;


    /**
     * 同步数据
     */
    @GetMapping("/sync")
    public AjaxResult syncData() {
        this.tReportYlgdService.deleteTReportYlgdByIds();
        this.tReportYlgdService.insertByTSpecdevYlgd();
        this.tReportYlgdService.updateByTSpecdevYlgd();
        return AjaxResult.success();
    }

    /**
     * 第三方数据导入
     *
     * @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 tReportThird = new TReportThird();
        tReportThird.setPlantCode(plantCode);
        tReportThird.setYear(year);
        tReportThird.setFileName(fileName);
        tReportThird.setFilePath(upload);
        tReportThird.setCreateBy(userId + "");
        tReportThird.setCreateTime(new Date());
        tReportThird.setType("2");
        int i = this.itReportYlrqThirdService.insertTReportThird(tReportThird);
        return AjaxResult.success(i);
    }

    /**
     * 查询压力管道年检报告列表
     */
    @PreAuthorize("@ss.hasPermi('sems:reportYlgd:list')")
    @GetMapping("/list")
    public TableDataInfo list(TReportYlgd tReportYlgd) {
        startPage();
        List<TReportYlgd> list = tReportYlgdService.selectTReportYlgdList(tReportYlgd);
        return getDataTable(list);
    }

    /**
     * 导出压力管道年检报告列表
     */
    @PreAuthorize("@ss.hasPermi('sems:reportYlgd:export')")
    @Log(title = "压力管道年检报告", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TReportYlgd tReportYlgd) {
        List<TReportYlgd> list = tReportYlgdService.selectTReportYlgdList(tReportYlgd);
        ExcelUtil<TReportYlgd> util = new ExcelUtil<TReportYlgd>(TReportYlgd.class);
        return util.exportExcel(list, "reportYlgd");
    }

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

    /**
     * 新增压力管道年检报告
     */
    @PreAuthorize("@ss.hasPermi('sems:reportYlgd:add')")
    @Log(title = "压力管道年检报告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TReportYlgd tReportYlgd) {
        return toAjax(tReportYlgdService.insertTReportYlgd(tReportYlgd));
    }

    /**
     * 修改压力管道年检报告
     */
    @PreAuthorize("@ss.hasPermi('sems:reportYlgd:edit')")
    @Log(title = "压力管道年检报告", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TReportYlgd tReportYlgd) {
        return toAjax(tReportYlgdService.updateTReportYlgd(tReportYlgd));
    }

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

    /**
     * 批量导入
     */
    @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<TReportYlgd> 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();
                TReportYlgd entity = new TReportYlgd();
                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) {
                        //备注
                        entity.setRemarks(cellValue);
                    } else if (j == 21) {
                        //检查日期
                        entity.setCheckDate(cellValue != null ? sdf.parse(cellValue) : null);
                    } else if (j == 22) {
                        //下次年度检查日期
                        entity.setNextCheckDate(cellValue != null ? sdf.parse(cellValue) : null);
                    } else if (j == 23) {
                        //问题及处理
                        entity.setProblem(cellValue);
                    } else if (j == 24) {
                        //检查结论
                        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 (TReportYlgd t : list
        ) {
            failNum++;
            try {
                //根据使用证、注册编号、位号，进行数据更新
                this.tReportYlgdService.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);
    }
}
