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

import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
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.google.common.collect.Lists;
import com.nantian.cloud.jly.entity.CompanyCalculater;
import com.nantian.cloud.jly.mapper.CompanyCalculaterMapper;
import com.nantian.cloud.jly.service.CompanyCalculaterService;
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.apache.xmlbeans.impl.piccolo.io.FileFormatException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @date 2018-09-27
 */
@Service("companyCalculaterService")
public class CompanyCalculaterServiceImpl extends ServiceImpl<CompanyCalculaterMapper, CompanyCalculater> implements CompanyCalculaterService {

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

    @Resource
    private CompanyCalculaterMapper companyCalculaterMapper;

    public List<Map> getCaculaterStatistics() {
        return companyCalculaterMapper.getCaculaterStatistics();
    }

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

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

    @Override
    public R excelImport(MultipartFile file,String epc) 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("开始导入数据...");
                CompanyCalculater companyCalculater = new CompanyCalculater();
                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) {
                            companyCalculater.setCalculaterName(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 1) {
                            companyCalculater.setDept(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 2) {
                            companyCalculater.setJob(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 3) {
                            companyCalculater.setTechnicalPost(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 4) {
                            companyCalculater.setExam(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 5) {
                            companyCalculater.setCertificateNo(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 6) {
                            companyCalculater.setRemark(currentCellValue);
                        }
//                        if (columnIndex == firstColumnIndex + 7) {
//                            companyCalculater.setCertificateName(currentCellValue);
//                        }
//                        if (columnIndex == firstColumnIndex + 8) {
//                            companyCalculater.setCertificateNo(currentCellValue);
//                        }
//                        if (columnIndex == firstColumnIndex + 9) {
//                            companyCalculater.setRemark(currentCellValue);
//                        }
                        companyCalculater.setUpdateTime(new Date());
                        companyCalculater.setDelFlag("1");
                        companyCalculater.setDeptId(user.getDeptId());
                        companyCalculater.setUserid(user.getId());
                        companyCalculater.setEnterpriseCode(epc);
                    }
                    this.save(companyCalculater);
                }
            }
            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 IPage<CompanyCalculater> selectByCmp(Page page, CompanyCalculater companyCalculater) {
        return companyCalculaterMapper.selectByCmp(page,companyCalculater);
    }

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


}

