package com.ruoyi.project.cui.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.cui.mapper.TProblemsMapper;
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.cui.domain.TProblems;
import com.ruoyi.project.cui.service.ITProblemsService;
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;

/**
 * CUI问题整改跟踪清单Controller
 *
 * @author ruoyi
 * @date 2020-12-03
 */
@RestController
@RequestMapping("/cui/problems")
public class TProblemsController extends BaseController
{
    @Autowired
    private ITProblemsService tProblemsService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private TProblemsMapper tProblemsMapper;
    /**
     * 查询CUI问题整改跟踪清单列表
     */
    @PreAuthorize("@ss.hasPermi('cui:problems:list')")
    @GetMapping("/list")
    public TableDataInfo list(TProblems tProblems)
    {
        startPage();
        List<TProblems> list = tProblemsService.selectTProblemsList(tProblems);
        return getDataTable(list);
    }

    //统计
    @GetMapping("/statusData")
    public List<DataEntity> riskData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tProblemsMapper.selectStatusData(param);
        List<SysDictData> dictList = iSysDictTypeService.selectDictDataByType("YES_NO");
        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;
    }

    /**
     * 导出CUI问题整改跟踪清单列表
     */
    @PreAuthorize("@ss.hasPermi('cui:problems:export')")
    @Log(title = "CUI问题整改跟踪清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TProblems tProblems)
    {
        List<TProblems> list = tProblemsService.selectTProblemsList(tProblems);
        ExcelUtil<TProblems> util = new ExcelUtil<TProblems>(TProblems.class);
        return util.exportExcel(list, "problems");
    }

    /**
     * 获取CUI问题整改跟踪清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('cui:problems:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tProblemsService.selectTProblemsById(id));
    }

    /**
     * 新增CUI问题整改跟踪清单
     */
    @PreAuthorize("@ss.hasPermi('cui:problems:add')")
    @Log(title = "CUI问题整改跟踪清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TProblems tProblems)
    {
        tProblems.setCreaterCode(getUserId().toString());
        return toAjax(tProblemsService.insertTProblems(tProblems));
    }

    /**
     * 修改CUI问题整改跟踪清单
     */
    @PreAuthorize("@ss.hasPermi('cui:problems:edit')")
    @Log(title = "CUI问题整改跟踪清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TProblems tProblems)
    {
        tProblems.setUpdaterCode(getUserId().toString());
        tProblems.setUpdatedate(new Date());
        return toAjax(tProblemsService.updateTProblems(tProblems));
    }

    /**
     * 删除CUI问题整改跟踪清单
     */
    @PreAuthorize("@ss.hasPermi('cui:problems:remove')")
    @Log(title = "CUI问题整改跟踪清单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tProblemsService.deleteTProblemsByIds(ids));
    }

    /**
     * 批量导入CUI问题整改跟踪清单
     */
    @PreAuthorize("@ss.hasPermi('cui:problems:add')")
    @Log(title = "CUI问题整改跟踪清单", businessType = BusinessType.INSERT)
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws IOException
    {
        //获取操作人员ID
        Long userId = getUserId();
        Workbook workbook = ExcelUtils.getWorkBook(file);
        Sheet sheet = workbook.getSheetAt(0);
        List<TProblems> list = new ArrayList<TProblems>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> unit = iSysDictTypeService.selectDictDataByType("UNIT");
        List<SysDictData> yes_no = iSysDictTypeService.selectDictDataByType("YES_NO");
        List<SysDictData> yes_no_en = iSysDictTypeService.selectDictDataByType("YES_NO_EN");
        //部门查询
        List<SysDept> dept = iSysDeptService.selectDeptList(new SysDept());
        int rowNum = sheet.getPhysicalNumberOfRows();
        int failNumber = 0;
        //报错行数统计
        List<Integer> failRow =new ArrayList<Integer>();
        for (int i = 1; i < rowNum; i++) {
            try {
                logger.info("读取行数：" + i);
                Row row = sheet.getRow(i);
                int cellNum = row.getLastCellNum();
                TProblems entity = new TProblems();
                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 != ""){
                            entity.setSerialnumber(Long.parseLong(cellValue));//序号
                        }
                    } else if (j == 2) {
                        for (SysDictData p : unit) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setUnit(p.getDictValue());//单元
                            }
                        }
                    } else if (j == 3) {
                        entity.setLineno(cellValue);//管线号/设备位号
                    } else if (j == 4) {
                        entity.setCuiproblem(cellValue);//CUI问题描述
                    } else if (j == 5) {
                        entity.setAnalysis(cellValue);//初步原因分析
                    } else if (j == 6) {
                        entity.setMeasures(cellValue);//整改措施
                    } else if (j == 7) {
                        if (cellValue != ""){
                            entity.setPlancost(Long.parseLong(cellValue));//预付费用
                        }
                    } else if (j == 8) {
                        for (SysDictData y : yes_no) {
                            if (y.getDictLabel().equals(cellValue.trim())) {
                                entity.setIsfinish(y.getDictValue());//是否已完成整改
                            }
                        }
                    } else if (j == 9) {
                        if (cellValue.length() > 3) {
                            entity.setFinishdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//完成整改时间
                        }
                    } else if (j == 10) {
                        for (SysDictData y : yes_no_en) {
                            if (y.getDictLabel().equals(cellValue.trim())) {
                                entity.setIsmeasure(y.getDictValue());//是否有相应措施
                            }
                        }
                    } else if (j == 11) {
                        entity.setResponsible(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++;
                failRow.add(i+1);
            }
        }
        int successNumber = 0;
        int failNum = 0;
        for (TProblems t : list
        ) {
            failNum++;
            try {
                tProblemsService.insertTProblems(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);
    }
}
