package com.lovenav.service.serviceImpl;

import com.alibaba.fastjson.JSON;
import com.lovenav.dao.CollectIconListDao;
import com.lovenav.dao.UrlListDao;
import com.lovenav.entity.CollectIconList;
import com.lovenav.entity.UrlList;
import com.lovenav.service.QRCService;
import com.lovenav.utils.QRCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;


@Service
public class QRCServiceImpl implements QRCService{
    @Autowired
    private UrlListDao urlListDao;
    @Autowired
    private CollectIconListDao collectIconListDao;

    public String QR(CollectIconList collect) throws Exception {
        String logoPath ="src/main/resources/static/logo/NAV.png";
        String destPath = "src/main/resources/static/qr";
//        通过传入collect的url_id查找相同网址图片列表
//        List<CollectIconList> collectIconList = collectIconListDao.selectByUrlid(collect.getUrl_id());

//        通过collect的url_id查找网址id对应网址
        UrlList urlList = urlListDao.selectByPrimaryKey(Long.valueOf(collect.getUrl_id()));

        List<CollectIconList> list = collectIconListDao.selectByUrlid(collect.getUrl_id());
        if(list.size()==0){
            if(urlList != null){
//        将icon下载到本地并存储本地路径
                String icon_url = QRCodeUtil.downloadPicture(collect.getIcon_url());
                collect.setIcon_url(icon_url);
//        获取网址url
                String url = urlList.getUrl();
//        将网址生成二维码并返回本地路径
                String url_wait = QRCodeUtil.encode(url, logoPath, destPath, true);
//        为collect设置二维码本地路径
                collect.setQr_url(url_wait);
                collectIconListDao.insert(collect);
                String base64 = QRCodeUtil.ImageToBase64(url_wait);
                return JSON.toJSONString(base64);
            }else{
                HashMap<String,Object> result = new HashMap<>();
                result.put("code",500);
                result.put("msg", "找不到对应网址");
                return JSON.toJSONString(result);
            }
        }else{
            String url_wait = list.get(0).getQr_url();
            String base64 = QRCodeUtil.ImageToBase64(url_wait);
            return JSON.toJSONString(base64);
        }
    }
}
