package org.dromara.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HtmlUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.SpringUtils;
import org.dromara.common.core.utils.StreamUtils;
import org.dromara.common.core.utils.ValidatorUtils;
import org.dromara.common.excel.core.ExcelListener;
import org.dromara.common.excel.core.ExcelResult;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.domain.houseInfo.bo.HouseInfoBo;
import org.dromara.domain.houseInfo.vo.HouseInfoVo;
import org.dromara.service.IHouseInfoService;

import java.util.List;

/**
 * 系统用户自定义导入
 *
 * @author Lion Li
 */
@Slf4j
public class HouseInfoImportListener extends AnalysisEventListener<HouseInfoVo> implements ExcelListener<HouseInfoVo> {

    private final IHouseInfoService houseInfoService;

    private final Long operUserId;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();


    public HouseInfoImportListener() {
        this.houseInfoService = SpringUtils.getBean(IHouseInfoService.class);
        this.operUserId = LoginHelper.getUserId();
    }

    @Override
    public void invoke(HouseInfoVo houseVo, AnalysisContext context) {
        try {
            HouseInfoBo houseInfo = BeanUtil.toBean(houseVo, HouseInfoBo.class);
            ValidatorUtils.validate(houseInfo);
            houseInfo.setCreateBy(operUserId);
            houseInfoService.insertByBo(houseInfo);
            successNum++;
            successMsg.append("<br/>").append(successNum).append("、账号 ").append(houseInfo.getPropertyUnitNumber()).append(" 导入成功");

        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、账号 " + HtmlUtil.cleanHtmlTag(houseVo.getPropertyUnitNumber()) + " 导入失败：";
            String message = e.getMessage();
            if (e instanceof ConstraintViolationException cvException) {
                message = StreamUtils.join(cvException.getConstraintViolations(), ConstraintViolation::getMessage, ", ");
            }
            failureMsg.append(msg).append(message);
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<HouseInfoVo> getExcelResult() {
        return new ExcelResult<>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<HouseInfoVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
