package com.ywt.service.common;

import com.ywt.gapi.ResultCode;
import com.ywt.gapi.base.file.FileServiceGrpc;
import com.ywt.gapi.base.file.UploadImageRequest;
import com.ywt.gapi.base.file.UploadImageResponse;
import com.ywt.gapi.base.wechat.CreateQrCodeStrSceneRequest;
import com.ywt.gapi.base.wechat.CreateQrCodeStrSceneResponse;
import com.ywt.gapi.base.wechat.WeChatServiceGrpc;
import com.ywt.mg.core.utils.Checksum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author daiyihua
 * @create 2022-01-19 16:29
 * @program glasses_service
 * @description 微信服务调用I（二维码、图片等）
 **/
@Service
public class WeChatService {

    private Logger logger = LoggerFactory.getLogger(WeChatService.class);

    @Autowired
    private WeChatServiceGrpc.WeChatServiceBlockingStub weChatServiceBlockingStub;

    @Autowired
    private FileServiceGrpc.FileServiceBlockingStub fileServiceBlockingStub;


    /**
     * 发送小程序订阅消息
     *
     * @param sceneStr 公众号或小程序地址
     * @param terminal 终端
     * @param vPath    文件上传路径
     * @return createQrCodeStrScene
     */
    public String createQrCodeStrScene(String sceneStr, int terminal, String vPath) {
        CreateQrCodeStrSceneRequest req = CreateQrCodeStrSceneRequest.newBuilder()
                .setSceneStr(sceneStr)
                .setType(terminal)
                .build();
        CreateQrCodeStrSceneResponse res = weChatServiceBlockingStub.createQrCodeStrScene(req);

        if (res.getCode() == ResultCode.SUCCEED_VALUE) {
            //上传图片
            String imgExt = "jpg";
            UploadImageRequest uploadImageRequest = UploadImageRequest.newBuilder()
                    .setFilename(String.format("%s.%s", Checksum.crc32(res.getQrData().toByteArray()), imgExt))
                    .setDatas(res.getQrData())
                    .setVpath(vPath).build();
            UploadImageResponse uploadImageResponse = fileServiceBlockingStub.uploadImage(uploadImageRequest);
            if (uploadImageResponse.getCode() == 0) {
                logger.info("createQrCodeStrScene(): 图片上传成功：{}\t{}\t{}\t{}", sceneStr, terminal, vPath, uploadImageResponse.getMsg());
                return uploadImageResponse.getRealityUrl();
            } else {
                logger.error("createQrCodeStrScene(): 图片上传失败，{}\t{}\t{}\t{}", sceneStr, terminal, vPath, uploadImageResponse.getMsg());
            }
        } else {
            logger.info("WeChatService#createQrCodeStrScene({})创建二维码失败: {}", req, res.getInfo());
        }
        return "";
    }
}
