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.scientific.excel.AssetExcel;
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
@Slf4j
public class AssetImportListener 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<>();

		AssetExcel excel = new AssetExcel();
		excel.setXh(data.get(0));
		excel.setZcbm(data.get(1));
		excel.setZcmc(data.get(2));
		excel.setGl(data.get(3));
		excel.setZclb(data.get(4));
		excel.setYt(data.get(5));
		excel.setKssj(ValidationUtils.safeParseDate(data.get(6), DateUtil.PATTERN_DATE));
		if (excel.getKssj() == null) {
			errors.add("开始日期为空或格式错误，yyyy-MM-dd");
		}
 		excel.setSysm(ValidationUtils.safeParseInteger(data.get(7)));
 		excel.setZcyz(ValidationUtils.safeParseBigDecimal(data.get(9)));
		excel.setJcz(ValidationUtils.safeParseDoubleWithPercentage(data.get(10), "净残值"));
		excel.setYzje(ValidationUtils.safeParseBigDecimal(data.get(11)));
		excel.setStatusName(data.get(12));

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