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 && totalPrice > 0 && 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) {
    const val = Number(value)
     if(val%1 === 0){
       return parseInt(val)
     }else{
       return val.toFixed(1)
     }
  },
};
