package com.ruoyi.project.process.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.process.domain.TLockValve;
import com.ruoyi.project.process.service.ITLockValveService;
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.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 阀门锁开锁关状态记录Controller
 *
 * @author ruoyi
 * @date 2024-04-03
 */
@RestController
@RequestMapping("/process/valve")
public class TLockValveController extends BaseController {
    @Autowired
    private ITLockValveService tLockValveService;

    /**
     * 查询阀门锁开锁关状态记录列表
     */
    @PreAuthorize("@ss.hasPermi('process:valve:list')")
    @GetMapping("/list")
    public TableDataInfo list(TLockValve tLockValve) {
        startPage();
        List<TLockValve> list = tLockValveService.selectTLockValveList(tLockValve);
        return getDataTable(list);
    }

    /**
     * 导出阀门锁开锁关状态记录列表
     */
    @PreAuthorize("@ss.hasPermi('process:valve:export')")
    @Log(title = "阀门锁开锁关状态记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TLockValve tLockValve) {
        List<TLockValve> list = tLockValveService.selectTLockValveList(tLockValve);
        ExcelUtil<TLockValve> util = new ExcelUtil<TLockValve>(TLockValve.class);
        util.exportExcel(response, list, "阀门锁开锁关状态记录数据");
    }

    /**
     * 获取阀门锁开锁关状态记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('process:valve:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tLockValveService.selectTLockValveById(id));
    }

    /**
     * 新增阀门锁开锁关状态记录
     */
    @PreAuthorize("@ss.hasPermi('process:valve:add')")
    @Log(title = "阀门锁开锁关状态记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TLockValve tLockValve) {
        return toAjax(tLockValveService.insertTLockValve(tLockValve));
    }

    /**
     * 修改阀门锁开锁关状态记录
     */
    @PreAuthorize("@ss.hasPermi('process:valve:edit')")
    @Log(title = "阀门锁开锁关状态记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TLockValve tLockValve) {
        return toAjax(tLockValveService.updateTLockValve(tLockValve));
    }

    /**
     * 删除阀门锁开锁关状态记录
     */
    @PreAuthorize("@ss.hasPermi('process:valve:remove')")
    @Log(title = "阀门锁开锁关状态记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tLockValveService.deleteTLockValveByIds(ids));
    }


    @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<>();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TLockValve> 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();
                TLockValve entity = new TLockValve();
                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.setUnit(cellValue);
                    } else if (j == 1) {
                        entity.setVtNo(cellValue);
                    } else if (j == 2) {
                        entity.setPidNo(cellValue);
                    } else if (j == 3) {
                        entity.setLocationDes(cellValue);
                    } else if (j == 4) {
                        entity.setMedium(cellValue);
                    } else if (j == 5) {
                        entity.setValveType(cellValue);
                    } else if (j == 6) {
                        entity.setValveSize(cellValue);
                    } else if (j == 7) {
                        entity.setIdentifier(cellValue);
                    } else if (j == 8) {
                        entity.setValvePosition(cellValue);
                    } else if (j == 9) {
                        entity.setFirmlySecured(cellValue);
                    } else if (j == 10) {
                        entity.setResponsibility(cellValue);
                    } else if (j == 11) {
                        entity.setCheckedBy(cellValue);
                    } else if (j == 12) {
                        entity.setCheckBeforeSu(cellValue);
                    } else if (j == 13) {
                        entity.setPidStatus(cellValue);
                    } else if (j == 14) {
                        entity.setRiskLevel(cellValue);
                    } else if (j == 15) {
                        entity.setSheReview(cellValue);
                    } else if (j == 16) {
                        entity.setCheckDate(DateUtils.parseDate(cellValue));
                    } else if (j == 17) {
                        entity.setRemarks(cellValue);
                    }
                }
                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 (TLockValve 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);
    }
}
