package com.ruoyi.project.ehs.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.file.ExcelUtils;
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.ehs.domain.TRcauditmenu;
import com.ruoyi.project.ehs.service.ITRcauditmenuService;
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;

/**
 * RC审计助手目录Controller
 *
 * @author ruoyi
 * @date 2020-12-07
 */
@RestController
@RequestMapping("/ehs/rcauditmenu")
public class TRcauditmenuController extends BaseController
{
    @Autowired
    private ITRcauditmenuService tRcauditmenuService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 查询RC审计助手目录列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:rcaudit:list')")
    @GetMapping("/list")
    public TableDataInfo list(TRcauditmenu tRcauditmenu)
    {
        startPage();
        List<TRcauditmenu> list = tRcauditmenuService.selectTRcauditmenuList(tRcauditmenu);
        return getDataTable(list);
    }

    /**
     * 查询目录列表
     */
    @GetMapping("/menulist")
    public List<TRcauditmenu> menulist(TRcauditmenu tRcauditmenu)
    {
        List<TRcauditmenu> list = tRcauditmenuService.selectTRcauditmenuList(tRcauditmenu);
        return list;
    }

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

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

    /**
     * 新增RC审计助手目录
     */
    @PreAuthorize("@ss.hasPermi('ehs:rcaudit:add')")
    @Log(title = "RC审计助手目录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TRcauditmenu tRcauditmenu)
    {
        tRcauditmenu.setCreaterCode(getUserId().toString());
        //序号排列
        String[] items = tRcauditmenu.getSerialNum().split("\\.");
        tRcauditmenu.setItemFirst(Long.parseLong(items[0]));
        if (items.length == 4) {
            tRcauditmenu.setItemSecond(Long.parseLong(items[1]));
            tRcauditmenu.setItemThird(Long.parseLong(items[2]));
            tRcauditmenu.setItemFourth(Long.parseLong(items[3]));
        }else if (items.length == 3) {
            tRcauditmenu.setItemSecond(Long.parseLong(items[1]));
            tRcauditmenu.setItemThird(Long.parseLong(items[2]));
            tRcauditmenu.setItemFourth(Long.parseLong("0"));
        }else if (items.length == 2) {
            tRcauditmenu.setItemSecond(Long.parseLong(items[1]));
            tRcauditmenu.setItemThird(Long.parseLong("0"));
            tRcauditmenu.setItemFourth(Long.parseLong("0"));
        }else if (items.length == 1) {
            tRcauditmenu.setItemSecond(Long.parseLong("0"));
            tRcauditmenu.setItemThird(Long.parseLong("0"));
            tRcauditmenu.setItemFourth(Long.parseLong("0"));
        }
        return toAjax(tRcauditmenuService.insertTRcauditmenu(tRcauditmenu));
    }

    /**
     * 修改RC审计助手目录
     */
    @PreAuthorize("@ss.hasPermi('ehs:rcaudit:edit')")
    @Log(title = "RC审计助手目录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TRcauditmenu tRcauditmenu)
    {
        tRcauditmenu.setUpdaterCode(getUserId().toString());
        tRcauditmenu.setUpdatedate(new Date());
        //序号排列
        String[] items = tRcauditmenu.getSerialNum().split("\\.");
        tRcauditmenu.setItemFirst(Long.parseLong(items[0]));
        if (items.length == 4) {
            tRcauditmenu.setItemSecond(Long.parseLong(items[1]));
            tRcauditmenu.setItemThird(Long.parseLong(items[2]));
            tRcauditmenu.setItemFourth(Long.parseLong(items[3]));
        }else if (items.length == 3) {
            tRcauditmenu.setItemSecond(Long.parseLong(items[1]));
            tRcauditmenu.setItemThird(Long.parseLong(items[2]));
            tRcauditmenu.setItemFourth(Long.parseLong("0"));
        }else if (items.length == 2) {
            tRcauditmenu.setItemSecond(Long.parseLong(items[1]));
            tRcauditmenu.setItemThird(Long.parseLong("0"));
            tRcauditmenu.setItemFourth(Long.parseLong("0"));
        }else if (items.length == 1) {
            tRcauditmenu.setItemSecond(Long.parseLong("0"));
            tRcauditmenu.setItemThird(Long.parseLong("0"));
            tRcauditmenu.setItemFourth(Long.parseLong("0"));
        }
        return toAjax(tRcauditmenuService.updateTRcauditmenu(tRcauditmenu));
    }

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

    /**
     * 批量导入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<TRcauditmenu> list = new ArrayList<TRcauditmenu>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        //部门查询
        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();
                TRcauditmenu entity = new TRcauditmenu();
                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.setSerialNum(cellValue);//RC代码
                    } else if (j == 2) {
                        entity.setNameCn(cellValue);//中文名称
                    } else if (j == 3) {
                        entity.setNameEn(cellValue);//英文名称
                    }else if (j == 4) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 5) {
                        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 (TRcauditmenu t : list
        ) {
            failNum++;
            try {
                tRcauditmenuService.insertTRcauditmenu(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);
    }
}
