package com.jeeplus.test.editor.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeeplus.test.editor.domain.EditorFiles;
import com.jeeplus.test.editor.mapper.EditorFilesMapper;
import com.jeeplus.test.oss.service.OssService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

@Service
@Transactional
public class EditorFilesService extends ServiceImpl<EditorFilesMapper, EditorFiles> {

    @Resource
    private OssService ossService;

    @Resource
    private EditorFilesMapper editorFilesMapper;

    /**
     * 将富文本内容中的临时图片地址替换为新的
     * @param content 富文本内容
     * @param sourceId 数据id
     * @return
     */
    public String getNewContent(String content,String sourceId){
        List<EditorFiles> list = this.list(new QueryWrapper<EditorFiles>().lambda().eq(EditorFiles::getSourceId, sourceId));
        AtomicReference<String> replace = new AtomicReference<>(content.replace("amp;", ""));
        list.stream().forEach(item->{
            boolean contains = replace.get().contains(item.getTemporaryUrl());
            if(contains){
                String fileTemporaryLookUrl = ossService.getFileTemporaryLookUrl(item.getUrl());
                String r = replace.get().replace(item.getTemporaryUrl(),fileTemporaryLookUrl);
                replace.set(r);
                EditorFiles editorFiles = new EditorFiles();
                editorFiles.setTemporaryUrl(fileTemporaryLookUrl);
                editorFiles.setSourceId(sourceId);
                this.update(editorFiles,new QueryWrapper<EditorFiles>().lambda().eq(EditorFiles::getSourceId,sourceId).eq(EditorFiles::getTemporaryUrl,item.getTemporaryUrl()));
            }
        });
        return replace.get();
    }

    /**
     * 富文本图片新增
     * @param temporaryUrl
     * @param url
     * @param sourceId
     * @return
     */
    public void saveUrl(String temporaryUrl,String url,String sourceId){
        EditorFiles editorFiles = new EditorFiles();
        editorFiles.setSourceId(sourceId);
        editorFiles.setTemporaryUrl(temporaryUrl);
        editorFiles.setUrl(url);
        this.save(editorFiles);
    }
}
