package com.ads.business.api;

import com.ads.business.service.TokenService;
import com.ads.common.data.JsonResult;
import com.ads.common.dingTalk.config.AppConfig;
import com.ads.common.dingTalk.domain.ConfigDTO;
import com.ads.common.dingTalk.exception.DingtalkEncryptException;
import com.ads.common.dingTalk.utils.JsApiSignature;
import com.ads.common.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Return
 * @Author hou
 * @Date 2021/9/3 13:15
 * @Destription
 */
@RestController
@RequestMapping("/api/auth")
@Api(tags = "用户授权相关")
public class AuthController {

    @Resource
    private AppConfig appConfig;

    @Resource
    private TokenService tokenService;

    @PostMapping("/config")
    @ApiOperation("获取调用钉钉api配置参数")
    public JsonResult<ConfigDTO> config(@RequestParam("url") String url){
        ConfigDTO configDTO = new ConfigDTO();
        JsonResult<String> result = tokenService.getJsTicket();
        configDTO.setCorpId(appConfig.getCorpId());
        configDTO.setAgentId(appConfig.getAgentId());
        configDTO.setJsticket(result.getData());
        configDTO.setNonceStr(JsApiSignature.genNonce());
        configDTO.setTimeStamp(System.currentTimeMillis()/1000);
        String sign;
        try {
            sign = JsApiSignature.sign(url, configDTO.getNonceStr(), configDTO.getTimeStamp(), configDTO.getJsticket());
        } catch (DingtalkEncryptException e) {
            throw new BusinessException("生成签名失败");
        }
        configDTO.setSignature(sign);
        return JsonResult.success(configDTO);
    }
}
