package com.ruoyi.project.document.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.common.domain.DataEntity;
import com.ruoyi.project.document.domain.TPlantproglist;
import com.ruoyi.project.document.mapper.TPlantproglistMapper;
import com.ruoyi.project.document.service.ITPlantproglistService;
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.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 装置程序清单Controller
 *
 * @author ruoyi
 * @date 2020-11-26
 */
@RestController
@RequestMapping("/document/plantproglist")
public class TPlantproglistController extends BaseController
{
    @Autowired
    private ITPlantproglistService tPlantproglistService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private TPlantproglistMapper tPlantproglistMapper;
    /**
     * 查询装置程序清单列表
     */
    @PreAuthorize("@ss.hasPermi('document:plantproglist:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPlantproglist tPlantproglist)
    {
        startPage();
        List<TPlantproglist> list = tPlantproglistService.selectTPlantproglistList(tPlantproglist);
        return getDataTable(list);
    }

    //情况统计
    @GetMapping("/rcData")
    public List<DataEntity> rcData(@RequestParam Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tPlantproglistMapper.selectRcData(param);
        return list;
    }

    //情况统计
    @GetMapping("/classifyData")
    public List<DataEntity> classifyData(@RequestParam Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tPlantproglistMapper.selectclassifyData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("CLASSIFY");
        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('document:plantproglist:export')")
    @Log(title = "装置程序清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPlantproglist tPlantproglist)
    {
        List<TPlantproglist> list = tPlantproglistService.selectTPlantproglistList(tPlantproglist);
        ExcelUtil<TPlantproglist> util = new ExcelUtil<TPlantproglist>(TPlantproglist.class);
        return util.exportExcel(list, "plantproglist" ,"蒸汽裂解装置程序清单");
    }

    /**
     * 获取装置程序清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('document:plantproglist:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tPlantproglistService.selectTPlantproglistById(id));
    }

    /**
     * 新增装置程序清单
     */
    @PreAuthorize("@ss.hasPermi('document:plantproglist:add')")
    @Log(title = "装置程序清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPlantproglist tPlantproglist) {
        tPlantproglist.setFilename(tPlantproglist.getFilename().trim());
        tPlantproglist.setFileno(tPlantproglist.getFileno().trim());
        tPlantproglist.setCreaterCode(getUserId().toString());
        return toAjax(tPlantproglistService.insertTPlantproglist(tPlantproglist));
    }

    /**
     * 修改装置程序清单
     */
    @PreAuthorize("@ss.hasPermi('document:plantproglist:edit')")
    @Log(title = "装置程序清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPlantproglist tPlantproglist)
    {
        tPlantproglist.setUpdaterCode(getUserId().toString());
        tPlantproglist.setUpdatedate(new Date());
        return toAjax(tPlantproglistService.updateTPlantproglist(tPlantproglist));
    }

    /**
     * 删除装置程序清单
     */
    @PreAuthorize("@ss.hasPermi('document:plantproglist:remove')")
    @Log(title = "装置程序清单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tPlantproglistService.deleteTPlantproglistByIds(ids));
    }

    /**
     * 批量导入装置程序清单
     */
    @PreAuthorize("@ss.hasPermi('document:plantproglist: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<TPlantproglist> list = new ArrayList<TPlantproglist>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> department = iSysDictTypeService.selectDictDataByType("DEPARTMENT");
        List<SysDictData> item = iSysDictTypeService.selectDictDataByType("FIREEMERGENCY_ITEM");
        List<SysDictData> classify = iSysDictTypeService.selectDictDataByType("CLASSIFY");
        //部门查询
        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();
                TPlantproglist entity = new TPlantproglist();
                //判断文件类型，如果是附件清单，读取逻辑不同
                int n = 0;
                for (int m = 0; m < cellNum; m++) {
                    Cell cell = row.getCell(m);
                    //  cell.setCellType(CellType.STRING);
                    String cellValue = ExcelUtils.getCellValue(cell);
                    if (m == 11) {
                        if (cellValue.trim().equals("附件总汇")) {
                            n = 1;
                        }
                    }
                }
                logger.info("n:" + n);
                if (n == 1) {
                    //附件清单
                    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.setFileno(cellValue);//文件编号
                        } else if (j == 1) {
                            entity.setFilename(cellValue);//文件名称
                        } else if (j == 2) {
                            entity.setRevision(cellValue);//版次
                        } else if (j == 3) {
                            entity.setRccode(cellValue);//RC代码
                        } else if (j == 4) {
                            entity.setResponsibility(cellValue);//责任者
                        } else if (j == 5) {
                            if (cellValue.length() > 3) {
                                entity.setFiledate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//文件日期
                            }
                        } else if (j == 6) {
                            if (cellValue.length() > 3) {
                                entity.setNexteditdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//下次修改日期
                            }
                        } else if (j == 7) {
                            entity.setAttachmentNo(cellValue);//附件编号
                        } else if (j == 8) {
                            entity.setAttachmentName(cellValue);//附件名称
                        } else if (j == 9) {
                            entity.setAttachmentRevision(cellValue);//附件版次
                        } else if (j == 10) {
                            if (cellValue.length() > 3) {
                                entity.setRevisionDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//附件修改日期
                            }
                        } else if (j == 11) {
                            for (SysDictData p : item) {
                                if (p.getDictLabel().equals(cellValue.trim())) {
                                    entity.setItem(Long.parseLong(p.getDictValue()));//文件类型
                                }
                            }
                        } 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());//部门编号
                                }
                            }
                        }
                    }
                }else {
                    //其他类型
                    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.setFileno(cellValue);//文件编号
                        } else if (j == 1) {
                            entity.setFilename(cellValue);//文件名称
                        } else if (j == 2) {
                            entity.setRevision(cellValue);//版次
                        } else if (j == 3) {
                            entity.setRccode(cellValue);//RC代码
                        } else if (j == 4) {
                            entity.setResponsibility(cellValue);//责任者
                        } else if (j == 5) {
                            if (cellValue.length() > 3) {
                                entity.setFiledate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//文件日期
                            }
                        } else if (j == 6) {
                            if (cellValue.length() > 3) {
                                entity.setNexteditdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//下次修改日期
                            }
                        } else if (j == 7) {
                            entity.setReviewFrequency(cellValue);//回顾频率

                        } else if (j == 8) {
                            if (cellValue.length() > 3) {
                                entity.setReviewdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//本次回顾日期
                            }
                        } else if (j == 9) {
                            entity.setReviewResult(cellValue);//回顾结果
                        } else if (j == 10) {
                            if (cellValue.length() > 3) {
                                entity.setNextreviewdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//下次回顾日期
                            }
                        } else if (j == 11) {
                            for (SysDictData p : item) {
                                if (p.getDictLabel().equals(cellValue.trim())) {
                                    entity.setItem(Long.parseLong(p.getDictValue()));//文件类型
                                }
                            }
                        } else if (j == 12) {
                            for (SysDictData p : classify) {
                                if (p.getDictLabel().equals(cellValue.trim())) {
                                    entity.setClassify(p.getDictValue());
                                }
                            }//分级
                        }  else if (j == 13) {
                            entity.setVersionPan(cellValue);//公共盘版本
                        } else if (j == 14) {
                            entity.setRemarks(cellValue);//备注
                        } else if (j == 15) {
                            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){
                logger.error(JSON.toJSONString(e));
                failNumber++;
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TPlantproglist t : list
        ) {
            failNum++;
            try {
                tPlantproglistService.insertTPlantproglist(t);
                successNumber++;
            }catch (Exception e){
                logger.error(JSON.toJSONString(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);
    }

    /**
     * 装置程序清单附件上传
     */
    @Log(title = "装置程序清单附件上传", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException
    {
        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getFilePath("/plantproglist"), file);
            return AjaxResult.success();
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }

    /**
     * 清单
     *
     * @param request
     * @param response
     * @throws IOException
     */
//    @RequestMapping("/download/exportDevList")
//    public ModelAndView exportList(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws ParseException {
//        logger.info(JSON.toJSONString(params));
//        String id = (String) params.get("ids");
//        int devType = Integer.parseInt((String) params.get("devType"));
//        String[] ids = id.split(",");
//        logger.info("ids" + ids);
//        int downloadType = Integer.parseInt((String) params.get("downloadType"));
//        logger.info("downloadType" + downloadType);
//        List<Object> list = new ArrayList<>();
//
//        return new ModelAndView(new JxlsView(JxlsTemplateEnum.DEV_CC_UPDATE, list));
//    }
}
