package com.ruoyi.project.cui.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.project.common.domain.DataEntity;
import com.ruoyi.project.cui.mapper.TPvesselMapper;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
import com.ruoyi.project.system.service.ISysDeptService;
import com.ruoyi.project.system.service.ISysDictTypeService;
import org.apache.poi.ss.usermodel.*;
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.cui.domain.TPvessel;
import com.ruoyi.project.cui.service.ITPvesselService;
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;

import javax.annotation.Resource;

/**
 * 容器清单Controller
 *
 * @author ruoyi
 * @date 2020-12-03
 */
@RestController
@RequestMapping("/cui/pvessel")
public class TPvesselController extends BaseController
{
    @Autowired
    private ITPvesselService tPvesselService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private TPvesselMapper tPvesselMapper;
    /**
     * 查询容器清单列表
     */
    @PreAuthorize("@ss.hasPermi('cui:pvessel:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPvessel tPvessel)
    {
        startPage();
        List<TPvessel> list = tPvesselService.selectTPvesselList(tPvessel);
        return getDataTable(list);
    }

    //风险统计
    @GetMapping("/riskData")
    public List<DataEntity> riskData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tPvesselMapper.selectRiskData(param);
        return list;
    }

    //统计
    @GetMapping("/statusData")
    public List<DataEntity> statusData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tPvesselMapper.selectStatusData(param);
        return list;
    }

    /**
     * 导出容器清单列表
     */
    @PreAuthorize("@ss.hasPermi('cui:pvessel:export')")
    @Log(title = "容器清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPvessel tPvessel)
    {
        List<TPvessel> list = tPvesselService.selectTPvesselList(tPvessel);
        ExcelUtil<TPvessel> util = new ExcelUtil<TPvessel>(TPvessel.class);
        return util.exportExcel(list, "pvessel");
    }

    /**
     * 获取容器清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('cui:pvessel:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tPvesselService.selectTPvesselById(id));
    }

    /**
     * 新增容器清单
     */
    @PreAuthorize("@ss.hasPermi('cui:pvessel:add')")
    @Log(title = "容器清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPvessel tPvessel)
    {
        tPvessel.setCreaterCode(getUserId().toString());
        return toAjax(tPvesselService.insertTPvessel(tPvessel));
    }

    /**
     * 修改容器清单
     */
    @PreAuthorize("@ss.hasPermi('cui:pvessel:edit')")
    @Log(title = "容器清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPvessel tPvessel)
    {
        tPvessel.setUpdaterCode(getUserId().toString());
        tPvessel.setUpdatedate(new Date());
        return toAjax(tPvesselService.updateTPvessel(tPvessel));
    }

    /**
     * 删除容器清单
     */
    @PreAuthorize("@ss.hasPermi('cui:pvessel:remove')")
    @Log(title = "容器清单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tPvesselService.deleteTPvesselByIds(ids));
    }

    /**
     * 批量导入容器清单
     */
    @PreAuthorize("@ss.hasPermi('cui:pvessel:add')")
    @Log(title = "容器清单", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException
    {
        //获取操作人员ID
        Long userId = getUserId();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TPvessel> list = new ArrayList<TPvessel>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> unit = iSysDictTypeService.selectDictDataByType("UNIT");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        //报错行数统计
        List<Integer> failRow =new ArrayList<Integer>();
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TPvessel entity = new TPvessel();
                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) {
                        if (cellValue != ""){
                            entity.setSerialnumber(Long.parseLong(cellValue));//序号
                        }
                    } else if (j == 2) {
                        entity.setTagno(cellValue);//位号
                    } else if (j == 3) {
                        entity.setArea(cellValue);//区域划分
                    } else if (j == 4) {
                        entity.setAreaowner(cellValue);//工艺负责人
                    } else if (j == 5) {
                        entity.setCatalogy(cellValue);//类别
                    } else if (j == 6) {
                        entity.setDescription(cellValue);//名称
                    } else if (j == 7) {
                        for (SysDictData p : unit) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setUnit(p.getDictValue());//单元
                            }
                        }
                    } else if (j == 8) {
                        entity.setManufactory(cellValue);//制造单位
                    } else if (j == 9) {
                        entity.setSizes(cellValue);//尺寸
                    } else if (j == 10) {
                        entity.setStuff(cellValue);//材料（管/壳）
                    } else if (j == 11) {
                        entity.setMedium(cellValue);//介质（管/壳）
                    } else if (j == 12) {
                        entity.setDesignpressure(cellValue);//设计压力MPa（管/壳）
                    } else if (j == 13) {
                        entity.setOperationpressure(cellValue);//操作压力MPa（管/壳）
                    } else if (j == 14) {
                        entity.setDesigntemp(cellValue);//设计温度℃（管/壳）
                    } else if (j == 15) {
                        entity.setMaterial(cellValue);//材质
                    } else if (j == 16) {
                        entity.setOperationtemp(cellValue);//工作温度℃（管/壳）
                    } else if (j == 17) {
                        entity.setCoatingage(cellValue);//涂层状况及年限
                    } else if (j == 18) {
                        entity.setJacketing(cellValue);//保温状况
                    } else if (j == 19) {
                        entity.setHeattracing(cellValue);//伴热状况
                    } else if (j == 20) {
                        entity.setExterenv(cellValue);//外部环境
                    } else if (j == 21) {
                        entity.setInsulatingmaterial(cellValue);//绝热材料
                    } else if (j == 22) {
                        entity.setOutsidediameter(cellValue);//管道外径
                    } else if (j == 23) {
                        if (cellValue.length() > 3) {
                            entity.setServicedate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//投用日期
                        }
                    } else if (j == 24) {
                        entity.setRisk(cellValue);//风险等级
                    } else if (j == 25) {
                        entity.setCuistatus(cellValue);//CUI完成情况
                    } else if (j == 26) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 27) {
                        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 (TPvessel t : list
        ) {
            failNum++;
            try {
                tPvesselService.insertTPvessel(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);
    }
}
