import {ACCESS_TOKEN_PREFIX} from './config'
import userInfo from './userInfo'
import tool from './tool'
import axiosObj from './axiosPlugin'
import ElementUI from 'element-ui'
import baseInfo from './baseInfo'
import store from './vuexStore'

const updateToken = function (callback, errorBack) {
  if (!userInfo.hasLogin()) {
    //console.log('尚未登录');
    //userInfo.clear();
    errorBack('E40004')
    return false
  }
  // 比较本地accessToken是否还有效
  if (userInfo.accessToken() && userInfo.accessTokenExpiresIn() && parseInt(userInfo.accessTokenExpiresIn()) + parseInt(userInfo.accessTokenUpdateAt()) - 30 > parseInt(tool.getTimestamp())) {
    // 有效
    //console.log('accessToken有效');
    callback(userInfo.accessToken())
    return true
  } else {
    // 已失效，去更新
    let refreshToken = userInfo.refreshToken()
    let refreshTokenExpiresIn = userInfo.refreshTokenExpiresIn()
    let refreshTokenUpdateAt = userInfo.refreshTokenUpdateAt()
    if (refreshToken && refreshTokenExpiresIn && parseInt(refreshTokenExpiresIn) - 30 + parseInt(refreshTokenUpdateAt) > parseInt(tool.getTimestamp())) {
      // 有效，去更新
      axiosObj.get(`oauth/refresh-token?refresh-token=${refreshToken}`).then(response => {
        // 更新本地accessToken
        userInfo.accessToken(response.accessToken)
        userInfo.accessTokenExpiresIn(response.accessTokenExpiresIn)
        userInfo.accessTokenUpdateAt(response.accessTokenUpdateAt)
        userInfo.refreshToken(response.refreshToken)
        userInfo.refreshTokenExpiresIn(response.refreshTokenExpiresIn)
        userInfo.refreshTokenUpdateAt(response.refreshTokenUpdateAt)
        // 成功
        callback(userInfo.accessToken())
        return true
      }).catch(error => {
        //userInfo.clear();
        //console.log(error);
        errorBack('E40001')
        return false
      })
    } else {
      //console.log('refreshToken已失效');
      userInfo.clear()
      // 失效
      errorBack('E40003')
      return false
    }
  }
}

const network = {
  loginGetAccessToken (userName, password, route = `oauth/login`, data = null) {
    let promise = new Promise((resolve, reject) => {
      // if(userInfo.hasLogin()){
      //     reject('E40005');
      //     return false;
      // }
      if (data === null) {
        data = {
          userName,
          password,
        }
      }
      axiosObj.post(route, data).then(response => {
        // 更新本地accessToken
        userInfo.updateLoginAllInfo(response)
        // 成功
        resolve(response)
      }).catch(error => {
        // console.log('登录获取数据错误');
        userInfo.clear()
        reject(error)
      })
    })
    return promise
  },
  updateToken () {
    let promise = new Promise((resolve, reject) => {
      updateToken(function (accessToken) {
        resolve(accessToken)
      }, function (error) {
        reject(error)
      })
    })
    return promise
  },
  getUserInfo () {
    let promise = new Promise((resolve, reject) => {
      updateToken(function (accessToken) {
        axiosObj.get(`oauth/info`, {
          headers: {
            'Authorization': ACCESS_TOKEN_PREFIX + accessToken,
          }
        }).then(response => {
          // 更新本地userInfo
          userInfo.userId(response.ID)
          userInfo.userName(response.USER_NAME)
          userInfo.baseData({AVATAR: response.AVATAR,VERIFIED: response.VERIFIED,DEC_LV: response.DEC_LV,EMP_LV: response.EMP_LV,PROVINCE: response.PROVINCE,CITY: response.CITY,COUNTY: response.COUNTY})
          // 成功
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      }, function (error) {
        reject(error)
      })
    })
    return promise
  },
  getBaseInfo () {
    let promise = new Promise((resolve, reject) => {
      updateToken(function (accessToken) {
        axiosObj.get(`site/base-info`, {
          headers: {
            'Authorization': ACCESS_TOKEN_PREFIX + accessToken,
          }
        }).then(response => {
          // 更新本地baseInfo
          baseInfo.clear()
          baseInfo.set(response)
          // 成功
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      }, function (error) {
        reject(error)
      })
    })
    return promise
  },
  getData (route, data = null) {
    if (data === null) {
      data = {}
    }
    let promise = new Promise((resolve, reject) => {
      updateToken(function (accessToken) {
        axiosObj.get(`${route}`, {
          params: data,
          headers: {
            'Authorization': ACCESS_TOKEN_PREFIX + accessToken,
          }
        }).then(response => {
          // 成功
          resolve(response)
        }).catch(error => {
          error = tool.errorHandle(error)
          ElementUI.Message.error(error.message)
          reject(error)
        })
      }, function (error) {
        error = tool.errorHandle(error)
        ElementUI.Message.error(error.message)
        reject(error)
      })
    })
    return promise
  },
  postData (route, data) {
    let promise = new Promise((resolve, reject) => {
      updateToken(function (accessToken) {
        axiosObj.post(`${route}`, data, {
          headers: {
            'Authorization': ACCESS_TOKEN_PREFIX + accessToken,
          }
        }).then(response => {
          // 成功
          resolve(response)
        }).catch(error => {
          error = tool.errorHandle(error)
          ElementUI.Message.error(error.message)
          reject(error)
        })
      }, function (error) {
        error = tool.errorHandle(error)
        ElementUI.Message.error(error.message)
        reject(error)
      })
    })
    return promise
  },
  getPageData (obj, path, page, pageSize, data = null, callback = null) {
    obj.loading = true
    if (page === undefined) page = 1
    if (pageSize === undefined) pageSize = 20
    let paramsData = {
      page: page,
      pageSize: pageSize,
    }
    if (data !== null) {
      paramsData = Object.assign(paramsData, data)
    }
    network.getData(path, paramsData).then(response => {
      obj.tableData = response.list
      obj.loading = false
      obj.currentPage = page
      obj.totalPages = parseInt(response.totalPages)
      obj.totalCount = parseInt(response.totalCount)
      obj.pageSize = pageSize
      if (callback !== null) {
        callback(response)
      }
    }).catch(response => {
      obj.loading = false
    })
  },
  getDaysDiff () {
    let promise = new Promise((resolve, reject) => {
      axiosObj.get(`site/days-diff`).then(response => {
        // 更新本地baseInfo
        baseInfo.setDaysDiff(response.daysDiff)
        // 成功
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
    return promise
  },
  getSiteInfo() {
    let promise = new Promise((resolve, reject) => {
      axiosObj.get(`site/config`).then(response => {
        if (response.siteClose) {
          document.body.innerHTML = response.siteCloseInfo
        } else {
          document.title = response.siteTitle
        }
        // 成功
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
    return promise
  },
  getUnreadMessage () {
    let promise = new Promise((resolve, reject) => {
      network.getData(`message/unread-num`).then(response => {
        store.state.baseInfo.messageUnreadNum = Number.parseInt(response)
        // 成功
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
    return promise
  },

}

export default network
