package com.ruoyi.project.reliability.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
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.reliability.domain.TSafetyvavle;
import com.ruoyi.project.reliability.service.ITSafetyvavleService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.domain.TUploadhistory;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import com.ruoyi.project.system.service.ITUploadhistoryService;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 安全阀清单Controller
 *
 * @author ruoyi
 * @date 2020-12-01
 */
@RestController
@RequestMapping("/reliability/safetyvavle")
public class TSafetyvavleController extends BaseController
{
    @Autowired
    private ITSafetyvavleService tSafetyvavleService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ITUploadhistoryService itUploadhistoryService;

    /**
     * 查询安全阀清单列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:safetyvavle:list')")
    @GetMapping("/list")
    public TableDataInfo list(TSafetyvavle tSafetyvavle)
    {
        startPage();
        List<TSafetyvavle> list = tSafetyvavleService.selectTSafetyvavleList(tSafetyvavle);
        return getDataTable(list);
    }

    /**
     * 导出安全阀清单列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:safetyvavle:export')")
    @Log(title = "安全阀清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSafetyvavle tSafetyvavle)
    {
        List<TSafetyvavle> list = tSafetyvavleService.selectTSafetyvavleList(tSafetyvavle);
        ExcelUtil<TSafetyvavle> util = new ExcelUtil<TSafetyvavle>(TSafetyvavle.class);
        return util.exportExcel(list, "safetyvavle");
    }

    /**
     * 获取安全阀清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('reliability:safetyvavle:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tSafetyvavleService.selectTSafetyvavleById(id));
    }

    /**
     * 新增安全阀清单
     */
    @PreAuthorize("@ss.hasPermi('reliability:safetyvavle:add')")
    @Log(title = "安全阀清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSafetyvavle tSafetyvavle)
    {
        tSafetyvavle.setCreaterCode(getUserId().toString());
        return toAjax(tSafetyvavleService.insertTSafetyvavle(tSafetyvavle));
    }

    /**
     * 修改安全阀清单
     */
    @PreAuthorize("@ss.hasPermi('reliability:safetyvavle:edit')")
    @Log(title = "安全阀清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSafetyvavle tSafetyvavle)
    {
        tSafetyvavle.setUpdaterCode(getUserId().toString());
        tSafetyvavle.setUpdatedate(new Date());
        return toAjax(tSafetyvavleService.updateTSafetyvavle(tSafetyvavle));
    }

    /**
     * 删除安全阀清单
     */
    @PreAuthorize("@ss.hasPermi('reliability:safetyvavle:remove')")
    @Log(title = "安全阀清单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tSafetyvavleService.deleteTSafetyvavleByIds(ids));
    }

    /**
     * 上传五合一安全阀清单
     */
    @PreAuthorize("@ss.hasPermi('reliability:safetyvavle:edit')")
    @Log(title = "安全阀清单", businessType = BusinessType.UPDATE)
    @GetMapping("upload/{ids}")
    public AjaxResult upload(@PathVariable Long[] ids)
    {
        //上传数据历史
        TUploadhistory uploadhistory = new TUploadhistory();
        for (Long i : ids) {
            TSafetyvavle safetyvavle = tSafetyvavleService.selectTSafetyvavleById(i);
            String content = "单元：" + safetyvavle.getUnit() + ",区域：" + safetyvavle.getSubarea() + ",位号：" + safetyvavle.getTagno() + ",现场位置描述：" + safetyvavle.getPlacedesc()
                    + ",安全阀计算书：" + safetyvavle.getPsvcalcreport() + ",数据表文件名：" + safetyvavle.getDatasheetdoc() + ",数据表提供方：" + safetyvavle.getDatasupplier() + ",设计工况：" + safetyvavle.getDeasignscenarios()
                    + ",需要排量：" + safetyvavle.getRelief() + ",排放地点：" + safetyvavle.getReleaseplace() + ",保护设备：" + safetyvavle.getService() + ",型号：" + safetyvavle.getType();
            uploadhistory.setContent(content);
            uploadhistory.setUploadCode(getUserId().toString());
            uploadhistory.setUploadDate(new Date());
            uploadhistory.setUploadType("safetyvalve");
            itUploadhistoryService.insertTUploadhistory(uploadhistory);
        }
        return toAjax(tSafetyvavleService.uploadTSafetyvavleByIds(ids));
    }

    /**
     * 批量导入安全阀清单
     */
    @PreAuthorize("@ss.hasPermi('reliability:safetyvavle: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<TSafetyvavle> list = new ArrayList<TSafetyvavle>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> unit = iSysDictTypeService.selectDictDataByType("UNIT");
        List<SysDictData> safetyvavle = iSysDictTypeService.selectDictDataByType("SAFETYVAVLE_ITEM");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TSafetyvavle entity = new TSafetyvavle();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    //  cell.setCellType(CellType.STRING);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    logger.info("cellValue:" + cellValue);
                    if (j == 0) {
                        for (SysDictData p : plant) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPlantCode(p.getDictValue());//装置名称
                            }
                        }
                    } else if (j == 1) {
                        for (SysDictData p : unit) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setUnit(p.getDictValue());//单元
                            }
                        }
                    } else if (j == 2) {
                        entity.setSubarea(cellValue);//区域
                    } else if (j == 3) {
                        entity.setTagno(cellValue);//位号
                    } else if (j == 4) {
                        entity.setPlacedesc(cellValue);//现场位置描述
                    } else if (j == 5) {
                        entity.setPsvcalcreport(cellValue);//安全阀计算书
                    } else if (j == 6) {
                        entity.setDatasheetdoc(cellValue);//数据表文件名
                    } else if (j == 7) {
                        entity.setDatasupplier(cellValue);//数据表提供方
                    } else if (j == 8) {
                        entity.setDeasignscenarios(cellValue);//设计工况
                    } else if (j == 9) {
                        entity.setRelief(cellValue);//需要排量
                    } else if (j == 10) {
                        entity.setReleaseplace(cellValue);//排放地点
                    } else if (j == 11) {
                        entity.setService(cellValue);//保护设备
                    } else if (j == 12) {
                        entity.setType(cellValue);//型号
                    } else if (j == 13) {
                        entity.setManufacture(cellValue);//制造商
                    } else if (j == 14) {
                        entity.setSettingpres(cellValue);//起跳整定压力（Mpag）
                    } else if (j == 15) {
                        entity.setSettingtestpres(cellValue);//密封压力（Mpag）
                    } else if (j == 16) {
                        entity.setMaxbackpres(cellValue);//最大背压（Mpag）
                    } else if (j == 17) {
                        entity.setWorkingpres(cellValue);//工作压力（Mpag）
                    } else if (j == 18) {
                        entity.setWorkingtemp(cellValue);//工作温度（deg C）
                    } else if (j == 19) {
                        entity.setSizeinlet(cellValue);//入口尺寸
                    } else if (j == 20) {
                        entity.setSizeoutlet(cellValue);//出口尺寸
                    } else if (j == 21) {
                        entity.setMaterials(cellValue);//材料
                    } else if (j == 22) {
                        entity.setFluidname(cellValue);//介质名称
                    } else if (j == 23) {
                        entity.setFluidstate(cellValue);//介质状态
                    } else if (j == 24) {
                        if (cellValue.length() > 3) {
                            entity.setInspectingdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//检验日期
                        }
                    } else if (j == 25) {
                        if (cellValue.length() > 3) {
                            entity.setNextinspectdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//下次检验日期
                        }
                    } else if (j == 26) {
                        entity.setPid(cellValue);//PID
                    } else if (j == 27) {
                        if (cellValue.length() > 3) {
                            entity.setUsingdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//投用日期
                        }
                    } else if (j == 28) {
                        entity.setVendordoc(cellValue);//供货商资料
                    } else if (j == 29) {
                        for (SysDictData p : safetyvavle) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setItem(Long.parseLong(p.getDictValue()));//分类
                            }
                        }
                    } else if (j == 30) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 31) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    }
                }
                entity.setCreaterCode(userId.toString());
                logger.info("entity:" + entity);
                list.add(entity);
            }catch (Exception e){
                failNumber++;
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TSafetyvavle t : list
        ) {
            failNum++;
            try {
                tSafetyvavleService.insertTSafetyvavle(t);
                successNumber++;
            }catch (Exception e){
                failNumber++;
                failRow.add(failNum+1);
            }
        }
        logger.info("list:" + JSON.toJSONString(list));
        logger.info("successNumber:" +String.valueOf(successNumber));
        logger.info("failNumber:" +String.valueOf(failNumber));
        logger.info("failRow:" +String.valueOf(failRow));
        return AjaxResult.success(String.valueOf(successNumber), failRow);
    }

    @GetMapping("/allSafetyvavle")
    public AjaxResult allSafetyvavle() {
        return AjaxResult.success(tSafetyvavleService.selectTSafetyvavleList(new TSafetyvavle()));
    }
}
