package com.inkasso.factoring.acceptanceManagement.service.impl;

import com.inkasso.adapter.exception.BusinessException;
import com.inkasso.adapter.util.CodeUtil;
import com.inkasso.auth.exception.ValidatorException;
import com.inkasso.factoring.acceptanceManagement.entity.CAcceptanceSignConfirmationGoodsInfo;
import com.inkasso.factoring.acceptanceManagement.dao.CAcceptanceSignConfirmationGoodsInfoMapper;
import com.inkasso.factoring.acceptanceManagement.service.ICAcceptanceSignConfirmationGoodsInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.inkasso.factoring.common.util.excel.ExcelLogs;
import com.inkasso.factoring.common.util.excel.ExcelUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;
import java.util.List;

/**
 * <p>
 * 下游验收单-签署确认货物信息表 服务实现类
 * </p>
 *
 * @author yafan
 * @since 2023-11-30
 */
@Service
public class CAcceptanceSignConfirmationGoodsInfoServiceImpl extends ServiceImpl<CAcceptanceSignConfirmationGoodsInfoMapper, CAcceptanceSignConfirmationGoodsInfo> implements ICAcceptanceSignConfirmationGoodsInfoService {

    @Override
    public List<CAcceptanceSignConfirmationGoodsInfo> importGoodsInfo(MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException(CodeUtil.FAIL, "导入Excel文件不能为空");
        }
        try {
            InputStream inputStream = file.getInputStream();
            Collection<CAcceptanceSignConfirmationGoodsInfo> acceptanceGoodsInfo = ExcelUtil.importExcel(CAcceptanceSignConfirmationGoodsInfo.class, inputStream, "yyyy-MM-dd", new ExcelLogs(), 0);
            for (CAcceptanceSignConfirmationGoodsInfo goodsInfo : acceptanceGoodsInfo) {
                int salesPriceLength = 0;
                if (goodsInfo.getSalesPrice() != null) {
                    salesPriceLength = goodsInfo.getSalesPrice().stripTrailingZeros().scale();
                }
                int goodsQuantityLength = goodsInfo.getGoodsQuantity().stripTrailingZeros().scale();
                if ((salesPriceLength != 0 && salesPriceLength > 4) || goodsQuantityLength > 4) {
                    throw new ValidatorException(CodeUtil.FAIL, "导入失败，销售单价或数量小数位数过长！");
                }
//                goodsInfo.setSalesPriceStr(goodsInfo.getSalesPrice() != null ? goodsInfo.getSalesPrice().toString() : "");
            }
            return (List<CAcceptanceSignConfirmationGoodsInfo>) acceptanceGoodsInfo;
        } catch (IOException e) {
            throw new BusinessException(CodeUtil.FAIL, "导入失败，请确认文件模板格式是否符合要求");
        }
    }
}
