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

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
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.CompanyCalculater;
import com.nantian.cloud.jly.entity.ConfigureGauge;
import com.nantian.cloud.jly.mapper.CheckGaugesMapper;
import com.nantian.cloud.jly.mapper.ConfigureGaugeMapper;
import com.nantian.cloud.jly.service.ConfigureGaugeService;
import com.nantian.cloud.jly.vo.StatisticsVo;
import com.nantian.sc.cloud.common.core.util.R;
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.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @date 2018-09-27
 */
@Service("configureGaugeService")
public class ConfigureGaugeServiceImpl extends ServiceImpl<ConfigureGaugeMapper, ConfigureGauge> implements ConfigureGaugeService {
    private static final String EXTENSION_XLS = "xls";
    private static final String EXTENSION_XLSX = "xlsx";

    @Resource
    private ConfigureGaugeMapper configureGaugeMapper;

    public List<StatisticsVo> getGaugesStatistics() {
        return configureGaugeMapper.getGaugesStatistics();
    }

    public IPage getPageData(Page page, String areaCodes, String industryCode, String cmpName, String meterLevel, String cmp, String location, String type) {
        String code = "";
        int flag = 0;
        if (areaCodes != null) {
            String[] codeList = areaCodes.split(",");
            flag = codeList.length;
            code = codeList[flag - 1];
        }
        return configureGaugeMapper.getPageData(page, code, flag, industryCode, cmpName, meterLevel, cmp, location, type);
    }

    @Override
    public IPage<ConfigureGauge> pageCmp(Page page, ConfigureGauge configureGauge) {
        return baseMapper.pageCmp(page, configureGauge);
    }

    @Override
    public R excelImport(MultipartFile file, String epc, String meterLevel) throws FileFormatException {
        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格式!");
        }
        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());
            }
            ScUser user = SecurityUtils.getUser();

            //读文件
            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("开始导入数据...");
                ConfigureGauge configureGauge = new ConfigureGauge();
                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");
                        if (columnIndex == firstColumnIndex) {

                        }
                        if (currentCellValue == null || currentCellValue.equals(""))
                            continue;
                        if (columnIndex == firstColumnIndex + 1) {
                            configureGauge.setMeterName(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 2) {
                            configureGauge.setMeterType(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 3) {
                            String l = currentCellValue;
                            if (currentCellValue.equals("进出用能计量器具")){
                                l="1";
                            }
                            if (currentCellValue.equals("主要次级用能计量器具")){
                                l="2";
                            }
                            if (currentCellValue.equals("主要用能设备计量器具")){
                                l="3";
                            }
                            if (currentCellValue.equals("进出用能计量器具、主要次级用能计量器具")){
                                l="12";
                            }
                            if (currentCellValue.equals("进出用能计量器具、主要用能设备计量器具")){
                                l="13";
                            }
                            if (currentCellValue.equals("主要次级用能计量器具、主要用能设备计量器具")){
                                l="23";
                            }
                            if (currentCellValue.equals("进出用能计量器具、主要次级用能计量器具、主要用能设备计量器具")){
                                l="123";
                            }
                            configureGauge.setMeterLevel(l);
                        }
                        if (columnIndex == firstColumnIndex + 4) {
                            configureGauge.setManufacturer(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 5) {
                            configureGauge.setModel(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 6) {
                            configureGauge.setPrecisionLevel(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 7) {
                            configureGauge.setRanges(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 8) {
                            configureGauge.setManageNo(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 9) {
                            configureGauge.setLocation(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 10) {
                            String installerData = currentCellValue;
                            if (currentCellValue.equals("用能单位")){
                                installerData="1";
                            }
                            if (currentCellValue.equals("能源供应公司")){
                                installerData="2";
                            }
                            if (currentCellValue.equals("第三方公司")){
                                installerData="3";
                            }
                            configureGauge.setInstaller(installerData);
                        }
                        if (columnIndex == firstColumnIndex + 11) {
                            configureGauge.setInstallTime(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 12) {
                            String setAlignStateData = currentCellValue;
                            if (currentCellValue.equals("不合格")){
                                setAlignStateData="0";
                            }
                            if (currentCellValue.equals("合格")){
                                setAlignStateData="1";
                            }
                            configureGauge.setAlignState(setAlignStateData);
                        }
                        if (columnIndex == firstColumnIndex + 13) {
                            configureGauge.setAlignCycle(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 14) {
                            configureGauge.setLastAlignDate(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 15) {
                            configureGauge.setNextAlignDate(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 16) {
                            configureGauge.setAlignOrg(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 17) {
                            configureGauge.setUnAlignReason(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 18) {
                            configureGauge.setLinkSys(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 19) {
                            configureGauge.setCurrentState(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 20) {
                            configureGauge.setStateChangeTime(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 21) {
                            configureGauge.setSerNo(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 22) {
                            configureGauge.setParams(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 23) {
                            configureGauge.setDataCode(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 24) {
                            configureGauge.setRemark(currentCellValue);
                        }
//                        if (columnIndex == firstColumnIndex + 1) {
//                            configureGauge.setMeterName(currentCellValue);
//
//                        }
//                        if (columnIndex == firstColumnIndex + 2) {
//                            configureGauge.setModel(currentCellValue);
//
//                        }
//                        if (columnIndex == firstColumnIndex + 3) {
//                            configureGauge.setPrecisionLevel(currentCellValue);
//
//                        }
//                        if (columnIndex == firstColumnIndex + 4) {
//                            configureGauge.setRanges(currentCellValue);
//
//                        }
//                        if (columnIndex == firstColumnIndex + 5) {
//                            configureGauge.setManufacturer(currentCellValue);
//
//                        }
//                        if (columnIndex == firstColumnIndex + 6) {
//                            configureGauge.setSerNo(currentCellValue);
//
//                        }
//                        if (columnIndex == firstColumnIndex + 7) {
//                            configureGauge.setManageNo(currentCellValue);
//
//                        }
//                        if (columnIndex == firstColumnIndex + 8) {
//                            configureGauge.setLocation(currentCellValue);
//
//
//                        }
//                        if (columnIndex == firstColumnIndex + 9) {
//                            configureGauge.setAlignCycle(currentCellValue);
//
//                        }
//                        if (columnIndex == firstColumnIndex + 10) {
//                            configureGauge.setState(currentCellValue);
//
//                        }
                        configureGauge.setUpdateTime(new Date());
                        configureGauge.setDelFlag("1");
                        configureGauge.setDeptId(user.getDeptId());
                        configureGauge.setUserid(user.getId());
                        configureGauge.setEnterpriseCode(epc);
//                        configureGauge.setMeterLevel(meterLevel);
                    }
                    if (!configureGauge.getEnterpriseCode().equals(""))
                        this.save(configureGauge);
                }
            }
            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 Integer getNotCertified(String enterpriseCode) {
        return baseMapper.getNotCertified(enterpriseCode);
    }

    @Override
    public List<ConfigureGauge> getList(String epc) {
        return baseMapper.getList(epc);
    }

    @Override
    public void updateConfigureGaugeState() {
        this.baseMapper.updateConfigureGaugeState();
    }

    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());
        }
    }

}

