import { req } from '@/common/js/index.js';

const SALESPERSON_PREFIX = '/newApi/salesperson-upload/';
const PLATFORM_PREFIX = '/newApi/platform-admin-upload/';
const CLINIC_ADMIN_PREFIX = '/newApi/clinic-admin-upload/';

function uploadChatFileByPrefix(prefix, headerKey, params) {
  return req.request({
    url: `${prefix}upload-chat-file`,
    type: 'upload',
    method: 'POST',
    filePath: params.filePath,
    name: params.name || 'file',
    formData: params.formData || {},
    header: {
      [headerKey]: '1',
    },
  });
}

function getOssSignatureByPrefix(prefix, headerKey) {
  return req.request({
    url: `${prefix}oss-signature`,
    method: 'GET',
    header: {
      [headerKey]: '1',
    },
  });
}

function registerOssFileByPrefix(prefix, headerKey, url, fileSize = 0, fileName = '') {
  const data = { url, source: 2, file_size: fileSize }
  if (fileName) {
    data.file_name = fileName
  }
  return req.request({
    url: `${prefix}register-oss-file`,
    method: 'POST',
    data,
    header: {
      [headerKey]: '1',
    },
  });
}

function registerBusinessOssFile(url, fileSize = 0, fileName = '') {
  const mode = uni.getStorageSync('loginMode');
  if (mode === 'platform_admin') {
    return registerOssFileByPrefix(PLATFORM_PREFIX, '_platformAdmin', url, fileSize, fileName);
  }
  if (mode === 'clinic_admin') {
    return registerOssFileByPrefix(CLINIC_ADMIN_PREFIX, '_clinicAdmin', url, fileSize, fileName);
  }
  return registerOssFileByPrefix(SALESPERSON_PREFIX, '_salesperson', url, fileSize, fileName);
}

export { registerBusinessOssFile };

/**
 * 业务员录入/聊天同款：服务端转存 OSS，返回 url
 */
export function uploadSalespersonChatFileApi(params) {
  return uploadChatFileByPrefix(SALESPERSON_PREFIX, '_salesperson', params);
}

/**
 * 平台管理员录入上传（与业务员对称）
 */
export function uploadPlatformAdminChatFileApi(params) {
  return uploadChatFileByPrefix(PLATFORM_PREFIX, '_platformAdmin', params);
}

/**
 * 诊所管理员上传（结算凭证等）
 */
export function uploadClinicAdminChatFileApi(params) {
  return uploadChatFileByPrefix(CLINIC_ADMIN_PREFIX, '_clinicAdmin', params);
}

/**
 * 按当前 loginMode 选择上传接口
 */
export function uploadBusinessChatFileApi(params) {
  const mode = uni.getStorageSync('loginMode');
  if (mode === 'platform_admin') {
    return uploadPlatformAdminChatFileApi(params);
  }
  if (mode === 'clinic_admin') {
    return uploadClinicAdminChatFileApi(params);
  }
  return uploadSalespersonChatFileApi(params);
}

/**
 * 推广员管理结算凭证上传（超管/诊所）
 */
export function uploadSalespersonManageFileApi(params) {
  const mode = uni.getStorageSync('loginMode');
  if (mode === 'platform_admin') {
    return uploadPlatformAdminChatFileApi(params);
  }
  return uploadClinicAdminChatFileApi(params);
}

function unwrapUploadResult(res) {
  if (res == null) return null;
  if (res.result !== undefined && res.result !== null) return res.result;
  if (res.data && res.data.result !== undefined) return res.data.result;
  return res.data != null ? res.data : res;
}

export function extractUploadUrl(res) {
  const inner = unwrapUploadResult(res);
  if (!inner) return null;
  return inner.url || inner.path || null;
}

/**
 * 从 Laravel jok 响应解包 OSS 签名
 */
export function unwrapOssSignature(res) {
  const inner = unwrapUploadResult(res);
  if (!inner) return null;
  if (!inner.accessKeyId || !inner.policy || !inner.signature || !inner.host || !inner.bucket) {
    return null;
  }
  return inner;
}

export function getSalespersonOssSignatureApi() {
  return getOssSignatureByPrefix(SALESPERSON_PREFIX, '_salesperson');
}

export function getPlatformAdminOssSignatureApi() {
  return getOssSignatureByPrefix(PLATFORM_PREFIX, '_platformAdmin');
}

export function getClinicAdminOssSignatureApi() {
  return getOssSignatureByPrefix(CLINIC_ADMIN_PREFIX, '_clinicAdmin');
}

/**
 * 按当前 loginMode 获取 OSS 直传签名
 */
export function getBusinessOssSignatureApi() {
  const mode = uni.getStorageSync('loginMode');
  if (mode === 'platform_admin') {
    return getPlatformAdminOssSignatureApi();
  }
  if (mode === 'clinic_admin') {
    return getClinicAdminOssSignatureApi();
  }
  return getSalespersonOssSignatureApi();
}

const LEGACY_ADMIN_UPLOAD_URL = 'https://api.xiaokang88.com/open-api/upload/old-admin-img';

/**
 * 录入/管理端旧版图片上传（与 d-upload、select-avatar-image 一致）
 */
export function uploadLegacyAdminImage(params) {
  const { filePath, name = 'file', formData = { store_id: '11001' } } = params || {};
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: LEGACY_ADMIN_UPLOAD_URL,
      filePath,
      name,
      formData,
      header: {
        authorization: `Bearer ${uni.getStorageSync('token')}`,
      },
      success: (uploadRes) => {
        try {
          const data =
            typeof uploadRes.data === 'string' ? JSON.parse(uploadRes.data) : uploadRes.data;
          if (![200, 201, 204].includes(uploadRes.statusCode)) {
            reject(new Error((data && data.msg) || '上传失败'));
            return;
          }
          const url = data && data.data && data.data.url;
          if (!url) {
            reject(new Error('上传失败'));
            return;
          }
          resolve(url);
        } catch (e) {
          reject(e);
        }
      },
      fail: reject,
    });
  });
}
