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.YsRyrgfyExcel;
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 YsRyrgfyImportListener 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<>();

		YsRyrgfyExcel excel = new YsRyrgfyExcel();
		excel.setXh(data.get(0));
		excel.setName(data.get(1));
		excel.setNumber(data.get(2));
		excel.setIdCard(data.get(3));

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

		String pjrgfy = data.get(5);
		if(Func.isNotBlank(pjrgfy)){
			excel.setPjrgfy(ValidationUtils.safeParseBigDecimal(pjrgfy));
			if (Func.isNull(excel.getPjrgfy())) {
				errors.add("月平均人工费用（元）数据格式错误");
			}else {
				excel.setPjrgfy(excel.getPjrgfy().multiply(BigDecimal.valueOf(10000)));
			}
		}
		errors.addAll(ValidationUtils.validate(excel));
		if (!errors.isEmpty()) {
			return ImportResult.error(rowIndex, errors, data.toString());
		}
		return ImportResult.success(rowIndex, excel);
	}
}
