package com.bweb.excelListener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.bweb.model.ImportGiveAwayModel;
import com.hai.common.utils.MemberValidateUtil;
import com.hai.entity.*;
import com.hai.model.HighCouponHandselModel;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
public class ImportGiveAwayListener extends AnalysisEventListener<ImportGiveAwayModel> {

    // 数据
    private Integer serialNum = 1;
    public List<ImportGiveAwayModel> dataList = new ArrayList<>();
    public List<HighUser> userList;

    /**
     * @Author 胡锐
     * @Description 解析到的每一条数据都会调用此方法
     * @Date 2021/3/20 21:08 
     **/
    @Override
    public void invoke(ImportGiveAwayModel giveAwayModel, AnalysisContext analysisContext) {
        giveAwayModel.setSerialNum(serialNum);
        serialNum++;

        // 校验账户手机号
        if (StringUtils.isNotBlank(giveAwayModel.getPhone())) {
            if (!MemberValidateUtil.validatePhone(giveAwayModel.getPhone())) {
                giveAwayModel.setRegisterStatus(false);
                giveAwayModel.setErrorStatus(true);
                giveAwayModel.setErrorMsg("手机号格式错误");
                dataList.add(giveAwayModel);
                return;
            }
            // 查询是否注册
            long count = userList.stream().filter(o -> o.getPhone().equals(giveAwayModel.getPhone())).count();
            giveAwayModel.setRegisterStatus(count == 0?false:true);

            if (this.dataList.stream().filter(o -> o.getPhone().equals(giveAwayModel.getPhone())).count() >= 1) {
                giveAwayModel.setErrorStatus(true);
                giveAwayModel.setErrorMsg("手机号重复增加");
                dataList.add(giveAwayModel);
                return;
            }
            giveAwayModel.setErrorStatus(false);
            dataList.add(giveAwayModel);
        }
    }

    /**
     * @Author 胡锐
     * @Description 所有数据解析完成了 都会来调用此方法
     * @Date 2021/3/20 21:08 
     **/
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        this.dataList = dataList.stream().sorted(Comparator.comparing(ImportGiveAwayModel::getErrorStatus).reversed()).collect(Collectors.toList());
    }

    public void initData(List<HighUser> userList) {
        this.userList = userList;
    }
}
