package com.nantian.cloud.jly.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantian.cloud.jly.entity.CheckGauges;
import com.nantian.cloud.jly.entity.CheckGauges;
import com.nantian.cloud.jly.entity.InspectionData;
import com.nantian.cloud.jly.mapper.CheckGaugesMapper;
import com.nantian.cloud.jly.service.CheckGaugesService;
import com.nantian.cloud.jly.service.InspectionDataService;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.data.datascope.DataScope;
import com.nantian.sc.cloud.common.security.service.ScUser;
import com.nantian.sc.cloud.common.security.util.SecurityUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Date;
import java.util.Map;

/**
 * @date 2018-09-27
 */
@Service("CheckGaugesService")
public class CheckGaugesServiceImpl extends ServiceImpl<CheckGaugesMapper, CheckGauges> implements CheckGaugesService {

    @Autowired
    private InspectionDataService inspectionDataService;

    private static final String EXTENSION_XLS = "xls";
    private static final String EXTENSION_XLSX = "xlsx";

    @Override
    public IPage getPageScope(Page page, CheckGauges checkGauges) {
        return baseMapper.getListPage(page, checkGauges);
    }

    @Override
    public R excelImport(MultipartFile file, BigInteger checkPlanId, String epc, String tableType, InspectionData inspectionData) {
        if (file == null) {
            //throw new FileFormatException("");
            return R.failed("导入失败，传入文件不存在！");
        }

        //获取原文件
        String originalFileName = file.getOriginalFilename();

        //判断传入文件格式
        if (!(originalFileName.endsWith(EXTENSION_XLS) || originalFileName.endsWith(EXTENSION_XLSX))) {
            //throw new FileFormatException("传入文件不是excel格式!");
            return R.failed("传入文件不是excel格式!");
        }
        Workbook workbook = null;
        try {
            if (originalFileName.endsWith(EXTENSION_XLS)) {
                workbook = new HSSFWorkbook(file.getInputStream());
            } else if (originalFileName.endsWith(EXTENSION_XLSX)) {
                workbook = new XSSFWorkbook(file.getInputStream());
            }

            //读文件
            for (int numSheet = 0; numSheet < workbook.getNumberOfSheets(); numSheet++) {
                org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(numSheet);
                if (sheet == null) {
                    continue;
                }
                int firstRowIndex = sheet.getFirstRowNum();
                int lastRowIndex = sheet.getLastRowNum();
                //读取首行（表头）
                Row firstRow = sheet.getRow(firstRowIndex);
                for (int i = firstRow.getFirstCellNum(); i < firstRow.getLastCellNum(); i++) {
                    Cell cell = firstRow.getCell(i);
                    String cellValue = this.getCellValue(cell, true);
                    System.err.println("表头数据：" + cellValue + "\t");
                }

                System.err.println("开始导入数据...");
                CheckGauges checkGauges = new CheckGauges();
                for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
                    Row currentRow = sheet.getRow(rowIndex);
                    int firstColumnIndex = currentRow.getFirstCellNum(); //首列
                    int lastColumnIndex = currentRow.getLastCellNum(); //尾列
                    boolean s = false;
                    for (int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++) {
                        Cell currentCell = currentRow.getCell(columnIndex);
                        String currentCellValue = this.getCellValue(currentCell, true);
                        System.err.println(" " + currentCellValue + "\t");
                        try {
                            if (columnIndex == firstColumnIndex) {
                                checkGauges.setNum(Integer.valueOf(currentCellValue));
                            }
                            if (columnIndex == firstColumnIndex + 1) {
                                checkGauges.setGaugeName(currentCellValue);
                            }
//                        if (columnIndex == firstColumnIndex + 2) {
//                            checkGauges.setGaugeClass(currentCellValue);
//                        }
//                        if (columnIndex == firstColumnIndex + 3) {
//                            checkGauges.setEnergyClass(currentCellValue);
//                        }
//                        if (columnIndex == firstColumnIndex + 4) {
//                            checkGauges.setEnergyName(currentCellValue);
//                        }
                            if (columnIndex == firstColumnIndex + 2) {
                                checkGauges.setGaugeType(currentCellValue);
                            }
                            if (columnIndex == firstColumnIndex + 3) {
                                checkGauges.setAccuracyLevels(currentCellValue);
                            }
                            if (columnIndex == firstColumnIndex + 4) {
                                checkGauges.setTestRegion(currentCellValue);
                            }
                            if (columnIndex == firstColumnIndex + 5) {
                                checkGauges.setProductFactory(currentCellValue);
                            }
                            if (columnIndex == firstColumnIndex + 6) {
                                checkGauges.setNumFactrory(currentCellValue);
                            }
                            if (columnIndex == firstColumnIndex + 7) {
                                checkGauges.setManagerNum(currentCellValue);
                            }
                            if (columnIndex == firstColumnIndex + 8) {
                                checkGauges.setLocation(currentCellValue);
                            }
                            if (columnIndex == firstColumnIndex + 9) {
                                checkGauges.setCheckTime(currentCellValue);
                            }
                            if (columnIndex == firstColumnIndex + 10) {
                                checkGauges.setGaugeStatus(currentCellValue);
                            }
                        } catch (Exception e) {
                            int col = columnIndex + 1;
                            return R.failed("第" + rowIndex + "行，第" + col + "列发生错误" + e.getMessage());
                        }
                    }
                    checkGauges.setUpdateTime(new Date());
                    checkGauges.setDelFlag("1");
                    ScUser u = SecurityUtils.getUser();
                    checkGauges.setUserid(u.getId());
                    checkGauges.setDeptId(u.getDeptId());
                    checkGauges.setCheckPlanId(checkPlanId);
                    checkGauges.setEpc(epc);

                    if (tableType == null || "".equals(tableType) || "1".equals(tableType)) {
                        checkGauges.setTableType(tableType);
                        inspectionData.setEnergyMeasuringInstruments("Y");
                    } else if ("2".equals(tableType)) {
                        checkGauges.setTableType(tableType);
                        inspectionData.setMeasuringInstruments("Y");
                    } else if ("3".equals(tableType)) {
                        checkGauges.setTableType(tableType);
                        inspectionData.setSecondaryMeasuringInstrument("Y");
                    } else if ("4".equals(tableType)) {
                        checkGauges.setTableType(tableType);
                        inspectionData.setMainMeasuringInstrument("Y");
                    } else if ("5".equals(tableType)) {
                        checkGauges.setTableType(tableType);
                        inspectionData.setOtherMeasuringInstruments("Y");
                    } else {
                        return R.failed("未知的tableType");
                    }

                    this.save(checkGauges);
                    inspectionDataService.updateById(inspectionData); //更新中间表
                }
            }
            return R.ok("导入成功");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            e.printStackTrace();
            return R.failed("导入失败！" + e.getMessage());
        } finally {
            if (workbook != null) {
                try {
                    file.getInputStream().close();
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void updateInspectionData(ScUser u, InspectionData inspectionData) {
        InspectionData newInspectionData = new InspectionData();
        newInspectionData.setEnergyMeasuringInstruments("Y");
        newInspectionData.setCheckPlanId(inspectionData.getCheckPlanId());
        newInspectionData.setEnterpriseCode(inspectionData.getEnterpriseCode());
        newInspectionData.setUpdateTime(new Date());
        newInspectionData.setDelFlag("1");
        inspectionDataService.save(newInspectionData);
    }

    private String getCellValue(Cell cell, boolean b) {
        if (cell == null) {
            return "";
        }
        if (b) {
            //虽然excel中设置的都是文本，但是数字文本还被读错，如“1”取成“1.0”,加上下面这句，临时把它当做文本来读取
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
        if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            return String.valueOf(cell.getNumericCellValue());
        } else {
            return String.valueOf(cell.getStringCellValue());
        }
    }
}

