import { store } from '@/store'

// 节流
export function throttle(func, wait, options = {
  leading: false,
  trailing: true
}) {
  let timeout, context, args, result
  let previous = 0

  const later = function () {
    previous = options.leading === false ? 0 : +new Date()
    timeout = null
    func.apply(context, args)
    if (!timeout) context = args = null
  }

  const throttled = function () {
    context = this
    args = arguments
    let now = +new Date()
    if (!previous && options.leading === false) previous = now
    let remaining = wait - (now - previous)
    context = this
    args = arguments
    if (remaining <= 0 || remaining > wait) {
      if (timeout) {
        clearTimeout(timeout)
        timeout = null
      }
      previous = now
      func.apply(context, args)
      if (!timeout) context = args = null
    } else if (!timeout && options.trailing !== false) {
      timeout = setTimeout(later, remaining)
    }
  }

  throttled.cancel = function () {
    clearTimeout(timeout)
    previous = 0
    timeout = null
  }

  return throttled
}

// 防抖
export function debounce(func, wait, immediate) {

  var timeout, result;

  var debounced = function () {
    var context = this;
    var args = arguments;

    if (timeout) clearTimeout(timeout);
    if (immediate) {
      // 如果已经执行过，不再执行
      var callNow = !timeout;
      timeout = setTimeout(function () {
        timeout = null;
      }, wait)
      if (callNow) result = func.apply(context, args)
    }
    else {
      timeout = setTimeout(function () {
        func.apply(context, args)
      }, wait);
    }
    return result;
  };

  debounced.cancel = function () {
    clearTimeout(timeout);
    timeout = null;
  };

  return debounced;
}

// 延迟加载
export const lazyLoad = ({ target, arr, totalCount, pageSize = 10 }) => {
  // console.log(target, arr, totalCount)
  if (totalCount === 0) return false
  let time = 0
  let timer = null
  loop(1)
  function loop(page) {
    timer = setTimeout(() => {
      let start = (page - 1) * pageSize
      let count = Math.min(page * pageSize, totalCount)
      for (let i = start; i < count; i++) {
        target.push(arr[i])
      }
      page++
      if (timer) {
        clearTimeout(timer)
      }
      if ((page - 1) * pageSize < totalCount) {
        time = 1000
        loop(page)
      }
    }, time)
  }
}

// 数据组合成queryString形式
export function json2query(json) {
  let str = ''
  for (let attr in json) {
    let value = json[attr]
    if (Object.prototype.toString.call(value).indexOf('Array') > -1) {
      // 数组
      str += `${attr}=${JSON.stringify(value)}&`
    } else {
      str += `${attr}=${value}&`
    }
  }
  return str.substring(0, str.length - 1)
}


// 判断空 json
export function isEmptyObj(obj) {
  let name
  for (name in obj) {
    return false
  }
  return true
}

// 判断数据类型
var class2type = {}
'Boolean Number String Function Array Date RegExp Object Error'.split(' ').map(item => {
  class2type[`[object ${item}]`] = item.toLowerCase()
})
function type(obj) {
  if (obj === null) {
    return obj + ''
  }
  return (typeof obj === 'object' || typeof obj === 'function') ? (
    Object.prototype.toString.call(obj) || 'object'
  ) : (typeof obj)
}

// isFunction
export function isFunction(obj) {
  return type(obj) === 'function'
}

// isArray
export const isArray = Array.isArray || function (obj) {
  return type(obj) === 'array'
}

// 重量转换
export const switchWeight = (weight) => {
  if (weight >= 1000) {
    return weight / 1000 + 'kg'
  } else {
    return weight + 'g'
  }
}

/**
 * sleep 函数
 * @param {Number} time 毫秒
 */
export const sleep = async (timeout = 1000) => {
  await new Promise((resolve) => {
    setTimeout(() => {
      resolve()
    }, timeout)
  })
}

export const businessHours = (start = 1, range = 48) => {
  let timeList = [
    // {value: 30, label: '00:30'},
  ]
  // 生成 timeList
  for (let i = start; i < range; i++) {
    timeList.push({
      value: 0 + (Math.ceil(i / 2) * 30 + Math.floor(i / 2) * 70),
      label: dealOpenTime(0 + (Math.ceil(i / 2) * 30 + Math.floor(i / 2) * 70))
    })
  }
  timeList.push({
    value: 2359,
    label: '23:59'
  })
  timeList.unshift({
    value: 1,
    label: '00:01'
  })
  timeList.unshift({
    value: 0,
    label: '无'
  })
  console.log(timeList)
  return timeList
}

export const dealOpenTime = (str) => {
  str = str.toString()
  if (str.length < 3) str = '0' + str
  if (str.length < 4) str = '0' + str

  return str.slice(0, 2) + ':' + str.slice(2, 4)
}
// 处理时间 2018-12-12 12:12:12
export const timeFormat = (time) => {
  let timer = new Date(time)
  return `${timer.getFullYear()}-${(timer.getMonth() + 1) < 10 ? '0' + (timer.getMonth() + 1) : (timer.getMonth() + 1)}-${timer.getDate() < 10 ? '0' + timer.getDate() : timer.getDate()} ${timer.getHours() < 10 ? '0' + timer.getHours() : timer.getHours()}:${timer.getMinutes() < 10 ? '0' + timer.getMinutes() : timer.getMinutes()}:${timer.getSeconds() < 10 ? '0' + timer.getSeconds() : timer.getSeconds()}`
}

// 处理时间 2018-12-12 12:12
export const timeFormat2 = (time) => {
  let timer = new Date(time)
  return `${timer.getFullYear()}-${(timer.getMonth() + 1) < 10 ? '0' + (timer.getMonth() + 1) : (timer.getMonth() + 1)}-${timer.getDate() < 10 ? '0' + timer.getDate() : timer.getDate()}  ${timer.getHours() < 10 ? '0' + timer.getHours() : timer.getHours()}:${timer.getMinutes() < 10 ? '0' + timer.getMinutes() : timer.getMinutes()}`
}
// 处理时间 2018-12-12
export const timeFormat3 = (time) => {
  let timer = time ? new Date(time) : new Date()
  return `${timer.getFullYear()}-${(timer.getMonth() + 1) < 10 ? '0' + (timer.getMonth() + 1) : (timer.getMonth() + 1)}-${timer.getDate() < 10 ? '0' + timer.getDate() : timer.getDate()}`
}

export const isNullDate = (date) => {
  if (!date || date.indexOf('1970-01-01') !== -1 || date.indexOf('0001-01-01') !== -1) {
    return true
  } else {
    return false
  }
}

// 两个经纬度之间的距离
export const getDistance = (lat, lng) => {
  let PI = Math.PI // 圆周率
  let R = 6371229 // 地球半径
  let x, y;

  let location = {
    lng: Number(store.getters['indexPage/myLocation'].lng),
    lat: Number(store.getters['indexPage/myLocation'].lat)
  }
  // let lngRes = store.state.location.lng > Number(lng) ? store.state.location.lng - Number(lng) : Number(lng) - store.state.location.lng
  let lngRes = location.lng > Number(lng) ? location.lng - Number(lng) : Number(lng) - location.lng
  // let latRes=store.state.location.lat > Number(lat) ?store.state.location.lat-Number(lat):Number(lat)-store.state.location.lat
  x = (lngRes) * PI * R * Math.cos(((Number(location.lat) + Number(lat)) / 2) * PI / 180) / 180
  y = (Number(lat) - location.lat) * PI * R / 180
  let s = Math.hypot(x, y)
  return s
}

export const mapSkuNames = (skuNames) => {
  const isMaterial = store.getters['indexPage/isMaterial']
  const carList = store.getters['cartPage/cartList']
  const storeID = store.getters['indexPage/storeID']


  const bagSkuIDs = store.getters['indexPage/bagSkuIDs']
  const actSkuIDs = store.getters['indexPage/actSkuIDs']

  return skuNames.filter(skuName => skuName.skus).map(skuName => {
    const sku = skuName.skus[0]
    // 处理购物车商品
    let count = 0
    let findCarGood = carList.find(item => item.id === sku.id && item.storeID === skuName.storeID)
    if (findCarGood) {
      count = findCarGood.count
    }
    const common = {
      id: sku.id,
      nameID: skuName.id,
      descImg: skuName.descImg,
      img: skuName.img,
      img2: skuName.img2,
      name: computedName(skuName, sku),
      storeID: skuName.storeID,
      storeName: skuName.storeName,
      actType: sku.actType,
      // earningPrice: sku.earningPrice,
      count,
      weight: sku.weight,
      stock: sku.stock,
      trendType: sku.trendType,
      trendPrice: sku.trendPrice,
      actPrice: sku.actPrice,
      discountType: sku.discountType,
      discountValue1: sku.discountValue1,
      discountValue2: sku.discountValue2,
      unit: skuName.unit
    }
    if (isMaterial) {
      if (bagSkuIDs.includes(sku.id)) {
        // console.log('袋子', sku.id)
        // 袋子
        return {
          ...common,
          // categoryID: skuName.categoryID,
          // 对price做处理，curPrice为卖价，如果有活动价，填充活动价，没有就填充原价;oriPrice 为原价，如果有活动价，填充原价，没有活动价为0
          curPrice: sku.actPrice ? sku.actPrice : sku.jxPrice,
          oriPrice: sku.jxPrice,
          specCount: +sku.comment.match(/\d+/)[0],
          jxPrice: sku.jxPrice
        }
      } else {
        return {
          ...common,
          // categoryID: skuName.categoryID,
          // 对price做处理，curPrice为卖价，如果有活动价，填充活动价，没有就填充原价;oriPrice 为原价，如果有活动价，填充原价，没有活动价为0
          curPrice: sku.actPrice ? sku.actPrice : sku.jxPrice,
          oriPrice: sku.actPrice ? sku.jxPrice : 0,
        }
      }
    } else {
      if (storeID && storeID.includes(666666) && actSkuIDs && actSkuIDs.includes(sku.id)) {
        // 贴纸和招牌
        return {
          ...common,
          actType: 0,
          curPrice: sku.jxPrice,
          oriPrice: 0
        }
      } else {
        return {
          ...common,
          // categoryID: skuName.categoryID,
          // 对price做处理，curPrice为卖价，如果有活动价，填充活动价，没有就填充原价;oriPrice 为原价，如果有活动价，填充原价，没有活动价为0
          curPrice: sku.actPrice ? sku.actPrice : sku.jxPrice,
          oriPrice: sku.actPrice ? sku.jxPrice : 0
        }
      }
    }
  })
}

export const computedName = (skuName, sku) => {
  let name = ''
  if (skuName.prefix) name += `[${skuName.prefix}]`
  name += skuName.name
  if (skuName.unit === '份') name += '约'
  name += +sku.specQuality
  name += sku.specUnit
  name += '/' + skuName.unit
  if (sku.comment) name += `(${sku.comment})`
  return name
}

// 对商品清单进行门店分组
export const groupByStore = (list) => {
  // console.log(list)
  let json = {}
  list.forEach(item => {
    let key = item.storeID
    // console.log(key)
    if (key in json) {
      json[key].push(item)
    } else {
      json[key] = []
      json[key].push(item)
    }
  })
  return json
}

export const mapData = (data) => {
  if (!data) {
    return []
  } else {
    return data.map(item => {
      return {
        vendorOrderID: item.vendorOrderID,
        vendorID: item.vendorID,
        storeName: item.storeName,
        storeID: item.storeID,
        status: item.status, // 状态
        salePrice: item.salePrice, // 订单商品价格
        actualPayPrice: item.actualPayPrice, // 实际支付
        // needPayEndAt: '2019-12-03T14:00:00+08:00',
        desiredFee: item.desiredFee, // 配送费
        businessType: item.businessType, // 1 立即达 2 定时达
        expectedDeliveredTime: item.expectedDeliveredTime, // 预计送达时间
        orderCreatedAt: item.orderCreatedAt, // 下单时间
        consigneeAddress: item.consigneeAddress, // 客户地址
        consigneeMobile: item.consigneeMobile, // 客户电话
        consigneeName: item.consigneeName, // 客户姓名
        courierMobile: item.courierMobile, // 骑手电话
        courierName: item.courierName, // 骑手姓名
        waybillVendorID: item.waybillVendorID, // 骑手厂商
        vendorWaybillID: item.vendorWaybillID, // 运单ID
        goodsCount: item.goodsCount, // 商品数量
        skuList: item.skuList,
        weight: item.weight,
        buyerComment: item.buyerComment, // 备注
        deliveryType: item.deliveryType, // 配送类型
        orderFinishedAt: item.orderFinishedAt, // 完成时间
      }
    })
  }
}