package com.ruoyi.xq.manager;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.vo.SysOssVo;
import com.ruoyi.system.service.ISysOssService;
import com.ruoyi.xq.domain.UserExtend;
import com.ruoyi.xq.service.UserExtendService;
import com.ruoyi.xq.util.ImageUtil;
import com.ruoyi.xq.util.QrUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;

@Component
@Slf4j
public class ShareManager {
    private final static String login = "https://xq.mubai8888.com/login?inviteCode=";

    @Autowired
    private UserExtendService userExtendService;
    @Autowired
    private ISysOssService sysOssService;

    public String genQrCode(String usercode){
        UserExtend userExtend = userExtendService.getByUserCode(usercode);
        if(userExtend == null){
            return null;
        }
        if(StringUtils.isNotEmpty(userExtend.getQrUrl())){
            return userExtend.getQrUrl();
        }
        String url = login + usercode;
        try {
            File file = QrUtils.generateQrCode(usercode, url);
            SysOssVo oss = sysOssService.upload(file);
            userExtendService.update(Wrappers.lambdaUpdate(UserExtend.class).eq(UserExtend::getId, userExtend.getId())
                    .set(UserExtend::getQrUrl, oss.getUrl()));
            return oss.getUrl();
        } catch (Exception e) {
            log.error("生成QR二维码失败!", e);
            return null;
        }
    }

    public String getOrGenShareUrl(String usercode) {
        UserExtend userExtend = userExtendService.getByUserCode(usercode);
        if(userExtend == null){
            return null;
        }
        if(StringUtils.isNotEmpty(userExtend.getShareUrl())){
            return userExtend.getShareUrl();
        }
        return genShareUrl(usercode);
    }

    public String genShareUrl(String usercode){
        String qrUrl = genQrCode(usercode);
        if(qrUrl == null){
            return null;
        }
        try {
            File file = ImageUtil.genShareFile(usercode, qrUrl);
            SysOssVo oss = sysOssService.upload(file);
            userExtendService.update(Wrappers.lambdaUpdate(UserExtend.class).eq(UserExtend::getUsercode, usercode)
                    .set(UserExtend::getShareUrl, oss.getUrl()));
            return oss.getUrl();
        }catch (Exception e){
            log.error("生成分享二维码失败!", e);
            return null;
        }
    }
}
