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


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.TTraining;
import com.nantian.cloud.jljc.entity.TTrainingPerson;
import com.nantian.cloud.jljc.mapper.TTrainingMapper;
import com.nantian.cloud.jljc.mapper.TTrainingPersonMapper;
import com.nantian.cloud.jljc.service.TTrainingPersonService;
import com.nantian.cloud.jljc.vo.TTrainingPersonVo;
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.Date;
import java.util.List;


@Service("tTrainingPersonService")
public class TTrainingPersonServiceImpl extends ServiceImpl<TTrainingPersonMapper, TTrainingPerson> implements TTrainingPersonService {

    @Autowired
    private TTrainingPersonMapper tTrainingPersonMapper;
    @Autowired
    private TTrainingServiceImpl trainingService;
    private static final String EXTENSION_XLS = "xls";
    private static final String EXTENSION_XLSX = "xlsx";

    @Autowired
    TTrainingMapper tTrainingMapper;
    @Override
    public IPage getTrainingId(Page page, Integer trainingId, Integer current, Integer size){
        if(trainingId==null){
            return null;
        }
        return null;
    }


    @Override
    public List<TTrainingPerson> getInfo(String enterpriseName, String name, Date updateTime) {
        //如果name 为空，就不需要查询trainingId
         //根据培训名称获取培训的ID
        List list=new ArrayList();
        if (name!=null) {
            List<TTraining> trainingList = tTrainingMapper.getTrainingIdByName(name);
            for (TTraining tTraining : trainingList) {
                Integer trainingId = tTraining.getId();
                //根据条件查询
                List personList = tTrainingPersonMapper.getInfoT(enterpriseName, trainingId, updateTime);

                list.add(personList);
            }
        }
        if (enterpriseName!=null){
            //根据单位名称模糊查询培训trainingId
            List<TTrainingPerson> list1=tTrainingPersonMapper.getInfoByBrainingId(enterpriseName);
            for (TTrainingPerson tTrainingPerson : list1) {
                Integer id = tTrainingPerson.getTrainingId();
                //根据trainingId = ID 去获取数据信息
                List perList=tTrainingPersonMapper.getInfoById(enterpriseName,id,updateTime);
                list.add(perList);

            }
        }
        List<TTrainingPerson> tTrainingPersonList= tTrainingPersonMapper.getInfoBy(enterpriseName,updateTime);
        list.add(tTrainingPersonList);


        return list;

    }



    @Override
    public Object getCount(Integer trainingId) {
        return tTrainingPersonMapper.getCount(trainingId);
    }


    /**
     * 查询报名的人员基本情况
     * @param territorial
     * @param enterpriseName
     * @param name
     * @return
     */
    @Override
    public Object getPersonInfo(String territorial, String enterpriseName, String name,String trainingId) {
        return  tTrainingPersonMapper.getPersonInfo(territorial,enterpriseName,name,trainingId);

    }


    /**
     * 根据ID查询人员信息
     * @param id
     * @return
     */
    @Override
    public List<TTrainingPerson> getPerson(String id) {

        if (id.isEmpty()){
            return null;
        }
        List<TTrainingPerson> personList = tTrainingPersonMapper.getPerson(id);
        return personList;
    }

    @Override
    public IPage<TTrainingPersonVo> pageByScope(Page page, TTrainingPerson tTrainingPerson) {
        return baseMapper.pageByScope(page,tTrainingPerson,new DataScope());
    }

    /**
     * 查询企业报名人员信息，培训信息
     * @param userid
     * @return
     */
    @Override
    public IPage<TTrainingPersonVo> getTrainingPersonInfo(Page page, Integer userid,String year,String trainingName){
        return baseMapper.getTrainingPersonInfo(page,userid,year,trainingName);
    }

    @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<TTrainingPerson> 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;
                    TTrainingPerson tTrainingPerson = new TTrainingPerson();
                    ScUser u = SecurityUtils.getUser();
                    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");

                        if (columnIndex == firstColumnIndex ) {
                            tTrainingPerson.setName(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 1) {
                            tTrainingPerson.setSex(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 2) {
                            tTrainingPerson.setEthnic(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 3) {
                            tTrainingPerson.setEnterpriseName(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 4) {
                            tTrainingPerson.setJobTitle(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 5) {
                            if(currentCellValue==""){
                                return R.failed("第"+rowIndex+"行的培训名称为空，请输入培训名称");
                            }else {
                                TTraining tTraining=trainingService.getOne(new QueryWrapper<>(new TTraining())
                                        .eq("name",currentCellValue)
                                        .eq("del_flag","1"));
                                if (tTraining!=null){
                                    tTrainingPerson.setTrainingId(tTraining.getId());
                                }else {
                                    return R.failed("未查询到第"+rowIndex+"行的培训名称为"+currentCellValue+"的培训,确认培训名称是否正确");
                                }
                            }
                        }
                        if (columnIndex == firstColumnIndex + 6) {
                            tTrainingPerson.setTelephone(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 7) {
                            tTrainingPerson.setLocation(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 8) {
                            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            tTrainingPerson.setUpdateTime(sdf.parse(currentCellValue));
                        }if (columnIndex == firstColumnIndex + 9) {
                            tTrainingPerson.setRemarks(currentCellValue);
                        }
                    }
                    tTrainingPerson.setUserid(u.getId());
                    tTrainingPerson.setDeptId(u.getDeptId());
                    tTrainingPerson.setState("0");
                    tTrainingPerson.setDelFlag("1");
                    list.add(tTrainingPerson);
                }
                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());
        }
    }


}
