package org.sky.scientific.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.excel.YsZjfyycqdtfyExcel;
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
public class YsZjfyycqdtfyImportListener 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<>();

		YsZjfyycqdtfyExcel excel = new YsZjfyycqdtfyExcel();
		excel.setXh(data.get(0));
		excel.setZcmc(data.get(1));

		String zzsc = data.get(2);
		if(Func.isNotBlank(zzsc)){
			excel.setZzsc(ValidationUtils.safeParseInteger(zzsc));
			if (Func.isNull(excel.getZzsc())) {
				errors.add("在项目中的工作时长（月）数据格式错误");
			}
		}

		excel.setCqdtfymc(data.get(5));

 		String cqdtfyysje = data.get(6);
		if(Func.isNotBlank(cqdtfyysje)){
			excel.setCqdtfyysje(ValidationUtils.safeParseBigDecimal(cqdtfyysje));
			if (Func.isNull(excel.getCqdtfyysje())) {
				errors.add("长期待摊费用预算金额数据格式错误");
			}else {
				excel.setCqdtfyysje(excel.getCqdtfyysje().multiply(new BigDecimal("10000")));
			}
		}
		errors.addAll(ValidationUtils.validate(excel));
		if (!errors.isEmpty()) {
			return ImportResult.error(rowIndex, errors, data.toString());
		}
		return ImportResult.success(rowIndex, excel);
	}
}
