package com.xdap.self_development.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.xdap.self_development.common.MyResponse;
import com.xdap.self_development.domain.pojo.ResponsiblePersonPojo;
import com.xdap.self_development.domain.view.XdapUserView;
import com.xdap.self_development.service.ResponsiblePersonService;

import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

public class PersonReadListener implements ReadListener<ResponsiblePersonPojo> {
    MyResponse problems;
    private final ResponsiblePersonService responsiblePersonService;
    private final List<ResponsiblePersonPojo> cachedDataList;

    public PersonReadListener(ResponsiblePersonService responsiblePersonService, MyResponse problems) {
        this.problems = problems;
        this.responsiblePersonService = responsiblePersonService;
        this.cachedDataList = new ArrayList<>();
    }

    @Override
    public void invoke(ResponsiblePersonPojo responsiblePerson, AnalysisContext analysisContext) {
        if (analysisContext.readRowHolder().getRowIndex() == 1) {
            return;
        }
        if (
                responsiblePerson.getDepartment() == null ||
                        responsiblePerson.getUsername() == null ||
                        responsiblePerson.getSubsystem() == null
        ) {
            problems.setFlag(true);
            problems.getErrors().add("责任人导入失败:" + responsiblePerson.getUsername() + "数据不完整");
            return;
        }
        XdapUserView user = responsiblePersonService
                .getUserByDeptAndName(responsiblePerson.getDepartment(), responsiblePerson.getUserAccount(),
                        responsiblePerson.getUsername());
        if (user.getUserId() == null) {
            problems.setFlag(true);
            problems.getErrors().add("责任人导入失败:用户" + responsiblePerson.getUsername() + "无法找到或有多个重名用户");
        } else if (user.getDepartmentId() == null) {
            problems.setFlag(true);
            problems.getErrors().add("责任人导入失败:部门" + responsiblePerson.getDepartment() + "无法找到");
        } else {
            responsiblePerson.setUserId(user.getUserId());
            responsiblePerson.setDepartmentId(user.getDepartmentId());
            responsiblePerson.setPersonLevel(1);
            responsiblePerson.setCreationDate(Timestamp.valueOf(LocalDateTime.now()));
            cachedDataList.add(responsiblePerson);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        responsiblePersonService.importAllPerson(cachedDataList, problems);
        cachedDataList.clear();
    }
}
