package cn.com.ctop.common.module.service.impl;

import cn.com.ctop.common.module.entity.BindAccountAuth;
import cn.com.ctop.common.module.entity.OauthConfig;
import cn.com.ctop.common.module.mapper.BindAccountAuthMapper;
import cn.com.ctop.common.module.service.IBindAccountAuthService;
import cn.com.ctop.common.module.service.IOauthConfigService;
import cn.com.ctop.common.module.utils.BytedanceInterfaceConstant;
import cn.com.ctop.common.module.utils.KuaishouInterfaceConstant;
import cn.com.ctop.common.module.utils.PropertiesUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 账号绑定-授权
 * @Author: jeecg-boot
 * @Date: 2019-07-31
 * @Version: V1.0
 */
@Slf4j
@Service
@Primary
public class BindAccountAuthServiceImpl extends ServiceImpl<BindAccountAuthMapper, BindAccountAuth> implements IBindAccountAuthService {
    @Value("${bytedance.appId}")
    private String bytedanceAppId;
    @Value("${bytedance.url.callback-url}")
    private String bytedanceCallbackUrl;
    @Value("${bytedance.url.auth-prefix}")
    private String bytedanceAuthUrl;
    @Autowired
    private BindAccountAuthMapper bindAccountAuthMapper;


    /**
     * 授权 绑定账号信息
     *
     * @param accountId
     * @param state
     */
    @Override
    public void addBindAccount(Long accountId, String authType, String state) {
        Map<String, Object> deleteMap = new HashMap<>();
        deleteMap.put("advertiser_id", state);
        deleteMap.put("account_id", accountId);
        deleteMap.put("auth_type", authType);
        bindAccountAuthMapper.deleteByMap(deleteMap);
        BindAccountAuth bindAccount = new BindAccountAuth();
        bindAccount.setAccountId(accountId);
        bindAccount.setAdvertiserId(state);
        bindAccount.setUpdateTime(new Date());
        bindAccount.setAuthType(authType);
        int i = bindAccountAuthMapper.insert(bindAccount);
        if (i > 0) {
            log.info("授权账号绑定成功，本地id:{}，accountId:{}", bindAccount.getAdvertiserId(), accountId);
        }
    }


    @Autowired
    private IOauthConfigService oauthConfigService;

    @Override
    public String getKuaishouCodeUrl(JSONObject state) throws UnsupportedEncodingException {
        StringBuffer sb = new StringBuffer();
        Long id = state.getLong("id");

        OauthConfig config = oauthConfigService.getById(id);
        state.put("appId", config.getAppId());
        state.put("callbackUrl", config.getCallbackUrl());
        sb.append(PropertiesUtils.getValue("kuaishou_config", "kuaishou_auth_url"))
                .append(KuaishouInterfaceConstant.AUTH_PATH)
                .append("?app_id=" + config.getAppId())
                .append("&state=" + URLEncoder.encode(URLEncoder.encode(state.toJSONString())))
                .append("&redirect_uri=" + URLEncoder.encode(config.getRedirectUri(), "UTF-8"));
        if (config.getOauthType() != 1) {
            sb.append("&scope=%5B%22report_service%22%2C%22ad_query%22%2C%22account_service%22%2C%22ad_manage%22%5D");
        } else {
            sb.append("&scope=%5B%22report_service%22%2C%22ad_query%22%2C%22ad_manage%22%5D");
        }
        return sb.toString();
    }

    @Override
    public String getByteDanceCodeUrl(String state) throws UnsupportedEncodingException {
        StringBuilder sb = new StringBuilder();
        sb.append(bytedanceAuthUrl)
                .append(BytedanceInterfaceConstant.AUTH_PATH)
                .append("?app_id=" + bytedanceAppId)
                .append("&state=" + URLEncoder.encode(state))
                .append("&material_auth=1")
                .append("&redirect_uri=" + URLEncoder.encode(bytedanceCallbackUrl, "UTF-8"));
        return sb.toString();
    }


}
