package com.chinaweal.aiccs.crgs.transfor.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chinaweal.aiccs.common.constant.Constant;
import com.chinaweal.aiccs.common.util.ExcelUtil;
import com.chinaweal.aiccs.common.util.StringUtils;
import com.chinaweal.aiccs.crgs.transfor.entity.OtNpermitDownloadLog;
import com.chinaweal.aiccs.crgs.transfor.entity.dto.StatisticLoadDto;
import com.chinaweal.aiccs.crgs.transfor.mapper.OtNpermitDownloadLogMapper;
import com.chinaweal.aiccs.crgs.transfor.service.OtNpermitDownloadLogService;
import com.chinaweal.youfool.framework.springboot.mybatis.plus.BaseServiceImpl;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 行政许可信息下载清单记录 服务实现类
 * </p>
 *
 * @author <a href="https://blog.lroyia.top">lroyia</a>
 * @since 2021-11-05
 */
@Service
public class OtNpermitDownloadLogServiceImpl extends BaseServiceImpl<OtNpermitDownloadLogMapper, OtNpermitDownloadLog> implements OtNpermitDownloadLogService {

    @Override
    @Transactional
    public List<OtNpermitDownloadLog> saveDownloadData(File file) throws IOException {
        POIFSFileSystem poifsFileSystem = new POIFSFileSystem(file);
        HSSFWorkbook workbook = new HSSFWorkbook(poifsFileSystem);
        HSSFSheet sheetAt = workbook.getSheetAt(0);
        List<OtNpermitDownloadLog> result = new ArrayList<>();
        String filePath = file.getAbsolutePath();
        for (int i = 2; i < sheetAt.getPhysicalNumberOfRows(); i++) {
            OtNpermitDownloadLog atom = new OtNpermitDownloadLog();
            HSSFRow row = sheetAt.getRow(i);
            atom.setFilepath(filePath);
            atom.setLicid(ExcelUtil.getCellValue(row.getCell(0)));
            atom.setRegno(ExcelUtil.getCellValue(row.getCell(1)));
            atom.setUniscid(ExcelUtil.getCellValue(row.getCell(2)));
            atom.setEntname(ExcelUtil.getCellValue(row.getCell(3)));
            atom.setLicno(ExcelUtil.getCellValue(row.getCell(4)));
            atom.setLicnameCn(ExcelUtil.getCellValue(row.getCell(5)));
            atom.setValfrom(ExcelUtil.getCellValue(row.getCell(6)));
            atom.setValto(ExcelUtil.getCellValue(row.getCell(7)));
            atom.setLicanth(ExcelUtil.getCellValue(row.getCell(8)));
            atom.setLicitem(ExcelUtil.getCellValue(row.getCell(9)));
            atom.setType(ExcelUtil.getCellValue(row.getCell(10)));
            atom.setCandate(ExcelUtil.getCellValue(row.getCell(11)));
            atom.setEquplecanrea(ExcelUtil.getCellValue(row.getCell(12)));
            atom.setRevdate(ExcelUtil.getCellValue(row.getCell(13)));
            atom.setSugrevreason(ExcelUtil.getCellValue(row.getCell(14)));
            atom.setInvaliddate(ExcelUtil.getCellValue(row.getCell(15)));
            atom.setInvalidrea(ExcelUtil.getCellValue(row.getCell(16)));
            atom.setDatadept(ExcelUtil.getCellValue(row.getCell(17)));
            atom.setUploadprov(ExcelUtil.getCellValue(row.getCell(18)));
            atom.setTargetprov(ExcelUtil.getCellValue(row.getCell(19)));
            atom.setOpflag(ExcelUtil.getCellValue(row.getCell(20)));
            result.add(atom);
            saveOrUpdate(atom);
        }
        poifsFileSystem.close();
        return result;
    }


    @Override
    public HSSFWorkbook download(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<OtNpermitDownloadLog> list = listByIds(idList);
        HSSFWorkbook workbook = renderBook(list);
        update(new OtNpermitDownloadLog().setIsDownload(Constant.TRUE_1_STR),
                new LambdaQueryWrapper<OtNpermitDownloadLog>().in(OtNpermitDownloadLog::getLicid, idList));
        return workbook;
    }

    @Override
    public List<StatisticLoadDto> statisticDownloadCount(String startDate, String endDate) {
        return baseMapper.statisticDownloadCount(startDate, endDate);
    }

    /**
     * 行政处罚信息查询结果
     *
     * @param list 数据列表
     * @return 渲染结果
     * @author lroyia
     * @since 2021年11月3日 15:13:17
     */
    private HSSFWorkbook renderBook(List<OtNpermitDownloadLog> list) {
        HSSFWorkbook workbook = new HSSFWorkbook();

        // 样式设置
        HSSFCellStyle style = getDefaultStyle(workbook);

        // 设置表头
        HSSFSheet sheet = workbook.createSheet("行政许可信息");
        HSSFRow headerRow = sheet.createRow(0);
        HSSFRow enHeaderRow = sheet.createRow(0);
        String[] headers = {"许可ID", "注册号", "统一社会信用代码", "企业（机构）名称", "许可文件编号",
                "许可文件名称（中文名称）", "有效期自", "有效期至", "许可机关", "许可内容", "状态", "注销日期",
                "注销原因", "吊销日期", "吊销原因", "其它无效日期", "其它无效原因", "数据来源单位",
                "数据上报省/市", "数据目标省/市", "操作标识"};
        String[] enHeaders = {"LICID", "REGNO", "UNISCID", "ENTNAME", "LICNO", "LICNAME_CN", "VALFROM", "VALTO"
                , "LICANTH", "LICITEM", "TYPE", "CANDATE", "EQUPLECANREA", "REVDATE", "SUGREVREASON", "INVALIDDATE"
                , "INVALIDREA", "DATADEPT", "UPLOADPROV", "TARGETPROV", "OPFLAG"};
        for (int i = 0; i < headers.length; i++) {
            HSSFCell cell = headerRow.createCell(i);
            HSSFCell enCell = enHeaderRow.createCell(i);
            setCellValue(cell, headers[i], style);
            setCellValue(enCell, enHeaders[i], style);
            sheet.setColumnWidth(i, 32 * 256);
        }

        // 设置数据
        int offset = 1;
        for (int i = 0; i < list.size(); i++) {
            OtNpermitDownloadLog each = list.get(i);
            HSSFRow row = sheet.createRow(i + offset);
            row.setHeightInPoints(28f);
            setCellValue(row.createCell(0), each.getLicid(), style); //许可ID
            setCellValue(row.createCell(1), each.getRegno(), style); // 注册号
            setCellValue(row.createCell(2), each.getUniscid(), style); //统一社会信用代码
            setCellValue(row.createCell(3), each.getEntname(), style);//企业（机构）名称
            setCellValue(row.createCell(4), each.getLicno(), style);//许可文件编号
            setCellValue(row.createCell(5), each.getLicnameCn(), style);//许可文件名称（中文名称）
            setCellValue(row.createCell(6), each.getValfrom(), style);//有效期自
            setCellValue(row.createCell(7), each.getValto(), style);//有效期至
            setCellValue(row.createCell(8), each.getLicanth(), style);//许可机关
            setCellValue(row.createCell(9), each.getLicitem(), style);//许可内容
            setCellValue(row.createCell(10), each.getType(), style);//许可内容
            setCellValue(row.createCell(11), each.getCandate(), style);//许可内容
            setCellValue(row.createCell(12), each.getEquplecanrea(), style);//许可内容
            setCellValue(row.createCell(13), each.getRevdate(), style);//许可内容
            setCellValue(row.createCell(14), each.getSugrevreason(), style);//许可内容
            setCellValue(row.createCell(15), each.getInvaliddate(), style);//许可内容
            setCellValue(row.createCell(16), each.getInvalidrea(), style);//许可内容
            setCellValue(row.createCell(17), each.getDatadept(), style);//数据来源单位
            setCellValue(row.createCell(18), each.getUploadprov(), style);//数据来源单位
            setCellValue(row.createCell(19), each.getTargetprov(), style);//数据来源单位
            setCellValue(row.createCell(20), each.getOpflag(), style);//数据来源单位
        }
        return workbook;
    }

    /**
     * 样式设置
     *
     * @param workbook 文件类
     * @return 样式对象
     * @author lroyia
     * @since 2021年11月3日 15:17:45
     */
    private HSSFCellStyle getDefaultStyle(HSSFWorkbook workbook) {
        HSSFCellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setFontName("微软雅黑");
        font.setFontHeightInPoints((short) 16);
        style.setFont(font);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        return style;
    }

    /**
     * 设置单元格的值
     *
     * @param cell  单元格
     * @param value 数值
     * @param style 样式
     * @author lroyia
     * @since 2021年11月3日 15:31:40
     */
    private void setCellValue(Cell cell, Object value, CellStyle style) {
        cell.setCellStyle(style);
        if (value == null) return;
        if (value instanceof BigDecimal) {
            cell.setCellValue(((BigDecimal) value).stripTrailingZeros().toPlainString());
        } else if (value instanceof LocalDateTime) {
            LocalDateTime localDateTime = (LocalDateTime) value;
            cell.setCellValue(localDateTime.format(DateTimeFormatter.ofPattern("yyyy/MM/dd")));
        } else if (value instanceof String) {
            cell.setCellValue(StringUtils.tranObject(value));
        }
    }
}
