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.TKkxglcsMapper;
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.TKkxglcs;
import com.ruoyi.project.reliability.service.ITKkxglcsService;
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/kkxglcs")
public class TKkxglcsController extends BaseController
{
    @Autowired
    private ITKkxglcsService tKkxglcsService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private TKkxglcsMapper tKkxglcsMapper;

    /**
     * 查询可靠性管理措施列表
     */
    @PreAuthorize("@ss.hasPermi('reliability:kkxglcs:list')")
    @GetMapping("/list")
    public TableDataInfo list(TKkxglcs tKkxglcs)
    {
        startPage();
        List<TKkxglcs> list = tKkxglcsService.selectTKkxglcsList(tKkxglcs);
        return getDataTable(list);
    }

    //情况统计
    @GetMapping("/urgencyData")
    public List<DataEntity> urgencyData(@RequestParam Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tKkxglcsMapper.selectUrgencyData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("URGENCY");
        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("/statusData")
    public List<DataEntity> statusData(@RequestParam Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tKkxglcsMapper.selectStatusData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("URGENCY");
        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:kkxglcs:export')")
    @Log(title = "可靠性管理措施", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TKkxglcs tKkxglcs)
    {
        List<TKkxglcs> list = tKkxglcsService.selectTKkxglcsList(tKkxglcs);
        ExcelUtil<TKkxglcs> util = new ExcelUtil<TKkxglcs>(TKkxglcs.class);
        return util.exportExcel(list, "kkxglcs");
    }

    /**
     * 获取可靠性管理措施详细信息
     */
    @PreAuthorize("@ss.hasPermi('reliability:kkxglcs:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tKkxglcsService.selectTKkxglcsById(id));
    }

    /**
     * 新增可靠性管理措施
     */
    @PreAuthorize("@ss.hasPermi('reliability:kkxglcs:add')")
    @Log(title = "可靠性管理措施", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TKkxglcs tKkxglcs)
    {
        tKkxglcs.setCreaterCode(getUserId().toString());
        return toAjax(tKkxglcsService.insertTKkxglcs(tKkxglcs));
    }

    /**
     * 修改可靠性管理措施
     */
    @PreAuthorize("@ss.hasPermi('reliability:kkxglcs:edit')")
    @Log(title = "可靠性管理措施", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TKkxglcs tKkxglcs)
    {
        tKkxglcs.setUpdaterCode(getUserId().toString());
        tKkxglcs.setUpdatedate(new Date());
        return toAjax(tKkxglcsService.updateTKkxglcs(tKkxglcs));
    }

    /**
     * 删除可靠性管理措施
     */
    @PreAuthorize("@ss.hasPermi('reliability:kkxglcs:remove')")
    @Log(title = "可靠性管理措施", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tKkxglcsService.deleteTKkxglcsByIds(ids));
    }

    /**
     * 批量导入可靠性管理措施
     */
    @PreAuthorize("@ss.hasPermi('reliability:kkxglcs: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<TKkxglcs> list = new ArrayList<TKkxglcs>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> area = iSysDictTypeService.selectDictDataByType("AREA_DIVIDE");
        List<SysDictData> rmgtmeassures = iSysDictTypeService.selectDictDataByType("RMGTMEASSURES_CATEGORY");
        List<SysDictData> urgency = iSysDictTypeService.selectDictDataByType("URGENCY");
        List<SysDictData> yesno = iSysDictTypeService.selectDictDataByType("YES_NO");
        //部门查询
        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();
                TKkxglcs entity = new TKkxglcs();
                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 : area) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setArea(p.getDictValue());//区域划分
                            }
                        }
                    } else if (j == 2) {
                        entity.setProblem(cellValue);//问题
                    } else if (j == 3) {
                        if (cellValue != ""){
                            entity.setLoss(Long.parseLong(cellValue));//年损失金额
                        }
                    } else if (j == 4) {
                        entity.setMeasures(cellValue);//措施
                    } else if (j == 5) {
                        for (SysDictData p : rmgtmeassures) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setCategory(p.getDictValue());//类别
                            }
                        }
                    } else if (j == 6) {
                        for (SysDictData p : urgency) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setUrgency(p.getDictValue());//紧急程度
                            }
                        }
                    } else if (j == 7) {
                        for (SysDictData p : yesno) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setSaving(p.getDictValue());//是否有节约
                            }
                        }
                    } else if (j == 8) {
                        if (cellValue.length() > 3) {
                            entity.setStartdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//开始日期
                        }
                    } else if (j == 9) {
                        if (cellValue.length() > 3) {
                            entity.setClosedate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//关闭日期
                        }
                    } else if (j == 10) {
                        entity.setStatus(cellValue);//状态
                    } else if (j == 11) {
                        entity.setImid(cellValue);//创意管理编号
                    } else if (j == 12) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 13) {
                        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 (TKkxglcs t : list
        ) {
            failNum++;
            try {
                tKkxglcsService.insertTKkxglcs(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);
    }
}
