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.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.project.ehs.domain.TSafetyapproval;
import com.ruoyi.project.ehs.service.ITSafetyapprovalService;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysDictData;
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.TSafetyapprcont;
import com.ruoyi.project.ehs.service.ITSafetyapprcontService;
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-11-27
 */
@RestController
@RequestMapping("/ehs/safetyapprcont")
public class TSafetyapprcontController extends BaseController
{
    @Autowired
    private ITSafetyapprcontService tSafetyapprcontService;

    @Autowired
    private ITSafetyapprovalService tSafetyapprovalService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询安全批文主要内容列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TSafetyapprcont tSafetyapprcont)
    {
        startPage();
        List<TSafetyapprcont> list = tSafetyapprcontService.selectTSafetyapprcontList(tSafetyapprcont);
        return getDataTable(list);
    }

    /**
     * 导出安全批文主要内容列表
     */
    @Log(title = "安全批文主要内容", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TSafetyapprcont tSafetyapprcont)
    {
        List<TSafetyapprcont> list = tSafetyapprcontService.selectTSafetyapprcontList(tSafetyapprcont);
        ExcelUtil<TSafetyapprcont> util = new ExcelUtil<TSafetyapprcont>(TSafetyapprcont.class);
        return util.exportExcel(list, "safetyapprcont");
    }

    /**
     * 获取安全批文主要内容详细信息
     */
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tSafetyapprcontService.selectTSafetyapprcontById(id));
    }

    /**
     * 新增安全批文主要内容
     */
    @Log(title = "安全批文主要内容", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TSafetyapprcont tSafetyapprcont)
    {
        tSafetyapprcont.setCreaterCode(getUserId().toString());
        return toAjax(tSafetyapprcontService.insertTSafetyapprcont(tSafetyapprcont));
    }

    /**
     * 修改安全批文主要内容
     */
    @Log(title = "安全批文主要内容", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TSafetyapprcont tSafetyapprcont)
    {
        tSafetyapprcont.setUpdaterCode(getUserId().toString());
        tSafetyapprcont.setUpdatedate(new Date());
        return toAjax(tSafetyapprcontService.updateTSafetyapprcont(tSafetyapprcont));
    }

    /**
     * 删除安全批文主要内容
     */
    @Log(title = "安全批文主要内容", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tSafetyapprcontService.deleteTSafetyapprcontByIds(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<TSafetyapprcont> list = new ArrayList<TSafetyapprcont>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> businessunit = iSysDictTypeService.selectDictDataByType("BUSINESSUNIT");
        //安全批文清单查询
        List<TSafetyapproval> safetyapprovals = tSafetyapprovalService.selectTSafetyapprovalList(new TSafetyapproval());
        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();
                TSafetyapprcont entity = new TSafetyapprcont();
                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 : businessunit) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setBusinessunit(p.getDictValue());//事业部
                            }
                        }
                    } else if (j == 1) {
                        entity.setPermitname(cellValue);//许可证上的名称
                    } else if (j == 2) {
                        entity.setBycname(cellValue);//BYC使用的名称
                    } else if (j == 3) {
                        entity.setCapacity(cellValue);//设计生产能力
                    } else if (j == 4) {
                        entity.setContents(cellValue);//详细内容
                    } else if (j == 5) {
                        for (TSafetyapproval s : safetyapprovals) {
                            if (s.getApprovalname().equals(cellValue.trim())) {
                                entity.setPid(s.getId().toString());//安全批文ID
                            }
                        }
                    }
                }
                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 (TSafetyapprcont t : list
        ) {
            failNum++;
            try {
                tSafetyapprcontService.insertTSafetyapprcont(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);
    }
}
