package com.cftech.shop.qrcode.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cftech.core.util.MpTokenUtil;
import com.cftech.core.util.OKHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author neil
 * @date 2017-12-05
 * @description 处理qrcode场景值的
 */
@Slf4j
@Component
public class WxQrcodeUtil {

    private static final String QRCODE_SCENE = "QRCODE:SCENE:ACCOUNTSID";
    private static final String MP_QRCODE_URI = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=TOKEN";

    @Autowired
    private RedisTemplate<String, String> redisApi;
    @Autowired
    private MpTokenUtil mpTokenUtil;




    /**
     * 获取当前帐号的场景值
     * @param accountsId
     * @return 返回场景值，利用redis，每次增加1
     */
    public Long getSceneId(Long accountsId) {
        String key = QRCODE_SCENE.replace("ACCOUNTSID", accountsId.toString());
        long sceneId = redisApi.opsForValue().increment(key, 1);
        return sceneId;
    }


    public JSONObject createLimitQrcode(Long accountsId, Long sceneId) {

        JSONObject retObj = new JSONObject();

        String qrcodeUri = MP_QRCODE_URI.replace("TOKEN", mpTokenUtil.getToken(accountsId)) ;
        JSONObject postJson = new JSONObject();
        postJson.put("action_name", "QR_LIMIT_SCENE");
        JSONObject actionInfoJson = new JSONObject();
        JSONObject sceneJson = new JSONObject();
        sceneJson.put("scene_id", sceneId);
        actionInfoJson.put("scene", sceneJson);
        postJson.put("action_info", actionInfoJson);

        try {
            String retStr = OKHttpUtils.postJSON(qrcodeUri, postJson.toJSONString());
            retObj = JSON.parseObject(retStr);
            return retObj;
        } catch (IOException e) {
            log.error("tcreateLimitQrcode from weixin got io error:" + e.getMessage());
            retObj.put("errcode", 1);
            retObj.put("errmsg", e.getMessage());
            return retObj;
        }

    }
}
