const { request, baseURL } = require('./request.js');

/**
 * 工具函数
 */
const utils = {
  // 检查是否有token
  hasToken() {
    const app = getApp();
    return (app && app.globalData && app.globalData.token) || wx.getStorageSync('token');
  },
  
  // 获取当前token
  getToken() {
    const app = getApp();
    if (app && app.globalData && app.globalData.token) {
      return app.globalData.token;
    }
    return wx.getStorageSync('token');
  },
  
  // 模拟登录获取token
  simulateLogin() {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://klmybwg.4dage.com/api/museum/wxMini/testlogin',
        method: 'GET',
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: (response) => {
          console.log('模拟登录接口调用成功:', response.data);
          
          if (response.data && response.data.code === 0) {
            const app = getApp();
            // 存储token到全局数据
            if (app && app.globalData) {
              app.globalData.token = response.data.data.token;
              app.globalData.userInfo = response.data.data.user;
            }
            
            // 也存储到本地存储
            wx.setStorageSync('token', response.data.data.token);
            wx.setStorageSync('userInfo', response.data.data.user);
            
            console.log('Token获取成功:', response.data.data.token);
            resolve(response.data.data);
          } else {
            const errorMsg = response.data.message || '模拟登录失败';
            console.error('模拟登录失败:', errorMsg);
            reject(new Error(errorMsg));
          }
        },
        fail: (error) => {
          console.error('模拟登录接口调用失败:', error);
          reject(error);
        }
      });
    });
  },

  // 刷新token
  refreshToken() {
    const app = getApp();
    const currentToken = (app && app.globalData && app.globalData.token) || wx.getStorageSync('token');
    
    if (!currentToken) {
      console.error('当前没有token，无法刷新');
      return Promise.reject('当前没有token，无法刷新');
    }

    return new Promise((resolve, reject) => {
      wx.request({
        url: `${baseURL}/museum/refresh`,
        method: 'POST',
        header: {
          'token': currentToken
        },
        success: (response) => {
          console.log('刷新token接口调用成功:', response.data);
          if (response.data && response.data.code === 0) {
            const newToken = response.data.data;
            // 更新全局数据中的token
            if (app && app.globalData && newToken) {
              app.globalData.token = newToken;
            }
            // 更新本地存储中的token
            if(newToken){
              wx.setStorageSync('token', newToken);
              console.log('token刷新成功:', newToken);
            }
            resolve(newToken);
          } else {
            console.error('刷新token失败:', response.data.message || '未知错误');
            reject(response.data.message || '刷新token失败');
          }
        },
        fail: (error) => {
          console.error('刷新token接口调用失败:', error);
          reject(error);
        }
      });
    });
  }
};

/**
 * 博物馆相关API
 */
const museumApi = {
  // 获取轮播图列表
  getCarouselList(params = {}) {
    return request({
      url: '/museum/carousel/page',
      method: 'POST',
      data: {
        pageNum: 1,
        pageSize: 10,
        status: 1,
        ...params,
      },
    });
  },

  // 获取资讯列表
  getNewsList(params = {}) {
    return request({
      url: '/museum/information/page',
      method: 'POST',
      data: {
        pageNum: 1,
        pageSize: 3,
        status: 1,
        ...params,
      },
    });
  },

  // 获取展览列表
  getExhibitionList(params = {}) {
    return request({
      url: '/museum/exhibit/page',
      method: 'POST',
      data: {
        pageNum: 1,
        pageSize: 5,
        status: 1,
        ...params,
      },
    });
  },

  // 社教活动列表
  getSocialActivityList(params = {}) {
    return request({
      url: '/museum/activity/page',
      method: 'POST',
      data: {
        pageNum: 1,
        pageSize: 5,
        ...params,
      },
    });
  },

  // 获取展览详情
  getExhibitionDetail(id) {
    return request({
      url: `/museum/exhibition/${id}`,
      method: 'GET',
    });
  },

  // 获取展览详情（新接口）
  getExhibitDetail(id) {
    return request({
      url: `/museum/exhibit/info/${id}`,
      method: 'POST',
    });
  },
  // 获取文物列表
  getArtifactList(params = {}) {
    return request({
      url: '/museum/artifact/page',
      method: 'POST',
      data: {
        pageNum: 1,
        pageSize: 10,
        status: 1,
        title: '',
        type: 0,
        ...params,
      },
    });
  },

  // 获取典藏详情
  getCollectionDetail(id) {
    return request({
      url: `/museum/collection/${id}`,
      method: 'GET',
    });
  },

  // 获取文物详情
  getArtifactDetail(id) {
    return request({
      url: `/museum/artifact/info/${id}`,
      method: 'POST',
    });
  },

  // 获取新闻详情
  getNewsDetail(id) {
    return request({
      url: `/museum/news/${id}`,
      method: 'GET',
    });
  },

  // 获取资讯详情
  getInformationDetail(id) {
    return request({
      url: `/museum/information/info/${id}`,
      method: 'POST',
    });
  },

  // 获取活动详情
  getActivityDetail(id) {
    return request({
      url: `/museum/activity/info/${id}`,
      method: 'POST',
    });
  },
  // 获取活动剩余票数
  getActivityticket(data) {
    return request({
      url: `/museum/activity/wxinfo`,
      method: 'POST',
      data: data,
      useToken: true
    });
  },

  // 获取展馆介绍详情
  getMuseumDetail(type) {
    return request({
      url: `/museum/introContext/info/${type}`,
      method: 'POST',
    });
  },

  // 获取微信JSSDK配置
  getWxJssdkConfig(url) {
    return request({
      url: '/museum/wxMini/getWxJssdkConfig',
      method: 'GET',
      data: {
        url: url
      }
    });
  },

  // 添加收藏
  addCollection(id) {
    return request({
      url: `/museum/artifact/collect/${id}`,
      method: 'post',
      useToken: true
    });
  },

  // 取消收藏
  removeCollection(id) {
    return request({
      url: `/museum/artifact/uncollect/${id}`,
      method: 'post',
      useToken: true
    });
  },

  // 获取用户收藏状态
  getCollectionStatus(id) {
    return request({
      url: `/museum/artifact/collectStatus/${id}`,
      method: 'get',
      useToken: true
    });
  },

  // 获取用户信息
  getUserInfo() {
    return request({
      url: '/museum/user/info',
      method: 'get',
      useToken: true
    });
  },

  // 更新用户信息
  updateUserInfo(data) {
    return request({
      url: '/museum/user/update',
      method: 'post',
      data,
      useToken: true
    });
  },

  // 获取指定日期的预约时段信息
  getSlotsByDate(dateString) {
    return request({
      url: '/museum/appointmentSlots/getSlotsByDate',
      method: 'POST',
      data: {
        time: dateString
      },
      useToken: true
    });
  },

  // 获取预约时段信息
  getSlots() {
    return request({
      url: '/museum/appointmentSlots/getSlots',
      method: 'POST',
      useToken: true
    });
  },

  // 获取我的参观人列表
  getMyVisitors() {
    return request({
      url: '/museum/appointmentVisitors/listMyVisitors',
      method: 'post',
      useToken: true
    });
  },

  // 提交预约
  submitReservation(params) {
    return request({
      url: '/museum/appointment/reservation',
      method: 'POST',
      data: params,
      useToken: true
    });
  },

  // 获取我的预约列表
  getMyReservations(params = {}) {
    return request({
      url: '/museum/appointment/pageMy',
      method: 'POST',
      data: {
        pageNum: 1,
        pageSize: 10,
        type: 0, // 预约类型：0-全部，1-参观，2-活动
        ...params
      },
      useToken: true
    });
  },

  // 新增参观人
  addVisitor(params) {
    return request({
      url: '/museum/appointmentVisitors/add',
      method: 'POST',
      data: params,
      useToken: true
    });
  },

  // 删除参观人
  deleteVisitor(id) {
    return request({
      url: `/museum/appointmentVisitors/del/${id}`,
      method: 'POST',
      useToken: true
    });
  },

  // 提交意见反馈
  submitFeedback(params) {
    return request({
      url: '/museum/feedback/add',
      method: 'POST',
      data: params,
      useToken: true
    });
  },

  // 取消预约
  cancelReservation(id) {
    return request({
      url: `/museum/appointment/cancel/${id}`,
      method: 'POST',
      useToken: true
    });
  },

  // 获取讲解服务列表
  getAppointmentServiceList() {
    return request({
      url: '/museum/appointmentService/list',
      method: 'post',
      useToken: true
    });
  }
};

module.exports = {
  museumApi,
  utils
};