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

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wms_main.app.AppCommon;
import com.wms_main.constant.enums.others.DbsStatusEnums;
import com.wms_main.dao.*;
import com.wms_main.excel.easypoi.excelTemplate.*;
import com.wms_main.excel.easypoi.service.IImportExcelEasyPoi;
import com.wms_main.model.po.*;
import com.wms_main.model.vo.others.FileVo;
import com.wms_main.model.dto.response.wms.BaseWmsApiResponse;
import com.wms_main.repository.utils.StringUtils;
import com.wms_main.repository.utils.UUIDUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class ImportExcelEasyPoi implements IImportExcelEasyPoi {
    private final ITAppDbsService tAppDbsService;// DBS服务
    private final ITAppProductService tAppProductService;// 成品配料单服务
    private final ITAppImageService tAppImageService;// 图纸服务
    private final ITAppGoodsService tAppGoodsService;// 物料服务
    private final ITAppKanbanService tAppKanbanService;// 看板服务
    private final ITAppProductExtendService tAppProductExtendService;// 总成-单片对应关系服务
    private final ITAppSingleProductService tAppSingleProductService;// 单片服务
    private final AppCommon appCommon;

    @Override
    public BaseWmsApiResponse doImportExcel(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        params.setSheetNum(1);
//        params.setNeedSave(false);
        //解析后的图片字段存放的是图片的地址，需要在GoodsModel中配置图片存放路径
        List<ImageTemplate> result = ExcelImportUtil.importExcel(file.getInputStream(), ImageTemplate.class, params);
        for (ImageTemplate imageModel : result) {
            if (StringUtils.isNotEmpty(imageModel.getImageTest())) {
                //将图片文件转为base64图片
                File file1 = new File(imageModel.getImageTest());
                FileInputStream inputStream = new FileInputStream(file1);
                byte[] buffer = new byte[inputStream.available()];
                if (inputStream.read(buffer) == -1) {
                    inputStream.close();
                }
                StringBuilder imageBase64 = new StringBuilder(Base64.getEncoder().encodeToString(buffer));
                imageModel.setImageTest(new String(imageBase64));
            }
        }
        return BaseWmsApiResponse.success();
    }

    /**
     * 导入dbs的实现
     *
     * @param file   dbs文件
     * @param fileVo 文件vo
     * @return BaseWmsApiResponse 结果
     * @throws Exception 异常
     */
    @Override
    @Transactional
    public BaseWmsApiResponse doImportDbs(MultipartFile file, FileVo fileVo) throws Exception {
        // 设置解析条件
        ImportParams dbsImportparams = new ImportParams();
        dbsImportparams.setHeadRows(1);
        dbsImportparams.setSheetNum(1);
        // 解析excel文件
        List<DbsExcelTemplate> dbsRawDatas = ExcelImportUtil.importExcel(file.getInputStream(), DbsExcelTemplate.class, dbsImportparams);
        List<TAppDbs> dbsList = new ArrayList<>();
        // 处理解析数据
        for (DbsExcelTemplate dbsRawData : dbsRawDatas) {
            // 校验数据正确性
            if (StringUtils.isEmpty(dbsRawData.getWorkOrder())
                    || StringUtils.isEmpty(dbsRawData.getProductIdOrigin())
                    || dbsRawData.getTestPlanStartDate() == null
                    || dbsRawData.getPlanProduction() == null
                    || StringUtils.isEmpty(dbsRawData.getFamily())
                    || StringUtils.isEmpty(dbsRawData.getTestNo())) {
                continue;
            }
            if (dbsRawData.getFamily().contains("NGH")) {
                // 去除J列的NGH
                continue;
            }
            dbsList.add(getDbs(dbsRawData, fileVo.getUserName()));
        }
        try {
            // 保存数据
            if (dbsList.isEmpty()) {
                return BaseWmsApiResponse.error("空数据。");
            }
            // 新的DBS Map
            Map<String, List<TAppDbs>> newDbsMap = dbsList.stream().collect(Collectors.groupingBy(TAppDbs::getWorkOrder));
            // 查找旧DBS
            List<TAppDbs> oldDbsList = tAppDbsService.list(new LambdaQueryWrapper<TAppDbs>().in(TAppDbs::getWorkOrder, newDbsMap.keySet()));
            // 旧的DBS Map
            Map<String, List<TAppDbs>> oldDbsMap = oldDbsList.stream().collect(Collectors.groupingBy(TAppDbs::getWorkOrder));
            // 需要保存的Map
            Map<String, TAppDbs> newDbsMapToSave = new HashMap<>();
            // 处理数据
            for (String workOrder : newDbsMap.keySet()) {
                TAppDbs thisDbs = newDbsMap.get(workOrder).getFirst();
                if (oldDbsMap.containsKey(workOrder)) {
                    TAppDbs thisOldDbs = oldDbsMap.get(workOrder).getFirst();
                    thisDbs.setDbsStatus(thisOldDbs.getDbsStatus());
                    thisDbs.setWorkStand(thisOldDbs.getWorkStand());
                    thisDbs.setFinishTime(thisOldDbs.getFinishTime());
                    thisDbs.setRealWorkDate(thisOldDbs.getRealWorkDate());
                    thisDbs.setRemark(thisOldDbs.getRemark());
                    thisDbs.setLastUpdateTime(LocalDateTime.now());
                }
                newDbsMapToSave.put(workOrder, thisDbs);
            }
            // 先移除这些workOrder下的dbs
            tAppDbsService.remove(new LambdaQueryWrapper<TAppDbs>().in(TAppDbs::getWorkOrder, newDbsMapToSave.keySet()));
            // 保存新的数据
            tAppDbsService.saveBatch(newDbsMapToSave.values());
            // 保存导入file记录
            saveFileVo(fileVo);
            return BaseWmsApiResponse.success("导入计划成功。");
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return BaseWmsApiResponse.error("导入计划失败。");
        }
    }

    /**
     * 导入成品配料单的实现
     *
     * @param file   配料单文件
     * @param fileVo 文件vo
     * @return BaseWmsApiResponse 结果
     * @throws Exception 异常
     */
    @Override
    @Transactional
    public BaseWmsApiResponse doImportProduct(MultipartFile file, FileVo fileVo) throws Exception {
        // 设置解析条件
        ImportParams productImportparams = new ImportParams();
        productImportparams.setHeadRows(1);
        productImportparams.setSheetNum(1);
        // 解析excel文件
        List<ProductExcelTemplate> productRawDatas = ExcelImportUtil.importExcel(file.getInputStream(), ProductExcelTemplate.class, productImportparams);
        List<TAppProduct> productList = new ArrayList<>();
        // 本次导入的成品号
        String thisProductId = "";
        // 处理解析数据
        for (ProductExcelTemplate productRawData : productRawDatas) {
            // 校验数据正确性
            if (StringUtils.isEmpty(productRawData.getModel())
                    || StringUtils.isEmpty(productRawData.getProductId())
                    || productRawData.getQuantity1Pair() == null
                    || StringUtils.isEmpty(productRawData.getGoodsId())
                    || StringUtils.isEmpty(productRawData.getGoodsDesc())
                    || productRawData.getQuantityOfPairs() == null
                    || StringUtils.isEmpty(productRawData.getBoxNo())) {
                continue;
            }
            if (StringUtils.isNotEmpty(thisProductId) && !thisProductId.equals(productRawData.getProductId())) {
                continue;
            } else {
                thisProductId = productRawData.getProductId();
            }
            productList.add(getProduct(productRawData, fileVo.getUserName()));
        }
        // 导入图纸
        ImportParams imageImportparams = new ImportParams();
        imageImportparams.setHeadRows(1);
        imageImportparams.setSheetName("图纸");
        // 解析excel文件
        List<ImageExcelTemplate> imageRawDatas = ExcelImportUtil.importExcel(file.getInputStream(), ImageExcelTemplate.class, imageImportparams);
        List<TAppImage> imageList = new ArrayList<>();
        for (ImageExcelTemplate imageRowData : imageRawDatas) {
            if (StringUtils.isNotEmpty(imageRowData.getBoxNo()) && StringUtils.isNotEmpty(imageRowData.getImageDetail())) {
                imageList.add(getImage(imageRowData, thisProductId, fileVo.getUserName(), 1));
            }
        }
        try {
            // 保存数据
            if (productList.isEmpty()) {
                return BaseWmsApiResponse.error("配料单为空。");
            }
            if (imageList.isEmpty()) {
                return BaseWmsApiResponse.error("图纸为空。");
            }
            // 处理旧数据
            Map<String, List<TAppProduct>> productMap = productList.stream().collect(Collectors.groupingBy(TAppProduct::getProductId));
            // 移除旧数据
            tAppProductService.remove(new LambdaQueryWrapper<TAppProduct>().in(TAppProduct::getProductId, productMap.keySet()));
            // 保存新数据
            tAppProductService.saveBatch(productList);
            // 处理旧图纸
            Map<String, List<TAppImage>> imageMap = imageList.stream().collect(Collectors.groupingBy(TAppImage::getProductId));
            // 移除旧图纸
            tAppImageService.remove(new LambdaQueryWrapper<TAppImage>().in(TAppImage::getProductId, imageMap.keySet()));
            // 保存新图纸
            tAppImageService.saveBatch(imageList);
            // 保存导入file记录
            saveFileVo(fileVo);
            return BaseWmsApiResponse.success("导入配料单成功。");
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return BaseWmsApiResponse.error("导入配料单失败。");
        }
    }

    /**
     * 导入单片实现
     * @param file 文件
     * @param fileVo 文件信息
     * @return 导入结果
     * @throws Exception 异常
     */
    @Override
    public BaseWmsApiResponse doImportSingleProduct(MultipartFile file, FileVo fileVo) throws Exception {
        // 设置解析条件
        ImportParams productImportparams = new ImportParams();
        productImportparams.setHeadRows(1);
        productImportparams.setSheetNum(1);
        // 解析excel文件
        List<SingleProductExcelTemplate> productRawDatas = ExcelImportUtil.importExcel(file.getInputStream(), SingleProductExcelTemplate.class, productImportparams);
        List<TAppSingleProduct> productList = new ArrayList<>();
        // 本次导入的成品号
        String thisProductId = "";
        // 处理解析数据
        for (SingleProductExcelTemplate productRawData : productRawDatas) {
            // 校验数据正确性
            if (StringUtils.isEmpty(productRawData.getModel())
                    || StringUtils.isEmpty(productRawData.getSingleProductId())
                    || productRawData.getQuantity1Pair() == null
                    || StringUtils.isEmpty(productRawData.getGoodsId())
                    || StringUtils.isEmpty(productRawData.getGoodsDesc())
                    || productRawData.getQuantityOfPairs() == null
                    || StringUtils.isEmpty(productRawData.getBoxNo())) {
                continue;
            }
            if (StringUtils.isNotEmpty(thisProductId) && !thisProductId.equals(productRawData.getSingleProductId())) {
                continue;
            } else {
                thisProductId = productRawData.getSingleProductId();
            }
            productList.add(getSingleProduct(productRawData, fileVo.getUserName()));
        }
        // 导入图纸
        ImportParams imageImportparams = new ImportParams();
        imageImportparams.setHeadRows(1);
        imageImportparams.setSheetName("图纸");
        // 解析excel文件
        List<ImageExcelTemplate> imageRawDatas = ExcelImportUtil.importExcel(file.getInputStream(), ImageExcelTemplate.class, imageImportparams);
        List<TAppImage> imageList = new ArrayList<>();
        for (ImageExcelTemplate imageRowData : imageRawDatas) {
            if (StringUtils.isNotEmpty(imageRowData.getBoxNo()) && StringUtils.isNotEmpty(imageRowData.getImageDetail())) {
                imageList.add(getImage(imageRowData, thisProductId, fileVo.getUserName(), 2));
            }
        }
        try {
            // 保存数据
            if (productList.isEmpty()) {
                return BaseWmsApiResponse.error("单片配料单为空。");
            }
            if (imageList.isEmpty()) {
                return BaseWmsApiResponse.error("图纸为空。");
            }
            // 处理旧数据
            Map<String, List<TAppSingleProduct>> productMap = productList.stream().collect(Collectors.groupingBy(TAppSingleProduct::getProductId));
            // 先移除这个单片号下面所有的配料单
            tAppSingleProductService.remove(new LambdaQueryWrapper<TAppSingleProduct>().in(TAppSingleProduct::getProductId, productMap.keySet()));
            // 保存新数据
            tAppSingleProductService.saveBatch(productList);
            // 处理旧图纸
            Map<String, List<TAppImage>> imageMap = imageList.stream().collect(Collectors.groupingBy(TAppImage::getProductId));
            // 移除旧图纸
            tAppImageService.remove(new LambdaQueryWrapper<TAppImage>().in(TAppImage::getProductId, imageMap.keySet()));
            // 保存新图纸
            tAppImageService.saveBatch(imageList);
            // 保存导入file记录
            saveFileVo(fileVo);
            return BaseWmsApiResponse.success("导入单片配料单成功。");
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return BaseWmsApiResponse.error("导入单片配料单失败。");
        }
    }

    /**
     * 导入总成与单片对应关系
     * @param file 文件
     * @param fileVo 文件信息
     * @return 导入结果
     * @throws Exception 异常
     */
    @Override
    public BaseWmsApiResponse doImportProductExtend(MultipartFile file, FileVo fileVo) throws Exception {
        // 设置解析条件
        ImportParams productImportparams = new ImportParams();
        productImportparams.setHeadRows(1);
        productImportparams.setSheetNum(1);
        // 解析excel文件
        List<ProductExtendExcelTemplate> productRawDatas = ExcelImportUtil.importExcel(file.getInputStream(), ProductExtendExcelTemplate.class, productImportparams);
        List<TAppProductExtend> productList = new ArrayList<>();
        // 处理解析数据
        for (ProductExtendExcelTemplate productRawData : productRawDatas) {
            // 校验数据正确性
            if (StringUtils.isEmpty(productRawData.getModel())
                    || StringUtils.isEmpty(productRawData.getProductId())
                    || StringUtils.isEmpty(productRawData.getSingleProductId())) {
                continue;
            }
            productList.add(getProductExtend(productRawData, fileVo.getUserName()));
        }
        try {
            // 保存数据
            if (productList.isEmpty()) {
                return BaseWmsApiResponse.error("空数据。");
            }
            Map<String, List<TAppProductExtend>> productExtendMap = productList.stream().collect(Collectors.groupingBy(TAppProductExtend::getProductId));
            // 先移除这个总成号下面的数据
            tAppProductExtendService.remove(new LambdaQueryWrapper<TAppProductExtend>().in(TAppProductExtend::getProductId, productExtendMap.keySet()));
            // 保存新数据
            tAppProductExtendService.saveBatch(productList);
            // 保存导入file记录
            saveFileVo(fileVo);
            return BaseWmsApiResponse.success("导入总成单片对应关系成功。");
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return BaseWmsApiResponse.error("导入总成单片对应关系失败。");
        }
    }

    /**
     * 业务逻辑实现
     *
     * @param file   文件
     * @param fileVo 文件信息
     * @return 导入结果
     */
    @Override
    @Transactional
    public BaseWmsApiResponse doImportBaseGoods(MultipartFile file, FileVo fileVo) throws Exception {
        // 设置解析条件
        ImportParams baseGoodsImportparams = new ImportParams();
        baseGoodsImportparams.setHeadRows(1);
        baseGoodsImportparams.setSheetNum(1);
        // 解析excel文件
        List<GoodsExcelTemplate> baseGoodsRawDatas = ExcelImportUtil.importExcel(file.getInputStream(), GoodsExcelTemplate.class, baseGoodsImportparams);
        List<TAppGoods> goodsList = new ArrayList<>();
        // 处理解析数据
        for (GoodsExcelTemplate baseGoodsRawData : baseGoodsRawDatas) {
            // 判断必须条件
            if (StringUtils.isEmpty(baseGoodsRawData.getMaterial())
                    || StringUtils.isEmpty(baseGoodsRawData.getFeedingType())
                    || StringUtils.isEmpty(baseGoodsRawData.getPutArea())
                    || StringUtils.isEmpty(baseGoodsRawData.getIsSled())) {
                continue;
            }
            if (baseGoodsRawData.getPutArea().equals("ASRS")) {
                // 如果是库内料
                if (baseGoodsRawData.getMaxBoxNum() == null || baseGoodsRawData.getBoxQty() == null || StringUtils.isEmpty(baseGoodsRawData.getHotPoint())) {
                    continue;
                }
            }
            // 判断SLED格式是否正确
            if (!List.of("Y", "N").contains(baseGoodsRawData.getIsSled())) {
                continue;
            }
            // SLED管理时没有SLED天数
            if (baseGoodsRawData.getIsSled().contains("Y") && baseGoodsRawData.getSledDays() == null) {
                continue;
            }
            // 保存数据
            goodsList.add(getGoods(baseGoodsRawData, fileVo.getUserName()));
        }
        try {
            if (goodsList.isEmpty()) {
                return BaseWmsApiResponse.error("符合条件数据行为0。");
            }
            // 保存数据
            tAppGoodsService.saveOrUpdateBatch(goodsList);
            // 更新common
            appCommon.initInstantGoodsMap();
            // 保存导入file记录
            saveFileVo(fileVo);
            return BaseWmsApiResponse.success("导入物料数据成功。原始数据" + baseGoodsRawDatas.size() + "行，导入成功" + goodsList.size() + "行。");
        } catch (Exception e){
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return BaseWmsApiResponse.error("导入物料数据失败。");
        }
    }

    /**
     * 业务逻辑实现
     *
     * @param file   文件
     * @param fileVo 文件信息
     * @return 导入结果
     * @throws Exception 异常
     */
    @Override
    @Transactional
    public BaseWmsApiResponse doImportKanban(MultipartFile file, FileVo fileVo) throws Exception {
        // 设置解析条件
        ImportParams kanbanImportparams = new ImportParams();
        kanbanImportparams.setHeadRows(1);
        kanbanImportparams.setSheetNum(1);
        // 解析excel文件
        List<KanbanExcelTemplate> kanbanRawDatas = ExcelImportUtil.importExcel(file.getInputStream(), KanbanExcelTemplate.class, kanbanImportparams);
        Map<String, List<TAppKanban>> kanbanListMap = new HashMap<>();
        // 处理解析数据
        for (KanbanExcelTemplate kanbanRawData : kanbanRawDatas) {
            if (StringUtils.isEmpty(kanbanRawData.getGoodsId()) || StringUtils.isEmpty(kanbanRawData.getKanbanId())) {
                continue;
            }
            // 键为物料id
            if (kanbanListMap.containsKey(kanbanRawData.getGoodsId())) {
                List<TAppKanban> oldKanbanList = new ArrayList<>(kanbanListMap.get(kanbanRawData.getGoodsId()));
                oldKanbanList.add(getKanban(kanbanRawData, fileVo.getUserName()));
                kanbanListMap.replace(kanbanRawData.getGoodsId(), oldKanbanList);
            } else {
                kanbanListMap.put(kanbanRawData.getGoodsId(), List.of(getKanban(kanbanRawData, fileVo.getUserName())));
            }
        }
        try {
            // 保存数据
            if (kanbanListMap.isEmpty()) {
                return BaseWmsApiResponse.error("空数据。");
            }
            // 先移除这些物料的看板
            tAppKanbanService.remove(new LambdaQueryWrapper<TAppKanban>().in(TAppKanban::getGoodsId, kanbanListMap.keySet()));
            // 转换保存数据
            List<TAppKanban> kanbanList = new ArrayList<>();
            kanbanListMap.values().forEach(kanbanList::addAll);
            tAppKanbanService.saveBatch(kanbanList);
            // 保存导入file记录
            saveFileVo(fileVo);
            return BaseWmsApiResponse.success("导入看板数据成功。");
        } catch (Exception e) {
            // 回滚事务
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return BaseWmsApiResponse.error("导入看板数据失败。");
        }
    }

    /**
     * 保存fileVo信息
     *
     * @param fileVo 文件Vo
     */
    private void saveFileVo(FileVo fileVo) {
        // TODO 待建表
    }

    /**
     * 创建dbsPo详细信息
     *
     * @param dbsRawData 原始数据
     * @param userName   用户名
     * @return 处理结果
     */
    private TAppDbs getDbs(DbsExcelTemplate dbsRawData, String userName) {
        TAppDbs tempDbs = new TAppDbs();
        tempDbs.setDbsId(UUIDUtils.getNewUUID());
        tempDbs.setWorkOrder(dbsRawData.getWorkOrder());
        // 处理零件号/成品号
        tempDbs.setProductIdOrigin(dbsRawData.getProductIdOrigin());// 原始数据
        if (dbsRawData.getProductIdOrigin().contains("/")) {
            // 如果包含“/”， 则以“/”为分隔符
            tempDbs.setProductId(dbsRawData.getProductIdOrigin().split("/")[0]);
        } else if (dbsRawData.getProductIdOrigin().contains("-")) {
            // 如果包含“-”， 则以“-”为分隔符
            tempDbs.setProductId(dbsRawData.getProductIdOrigin().split("-")[0]);
        } else {
            tempDbs.setProductId(dbsRawData.getProductIdOrigin());
        }
        tempDbs.setTestPlanStartDate(dbsRawData.getTestPlanStartDate());
        tempDbs.setTestPlanFinishDate(dbsRawData.getTestPlanFinishDate());
        tempDbs.setPntPlanStartDate(dbsRawData.getPntPlanStartDate());
        tempDbs.setPntPlanFinishDate(dbsRawData.getPntPlanFinishDate());
        tempDbs.setPlanProduction(dbsRawData.getPlanProduction());
        tempDbs.setEquipmentName(dbsRawData.getEquipmentName());
        tempDbs.setWorkShift(dbsRawData.getWorkShift());
        tempDbs.setFamily(dbsRawData.getFamily());
        tempDbs.setTestNo(dbsRawData.getTestNo());
        tempDbs.setKittingRemark(dbsRawData.getKittingRemark());
        tempDbs.setRemark(dbsRawData.getRemark());

        tempDbs.setDbsStatus(DbsStatusEnums.NEW.getValue());
        tempDbs.setFirstImportTime(LocalDateTime.now());
        tempDbs.setFirstImportUser(userName);

        return tempDbs;
    }

    /**
     * 创建详细的成品配料单Po
     *
     * @param productRawData 原始数据
     * @param userName       用户名
     * @return 处理结果
     */
    private TAppProduct getProduct(ProductExcelTemplate productRawData, String userName) {
        TAppProduct tempProduct = new TAppProduct();
        tempProduct.setTemplateId(UUIDUtils.getNewUUID());
        tempProduct.setModel(productRawData.getModel());
        tempProduct.setProductId(productRawData.getProductId());
        tempProduct.setGoodsId(productRawData.getGoodsId());
        tempProduct.setGoodsDescription(productRawData.getGoodsDesc());
        tempProduct.setQuantity1Pair(productRawData.getQuantity1Pair());
        tempProduct.setBoxNo(productRawData.getBoxNo());
        tempProduct.setQuantityOfPair(productRawData.getQuantityOfPairs());
        tempProduct.setFirstImportTime(LocalDateTime.now());
        tempProduct.setFirstImportUser(userName);
        return tempProduct;
    }

    /**
     * 创建详细的单片配料单Po
     *
     * @param productRawData 原始数据
     * @param userName       用户名
     * @return 处理结果
     */
    private TAppSingleProduct getSingleProduct(SingleProductExcelTemplate productRawData, String userName) {
        TAppSingleProduct tempSingleProduct = new TAppSingleProduct();
        tempSingleProduct.setSingleTemplateId(UUIDUtils.getNewUUID());
        tempSingleProduct.setModel(productRawData.getModel());
        tempSingleProduct.setProductId(productRawData.getSingleProductId());
        tempSingleProduct.setGoodsId(productRawData.getGoodsId());
        tempSingleProduct.setGoodsDescription(productRawData.getGoodsDesc());
        tempSingleProduct.setQuantity1Pair(productRawData.getQuantity1Pair());
        tempSingleProduct.setBoxNo(productRawData.getBoxNo());
        tempSingleProduct.setQuantityOfPair(productRawData.getQuantityOfPairs());
        tempSingleProduct.setFirstImportTime(LocalDateTime.now());
        tempSingleProduct.setFirstImportUser(userName);
        return tempSingleProduct;
    }

    /**
     * 创建详细的图纸po
     *
     * @param imageRawData 原始数据
     * @param userName     用户名
     * @param imageType   图片类型 1：总成；2:单片
     * @return 处理结果
     */
    private TAppImage getImage(ImageExcelTemplate imageRawData, String productId, String userName, int imageType) throws IOException {
        TAppImage tempImage = new TAppImage();
        tempImage.setImageId(UUIDUtils.getNewUUID());
        tempImage.setProductId(productId);
        tempImage.setBoxNo(imageRawData.getBoxNo());
        // 获取文件名
        int startIndex = imageRawData.getImageDetail().lastIndexOf(File.separator);
        int endIndex = imageRawData.getImageDetail().lastIndexOf(".");
        String fileDir = imageRawData.getImageDetail().substring(0, startIndex);
        String oldImageName = imageRawData.getImageDetail().substring(startIndex + 1);
        String fileType = imageRawData.getImageDetail().substring(endIndex);
        // 文件路径
        tempImage.setImagePath(fileDir + File.separator);
        // 格式化文件名
        String newImageName = productId + "_" + imageRawData.getBoxNo() + fileType;
        //将图片文件转为base64图片
        File oldFile = new File(imageRawData.getImageDetail());
        // 重命名
        File renamedFile = FileUtil.rename(oldFile, newImageName, true);
        if (renamedFile.getName().contains(newImageName)) {
            tempImage.setImageName(newImageName);
        } else {
            tempImage.setImageName(oldImageName);
        }
        // 存储图片实例
        FileInputStream inputStream = new FileInputStream(renamedFile);
        byte[] buffer = new byte[inputStream.available()];
        if (inputStream.read(buffer) == -1) {
            inputStream.close();
        }
        StringBuilder imageBase64 = new StringBuilder(Base64.getEncoder().encodeToString(buffer));
        tempImage.setImageDetail(new String(imageBase64));
        tempImage.setImageType(imageType);
        tempImage.setFirstImportTime(LocalDateTime.now());
        tempImage.setFirstImportUser(userName);
        return tempImage;
    }

    /**
     * 创建详细的goods po
     * @param goodsRawData 原始数据
     * @param userName 用户名
     * @return po
     */
    private TAppGoods getGoods(GoodsExcelTemplate goodsRawData, String userName) {
        TAppGoods goods = new TAppGoods(
                goodsRawData.getMaterial(),
                goodsRawData.getPlant(),
                goodsRawData.getDescription(),
                goodsRawData.getVendorName(),
                goodsRawData.getIsSled(),
                goodsRawData.getSledDays(),
                goodsRawData.getFeedingType(),
                goodsRawData.getBoxQty(),
                goodsRawData.getPutArea(),
                goodsRawData.getHotPoint(),
                goodsRawData.getMaxBoxNum()
        );
        goods.setFirstImportTime(LocalDateTime.now());
        goods.setFirstImportUser(userName);

        return goods;
    }

    /**
     * 创建详细的kanban po
     * @param kanbanRawData 原始数据
     * @param userName 用户名
     * @return po
     */
    private TAppKanban getKanban(KanbanExcelTemplate kanbanRawData, String userName) {
        TAppKanban kanban = new TAppKanban(
                UUIDUtils.getNewUUID(),
                kanbanRawData.getGoodsId(),
                kanbanRawData.getKanbanId(),
                0,
                LocalDateTime.now()
        );
        kanban.setFirstImportTime(LocalDateTime.now());
        kanban.setFirstImportUser(userName);
        return kanban;
    }

    /**
     * 创建详细的成品-单片po
     * @param productExtendRawData 原始数据
     * @param userName 用户名
     * @return po
     */
    private TAppProductExtend getProductExtend(ProductExtendExcelTemplate productExtendRawData, String userName) {
        TAppProductExtend productExtend = new TAppProductExtend(
                UUIDUtils.getNewUUID(),
                productExtendRawData.getProductId(),
                productExtendRawData.getSingleProductId(),
                productExtendRawData.getModel()
        );
        productExtend.setFirstImportTime(LocalDateTime.now());
        productExtend.setFirstImportUser(userName);
        return productExtend;
    }
}
