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

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nantian.cloud.jljc.entity.RecordPersonManager;
import com.nantian.cloud.jljc.entity.TFaFixedAssets;
import com.nantian.cloud.jljc.mapper.TFaFixedAssetsMapper;
import com.nantian.cloud.jljc.service.TFaFixedAssetsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantian.cloud.jljc.vo.TFaProjectVO;
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.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 固定资产投资项目节能审查企业项目表 服务实现类
 * </p>
 *
 * @author fyf
 * @since 2022-02-15
 */
@Service
public class TFaFixedAssetsServiceImpl extends ServiceImpl<TFaFixedAssetsMapper, TFaFixedAssets> implements TFaFixedAssetsService {

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

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

    @Override
    public IPage<TFaProjectVO> getProjectInfo(Page page, TFaFixedAssets tFaFixedAssets, DataScope dataScope) {

        return baseMapper.getProjectInfo(page, tFaFixedAssets,new DataScope());
    }

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

        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;
        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);
                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("开始导入数据...");
                TFaFixedAssets tFaFixedAssets = new TFaFixedAssets();
                for (int rowIndex = firstRowIndex + 1; rowIndex <= lastRowIndex; rowIndex++) {
                    Row currentRow = sheet.getRow(rowIndex);
                    int firstColumnIndex = currentRow.getFirstCellNum(); //首列
                    int lastColumnIndex = currentRow.getLastCellNum(); //尾列
                    boolean s = false;

                    ScUser u = SecurityUtils.getUser();
                    for (int columnIndex = firstColumnIndex; columnIndex <= lastColumnIndex; columnIndex++) {
                        Cell currentCell = currentRow.getCell(columnIndex);
                        String currentCellValue = this.getCellValue(currentCell, true);

                        tFaFixedAssets.setUpdateTime(new Date());
                        tFaFixedAssets.setUserId(u.getId());
                        tFaFixedAssets.setDeptId(u.getDeptId());
                        tFaFixedAssets.setDelFlag(1);
                        tFaFixedAssets.setProjectStatus(1);
                        tFaFixedAssets.setStatusData(9);
                        if (columnIndex == firstColumnIndex){
                            tFaFixedAssets.setProjectName(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 1){
                            tFaFixedAssets.setProjectAddr(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 2){
                            tFaFixedAssets.setProjectLeader(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 3){
                            tFaFixedAssets.setTel(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 4){
                            tFaFixedAssets.setAffiliatedCompanies(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 5){
                            tFaFixedAssets.setIndustry(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 6){
                            tFaFixedAssets.setProjectTime(currentCellValue);
                        }
                    }
                    this.save(tFaFixedAssets);
                }
            }
        }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("");
        }
    }

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