package com.ruoyi.project.pssr.controller;

import java.io.IOException;
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.project.pssr.domain.TPssrRegion;
import org.apache.commons.collections4.CollectionUtils;
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.pssr.domain.TPssrFrameModel;
import com.ruoyi.project.pssr.service.ITPssrFrameModelService;
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 ssy
 * @date 2024-12-18
 */
@RestController
@RequestMapping("/pssr/frameModel")
public class TPssrFrameModelController extends BaseController
{
    @Autowired
    private ITPssrFrameModelService tPssrFrameModelService;

    /**
     * 查询支（吊）架列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:frameModel:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPssrFrameModel tPssrFrameModel)
    {
        startPage();
        List<TPssrFrameModel> list = tPssrFrameModelService.selectTPssrFrameModelList(tPssrFrameModel);
        return getDataTable(list);
    }

    /**
     * 导出支（吊）架列表
     */
    @PreAuthorize("@ss.hasPermi('pssr:frameModel:export')")
    @Log(title = "支（吊）架", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPssrFrameModel tPssrFrameModel)
    {
        List<TPssrFrameModel> list = tPssrFrameModelService.selectTPssrFrameModelList(tPssrFrameModel);
        ExcelUtil<TPssrFrameModel> util = new ExcelUtil<TPssrFrameModel>(TPssrFrameModel.class);
        return util.exportExcel(list, "frameModel");
    }

    /**
     * 获取支（吊）架详细信息
     */
    @PreAuthorize("@ss.hasPermi('pssr:frameModel:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tPssrFrameModelService.selectTPssrFrameModelById(id));
    }

    /**
     * 新增支（吊）架
     */
    @PreAuthorize("@ss.hasPermi('pssr:frameModel:add')")
    @Log(title = "支（吊）架", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPssrFrameModel tPssrFrameModel)
    {
        return toAjax(tPssrFrameModelService.insertTPssrFrameModel(tPssrFrameModel));
    }


    private int insertOrUpdate(TPssrFrameModel tPssrFrameModel) {
        TPssrFrameModel model = new TPssrFrameModel();
        model.setRegion(tPssrFrameModel.getRegion());
        model.setBracketNumber(tPssrFrameModel.getBracketNumber());
        List<TPssrFrameModel> tPssrFrameModels = tPssrFrameModelService.selectTPssrFrameModelList(model);
        if (CollectionUtils.isEmpty(tPssrFrameModels)) {
            return tPssrFrameModelService.insertTPssrFrameModel(tPssrFrameModel);
        } else {
            tPssrFrameModel.setId(tPssrFrameModels.get(0).getId());
            return tPssrFrameModelService.updateTPssrFrameModel(tPssrFrameModel);
        }
    }

    /**
     * 修改支（吊）架
     */
    @PreAuthorize("@ss.hasPermi('pssr:frameModel:edit')")
    @Log(title = "支（吊）架", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPssrFrameModel tPssrFrameModel)
    {
        return toAjax(tPssrFrameModelService.updateTPssrFrameModel(tPssrFrameModel));
    }

    /**
     * 删除支（吊）架
     */
    @PreAuthorize("@ss.hasPermi('pssr:frameModel:remove')")
    @Log(title = "支（吊）架", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tPssrFrameModelService.deleteTPssrFrameModelByIds(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<TPssrFrameModel> list = new ArrayList<>();
        int rowNum = sheet.getLastRowNum();
        int failNumber = 0;
        String topic = "";
        boolean flag = false;
        for (int i = 2; i <= rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                if (row == null) {
                    sheet.removeRow(row);
                    rowNum++;
                    continue;
                }
                int cellNum = row.getLastCellNum();
                TPssrFrameModel entity = new TPssrFrameModel();
                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.setRegion(cellValue);
                    } else if (j == 1) {
                        entity.setBracketNumber(cellValue);
                    } else if (j == 2) {
                        entity.setPipelineNumber(cellValue);
                    } else if (j == 3) {
                        entity.setDevNo(cellValue);
                    } else if (j == 4) {
                        entity.setUnit(cellValue);
                    } else if (j == 5) {
                        entity.setSupportType(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 (TPssrFrameModel 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);
    }
}
