package com.nantian.cloud.jljc.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.jljc.entity.TFaFixedAssets;
import com.nantian.cloud.jljc.entity.TFaReviewerComment;
import com.nantian.cloud.jljc.mapper.TFaReviewerCommentMapper;
import com.nantian.cloud.jljc.service.TFaReviewerCommentService;
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.Sheet;
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 java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 固定资产投资项目节能审查评审意见汇总 服务实现类
 * </p>
 *
 * @author fyf
 * @since 2022-03-10
 */
@Service
public class TFaReviewerCommentServiceImpl extends ServiceImpl<TFaReviewerCommentMapper, TFaReviewerComment> implements TFaReviewerCommentService {

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


    @Override
    public IPage<TFaReviewerComment> getPage(Page page, TFaReviewerComment tFaReviewerComment, DataScope dataScope) {
        return baseMapper.getPage(page, tFaReviewerComment, new DataScope());
    }

    @Override
    public R excelImport(MultipartFile file) throws IOException {

        if (file == null){
            return R.failed("导入失败，传入文件为空!");
        }

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

        //判断传入文件格式
        if (!(originalFileName.endsWith(EXTENSION_XLS) || originalFileName.endsWith(EXTENSION_XLSX))) {
            throw new FileFormatException("传入文件不是excel格式!");
        }
        Workbook workbook = null;
        ScUser u = SecurityUtils.getUser();
        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++) {

                Sheet sheet = workbook.getSheetAt(numSheet);
                String sheetName = sheet.getSheetName();
                String year = sheetName.substring(0, 4);
                String quarter = sheetName.substring(6,7);
                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("开始导入数据...");
                for (int rowIndex = firstRowIndex + 3; rowIndex <= lastRowIndex; rowIndex++) {
                    Row currentRow = sheet.getRow(rowIndex);
                    int firstColumnIndex = currentRow.getFirstCellNum(); //首列
                    int lastColumnIndex = currentRow.getLastCellNum(); //尾列

                    TFaReviewerComment tFaReviewerComment = new TFaReviewerComment();
                    tFaReviewerComment.setYear(year);
                    tFaReviewerComment.setQuarter(quarter);
                    tFaReviewerComment.setUpdateTime(new Date());
                    tFaReviewerComment.setUserId(u.getId());
                    tFaReviewerComment.setDeptId(u.getDeptId());
                    tFaReviewerComment.setDelFlag(1);
                    tFaReviewerComment.setUserRealName(u.getUserRealName());

                    for (int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++) {
                        Cell currentCell = currentRow.getCell(columnIndex);
                        String currentCellValue = this.getCellValue(currentCell, true);
                        if (columnIndex == firstColumnIndex + 1){
                            if (currentCellValue != null &&  !"". equals(currentCellValue)){
                                tFaReviewerComment.setProjectName(currentCellValue);
                            }else {
                                tFaReviewerComment.setProjectName(null);
                            }
                        }
                        if (columnIndex == firstColumnIndex + 2){
                            tFaReviewerComment.setProjectCode(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 3){
                            tFaReviewerComment.setConstructionUnit(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 4){
                            if (currentCellValue == null || currentCellValue == "" || currentCellValue.isEmpty()){
                                tFaReviewerComment.setIndustryCode(null);
                            }else
                            tFaReviewerComment.setIndustryCode(Integer.valueOf(currentCellValue));
                        }
                        if (columnIndex == firstColumnIndex + 5){
                            tFaReviewerComment.setIndustryName(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 6){
                            if(currentCellValue != null && currentCellValue != "" && !currentCellValue.isEmpty()){
                                if (currentCellValue != null && !"".equals(currentCellValue)){
                                    if (currentCellValue.contains("年")){
                                        tFaReviewerComment.setStartingTime(currentCellValue);
                                    }else {
                                        tFaReviewerComment.setStartingTime(this.int2Date(currentCellValue,"yyyy年MM月"));
                                    }
                                }
                            }
                        }
                        if (columnIndex == firstColumnIndex + 7){
                            tFaReviewerComment.setOrgan(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 8){
                            if (currentCellValue != null && currentCellValue != "" && !currentCellValue.isEmpty()){
                                if (currentCellValue.contains("年")){
                                    tFaReviewerComment.setEndingTime(currentCellValue);
                                }else {
                                    tFaReviewerComment.setEndingTime(this.int2Date(currentCellValue,"yyyy年MM月dd日"));
                                }
                            }
                        }
                        if (columnIndex == firstColumnIndex + 9){
                            tFaReviewerComment.setReferenceNumber(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 10){
                            if (currentCellValue == null || currentCellValue == "" || currentCellValue.isEmpty()){
                                tFaReviewerComment.setEquivalentValue(null);
                            }else
                                tFaReviewerComment.setEquivalentValue(BigDecimal.valueOf(Double.parseDouble(currentCellValue)));
                        }
                        if (columnIndex == firstColumnIndex + 11){
                            if (currentCellValue == null || currentCellValue == "" || currentCellValue.isEmpty()){
                                tFaReviewerComment.setIndifferenceValue(null);
                            }else
                                tFaReviewerComment.setIndifferenceValue(BigDecimal.valueOf(Double.valueOf(currentCellValue)));
                        }
                        if (columnIndex == firstColumnIndex + 12){
                            if (currentCellValue == null || currentCellValue == "" || currentCellValue.isEmpty()){
                                tFaReviewerComment.setIncreEquivalentValue(null);
                            }else
                                tFaReviewerComment.setIncreEquivalentValue(BigDecimal.valueOf(Double.parseDouble(currentCellValue)));
                        }
                        if (columnIndex == firstColumnIndex + 13){
                            if (currentCellValue == null || currentCellValue == "" || currentCellValue.isEmpty()){
                                tFaReviewerComment.setIncreIndifferenceValue(null);
                            }else
                                tFaReviewerComment.setIncreIndifferenceValue(BigDecimal.valueOf(Double.valueOf(currentCellValue)));
                        }
                        if (columnIndex == firstColumnIndex + 14){
                            if (currentCellValue == null || currentCellValue == "" || currentCellValue.isEmpty()){
                                tFaReviewerComment.setEnergyResult(null);
                            }else
                                tFaReviewerComment.setEnergyResult(BigDecimal.valueOf(Double.valueOf(currentCellValue)));
                        }
                        if (columnIndex == firstColumnIndex + 15){
                            if (currentCellValue == null || currentCellValue == "" || currentCellValue.isEmpty()){
                                tFaReviewerComment.setElectricExpend(null);
                            }else
                                tFaReviewerComment.setElectricExpend(BigDecimal.valueOf(Double.valueOf(currentCellValue)));
                        }
                        if (columnIndex == firstColumnIndex + 16){
                            if (currentCellValue == null || currentCellValue == "" || currentCellValue.isEmpty()){
                                tFaReviewerComment.setCoalExpend(null);
                            }else
                                tFaReviewerComment.setCoalExpend(BigDecimal.valueOf(Double.valueOf(currentCellValue)));
                        }
                        if (columnIndex == firstColumnIndex + 17){
                            tFaReviewerComment.setRest(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 18){
                            tFaReviewerComment.setAuthorizedUnit(currentCellValue);
                        }
                    }
                    if (!tFaReviewerComment.getProjectName().isEmpty() && !"".equals(tFaReviewerComment.getProjectName())){
                        this.save(tFaReviewerComment);
                    }
                }
            }
        }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();
                }
            }
            return R.ok("");
        }
    }

    @Override
    public List<TFaReviewerComment> getExcelData(TFaReviewerComment tFaReviewerComment) {

        return baseMapper.getExcelData(tFaReviewerComment);
    }


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

    //excel 导入时数字转日期
    private String int2Date(String item, String dateType) throws ParseException {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sf =new SimpleDateFormat("yyyy/MM/dd");
        SimpleDateFormat sf1 =new SimpleDateFormat(dateType);
        Date parse = sf.parse("1900/01/01");
        int i = Integer.parseInt(item);
        calendar.setTime(parse);
        calendar.add(Calendar.DATE,i-2);
        String format = sf1.format(calendar.getTime());
        return format;
    }
}
