package com.zcloud.basic.info.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.basic.info.command.convertor.ImgFilesCoConvertor;
import com.zcloud.basic.info.domain.gateway.ImgFilesGateway;
import com.zcloud.basic.info.domain.model.ImgFilesE;
import com.zcloud.basic.info.persistence.dataobject.ImgFilesDO;
import com.zcloud.basic.info.persistence.repository.ImgFilesRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * web-app
 *
 * @Author zhangyue
 * @Date 2025-10-30 16:10:07
 */
@Component
@AllArgsConstructor
public class ImgFilesRemoveExe {
    private final ImgFilesGateway imgFilesGateway;
    private final ImgFilesRepository imgFilesRepository;
    private final ImgFilesCoConvertor imgFilesCoConvertor;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(String filePath) {
        ImgFilesE imgFilesE = new ImgFilesE();
        try {
            imgFilesE.deleteFile(filePath);
        } catch (Exception e) {
            throw new BizException("删除失败");
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long[] ids) {
        List<ImgFilesDO> imgFilesDOList = imgFilesRepository.listByIds(Arrays.asList(ids));
        List<ImgFilesE> imgFilesEList = imgFilesCoConvertor.converDOsToEs(imgFilesDOList);
        ImgFilesE imgFilesE = new ImgFilesE();
        try {
            imgFilesE.deleteFileList(imgFilesEList);
            imgFilesRepository.deleteList(ids);
        } catch (Exception e) {
            throw new BizException("删除失败");
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Map<String, Object> params) {
        List<ImgFilesDO> imgFilesDOList = imgFilesRepository.listAll(params);
        List<ImgFilesE> imgFilesEList = imgFilesCoConvertor.converDOsToEs(imgFilesDOList);
        ImgFilesE imgFilesE = new ImgFilesE();
        try {
            imgFilesE.deleteFileList(imgFilesEList);
            Long[] ids = imgFilesEList.stream().map(ImgFilesE::getId).toArray(Long[]::new);
            imgFilesRepository.deleteList(ids);
        } catch (Exception e) {
            throw new BizException("删除失败");
        }
        return true;
    }
}

