const app = require('../utils/util.js');
const request = (url, data = {}, type = 'GET') => {
  return new Promise((resolve, reject) => {
    wx.request({
      url: `${app.globalData.publicUrl}${url}`,
      method: type,
      data,
      success({
        data
      }) {
        resolve({
          status: 0,
          data,
          msg: 'request请求成功获取到数据'
        });
      },
      fail(error) {
        reject({
          status: 1,
          msg: 'request请求失败'
        })
      }
    });
  });
};
const checkSessionAndLogin = () => {
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success() {
        const sessionKey = wx.getStorageSync('sessionKey');
        wx.request({
          url: app.globalData.publicUrl + '/wx/student/inspectSession',
          method: "post",
          data: {
            sessionKey: sessionKey
          },
          success: (res) => {
            if (res.data.msg == 0) {
              reject('error');
            } else {
              resolve(sessionKey);
            }
          }
        })
      },
      fail() {
        reject('error');
      }
    });
  }).then(value => {
    return new Promise((resolve, reject) => {
      if (value != '') {
        resolve({
          status: 0,
          sessionKey,
          type: 'sessionKey',
          msg: 'checkSession成功获取到sessionKey'
        });
      } else {
        throw 1;
      }
    });
  }).catch(reason => {
    return new Promise((resolve, reject) => {
      wx.login({
        success(res) {
          if (res.code) {
            resolve({
              status: 0,
              data: res.code,
              type: 'code',
              msg: '成功获取到code'
            });
          } else {
            reject({
              status: 1,
              msg: '获取sessionKey失败'
            });
          }
        }
      });
    });
  }).then(
    value => {
      return new Promise(async (resolve, reject) => {
        if (value.type == 'code') {
          const url = '/wx/user/wx7e7a46e129d6cd0f/login';
          const {
            data
          } = await request(url, {
            code: value.data
          }, 'GET');
          wx.setStorageSync('sessionKey', data.sessionKey);
          resolve(data.sessionKey);
        } else {
          resolve(value);
        }
      });
    }
  );
};
// const scalarArrayEquals = function (array1, array2) {
//   return array1.length == array2.length && array1.every(function (v, i) {
//     return v === array2[i]
//   });
// }
module.exports = {
  request,
  checkSessionAndLogin
  // scalarArrayEquals
}