package org.sky.scientific.excel.listener;

import com.alibaba.excel.context.AnalysisContext;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.sky.core.tool.utils.DateUtil;
import org.sky.core.tool.utils.Func;
import org.sky.scientific.excel.XmCostDetailsExcel;
import org.sky.scientific.utils.ImportResult;
import org.sky.scientific.utils.ValidationUtils;

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

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

		XmCostDetailsExcel excel = new XmCostDetailsExcel();
		excel.setSerialNumber(data.get(0));
		Date recordDate = ValidationUtils.safeParseDate(data.get(1), DateUtil.PATTERN_DATE);
		if(recordDate==null){
			errors.add("日期为空或格式错误，yyyy-MM-dd");
		}
		excel.setRecordDate(recordDate);
		excel.setXmbh(data.get(2));
		if(Func.isBlank(excel.getXmbh())){
			errors.add("研发项目编号为空");
		}
		excel.setVoucherNumber(data.get(5));
		if(Func.isBlank(excel.getVoucherNumber())){
			errors.add("凭证字号为空");
		}
		excel.setDigest(data.get(6));
		if(Func.isBlank(excel.getDigest())){
			errors.add("摘要为空");
		}
		excel.setESubjectCode(data.get(7));
		if(Func.isBlank(excel.getESubjectCode())){
			errors.add("科目代码为空");
		}
		excel.setESubjectName(data.get(8));
		if(Func.isBlank(excel.getESubjectName())){
			errors.add("科目名称为空");
		}

		excel.setAmount(ValidationUtils.safeParseBigDecimal(data.get(9)));
		if(Func.isNull(excel.getAmount())){
			errors.add("金额为空或格式错误");
		}

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