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

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

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

		XmCqdtfyExcel excel = new XmCqdtfyExcel();
		excel.setXh(data.get(0));
		excel.setXmbh(data.get(1));
		excel.setXmmc(data.get(2));
		excel.setCtdtfybm(data.get(3));
		excel.setCtdtfymc(data.get(4));
		excel.setYt(data.get(5));
		Date txksrq = ValidationUtils.safeParseDate(data.get(6), DateUtil.PATTERN_DATE);
		if (txksrq != null) {
			excel.setTxksrq(DateUtil.format(txksrq, DateUtil.PATTERN_DATE));
		} else {
			errors.add("摊销开始时间为空或格式错误，yyyy-MM-dd");
		}
		excel.setSysm(ValidationUtils.safeParseInteger(data.get(7)));
		if (Func.isNull(excel.getSysm())) {
			errors.add("使用寿命数据格式错误");
		}
		excel.setYsyys(ValidationUtils.safeParseInteger(data.get(8)));
		if (Func.isNull(excel.getYsyys())) {
			errors.add("已使用月数数据格式错误");
		}
		excel.setZcyz(ValidationUtils.safeParseBigDecimal(data.get(9)));
		if (Func.isNull(excel.getZcyz())) {
			errors.add("资产原值数据格式错误");
		}
		excel.setYtxe(ValidationUtils.safeParseBigDecimal(data.get(10)));
		if (Func.isNull(excel.getYtxe())) {
			errors.add("月摊销额数据格式错误");
		}
		excel.setSyzb(ValidationUtils.safeParseBigDecimal(data.get(11)));
		if (Func.isNull(excel.getSyzb())) {
			errors.add("使用占比数据格式错误");
		}else {
			excel.setSyzb(excel.getSyzb().multiply(new BigDecimal("0.01")));
		}

		excel.setZbyj(data.get(12));
		excel.setFtyj(data.get(14));

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