package com.bcxin.platform.web.controller.oauth;

import com.bcxin.platform.common.constant.Constants;
import com.bcxin.platform.common.utils.ResponseJsonUtils;
import com.bcxin.platform.common.utils.Result;
import com.bcxin.platform.common.utils.StringUtils;
import com.bcxin.platform.domain.company.PerBaseInfo;
import com.bcxin.platform.dto.oauth.AccessToken;
import com.bcxin.platform.service.company.PerBaseInfoService;
import com.bcxin.platform.service.oauth.OAuthService;
import com.bcxin.platform.service.system.ISysConfigService;
import com.bcxin.platform.util.AESUtil;
import com.bcxin.platform.util.constants.CommonConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author linqinglin
 * @date 2021/06/01 0001 13:09
 */
@Controller
public class UrlController {

    @Autowired
    private OAuthService oAuthService;

    @Resource
    private ISysConfigService sysConfigService;

    @Autowired
    private PerBaseInfoService perBaseInfoService;

    @RequestMapping("redirect")
    public String redirect(HttpServletRequest request, HttpServletResponse response)throws Exception{
        try {
            String token = request.getParameter("token");
            String url = request.getParameter("url");
            String v5_access_token = request.getParameter("v5_access_token");
            String mobilePhone = request.getParameter("mobilePhone");
            String tlkId = AESUtil.decode(token);
            //System.out.println(URLEncoder.encode("taskmanager/tasklist","UTF-8"));
            PerBaseInfo perBaseInfo = perBaseInfoService.selectPerBaseInfoByTlkId(tlkId);
            AccessToken accessToken = oAuthService.getAccessToken(CommonConst.CLIENTTYPE_WEB,perBaseInfo);
            String webUrl = sysConfigService.selectConfigByKey(Constants.WEB_URL);


            webUrl = webUrl + url+"?access_token="+accessToken.getTokenId();
            if(StringUtils.isNotEmpty(v5_access_token)){
                webUrl = webUrl + "&v5_access_token="+v5_access_token;
            }
            if(StringUtils.isNotEmpty(mobilePhone)){
                webUrl = webUrl + "&mobilePhone="+mobilePhone;
            }

            return "redirect:" + webUrl;
        }catch (Exception e){
            e.printStackTrace();
            ResponseJsonUtils.writeJSON(response, Result.fail("token错误"));
            return "";
        }

    }

}
