package com.thinkgem.jeesite.modules.img.service;

import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.modules.img.bean.ImgRequest;
import com.thinkgem.jeesite.modules.img.dao.ImgDao;
import com.thinkgem.jeesite.modules.img.util.ImgUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;


/**
 * 图片
 */
@Service
@Transactional(readOnly = true)
public class ImgService {

    @Autowired
    private ImgDao imgDao;

    public String uploadImg(ImgRequest request) {
        //将base64转为图片并保存到路径中
        String imgName = checkImgExist(request.getImgExt());
        ImgUtils.generateImage(request.getImgBase(), Global.getConfig("image.save.url") + imgName);
        //返回图片的的地址
        return Global.getConfig("sys.pre.url") + Global.getConfig("image.return.url") + imgName;
    }

    /**
     * 判断图片是否已存在
     *
     * @param ext 图片扩展名
     * @return 图片名
     */
    public String checkImgExist(String ext) {
        String imgName;
        boolean isExist = true;
        do {
            imgName = IdGen.randomBase62(32) + "." + ext;
            File file = new File(Global.getConfig("image.save.url") + imgName);
            if (!file.exists()) {
                isExist = false;
            }
        } while (isExist);
        return imgName;
    }
}
