package com.nantian.cloud.jljc.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.google.common.collect.Lists;
import com.nantian.cloud.jljc.dto.AuditorDto;
import com.nantian.cloud.jljc.entity.RecordPersonManager;
import com.nantian.cloud.jljc.mapper.RecordPersonManagerMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nantian.cloud.jljc.service.RecordPersonManagerService;
import com.nantian.cloud.jljc.vo.RecordPersonManagerPOJO;
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 lombok.extern.slf4j.Slf4j;
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.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 备案管理-能源管理人员 服务实现类
 * </p>
 *
 * @author stz
 * @since 2020-09-03
 */
@Service("recordPersonManagerService")
@Slf4j
public class RecordPersonManagerServiceImpl extends ServiceImpl<RecordPersonManagerMapper, RecordPersonManager> implements RecordPersonManagerService {

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

    @Override
    public IPage getCompInfoByCodeAndYear(Page page, String epc, String year) {
       /* IPage compInfoByCodeAndYear = baseMapper.getCompInfoByCodeAndYear(page, epc, year);
        List newRecords = getTypeNameList(compInfoByCodeAndYear.getRecords());
        if(newRecords!=null){
            compInfoByCodeAndYear.setRecords(newRecords);
        }*/
        return baseMapper.getCompInfoByCodeAndYear(page, epc, year);
    }

    @Override
    public IPage getGovInfoByCodeAndYear(Page page,String name, String enterpriseStr, String year, String area, String trade) {
//        baseMapper.getGovInfoByCodeAndYear(page, enterpriseStr, year,parea, area, trade)
        if (area != null) {
            //String s = area.substring(4, 5); //area 530100，截取最后两位
            if (area.contains("00")) { //parea
                return baseMapper.getGovInfoByCodeAndYear(page,name, enterpriseStr, year, area, null, trade, new DataScope());
            } else { //area
                return baseMapper.getGovInfoByCodeAndYear(page,name, enterpriseStr, year, null, area, trade, new DataScope());
            }
        } else {
            return baseMapper.getGovInfoByCodeAndYear(page,name, enterpriseStr, year, null, null, trade, new DataScope());
        }
    }

    @Override
    public RecordPersonManager getPersonById(Long id) {
        //return getTypeName(baseMapper.getPersonById(id));
        return baseMapper.getPersonById(id);
    }

    @Override
    public boolean removeByPersonId(RecordPersonManager recordPersonManager) {
        return baseMapper.removeByPersonId(recordPersonManager);
    }

    @Override
    public boolean updateByAudit(AuditorDto auditorDto) {
        return baseMapper.updateByAudit(auditorDto);
    }

    @Override
    public RecordPersonManager getTypeName(RecordPersonManager recordPersonManager) {
        if (recordPersonManager.getCardType() != null) {
            switch (recordPersonManager.getCardType()) {
                case "1":
                    recordPersonManager.setCardType("身份证");
                    break;
                case "2":
                    recordPersonManager.setCardType("驾驶证");
                    break;
                case "3":
                    recordPersonManager.setCardType("行驶证");
                    break;
                case "4":
                    recordPersonManager.setCardType("社会保障卡");
                    break;
                case "5":
                    recordPersonManager.setCardType("护照");
                    break;
                case "6":
                    recordPersonManager.setCardType("港澳通行证");
                    break;
                default:
                    recordPersonManager.setCardType("其他证件");
                    break;
            }
        }
        return recordPersonManager;
    }

    @Override
    public List<RecordPersonManager> getTypeNameList(List<RecordPersonManager> recordPersonManager) {
        List<RecordPersonManager> newRecord = new ArrayList<>();
        for (RecordPersonManager personManager : recordPersonManager) {
            newRecord.add(getTypeName(personManager));
        }
        return newRecord;
    }

    @Override
    public R excelExport(HttpServletResponse response, String enterpriseStr, String enterpriseCode, String year, String area, String trade) throws Exception {
        OutputStream out = null;
        ExcelWriter writer = null;
        try {
            //List<RecordPersonManagerPOJO> data = this.baseMapper.excelExport(enterpriseStr, enterpriseCode, year, area, trade);
            List<RecordPersonManagerPOJO> data = null;
            if (area != null) {
                //String s = area.substring(4, 5); //area 530100，截取最后两位
                if (area.contains("00")) { //parea
                    data = this.baseMapper.excelExport(enterpriseStr, enterpriseCode, year, area,null, trade);
                } else { //area
                    data = this.baseMapper.excelExport(enterpriseStr, enterpriseCode, year, null,area, trade);
                }
            } else {
                data = this.baseMapper.excelExport(enterpriseStr, enterpriseCode, year, null, null, trade);
            }
            String fileName = new String(String.valueOf(("备案人员信息")).getBytes("UTF-8"), "ISO-8859-1") + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.flushBuffer();
            out = response.getOutputStream();
            writer = new ExcelWriter(out, ExcelTypeEnum.XLSX);
            List<List<RecordPersonManagerPOJO>> lt = Lists.partition(data, 60000);
            for (int i = 0; i < lt.size(); i++) {
                Sheet sheet = new Sheet((i + 1), 0, RecordPersonManagerPOJO.class, "sheet" + (i + 1), null);
                writer.write(lt.get(i), sheet);
            }
            data.clear();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            out.flush();
            writer.finish();
            out.close();
        }
        return R.ok("导出系统列表EXCEL成功");
    }

    @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);
                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("开始导入数据...");
                RecordPersonManager recordPersonManager = new RecordPersonManager();
                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);
                        System.err.println(" " + currentCellValue + "\t");
                        /*if (columnIndex == firstColumnIndex) {
                            recordPersonManager.setEpc(currentCellValue);
                        }*/
                        recordPersonManager.setEpc(u.getEnterpriseCode());
                        if (columnIndex == firstColumnIndex ) {
                            recordPersonManager.setName(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 1) {
                            recordPersonManager.setPhone(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 2) {
                            recordPersonManager.setDuties(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 3) {
                            recordPersonManager.setCardType(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 4) {
                            recordPersonManager.setCardCode(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 5) {
                            recordPersonManager.setWorkExperience(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 6) {
                            recordPersonManager.setProfile(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 7) {
                            recordPersonManager.setYear(currentCellValue);
                        }
                        if (columnIndex == firstColumnIndex + 8) {
                            recordPersonManager.setRemark(currentCellValue);
                        }
                        recordPersonManager.setUpdateDate(new Date());
                        recordPersonManager.setDeleteFlag("1");
                    }
                    this.save(recordPersonManager);
                }
            }
            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();
                }
            }
        }
    }

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