package com.zksy.system.basicData.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.utils.DeleteTableUtils;
import com.zksy.system.basicData.domain.CrmEnterpriseTrademarkInformation;
import com.zksy.system.basicData.domain.CrmFile;
import com.zksy.system.basicData.mapper.CrmEnterpriseTrademarkInformationMapper;
import com.zksy.system.basicData.service.CrmEnterpriseTrademarkInformationService;
import com.zksy.system.basicData.service.CrmFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * 企业商标信息Service业务层处理
 * 
 * @author sy
 * @date 2024-04-02
 */
@Service
public class CrmEnterpriseTrademarkInformationServiceImpl extends ServiceImpl<CrmEnterpriseTrademarkInformationMapper, CrmEnterpriseTrademarkInformation> implements CrmEnterpriseTrademarkInformationService {

    @Resource
    public CrmEnterpriseTrademarkInformationMapper mapper;

    @Autowired
    private CrmFileService crmFileService;

    @Override
    public AjaxResult removeFileById(List<String> ids,String localFileServerMappingPath,String localFileServerUploadDir) {
        List<CrmEnterpriseTrademarkInformation> crmEnterpriseTrademarkInformationList = mapper.selectBatchIds(ids);

        // 收集所有需要删除的文件路径
        List<String> filePathsToDelete = crmEnterpriseTrademarkInformationList.stream()
                .filter(entity -> !"".equals(entity.getTrademarkImage()))
                .map(entity -> {
                    String image = entity.getTrademarkImage();
                    int index = image.indexOf(localFileServerMappingPath);
                    if (index == -1) {
                        throw new RuntimeException("文件路径解析异常");
                    }
                    return localFileServerUploadDir + image.substring(index + localFileServerMappingPath.length());
                })
                .collect(Collectors.toList());

        // 使用线程池异步删除文件
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(10); // 根据实际情况调整线程数
        List<Future<Boolean>> futures = filePathsToDelete.stream()
                .map(filePath -> executor.submit(() -> {
                    File file = new File(filePath);
                    return file.exists() && file.delete();
                }))
                .collect(Collectors.toList());
        // 等待所有文件删除完成
        try {
            futures.forEach(future -> {
                try {
                    future.get(); // 阻塞等待文件删除完成
                } catch (Exception e) {
                    throw new RuntimeException("文件删除失败", e);
                }
            });
        } catch (Exception e) {
            return AjaxResult.error("文件删除失败");
        }

        // 删除数据库记录
        QueryWrapper<CrmFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("fid", ids);
        BaseMapper<CrmFile> baseMapper = crmFileService.getBaseMapper();
        baseMapper.delete(queryWrapper);

        // 删除商标信息
        mapper.deleteBatchIds(ids);

        return AjaxResult.success("文件已成功删除");
    }


    @Override
    @Transactional
    public AjaxResult deleteAll() {
        DeleteTableUtils<CrmEnterpriseTrademarkInformation> utils = new DeleteTableUtils<>();
        utils.del(CrmEnterpriseTrademarkInformation::getId,mapper);
        return AjaxResult.success("全部删除成功");
    }
}
