import * as dd from 'dingtalk-jsapi';

/**
 * 获取钉钉免登授权码
 * @param {string} corpId 企业的corpId (可选，如果不传则尝试从环境或URL获取)
 * @param {string} clientId 应用的clientId (可选，如果不传则从环境获取)
 */
export function getDingTalkAuthCode(corpId?: string, clientId?: string) {
  return new Promise<string>((resolve, reject) => {
    // 钉钉环境判断
    if (dd.env.platform === 'notInDingTalk') {
      reject(new Error('请在钉钉客户端打开'));
      return;
    }

    // @ts-ignore 新版写法，可能类型定义未及时更新
    dd.requestAuthCode({
      corpId: corpId || '',
      clientId: clientId || import.meta.env.VITE_DINGTALK_CLIENTID || '',
      onSuccess: (result: { code: string }) => {
        resolve(result.code);
      },
      onFail: (err: any) => {
        reject(err);
      }
    });
  });
}
