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.OtNcaseDownloadLog;
import com.chinaweal.aiccs.crgs.transfor.entity.dto.StatisticLoadDto;
import com.chinaweal.aiccs.crgs.transfor.mapper.OtNcaseDownloadLogMapper;
import com.chinaweal.aiccs.crgs.transfor.service.OtNcaseDownloadLogService;
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 OtNcaseDownloadLogServiceImpl extends BaseServiceImpl<OtNcaseDownloadLogMapper, OtNcaseDownloadLog> implements OtNcaseDownloadLogService {

    @Override
    @Transactional
    public List<OtNcaseDownloadLog> saveDownloadData(File file) throws IOException {
        POIFSFileSystem poifsFileSystem = new POIFSFileSystem(file);
        HSSFWorkbook workbook = new HSSFWorkbook(poifsFileSystem);
        HSSFSheet sheetAt = workbook.getSheetAt(0);
        String filePath = file.getAbsolutePath();
        List<OtNcaseDownloadLog> result = new ArrayList<>();
        for (int i = 2; i < sheetAt.getPhysicalNumberOfRows(); i++) {
            OtNcaseDownloadLog atom = new OtNcaseDownloadLog();
            HSSFRow row = sheetAt.getRow(i);
            atom.setFilepath(filePath);
            atom.setCaseid(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.setPendecno(ExcelUtil.getCellValue(row.getCell(4)));
            atom.setIllegacttype(ExcelUtil.getCellValue(row.getCell(5)));
            atom.setPentype(ExcelUtil.getCellValue(row.getCell(6)));
            atom.setPentypeCn(ExcelUtil.getCellValue(row.getCell(7)));
            atom.setPenam(ExcelUtil.getCellValue(row.getCell(8)));
            atom.setForfam(ExcelUtil.getCellValue(row.getCell(9)));
            atom.setPencontent(ExcelUtil.getCellValue(row.getCell(10)));
            atom.setJudauth(ExcelUtil.getCellValue(row.getCell(11)));
            atom.setPendecissdate(ExcelUtil.getCellValue(row.getCell(12)));
            atom.setRemark(ExcelUtil.getCellValue(row.getCell(13)));
            atom.setPublicDate(ExcelUtil.getCellValue(row.getCell(14)));
            atom.setDatadept(ExcelUtil.getCellValue(row.getCell(15)));
            atom.setUploadprov(ExcelUtil.getCellValue(row.getCell(16)));
            atom.setTargetprov(ExcelUtil.getCellValue(row.getCell(17)));
            atom.setOpflag(ExcelUtil.getCellValue(row.getCell(18)));
            saveOrUpdate(atom);
            result.add(atom);
        }
        poifsFileSystem.close();
        return result;
    }


    @Override
    public HSSFWorkbook download(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<OtNcaseDownloadLog> list = listByIds(idList);
        HSSFWorkbook workbook = renderBook(list);
        update(new OtNcaseDownloadLog().setIsDownload(Constant.TRUE_1_STR),
                new LambdaQueryWrapper<OtNcaseDownloadLog>().in(OtNcaseDownloadLog::getCaseid, 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<OtNcaseDownloadLog> list) {
        HSSFWorkbook workbook = new HSSFWorkbook();

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

        // 设置表头
        HSSFSheet sheet = workbook.createSheet("行政处罚信息");
        HSSFRow headerRow = sheet.createRow(0);
        HSSFRow enHeaderRow = sheet.createRow(1);
        String[] headers = {"行政处罚ID", "注册号", "统一社会信用代码", "企业（机构）名称", "处罚决定书文号", "违法行为类型", "处罚种类"
                , "处罚种类（中文名称）", "罚款金额", "没收金额", "处罚内容", "作出行政处罚决定机关名称", "作出处罚决定书日期", "备注"
                , "公示日期", "数据来源单位", "数据上报省/市", "数据目标省/市", "操作标识"};
        String[] enHeaders = {"CASEID", "REGNO", "UNISCID", "ENTNAME", "PENDECNO", "ILLEGACTTYPE", "PENTYPE"
                , "PENTYPE_CN", "PENAM", "FORFAM", "PENCONTENT", "JUDAUTH", "PENDECISSDATE", "REMARK", "PUBLICDATE"
                , "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 = 2;
        for (int i = 0; i < list.size(); i++) {
            OtNcaseDownloadLog each = list.get(i);
            HSSFRow row = sheet.createRow(i + offset);
            row.setHeightInPoints(28f);
            setCellValue(row.createCell(0), each.getCaseid(), 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.getPendecno(), style);//处罚决定书文号
            setCellValue(row.createCell(5), each.getIllegacttype(), style);//违法行为类型
            setCellValue(row.createCell(6), each.getPentype(), style);//处罚种类
            setCellValue(row.createCell(7), each.getPentypeCn(), style);//处罚种类（中文名称）
            setCellValue(row.createCell(8), each.getPenam(), style);//罚款金额
            setCellValue(row.createCell(9), each.getForfam(), style);//没收金额
            setCellValue(row.createCell(10), each.getPencontent(), style);//处罚内容
            setCellValue(row.createCell(11), each.getJudauth(), style);//作出行政处罚决定机关名称
            setCellValue(row.createCell(12), each.getPendecissdate(), style);//作出处罚决定书日期
            setCellValue(row.createCell(13), each.getRemark(), style);//备注
            setCellValue(row.createCell(14), each.getPublicDate(), style);//公示日期
            setCellValue(row.createCell(15), each.getDatadept(), style);//数据来源单位
            setCellValue(row.createCell(16), each.getUploadprov(), style);//数据上报省/市
            setCellValue(row.createCell(17), each.getTargetprov(), style);//数据目标省/市
            setCellValue(row.createCell(18), 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));
        }
    }
}
