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.TPreventivemaintenanceMapper;
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.reliability.domain.TPreventivemaintenance;
import com.ruoyi.project.reliability.service.ITPreventivemaintenanceService;
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/preventivemaintenance")
public class TPreventivemaintenanceController extends BaseController
{
    @Autowired
    private ITPreventivemaintenanceService tPreventivemaintenanceService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private TPreventivemaintenanceMapper tPreventivemaintenanceMapper;

    /**
     * 查询预防性管理列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:preventivemaintenance:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPreventivemaintenance tPreventivemaintenance)
    {
        startPage();
        List<TPreventivemaintenance> list = tPreventivemaintenanceService.selectTPreventivemaintenanceList(tPreventivemaintenance);
        return getDataTable(list);
    }
    //统计
    @GetMapping("/pmStatusData")
    public List<DataEntity> pmStatusData(@RequestParam Map param)
    {
        param.put("params" , new HashMap<>());
        param.put("status" , "12");
        param.put("month" , "1");
        int d1 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "2");
        int d2 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "3");
        int d3 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "4");
        int d4 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "5");
        int d5 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "6");
        int d6 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "7");
        int d7 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "8");
        int d8 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "9");
        int d9 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "10");
        int d10 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "11");
        int d11 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "12");
        int d12 = tPreventivemaintenanceMapper.selectPmStatusData(param);

        param.put("status" , "14");
        param.put("month" , "1");
        int a1 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "2");
        int a2 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "3");
        int a3 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "4");
        int a4 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "5");
        int a5 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "6");
        int a6 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "7");
        int a7 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "8");
        int a8 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "9");
        int a9 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "10");
        int a10 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "11");
        int a11 = tPreventivemaintenanceMapper.selectPmStatusData(param);
        param.put("month" , "12");
        int a12 = tPreventivemaintenanceMapper.selectPmStatusData(param);

        DataEntity data1 = new DataEntity();
        data1.setDataName("已完成");
        data1.setDataNum(d1+d2+d3+d4+d5+d6+d7+d8+d9+d10+d11+d12);
        DataEntity data2 = new DataEntity();
        data2.setDataName("逾期");
        data2.setDataNum(a1+a2+a3+a4+a5+a6+a7+a8+a9+a10+a11+a12);
        List<DataEntity> list = new ArrayList<>();
        list.add(data1);
        list.add(data2);
        return list;
    }
    /**
     * 导出预防性管理列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:preventivemaintenance:export')")
    @Log(title = "预防性管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPreventivemaintenance tPreventivemaintenance)
    {
        List<TPreventivemaintenance> list = tPreventivemaintenanceService.selectTPreventivemaintenanceList(tPreventivemaintenance);
        ExcelUtil<TPreventivemaintenance> util = new ExcelUtil<TPreventivemaintenance>(TPreventivemaintenance.class);
        return util.exportExcel(list, "preventivemaintenance");
    }

    /**
     * 获取预防性管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('reliability:preventivemaintenance:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tPreventivemaintenanceService.selectTPreventivemaintenanceById(id));
    }

    /**
     * 新增预防性管理
     */
    @PreAuthorize("@ss.hasPermi('reliability:preventivemaintenance:add')")
    @Log(title = "预防性管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPreventivemaintenance tPreventivemaintenance)
    {
        tPreventivemaintenance.setCreaterCode(getUserId().toString());
        return toAjax(tPreventivemaintenanceService.insertTPreventivemaintenance(tPreventivemaintenance));
    }

    /**
     * 修改预防性管理
     */
    @PreAuthorize("@ss.hasPermi('reliability:preventivemaintenance:edit')")
    @Log(title = "预防性管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPreventivemaintenance tPreventivemaintenance)
    {
        tPreventivemaintenance.setUpdaterCode(getUserId().toString());
        tPreventivemaintenance.setUpdatedate(new Date());
        return toAjax(tPreventivemaintenanceService.updateTPreventivemaintenance(tPreventivemaintenance));
    }

    /**
     * 删除预防性管理
     */
    @PreAuthorize("@ss.hasPermi('reliability:preventivemaintenance:remove')")
    @Log(title = "预防性管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tPreventivemaintenanceService.deleteTPreventivemaintenanceByIds(ids));
    }

    /**
     * 批量导入预防性管理
     */
    @PreAuthorize("@ss.hasPermi('reliability:preventivemaintenance: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<TPreventivemaintenance> list = new ArrayList<TPreventivemaintenance>();
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> preventivemaintenance = iSysDictTypeService.selectDictDataByType("PREVENTIVEMAINTENANCE_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();
                TPreventivemaintenance entity = new TPreventivemaintenance();
                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) {
                        entity.setPart(cellValue);//part
                    } else if (j == 2) {
                        entity.setItemtag(cellValue);//ITEM
                    } else if (j == 3) {
                        entity.setTagno(cellValue);//位号
                    } else if (j == 4) {
                        entity.setMaintcontents(cellValue);//维护检修内容
                    } else if (j == 5) {
                        entity.setMaintperiod(cellValue);//维护周期
                    } else if (j == 6) {
                        entity.setResponsibleby(cellValue);//责任人
                    } else if (j == 7) {
                        entity.setExecutor(cellValue);//执行人
                    } else if (j == 8) {
                        entity.setConfirmedby(cellValue);//确认人
                    } else if (j == 9) {
                        entity.setExecutionresult(cellValue);//实施结果
                    } else if (j == 10) {
                        entity.setQuantity(cellValue);//数量
                    } else if (j == 11) {
                        if (cellValue != "") {
                            entity.setYear(Long.parseLong(cellValue));//年份
                        }
                    } else if (j == 12) {
                        entity.setJan(cellValue);//一月
                    } else if (j == 13) {
                        entity.setFeb(cellValue);//二月
                    } else if (j == 14) {
                        entity.setMar(cellValue);//三月
                    } else if (j == 15) {
                        entity.setApr(cellValue);//四月
                    } else if (j == 16) {
                        entity.setMay(cellValue);//五月
                    } else if (j == 17) {
                        entity.setJun(cellValue);//六月
                    } else if (j == 18) {
                        entity.setJul(cellValue);//七月
                    } else if (j == 19) {
                        entity.setAug(cellValue);//八月
                    } else if (j == 20) {
                        entity.setSep(cellValue);//九月
                    } else if (j == 21) {
                        entity.setOct(cellValue);//十月
                    } else if (j == 22) {
                        entity.setNov(cellValue);//十一月
                    } else if (j == 23) {
                        entity.setDec(cellValue);//十二月
                    } else if (j == 24) {
                        for (SysDictData p : preventivemaintenance) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setItem(Long.parseLong(p.getDictValue()));//类型
                            }
                        }
                    } else if (j == 25) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 26) {
                        entity.setRemarks(cellValue);//备注
                    }
                }
                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 (TPreventivemaintenance t : list
        ) {
            failNum++;
            try {
                tPreventivemaintenanceService.insertTPreventivemaintenance(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);
    }
}
