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.TPssrContentModel;
import com.ruoyi.project.pssr.mapper.TPssrContentModelMapper;
import com.ruoyi.project.pssr.service.ITPssrContentModelService;
import com.ruoyi.project.pssr.service.ITPssrFileService;
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 javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 开车条件确认模板Controller
 *
 * @author ssy
 * @date 2024-09-18
 */
@RestController
@RequestMapping("/pssr/pssrModel")
public class TPssrContentModelController extends BaseController {
    @Autowired
    private ITPssrFileService tPssrFileService;
    @Resource
    private TPssrContentModelMapper tPssrContentModelMapper;
    @Autowired
    private ITPssrContentModelService tPssrContentModelService;

    /**
     * 查询开车条件确认模板列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:pssrModel:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrContentModel tPssrContentModel) {
        startPage();
        List<TPssrContentModel> list = tPssrContentModelService.selectTPssrContentModelList(tPssrContentModel);
        return getDataTable(list);
    }

    /**
     * 导出开车条件确认模板列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:pssrModel:export')")
    @Log(title = "开车条件确认模板", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrContentModel tPssrContentModel) {
        List<TPssrContentModel> list = tPssrContentModelService.selectTPssrContentModelList(tPssrContentModel);
        ExcelUtil<TPssrContentModel> util = new ExcelUtil<TPssrContentModel>(TPssrContentModel.class);
        return util.exportExcel(list, "pssrModel");
    }

    /**
     * 获取开车条件确认模板详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:pssrModel:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tPssrContentModelService.selectTPssrContentModelById(id));
    }

    /**
     * 新增开车条件确认模板
     */
    @PreAuthorize("@ss.hasPermi('pssr:pssrModel:add')")
    @Log(title = "开车条件确认模板", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrContentModel tPssrContentModel) {
        return toAjax(tPssrContentModelService.insertTPssrContentModel(tPssrContentModel));
    }

    /**
     * 修改开车条件确认模板
     */
    @PreAuthorize("@ss.hasPermi('pssr:pssrModel:edit')")
    @Log(title = "开车条件确认模板", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrContentModel tPssrContentModel) {
        return toAjax(tPssrContentModelService.updateTPssrContentModel(tPssrContentModel));
    }

    /**
     * 删除开车条件确认模板
     */
    @PreAuthorize("@ss.hasPermi('pssr:pssrModel:remove')")
    @Log(title = "开车条件确认模板", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tPssrContentModelService.deleteTPssrContentModelByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('pssr:pssrModel: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<TPssrContentModel> 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();
                TPssrContentModel entity = new TPssrContentModel();
                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.setDeptUnit(cellValue);
                    } else if (j == 1) {
                        entity.setSerialNumber(cellValue);
                    } else if (j == 2) {
                        entity.setItem(cellValue);
                    } else if (j == 3) {
                        entity.setForShort(cellValue);
                    } else if (j == 4) {
                        entity.setContent(cellValue);
                    }
                }
                entity.setStatus(1L);
                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 (TPssrContentModel 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);
    }
}
