package com.ruoyi.project.ehs.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.ehs.domain.TRcauditmenu;
import com.ruoyi.project.ehs.mapper.TRcauditMapper;
import com.ruoyi.project.ehs.service.ITRcauditmenuService;
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.ehs.domain.TRcaudit;
import com.ruoyi.project.ehs.service.ITRcauditService;
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;

/**
 * RC审计助手Controller
 *
 * @author ruoyi
 * @date 2020-12-07
 */
@RestController
@RequestMapping("/ehs/rcaudit")
public class TRcauditController extends BaseController
{
    @Autowired
    private ITRcauditService tRcauditService;

    @Autowired
    private ITRcauditmenuService itRcauditmenuService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;
    @Resource
    private TRcauditMapper tRcauditMapper;
    /**
     * 查询RC审计助手列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:rcaudit:list')")
    @GetMapping("/list")
    public TableDataInfo list(TRcaudit tRcaudit)
    {
        startPage();
        List<TRcaudit> list = tRcauditService.selectTRcauditList(tRcaudit);
        return getDataTable(list);
    }

    //情况统计
    @GetMapping("/naData")
    public List<DataEntity> naData(Map param)
    {
        param.put("params" , new HashMap<>());
        param.put("yes" , 1);
        DataEntity data1 = tRcauditMapper.selectNaData(param);
        data1.setDataName("YES");
        param.put("yes" , 2);
        DataEntity data2 = tRcauditMapper.selectNaData(param);
        data2.setDataName("NO");
        param.put("yes" , 3);
        DataEntity data3 = tRcauditMapper.selectNaData(param);
        data3.setDataName("NA");
        List<DataEntity> list = new ArrayList<>();
        list.add(data1);
        list.add(data2);
        list.add(data3);
        return list;
    }

    /**
     * 导出RC审计助手列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:rcaudit:export')")
    @Log(title = "RC审计助手", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TRcaudit tRcaudit)
    {
        List<TRcaudit> list = tRcauditService.selectTRcauditList(tRcaudit);
        ExcelUtil<TRcaudit> util = new ExcelUtil<TRcaudit>(TRcaudit.class);
        return util.exportExcel(list, "rcaudit");
    }

    /**
     * 获取RC审计助手详细信息
     */
    @PreAuthorize("@ss.hasPermi('ehs:rcaudit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tRcauditService.selectTRcauditById(id));
    }

    /**
     * 新增RC审计助手
     */
    @PreAuthorize("@ss.hasPermi('ehs:rcaudit:add')")
    @Log(title = "RC审计助手", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TRcaudit tRcaudit)
    {
        tRcaudit.setCreaterCode(getUserId().toString());
        return toAjax(tRcauditService.insertTRcaudit(tRcaudit));
    }

    /**
     * 修改RC审计助手
     */
    @PreAuthorize("@ss.hasPermi('ehs:rcaudit:edit')")
    @Log(title = "RC审计助手", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TRcaudit tRcaudit)
    {
        tRcaudit.setUpdaterCode(getUserId().toString());
        tRcaudit.setUpdatedate(new Date());
        return toAjax(tRcauditService.updateTRcaudit(tRcaudit));
    }

    /**
     * 删除RC审计助手
     */
    @PreAuthorize("@ss.hasPermi('ehs:rcaudit:remove')")
    @Log(title = "RC审计助手", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tRcauditService.deleteTRcauditByIds(ids));
    }

    /**
     * RC审计助手附件增加
     */
    @Log(title = "RC审计助手", businessType = BusinessType.UPDATE)
    @PutMapping("/addFile")
    public AjaxResult addFile(@RequestBody TRcaudit tRcaudit)
    {
        tRcaudit.setUpdaterCode(getUserId().toString());
        tRcaudit.setUpdatedate(new Date());
        TRcaudit rcaudit = tRcauditService.selectTRcauditById(tRcaudit.getId());
        tRcaudit.setFileNum(rcaudit.getFileNum() + 1);
        return toAjax(tRcauditService.updateTRcaudit(tRcaudit));
    }

    /**
     * RC审计助手附件减少
     */
    @Log(title = "RC审计助手", businessType = BusinessType.UPDATE)
    @PutMapping("/reduceFile")
    public AjaxResult reduceFile(@RequestBody TRcaudit tRcaudit)
    {
        tRcaudit.setUpdaterCode(getUserId().toString());
        tRcaudit.setUpdatedate(new Date());
        TRcaudit rcaudit = tRcauditService.selectTRcauditById(tRcaudit.getId());
        tRcaudit.setFileNum(rcaudit.getFileNum() - 1);
        return toAjax(tRcauditService.updateTRcaudit(tRcaudit));
    }

    /**
     * 批量导入RC审计助手
     */
    @PreAuthorize("@ss.hasPermi('ehs:rcaudit:add')")
    @Log(title = "RC审计助手", 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<TRcaudit> list = new ArrayList<TRcaudit>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> tickcross = iSysDictTypeService.selectDictDataByType("TICK_CROSS");
        //RC审计助手目录查询
        List<TRcauditmenu> menulist = itRcauditmenuService.selectTRcauditmenuList(new TRcauditmenu());
        //部门查询
        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();
                TRcaudit entity = new TRcaudit();
                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.setRcCode(cellValue);//序号
                    } else if (j == 2) {
                        entity.setMenuid(cellValue);//目录
                    } else if (j == 3) {
                        entity.setNameCn(cellValue);//中文名称
                    } else if (j == 4) {
                        entity.setNameEn(cellValue);//英文名称
                    } else if (j == 5) {
                        for (SysDictData p : tickcross) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setYes(Long.parseLong(p.getDictValue()));//YES
                            }
                        }
                    } else if (j == 6) {
                        for (SysDictData p : tickcross) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setNo(Long.parseLong(p.getDictValue()));//NO
                            }
                        }
                    } else if (j == 7) {
                        for (SysDictData p : tickcross) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setNa(p.getDictValue());//NA
                            }
                        }
                    } else if (j == 8) {
                        entity.setLink(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 (TRcaudit t : list
        ) {
            failNum++;
            try {
                tRcauditService.insertTRcaudit(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);
    }
}
