package com.fs.wxcid.service.impl;

import com.fs.common.core.redis.RedisCache;
import com.fs.common.exception.CustomException;
import com.fs.wxcid.ServiceUtils;
import com.fs.wxcid.dto.common.ApiResponseCommon;
import com.fs.wxcid.dto.login.AccountIdParam;
import com.fs.wxcid.dto.login.GetLoginQrCodeParam;
import com.fs.wxcid.dto.login.LoginQrCodeResponseData;
import com.fs.wxcid.dto.login.LoginStatusData;
import com.fs.wxcid.dto.login.LoginStatusResponseData;
import com.fs.wxcid.dto.login.QrCodeRequest;
import com.fs.wxcid.dto.login.RequestBaseVo;
import com.fs.wxcid.service.AdminLicenseService;
import com.fs.wxcid.service.LoginService;
import com.fs.wxwork.utils.WxWorkHttpUtil;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


@Slf4j
@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private AdminLicenseService adminLicenseService;
    @Autowired
    private ServiceUtils serviceUtils;
    private static final String BASE_URL = "/login/";

    public String getLoginQrCodeNewDirect(GetLoginQrCodeParam param) {
        QrCodeRequest request = new QrCodeRequest();
        request.setCheck(false);
        request.setIpadOrmac(param.getIpadOrMac());
        request.setProxy(serviceUtils.getProxy(param.getAccountId()));
        ApiResponseCommon<LoginQrCodeResponseData> response = serviceUtils.sendPost(BASE_URL + "GetLoginQrCodeNewDirect", RequestBaseVo.builder().accountId(param.getAccountId()).data(request).build(), new TypeReference<ApiResponseCommon<LoginQrCodeResponseData>>() {});
        //安全访问 data
        log.info("二维码照片url: {}", response.getData().getQrCodeUrl());
        return response.getData().getQrCodeUrl();
    }
    @Override
    public LoginStatusResponseData checkLoginStatus(AccountIdParam param) {
        ApiResponseCommon<LoginStatusResponseData> response = serviceUtils.sendGet(BASE_URL + "CheckLoginStatus", RequestBaseVo.builder().accountId(param.getAccountId()).build(), new TypeReference<ApiResponseCommon<LoginStatusResponseData>>() {});
        // 只认 text == "账号已登录"
        if ("账号已登录".equals(response.getText()) || "登录成功".equals(response.getText())) {
            if (response.getData() == null) {
                throw new CustomException("登录状态异常：text 显示已登录，但 data 为空");
            }
            return response.getData();
        } else {
            // 抛出具体的错误原因
            throw new CustomException("检查登录状态失败: " + (response.getText() != null ? response.getText() : "未知错误"));
        }
    }

    public LoginStatusData getLoginStatus(AccountIdParam param) {
        try {
            ApiResponseCommon<LoginStatusData> response = serviceUtils.sendGet(BASE_URL + "GetLoginStatus", RequestBaseVo.builder().accountId(param.getAccountId()).data(null).build(), new TypeReference<ApiResponseCommon<LoginStatusData>>() {});
            return response.getData();
        }catch (Exception e){
            return new LoginStatusData();
        }
    }

    public ApiResponseCommon<Void> logOut(AccountIdParam param) {
        ApiResponseCommon<Void> response = serviceUtils.sendGet(BASE_URL + "LogOut", RequestBaseVo.builder().accountId(param.getAccountId()).build(), new TypeReference<ApiResponseCommon<Void>>() {});
        String text = response.getText();
        int code = response.getCode();
        //真正的成功退出
        if (code == 200 && "退出成功！".equals(text)) {
            return response;
        }
        //已经退出过了（幂等，视为成功）
        else if (code == 300 && "你已退出登录".equals(text)) {
            return response;
        }
        //其他情况一律视为失败
        else {
            String errorMsg = text != null ? text : "退出登录失败，未知错误";
            throw new CustomException("退出登录失败: " + errorMsg);
        }
    }

    @Override
    public ApiResponseCommon<Void> wakeUpLogin(AccountIdParam param) {
        QrCodeRequest request = new QrCodeRequest();
        request.setCheck(false);
        request.setIpadOrmac("ipad");
        request.setProxy(serviceUtils.getProxy(param.getAccountId()));
        ApiResponseCommon<Void> response = serviceUtils.sendPost(BASE_URL + "WakeUpLogin", RequestBaseVo.builder().accountId(param.getAccountId()).data(request).build(), new TypeReference<ApiResponseCommon<Void>>() {});
        String text = response.getText();
        int code = response.getCode();
        if (code == 200) {
            return response;
        }
        else {
            String errorMsg = text != null ? text : "唤醒登录失败，未知错误";
            throw new CustomException("唤醒登录失败: " + errorMsg);
        }
    }
}