package org.sky.scientific.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;
import org.sky.core.tool.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.excel.XmGoodsExcel;
import org.sky.scientific.utils.ImportResult;
import org.sky.scientific.utils.ValidationUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
public class XmGoodsImportListener extends BaseReadListener {

	@Override
	public void invoke(Map<Integer, String> map, AnalysisContext context) {
		int rowIndex = context.readRowHolder().getRowIndex() + 1;

		ImportResult<Object> result = convertAndValidate(map, rowIndex);
		resultList.add(result);
		if (result.isSuccess()) {
			dataList.add(result.getData());
			incrementSuccessCount();
		} else {
			incrementErrorCount();
		}
	}

	private ImportResult<Object> convertAndValidate(Map<Integer, String> data, int rowIndex) {

		List<String> errors = new ArrayList<>();

		XmGoodsExcel excel = new XmGoodsExcel();
		excel.setXh(data.get(0));
		excel.setUseDate(ValidationUtils.safeParseDate(data.get(1), DateUtil.PATTERN_DATE));
		if (excel.getUseDate() == null) {
			errors.add("领取日期为空或格式错误，yyyy-MM-dd");
		}
		excel.setXmbh(data.get(2));
		excel.setXmmc(data.get(3));
		excel.setType(data.get(4));
		excel.setCode(data.get(5));
		excel.setName(data.get(6));
		excel.setModel(data.get(7));
		excel.setUnit(data.get(8));

		String unitPrice = data.get(9);
		if(Func.isNotBlank(unitPrice)){
			BigDecimal tmp = ValidationUtils.safeParseBigDecimal(data.get(9));
			if(tmp==null || tmp.compareTo(BigDecimal.ZERO) <= 0){
				errors.add("单价须为数字，且大于等于0");
			}
			excel.setUnitPrice(tmp);
		}
		String useQuantity = data.get(10);
		if(Func.isNotBlank(useQuantity)){
			Double tmp = ValidationUtils.safeParseDouble(useQuantity);
			if(tmp == null || tmp <= 0){
				errors.add("领取数量须为数字，且大于等于0");
			}
			excel.setUseQuantity(tmp);
		}
		excel.setAmount(BigDecimal.valueOf(excel.getUseQuantity()).multiply(excel.getUnitPrice()));

		errors.addAll(ValidationUtils.validate(excel));
		if (!errors.isEmpty()) {
			return ImportResult.error(rowIndex, errors, data.toString());
		}
		return ImportResult.success(rowIndex, excel);
	}
}
