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.TPipeMapper;
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.TPipe;
import com.ruoyi.project.cui.service.ITPipeService;
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-12-03
 */
@RestController
@RequestMapping("/cui/pipe")
public class TPipeController extends BaseController
{
    @Autowired
    private ITPipeService tPipeService;

    @Autowired
    private ISysDeptService iSysDeptService;

    @Autowired
    private ISysDictTypeService iSysDictTypeService;
    @Resource
    private TPipeMapper tPipeMapper;

    /**
     * 查询管线清单列表
     */
    @PreAuthorize("@ss.hasPermi('cui:pipe:list')")
    @GetMapping("/list")
    public TableDataInfo list(TPipe tPipe)
    {
        startPage();
        List<TPipe> list = tPipeService.selectTPipeList(tPipe);
        return getDataTable(list);
    }

    //风险统计
    @GetMapping("/riskData")
    public List<DataEntity> riskData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tPipeMapper.selectRiskData(param);
        return list;
    }

    //统计
    @GetMapping("/statusData")
    public List<DataEntity> statusData(Map param)
    {
        param.put("params" , new HashMap<>());
        List<DataEntity> list = tPipeMapper.selectStatusData(param);
        return list;
    }

    /**
     * 导出管线清单列表
     */
    @PreAuthorize("@ss.hasPermi('cui:pipe:export')")
    @Log(title = "管线清单", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TPipe tPipe)
    {
        List<TPipe> list = tPipeService.selectTPipeList(tPipe);
        ExcelUtil<TPipe> util = new ExcelUtil<TPipe>(TPipe.class);
        return util.exportExcel(list, "pipe");
    }

    /**
     * 获取管线清单详细信息
     */
    @PreAuthorize("@ss.hasPermi('cui:pipe:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(tPipeService.selectTPipeById(id));
    }

    /**
     * 新增管线清单
     */
    @PreAuthorize("@ss.hasPermi('cui:pipe:add')")
    @Log(title = "管线清单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TPipe tPipe)
    {
        tPipe.setCreaterCode(getUserId().toString());
        return toAjax(tPipeService.insertTPipe(tPipe));
    }

    /**
     * 修改管线清单
     */
    @PreAuthorize("@ss.hasPermi('cui:pipe:edit')")
    @Log(title = "管线清单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TPipe tPipe)
    {
        tPipe.setUpdaterCode(getUserId().toString());
        tPipe.setUpdatedate(new Date());
        return toAjax(tPipeService.updateTPipe(tPipe));
    }

    /**
     * 删除管线清单
     */
    @PreAuthorize("@ss.hasPermi('cui:pipe:remove')")
    @Log(title = "管线清单", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tPipeService.deleteTPipeByIds(ids));
    }

    /**
     * 批量导入管线清单
     */
    @PreAuthorize("@ss.hasPermi('cui:pipe:add')")
    @Log(title = "管线清单", 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<TPipe> list = new ArrayList<TPipe>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //字典查询
        List<SysDictData> plant = iSysDictTypeService.selectDictDataByType("PLANT_DIVIDE");
        List<SysDictData> unit = iSysDictTypeService.selectDictDataByType("UNIT");
        //部门查询
        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();
                TPipe entity = new TPipe();
                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) {
                        entity.setPipeno(cellValue);//管道编号
                    } else if (j == 3) {
                        entity.setPipename(cellValue);//管道名称
                    } else if (j == 4) {
                        for (SysDictData p : unit) {
                            if (p.getDictLabel().equals(cellValue.trim())) {
                                entity.setUnit(p.getDictValue());//单元
                            }
                        }
                    } else if (j == 5) {
                        entity.setServicedate(cellValue);//投用年月
                    } else if (j == 6) {
                        if (cellValue != ""){
                            entity.setPipelength(Long.parseLong(cellValue));//长度
                        }
                    } else if (j == 7) {
                        entity.setStarting(cellValue);//起点
                    } else if (j == 8) {
                        entity.setEnding(cellValue);//终点
                    } else if (j == 9) {
                        entity.setMedium(cellValue);//介质编号
                    } else if (j == 10) {
                        entity.setMaterial(cellValue);//材质
                    } else if (j == 11) {
                        entity.setOperationtemp(cellValue);//工作温度（℃）
                    } else if (j == 12) {
                        entity.setCoatingage(cellValue);//图层状况及年限
                    } else if (j == 13) {
                        entity.setJacketing(cellValue);//保温状况
                    } else if (j == 14) {
                        entity.setHeattracing(cellValue);//伴热状况
                    } else if (j == 15) {
                        entity.setExterenv(cellValue);//外部环境
                    } else if (j == 16) {
                        entity.setInsulatingmaterial(cellValue);//绝热材料
                    } else if (j == 17) {
                        entity.setOutsidediameter(cellValue);//管道外径
                    } else if (j == 18) {
                        entity.setRisk(cellValue);//风险等级
                    } else if (j == 19) {
                        entity.setFieldwalkdown(cellValue);//现场巡查状态
                    } else if (j == 20) {
                        entity.setInspector(cellValue);//检验人
                    } else if (j == 21) {
                        if (cellValue.length() > 3) {
                            entity.setInspectingdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//检验日期
                        }
                    } else if (j == 22) {
                        if (cellValue.length() > 3) {
                            entity.setNextinspectdate(new SimpleDateFormat(DateUtils.getDateFormat(cellValue)).parse(cellValue));//下次检验日期
                        }
                    } else if (j == 23) {
                        entity.setRemarks(cellValue);//备注
                    } else if (j == 24) {
                        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 (TPipe t : list
        ) {
            failNum++;
            try {
                tPipeService.insertTPipe(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);
    }
}
