import Global from './global'
import Auth from './auth'
import Cache from './cache'
import Dialog from './dialog'
import Util from './util2'
import ApiEnum from './api_enum'

//加载器文本
let _loadingTextDefault = '加载中..'
let api = {};

// 获取设备信息
let getDevice = ()=>{
  if(api._device){
    return api._device
  }
  
  let deviceInfo = uni.getSystemInfoSync()
  // '设备名称|设备版本|设备系统版本|设备当前使用语言|设备屏幕分辨率|http请求版本|设备唯一识别码|default'
  // 'MI 5|V1.0.0|6.0.1|zh|720*1280|1.0|320981221265414|default'
  let device = [
    deviceInfo.model,
    deviceInfo.version,
    deviceInfo.system,
    deviceInfo.language,
    deviceInfo.screenWidth+'*'+deviceInfo.screenHeight,
    'default',
    'default',
    'default'
  ].join('|');

  api._device = device
  return device
}

// 获取请求时间，并格式化
let getRequestTime = () => {
  let time = new Date().getTime();
  let requestTime = Util.dateFormat(time, "yyyyMMddhhmmss");
  return requestTime;
}

// 获取随机数
let getRands = () => {
  let num = Math.random() * (999999 - 100000) + 100000;
  let rands = parseInt(num, 10);
  return rands
}

api.request = (code, data, method = 'GET', dataType = 'json', header = null) => {
  //设置请求头
  header = header || {}
  header['Content-Type'] = 'application/json;charset=UTF-8'
  
  let head = {
    version:'v1',
    device: getDevice(),
    reqtime: getRequestTime(),
    seqno: getRands(),
    sessionId: Auth.getSessionId()
  }
  if([ApiEnum.loginByCode, ApiEnum.loginByWxapp].includes(code)){
    delete head.sessionId
  }

  // 1	reqtime	请求时间	N	X（14）	yyyymmddhhmmss
  // 2	seqno	请求随机数	N	X（6）	随机数
  // 3	device 	设备信息	N	X（100）	设备信息
  // 4	sessionId	会话	Y	X（20）	当需要识别请求者身份时必填
  // 5	version	请求版本号	Y	X	默认v1

  //设置请求参数
  data = data || {}
  
  //操作店铺
  if(!Array.isArray(data)){
    data.storeId = data.storeId || Global.server.storeId;
  }

  //是否显示加载器
  let isShowLoading = data._isShowLoading || false
  let isPull = data._isPull || false
  let loadingText = data._loadingText || _loadingTextDefault
  let isReject = data._isReject || false

  //显示加载器
  if (isShowLoading) {
    isShowLoading = true
    Dialog.showLoading(loadingText)
  }

  //删除字段
  delete data._isShowLoading
  delete data._isPull
  delete data._isReject
  delete data._loadingText
  
  let realData = {}
  realData.head = head
  realData.body = data

  return new Promise((resolve, reject) => {
    //请求http
    uni.request({
      header: header,
      url: Global.server.apiUrl + "/"+Global.server.miniappCode+"/"+code,
      data: method=='POST'?realData:data,
      dataType: dataType,
      responseType: 'text',
      method: method,
      success: (res)=>{
        let response=res.data;
        if(response.head.bzflag=='200' && response.head.sysflag=='200'){
          resolve(response.body)
        }else{
          if(isReject){
            reject(response.head)
            return 
          }
          Dialog.alert({
            content: response.head.errmsg || '服务繁忙，请稍后再试...'
          })
        }
      },
      fail: (res)=>{
        console.error(res)
      },
      complete: ()=>{
        if(isPull){
          uni.stopPullDownRefresh()
        }
        if (isShowLoading) {
          Dialog.hideLoading()
        }
      }
    })
  })
}

// 包裹一层，方便后续拓展
api.requestWithTicket = (code, data, method = 'GET', dataType = 'json') => {
  return new Promise((resolve, reject) => {
    api.request(code, data, method, dataType)
      .then(resolve)
      .catch(reject)
  })
}

/**  
 * 上传图片(多张)
 * @param {string} uri 文件路径 [Y] 
 * @param {string} type 'multipart/form-data' [Y]
 * @param {string} name 文件key [Y]
 * 
 * @return {Array<Object>} body
 *    @return {string} id
 *    @return {string} name
 *    @return {string} path
 */
api.uploadImg = (data) => {

  data = data || {}
  
  let isShowLoading = data._isShowLoading || false
  let isReject = data._isReject || false
  if(isShowLoading){
    Dialog.showLoading('上传中...')
  }
  return new Promise((resolve, reject) => {
    let header = {}
    header['Content-Type'] = 'multipart/form-data;'
    let uploadUrl = Global.server.apiUrl + "/" + Global.server.miniappCode+ "/" + ApiEnum.uploadImg

    uni.uploadFile({
      url: uploadUrl,
      filePath: data.uri,
      header: header,
      async: false,
      name: data.name,
      formData: {
        uri: data.uri, 
        type: 'multipart/form-data',
        name: data.name
      },
      success: (res) => {
        let ret = JSON.parse(res.data)
        if(res.statusCode==200){
          resolve(ret.body)
        }else{
          if(isReject){
            reject(ret)
          }
        }
      },
      fail: (err) => {
        if(isReject){
          resolve(err)
        }
      },
      complete: () => {
        if(isShowLoading){
          Dialog.hideLoading()
        }
      }
    })
  })
}

export default api