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.YsZjtrfyExcel;
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 YsZjtrfyImportListener 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<>();

		YsZjtrfyExcel excel = new YsZjtrfyExcel();
		excel.setXh(data.get(0));
		excel.setWzmc(data.get(1));
		String yongliang = data.get(2);
		if(Func.isNotBlank(yongliang)){
			excel.setYongLiang(ValidationUtils.safeParseDouble(yongliang));
			if (Func.isNull(excel.getYongLiang())) {
				errors.add("用量数据格式错误");
			}
		}

		String danjia = data.get(4);
		if(Func.isNotBlank(danjia)){
			excel.setDanJia(ValidationUtils.safeParseDouble(danjia));
			if (Func.isNull(excel.getDanJia())) {
				errors.add("单价数据格式错误");
			}else {
				excel.setDanJia(excel.getDanJia() * 10000);
			}
		}

 		excel.setYqsbmc(data.get(6));

		String ysje = data.get(7);
		if(Func.isNotBlank(ysje)){
			excel.setYsje(ValidationUtils.safeParseDouble(ysje));
			if (Func.isNull(excel.getYsje())) {
				errors.add("仪器设备的预算金额（万元）数据格式错误");
			}else {
				excel.setYsje(excel.getYsje() * 10000);
			}
		}
		excel.setGdzcmc(data.get(8));
		String zlfyys = data.get(9);
		if(Func.isNotBlank(zlfyys)){
			excel.setZlfyys(ValidationUtils.safeParseDouble(zlfyys));
			if (Func.isNull(excel.getZlfyys())) {
				errors.add("固定资产租赁预算金额（万元）数据格式错误");
			}else {
				excel.setZlfyys(excel.getZlfyys() * 10000);
			}
		}

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