package com.cpms.project.process.controller;

import java.io.IOException;
import java.util.List;
import java.util.ArrayList;
import com.alibaba.fastjson2.JSON;
import com.cpms.common.utils.file.ExcelUtils;
import com.cpms.common.utils.DateUtils;
import javax.servlet.http.HttpServletResponse;
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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.cpms.common.annotation.Log;
import com.cpms.common.core.controller.BaseController;
import com.cpms.common.core.domain.AjaxResult;
import com.cpms.common.enums.BusinessType;
import com.cpms.project.process.domain.TClassdOverview;
import com.cpms.project.process.service.ITClassdOverviewService;
import com.cpms.common.utils.poi.ExcelUtil;
import com.cpms.common.core.page.TableDataInfo;

/**
 * Class D overview listController
 * 
 * @author admin
 * @date 2024-04-16
 */
@RestController
@RequestMapping("/process/classd")
public class TClassdOverviewController extends BaseController
{
    @Autowired
    private ITClassdOverviewService tClassdOverviewService;

    /**
     * 查询Class D overview list列表
     */
    @PreAuthorize("@ss.hasPermi('process:classd:list')")
    @GetMapping("/list")
    public TableDataInfo list(TClassdOverview tClassdOverview)
    {
        startPage();
        List<TClassdOverview> list = tClassdOverviewService.selectTClassdOverviewList(tClassdOverview);
        return getDataTable(list);
    }

    /**
     * 导出Class D overview list列表
     */
    @PreAuthorize("@ss.hasPermi('process:classd:export')")
    @Log(title = "Class D overview list", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TClassdOverview tClassdOverview)
    {
        List<TClassdOverview> list = tClassdOverviewService.selectTClassdOverviewList(tClassdOverview);
        ExcelUtil<TClassdOverview> util = new ExcelUtil<TClassdOverview>(TClassdOverview.class);
        util.exportExcel(response, list, "Class D overview list数据");
    }

    /**
     * 获取Class D overview list详细信息
     */
    @PreAuthorize("@ss.hasPermi('process:classd:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tClassdOverviewService.selectTClassdOverviewById(id));
    }

    /**
     * 新增Class D overview list
     */
    @PreAuthorize("@ss.hasPermi('process:classd:add')")
    @Log(title = "Class D overview list", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TClassdOverview tClassdOverview)
    {
        return toAjax(tClassdOverviewService.insertTClassdOverview(tClassdOverview));
    }

    /**
     * 修改Class D overview list
     */
    @PreAuthorize("@ss.hasPermi('process:classd:edit')")
    @Log(title = "Class D overview list", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TClassdOverview tClassdOverview)
    {
        return toAjax(tClassdOverviewService.updateTClassdOverview(tClassdOverview));
    }

    /**
     * 删除Class D overview list
     */
    @PreAuthorize("@ss.hasPermi('process:classd:remove')")
    @Log(title = "Class D overview list", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tClassdOverviewService.deleteTClassdOverviewByIds(ids));
    }


    @Log(title = "Class D overview list批量导入", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException {
        //获取操作人员ID
        Long userId = getUserId();
        //报错行数统计
        List<Integer> failRow = new ArrayList<>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TClassdOverview> 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();
                TClassdOverview entity = new TClassdOverview();
                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);
                    switch (j) {
                        case 0:
                            entity.setDiscussionItem ( cellValue);
                            break;
                        case 1:
                            entity.setHazard ( cellValue);
                            break;
                        case 2:
                            entity.setCause ( cellValue);
                            break;
                        case 3:
                            entity.setConsequence ( cellValue);
                            break;
                        case 4:
                            entity.setP ( cellValue);
                            break;
                        case 5:
                            entity.setJustificationP ( cellValue);
                            break;
                        case 6:
                            entity.setS ( cellValue);
                            break;
                        case 7:
                            entity.setJustificationS ( cellValue);
                            break;
                        case 8:
                            entity.setRc ( cellValue);
                            break;
                        case 9:
                            entity.setCountermeasure ( cellValue);
                            break;
                        case 10:
                            entity.setRemarks ( cellValue);
                            break;
                    }
                }
                entity.setCreaterCode(String.valueOf(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 (TClassdOverview 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);
    }
}
