package com.cyksj.model.excel.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.mapper.AppleAutoRegisterDataMapper;
import com.cyksj.model.entity.AppleAutoRegisterData;
import com.cyksj.model.excel.ExcelAppleIdTemplateData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;

import java.util.ArrayList;
import java.util.List;

/*
 *项目名: netflix
 *文件名: ExcelAppleDataListener
 *创建者: JavaZou
 *创建时间:2022/11/22 15:48
 */
public class ExcelAppleDataListener extends AnalysisEventListener<ExcelAppleIdTemplateData> {
	private static final Logger LOGGER = LoggerFactory.getLogger(ExcelAppleDataListener.class);

	private AppleAutoRegisterDataMapper appleAutoRegisterDataMapper;

	private String countryOrArea;

	private String remark;

	public ExcelAppleDataListener() {
	}

	public ExcelAppleDataListener(AppleAutoRegisterDataMapper appleAutoRegisterDataMapper, String countryOrArea, String remark) {
		this.appleAutoRegisterDataMapper = appleAutoRegisterDataMapper;
		this.countryOrArea = countryOrArea;
		this.remark = remark;
	}

	private List<ExcelAppleIdTemplateData> list = new ArrayList<>();

	private static final int BATCH_COUNT = 100;

	@Override
	public void invoke(ExcelAppleIdTemplateData data, AnalysisContext analysisContext) {
		LOGGER.info("解析到一条数据:{}", data);
		if (StrUtil.hasEmpty(data.getApplePwdId())) {
			throw new BusinessRuntimeException("表格缺少必填参数,请重新确认");
		}
		list.add(data);
		// 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
		if (list.size() >= BATCH_COUNT) {
			saveData();
			// 存储完成清理 list
			list.clear();
		}
	}

	@Override
	public void doAfterAllAnalysed(AnalysisContext analysisContext) {
		// 这里也要保存数据，确保最后遗留的数据也存储到数据库
		saveData();
		list.clear();
		LOGGER.info("所有数据解析完成！");
	}


	private void saveData() {
		for (ExcelAppleIdTemplateData data : list) {
			AppleAutoRegisterData appleAutoRegisterData = new AppleAutoRegisterData();
			BeanUtil.copyProperties(data, appleAutoRegisterData);
			AppleAutoRegisterData.CountryOrArea countryOrArea = AppleAutoRegisterData.CountryOrArea.valueOf(this.countryOrArea);
			if (countryOrArea == null) {
				throw BusinessRuntimeException.getInstance("该国家或区域不存在");
			}
			appleAutoRegisterData.setCountryOrArea(countryOrArea);
			appleAutoRegisterData.setRemark(remark);
			try {
				appleAutoRegisterDataMapper.insert(appleAutoRegisterData);
			} catch (DuplicateKeyException e) {
				LOGGER.info("重复Apple ID:{}记录！", data.getApplePwdId());
			}
		}
	}
}
