package com.ruoyi.project.approval.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.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.project.approval.domain.TApproval;
import com.ruoyi.project.approval.service.ITApprovalService;
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 java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 批文清单Controller
 *
 * @author ruoyi
 * @date 2023-10-18
 */
@RestController
@RequestMapping("/ehs/approval")
public class TApprovalController extends BaseController {
    @Autowired
    private ITApprovalService tApprovalService;

    /**
     * 查询批文清单列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:approval:list')")
    @GetMapping("/list")
    public TableDataInfo list(TApproval tApproval) {
        startPage();
        List<TApproval> list = tApprovalService.selectTApprovalList(tApproval);
        return getDataTable(list);
    }

    /**
     * 导出批文清单列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:approval:export')")
    @Log(title = "批文清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TApproval tApproval) {
        List<TApproval> list = tApprovalService.selectTApprovalList(tApproval);
        ExcelUtil<TApproval> util = new ExcelUtil<TApproval>(TApproval.class);
        return util.exportExcel(list, "批文清单数据");
    }

    /**
     * 获取批文清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('ehs:approval:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tApprovalService.selectTApprovalById(id));
    }

    /**
     * 新增批文清单
     */
    @PreAuthorize("@ss.hasPermi('ehs:approval:add')")
    @Log(title = "批文清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TApproval tApproval) {
        return toAjax(tApprovalService.insertTApproval(tApproval));
    }

    /**
     * 修改批文清单
     */
    @PreAuthorize("@ss.hasPermi('ehs:approval:edit')")
    @Log(title = "批文清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TApproval tApproval) {
        return toAjax(tApprovalService.updateTApproval(tApproval));
    }

    /**
     * 删除批文清单
     */
    @PreAuthorize("@ss.hasPermi('ehs:approval:remove')")
    @Log(title = "批文清单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tApprovalService.deleteTApprovalByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('ehs:approval:add')")
    @Log(title = "批文清单批量导入", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult updateData(@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<TApproval> list = new ArrayList<>();
        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();
                TApproval entity = new TApproval();
                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.setApprovalAttibutes(cellValue);
                    } else if (j == 1) {
                        entity.setEffetivedate(DateUtils.parseDate(cellValue));//装置名称
                    } else if (j == 2) {
                        entity.setItemName(cellValue);//位号
                    } else if (j == 3) {
                        entity.setItemOverview(cellValue);//设备名称
                    } else if (j == 4) {
                        entity.setApprovalname(cellValue);//使用证号
                    } else if (j == 5) {
                        entity.setFileno(cellValue);//检验单位
                    } else if (j == 6) {
                        entity.setResponsauth(cellValue);
                    } else if (j == 7) {
                        entity.setContent(cellValue);//内部检验结论
                    } else if (j == 8) {
                        entity.setScope(cellValue);//内部检验报告编号
                    } else if (j == 9) {
                        entity.setRelatedlaw(cellValue);
                    } else if (j == 10) {
                        entity.setValidityBefore(DateUtils.parseDate(cellValue));
                    } else if (j == 11) {
                        entity.setValidityAfter(DateUtils.parseDate(cellValue));//外部检验结论
                    } else if (j == 12) {
                        if ("是".equals(cellValue)) {
                            entity.setIsPermanent("1");
                        } else if ("否".equals(cellValue)) {
                            entity.setIsPermanent("0");
                        }
                    } else if (j == 13) {
                        entity.setFollow(cellValue);
                    } else if (j == 14) {
                        entity.setOwner(cellValue);
                    } else if (j == 15) {
                        entity.setReviewer(cellValue);
                    } else if (j == 16) {
                        entity.setReviewdate(DateUtils.parseDate(cellValue));
                    } else if (j == 17) {
                        entity.setIsCompliance(cellValue);
                    } else if (j == 18) {
                        entity.setNextreviewdate(DateUtils.parseDate(cellValue));
                    } else if (j == 19) {
                        entity.setRemarks(cellValue);
                    }
                }
                logger.info("entity:" + JSON.toJSONString(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 (TApproval t : list) {
            failNum++;
            try {
                add(t);
                successNumber++;
            } catch (Exception e) {
                failNumber++;
                logger.info("e:" + e);
                failRow.add(failNum + 1);
                e.printStackTrace();
            }
        }
        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);
    }
}
