package com.fs.his.listenner;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.fs.his.domain.FsImportMember;
import com.fs.his.dto.MemberExcelDTO;
import com.fs.his.service.IFsImportMemberService;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;

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

public class MemberImportListener  extends AnalysisEventListener<MemberExcelDTO> {
    // 每批处理数量
    private static final int BATCH_COUNT = 500;

    private final List<MemberExcelDTO> cachedData  = new ArrayList<>(BATCH_COUNT);

    private final IFsImportMemberService fsImportMemberService;

    // 导入结果统计
    private int successCount = 0;
    private int failCount = 0;
    private final List<String> errorMsgs = new ArrayList<>();

    public MemberImportListener(IFsImportMemberService fsImportMemberService) {
        this.fsImportMemberService = fsImportMemberService;
    }

    @Override
    public void invoke(MemberExcelDTO data, AnalysisContext context) {
        // 数据校验
        if (StringUtils.isBlank(data.getMemberName())) {
            failCount++;
            errorMsgs.add("第" + context.readRowHolder().getRowIndex() + "行：姓名不能为空");
            return;
        }
        if (StringUtils.isBlank(data.getMemberPhone())) {
            failCount++;
            errorMsgs.add("第" + context.readRowHolder().getRowIndex() + "行：电话不能为空");
            return;
        }
        if (!data.getMemberPhone().matches("^1[3-9]\\d{9}$")) {
            failCount++;
            errorMsgs.add("第" + context.readRowHolder().getRowIndex() + "行：手机号格式错误");
            return;
        }

        cachedData.add(data);

        // 达到批量阈值，执行保存
        if (cachedData.size() >= BATCH_COUNT) {
            saveData();
            cachedData.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 保存剩余数据
        saveData();
    }

    private void saveData() {
        if (cachedData.isEmpty()) return;

        try {
            fsImportMemberService.batchInsert(cachedData);
            successCount += cachedData.size();
        } catch (DuplicateKeyException e) {
            for (MemberExcelDTO dto : cachedData) {
                try {
                    FsImportMember member = new FsImportMember();
                    BeanUtils.copyProperties(dto, member);
                    member.setStatus(0);
                    fsImportMemberService.insertFsImportMember(member);
                    successCount++;
                } catch (DuplicateKeyException ex) {
                    failCount++;
                    errorMsgs.add("第" + dto.getMemberPhone() + " 已存在");
                }
            }
        }
    }

    public Map<String, Object> getResult(){
        HashMap<String, Object> map = Maps.newHashMap();
        map.put("successCount", successCount);
        map.put("failCount", failCount);
        map.put("errorMsgs", errorMsgs);
        return map;
    }
}
