const {
  Toast
} = require('./util');

// 新的API服务域名
const serverName = 'https://test.4dmuseum.cn/api';
const newServerName = 'https://test.4dmuseum.cn/api';
const fileBaseURL = 'https://test.4dmuseum.cn/swkzModel/index.html';
const cosBaseUrl = 'https://swkz-1332577016.cos.ap-guangzhou.myqcloud.com/'

const urls = {
  //用户API
  getLoginSessionKey: '/wx/user/getLoginSessionKey',
  // checkPaySessionKey:'/wx/api/user/checkLoginSessionKey',
  checkLoginSessionKey: '/wx/user/getBrowsedExhibitions',

  logout: '/wx/user/logout',
  isCollect: '/wx/exhibition/like',
  collectExhibitions: "/wx/user/getExhibitions",
  getOrders: '/wx/user/getOrders',

  // 归藏轮播图接口
  getAntiqueList: '/wx/antique/page',
  // 归藏详情接口
  getAntiqueDetail: '/wx/antique'
};

const requestFns = {};

Object.keys(urls).forEach(function(key) {
  requestFns[key] = function(
    data = {},
    method = "GET",
    success = () => {},
    fail = () => {},
    complete = () => {}
  ) {
    console.log(`request ${urls[key]}`);
    let commonData = {
      loginSessionKey: wx.getStorageSync('token') || ""
    };

    const url = `${serverName}${urls[key]}`;
    return wx.request({
      method: method || 'GET',
      url,
      data: {
        ...data,
        ...commonData
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function(res) {
        if (res.data.code == 0) {
          console.log(`request ${urls[key]}, success:`, res);
          success(res);
        } else if (res.data.code == 102) {
          // 未登录
          wx.showModal({
            title: '提示',
            content: '登录才能进行以上操作,确定登录吗？',
            confirmColor: '#e83828',
            success: function (res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/login_page/index',
                  success: function (res) { },
                  fail: function (res) { },
                  complete: function (res) { },
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
          fail(res);
        } else if (res.data.code == 11) {
          Toast.showToast('warn', '提交信息不完整');
          fail(res);
        } else if (res.data.code == 101) {
          Toast.showToast('warn', '网络超时，请重新登录');
          fail(res);
        } else if (res.data.code == -1) {
          Toast.showToast('warn', '请求发送失败');
          fail(res);
        } else {
          Toast.showToast('warn', res.data.msg || '网络超时，请检查网络');
          fail(res);
        }
      },
      fail: function(res) {
        fail(res);
      },
      complete: function() {
        complete()
      }
    });
  };
});

const request = {
  getAntiqueList: function(data, method, success, fail) {
    wx.request({
      url: serverName + urls.getAntiqueList,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (res.statusCode === 200) {
          if (res.data.code === 0) {
            success(res);
          } else if (res.data.code === 401) {
            // 未登录
            wx.showToast({
              title: '请先登录',
              icon: 'none'
            });
            fail(res);
          } else if (res.data.code === 400) {
            // 提交信息不完整
            wx.showToast({
              title: res.data.msg || '提交信息不完整',
              icon: 'none'
            });
            fail(res);
          } else {
            // 其他错误
            wx.showToast({
              title: res.data.msg || '请求失败',
              icon: 'none'
            });
            fail(res);
          }
        } else {
          // 网络错误
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
          fail(res);
        }
      },
      fail: function(err) {
        // 请求失败
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
        fail(err);
      }
    });
  },
  
  getAntiqueDetail: function(data, method, success, fail) {
    // 从页面参数中获取id
    const pages = getCurrentPages();
    const currentPage = pages[pages.length - 1];
    const id = currentPage.data.id;
    
    if (!id) {
      wx.showToast({
        title: '缺少文物ID',
        icon: 'none'
      });
      fail({ msg: '缺少文物ID' });
      return;
    }
    
    wx.request({
      url: serverName + urls.getAntiqueDetail + '/' + id,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (res.statusCode === 200) {
          if (res.data.code === 0) {
            success(res);
          } else if (res.data.code === 401) {
            // 未登录
            wx.showToast({
              title: '请先登录',
              icon: 'none'
            });
            fail(res);
          } else if (res.data.code === 400) {
            // 提交信息不完整
            wx.showToast({
              title: res.data.msg || '提交信息不完整',
              icon: 'none'
            });
            fail(res);
          } else {
            // 其他错误
            wx.showToast({
              title: res.data.msg || '请求失败',
              icon: 'none'
            });
            fail(res);
          }
        } else {
          // 网络错误
          wx.showToast({
            title: '网络错误',
            icon: 'none'
          });
          fail(res);
        }
      },
      fail: function(err) {
        // 请求失败
        wx.showToast({
          title: '请求失败',
          icon: 'none'
        });
        fail(err);
      }
    });
  }
};

module.exports.request = request;
module.exports.serverName = serverName;
module.exports.newServerName = newServerName;
module.exports.cosBaseUrl = cosBaseUrl;
module.exports.fileBaseURL = fileBaseURL;