package com.cyksj.web.controller.mirror;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cyksj.common.EnvCommonService;
import com.cyksj.common.exception.BusinessRuntimeException;
import com.cyksj.common.task.GlobalThreadPoolTaskExecutor;
import com.cyksj.common.util.StringUtil;
import com.cyksj.dto.Result;
import com.cyksj.enums.GatewayResponse;
import com.cyksj.mapper.GroupsMapper;
import com.cyksj.mapper.GroupsRelationMapper;
import com.cyksj.mapper.WebInfoMapper;
import com.cyksj.mapper.renew.RenewUpgradePackageMapper;
import com.cyksj.model.dto.ChatgptUserVerifyDto;
import com.cyksj.model.entity.*;
import com.cyksj.model.views.*;
import com.cyksj.service.chatgpt.ChatGptAccountService;
import com.cyksj.service.claude.ClaudeService;
import com.cyksj.service.grok.GrokService;
import com.cyksj.service.luma.LumaService;
import com.cyksj.service.midjourney.MidjourneyAccountService;
import com.cyksj.service.quota.NanoUserQuotaService;
import com.cyksj.service.sys.SysConfigService;
import com.cyksj.web.util.StpUserUtil;
import com.ejlchina.searcher.BeanSearcher;
import com.ejlchina.searcher.SearchResult;
import com.ejlchina.searcher.util.MapBuilder;
import com.ejlchina.searcher.util.MapUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.List;

/**
 * /server/镜像服务/grok
 *
 * @author chan
 * @date 2024/3/19 14:41
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/applets/mirror")
public class MirrorController {

    private static final GlobalThreadPoolTaskExecutor TASK_EXECUTOR = GlobalThreadPoolTaskExecutor.getInstance();

    private static String DOMAIN = "https://gpt.bestaistore.com";

    private final ChatGptAccountService chatGptAccountService;

    private final ClaudeService claudeService;

    private final HttpServletResponse response;

    private final HttpServletRequest request;

    private final BeanSearcher beanSearcher;

    private final MidjourneyAccountService midjourneyAccountService;

    private final EnvCommonService envCommonService;

    @Value("${midjourney.url}")
    private String midjourneyHost;

    @Value("${midjourney.drawUrl}")
    private String midjourneyDrawUrl;

    @Value("${luma.url}")
    private String lumaHost;

    @Value("${luma.videoUrl}")
    private String lumaVideoUrl;

    private final RenewUpgradePackageMapper renewUpgradePackageMapper;

    private final GroupsRelationMapper relationMapper;

    private final GroupsMapper groupsMapper;

    private final LumaService lumaService;

    private final SysConfigService sysConfigService;

    private final GrokService grokService;

    private final NanoUserQuotaService nanoUserQuotaService;

    private final WebInfoMapper webInfoMapper;


    /**
     * GPT车票跳转登录
     *
     * @param relationId 车票id
     */
    @GetMapping("/chatGptMirror/{relationId}")
    public Result<String> chatGptMirror(@PathVariable Long relationId) throws IOException {
        Long userId = StpUserUtil.getLoginIdAsLong();
        return GatewayResponse.SUCCESS.newBuilder().toResult(chatGptAccountService.getLoginUrl(userId, relationId));
    }

    /**
     * GPT车票跳转登录
     *
     * @param userToken 用户token
     * @return 登陆结果
     */
    @RequestMapping("/gpt/oauth")
    public String gptOauth(@RequestParam("usertoken") String userToken) {
        try {
            log.info("用户通过userToken:{}", userToken);
            ChatgptUser user = chatGptAccountService.findByUserTokenAndExpireTimeAfter(userToken, LocalDateTime.now());
            if (user == null) {
                JSONObject result = new JSONObject();
                result.putOpt("code",0);
                result.putOpt("msg","用户不存在或已过期");
                return result.toString();
            }
            //ChatgptSession session = chatGptAccountService.checkSession(carId);
            JSONObject result = new JSONObject();
            result.putOpt("code",1);
            result.putOpt("msg","登录成功");
            result.putOpt("avatar",user.getImg());
            result.putOpt("nickname",user.getName());
            result.putOpt("uid",user.getRelationId());
            result.putOpt("limit",user.getLimitNum());
            result.putOpt("time",user.getLimitTime());
            result.putOpt("usertoken",user.getUserToken());
            result.putOpt("expireTime",user.getExpireTime());
            if (user.getRelationId() != null) {
                GroupsRelation relation = relationMapper.selectById(user.getRelationId());
                result.putOpt("isVip", relation.getIsVip());
            }
            return result.toString();
        } catch (Exception e) {
            log.error("服务器错误", e);
            JSONObject result = new JSONObject();
            result.putOpt("code",0);
            result.putOpt("msg","服务器错误");
            return result.toString();
        }
    }


    /**
     * GPT车队跳转登录
     *
     * @param carId 车队id
     */
    @GetMapping("/chatGptMirror/{relationId}/{carId}")
    public Result<String> chatGPtCarLogin(String domain, @PathVariable Long relationId, @PathVariable String carId) throws IOException {
        Long userId = StpUserUtil.getLoginIdAsLong();
        chatGptAccountService.checkCarAccount(userId, relationId);
        String url = chatGptAccountService.getCarLoginUrl(domain, userId, relationId, carId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(url);
    }

    /**
     * 获取车队列表
     *
     * @param relationId
     * @return
     */
    @GetMapping("/gpt/cars")
    public Result<SearchResult<ChatgptCarInfoView>> getCarInfoList(Long relationId, @RequestParam(defaultValue = "20") Integer limit) {
        Long userId = StpUserUtil.getUserIdAfterLogin();
        String userToken = null;
        if (relationId != null) {
            //查看用户是否存在车票
            ChatgptUser carChatGptUser = chatGptAccountService.getCarChatGptUser(userId, relationId);
            if (carChatGptUser == null) {
                throw BusinessRuntimeException.getInstance("您还未购买车票");
            }
            userToken = carChatGptUser.getUserToken();
        }
        SearchResult<ChatgptCarInfoView> carInfoList = chatGptAccountService.getCarInfoPage(userToken, limit);
        return GatewayResponse.SUCCESS.newBuilder().toResult(carInfoList);
    }


    /**
     * 获取gpt车票信息
     */
    @GetMapping("/gpt/userInfo")
    public Result<ChatGptUserView> getUserInfo(Long relationId) {
        long userId = StpUserUtil.getLoginIdAsLong();
        ChatGptUserView user = chatGptAccountService.getUserInfo(userId, relationId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(user);
    }

    /**
     * gpt车票使用信息
     */
    @GetMapping("/get/gptUseInfo")
    public Result getGptUseInfo(String userToken) {
        JSONObject re = chatGptAccountService.getGptUseInfo(userToken);
        return GatewayResponse.SUCCESS.newBuilder().toResult(re.toString());
    }

    /**
     * 获取用户镜像token
     */
    @GetMapping("/get/mirrorToken/{relationId}")
    public Result getMirrorToken(@PathVariable Long relationId) {
        long userId = StpUserUtil.getLoginIdAsLong();
        String token = chatGptAccountService.getMirrorToken(userId, relationId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(token);
    }

    /**
     * 获取车队历史记录
     */
    @GetMapping("/gpt/car/history")
    public Result<SearchResult<ChatGptUserConversationRecordHistoryView>> getCarHistory(Long relationId) {
        long userId = StpUserUtil.getLoginIdAsLong();
        ChatgptUser carChatGptUser = chatGptAccountService.getCarChatGptUser(userId, relationId);
        if (carChatGptUser == null) {
            throw BusinessRuntimeException.getInstance("车票出现了异常.");
        }
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap()).field("userToken", carChatGptUser.getUserToken());
        SearchResult<ChatGptUserConversationRecordHistoryView> search = beanSearcher.search(ChatGptUserConversationRecordHistoryView.class, builder.build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }



    /**
     * 根据userToken获取gpt车票信息
     */
    @GetMapping("/gpt/userInfoWithToken")
    public Result<ChatGptUserView> getUserInfoWithToken(String userToken) {
        ChatGptUserView user = chatGptAccountService.getUserInfoWithToken(userToken);
        return GatewayResponse.SUCCESS.newBuilder().toResult(user);
    }

    /**
     * 根据userToken GPT车队跳转登录
     *
     * @param carId 车队id
     */
    @GetMapping("/chatGptMirrorWithToken/{userToken}/{carId}")
    public Result<String> chatGPtCarLoginWithToken(String domain, @PathVariable String userToken, @PathVariable String carId) {
        chatGptAccountService.checkCarAccountWithToken(userToken);
        String url = chatGptAccountService.getCarLoginUrlWithToken(domain, userToken, carId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(url);
    }

    /**
     * 根据userToken获取车队列表
     */
    @GetMapping("/gpt/cars/withToken")
    public Result<List<ChatgptCarInfoView>> getCarInfoListWithToken(String userToken,@RequestParam(defaultValue = "10") Integer limit, @RequestParam(defaultValue = "false") Boolean isPlus) {
        //查看用户是否存在车票
        ChatgptUser carChatGptUser = chatGptAccountService.getCarChatGptUserWithToken(userToken);
        if (carChatGptUser == null) {
            throw BusinessRuntimeException.getInstance("您还未购买车票");
        }
        List<ChatgptCarInfoView> carInfoList = chatGptAccountService.getCarInfoList(carChatGptUser.getUserToken(), limit, isPlus);
        return GatewayResponse.SUCCESS.newBuilder().toResult(carInfoList);
    }

    /**
     * 根据userToken获取车队历史记录
     */
    @GetMapping("/gpt/car/history/withToken")
    public Result<SearchResult<ChatGptUserConversationRecordHistoryView>> getCarHistory(String userToken) {
        ChatgptUser carChatGptUser = chatGptAccountService.getCarChatGptUserWithToken(userToken);
        if (carChatGptUser == null) {
            throw BusinessRuntimeException.getInstance("车票出现了异常.");
        }
        MapBuilder builder = MapUtils.flatBuilder(request.getParameterMap()).field("userToken", carChatGptUser.getUserToken());
        SearchResult<ChatGptUserConversationRecordHistoryView> search = beanSearcher.search(ChatGptUserConversationRecordHistoryView.class, builder.build());
        return GatewayResponse.SUCCESS.newBuilder().toResult(search);
    }

    /**
     * GPT切换模式
     */
    @PutMapping("/gpt/switch/model/{relationId}")
    public Result<String> gptSwitchModel(@PathVariable Long relationId) {
        long userId = StpUserUtil.getLoginIdAsLong();
        chatGptAccountService.gptSwitchModel(userId, relationId);
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }



    /**
     * MJ车票跳转登录
     *
     * @param relationId 车票id
     */
    @GetMapping("/midjourneyMirror/{relationId}")
    public Result<String> midjourneyMirror(String domain, @PathVariable Long relationId) {
        Long userId = StpUserUtil.getLoginIdAsLong();
        MidjourneyUser midjourneyUser = midjourneyAccountService.getMidjourneyUserToken(userId, relationId);
        String DOMAIN = domain;
        if (StrUtil.isEmpty(DOMAIN)) {
            DOMAIN = midjourneyHost;
            try {
                SysConfig sysConfig = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getSysKey, "mirror_mj_discord_domain"));
                if (sysConfig != null) {
                    String sysValue = sysConfig.getSysValue();
                    if (JSONUtil.isJsonArray(sysValue)) {
                        List<String> domainList = JSONUtil.parseArray(sysValue).toList(String.class);
                        DOMAIN = domainList.get(RandomUtil.randomInt(domainList.size()));
                    }
                }
            } catch (Exception e) {
                log.error("随机抽取域名错误. msg:{}", StringUtil.getErrorText(e));
            }
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult(DOMAIN + (EnvCommonService.active_prd.equals(envCommonService.getEnv()) ? "/8082" : "/8083") + "/api/applets/midjourney/midjourneyMirrorWithToken/" + midjourneyUser.getUserToken());
    }

    @GetMapping("/midjourneyMirrorWithToken/{userToken}")
    public void midjourneyMirrorWithToken(@PathVariable String userToken) throws IOException {
        Cookie cookie = new Cookie("userToken", userToken);
        cookie.setMaxAge(31536000);
        cookie.setPath("/");
        response.addCookie(cookie);
        String host = request.getHeader("Host");
        response.sendRedirect("https://" + host + "/draw/web/");
    }

    /**
     * gpt续费广告弹窗
     */
    @GetMapping("/get/gpt/renew/discount")
    public Result<RenewUpgradePackage> getGptRenewDiscount(Long relationId) {
        if (relationId != null) {
            GroupsRelation relation = relationMapper.selectById(relationId);
            if (relation != null) {
                GroupsTrips groupsTrips = groupsMapper.selectById(relation.getGroupsId());
                if (groupsTrips != null) {
                    RenewUpgradePackage renewUpgradePackage = renewUpgradePackageMapper.selectOne(Wrappers.lambdaQuery(RenewUpgradePackage.class)
                            .eq(RenewUpgradePackage::getGoodsId, 18)
                            .eq(RenewUpgradePackage::getStatus, 1)
                            .eq(RenewUpgradePackage::getDeleted, 1)
                            .eq(RenewUpgradePackage::getSkuId, groupsTrips.getSkuId())
                            .orderByAsc(RenewUpgradePackage::getDiscount)
                            .last("limit 1")
                            .select(RenewUpgradePackage::getId, RenewUpgradePackage::getDiscount));
                    return GatewayResponse.SUCCESS.newBuilder().toResult(renewUpgradePackage);
                }
            }
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult();
    }


    // ---------------------------------- claude ----------------------------------


    /**
     * 获取claude车票信息
     */
    @GetMapping("/claude/userInfo")
    public Result<ClaudeUserView> getClaudeUserInfo(Long relationId) {
        long userId = StpUserUtil.getLoginIdAsLong();
        ClaudeUserView user = claudeService.getUserInfo(userId, relationId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(user);
    }

    /**
     * Claude车队跳转登录
     *
     * @param carId 车队id
     */
    @GetMapping("/claudeMirror/{relationId}/{carId}")
    public Result<String> claudeCarLogin(String domain, @PathVariable Long relationId, @PathVariable String carId) throws IOException {
        Long userId = StpUserUtil.getLoginIdAsLong();
        claudeService.checkCarAccount(userId, relationId);
        String url = claudeService.getCarLoginUrl(domain, userId, relationId, carId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(url);
    }

    /**
     * Claude车票跳转登录
     *
     * @param userToken 用户token
     * @param carId     车票id
     * @return 登陆结果
     */
    @RequestMapping("/claude/oauth")
    public Result<String> claudeOauth(@RequestParam("usertoken") String userToken, @RequestParam("carid") String carId) {
        try {
            log.info("用户通过userToken:{}访问claude镜像车队carId:{}", userToken, carId);
            ClaudeUser user = claudeService.findByUserTokenAndExpireTimeAfter(userToken, LocalDateTime.now());
            if (user == null) {
                return GatewayResponse.SUCCESS.newBuilder().setMsg("用户不存在或已过期").setCode(0).toResult();
            }
            GatewayResponse.buildGateWay builder = GatewayResponse.SUCCESS.newBuilder()
                    .setMsg("登陆成功")
                    .setCode(1);
            return user.getRelationId() != null
                    ? builder.toResult(StringUtil.getString(user.getRelationId()))
                    : builder.toResult();
        } catch (Exception e) {
            log.error("服务器错误", e);
            return GatewayResponse.FAIL.newBuilder().setMsg("服务器错误").setCode(0).toResult();
        }
    }


    /**
     *  Claude获取车队列表
     *
     * @param relationId
     * @return
     */
    @GetMapping("/claude/cars")
    public Result<SearchResult<ClaudeCarInfoView>> claudeCarInfoList(Long relationId) {
        Long userId = StpUserUtil.getUserIdAfterLogin();
        if (relationId != null) {
            //查看用户是否存在车票
            ClaudeUser claudeUser = claudeService.getClaudeUser(userId, relationId);
            if (claudeUser == null) {
                throw BusinessRuntimeException.getInstance("您还未购买车票");
            }
        }
        SearchResult<ClaudeCarInfoView> carInfoList = beanSearcher.search(ClaudeCarInfoView.class, MapUtils.flatBuilder(request.getParameterMap()).field(ClaudeCarInfoView::getCsStatus, true).orderBy(ClaudeCarInfoView::getIsPlus).desc().orderBy(ClaudeCarInfoView::getSort).desc().orderBy(ClaudeCarInfoView::getScore).asc().build());
        carInfoList.getDataList().forEach((claudeCarInfoView)->{
            if (claudeCarInfoView.getClearsIn() > 0) {
                claudeCarInfoView.setStatus("停运");
                claudeCarInfoView.setExpTime(new DateTime(System.currentTimeMillis() + claudeCarInfoView.getClearsIn() * 1000));
            }else {
                claudeCarInfoView.setStatus(claudeCarInfoView.getScore() > 50 ? "繁忙":"空闲");
            }
        });
        return GatewayResponse.SUCCESS.newBuilder().toResult(carInfoList);
    }



    /**
     * luma车票跳转登录
     *
     * @param relationId 车票id
     */
    @GetMapping("/luma/{relationId}")
    public Result<String> lumaRedirect(@PathVariable Long relationId) {
        Long userId = StpUserUtil.getLoginIdAsLong();
        LumaUser lumaUser = lumaService.getLumaUser(userId, relationId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(lumaHost + (EnvCommonService.active_pre.equals(envCommonService.getEnv()) ? "/8083":"/8085") +"/api/applets/luma/lumaMirrorWithToken/" + lumaUser.getUserToken());
    }

    /**
     * 获取luma车票信息
     */
    @GetMapping("/luma/userInfo")
    public Result<LumaUserInfoView> getLumaUserInfo(Long relationId) {
        long userId = StpUserUtil.getLoginIdAsLong();
        LumaUserInfoView userInfoView = lumaService.getLumaUserInfo(userId, relationId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(userInfoView);
    }

    /**
     * gpt 次数风控
     * @return
     */
    @GetMapping("/gpt/restrictions")
    public String gptRestrictions(){
        String authorization = request.getHeader("Authorization");
        String referer = request.getHeader("Referer");
        String userAgent = request.getHeader("User-Agent");
        if (StringUtils.isNotBlank(authorization)) {
            if (authorization.length() > 7) {
                String userToken = authorization.substring(7);
                return chatGptAccountService.isRestrictions(userToken,referer,userAgent);
            }
        }
        JSONObject result = new JSONObject();
        result.putOpt("code",0);
        return result.toString();
    }

    /**
     * 获取验证状态
     * @return
     */
    @GetMapping("/gpt/restrictions/status")
    public Result<Boolean> gptRestrictionStatus(String userToken, String restrictionId){
        if (StringUtils.isAnyBlank(userToken, restrictionId)) {
            throw BusinessRuntimeException.getInstance("缺少必填参数");
        }
        Boolean success = chatGptAccountService.gptRestrictionStatus(userToken, restrictionId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(success);
    }

    /**
     * 验证
     * @return
     */
    @PostMapping("/gpt/restrictions/verify")
    public Result<Boolean> verifyRestriction(@RequestBody  ChatgptUserVerifyDto chatgptUserVerifyDto){
        if (StringUtils.isAnyBlank(chatgptUserVerifyDto.getUserToken(), chatgptUserVerifyDto.getRestrictionId(),chatgptUserVerifyDto.getTicket(),chatgptUserVerifyDto.getRandStr())) {
            throw BusinessRuntimeException.getInstance("缺少必填参数");
        }
        String ip = ServletUtil.getClientIP(request);
        chatgptUserVerifyDto.setUserAgent(request.getHeader("User-Agent"));
        chatgptUserVerifyDto.setIp(ip);
        Boolean success = chatGptAccountService.verifyRestriction(chatgptUserVerifyDto);
        return GatewayResponse.SUCCESS.newBuilder().toResult(success);
    }




    /**
     * gpt3天体验
     */
    @GetMapping("/gpt/trial")
    public void trialGpt() throws IOException {
        String clientIP = ServletUtil.getClientIP(request);
        Cookie trialTokenCookie = ServletUtil.getCookie(request, "trialToken");
        String userAgent = ServletUtil.getHeader(request, "user-agent", StandardCharsets.UTF_8);
        String trialToken = "";
        if (trialTokenCookie != null) {
            trialToken = trialTokenCookie.getValue();

        }
        String userToken = chatGptAccountService.trialGpt(clientIP, trialToken, userAgent);

        if (StringUtils.isBlank(userToken)) {
            response.sendRedirect("https://nf.video/4p465k/?gid=18&trial=1");
        }else {
            SysConfig sysConfig = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getSysKey,"trial_gpt_domain"));
            if (sysConfig != null) {
                String sysValue = sysConfig.getSysValue();
                if (JSONUtil.isJsonArray(sysValue)) {
                    List<String> domainList = JSONUtil.parseArray(sysValue).toList(String.class);
                    DOMAIN = domainList.get(RandomUtil.randomInt(domainList.size()));
                }
            }
            Cookie cookie = new Cookie("trialToken",userToken);
            cookie.setMaxAge(2592000);
            cookie.setPath("/");
            ServletUtil.addCookie(response,cookie);
            response.sendRedirect(DOMAIN + "/codetoken?logintoken=" + userToken);
        }
    }


    //------------------------ grok -------------------------------


    /**
     * Grok车票跳转登录
     *
     */
    @RequestMapping("/grok/oauth")
    public String grokOauth(String userToken) {
        try {
            log.info("用户通过userToken:{}访问grok镜像", userToken);
            GrokUser user = grokService.findByUserTokenAndExpireTimeAfter(userToken, LocalDateTime.now());
            JSONObject result = new JSONObject();

            if (user == null) {
                result.putOpt("code",0);
                result.putOpt("msg","用户不存在或已过期");
                return result.toString();
            }
            result.putOpt("code",1);
            result.putOpt("msg","登陆成功");
            result.putOpt("isPro",true);
            result.putOpt("usertoken",userToken);
            result.putOpt("userToken",userToken);
            result.putOpt("expireTime", new DateTime(user.getExpireTime()).toString());
            return result.toString();
        } catch (Exception e) {
            log.error("服务器错误", e);
            JSONObject result = new JSONObject();
            result.putOpt("code",0);
            result.putOpt("msg","服务器错误");
            return result.toString();
        }
    }

    /**
     * 获取grok车票信息
     */
    @GetMapping("/grok/userInfo")
    public Result<GrokUserView> getGrokUserInfo(Long relationId) {
        long userId = StpUserUtil.getLoginIdAsLong();
        GrokUserView user = grokService.getUserInfo(userId, relationId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(user);
    }

    /**
     * grok车队跳转登录
     *
     */
    @GetMapping("/grok/{relationId}/")
    public Result<String> grokCarLogin(String domain, @PathVariable Long relationId) throws IOException {
        Long userId = StpUserUtil.getLoginIdAsLong();
        grokService.checkCarAccount(userId, relationId);
        String url = grokService.getCarLoginUrl(domain, userId, relationId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(url);
    }


    /**
     * 根据showId 查询批发网站
     */
    @GetMapping("/wholesale/{showId}")
    public Result<WebInfo> wholesale(@PathVariable String showId) {
        WebInfo webInfo = webInfoMapper.selectOne(Wrappers.lambdaQuery(WebInfo.class)
                .select(WebInfo::getAccount, WebInfo::getPrefix,WebInfo::getLogo,WebInfo::getShopName,WebInfo::getContactMe)
                .eq(WebInfo::getShowId, showId).last("limit 1"));
        return GatewayResponse.SUCCESS.newBuilder().toResult(webInfo);
    }

    /**
     * nano车票信息
     */
    @GetMapping("/nanoUser/info")
    public Result<NanoUserQuota> nanoUserInfo(Long relationId) {
        Long userId = StpUserUtil.getLoginIdAsLong();
        NanoUserQuota nanoUserQuota = nanoUserQuotaService.getNanoUser(userId, relationId);
        return GatewayResponse.SUCCESS.newBuilder().toResult(nanoUserQuota);
    }

    /**
     * nano车票跳转登录
     */
    @GetMapping("/nanoUser/{relationId}")
    public Result<String> nanoUserWithTokenRedirect(String domain, @PathVariable Long relationId) throws IOException {
        Long userId = StpUserUtil.getLoginIdAsLong();
        NanoUserQuota nanoUserQuota = nanoUserQuotaService.getNanoUser(userId, relationId);
        String DOMAIN = domain;
        if (StrUtil.isEmpty(DOMAIN)) {
            try {
                SysConfig sysConfig = sysConfigService.getOne(Wrappers.lambdaQuery(SysConfig.class).eq(SysConfig::getSysKey, "mirror_nano_domain"));
                if (sysConfig != null) {
                    String sysValue = sysConfig.getSysValue();
                    if (JSONUtil.isJsonArray(sysValue)) {
                        List<String> domainList = JSONUtil.parseArray(sysValue).toList(String.class);
                        DOMAIN = domainList.get(RandomUtil.randomInt(domainList.size()));
                    }
                }
            } catch (Exception e) {
                log.error("nano随机抽取域名错误. msg:{}", StringUtil.getErrorText(e));
            }
        }
        return GatewayResponse.SUCCESS.newBuilder().toResult((DOMAIN + "/login?usertoken=" + nanoUserQuota.getUserToken()));
    }

}
