package com.ruoyi.project.production.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.production.domain.TWsgl;
import com.ruoyi.project.production.service.ITWsglService;
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;

/**
 * 5S管理Controller
 *
 * @author ruoyi
 * @date 2020-11-25
 */
@RestController
@RequestMapping("/production/wsgl")
public class TWsglController extends BaseController
{
    @Autowired
    private ITWsglService tWsglService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 查询5S管理列表
     */
    @PreAuthorize("@ss.hasPermi('production:wsgl:list')")
    @GetMapping("/list")
    public TableDataInfo list(TWsgl tWsgl)
    {
        startPage();
        List<TWsgl> list = tWsglService.selectTWsglList(tWsgl);
        return getDataTable(list);
    }

    /**
     * 导出5S管理列表
     */
    @PreAuthorize("@ss.hasPermi('production:wsgl:export')")
    @Log(title = "5S管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TWsgl tWsgl)
    {
        List<TWsgl> list = tWsglService.selectTWsglList(tWsgl);
        ExcelUtil<TWsgl> util = new ExcelUtil<TWsgl>(TWsgl.class);
        return util.exportExcel(list, "wsgl");
    }

    /**
     * 获取5S管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('production:wsgl:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tWsglService.selectTWsglById(id));
    }

    /**
     * 新增5S管理
     */
    @PreAuthorize("@ss.hasPermi('production:wsgl:add')")
    @Log(title = "5S管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TWsgl tWsgl)
    {
        tWsgl.setCreaterCode(getUserId().toString());
        return toAjax(tWsglService.insertTWsgl(tWsgl));
    }

    /**
     * 修改5S管理
     */
    @PreAuthorize("@ss.hasPermi('production:wsgl:edit')")
    @Log(title = "5S管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TWsgl tWsgl)
    {
        tWsgl.setUpdaterCode(getUserId().toString());
        tWsgl.setUpdatedate(new Date());
        return toAjax(tWsglService.updateTWsgl(tWsgl));
    }

    /**
     * 删除5S管理
     */
    @PreAuthorize("@ss.hasPermi('production:wsgl:remove')")
    @Log(title = "5S管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tWsglService.deleteTWsglByIds(ids));
    }

    /**
     * 批量导入5S管理
     */
    @PreAuthorize("@ss.hasPermi('production:wsgl:add')")
    @Log(title = "5S管理", 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<TWsgl> list = new ArrayList<TWsgl>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> item = iSysDictTypeService.selectDictDataByType("WSGL_ITEM");
        List<SysDictData> team = iSysDictTypeService.selectDictDataByType("ACCIDENT_TEAM");
        //部门查询
        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();
                TWsgl entity = new TWsgl();
                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.setMacharea(cellValue);//MACHINE/AREA
                    } else if (j == 1) {
                        entity.setWsno(cellValue);//编号
                    } else if (j == 2) {
                        entity.setOwner(cellValue);//负责人
                    } else if (j == 3) {
                        for (SysDictData p : team) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setTeam(p.getDictValue());//班值
                            }
                        }
                    } else if (j == 4) {
                        if (cellValue != ""){
                            entity.setYear(Long.parseLong(cellValue));//年份
                        }
                    } else if (j == 5) {
                        if (cellValue != ""){
                            entity.setJan(Long.parseLong(cellValue));//一月
                        }
                    } else if (j == 6) {
                        if (cellValue != ""){
                            entity.setFeb(Long.parseLong(cellValue));//二月
                        }
                    } else if (j == 7) {
                        if (cellValue != ""){
                            entity.setMar(Long.parseLong(cellValue));//三月
                        }
                    } else if (j == 8) {
                        if (cellValue != ""){
                            entity.setApr(Long.parseLong(cellValue));//四月
                        }
                    } else if (j == 9) {
                        if (cellValue != ""){
                            entity.setMay(Long.parseLong(cellValue));//五月
                        }
                    } else if (j == 10) {
                        if (cellValue != ""){
                            entity.setJun(Long.parseLong(cellValue));//六月
                        }
                    } else if (j == 11) {
                        if (cellValue != ""){
                            entity.setJul(Long.parseLong(cellValue));//七月
                        }
                    } else if (j == 12) {
                        if (cellValue != ""){
                            entity.setAug(Long.parseLong(cellValue));//八月
                        }
                    } else if (j == 13) {
                        if (cellValue != ""){
                            entity.setSep(Long.parseLong(cellValue));//九月
                        }
                    } else if (j == 14) {
                        if (cellValue != ""){
                            entity.setOct(Long.parseLong(cellValue));//十月
                        }
                    } else if (j == 15) {
                        if (cellValue != ""){
                            entity.setNov(Long.parseLong(cellValue));//十一月
                        }
                    } else if (j == 16) {
                        if (cellValue != ""){
                            entity.setDec(Long.parseLong(cellValue));//十二月
                        }
                    } else if (j == 17) {
                        entity.setAverage(cellValue);//排名
                    } else if (j == 18) {
                        for (SysDictData p : item) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setItem(Long.parseLong(p.getDictValue()));//ITEM
                            }
                        }
                    } else if (j == 19) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 20) {
                        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){
                failNumber++;
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TWsgl t : list
        ) {
            failNum++;
            try {
                tWsglService.insertTWsgl(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);
    }
}
