package org.eco.als.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.mybatisflex.core.query.QueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.eco.als.domain.Product;
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.listener.ProductImportListener;
import org.eco.als.mapper.ProductMapper;
import org.eco.als.service.IProductService;
import org.eco.common.core.core.domain.model.LoginUser;
import org.eco.common.core.utils.MapstructUtils;
import org.eco.common.excel.entity.ExcelResultRes;
import org.eco.common.excel.service.IExcelService;
import org.eco.common.orm.core.service.impl.BaseServiceImpl;
import org.eco.system.service.IImportExportService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import static org.eco.als.domain.table.ProductTableDef.PRODUCT;

/**
 * 产品树Service业务层处理
 *
 * @author wgk
 * @date 2024-07-19
 */
@Service
@Slf4j
public class ProductServiceImpl extends BaseServiceImpl<ProductMapper, Product> implements IProductService {
    @Resource
    private ProductMapper productMapper;

    @Resource
    private IExcelService excelService;

    @Resource
    private IImportExportService importExportService;

    @Override
    public QueryWrapper query() {
        return super.query().from(PRODUCT);
    }

    private QueryWrapper buildQueryWrapper(ProductBo productBo) {
        QueryWrapper queryWrapper = super.buildBaseQueryWrapper();
        queryWrapper.and(PRODUCT.SNS_CODE.eq
            (productBo.getSnsCode()));
        queryWrapper.and(PRODUCT.NAME.like
            (productBo.getName()));
        queryWrapper.orderBy(PRODUCT.ORDER_NUM.asc());

        return queryWrapper;
    }

    /**
     * 查询产品树
     *
     * @param id 产品树主键
     * @return 产品树
     */
    @Override
    public ProductVo selectById(Long id) {
        return this.getOneAs(query().where(PRODUCT.ID.eq(id)), ProductVo.class);

    }

    /**
     * 查询产品树
     *
     * @param name 产品树主键
     * @return 产品树
     */
    @Override
    public ProductVo selectByName(String name) {
        return this.getOneAs(query().where(PRODUCT.NAME.eq(name)), ProductVo.class);
    }

    /**
     * 查询产品树列表
     *
     * @param productBo 产品树Bo
     * @return 产品树集合
     */
    @Override
    public List<ProductVo> selectList(ProductBo productBo) {
        QueryWrapper queryWrapper = buildQueryWrapper(productBo);
        return this.listAs(queryWrapper, ProductVo.class);
    }


    /**
     * 新增产品树
     *
     * @param productBo 产品树Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insert(ProductBo productBo) {
        Product product = MapstructUtils.convert(productBo, Product.class);

        return this.save(product);//使用全局配置的雪花算法主键生成器生成ID值
    }

    /**
     * 新增产品树，前台提供主键值，一般用于导入的场合
     *
     * @param productBo 产品树Bo
     * @return 结果:true 操作成功，false 操作失败
     */
    @Override
    public boolean insertWithPk(ProductBo productBo) {
        Product product = MapstructUtils.convert(productBo, Product.class);

        //获取祖级列表字段
        assert product != null;
        Long parentId = product.getParentId();
        if (parentId == 0) {
            product.setAncestors("0");
        } else {
            ProductVo parentProduct = selectById(productBo.getParentId());
            if (ObjectUtil.isNotNull(parentProduct)) {
                product.setAncestors(parentProduct.getAncestors() + "," + parentId);
            } else {
                product.setAncestors("0");
            }
        }

        return productMapper.insertWithPk(product) > 0;//前台传来主键值
    }

    @Override
    public boolean insertWithName(ProductBo productBo) {
        Product product = MapstructUtils.convert(productBo, Product.class);
        assert product != null;
        //获取祖级列表
        ProductVo productVo = this.selectByName(product.getParentName());
        if (productVo.getParentId() == 0) {
            product.setAncestors("0");
        } else {
            ProductVo parentProduct = selectById(productBo.getParentId());
            if (ObjectUtil.isNotNull(parentProduct)) {
                product.setAncestors(parentProduct.getAncestors() + "," + productVo.getParentId());
            } else {
                product.setAncestors("0");
            }
        }
        return productMapper.insert(product) > 0;//前台传来主键值
    }

    /**
     * 修改产品树
     *
     * @param productBo 产品树Bo
     * @return 结果:true 更新成功，false 更新失败
     */
    @Override
    public boolean update(ProductBo productBo) {
        Product product = MapstructUtils.convert(productBo, Product.class);
        if (ObjectUtil.isNotNull(product) && ObjectUtil.isNotNull(product.getId())) {
            return this.updateById(product);
        }
        return false;
    }

    @Override
    public void asyncImportData(MultipartFile file, boolean updateSupport, LoginUser loginUser) {
        ExcelResultRes result;
        try {
            String name = file.getOriginalFilename();
            result = excelService.importExcel(file.getInputStream(), name, ProductImportVo.class, new ProductImportListener(updateSupport, loginUser));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        boolean flag = importExportService.saveInfo(result, loginUser, "0");
        if (flag) {
            log.info("异步导入日志写入成功");
        }
    }

    @Override
    public void asyncExport(List<ProductVo> listVo, String sheetName, LoginUser loginUser) {
        ExcelResultRes result = excelService.exportExcel(listVo, sheetName, ProductVo.class);
        boolean flag = importExportService.saveInfo(result, loginUser, "1");
        if (flag) {
            log.info("异步导出日志写入成功");
        }
    }

    /**
     * 批量删除产品树
     *
     * @param ids 需要删除的产品树主键集合
     * @return 结果:true 删除成功，false 删除失败
     */
    @Transactional
    @Override
    public boolean deleteByIds(Long[] ids) {
        return this.removeByIds(Arrays.asList(ids));
    }

}
