package com.wms_main.excel.easypoi.service.serviceImpl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.wms_main.excel.easypoi.excelTemplate.*;
import com.wms_main.excel.easypoi.service.ISaveExcelEasyPoi;
import com.wms_main.model.po.*;
import com.wms_main.repository.utils.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 保存数据服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SaveExcelEasyPoi implements ISaveExcelEasyPoi {
    private final String ROOT_PATH = "./file";

    /**
     * 写入excel
     *
     * @param fileDesc  文件描述，不需要文件类型的后缀
     * @param filePath  文件路径，最后一位不需要添加文件分割符
     * @param sheetName 页名
     * @param list      数据列表
     * @param clazz     泛型类
     * @param <T>       泛型
     * @throws IOException 异常
     */
    public <T> void doWriteExcel(String fileDesc, String filePath, String sheetName, List<T> list, Class<T> clazz) throws IOException {
        ExportParams exportParams = new ExportParams();
        exportParams.setSheetName(sheetName);
        exportParams.setType(ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, clazz, list);
        File file = new File(filePath + File.separator + fileDesc + ".xlsx");
        createFile(file);// 新建文件
        FileOutputStream fos = new FileOutputStream(file);
        workbook.write(fos);
        fos.close();
        workbook.close();
        log.info("保存文件成功：{}。", fileDesc);
    }

    /**
     * 创建文件
     *
     * @param file 目标文件
     */
    public void createFile(File file) {
        if (!file.exists()) {
            // 文件不存在
            if (!file.getParentFile().exists()) {
                // 目录不存在，创建上级目录
                boolean createDirectSuccessFlag = file.getParentFile().mkdirs();
                if (!createDirectSuccessFlag) {
                    log.error("创建目录失败。");
                    return;
                }
            }
            try {
                // 在上级目录里创建文件
                boolean createFileSuccessFlag = file.createNewFile();
                if (!createFileSuccessFlag) {
                    log.error("创建文件失败。");
                }
            } catch (IOException e) {
                log.error("创建文件异常。{}", StringUtils.objectToString(e));
            }
        }
    }

    /**
     * 保存api接收日志
     *
     * @param fileSuffix 文件后缀
     * @param logList    数据列表
     */
    @Override
    public void saveApiReceiveLogs(String fileSuffix, List<TSysLog> logList) {
        if (logList == null || logList.isEmpty()) {
            // 空数据体，不做处理
            return;
        }
        // 将数据转化为excel Template
        List<ApiReceiveLogExcelTemplate> logExcelTemplateList = new ArrayList<>(logList.stream().map(log -> new ApiReceiveLogExcelTemplate(
                log.getLogId(),
                log.getMethod(),
                log.getUri(),
                log.getRemoteHost(),
                log.getRemoteAddr(),
                log.getRequestContent(),
                log.getStatus(),
                log.getResponseContent(),
                log.getLogTime()
        )).toList());
        try {
            // 写入excel
            doWriteExcel("t_sys_log_" + fileSuffix, ROOT_PATH + "/t_sys_log", "t_sys_log", logExcelTemplateList, ApiReceiveLogExcelTemplate.class);
        } catch (IOException e) {
            log.error("缓存过期接口接收日志异常。");
        }
    }

    /**
     * 保存api发送日志
     *
     * @param fileSuffix 文件后缀
     * @param apiLogList 数据列表
     */
    @Override
    public void saveApiSendLogs(String fileSuffix, List<TSysApi> apiLogList) {
        if (apiLogList == null || apiLogList.isEmpty()) {
            // 空数据体，不做处理
            return;
        }
        // 将数据转化为excel Template
        List<ApiSendLogExcelTemplate> logExcelTemplateList = new ArrayList<>(apiLogList.stream().map(log -> new ApiSendLogExcelTemplate(
                log.getLogId(),
                log.getUrl(),
                log.getTimeout(),
                log.getMethod(),
                log.getContentType(),
                log.getData(),
                log.getToken(),
                log.getSuccess(),
                log.getResponseCode(),
                log.getRequestMessage(),
                log.getResponseMessage(),
                log.getRequestTime(),
                log.getResponseTime(),
                log.getRequestUrl(),
                log.getUseTime(),
                log.getExceptionMessage(),
                log.getLogTime()
        )).toList());
        try {
            // 写入excel
            doWriteExcel("t_sys_api_" + fileSuffix, ROOT_PATH + "/t_sys_api", "t_sys_api", logExcelTemplateList, ApiSendLogExcelTemplate.class);
        } catch (IOException e) {
            log.error("缓存过期接口发送日志异常。");
        }
    }

    /**
     * 保存Wms任务记录
     *
     * @param fileSuffix     文件后缀
     * @param wmsTaskBakList 数据列表
     */
    @Override
    public void saveWmsTaskBak(String fileSuffix, List<TAppTaskBak> wmsTaskBakList) {
        if (wmsTaskBakList == null || wmsTaskBakList.isEmpty()) {
            // 空数据体，不做处理
            return;
        }
        // 将数据转化为excel Template
        List<WmsTaskBakExcelTemplate> wmsTaskBakExcelTemplateList = new ArrayList<>(wmsTaskBakList.stream().map(wmsTaskBak -> new WmsTaskBakExcelTemplate(
                wmsTaskBak.getTaskId(),
                wmsTaskBak.getTaskType(),
                wmsTaskBak.getTaskStatus(),
                wmsTaskBak.getTaskPriority(),
                wmsTaskBak.getVehicleId(),
                wmsTaskBak.getOrigin(),
                wmsTaskBak.getDestination(),
                wmsTaskBak.getWcsTaskId(),
                wmsTaskBak.getCreateTime(),
                wmsTaskBak.getFinishTime(),
                wmsTaskBak.getGoodsId(),
                wmsTaskBak.getOpNum(),
                wmsTaskBak.getStockNum(),
                wmsTaskBak.getOpUser(),
                wmsTaskBak.getRemark(),
                wmsTaskBak.getCallStand(),
                wmsTaskBak.getGoodsDesc()
        )).toList());
        try {
            // 写入excel
            doWriteExcel("t_app_task_bak_" + fileSuffix, ROOT_PATH + "/t_app_task_bak", "t_app_task_bak", wmsTaskBakExcelTemplateList, WmsTaskBakExcelTemplate.class);
        } catch (IOException e) {
            log.error("缓存过期Wms任务记录异常。");
        }
    }

    /**
     * 保存wcs任务记录
     *
     * @param fileSuffix     文件后缀
     * @param wcsTaskBakList 数据记录
     */
    @Override
    public void saveWcsTaskBak(String fileSuffix, List<TAppWcsTaskBak> wcsTaskBakList) {
        if (wcsTaskBakList == null || wcsTaskBakList.isEmpty()) {
            // 空数据体，不做处理
            return;
        }
        // 将数据转化为excel Template
        List<WcsTaskBakExcelTemplate> wcsTaskBakExcelTemplateList = new ArrayList<>(wcsTaskBakList.stream().map(wcsTaskBak -> new WcsTaskBakExcelTemplate(
                wcsTaskBak.getWcsTaskId(),
                wcsTaskBak.getWcsTaskStatus(),
                wcsTaskBak.getWcsTaskType(),
                wcsTaskBak.getTaskPriority(),
                wcsTaskBak.getVehicleId(),
                wcsTaskBak.getOrigin(),
                wcsTaskBak.getDestination(),
                wcsTaskBak.getCreateTime(),
                wcsTaskBak.getSendTime(),
                wcsTaskBak.getFinishTime(),
                wcsTaskBak.getRemark()
        )).toList());
        try {
            // 写入excel
            doWriteExcel("t_app_wcs_task_bak_" + fileSuffix, ROOT_PATH + "/t_app_wcs_task_bak", "t_app_wcs_task_bak", wcsTaskBakExcelTemplateList, WcsTaskBakExcelTemplate.class);
        } catch (IOException e) {
            log.error("缓存过期Wcs任务记录异常。");
        }
    }

    /**
     * 保存拣选任务记录
     *
     * @param fileSuffix      文件后缀
     * @param pickTaskBakList 数据记录
     */
    @Override
    public void savePickTaskBak(String fileSuffix, List<TAppPickTaskBak> pickTaskBakList) {
        if (pickTaskBakList == null || pickTaskBakList.isEmpty()) {
            // 空数据体，不做处理
            return;
        }
        // 将数据转化为excel Template
        List<PickTaskBakExcelTemplate> pickTaskExcelTemplateList = new ArrayList<>(pickTaskBakList.stream().map(log -> new PickTaskBakExcelTemplate(
                log.getPickId(),
                log.getPickStand(),
                log.getVehicleId(),
                log.getPickStatus(),
                log.getCreateTime(),
                log.getSendTime(),
                log.getArriveTime(),
                log.getLeaveTime()
        )).toList());
        try {
            // 写入excel
            doWriteExcel("t_app_pick_task_bak_" + fileSuffix, ROOT_PATH + "/t_app_pick_task_bak", "t_app_pick_task_bak", pickTaskExcelTemplateList, PickTaskBakExcelTemplate.class);
        } catch (IOException e) {
            log.error("缓存过期拣选任务记录异常。");
        }
    }

    /**
     * 保存DBS记录
     *
     * @param fileSuffix 文件后缀
     * @param dbsRecordList 数据列表
     */
    @Override
    public void saveDbsRecord(String fileSuffix, List<TAppDbs> dbsRecordList) {
        if (dbsRecordList == null || dbsRecordList.isEmpty()) {
            // 空数据体，不做处理
            return;
        }
        // 将数据转化为excel Template
        List<DbsRecordExcelTemplateForSave> dbsRecordExcelTemplateList = new ArrayList<>(dbsRecordList.stream().map(dbsRecord -> new DbsRecordExcelTemplateForSave(
                dbsRecord.getDbsId(),
                dbsRecord.getWorkOrder(),
                dbsRecord.getProductIdOrigin(),
                dbsRecord.getProductId(),
                dbsRecord.getTestPlanStartDate(),
                dbsRecord.getTestPlanFinishDate(),
                dbsRecord.getPntPlanStartDate(),
                dbsRecord.getPntPlanFinishDate(),
                dbsRecord.getPlanProduction(),
                dbsRecord.getEquipmentName(),
                dbsRecord.getWorkShift(),
                dbsRecord.getFamily(),
                dbsRecord.getTestNo(),
                dbsRecord.getDbsStatus(),
                dbsRecord.getWorkStand(),
                dbsRecord.getRealWorkDate(),
                dbsRecord.getFinishTime(),
                dbsRecord.getKittingRemark(),
                dbsRecord.getRemark()
        )).toList());
        try {
            // 写入excel
            doWriteExcel("t_app_dbs_" + fileSuffix, ROOT_PATH + "/t_app_dbs", "t_app_dbs", dbsRecordExcelTemplateList, DbsRecordExcelTemplateForSave.class);
        } catch (IOException e) {
            log.error("缓存Dbs记录异常。");
        }
    }

    /**
     * 保存出库单记录
     * @param fileSuffix 文件后缀
     * @param outsRecordList 数据列表
     */
    @Override
    public void saveOutsRecord(String fileSuffix, List<TAppOutsRecord> outsRecordList) {
        if (outsRecordList == null || outsRecordList.isEmpty()) {
            // 空数据体，不做处理
            return;
        }
        // 将数据转化为excel Template
        List<OutsRecordExcelTemplateForSave> outsRecordExcelTemplateList = new ArrayList<>(outsRecordList.stream().map(outsRecord -> new OutsRecordExcelTemplateForSave(
                outsRecord.getTaskId(),
                outsRecord.getGoodsId(),
                outsRecord.getVehicleId(),
                outsRecord.getNeedNum(),
                outsRecord.getDistributeNum(),
                outsRecord.getPickNum(),
                outsRecord.getOutType(),
                outsRecord.getDestination(),
                outsRecord.getUserName(),
                outsRecord.getReason(),
                outsRecord.getRequestTime()
        )).toList());
        try {
            // 写入excel
            doWriteExcel("t_app_outs_record_" + fileSuffix, ROOT_PATH + "/t_app_outs_record", "t_app_outs_record", outsRecordExcelTemplateList, OutsRecordExcelTemplateForSave.class);
        } catch (IOException e) {
            log.error("缓存出库单记录异常。");
        }
    }

    /**
     * 缓存库存流水记录
     * @param fileSuffix 文件后缀
     * @param stockUpdateList 数据列表
     */
    @Override
    public void saveStockUpdateRecord(String fileSuffix, List<TAppStockUpdate> stockUpdateList) {
        if (stockUpdateList == null || stockUpdateList.isEmpty()) {
            // 空数据体，不做处理
            return;
        }
        // 将数据转化为excel Template
        List<StockUpdateRecordExcelTemplateForSave> stockUpdateExcelTemplateList = new ArrayList<>(stockUpdateList.stream().map(stockUpdate -> new StockUpdateRecordExcelTemplateForSave(
                stockUpdate.getUpdateId(),
                stockUpdate.getVehicleId(),
                stockUpdate.getGoodsId(),
                stockUpdate.getFirstInTime(),
                stockUpdate.getBeforeNum(),
                stockUpdate.getAfterNum(),
                stockUpdate.getReason(),
                stockUpdate.getUpdateTime(),
                stockUpdate.getUpdateUser()
        )).toList());
        try {
            // 写入excel
            doWriteExcel("t_app_stock_update_" + fileSuffix, ROOT_PATH + "/t_app_stock_update", "t_app_stock_update", stockUpdateExcelTemplateList, StockUpdateRecordExcelTemplateForSave.class);
        } catch (IOException e) {
            log.error("缓存库存流水记录异常。");
        }
    }

    /**
     * 保存盘点记录
     * @param fileSuffix 文件后缀
     * @param inventoryList 数据列表
     */
    @Override
    public void saveInventoryRecord(String fileSuffix, List<TAppInventoryRecord> inventoryList) {
        if (inventoryList == null || inventoryList.isEmpty()) {
            // 空数据体，不做处理
            return;
        }
        // 将数据转化为excel Template
        List<InventoryRecordExcelTemplateForSave> inventoryRecordExcelTemplateList = new ArrayList<>(inventoryList.stream().map(inventoryRecord -> new InventoryRecordExcelTemplateForSave(
                inventoryRecord.getInventoryId(),
                inventoryRecord.getGoodsId(),
                inventoryRecord.getVehicleId(),
                inventoryRecord.getStockNum(),
                inventoryRecord.getConfirmNum(),
                inventoryRecord.getInvStand(),
                inventoryRecord.getInvUser(),
                inventoryRecord.getInvType(),
                inventoryRecord.getInvStatus(),
                inventoryRecord.getInvResult(),
                inventoryRecord.getInvCreateTime(),
                inventoryRecord.getInvConfirmTime(),
                inventoryRecord.getInvOrderId()
        )).toList());
        try {
            // 写入excel
            doWriteExcel("t_app_inventory_" + fileSuffix, ROOT_PATH + "/t_app_inventory", "t_app_inventory", inventoryRecordExcelTemplateList, InventoryRecordExcelTemplateForSave.class);
        } catch (IOException e) {
            log.error("缓存盘点记录异常。");
        }
    }

    /**
     * 保存工作记录
     *
     * @param fileSuffix     文件后缀
     * @param workRecordList 数据列表
     */
    @Override
    public void saveWorkRecord(String fileSuffix, List<TAppWorkRecord> workRecordList) {
        if (workRecordList == null || workRecordList.isEmpty()) {
            // 空数据体，不做处理
            return;
        }
        // 将数据转化为excel Template
        List<WorkRecordExcelTemplateForSave> workRecordExcelTemplateList = new ArrayList<>(workRecordList.stream().map(workRecord -> new WorkRecordExcelTemplateForSave(
                workRecord.getWorkIndex(),
                workRecord.getWorkOrder(),
                workRecord.getPlanStartDate(),
                workRecord.getProductId(),
                workRecord.getSingleProductId(),
                workRecord.getBoxNo(),
                workRecord.getGoodsId(),
                workRecord.getNeedNum(),
                workRecord.getFinishNum(),
                workRecord.getWorkStand(),
                workRecord.getWorkStatus(),
                workRecord.getWorkUser(),
                workRecord.getCreateTime(),
                workRecord.getFinishTime(),
                workRecord.getLackStatus(),
                workRecord.getIsOut(),
                workRecord.getProductType(),
                workRecord.getKittingRemark()
        )).toList());
        try {
            // 写入excel
            doWriteExcel("t_app_work_record_" + fileSuffix, ROOT_PATH + "/t_app_work_record", "t_app_work_record", workRecordExcelTemplateList, WorkRecordExcelTemplateForSave.class);
        } catch (IOException e) {
            log.error("缓存工作记录异常。");
        }
    }
}
