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.TBamOriginalMapper;
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.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.reliability.domain.TBamOriginal;
import com.ruoyi.project.reliability.service.ITBamOriginalService;
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/original")
public class TBamOriginalController extends BaseController
{
    @Autowired
    private ITBamOriginalService tBamOriginalService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private TBamOriginalMapper tBamOriginalMapper;
    /**
     * 查询故障管理初选列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:original:list')")
    @GetMapping("/list")
    public TableDataInfo list(TBamOriginal tBamOriginal)
    {
        startPage();
        List<TBamOriginal> list = tBamOriginalService.selectTBamOriginalList(tBamOriginal);
        return getDataTable(list);
    }

    //优先级统计
    @GetMapping("/priorityData")
    public List<DataEntity> priorityData(@RequestParam Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tBamOriginalMapper.selectPriorityData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("PRIORITY");
        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;
    }
    //专业统计
    @GetMapping("/disciplineData")
    public List<DataEntity> disciplineData(@RequestParam Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tBamOriginalMapper.selectDisciplineData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("DISCIPLINE");
        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:original:export')")
    @Log(title = "故障管理初选", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TBamOriginal tBamOriginal)
    {
        List<TBamOriginal> list = tBamOriginalService.selectTBamOriginalList(tBamOriginal);
        ExcelUtil<TBamOriginal> util = new ExcelUtil<TBamOriginal>(TBamOriginal.class);
        return util.exportExcel(list, "original");
    }

    /**
     * 获取故障管理初选详细信息
     */
    @PreAuthorize("@ss.hasPermi('reliability:original:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tBamOriginalService.selectTBamOriginalById(id));
    }

    /**
     * 新增故障管理初选
     */
    @PreAuthorize("@ss.hasPermi('reliability:original:add')")
    @Log(title = "故障管理初选", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TBamOriginal tBamOriginal)
    {
        tBamOriginal.setCreaterCode(getUserId().toString());
        return toAjax(tBamOriginalService.insertTBamOriginal(tBamOriginal));
    }

    /**
     * 修改故障管理初选
     */
    @PreAuthorize("@ss.hasPermi('reliability:original:edit')")
    @Log(title = "故障管理初选", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TBamOriginal tBamOriginal)
    {
        tBamOriginal.setUpdaterCode(getUserId().toString());
        tBamOriginal.setUpdatedate(new Date());
        return toAjax(tBamOriginalService.updateTBamOriginal(tBamOriginal));
    }

    /**
     * 删除故障管理初选
     */
    @PreAuthorize("@ss.hasPermi('reliability:original:remove')")
    @Log(title = "故障管理初选", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tBamOriginalService.deleteTBamOriginalByIds(ids));
    }

    /**
     * 批量导入故障管理初选
     */
    @PreAuthorize("@ss.hasPermi('reliability:original: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<TBamOriginal> list = new ArrayList<TBamOriginal>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> priority = iSysDictTypeService.selectDictDataByType("PRIORITY");
        List<SysDictData> discipline = iSysDictTypeService.selectDictDataByType("DISCIPLINE");
        List<SysDictData> phase = iSysDictTypeService.selectDictDataByType("PHASE");
        //部门查询
        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();
                TBamOriginal entity = new TBamOriginal();
                for (int j = 0; j < cellNum; j++) {
                    Cell cell = row.getCell(j);
                    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 : priority) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPriority(p.getDictValue());//优先级
                            }
                        }
                    } else if (j == 2) {
                        entity.setFl(cellValue);//位号
                    } else if (j == 3) {
                        entity.setDescription(cellValue);//设备名称
                    } else if (j == 4) {
                        for (SysDictData p : discipline) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setDiscipline(p.getDictValue());//专业
                            }
                        }
                    } else if (j == 5) {
                        entity.setFailbrief(cellValue);//故障简述
                    } else if (j == 6) {
                        entity.setPrimstudy(cellValue);//初步分析
                    } else if (j == 7) {
                        if (cellValue != ""){
                            entity.setMaintcost(Double.parseDouble(cellValue));//维修费用
                        }
                    } else if (j == 8) {
                        entity.setFrequency(cellValue);//文件放置频次
                    } else if (j == 9) {
                        if (cellValue != ""){
                            entity.setLoss(Double.parseDouble(cellValue));//工艺损失
                        }
                    } else if (j == 10) {
                        if (cellValue != ""){
                            entity.setTotalcost(Double.parseDouble(cellValue));//总费用
                        }
                    } else if (j == 11) {
                        for (SysDictData p : phase) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPhase(p.getDictValue());//阶段
                            }
                        }
                    } else if (j == 12) {
                        entity.setResponsible(cellValue);//负责人
                    } else if (j == 13) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 14) {
                        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 (TBamOriginal t : list
        ) {
            failNum++;
            try {
                tBamOriginalService.insertTBamOriginal(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);
    }
}
