package com.ruoyi.project.reliability.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.reliability.mapper.TAbnormalreportMapper;
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.commons.lang.StringUtils;
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.reliability.domain.TAbnormalreport;
import com.ruoyi.project.reliability.service.ITAbnormalreportService;
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-11-27
 */
@RestController
@RequestMapping("/reliability/abnormalreport")
public class TAbnormalreportController extends BaseController
{
    @Autowired
    private ITAbnormalreportService tAbnormalreportService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private TAbnormalreportMapper tAbnormalreportMapper;

    /**
     * 查询异常报告管理列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:abnormalreport:list')")
    @GetMapping("/list")
    public TableDataInfo list(TAbnormalreport tAbnormalreport)
    {
        startPage();
        List<TAbnormalreport> list = tAbnormalreportService.selectTAbnormalreportList(tAbnormalreport);
        return getDataTable(list);
    }

    //年份统计
    @GetMapping("/yearData")
    public List<DataEntity> engData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tAbnormalreportMapper.selectYearData(param);
        return list;
    }

    //班组统计
    @GetMapping("/teamData")
    public List<DataEntity> teamData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tAbnormalreportMapper.teamData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("ABNORMAL_TEAM");
        for (DataEntity d: list
        ) {
            for (SysDictData s: dictList
            ) {
                if (StringUtils.isBlank(d.getDataName())){
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())){
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    /**
     * 导出异常报告管理列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:abnormalreport:export')")
    @Log(title = "异常报告管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TAbnormalreport tAbnormalreport)
    {
        List<TAbnormalreport> list = tAbnormalreportService.selectTAbnormalreportList(tAbnormalreport);
        ExcelUtil<TAbnormalreport> util = new ExcelUtil<TAbnormalreport>(TAbnormalreport.class);
        return util.exportExcel(list, "abnormalreport");
    }

    /**
     * 获取异常报告管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('reliability:abnormalreport:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tAbnormalreportService.selectTAbnormalreportById(id));
    }

    /**
     * 新增异常报告管理
     */
    @PreAuthorize("@ss.hasPermi('reliability:abnormalreport:add')")
    @Log(title = "异常报告管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TAbnormalreport tAbnormalreport)
    {
        tAbnormalreport.setCreaterCode(getUserId().toString());
        return toAjax(tAbnormalreportService.insertTAbnormalreport(tAbnormalreport));
    }

    /**
     * 修改异常报告管理
     */
    @PreAuthorize("@ss.hasPermi('reliability:abnormalreport:edit')")
    @Log(title = "异常报告管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TAbnormalreport tAbnormalreport)
    {
        tAbnormalreport.setUpdaterCode(getUserId().toString());
        tAbnormalreport.setUpdatedate(new Date());
        return toAjax(tAbnormalreportService.updateTAbnormalreport(tAbnormalreport));
    }

    /**
     * 删除异常报告管理
     */
    @PreAuthorize("@ss.hasPermi('reliability:abnormalreport:remove')")
    @Log(title = "异常报告管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tAbnormalreportService.deleteTAbnormalreportByIds(ids));
    }

    /**
     * 批量导入异常报告管理
     */
    @PreAuthorize("@ss.hasPermi('reliability:abnormalreport: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<TAbnormalreport> list = new ArrayList<TAbnormalreport>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> team = iSysDictTypeService.selectDictDataByType("ABNORMAL_TEAM");
        //部门查询
        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();
                TAbnormalreport entity = new TAbnormalreport();
                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.length() > 3) {
                            entity.setTime(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//时间
                        }
                    } else if (j == 2) {
                        for (SysDictData p : team) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setTeam(p.getDictValue());//班组
                            }
                        }
                    } else if (j == 3) {
                        entity.setReporter(cellValue);//报告人
                    } else if (j == 4) {
                        entity.setReportno(cellValue);//报告号
                    } else if (j == 5) {
                        entity.setAbnormalphen(cellValue);//异常现象
                    } else if (j == 6) {
                        entity.setTreatprocess(cellValue);//处理经过
                    } else if (j == 7) {
                        entity.setReason(cellValue);//原因
                    } else if (j == 8) {
                        entity.setMeasures(cellValue);//措施
                    } else if (j == 9) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 10) {
                        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 (TAbnormalreport t : list
        ) {
            failNum++;
            try {
                tAbnormalreportService.insertTAbnormalreport(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);
    }
}
