package org.eco.als.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.mybatisflex.core.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.eco.als.domain.bo.ProductBo;
import org.eco.als.domain.vo.ProductImportVo;
import org.eco.als.domain.vo.ProductVo;
import org.eco.als.service.IProductService;
import org.eco.common.core.core.domain.model.LoginUser;
import org.eco.common.core.utils.SpringUtils;
import org.eco.common.core.utils.ValidatorUtils;
import org.eco.common.excel.core.ExcelListener;
import org.eco.common.excel.core.ExcelResult;
import org.eco.common.excel.entity.ExcelResultRes;

import java.util.List;

/**
 * 产品树自定义导入
 *
 * @author wgk
 */
@Slf4j
public class ProductImportListener extends AnalysisEventListener<ProductImportVo> implements ExcelListener<ProductImportVo> {
    private final IProductService productService;

    private final Boolean isUpdateSupport;
    private final LoginUser loginUser;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();
    private int successNum = 0;
    private int failureNum = 0;

    public ProductImportListener(Boolean isUpdateSupport, LoginUser loginUser) {
        this.productService = SpringUtils.getBean(IProductService.class);
        this.isUpdateSupport = isUpdateSupport;
        this.loginUser = loginUser;
    }

    @Override
    public void invoke(ProductImportVo productVo, AnalysisContext context) {
        try {
            ProductBo productBo = BeanUtil.toBean(productVo, ProductBo.class);
            QueryWrapper queryWrapper = QueryWrapper.create();
            queryWrapper.where("name = ?", productBo.getName());
            queryWrapper.and("parent_name = ?", productBo.getParentName());
            queryWrapper.or("(name = ?", productBo.getName()).and("parent_id = ?)", 0);
            ProductVo productVo1 = productService.getOneAs(queryWrapper, ProductVo.class);
            ProductVo productVo2 = productService.selectByName(productBo.getParentName());
            if (ObjectUtil.isNull(productVo1)) {
                //不存在就新增
                setBo(productBo);
                productBo.setParentId(ObjectUtil.isNull(productVo2) ? 0 : productVo2.getId());
                productBo.setParentName(ObjectUtil.isNull(productVo2) ? "" : productVo2.getName());
                ValidatorUtils.validate(productBo);
                boolean inserted = productService.insert(productBo);//树表需要前台传来主键值
                if (inserted) {
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、产品树 记录导入成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、产品树 记录导入失败");
                }
            } else if (isUpdateSupport) {
                //存在就更新
                productBo.setId(productVo1.getId());//主键
                productBo.setVersion(productVo1.getVersion());
                boolean updated = productService.update(productBo);
                if (updated) {
                    successNum++;
                    successMsg.append("<br/>").append(successNum).append("、产品树 记录更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>").append(failureNum).append("、产品树 记录更新失败");
                }
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、产品树 记录导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    private void setBo(ProductBo productBo) {
        productBo.setVersion(0);
        productBo.setCreateBy(loginUser.getUserId());
        productBo.setUpdateBy(loginUser.getUserId());
        productBo.setTenantId(loginUser.getTenantId());
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        log.info("解析完成");
    }

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

            @Override
            public ExcelResultRes getAnalysis() {
                if (failureNum > 0 && successNum == 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据没有成功导入，错误如下：");
                    return ExcelResultRes.builder().logInfo(failureMsg.toString()).status("0").build();
                } else if (failureNum > 0 && successNum > 0) {
                    failureMsg.insert(0, "很抱歉，部分导入失败！共 " + failureNum + " 条数据没有成功导入，错误如下：");
                    return ExcelResultRes.builder().logInfo(failureMsg.toString()).status("2").build();
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                    return ExcelResultRes.builder().logInfo(successMsg.toString()).status("1").build();
                }
            }

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

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