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.dto.TTrainingDto;
import com.nantian.cloud.jljc.entity.TTraining;
import com.nantian.cloud.jljc.mapper.TTrainingMapper;
import com.nantian.cloud.jljc.mapper.TTrainingPersonMapper;
import com.nantian.cloud.jljc.service.TTrainingService;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;


@Service("tTrainingService")
public class TTrainingServiceImpl extends ServiceImpl<TTrainingMapper, TTraining> implements TTrainingService {

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

    @Autowired
    private TTrainingMapper tTrainingMapper;

    @Autowired
    private TTrainingPersonMapper tTrainingPersonMapper;

    @Override
    public Object getInfoByKeyWord(String name) {
        if (name.isEmpty()){
            return null;
        }
        Object obj = tTrainingMapper.getInfoByKeyWord(name);
        return obj;
    }


    @Override
    public IPage<TTrainingDto> pageInfo(Page page, TTraining tTraining) {

        //查询出培训信息
       IPage<TTrainingDto> tTrainingDto = tTrainingMapper.getPage(page,tTraining,new DataScope());
        List<TTrainingDto> newDtoList = tTrainingDto.getRecords();
        List<TTrainingDto> list = new ArrayList<>();
        for (TTrainingDto trainingDto : newDtoList) {
            Integer id=trainingDto.getId();
            //根据ID去获取培训内容下的培训人数
          Integer count =  tTrainingPersonMapper.getCountById(id);
            trainingDto.setCount(count);
            list.add(trainingDto);
        }
        IPage<TTrainingDto> page1 = new Page<>();
        page1.setCurrent(tTrainingDto.getCurrent());
        page1.setSize(tTrainingDto.getSize());
        page1.setRecords(list);
        page1.setTotal(tTrainingDto.getTotal());

        return page1;
    }

    @Override
    public R excelImport(MultipartFile file) 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());
            }

            //读文件
            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);
                if(firstRow == null){
                    continue;
                }
                for (int i = firstRow.getFirstCellNum(); i < firstRow.getLastCellNum(); i++) {
                    System.err.println(i + " "+firstRow.getLastCellNum());
                    Cell cell = firstRow.getCell(i);
                    String cellValue = this.getCellValue(cell, true);
                    System.err.println("表头数据：" + cellValue + "\t");
                }

                System.err.println("开始导入数据...");
                List<TTraining> list = new ArrayList<>();
                for (int rowIndex = firstRowIndex+1 ; rowIndex <= lastRowIndex; rowIndex++) {
                    Row currentRow = sheet.getRow(rowIndex);
                    for (int i=0;i<firstRow.getLastCellNum();i++){
                        if (currentRow.getCell(i)==null)
                            currentRow.createCell(i).setCellValue("");
                    }
                    int firstColumnIndex = currentRow.getFirstCellNum(); //数据首列
                    int lastColumnIndex = currentRow.getLastCellNum(); //尾列
                    boolean s = false;
                    TTraining tTraining = new TTraining();
                    ScUser u = SecurityUtils.getUser();
                    int num = currentRow.getRowNum();
                    for (int columnIndex = firstColumnIndex; columnIndex < lastColumnIndex; columnIndex++) {

                        Cell currentCell = currentRow.getCell(columnIndex);
                        String currentCellValue = this.getCellValue(currentCell, true);
                        System.err.println(firstColumnIndex+" "+columnIndex+" " + currentCellValue + "\t");
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        if (columnIndex == firstColumnIndex ) {
                            if(currentCellValue==""){
                                return R.failed("第"+rowIndex+"行的培训名称为空，请输入培训名称");
                            }else {
                                tTraining.setName(currentCellValue);
                            }
                        }
                        if (columnIndex == firstColumnIndex + 1) {
                            tTraining.setContent(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 2) {
                            tTraining.setAddress(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 3) {
                            tTraining.setStartTime(sdf.parse(currentCellValue));
                        }
                        if (columnIndex == firstColumnIndex + 4) {
                            tTraining.setEndTime(sdf.parse(currentCellValue));
                        }
                        if (columnIndex == firstColumnIndex + 5) {
                            tTraining.setStartSignUpTime(sdf.parse(currentCellValue));
                        }
                        if (columnIndex == firstColumnIndex + 6) {
                            tTraining.setEndSignUpTime(sdf.parse(currentCellValue));
                        }

                    }
                    //tTraining.setTrainingId(56);
                    tTraining.setUserid(u.getId());
                    tTraining.setDeptId(u.getDeptId());
                    tTraining.setState("0");
                    tTraining.setDelFlag("1");
                    list.add(tTraining);
                }
                this.saveBatch(list);
            }
            return R.ok("导入成功");
        } catch (Exception e) {
            System.err.println(e.toString());
            e.printStackTrace();
            return R.failed("导入失败！" + e.getMessage());
        } finally {
            if (workbook != null) {
                try {
                    file.getInputStream().close();
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

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

}
