package com.ruoyi.project.production.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.ExcelUtils;
import com.ruoyi.project.common.domain.DataEntity;
import com.ruoyi.project.plant.domain.TStaffmgr;
import com.ruoyi.project.plant.service.ITStaffmgrService;
import com.ruoyi.project.production.mapper.TAccidentMapper;
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.commons.lang.StringUtils;
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.TAccident;
import com.ruoyi.project.production.service.ITAccidentService;
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.annotation.Resource;

/**
 * 隐患排查Controller
 *
 * @author ruoyi
 * @date 2020-11-24
 */
@RestController
@RequestMapping("/production/accident")
public class TAccidentController extends BaseController
{
    @Autowired
    private ITAccidentService tAccidentService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Resource
    private TAccidentMapper tAccidentMapper;

    @Autowired
    private ITStaffmgrService tStaffmgrService;

    /**
     * 查询隐患排查列表
     */
    @PreAuthorize("@ss.hasPermi('production:accident:list')")
    @GetMapping("/list")
    public TableDataInfo list(TAccident tAccident)
    {
        startPage();
        List<TAccident> list = tAccidentService.selectTAccidentList(tAccident);
        return getDataTable(list);
    }

    //首页统计
    @GetMapping("/homeData")
    public TAccident homeData(TAccident tAccident)
    {
        String year = String.valueOf(tAccident.getYear());
        TAccident accident = new TAccident();
        int jan = tAccidentService.selectHomeData(year + "-01");
        int feb = tAccidentService.selectHomeData(year + "-02");
        int mar = tAccidentService.selectHomeData(year + "-03");
        int apr = tAccidentService.selectHomeData(year + "-04");
        int may = tAccidentService.selectHomeData(year + "-05");
        int jun = tAccidentService.selectHomeData(year + "-06");
        int jul = tAccidentService.selectHomeData(year + "-07");
        int aug = tAccidentService.selectHomeData(year + "-08");
        int sep = tAccidentService.selectHomeData(year + "-09");
        int oct = tAccidentService.selectHomeData(year + "-10");
        int nov = tAccidentService.selectHomeData(year + "-11");
        int dec = tAccidentService.selectHomeData(year + "-12");
        if (jan != 0) { accident.setJan(Long.parseLong(String.valueOf(jan))); }
        if (feb != 0) { accident.setFeb(Long.parseLong(String.valueOf(feb))); }
        if (mar != 0) { accident.setMar(Long.parseLong(String.valueOf(mar))); }
        if (apr != 0) { accident.setApr(Long.parseLong(String.valueOf(apr))); }
        if (may != 0) { accident.setMay(Long.parseLong(String.valueOf(may))); }
        if (jun != 0) { accident.setJun(Long.parseLong(String.valueOf(jun))); }
        if (jul != 0) { accident.setJul(Long.parseLong(String.valueOf(jul))); }
        if (aug != 0) { accident.setAug(Long.parseLong(String.valueOf(aug))); }
        if (sep != 0) { accident.setSep(Long.parseLong(String.valueOf(sep))); }
        if (oct != 0) { accident.setOct(Long.parseLong(String.valueOf(oct))); }
        if (nov != 0) { accident.setNov(Long.parseLong(String.valueOf(nov))); }
        if (dec != 0) { accident.setDec(Long.parseLong(String.valueOf(dec))); }
        return accident;
    }

    //年份统计
    @GetMapping("/yearData")
    public List<DataEntity> engData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tAccidentMapper.selectYearData(param);
        return list;
    }

    //状态统计
    @GetMapping("/statusData")
    public List<DataEntity> statusData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tAccidentMapper.selectStatusData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("ACCIDENT_STATUS");
        for (DataEntity d: list
        ) {
            for (SysDictData s: dictList
            ) {
                if (StringUtils.isBlank(d.getDataName())){
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())){
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    //班组统计
    @GetMapping("/teamData")
    public List<DataEntity> teamData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tAccidentMapper.selectTeamData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("ACCIDENT_TEAM");
        for (DataEntity d: list
        ) {
            for (SysDictData s: dictList
            ) {
                if (StringUtils.isBlank(d.getDataName())){
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())){
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }

    //隐患类型统计
    @GetMapping("/accidentTypeData")
    public List<DataEntity> accidentTypeData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tAccidentMapper.selectAccidentTypeData(param);
        for (DataEntity d: list
        ) {
                if (StringUtils.isBlank(d.getDataName())){
                    d.setDataName("未知");
                    break;
                }
            }
        return list;
    }

    //分级统计
    @GetMapping("/confirmData")
    public List<DataEntity> confirmData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tAccidentMapper.selectConfirmData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("CONFIRM_LEVEL");
        for (DataEntity d: list
        ) {
            for (SysDictData s: dictList
            ) {
                if (StringUtils.isBlank(d.getDataName())){
                    d.setDataName("未知");
                    break;
                }
                if (s.getDictValue().equals(d.getDataName())){
                    d.setDataName(s.getDictLabel());
                    break;
                }
            }
        }
        return list;
    }
    /**
     * 导出隐患排查列表
     */
    @PreAuthorize("@ss.hasPermi('production:accident:export')")
    @Log(title = "隐患排查", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TAccident tAccident)
    {
        List<TAccident> list = tAccidentService.selectTAccidentList(tAccident);
        ExcelUtil<TAccident> util = new ExcelUtil<TAccident>(TAccident.class);
        return util.exportExcel(list, "accident");
    }

    /**
     * 获取隐患排查详细信息
     */
    @PreAuthorize("@ss.hasPermi('production:accident:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tAccidentService.selectTAccidentById(id));
    }

    /**
     * 新增隐患排查
     */
    @PreAuthorize("@ss.hasPermi('production:accident:add')")
    @Log(title = "隐患排查", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TAccident tAccident)
    {
        tAccident.setCreaterCode(getUserId().toString());
        //人员信息模块隐患查找数量字段增加
        TStaffmgr tStaffmgr = tStaffmgrService.selectTStaffmgrByStaffId(tAccident.getStaffid());
        Long accidenttNum = tStaffmgr.getAccidentNum() + 1;
        tStaffmgr.setAccidentNum(accidenttNum);
        tStaffmgrService.updateTStaffmgr(tStaffmgr);
        return toAjax(tAccidentService.insertTAccident(tAccident));
    }

    /**
     * 修改隐患排查
     */
    @PreAuthorize("@ss.hasPermi('production:accident:edit')")
    @Log(title = "隐患排查", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TAccident tAccident)
    {
        tAccident.setUpdaterCode(getUserId().toString());
        tAccident.setUpdatedate(new Date());
        //人员信息模块隐患查找数量字段增减
        String lastStaffid = tAccidentService.selectTAccidentById(tAccident.getId()).getStaffid();
        String newStaffid = tAccident.getStaffid();
        if (!newStaffid.equals(lastStaffid)) {
            TStaffmgr lastStaffmgr = tStaffmgrService.selectTStaffmgrByStaffId(lastStaffid);
            Long lastNum = lastStaffmgr.getAccidentNum() - 1;
            lastStaffmgr.setAccidentNum(lastNum);
            tStaffmgrService.updateTStaffmgr(lastStaffmgr);
            TStaffmgr newStaffmgr = tStaffmgrService.selectTStaffmgrByStaffId(newStaffid);
            Long newNum = newStaffmgr.getAccidentNum() + 1;
            newStaffmgr.setAccidentNum(newNum);
            tStaffmgrService.updateTStaffmgr(newStaffmgr);
        }
        return toAjax(tAccidentService.updateTAccident(tAccident));
    }

    /**
     * 删除隐患排查
     */
    @PreAuthorize("@ss.hasPermi('production:accident:remove')")
    @Log(title = "隐患排查", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        for (Long i : ids) {
            TAccident accident = tAccidentService.selectTAccidentById(i);
            //人员信息模块隐患查找数量字段增加
            TStaffmgr tStaffmgr = tStaffmgrService.selectTStaffmgrByStaffId(accident.getStaffid());
            Long accidenttNum = tStaffmgr.getAccidentNum() - 1;
            tStaffmgr.setAccidentNum(accidenttNum);
            tStaffmgrService.updateTStaffmgr(tStaffmgr);
        }
        return toAjax(tAccidentService.deleteTAccidentByIds(ids));
    }

    /**
     * 批量导入隐患排查
     */
    @PreAuthorize("@ss.hasPermi('production:accident: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<TAccident> list = new ArrayList<TAccident>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> area = iSysDictTypeService.selectDictDataByType("AREA_DIVIDE");
        List<SysDictData> team = iSysDictTypeService.selectDictDataByType("ACCIDENT_TEAM");
        List<SysDictData> accident_status = iSysDictTypeService.selectDictDataByType("ACCIDENT_STATUS");
        List<SysDictData> confirm_level = iSysDictTypeService.selectDictDataByType("CONFIRM_LEVEL");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        //人员信息
        List<TStaffmgr> staffmgrs = tStaffmgrService.selectTStaffmgrList(new TStaffmgr());
        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();
                TAccident entity = new TAccident();
                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) {
                        for (SysDictData p : area) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setArea(p.getDictValue());//片区
                            }
                        }
                    } else if (j == 2) {
                        if (cellValue.length() > 3) {
                            entity.setAreadate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//日期
                        }
                    } else if (j == 3) {
                        entity.setContent(cellValue);//内容
                    } else if (j == 4) {
                        for (SysDictData p : team) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setTeam(p.getDictValue());//班组
                            }
                        }
                    } else if (j == 5) {
                    } else if (j == 6) {
                        for (TStaffmgr s : staffmgrs) {
                            if (s.getName().equals(cellValue.trim())) {
                                if (s.getStaffid().equals(ExcelUtils.getCellValue(row.getCell(5)))) {
                                    entity.setStaffid(s.getStaffid());//发现者
                                }
                            }
                        }
                    } else if (j == 7) {
                        entity.setDealer(cellValue);//处理者
                    } else if (j == 8) {
                        for (SysDictData p : accident_status) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setStatus(p.getDictValue());//状态
                            }
                        }
                    } else if (j == 9) {
                        entity.setAreaowner(cellValue);//确认片区或负责人
                    } else if (j == 10) {
                        for (SysDictData p : confirm_level) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setConfirm(p.getDictValue());//分级确认
                            }
                        }
                    } else if (j == 11) {
                        entity.setAccidentytpe(cellValue);//隐患类型
                    } else if (j == 12) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 13) {
                        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++;
                logger.error("e:" + e);
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TAccident t : list
        ) {
            failNum++;
            try {
                tAccidentService.insertTAccident(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);
    }
}
