import Config from '../static/config/index.js';
import WXBizDataCrypt from './WXBizDataCrypt.js';
import context from '../main.js'
import { $EventBus } from './EventBus';

export default {
  // 组装提交订单数据
  AssemblyOrder(shopData, totalPrice, totalNum, buyType, shopCarInfo) {
    if (shopCarInfo && totalNum > 0) {
      let orderDetails = [];
      for (let i = 0; i < shopCarInfo.length; i++) {
        let item = shopCarInfo[i];

        let res = {
          goodsId: item.goodsId, //商品id
          goodsName: item.name, //商品名称
          machineId: undefined, //点单屏机器ID
          num: item.num, //当前sku数量
          realAmount: item.sku.discount * item.num, //实付金额
          amount: item.sku.price * item.num, //总价格
          specRuleDetail: JSON.stringify(item.sku.rules), //规格选项详情
          specRuleIds: item.sku.rules.map((item) => item.ruleId).join(','), //规格选项详情
          skuId: item.skuId, //"sku ID"
          goodsCategory: item.categoryId, //商品分类
        };

        orderDetails.push(res);
      }
      // const shopData = uni.getStorageSync('shopData');
      let DAta = {
        amount: totalPrice, //商品总金额
        goodsNum: totalNum, //商品总数量
        shopId: shopData.id, //店铺f
        machineId: undefined, //机器ID
        source: buyType, //小程序固定传3
        orderDetails: orderDetails,
      };
      return DAta;
    } else {
      context.showToast({
        title: '请选择商品',
      });
    }
  },
  // 加入购物车数据
  async getallNum(Obj, unCheckCount) {
    console.log(Obj);
    let shopCarInfo = uni.getStorageSync('shopCarInfo') || [];
    let size = 0;
    shopCarInfo.forEach((item) => (size += item.num));
	
	if(!unCheckCount) {
		let countOfOrder = uni.getStorageSync('countOfOrder');
		if (size >= countOfOrder) {
		  context.showToast({
			title: '最多可一次购买'+countOfOrder+'杯',
			icon: 'none',
		  });
		  return false;
		}
	}

    if (shopCarInfo) {
      let currentGoods = shopCarInfo.find((v) => v.goodsId == Obj.goodsId && v.skuId == Obj.skuId);
      if (currentGoods) {
        currentGoods.num += Obj.num;
      } else {
        shopCarInfo.push(Obj);
      }
    } else {
      shopCarInfo = [Obj];
    }
    console.log(Obj);
    uni.setStorageSync('shopCarInfo', shopCarInfo);
    $EventBus.$emit('updateCar');
    // if (callback) {
    //   callback();
    // }
  },
  // 商品详情立即购买
  async addGoods(Obj) {
    let goodsList = [];
    let size = 0;
    goodsList.forEach((item) => (size += item.num));
	let countOfOrder = uni.getStorageSync('countOfOrder');
    if (size >= countOfOrder) {
      context.showToast({
        title: '最多可一次购买'+countOfOrder+'杯',
        icon: 'none',
      });
      return false;
    }
    if (goodsList) {
      let currentGoods = goodsList.find(
        (item) => item.goodsId == Obj.goodsId && item.skuId == Obj.skuId
      );
      if (currentGoods) {
        currentGoods.num += 1;
      } else {
        goodsList.push(Obj);
      }
    } else {
      goodsList = [Obj];
    }
    uni.setStorageSync('goodsList', goodsList);
  },

  // 解密手机
  async onGetPhoneNumber(appid, session_key, encryptedData, iv) {
    let pc = await new WXBizDataCrypt(appid, session_key);
    let data = await pc.decryptData(encryptedData, iv);
    return data;
  },
  // 扫码方法
  scanCode() {
    uni.scanCode({
      success: (res) => {
        this.scaninfo = res;
        if (res.result) {
          if (res.result.includes(Config.AVScanUrl)) {
            uni.reLaunch({
              url: `/pages/index/index?q=${res.result}`,
            });
          } else {
            context.showToast({
              title: '二维码错误',
              icon: 'none',
            });
          }
        }
      },
      fail() {
        context.showToast({
          icon: 'none',
          title: '扫码失败',
        });
      },
    });
  },
  formatDate(value) {
    var date = new Date();
    date.setTime(value);
    var month = date.getMonth() + 1;
    if (month < 10) month = '0' + month;
    var cdate = date.getDate();
    if (cdate < 10) cdate = '0' + cdate;
    var hours = date.getHours();
    if (hours < 10) hours = '0' + hours;
    var minutes = date.getMinutes();
    if (minutes < 10) minutes = '0' + minutes;
    var time = date.getFullYear() + '-' + month + '-' + cdate + ' ' + hours + ':' + minutes;
    return time;
  },
  numberFixed(data, fixed = 2) {
    if (data == undefined) {
      return undefined;
    } else if (data == 0) {
      return '0';
    } else {
      return (Math.round(Number(data) * Math.pow(10, fixed)) / Math.pow(10, fixed)).toFixed(fixed);
    }
  },
  isInteger(value) {
      return parseFloat(Number(value).toFixed(2))
  },
  // 计算经纬度之间的距离
  // 根据经纬度计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
  getDistances(lat1, lng1, lat2, lng2) {
    function rad(d) {
      return d * Math.PI / 180.0;
    }
    var radLat1 = rad(lat1);
    var radLat2 = rad(lat2);
    var a = radLat1 - radLat2;
    var b = rad(lng1) - rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
        Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    // 输出为公里
    s = Math.round(s * 10000) / 10000;

    var distance = s;
    var distance_str = "";

    if (parseInt(distance) >= 1) {
        // distance_str = distance.toFixed(1) + "km";
        distance_str = distance.toFixed(2) + "km";
    } else {
        // distance_str = distance * 1000 + "m";
        distance_str = (distance * 1000).toFixed(2) + "m";
    }

    //s=s.toFixed(4);

    // console.info('距离是', s);
    // console.info('距离是', distance_str);
    // return s;
    
    //小小修改，这里返回对象
    let objData = {
        distance: distance,
        distance_str: distance_str
    }
    return objData
  },
  // 单位转换
  getPx(rpx) {
    // console.log((rpx * (wx.getSystemInfoSync().windowWidth / 750)));
    // console.log(wx.getSystemInfoSync().windowWidth);
    return rpx * (wx.getSystemInfoSync().windowWidth / 750);
  },
  // 返回上一页
  goBack() {
			wx.navigateBack({
    			delta: 1
  			});
		},
};
