package com.fjhx.victoriatourist.controller.jd;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.fjhx.victoriatourist.service.jd.JdApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;


/**
 * <p>
 * 京东API 前端控制器
 * </p>
 *
 * @author
 * @since 2023-11-03
 */
@Slf4j
@Controller
@RequestMapping("/open/jd")
public class JdApiController {

    @Autowired
    private JdApiService jdApiService;
    private static String DOMAIN = "http://127.0.0.1:80";

    /**
     * 京东登录回调
     */
    @RequestMapping("/callback")
    public void callback(HttpServletResponse response, String code, String state) throws IOException {
        log.info("京东回调code：{},state：{}", code, state);
        String msg = "";
        if (StrUtil.isBlank(code) || StrUtil.isBlank(state)){
            msg = "参数错误";
//            response.sendError(HttpStatus.HTTP_BAD_REQUEST, "参数错误");
//            return;
        }
        //获取token并且入库
        try{
            jdApiService.getAccessTokenByCode(code);
        }catch (Exception e){
            log.error("京东获取token异常", e);
            msg = "京东获取token异常";
//            response.sendError(HttpStatus.HTTP_INTERNAL_ERROR, e.getMessage());
//            return;
        }
        response.sendRedirect(DOMAIN + "/callback.html?msg="+ URLEncoder.encode(msg));
    }


    @RequestMapping("/build2LoginUrl")
    @ResponseBody
    public String build2LoginUrl(){
        String url = jdApiService.build2LoginUrl();
//        String url = DOMAIN + "/testLogin.html?"+ IdUtil.getSnowflakeNextIdStr();
        return url;
    }

}
