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.YsWtwbyjkffyExcel;
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 YsWtwbyjkffyImportListener 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<>();

		YsWtwbyjkffyExcel excel = new YsWtwbyjkffyExcel();
		excel.setXh(data.get(0));
		excel.setStdwmc(data.get(1));
		excel.setZznr(data.get(2));

		String wwfy = data.get(3);
		if(Func.isNotBlank(wwfy)){
			excel.setWwfy(ValidationUtils.safeParseDouble(wwfy));
			if (Func.isNull(excel.getWwfy())) {
				errors.add("委外费用/万元数据格式错误");
			}else {
				excel.setWwfy(excel.getWwfy() * 10000);
			}
		}
		errors.addAll(ValidationUtils.validate(excel));
		if (!errors.isEmpty()) {
			return ImportResult.error(rowIndex, errors, data.toString());
		}
		return ImportResult.success(rowIndex, excel);
	}
}
