package com.ruoyi.project.process.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
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.process.domain.TAlarmmodify;
import com.ruoyi.project.process.service.ITAlarmmodifyService;
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;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 报警值管理Controller
 *
 * @author ruoyi
 * @date 2020-11-25
 */
@RestController
@RequestMapping("/process/alarmmodify")
public class TAlarmmodifyController extends BaseController
{
    @Autowired
    private ITAlarmmodifyService tAlarmmodifyService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    /**
     * 查询报警值管理列表
     */
    @PreAuthorize("@ss.hasPermi('process:alarmmodify:list')")
    @GetMapping("/list")
    public TableDataInfo list(TAlarmmodify tAlarmmodify)
    {
        startPage();
        List<TAlarmmodify> list = tAlarmmodifyService.selectTAlarmmodifyList(tAlarmmodify);
        return getDataTable(list);
    }

    /**
     * 导出报警值管理列表
     */
    @PreAuthorize("@ss.hasPermi('process:alarmmodify:export')")
    @Log(title = "报警值管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TAlarmmodify tAlarmmodify)
    {
        List<TAlarmmodify> list = tAlarmmodifyService.selectTAlarmmodifyList(tAlarmmodify);
        ExcelUtil<TAlarmmodify> util = new ExcelUtil<TAlarmmodify>(TAlarmmodify.class);
        return util.exportExcel(list, "alarmmodify");
    }

    /**
     * 获取报警值管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('process:alarmmodify:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tAlarmmodifyService.selectTAlarmmodifyById(id));
    }

    /**
     * 新增报警值管理
     */
    @PreAuthorize("@ss.hasPermi('process:alarmmodify:add')")
    @Log(title = "报警值管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TAlarmmodify tAlarmmodify)
    {
        tAlarmmodify.setCreaterCode(getUserId().toString());
        return toAjax(tAlarmmodifyService.insertTAlarmmodify(tAlarmmodify));
    }

    /**
     * 修改报警值管理
     */
    @PreAuthorize("@ss.hasPermi('process:alarmmodify:edit')")
    @Log(title = "报警值管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TAlarmmodify tAlarmmodify)
    {
        tAlarmmodify.setUpdaterCode(getUserId().toString());
        tAlarmmodify.setUpdatedate(new Date());
        return toAjax(tAlarmmodifyService.updateTAlarmmodify(tAlarmmodify));
    }

    /**
     * 删除报警值管理
     */
    @PreAuthorize("@ss.hasPermi('process:alarmmodify:remove')")
    @Log(title = "报警值管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tAlarmmodifyService.deleteTAlarmmodifyByIds(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<TAlarmmodify> list = new ArrayList<TAlarmmodify>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> area = iSysDictTypeService.selectDictDataByType("AREA_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();
                TAlarmmodify entity = new TAlarmmodify();
                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.setTime(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//时间
                        }
                    } else if (j == 2) {
                        for (SysDictData a : area) {
                            if (a.getDictLabel().equals(cellValue.trim())) {
                                entity.setArea(a.getDictValue());//区域
                            }
                        }
                    } else if (j == 3) {
                        entity.setContents(cellValue);//修改内容
                    } else if (j == 4) {
                        entity.setApplicant(cellValue);//批准人
                    } else if (j == 5) {
                        entity.setReviewer(cellValue);//申请人
                    } else if (j == 6) {
                        entity.setApprover(cellValue);//审核人
                    } else if (j == 7) {
                        entity.setExecutor(cellValue);//执行人
                    } else if (j == 8) {
                        entity.setRemarks(cellValue);//执行人
                    } else if (j == 9) {
                        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 (TAlarmmodify t : list
        ) {
            failNum++;
            try {
                tAlarmmodifyService.insertTAlarmmodify(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);
    }
}
