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.TBlind;
import com.ruoyi.project.production.service.ITBlindService;
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-24
 */
@RestController
@RequestMapping("/production/blind")
public class TBlindController extends BaseController
{
    @Autowired
    private ITBlindService tBlindService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    /**
     * 查询盲板清单列表
     */
    @PreAuthorize("@ss.hasPermi('production:blind:list')")
    @GetMapping("/list")
    public TableDataInfo list(TBlind tBlind)
    {
        startPage();
        List<TBlind> list = tBlindService.selectTBlindList(tBlind);
        return getDataTable(list);
    }

    /**
     * 导出盲板清单列表
     */
    @PreAuthorize("@ss.hasPermi('production:blind:export')")
    @Log(title = "盲板清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TBlind tBlind)
    {
        List<TBlind> list = tBlindService.selectTBlindList(tBlind);
        ExcelUtil<TBlind> util = new ExcelUtil<TBlind>(TBlind.class);
        return util.exportExcel(list, "blind");
    }

    /**
     * 获取盲板清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('production:blind:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return AjaxResult.success(tBlindService.selectTBlindById(id));
    }

    /**
     * 新增盲板清单
     */
    @PreAuthorize("@ss.hasPermi('production:blind:add')")
    @Log(title = "盲板清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TBlind tBlind)
    {
        tBlind.setCreaterCode(getUserId().toString());
        return toAjax(tBlindService.insertTBlind(tBlind));
    }

    /**
     * 修改盲板清单
     */
    @PreAuthorize("@ss.hasPermi('production:blind:edit')")
    @Log(title = "盲板清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TBlind tBlind)
    {
        tBlind.setUpdaterCode(getUserId().toString());
        tBlind.setUpdatedate(new Date());
        return toAjax(tBlindService.updateTBlind(tBlind));
    }

    /**
     * 删除盲板清单
     */
    @PreAuthorize("@ss.hasPermi('production:blind:remove')")
    @Log(title = "盲板清单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(tBlindService.deleteTBlindByIds(ids));
    }

    /**
     * 批量导入盲板清单
     */
    @PreAuthorize("@ss.hasPermi('production:blind: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<TBlind> list = new ArrayList<TBlind>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> yesno = iSysDictTypeService.selectDictDataByType("YES_NO_EN");
        //部门查询
        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();
                TBlind entity = new TBlind();
                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) {
                        entity.setUnit(cellValue);//单元
                    } else if (j == 2) {
                        entity.setSystem(cellValue);//系统
                    } else if (j == 3) {
                        entity.setBlindno(cellValue);//盲板编号
                    } else if (j == 4) {
                        entity.setSizes(cellValue);//尺寸
                    } else if (j == 5) {
                        for (SysDictData p : yesno) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setEightblind(p.getDictValue());//“8”字盲板 YES/NO
                            }
                        }
                    } else if (j == 6) {
                        entity.setPressure(cellValue);//压力（LB）
                    } else if (j == 7) {
                        entity.setBlindtype(cellValue);//盲板类型
                    } else if (j == 8) {
                        entity.setPipeno(cellValue);//管道编号
                    } else if (j == 9) {
                        entity.setMedia(cellValue);//介质
                    } else if (j == 10) {
                        entity.setPid(cellValue);//PID图号
                    } else if (j == 11) {
                        entity.setPlace(cellValue);//位置描述
                    } else if (j == 12) {
                        for (SysDictData p : yesno) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setYnblind(p.getDictValue());//YESNO盲位（YES/NO）
                            }
                        }
                    } else if (j == 13) {
                        if (cellValue.length() > 3) {
                            entity.setBlinddate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(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){
                failNumber++;
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TBlind t : list
        ) {
            failNum++;
            try {
                tBlindService.insertTBlind(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);
    }
}
