package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.TableQrcodeMapper;
import com.ruoyi.system.domain.TableQrcode;
import com.ruoyi.system.service.ITableQrcodeService;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.List;

/**
 * 餐桌码Service业务层处理
 */
@Service
public class TableQrcodeServiceImpl extends ServiceImpl<BaseMapper<TableQrcode>, TableQrcode> implements ITableQrcodeService
{
    @Autowired
    private TableQrcodeMapper tableQrcodeMapper;

    @Override
    public TableQrcode selectTableQrcodeById(Long id)
    {
        return tableQrcodeMapper.selectTableQrcodeById(id);
    }

    @Override
    public List<TableQrcode> selectTableQrcodeList(TableQrcode tableQrcode)
    {
        return tableQrcodeMapper.selectTableQrcodeList(tableQrcode);
    }

    @Override
    public int insertTableQrcode(TableQrcode tableQrcode)
    {
        return tableQrcodeMapper.insertTableQrcode(tableQrcode);
    }

    @Override
    public int updateTableQrcode(TableQrcode tableQrcode)
    {
        return tableQrcodeMapper.updateTableQrcode(tableQrcode);
    }

    @Override
    public int deleteTableQrcodeById(Long id)
    {
        return tableQrcodeMapper.deleteTableQrcodeById(id);
    }

    @Override
    public int checkTableNoUnique(TableQrcode tableQrcode)
    {
        return tableQrcodeMapper.checkTableNoUnique(tableQrcode);
    }

    @Override
    public String generateQrcodeImage(Long id)
    {
        TableQrcode tableQrcode = tableQrcodeMapper.selectTableQrcodeById(id);
        if (tableQrcode == null || tableQrcode.getQrCode() == null || tableQrcode.getQrCode().isEmpty())
        {
            return null;
        }
        try
        {
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(tableQrcode.getQrCode(), BarcodeFormat.QR_CODE, 300, 300);
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(image, "png", os);
            return "data:image/png;base64," + Base64.getEncoder().encodeToString(os.toByteArray());
        }
        catch (WriterException | IOException e)
        {
            throw new RuntimeException("二维码生成失败", e);
        }
    }
}
