package com.ruoyi.project.ehs.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.ehs.mapper.TJobticketMapper;
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.ehs.domain.TJobticket;
import com.ruoyi.project.ehs.service.ITJobticketService;
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-12-01
 */
@RestController
@RequestMapping("/ehs/jobticket")
public class TJobticketController extends BaseController
{
    @Autowired
    private ITJobticketService tJobticketService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;

    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private TJobticketMapper tJobticketMapper;
    /**
     * 查询工作票列表
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:list')")
    @GetMapping("/list")
    public TableDataInfo list(TJobticket tJobticket)
    {
        startPage();
        List<TJobticket> list = tJobticketService.selectTJobticketList(tJobticket);
        return getDataTable(list);
    }

    //情况统计
    @GetMapping("/fireData")
    public List<DataEntity> fireData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tJobticketMapper.selectFireData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("HPJB");
        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('ehs:jobticket:export')")
    @Log(title = "工作票", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TJobticket tJobticket)
    {
        List<TJobticket> list = tJobticketService.selectTJobticketList(tJobticket);
        ExcelUtil<TJobticket> util = new ExcelUtil<TJobticket>(TJobticket.class);
        return util.exportExcel(list, "jobticket");
    }

    /**
     * 获取工作票详细信息
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tJobticketService.selectTJobticketById(id));
    }

    /**
     * 新增工作票
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:add')")
    @Log(title = "工作票", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TJobticket tJobticket)
    {
        tJobticket.setCreaterCode(getUserId().toString());
        return toAjax(tJobticketService.insertTJobticket(tJobticket));
    }

    /**
     * 修改工作票
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:edit')")
    @Log(title = "工作票", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TJobticket tJobticket)
    {
        tJobticket.setUpdaterCode(getUserId().toString());
        tJobticket.setUpdatedate(new Date());
        return toAjax(tJobticketService.updateTJobticket(tJobticket));
    }

    /**
     * 删除工作票
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket:remove')")
    @Log(title = "工作票", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tJobticketService.deleteTJobticketByIds(ids));
    }

    /**
     * 批量导入工作票
     */
    @PreAuthorize("@ss.hasPermi('ehs:jobticket: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<TJobticket> list = new ArrayList<TJobticket>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> qfbz = iSysDictTypeService.selectDictDataByType("QFBZ");
        List<SysDictData> xpxp = iSysDictTypeService.selectDictDataByType("XPXP");
        List<SysDictData> hpjb = iSysDictTypeService.selectDictDataByType("HPJB");
        List<SysDictData> zypzt = iSysDictTypeService.selectDictDataByType("ZYPZT");
        //部门查询
        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.getPhysicalNumberOfCells();
                TJobticket entity = new TJobticket();
                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.setKprq(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//开票日期
                        }
                    } else if (j == 2) {
                        entity.setQfsj(cellValue);//签发时间
                    } else if (j == 3) {
                        for (SysDictData p : qfbz) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setQfbz(p.getDictValue());//签发班组
                            }
                        }
                    } else if (j == 4) {
                        entity.setQfr(cellValue);//签发人
                    } else if (j == 5) {
                        for (SysDictData p : xpxp) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setXpxp(p.getDictValue());//新票/续票
                            }
                        }
                    } else if (j == 6) {
                        entity.setYqxkzh(cellValue);//延期许可证号
                    } else if (j == 7) {
                        entity.setWhgzxkzh(cellValue);//危害工作许可证号
                    } else if (j == 8) {
                        entity.setDhzyxkzh(cellValue);//未撤销项编号
                    } else if (j == 9) {
                        for (SysDictData p : hpjb) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setHpjb(p.getDictValue());//火票级别
                            }
                        }
                    } else if (j == 10) {
                        entity.setXzkjxkzh(cellValue);//限制空间许可证号
                    } else if (j == 11) {
                        entity.setContent(cellValue);//工作内容
                    } else if (j == 12) {
                        entity.setByclxr(cellValue);//BYC负责单位/联系人
                    } else if (j == 13) {
                        entity.setSgdw(cellValue);//施工单位
                    } else if (j == 14) {
                        entity.setLxr(cellValue);//联系人
                    } else if (j == 15) {
                        entity.setLxdh(cellValue);//联系电话
                    } else if (j == 16) {
                        if (cellValue.length() > 3) {
                            entity.setXpsj(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//销票时间
                        }
                    } else if (j == 17) {
                        for (SysDictData p : zypzt) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setZypzt(p.getDictValue());//作业票状态
                            }
                        }
                    } else if (j == 18) {
                        entity.setJccdr(cellValue);//检查/存档人
                    } else if (j == 19) {
                        entity.setWcxxbh(cellValue);//未撤销项编号
                    } else if (j == 20) {
                        entity.setWcxzt(cellValue);//未撤销状态
                    } else if (j == 21) {
                        if (cellValue.length() > 3) {
                            entity.setCxsj(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//撤销时间
                        }
                    } else if (j == 22) {
                        for (SysDept d : dept) {
                            if (d.getDeptName().equals(cellValue.trim())) {
                                entity.setDeptId(d.getDeptId());//部门编号
                            }
                        }
                    } else if (j == 23) {
                        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 (TJobticket t : list
        ) {
            failNum++;
            try {
                tJobticketService.insertTJobticket(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);
    }
}
