import request from '@/utils/request';
import type { ApiResult } from '@/api/index';
import type {
  LoginParam,
  LoginResult,
  CaptchaResult,
  SmsCaptchaResult
} from './model';
import {saveStorageByLoginUser, SERVER_API_URL} from "@/utils/server";
import Taro from '@tarojs/taro';

/**
 * 登录
 */
export async function login(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    SERVER_API_URL + '/login',
    data
  );
  if (res.code === 0) {
    // setToken(res.data.data?.access_token, data.remember);
    if (res.data?.user) {
      const user = res.data?.user;
      localStorage.setItem('TenantId', String(user.tenantId));
      localStorage.setItem('UserId', String(user.userId));
    }

    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 获取验证码
 */
export async function getCaptcha() {
  const res = await request.get<ApiResult<CaptchaResult>>(
    SERVER_API_URL + '/captcha',
    {}
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

export async function loginBySms(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    SERVER_API_URL + '/loginBySms',
    data
  );
  if (res.code === 0) {
    if(res.data?.user){
      saveStorageByLoginUser(`${res.data?.access_token}`, res.data?.user)
    }
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 发送短信验证码
 */
export async function sendSmsCaptcha(data: LoginParam) {
  const res = await request.post<ApiResult<SmsCaptchaResult>>(
    SERVER_API_URL + '/sendSmsCaptcha',
    data
  );
  if (res.code === 0) {
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

export async function getOpenId(data: any){
  const res = request.post<ApiResult<LoginResult>>(
    SERVER_API_URL + '/wx-login/getOpenId',
    data
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

export async function loginByOpenId(data:any){
  const res = request.post<ApiResult<LoginResult>>(
    SERVER_API_URL + '/wx-login/loginByOpenId',
    data
  );
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}
/**
 * 登录
 */
export async function remoteLogin(data: LoginParam) {
  const res = await request.post<ApiResult<LoginResult>>(
    'https://open.gxwebsoft.com/api/login',
    data
  );
  if (res.code === 0) {
    // setToken(res.data.data?.access_token, data.remember);
    return res.message;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 获取企业微信登录链接
 */
export async function getWxWorkQrConnect(data: any) {
  const res = await request.post<ApiResult<unknown>>(
    '/wx-work',
    data
  );
  if (res.code === 0 && res.data) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

export async function loginMpWxMobile(data: {
  refereeId: number;
  gradeId: number;
  code: any;
  sceneType: string;
  comments: string;
  encryptedData: any;
  tenantId: string;
  iv: any;
  notVerifyPhone: boolean
}) {
  const res = request.post<ApiResult<unknown>>(SERVER_API_URL + '/wx-login/loginByMpWxPhone', data);
  if (res.code === 0) {
    return res.data;
  }
  return Promise.reject(new Error(res.message));
}

/**
 * 微信小程序手机号登录
 * @param phoneDetail 微信授权手机号的详细信息
 * @param options 登录选项配置
 */
export async function wxPhoneLogin(
  phoneDetail: { code: string; encryptedData: string; iv: string },
  options?: {
    onSuccess?: (user: any) => void;
    onError?: (error: string) => void;
    showToast?: boolean;
    navigateBack?: boolean;
    tenantId?: number;
  }
) {
  const { code, encryptedData, iv } = phoneDetail;
  const {
    onSuccess,
    onError,
    showToast = true,
    navigateBack = true,
    tenantId
  } = options || {};

  return new Promise((resolve, reject) => {
    Taro.login({
      success: function () {
        if (code) {
          Taro.request({
            url: 'https://server.websoft.top/api/wx-login/loginByMpWxPhone',
            method: 'POST',
            data: {
              code,
              encryptedData,
              iv,
              notVerifyPhone: true,
              refereeId: 0,
              sceneType: 'save_referee',
              tenantId: tenantId || require('@/utils/config').TenantId
            },
            header: {
              'content-type': 'application/json',
              TenantId: tenantId || require('@/utils/config').TenantId
            },
            success: function (res) {
              if (res.data?.code === 0 && res.data?.data) {
                // 保存登录信息
                saveStorageByLoginUser(res.data.data.access_token, res.data.data.user);

                if (showToast) {
                  Taro.showToast({
                    title: '登录成功',
                    icon: 'success'
                  });
                }

                // 执行成功回调
                if (onSuccess) {
                  onSuccess(res.data.data.user);
                }

                // 导航返回
                if (navigateBack) {
                  setTimeout(() => {
                    Taro.navigateBack();
                  }, 1500);
                }

                resolve(res.data.data.user);
              } else {
                const errorMsg = res.data?.message || '登录失败';
                if (onError) {
                  onError(errorMsg);
                }
                if (showToast) {
                  Taro.showToast({
                    title: errorMsg,
                    icon: 'error'
                  });
                }
                reject(new Error(errorMsg));
              }
            },
            fail: function (_error) {
              const errorMsg = '网络请求失败';
              if (onError) {
                onError(errorMsg);
              }
              if (showToast) {
                Taro.showToast({
                  title: errorMsg,
                  icon: 'error'
                });
              }
              reject(new Error(errorMsg));
            }
          });
        } else {
          const errorMsg = '获取微信登录凭证失败';
          if (onError) {
            onError(errorMsg);
          }
          if (showToast) {
            Taro.showToast({
              title: errorMsg,
              icon: 'error'
            });
          }
          reject(new Error(errorMsg));
        }
      },
      fail: function (_error) {
        const errorMsg = '微信登录失败';
        if (onError) {
          onError(errorMsg);
        }
        if (showToast) {
          Taro.showToast({
            title: errorMsg,
            icon: 'error'
          });
        }
        reject(new Error(errorMsg));
      }
    });
  });
}
