package com.sv.api.service.impl.wechat;

import com.sv.api.context.PlatformContext;
import com.sv.dto.api.wechat.AccessTokenResponse;
import com.sv.entity.Platform;
import com.sv.service.common.PlatformService;
import com.ydd.framework.core.common.utils.HttpUtils;
import com.ydd.framework.core.common.utils.JsonMapper;
import com.ydd.framework.core.exception.ExceptionCodeTemplate;
import com.ydd.framework.core.exception.ServiceException;
import com.ydd.framework.core.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;


@Service
public class WechatService extends BaseServiceImpl {
    private Logger logger = LoggerFactory.getLogger(WechatService.class);

    //小程序登录 获取信息url
    private static final String ACCESS_TOKEN_URL = "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code";

    /**
     * 微信全局token缓存变量
     */
    public final static String REDIS_ACCESS_TOKEN = "SZPM_ACCESS_TOKEN";

    @Resource
    private PlatformService platformServiceImpl;


    /**
     * 通过code获取openid 小程序
     *
     * @param code
     * @return
     */
    public String getXcxOpenId(String code) {
        Platform platform = platformServiceImpl.findById(PlatformContext.getValue());
        String url = String.format(ACCESS_TOKEN_URL, platform.getAppId(), platform.getSecret(), code);
        String result = HttpUtils.get(url);
        AccessTokenResponse response = JsonMapper.nonEmptyMapper().fromJson(result, AccessTokenResponse.class);
        if (StringUtils.isBlank(response.getOpenid())) {
            logger.error("小程序openid获取失败：" + result);
            throw new ServiceException(ExceptionCodeTemplate.SERVICE_EXCEPTION);
        } else {
            String openId = response.getOpenid();
            String accessToken = response.getAccess_token();
            return openId;
        }
    }


/*    private boolean checkWxXml( Map<String,String> params) throws IOException {
        String signFromAPIResponse = params.get("sign").toString();
        if (signFromAPIResponse == "" || signFromAPIResponse == null) {
            logger.info("API返回的数据签名数据不存在，有可能被第三方篡改!!!");
            return false;
        }
        //清掉返回数据对象里面的Sign数据（不能把这个数据也加进去进行签名），然后用签名算法进行签名
        params.put("sign", "");
        String signForAPIResponse = getSign(params);
        logger.info("签名验证后的sign:"+signForAPIResponse+"  微信回调传入的sign:"+signFromAPIResponse);
        if (!signForAPIResponse.equalsIgnoreCase(signFromAPIResponse)) {
            logger.info("API返回的数据签名数据不一样，有可能被第三方篡改!!!");
            return false;
        }
        return true;
    }*/

/*    private String getSign(Map<String, String> map) {
        SortedMap<String, String> signParams = new TreeMap<>();
        for (Map.Entry<String, String> stringStringEntry : map.entrySet()) {
            signParams.put(stringStringEntry.getKey(), stringStringEntry.getValue());
        }
        signParams.remove("sign");
        String sign =  CommonUtils.getSign(signParams, key);
        return sign;
    }*/

}
