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.YsSjfyExcel;
import org.sky.scientific.utils.ImportResult;
import org.sky.scientific.utils.ValidationUtils;

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

@EqualsAndHashCode(callSuper = true)
@Data
public class YsSjfyImportListener 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<>();

		YsSjfyExcel excel = new YsSjfyExcel();
		excel.setXh(data.get(0));
		excel.setSjnr(data.get(1));

		String ysje = data.get(3);
		if(Func.isNotBlank(ysje)){
			excel.setYsje(ValidationUtils.safeParseDouble(ysje));
			if (Func.isNull(excel.getYsje())) {
				errors.add("预算金额/万元数据格式错误");
			}else {
				excel.setYsje(excel.getYsje() * 10000);
			}
		}
		errors.addAll(ValidationUtils.validate(excel));
		if (!errors.isEmpty()) {
			return ImportResult.error(rowIndex, errors, data.toString());
		}
		return ImportResult.success(rowIndex, excel);
	}
}
