package com.ruoyi.project.pssr.controller;

import com.alibaba.fastjson.JSON;
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.pssr.domain.TPssrRegion;
import com.ruoyi.project.pssr.service.ITPssrFileService;
import com.ruoyi.project.pssr.service.ITPssrRegionService;
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.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * pssr区域管理Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/region")
public class TPssrRegionController extends BaseController {
    @Autowired
    private ITPssrFileService tPssrFileService;
    @Autowired
    private ITPssrRegionService tPssrRegionService;

    /**
     * 查询pssr区域管理列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:region:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrRegion tPssrRegion) {
        startPage();
        List<TPssrRegion> list = tPssrRegionService.selectTPssrRegionList(tPssrRegion);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('pssr:region:list')")
    @GetMapping("/groupList")
    public AjaxResult groupList(TPssrRegion tPssrRegion) {
        List<TPssrRegion> list = tPssrRegionService.selectTPssrRegionList(tPssrRegion);
        //根据区域分组
        Map<String, List<TPssrRegion>> collect = list.stream().collect(Collectors.groupingBy(TPssrRegion::getRegion));
        return AjaxResult.success(collect);
    }

    /**
     * 导出pssr区域管理列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:region:export')")
    @Log(title = "pssr区域管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrRegion tPssrRegion) {
        List<TPssrRegion> list = tPssrRegionService.selectTPssrRegionList(tPssrRegion);
        ExcelUtil<TPssrRegion> util = new ExcelUtil<TPssrRegion>(TPssrRegion.class);
        return util.exportExcel(list, "region");
    }

    /**
     * 获取pssr区域管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:region:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tPssrRegionService.selectTPssrRegionById(id));
    }

    /**
     * 新增pssr区域管理
     */
    @PreAuthorize("@ss.hasPermi('pssr:region:add')")
    @Log(title = "pssr区域管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrRegion tPssrRegion) {
        return toAjax(tPssrRegionService.insertTPssrRegion(tPssrRegion));
    }

    /**
     * 修改pssr区域管理
     */
    @PreAuthorize("@ss.hasPermi('pssr:region:edit')")
    @Log(title = "pssr区域管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrRegion tPssrRegion) {
        return toAjax(tPssrRegionService.updateTPssrRegion(tPssrRegion));
    }

    /**
     * 删除pssr区域管理
     */
    @PreAuthorize("@ss.hasPermi('pssr:region:remove')")
    @Log(title = "pssr区域管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrRegionService.deleteTPssrRegionByIds(ids));
    }


    @PreAuthorize("@ss.hasPermi('pssr:region:add')")
    @Log(title = "分离培训模版", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    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<TPssrRegion> list = new ArrayList<>();
        int rowNum = sheet.getLastRowNum();
        int failNumber = 0;
        String topic = "";
        boolean flag = false;
        for (int i = 1; i <= rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                if (row == null) {
                    sheet.removeRow(row);
                    rowNum++;
                    continue;
                }
                int cellNum = row.getLastCellNum();
                TPssrRegion entity = new TPssrRegion();
                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.setPlant(cellValue);
                    } else if (j == 1) {
                        entity.setRegion(cellValue);
                    } else if (j == 2) {
                        entity.setUnit(cellValue);
                    } else if (j == 3) {
                        entity.setRemarks(cellValue);
                    }
                }
                entity.setCreaterCode(userId.toString());
                entity.setCreatedate(new Date());
                logger.info("entity:" + entity);
                list.add(entity);
            } catch (Exception e) {
                failNumber++;
                failRow.add(i + 1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TPssrRegion t : list) {
            failNum++;
            try {
                add(t);
                successNumber++;
            } catch (Exception e) {
                e.printStackTrace();
                failNumber++;
                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);
    }
}
