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.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.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.TWasteBarrelmonth;
import com.ruoyi.project.ehs.service.ITWasteBarrelmonthService;
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-08
 */
@RestController
@RequestMapping("/ehs/barrelmonth")
public class TWasteBarrelmonthController extends BaseController
{
    @Autowired
    private ITWasteBarrelmonthService tWasteBarrelmonthService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 查询废桶进出库统计日报列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:barrelmonth:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWasteBarrelmonth tWasteBarrelmonth)
    {
        startPage();
        List<TWasteBarrelmonth> list = tWasteBarrelmonthService.selectTWasteBarrelmonthList(tWasteBarrelmonth);
        return getDataTable(list);
    }

    /**
     * 导出废桶进出库统计日报列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:barrelmonth:export')")
    @Log(title = "废桶进出库统计日报", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TWasteBarrelmonth tWasteBarrelmonth)
    {
        List<TWasteBarrelmonth> list = tWasteBarrelmonthService.selectTWasteBarrelmonthList(tWasteBarrelmonth);
        ExcelUtil<TWasteBarrelmonth> util = new ExcelUtil<TWasteBarrelmonth>(TWasteBarrelmonth.class);
        return util.exportExcel(list, "barrelmonth");
    }

    /**
     * 获取废桶进出库统计日报详细信息
     */
    @PreAuthorize("@ss.hasPermi('ehs:barrelmonth:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tWasteBarrelmonthService.selectTWasteBarrelmonthById(id));
    }

    /**
     * 新增废桶进出库统计日报
     */
    @PreAuthorize("@ss.hasPermi('ehs:barrelmonth:add')")
    @Log(title = "废桶进出库统计日报", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWasteBarrelmonth tWasteBarrelmonth)
    {
        tWasteBarrelmonth.setCreaterCode(getUserId().toString());
        return toAjax(tWasteBarrelmonthService.insertTWasteBarrelmonth(tWasteBarrelmonth));
    }

    /**
     * 修改废桶进出库统计日报
     */
    @PreAuthorize("@ss.hasPermi('ehs:barrelmonth:edit')")
    @Log(title = "废桶进出库统计日报", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWasteBarrelmonth tWasteBarrelmonth)
    {
        tWasteBarrelmonth.setUpdaterCode(getUserId().toString());
        tWasteBarrelmonth.setUpdatedate(new Date());
        return toAjax(tWasteBarrelmonthService.updateTWasteBarrelmonth(tWasteBarrelmonth));
    }

    /**
     * 删除废桶进出库统计日报
     */
    @PreAuthorize("@ss.hasPermi('ehs:barrelmonth:remove')")
    @Log(title = "废桶进出库统计日报", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tWasteBarrelmonthService.deleteTWasteBarrelmonthByIds(ids));
    }

    /**
     * 批量导入废桶进出库统计日报
     */
    @PreAuthorize("@ss.hasPermi('ehs:barrelmonth: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<TWasteBarrelmonth> list = new ArrayList<TWasteBarrelmonth>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        //部门查询
        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();
                TWasteBarrelmonth entity = new TWasteBarrelmonth();
                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 : plant) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setPlantCode(p.getDictValue());//产废部门
                            }
                        }
                    } else if (j == 1) {
                        if (cellValue.length() > 3) {
                            entity.setIncomingDate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//日期
                        }
                    } else if (j == 2) {
                        entity.setName(cellValue);//危险废品名称
                    } else if (j == 3) {
                        if (cellValue != "") {
                            entity.setIncomingQuantity(Double.parseDouble(cellValue));//入库数量
                        }
                    } else if (j == 4) {
                        entity.setPackaging(cellValue);//包装形式
                    } else if (j == 5) {
                        if (cellValue != "") {
                            entity.setContainers(Long.parseLong(cellValue));//容器数量（个）
                        }
                    } else if (j == 6) {
                        entity.setPlace(cellValue);//存放位置
                    } else if (j == 7) {
                        entity.setReceiver(cellValue);//接收人
                    } else if (j == 8) {
                        if (cellValue != "") {
                            entity.setDeliveryQuantity(Double.parseDouble(cellValue));//出库数量
                        }
                    } else if (j == 9) {
                        entity.setDeliveryDirection(cellValue);//出库方向
                    } else if (j == 10) {
                        entity.setHandler(cellValue);//经手人
                    } else if (j == 11) {
                        entity.setSheetNumber(cellValue);//联单号
                    } else if (j == 12) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 13) {
                        entity.setRemarks(cellValue);//备注
                    }
                }
                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 (TWasteBarrelmonth t : list
        ) {
            failNum++;
            try {
                tWasteBarrelmonthService.insertTWasteBarrelmonth(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);
    }
}
