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.THighpresfire;
import com.ruoyi.project.ehs.service.ITHighpresfireService;
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-25
 */
@RestController
@RequestMapping("/ehs/highpresfire")
public class THighpresfireController extends BaseController
{
    @Autowired
    private ITHighpresfireService tHighpresfireService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询高压消防炮列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:highpresfire:list')")
    @GetMapping("/list")
    public TableDataInfo list(THighpresfire tHighpresfire)
    {
        startPage();
        List<THighpresfire> list = tHighpresfireService.selectTHighpresfireList(tHighpresfire);
        return getDataTable(list);
    }

    /**
     * 导出高压消防炮列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:highpresfire:export')")
    @Log(title = "高压消防炮", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(THighpresfire tHighpresfire)
    {
        List<THighpresfire> list = tHighpresfireService.selectTHighpresfireList(tHighpresfire);
        ExcelUtil<THighpresfire> util = new ExcelUtil<THighpresfire>(THighpresfire.class);
        return util.exportExcel(list, "highpresfire");
    }

    /**
     * 获取高压消防炮详细信息
     */
    @PreAuthorize("@ss.hasPermi('ehs:highpresfire:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tHighpresfireService.selectTHighpresfireById(id));
    }

    /**
     * 新增高压消防炮
     */
    @PreAuthorize("@ss.hasPermi('ehs:highpresfire:add')")
    @Log(title = "高压消防炮", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody THighpresfire tHighpresfire)
    {
        tHighpresfire.setCreaterCode(getUserId().toString());
        return toAjax(tHighpresfireService.insertTHighpresfire(tHighpresfire));
    }

    /**
     * 修改高压消防炮
     */
    @PreAuthorize("@ss.hasPermi('ehs:highpresfire:edit')")
    @Log(title = "高压消防炮", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody THighpresfire tHighpresfire)
    {
        tHighpresfire.setUpdaterCode(getUserId().toString());
        tHighpresfire.setUpdatedate(new Date());
        return toAjax(tHighpresfireService.updateTHighpresfire(tHighpresfire));
    }

    /**
     * 批量修改消防竖管
     */
    @PreAuthorize("@ss.hasPermi('ehs:highpresfire:edit')")
    @Log(title = "高压消防炮", businessType = BusinessType.UPDATE)
    @RequestMapping("/batchEdit")
    public AjaxResult batchEdit(@RequestBody THighpresfire dto)
    {
        Long[] ids = dto.getIds();
        for (int i = 0; i < ids.length; i++) {
            THighpresfire t = new THighpresfire();
            t.setId(ids[i]);
            t.setRemarks(dto.getRemarks());
            t.setInspectstatus(dto.getInspectstatus());
            t.setUpdaterCode(getUserId().toString());
            t.setUpdatedate(new Date());
            tHighpresfireService.updateTHighpresfire(t);
        }
        return AjaxResult.success();
    }

    /**
     * 删除高压消防炮
     */
    @PreAuthorize("@ss.hasPermi('ehs:highpresfire:remove')")
    @Log(title = "高压消防炮", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tHighpresfireService.deleteTHighpresfireByIds(ids));
    }

    /**
     * 批量导入高压消防炮
     */
    @PreAuthorize("@ss.hasPermi('ehs:highpresfire: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<THighpresfire> list = new ArrayList<THighpresfire>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> inspectstatus = iSysDictTypeService.selectDictDataByType("INSPECTSTATUS");
        //部门查询
        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();
                THighpresfire entity = new THighpresfire();
                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.setNumb(cellValue);//编号
                    } else if (j == 2) {
                        entity.setName(cellValue);//名称
                    } else if (j == 3) {
                        entity.setArea(cellValue);//区域
                    } else if (j == 4) {
                        entity.setPosition(cellValue);//位置
                    } else if (j == 5) {
                        if (cellValue.length() > 3) {
                            entity.setInspectdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//检查日期
                        }
                    } else if (j == 6) {
                        for (SysDictData p : inspectstatus) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setInspectstatus(p.getDictValue());//检查状况
                            }
                        }
                    } else if (j == 7) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 8) {
                        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 (THighpresfire t : list
        ) {
            failNum++;
            try {
                tHighpresfireService.insertTHighpresfire(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);
    }
}
