import { faker } from '@faker-js/faker/locale/zh_CN';
import TcVod from 'vod-js-sdk-v6';
import symmetryEncrypt from '../js/login_crypt';

// import appParams from './app_params.json';

// post 请求
const postData = async (url, data) => {
  if (!sessionStorage.getItem('server_gateway')) {
    const jsonResponse = await fetch(
      process.env.PUBLIC_URL + '/app_params.json',
    );
    const content = await jsonResponse.json();
    sessionStorage.setItem('server_gateway', content.server_gateway);
  }
  // server_gateway
  const response = await fetch(sessionStorage.getItem('server_gateway') + url, {
    method: 'POST', // 设置请求方法为 "POST"
    headers: {
      'Content-Type': 'application/json', // 设置内容类型为 JSON
    },
    body: JSON.stringify(data), // 将参数对象序列化为 JSON 字符串
  });
  return await response.json(); // 解析响应并返回 JSON 数据
};
const jsonRpcObj = (method, params) => {
  return {
    jsonrpc: '2.0',
    method: method,
    params: [params],
    id: 1,
  };
};

// 发送学院相关的接口
const sendRequest = async (method, params) => {
  let token = '';
  if (sessionStorage.getItem('token')) {
    token = JSON.parse(sessionStorage.getItem('token'));
  }
  const data = await postData(
    '/IEducationService',
    jsonRpcObj(method, token ? { Token: token, ...params } : { ...params }),
  );
  return data;
};

// 发送登录服务相关的接口
const sendLoginRequest = async (method, params) => {
  const data = await postData(
    '/ILoginService',
    jsonRpcObj(method, { ...params }),
  );
  return data;
};

// 发送存储相关的接口
const sendStorageRequest = async (method, params) => {
  const token = JSON.parse(sessionStorage.getItem('token'));
  const data = await postData(
    '/IStorageService',
    jsonRpcObj(method, { Token: token, ...params }),
  );
  return data;
};
// 发送权限相关的接口
const sendAuthenticationRequest = async (method, params) => {
  const token = JSON.parse(sessionStorage.getItem('token'));
  const data = await postData(
    '/IAuthenticationService',
    jsonRpcObj(method, { Token: token }),
  );
  return data;
};
// 发送用户相关的接口
const sendUserServicenRequest = async (method, params) => {
  const token = JSON.parse(sessionStorage.getItem('token'));
  const data = await postData(
    '/IUserService',
    jsonRpcObj(method, { Token: token }),
  );
  return data;
};
// 发送消息聊天相关的接口
const sendChatMessageServicenRequest = async (method, params) => {
  let token = '';
  if (
    sessionStorage.getItem('token') &&
    sessionStorage.getItem('token') !== 'undefined'
  ) {
    token = JSON.parse(sessionStorage.getItem('token'));
  }
  const data = await postData(
    '/IChatMessageService',
    jsonRpcObj(method, token ? { Token: token, ...params } : { ...params }),
  );
  return data;
};

const getUserInfo = async () => {
  try {
    const data = await sendUserServicenRequest('GetUserInfoAsync');
    return data.result;
  } catch (err) {
    console.log('%c Line:55 👾 err', 'color:#4fff4B', err);
    return {};
  }
};

const generateMockCourseItem = (num) => {
  const classifications = ['产筛', '急诊', '学术', '麻醉', '规培', '质控'];
  const lecturers = ['张三', '李四', '王五', '赵六'];
  const types = ['直播', '视频'];

  const course = {
    index: num,
    id: faker.datatype.uuid(),
    name: faker.commerce.productName(),
    type: types[Math.floor(Math.random() * types.length)],
    classification:
      classifications[Math.floor(Math.random() * classifications.length)],
    lecturers: Array.from(
      { length: 2 },
      () => lecturers[Math.floor(Math.random() * lecturers.length)],
    ),
    coverImageUrl:
      'https://picsum.photos/id/' +
      Math.floor(Math.random() * 1000) +
      '/160/90',
    playCount: faker.datatype.number(),
    updateTime: faker.date.recent().toLocaleDateString(),
    duration: faker.datatype.number(),
  };

  return course;
};
// 课程或者专辑
const fetchCoursesData = async (
  classification,
  pageIndex,
  selectedOption,
  keyword,
) => {
  let params = {};
  let methodName = '';
  const commonParams = {
    PageIndex: pageIndex,
    PageSize: 12,
    Keyword: keyword,
  };
  const publicParams = !classification
    ? commonParams
    : {
        ...commonParams,
        CourseLabels: [classification],
      };
  if (selectedOption === 'album') {
    methodName = 'FindCourseAlbumPageAsync';
    params = publicParams;
  } else if (selectedOption === 'course') {
    methodName = 'FindCoursePagesAsync';
    params = {
      ...publicParams,
      CourseApprovalStatus: 2,
    };
  }
  const data = await sendRequest(methodName, params);
  return data;
};
// 我创建的课程和专辑列表
const fetchMyCoursesData = async (
  currentTab,
  pageIndex,
  pageSize,
  selectedOption,
  keyword,
) => {
  let params = {};
  let methodName = '';
  const { UserCode } = await getUserInfo();
  sessionStorage.setItem('userCode', UserCode);
  if (currentTab === 1) {
    if (selectedOption === 'album') {
      methodName = 'FindCourseAlbumPageAsync';
      params = {
        PageIndex: pageIndex,
        PageSize: pageSize,
        Keyword: keyword,
        TeacherCode: UserCode,
      };
    } else if (selectedOption === 'course') {
      methodName = 'FindCoursePagesAsync';
      params = {
        PageIndex: pageIndex,
        PageSize: pageSize,
        Keyword: keyword,
        TeacherCode: UserCode,
      };
    }
  } else if (currentTab === 2) {
    if (selectedOption === 'album') {
      methodName = 'FindMyAlbumPagesAsync';
      params = {
        PageIndex: pageIndex,
        PageSize: pageSize,
        Keyword: keyword,
      };
    } else if (selectedOption === 'course') {
      methodName = 'FindMyCoursePagesAsync';
      params = {
        PageIndex: pageIndex,
        PageSize: pageSize,
        Keyword: keyword,
      };
    }
  } else if (currentTab === 3) {
    if (selectedOption === 'album') {
      methodName = 'FindCourseAlbumPageAsync';
      params = {
        PageIndex: pageIndex,
        PageSize: pageSize,
        Keyword: keyword,
        ParticipantCode: UserCode,
      };
    } else if (selectedOption === 'course') {
      methodName = 'FindCoursePagesAsync';
      params = {
        PageIndex: pageIndex,
        PageSize: pageSize,
        Keyword: keyword,
        ParticipantCode: UserCode,
      };
    }
  }

  const data = await sendRequest(methodName, params);
  return data;
};
// 首页课程数据
const fetchPopularCoursesData = async () => {
  const { UserCode } = await getUserInfo();
  sessionStorage.setItem('userCode', UserCode);
  // 在这里发送请求，返回请求到的数据
  // 您可以根据您的实际 API 修改这个函数
  const data = await sendRequest('FindCoursePagesAsync', {
    PageIndex: 1,
    PageSize: 5,
    CourseApprovalStatus: 2,
  });
  return data;
};
// 首页专辑数据
const fetchPopularCourseAlbumsData = async () => {
  const { UserCode } = await getUserInfo();
  sessionStorage.setItem('userCode', UserCode);
  // 在这里发送请求，返回请求到的数据
  // 您可以根据您的实际 API 修改这个函数
  const data = await sendRequest('FindCourseAlbumPageAsync', {
    PageIndex: 1,
    PageSize: 5,
  });

  return data;
};

// 标签列表
const getCourseLabelsAsyncData = async (type) => {
  // 在这里发送请求，返回请求到的数据
  // 您可以根据您的实际 API 修改这个函数
  const data = await sendRequest('GetCourseLabelsAsync', {
    LanguageCode: 'zh-CN',
    Type: type || 2,
  });
  return data;
};
// 根据老师查询班级
const getUserGroupListsByCreatorCode = async () => {
  const data = await sendRequest('GetUserGroupListsByCreatorCodeAsync', {
    PageIndex: 1,
    PageSize: 1000,
  });
  return data;
};

// 创建课程（申请课程）
const createCourseAsync = async (courseInfo) => {
  const data = await sendRequest('ApplyCourseAsync', courseInfo);
  return data;
};
// 修改课程
const updateCourseAsyncAsync = async (courseInfo) => {
  const data = await sendRequest('UpdateCourseAsync', courseInfo);
  return data;
};

// 创建专辑
const addCourseAlbumAsync = async (courseInfo) => {
  const data = await sendRequest('AddCourseAlbumAsync', courseInfo);
  return data;
};
// 修改专辑
const updateCourseAlbumAsync = async (courseInfo) => {
  const data = await sendRequest('UpdateCourseAlbumAsync', courseInfo);
  return data;
};

// 删除课程
const deleteCourseByCodeAsync = async (courseInfo) => {
  const data = await sendRequest('DeleteCourseByCodeAsync', courseInfo);
  return data;
};

// 删除专辑
const deleteCourseAlbumAsync = async (courseInfo) => {
  const data = await sendRequest('DeleteCourseAlbumAsync', courseInfo);
  return data;
};

/// 报名
const signUpCourse = async (code, typeIndex) => {
  const data = await sendRequest('SignUpCourseAsync', {
    CourseOrAlbumCode: code,
    CourseAppearType: typeIndex,
  });
  return data.result;
};
/// 取消报名
const cancelSignUpCourseAsync = async (code) => {
  const data = await sendRequest('CancelSignUpCourseAsync', {
    CourseOrAlbumCode: code,
  });
  return data.result;
};
/// 获取详情
const fetchCourseDetail = async (id, subsetTab) => {
  try {
    let params = {};
    let methodName = '';
    if (subsetTab === 'album') {
      methodName = 'FindCourseAlbumByCodeAsync';
      // 课程详情
      params = {
        CourseAlbumCode: id,
        LanguageCode: 'zh-CN',
      };
    } else if (subsetTab === 'course') {
      methodName = 'FindCourseByCodeAsync';
      params = {
        Code: id,
      };
    }
    const data = await sendRequest(methodName, params);
    return data.result;
  } catch (err) {
    console.log('%c Line:225 👾 err', 'color:#93c0a4', err);
    return 'error';
  }
};
/// 获取参与者或者助教
const getAllStudentsAsync = async (keyword, excludeUserCodes) => {
  const params = {
    PageIndex: 1,
    PageSize: 100,
    Keyword: keyword,
    ExcludeUserCodes: excludeUserCodes, // 排除的用户
  };
  const data = await sendRequest('GetAllStudentsAsync', params);
  return data;
};

/// 关联专辑的列表
const findCourseAlbumList = async () => {
  const data = await sendRequest('FindCourseAlbumListAsync');
  return data;
};

/// 购买课程
const buyCourse = async (code, payType) => {
  const data = await sendRequest('BuyCourseAsync', {
    CourseCode: code,
    PayType: payType,
    Quantity: 1,
  });

  return data.result;
};

// 获取课程目录
const fetchCourseCatalog = async (id) => {
  const mockData = {
    courseItems: Array.from({ length: 22 }, (_, i) =>
      generateMockCourseItem(i),
    ),
  };
  console.log('data length', mockData.courseItems.length);
  return mockData;
};

// 获取上传权限
const getAuthorization = async (flieType, isRechristen) => {
  // 后端接口FileName其实传的是他的文件类型
  const data = await sendStorageRequest('GetAuthorizationAsync', {
    FileName: flieType ?? 'dat',
    IsRechristen: isRechristen ?? true,
  });
  return data.result;
};

// 文件上传
const upload = async (file) => {
  const auth = await getAuthorization(file.type);
  const headers = {
    Authorization: auth.Authorization,
    ContentType: auth.ContentType,
  };

  const response = await fetch(auth.StorageUrl, {
    method: 'PUT', // 设置请求方法为 "POST"
    headers: headers,
    body: file, // 将参数对象序列化为 JSON 字符串
  });
  return auth.StorageUrl;
};

/// 云点播上传的鉴权接口
const getVodAuthorization = async () => {
  const data = await sendAuthenticationRequest('GetVodAuthorizationAsync');
  return data.result;
};

/// 上传到云点播
const vodUpload = async (mediaFile) => {
  let uploader;
  try {
    const signature = await getVodAuthorization();
    function getSignature() {
      return signature;
    }

    const tcVod = new TcVod({
      getSignature: getSignature, // 前文中所述的获取上传签名的函数
    });
    uploader = tcVod.upload({
      mediaFile: mediaFile, // 媒体文件（视频或音频或图片），类型为 File
    });
  } catch (err) {
    console.log('%c Line:288 👾 err', 'color:#7f2b82', err);
    uploader = '';
  }
  return uploader;
};

const findVideosPages = async (keyword) => {
  try {
    const result = await sendRequest('FindVideosPagesAsync', {
      PageIndex: 1, //页码
      PageSize: 100, //页大小
      Keyword: keyword,
      IsJustQueryMyUpload: false, //是否只查询我上传的，true-表示是，false-表示不只是看到我上传的，还有只要是公共的素材都可以看到
    });
    return result.result.PageData;
  } catch (err) {
    console.log('%c Line:339 👾 err', 'color:#ed9ec7', err);
    return [];
  }
};
/// 发给flutter的通知
const sendCourseEntryNotice = async (noticeData) => {
  const data = await sendRequest('SendCourseEntryNoticeAsync', {
    NoticeData: noticeData,
  });
  return data;
};
/// 结束课程直播
const completedLiveCourseAsync = async (courseCode) => {
  const result = await sendRequest('CompletedLiveCourseAsync', {
    CourseCode: courseCode,
  });
  return result;
};
/// 获取聊天消息分页
const getChatMessagePagesAsync = async (courseCode) => {
  const result = await sendChatMessageServicenRequest(
    'GetChatMessagePagesAsync',
    {
      RelevanceCode: courseCode,
      PageIndex: 1, //页码
      PageSize: 100, //页大小
    },
  );
  return result;
};

/// 获取游客聊天消息分页
const getChatMessagePagesVisitorAsync = async (courseCode) => {
  const result = await sendChatMessageServicenRequest(
    'GetChatMessagePagesVisitorAsync',
    {
      RelevanceCode: courseCode,
      PageIndex: 1, //页码
      PageSize: 100, //页大小
    },
  );
  return result;
};

/// 游客 发送消息
const sendVisitChatMessageAsync = async (content, courseCode, visitor) => {
  const result = await sendChatMessageServicenRequest(
    'SendVisitChatMessageAsync',
    {
      Content: content,
      RelevanceCode: courseCode,
      Visitor: visitor,
    },
  );
  return result;
};
/// 发送消息
const sendChatMessageAsync = async (content, courseCode) => {
  const result = await sendChatMessageServicenRequest('SendChatMessageAsync', {
    Content: content,
    RelevanceCode: courseCode,
  });
  return result;
};

/// 登录获取 Token
const getToken = async (username, password) => {
  const data = await sendLoginRequest('CommonLoginAsync', {
    AnyAccount: username, //用户名/手机/邮箱
    AnyCode: '',
    Password: symmetryEncrypt(password),
    Platform: 0, //平台
    LoginSource: 3, //来源
  });
  return data.result;
};

/// 统计播放次数（播放量+1）
const addCoursePlayCountAsync = async (code) => {
  const data = await sendRequest('AddCoursePlayCountAsync', {
    Code: code,
  });
  return data;
};

export {
  fetchMyCoursesData,
  fetchCoursesData,
  fetchCourseDetail,
  fetchCourseCatalog,
  fetchPopularCoursesData,
  fetchPopularCourseAlbumsData,
  getCourseLabelsAsyncData,
  signUpCourse,
  buyCourse,
  createCourseAsync,
  upload,
  vodUpload,
  findCourseAlbumList,
  getUserGroupListsByCreatorCode,
  findVideosPages,
  updateCourseAsyncAsync,
  deleteCourseByCodeAsync,
  cancelSignUpCourseAsync,
  addCourseAlbumAsync,
  updateCourseAlbumAsync,
  deleteCourseAlbumAsync,
  sendCourseEntryNotice,
  getAllStudentsAsync,
  completedLiveCourseAsync,
  getUserInfo,
  getChatMessagePagesAsync,
  sendChatMessageAsync,
  getChatMessagePagesVisitorAsync,
  sendVisitChatMessageAsync,
  getToken,
  addCoursePlayCountAsync,
};
