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'

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)
        // 成功
        //console.log('accessToken更新成功，refreshToken更新为：'+userInfo.refreshToken());
        //console.log('accessToken更新成功，refreshToken的更新时间为：'+tool.formatDate(userInfo.refreshTokenUpdateAt()));
        //console.log('accessToken更新成功，refreshToken的有效时间为：'+userInfo.refreshTokenExpiresIn());
        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(adminName, password, verifyCode, pageId) {
    let promise = new Promise((resolve, reject) => {
      // if(userInfo.hasLogin()){
      //     reject('E40005');
      //     return false;
      // }
      axiosObj.post(`oauth/login?page_id=${pageId}`, {
        LoginForm: {
          adminName,
          password,
          verifyCode,
        }
      }).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.adminName(response.ADMIN_NAME)
          userInfo.baseData({roleId: response.ROLE_ID})
          // 成功
          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.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({type: 'error', message: error.message, showClose: true, duration: 0})
          reject(error)
        })
      }, function (error) {
        error = tool.errorHandle(error)
        ElementUI.Message({type: 'error', message: error.message, showClose: true, duration: 0})
        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({type: 'error', message: error.message, showClose: true, duration: 0})
          reject(error)
        })
      }, function (error) {
        error = tool.errorHandle(error)
        ElementUI.Message({type: 'error', message: error.message, showClose: true, duration: 0})
        reject(error)
      })
    })
    return promise
  },
  getPageData(obj, path, page = null, pageSize = null, data = null, callback = null, isLoading = null, percentFieldName = null) {
    if (isLoading === false) {
      obj.loading = isLoading
    } else {
      obj.loading = true
    }
    if (page === null) page = 1
    if (pageSize === null) pageSize = 20
    let paramsData = {
      page: page,
      pageSize: pageSize,
    }
    if (data === null || tool.isEmptyObject(data)) {
      // 查看地址栏中的内容，如果有内容则把地址栏中的参数给拿到
      if(window.location.href.indexOf('filter') !== -1){
        let nowUrl = tool.parseURL(window.location.href)
        if(nowUrl.params.filter){
          data = JSON.parse(unescape(nowUrl.params.filter))
          if(obj.filterModel){
            obj.filterModel = data
          }
        }
      }
    }
    paramsData = Object.assign(paramsData, data)
    network.getData(path, paramsData).then(response => {
      obj.tableData = response.list
      obj.tableHeaders = response.columnsShow ? response.columnsShow : []
      obj.loading = false
      obj.currentPage = page
      obj.totalPages = parseInt(response.totalPages)
      obj.totalCount = parseInt(response.totalCount)
      obj.pageSize = pageSize
      if (percentFieldName !== null) {
        if(percentFieldName.length > 0){
          for(let i in obj.tableData){
            for(let j in percentFieldName){
              obj.$set(obj.percentList[percentFieldName[j]], obj.tableData[i].ID, obj.tableData[i][percentFieldName[j]])
            }
          }
        }
      }
      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
  }

}

export default network
