package com.ruoyi.project.document.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.document.domain.TPublicdoc;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.service.ISysDeptService;
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.document.domain.TPublicdocmenu;
import com.ruoyi.project.document.service.ITPublicdocmenuService;
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;

/**
 * 公共盘文档目录Controller
 *
 * @author ruoyi
 * @date 2020-12-03
 */
@RestController
@RequestMapping("/document/publicdocmenu")
public class TPublicdocmenuController extends BaseController
{
  @Autowired
  private ITPublicdocmenuService tPublicdocmenuService;

  @Autowired
  private ISysDeptService iSysDeptService;

  /**
   * 查询公共盘文档目录列表
   */
  @GetMapping("/list")
  public TableDataInfo list(TPublicdocmenu tPublicdocmenu)
  {
    startPage();
    List<TPublicdocmenu> list = tPublicdocmenuService.selectTPublicdocmenuList(tPublicdocmenu);
    return getDataTable(list);
  }

  /**
   * 查询目录列表
   */
  @GetMapping("/menulist")
  public List<TPublicdocmenu> menulist(TPublicdocmenu tPublicdocmenu)
  {
    List<TPublicdocmenu> list = tPublicdocmenuService.selectTPublicdocmenuList(tPublicdocmenu);
    return list;
  }

  /**
   * 导出公共盘文档目录列表
   */
  @Log(title = "公共盘文档目录", businessType = BusinessType.EXPORT)
  @GetMapping("/export")
  public AjaxResult export(TPublicdocmenu tPublicdocmenu)
  {
    List<TPublicdocmenu> list = tPublicdocmenuService.selectTPublicdocmenuList(tPublicdocmenu);
    ExcelUtil<TPublicdocmenu> util = new ExcelUtil<TPublicdocmenu>(TPublicdocmenu.class);
    return util.exportExcel(list, "publicdocmenu");
  }

  /**
   * 获取公共盘文档目录详细信息
   */
  @GetMapping(value = "/{id}")
  public AjaxResult getInfo(@PathVariable("id") Long id)
  {
    return AjaxResult.success(tPublicdocmenuService.selectTPublicdocmenuById(id));
  }

  /**
   * 新增公共盘文档目录
   */
  @Log(title = "公共盘文档目录", businessType = BusinessType.INSERT)
  @PostMapping
  public AjaxResult add(@RequestBody TPublicdocmenu tPublicdocmenu)
  {
    tPublicdocmenu.setCreaterCode(getUserId().toString());
    //序号排列
    String[] items = tPublicdocmenu.getCatano().split("\\.");
    tPublicdocmenu.setItemFirst(Long.parseLong(items[0]));
    if (items.length == 3) {
      tPublicdocmenu.setItemSecond(Long.parseLong(items[1]));
      tPublicdocmenu.setItemThird(Long.parseLong(items[2]));
    }else if (items.length == 2) {
      tPublicdocmenu.setItemSecond(Long.parseLong(items[1]));
      tPublicdocmenu.setItemThird(Long.parseLong("0"));
    }else if (items.length == 1) {
      tPublicdocmenu.setItemSecond(Long.parseLong("0"));
      tPublicdocmenu.setItemThird(Long.parseLong("0"));
    }
    return toAjax(tPublicdocmenuService.insertTPublicdocmenu(tPublicdocmenu));
  }

  /**
   * 修改公共盘文档目录
   */
  @Log(title = "公共盘文档目录", businessType = BusinessType.UPDATE)
  @PutMapping
  public AjaxResult edit(@RequestBody TPublicdocmenu tPublicdocmenu)
  {
    tPublicdocmenu.setUpdaterCode(getUserId().toString());
    tPublicdocmenu.setUpdatedate(new Date());
    //序号排列
    String[] items = tPublicdocmenu.getCatano().split("\\.");
    tPublicdocmenu.setItemFirst(Long.parseLong(items[0]));
    if (items.length == 3) {
      tPublicdocmenu.setItemSecond(Long.parseLong(items[1]));
      tPublicdocmenu.setItemThird(Long.parseLong(items[2]));
    }else if (items.length == 2) {
      tPublicdocmenu.setItemSecond(Long.parseLong(items[1]));
      tPublicdocmenu.setItemThird(Long.parseLong("0"));
    }else if (items.length == 1) {
      tPublicdocmenu.setItemSecond(Long.parseLong("0"));
      tPublicdocmenu.setItemThird(Long.parseLong("0"));
    }
    return toAjax(tPublicdocmenuService.updateTPublicdocmenu(tPublicdocmenu));
  }

  /**
   * 删除公共盘文档目录
   */
  @Log(title = "公共盘文档目录", businessType = BusinessType.DELETE)
  @DeleteMapping("/{ids}")
  public AjaxResult remove(@PathVariable Long[] ids)
  {
    return toAjax(tPublicdocmenuService.deleteTPublicdocmenuByIds(ids));
  }

  /**
   * 批量导入公共盘文档目录
   */
  @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<TPublicdocmenu> list = new ArrayList<TPublicdocmenu>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    //部门查询
    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();
        TPublicdocmenu entity = new TPublicdocmenu();
        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) {
            entity.setCataname(cellValue);//目录名称
          } else if (j == 1) {
            entity.setCatano(cellValue);//目录编号
          } else if (j == 2) {
            entity.setRemarks(cellValue);//备注
          } else if (j == 3) {
            for (SysDept d : dept) {
              if (d.getDeptName().equals(cellValue.trim())) {
                entity.setDeptId(d.getDeptId());//部门编号
              }
            }
          }
        }
        entity.setCreaterCode(userId.toString());
        logger.info("entity:" + JSON.toJSONString(entity));
        list.add(entity);
      }catch (Exception e){
        failNumber++;
        failRow.add(i+1);
      }
    }
    int successNumber = 0;
    int failNum = 0;
    for (TPublicdocmenu t : list
    ) {
      failNum++;
      try {
        tPublicdocmenuService.insertTPublicdocmenu(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);
  }
}
