package com.njyunzhi.pet_identity.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaQrcodeService;
import cn.binarywang.wx.miniapp.bean.WxMaCodeLineColor;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.njyunzhi.pet_identity.common.OSSUtils;
import com.njyunzhi.pet_identity.common.StringUtils;
import com.njyunzhi.pet_identity.common.WxUtils;
import com.njyunzhi.pet_identity.entity.TaMiniappQrcode;
import com.njyunzhi.pet_identity.mapper.TaMiniappQrcodeMapper;
import com.njyunzhi.pet_identity.mapper.TaSequenceMapper;
import com.njyunzhi.pet_identity.service.ITaMiniappQrcodeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njyunzhi.pet_identity.vo.MiniAppScene;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileNotFoundException;
import java.time.LocalDateTime;

/**
 * <p>
 * 小程序码 服务实现类
 * </p>
 *
 * @author yansen
 * @since 2022-05-28
 */
@Service
public class TaMiniappQrcodeServiceImpl extends ServiceImpl<TaMiniappQrcodeMapper, TaMiniappQrcode> implements ITaMiniappQrcodeService {

    @Autowired
    WxUtils wxUtils;
    
    @Autowired
    OSSUtils ossUtils;

    @Value("${weixin.miniapp.appid}")
    String miniAppid;

    @Value("${yz.miniapp.qrpath}")
    String qrpath;

    @Value("${yz.miniapp.qrEnv}")
    String envVersion;

    @Autowired
    TaSequenceMapper taSequenceMapper;

    @Override
    public TaMiniappQrcode createQRCode(MiniAppScene scene) throws Exception {
        String sceneStr = JSON.toJSONString(scene);
        TaMiniappQrcode taMiniappQrcode = getByScene(sceneStr);
        if (null != taMiniappQrcode) return taMiniappQrcode;

        // 从 nextval 是从 0 开始, qrcodeId 必须从 +1 开始
        Integer qrCodeID = taSequenceMapper.getNextVal("qrcode") + 1;

        // 调用SDK, 生成小程序码, 小程序码的 scene 实际上是 TaMiniappQrcode 的主键
        String qrImage = buildMAQrCode(qrCodeID.toString());
        //
        taMiniappQrcode = new TaMiniappQrcode();
        taMiniappQrcode.setQrId(qrCodeID);
        taMiniappQrcode.setMiniappId(miniAppid);
        taMiniappQrcode.setPage(qrpath);
        taMiniappQrcode.setScene(sceneStr);
        taMiniappQrcode.setQrImage(qrImage);

        if (!save(taMiniappQrcode)) {
            throw new Exception("生成小程序码失败, 请重试");
        }

        return taMiniappQrcode;
    }

    public TaMiniappQrcode getByScene(String sceneStr) {
        LambdaQueryWrapper<TaMiniappQrcode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TaMiniappQrcode::getMiniappId, miniAppid)
                .eq(TaMiniappQrcode::getPage, qrpath)
                .eq(TaMiniappQrcode::getScene, sceneStr)
                .orderByDesc(TaMiniappQrcode::getCreateDate)
                .last("limit 1");

        return getOne(queryWrapper);
    }

    /**
     * 生成小程序码, 并上传阿里云
     * @param scene
     * @return
     * @throws WxErrorException
     */
    private String buildMAQrCode(String scene) throws WxErrorException, FileNotFoundException {
        WxMaQrcodeService qrcodeService = wxUtils.getMaService().getQrcodeService();
        File qrFile = qrcodeService.createWxaCodeUnlimit(scene,
                qrpath,
                false, // checkPath
                envVersion,
                430, // width
                false, // autoColor
                new WxMaCodeLineColor("0", "0", "0"), // lineColor
                true // isHyaline 透明色
                );

        return ossUtils.putObject(qrFile);
    }
}
