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.TEnvironapproval;
import com.ruoyi.project.ehs.service.ITEnvironapprovalService;
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.TEnvironapprcont;
import com.ruoyi.project.ehs.service.ITEnvironapprcontService;
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/environapprcont")
public class TEnvironapprcontController extends BaseController
{
    @Autowired
    private ITEnvironapprcontService tEnvironapprcontService;

    @Autowired
    private ITEnvironapprovalService tEnvironapprovalService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询环保批文主要内容列表
     */
    @GetMapping("/list")
    public TableDataInfo list(TEnvironapprcont tEnvironapprcont)
    {
        startPage();
        List<TEnvironapprcont> list = tEnvironapprcontService.selectTEnvironapprcontList(tEnvironapprcont);
        return getDataTable(list);
    }

    /**
     * 导出环保批文主要内容列表
     */
    @Log(title = "环保批文主要内容", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TEnvironapprcont tEnvironapprcont)
    {
        List<TEnvironapprcont> list = tEnvironapprcontService.selectTEnvironapprcontList(tEnvironapprcont);
        ExcelUtil<TEnvironapprcont> util = new ExcelUtil<TEnvironapprcont>(TEnvironapprcont.class);
        return util.exportExcel(list, "environapprcont");
    }

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

    /**
     * 新增环保批文主要内容
     */
    @Log(title = "环保批文主要内容", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TEnvironapprcont tEnvironapprcont)
    {
        tEnvironapprcont.setCreaterCode(getUserId().toString());
        return toAjax(tEnvironapprcontService.insertTEnvironapprcont(tEnvironapprcont));
    }

    /**
     * 修改环保批文主要内容
     */
    @Log(title = "环保批文主要内容", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TEnvironapprcont tEnvironapprcont)
    {
        tEnvironapprcont.setUpdaterCode(getUserId().toString());
        tEnvironapprcont.setUpdatedate(new Date());
        return toAjax(tEnvironapprcontService.updateTEnvironapprcont(tEnvironapprcont));
    }

    /**
     * 删除环保批文主要内容
     */
    @Log(title = "环保批文主要内容", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tEnvironapprcontService.deleteTEnvironapprcontByIds(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<TEnvironapprcont> list = new ArrayList<TEnvironapprcont>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> waste = iSysDictTypeService.selectDictDataByType("WASTE_CATEGORY");
        //环保批文清单查询
        List<TEnvironapproval> environapprovals = tEnvironapprovalService.selectTEnvironapprovalList(new TEnvironapproval());
        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();
                TEnvironapprcont entity = new TEnvironapprcont();
                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.setEmissionname(cellValue);//污染物名称
                    } else if (j == 1) {
                        for (SysDictData p : waste) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setCategory(p.getDictValue());//类别
                            }
                        }
                    } else if (j == 2) {
                        if (cellValue != ""){
                            entity.setYear(Long.parseLong(cellValue));//年份
                        }
                    } else if (j == 3) {
                        if (cellValue != ""){
                            entity.setEmissions(Long.parseLong(cellValue));//排放量
                        }
                    } else if (j == 4) {
                        entity.setContents(cellValue);//详细内容
                    } else if (j == 5) {
                        for (TEnvironapproval environapproval : environapprovals) {
                            if (environapproval.getApprovalname().equals(cellValue.trim())) {
                                entity.setPid(environapproval.getId().toString());//部门编号
                            }
                        }
                    }
                }
                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 (TEnvironapprcont t : list
        ) {
            failNum++;
            try {
                tEnvironapprcontService.insertTEnvironapprcont(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);
    }
}
