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.TPublicdocmenu;
import com.ruoyi.project.document.service.ITPublicdocmenuService;
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.TPublicdoc;
import com.ruoyi.project.document.service.ITPublicdocService;
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/publicdoc")
public class TPublicdocController extends BaseController
{
    @Autowired
    private ITPublicdocService tPublicdocService;

    @Autowired
    private ITPublicdocmenuService tPublicdocmenuService;

    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 查询公共盘文档列表
     */
    @PreAuthorize("@ss.hasPermi('document:publicdoc:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPublicdoc tPublicdoc)
    {
        startPage();
        List<TPublicdoc> list = tPublicdocService.selectTPublicdocList(tPublicdoc);
        return getDataTable(list);
    }

    /**
     * 导出公共盘文档列表
     */
    @PreAuthorize("@ss.hasPermi('document:publicdoc:export')")
    @Log(title = "公共盘文档", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPublicdoc tPublicdoc)
    {
        List<TPublicdoc> list = tPublicdocService.selectTPublicdocList(tPublicdoc);
        ExcelUtil<TPublicdoc> util = new ExcelUtil<TPublicdoc>(TPublicdoc.class);
        return util.exportExcel(list, "publicdoc");
    }

    /**
     * 获取公共盘文档详细信息
     */
    @PreAuthorize("@ss.hasPermi('document:publicdoc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tPublicdocService.selectTPublicdocById(id));
    }

    /**
     * 新增公共盘文档
     */
    @PreAuthorize("@ss.hasPermi('document:publicdoc:add')")
    @Log(title = "公共盘文档", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPublicdoc tPublicdoc)
    {
        tPublicdoc.setCreaterCode(getUserId().toString());
        return toAjax(tPublicdocService.insertTPublicdoc(tPublicdoc));
    }

    /**
     * 修改公共盘文档
     */
    @PreAuthorize("@ss.hasPermi('document:publicdoc:edit')")
    @Log(title = "公共盘文档", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPublicdoc tPublicdoc)
    {
        tPublicdoc.setUpdaterCode(getUserId().toString());
        tPublicdoc.setUpdatedate(new Date());
        //序号排列
        String[] items = tPublicdoc.getLocation().split("\\.");
        tPublicdoc.setItemFirst(Long.parseLong(items[0]));
        if (items.length == 3) {
            tPublicdoc.setItemSecond(Long.parseLong(items[1]));
            tPublicdoc.setItemThird(Long.parseLong(items[2]));
        }else if (items.length == 2) {
            tPublicdoc.setItemSecond(Long.parseLong(items[1]));
            tPublicdoc.setItemThird(Long.parseLong("0"));
        }else if (items.length == 1) {
            tPublicdoc.setItemSecond(Long.parseLong("0"));
            tPublicdoc.setItemThird(Long.parseLong("0"));
        }
        return toAjax(tPublicdocService.updateTPublicdoc(tPublicdoc));
    }

    /**
     * 删除公共盘文档
     */
    @PreAuthorize("@ss.hasPermi('document:publicdoc:remove')")
    @Log(title = "公共盘文档", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tPublicdocService.deleteTPublicdocByIds(ids));
    }

    /**
     * 批量导入公共盘文档
     */
    @PreAuthorize("@ss.hasPermi('document:publicdoc: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<TPublicdoc> list = new ArrayList<TPublicdoc>();
        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();
                TPublicdoc entity = new TPublicdoc();
                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.setFilename(cellValue);//文件名称
                    } else if (j == 1) {
                        entity.setResponsibility(cellValue);//负责人
                    } else if (j == 2) {
                        entity.setAction(cellValue);//具体行动
                    } else if (j == 3) {
                        entity.setLocation(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());//部门编号
                            }
                        }
                    } else if (j == 6) {
                        TPublicdocmenu menu = tPublicdocmenuService.selectTPublicdocmenuByCatano(cellValue);
                        entity.setMenuid(menu.getId().toString());//目录编号
                    }
                }
                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 (TPublicdoc t : list
        ) {
            failNum++;
            try {
                tPublicdocService.insertTPublicdoc(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);
    }
}
