<template>
  <view class="u-wrap u-font-14 bg-gray">
    <template v-if="false">
      <my-skeleton @skeletonClick="skeletonClick"></my-skeleton>
    </template>
    <template v-else>
      <view class="fixed top bg-fff u-flex u-flex-row">
        <template v-if="true">
          <view
            class="u-flex u-font-32 u-p-l-58"
            style="padding-right: 100rpx"
            @click="uni.navigateBack()"
          >
            <up-icon name="arrow-left" size="32rpx" color="#333"></up-icon>
            <text class="u-m-l-20">返回</text>
          </view>
          <view class="u-flex-1 u-flex u-flex-row" style="overflow-x: scroll">
            <!-- 顶部左侧   -->
            <scroll-view
              v-if="!isSearch"
              scroll-x
              scroll-with-animation
              :scroll-left="tabsEle.scrollLeft"
              class="u-tab-view content-scroll u-flex-row u-flex-1"
              style="white-space: nowrap"
            >
              <view class="u-flex u-flex-row">
                <view
                  v-for="(item, index) in layoutData.category.list"
                  :key="index"
                  class="u-tab-item"
                  :class="[
                    layoutData.category.sel == index ? 'u-tab-item-active' : '',
                    'u-tab-item' + index,
                  ]"
                  @tap.stop="changeCategorySel(index)"
                >
                  <text class="u-line-1 u-font-14">{{ item.name }}</text>
                </view>
              </view>
            </scroll-view>
          </view>
          <!-- 顶部右侧 选择桌台什么的 -->
          <view class="search-box u-flex u-col-center color-333 u-font-32">
            <!-- 	<view style="display: flex;align-items: center;">
							<view :class="[lvhong?'lvstyle':'hongstyle']">
							</view><text style="margin: 0 6px;">状态</text>
						</view> -->
            <view class="u-flex u-col-center" @click="chooseTable">
              <view class="u-flex u-col-center u-m-r-22">
                <image
                  src="/pagesCreateOrder/static/images/icon-table.svg"
                  mode=""
                  style="width: 20px; height: 20px"
                ></image>
              </view>
              <view class="u-m-r-12 font-14 no-wrap">
                <view class="u-flex" v-if="data.table.name">
                  <text class="font-bold u-m-r-4 no-wrap">
                    {{ data.table.name }}
                  </text>
                  <!-- <view
                    class="u-flex"
                    @click.stop="resetTable"
                    style="margin-left: 6px"
                  >
                    <up-icon
                      name="close-circle"
                      color="rgb(250,173,40)"
                      bold=""
                      :size="24"
                    ></up-icon>
                  </view> -->
                </view>

                <text class="no-wrap" v-else>换台</text>
              </view>
            </view>

            <view
              class="u-flex u-col-center"
              @click="toOrder"
              style="margin-left: 74rpx"
            >
              <view class="u-flex">
                <image
                  src="/static/iconImg/order.svg"
                  style="width: 40rpx; height: 40rpx"
                />
              </view>

              <view class="u-m-l-22">已点订单</view>
            </view>

            <view
              style="margin-left: 74rpx"
              class="u-flex u-col-center"
              @click="changePop('search', true)"
            >
              <view class="u-flex u-m-r-22">
                <up-icon name="search" size="24"></up-icon>
              </view>
              <view class="">搜索</view>
            </view>
            <view class="u-flex u-col-center u-m-l-10">
              <view
                class="color-333 u-font-32 font-700"
                style="margin-left: 87px"
                >{{ accountStore.shopStaff.name }}</view
              >
            </view>
            <view class="u-flex u-col-center u-m-l-38" @click="loginShowOut">
              <view class="u-flex">
                <!-- <up-icon name="account" size="24"></up-icon> -->
              </view>
              <view style="color: #aaa">退出登录</view>
            </view>
          </view>
        </template>
      </view>
      <template v-if="!isSearch">
        <!-- 	<view style="margin-top: 200px;">
				</view> -->
        <swiper
          :current="layoutData.current"
          :indicator-dots="false"
          :autoplay="false"
          :interval="3000"
          @transition="animationStart"
          @animationfinish="animationfinish"
          :duration="300"
          style="width: 100vw; height: 100vh"
        >
          <swiper-item v-for="(item, index) in layoutData.list" :key="index">
            <view
              class="bg-gray swiper-item-box h-100 u-flex u-flex-col"
              :style="computedSwiperItemStyle"
            >
              <view :style="zhanweiStyle"></view>
              <template v-if="item.productList.length > 0">
                <view
                  class="item-container u-flex-1"
                  :class="['layout-' + item.padLayoutCode]"
                >
                  <!-- style="height: 100%;" -->
                  <view
                    :class="['div' + (goodsIndex + 1)]"
                    v-for="(goodsItem, goodsIndex) in item.productList"
                    :key="goodsIndex"
                  >
                    <!-- <img :src="goodsItem.coverImg" alt="" /> -->
                    <cart-goods-item
                      @chooseGuige="chooseGuige($event, goodsIndex)"
                      :layout="layout.sel"
                      @showDetail="showDetail(goodsItem)"
                      :windowWidth="sysInfo.windowWidth"
                      :windowHeight="sysInfo.windowHeight"
                      @add="goodsUpdate($event, goodsIndex, true)"
                      @reduce="goodsUpdate($event, goodsIndex, false)"
                      :index="index"
                      @tapweigh="tapweigh($event, goodsIndex)"
                      :data="goodsItem"
                      :limitTimeDiscount="data.limitTimeDiscount"
                    ></cart-goods-item>
                  </view>
                </view>
              </template>
              <template v-else>
                <view class="u-p-30">
                  <my-img-empty tips="该分类下暂无商品"></my-img-empty>
                </view>
              </template>
            </view>
          </swiper-item>
        </swiper>
      </template>
      <template v-else>
        <swiper
          :indicator-dots="false"
          :autoplay="false"
          :interval="3000"
          :duration="300"
          style="width: 100vw; height: 100vh"
        >
          <template v-if="searchResult.length > 0">
            <swiper-item v-for="(item, index) in searchResult" :key="index">
              <view
                class="bg-fff swiper-item-box h-100 u-flex u-flex-col"
                :style="computedSwiperItemStyle"
              >
                <view :style="zhanweiStyle"></view>
                <view
                  class="item-container u-flex-1"
                  :class="['layout-' + item.padLayoutCode]"
                >
                  <view
                    :class="['div' + (goodsIndex + 1)]"
                    v-for="(goodsItem, goodsIndex) in item.productList"
                    :key="goodsIndex"
                  >
                    <cart-goods-item
                      @chooseGuige="chooseGuige($event, goodsIndex)"
                      :layout="layout.sel"
                      @showDetail="showDetail(goodsItem)"
                      :windowWidth="sysInfo.windowWidth"
                      :windowHeight="sysInfo.windowHeight"
                      @add="goodsUpdate($event, goodsIndex, true)"
                      @reduce="goodsUpdate($event, goodsIndex, false)"
                      :index="index"
                      @tapweigh="tapweigh($event, goodsIndex)"
                      :data="goodsItem"
                    ></cart-goods-item>
                  </view>
                </view>
              </view>
            </swiper-item>
          </template>

          <swiper-item v-else>
            <view
              class="bg-fff swiper-item-box h-100 u-flex u-flex-col"
              :style="computedSwiperItemStyle"
            >
              <view :style="zhanweiStyle"></view>
              <my-img-empty
                v-if="!searchResult.length"
                tips="未搜索到相关商品"
              ></my-img-empty>
            </view>
          </swiper-item>
        </swiper>
      </template>
      <!-- 是否允许下单 -->
      <!-- <view class="u-fixed position-all" style="z-index: 999;" v-if="!canXiadan" @click="xiadanClick"></view> -->
      <view class="bottom w-full">
        <my-car
          :limitTimeDiscount="data.limitTimeDiscount"
          @updateSafeBottom="updateSafeBottom"
          :instance="instance"
          @updateCart="getCart"
          @updateCartRemark="updateCartRemark"
          :sysInfo="sysInfo"
          :isCreateOrderToDetail="isCreateOrderToDetail"
          @updateNumber="carsNumberChange"
          :user="data.vipUser"
          :masterId="data.masterId"
          :table="data.table"
          :data="cars"
          :orderInfo="data.orderInfo"
          :historyOrder="data.historyOrder"
          :tableCode="data.table.tableCode"
          @clear="cleaCart"
        ></my-car>
      </view>
    </template>

    <!-- 搜索 -->
    <pop-search @search="search" v-model:show="popup.search"></pop-search>
    <!-- 商品详情 -->
    <pop-goods-detail
      v-model:show="popup.goodsDetail"
      :goods="popup.data"
    ></pop-goods-detail>
    <!-- 套餐选择规格 -->
    <taocanModel
      ref="taocanModelRef"
      @confirm="taocanConfirm"
      :goodsData="selGoods"
    ></taocanModel>
    <!-- 选择规格 -->
    <guige-model
      :limitTimeDiscount="data.limitTimeDiscount"
      @update-sku="updateSkuSel"
      @confirm="guigeConfirm"
      ref="chooseGuigeModel"
      :goodsData="selGoods"
      :title="guigeModelData.title"
      :sku-map="guigeModelData.chooseGoods.skuMap"
      :skus="guigeModelData.chooseGoods.skus"
    ></guige-model>
    <!-- 添加附加费 -->
    <my-surcharge
      @confirm="surchargeConfirm"
      ref="surcharge"
      title="添加附加费"
    ></my-surcharge>
    <!-- 称重 -->
    <weigh-item
      ref="refweighitem"
      @weighgoodsUpdate="goodsUpdate"
      :limitTimeDiscount="data.limitTimeDiscount"
    ></weigh-item>
    <up-modal
      title="提示"
      content="该台桌购物车里有商品，是否清除该台桌里的商品?"
      :show="modal.clear"
      showCancelButton
      closeOnClickOverlay
      @confirm="confirmModelConfirm"
      @cancel="confirmModelConfirm('cancel')"
      @close="setModalShow('clear', false)"
      width="300px"
    ></up-modal>
  </view>
</template>
<script setup>
import _ from "lodash";
import * as Api from "@/http/yskApi/Instead.js";
import * as limitTimeDiscountApi from "@/http/yskApi/limitTimeDiscount.js";

import {
  $table,
  $choseTable,
  $returnTableDetail,
} from "@/http/yskApi/table.js";
import weighItem from "./components/weigh.vue";
import taocanModel from "./components/taocanModel.vue";
import util from "./util.js";
import color from "@/commons/color.js";
import guigeModel from "./components/guige";
import cartGoodsItem from "./components/cart-goods-item.vue";
import mySurcharge from "./components/surcharge";
import mySkeleton from "./components/skeleton";
import popSearch from "./components/pop-search.vue";
import popGoodsDetail from "./components/pop-goods-detail.vue";
import {
  $getProductDetail,
  adminProduct,
  $tbShopCategory,
  getHistoryOrder,
  rmPlaceOrder,
} from "@/http/yskApi/goods.js";
import {
  onLoad,
  onReady,
  onShow,
  onPageScroll,
  onPullDownRefresh,
  onUnload,
  onHide,
} from "@dcloudio/uni-app";
import {
  onBeforeUnmount,
  computed,
  reactive,
  ref,
  nextTick,
  getCurrentInstance,
  watch,
  onMounted,
  provide,
  inject,
  onUnmounted,
} from "vue";
import myCar from "./components/car";
import go from "@/commons/utils/go.js";
import infoBox from "@/commons/utils/infoBox.js";
import { getNowCart } from "@/pagesCreateOrder/util.js";
// import yskUtils from "ysk-utils";
import yskUtils from "@/lib/index";
provide("yskUtils", yskUtils);

import { useAccountStore } from "@/stores/account";
const accountStore = useAccountStore();

provide("accountStore", accountStore);

import {
  $productCategory,
  $layoutpage,
  cancelOrder,
} from "@/http/yskApi/pad.js";
import { tbShopInfo, getShopInfo, getLayout } from "@/http/yskApi/user.js";
import { hasPermission } from "@/commons/utils/hasPermission.js";
import { getElRect } from "@/commons/utils/safe-bottom.js";
// import {
// 	categorylist
// } from '@/http/yskApi/shop.js'
// import WebsocketUtil from '../../http/websock.js';
// 编辑库存不足的清空下,让首页数量为0-----编辑保存当前列表item
let editItem = ref();
let instance = ref();
instance.value = getCurrentInstance();
const websocketUtil = inject("websocketUtil"); // 注入 WebSocket 工具类实例
function toOrder() {
  go.to("PAGES_ORDER_INDEX");
}
// 状态绿红
const lvhong = ref(true);
//临时菜
const lingshi = reactive({
  show: false,
});
//附加费
const extraFee = reactive({
  show: false,
});
/**
 * 称重
 */
const refweighitem = ref(null);
const tapweigh = (foodsindex, index) => {
  const goods = layoutData.list[foodsindex].productList[index];
  // const goods = data.tabbar[index].foods[foodsindex]
  refweighitem.value.open(foodsindex, index, goods);
};

// wx拿到的数据
const cars = reactive([]);
const layout = reactive({
  listMap: {
    default: {
      size: 4,
    },
    bigOne: {
      size: 1,
    },
  },
  sel: "default",
});
let option = {
  type: "",
};
const data = reactive({
  // loading: true,
  noLogin: false,
  scrollTop: 0, //tab标题的滚动条位置
  oldScrollTop: 0,
  current: 0, // 预设当前项的值
  menuHeight: 0, // 左边菜单的高度
  menuItemHeight: 0, // 左边菜单item的高度
  itemId: "", // 栏目右边scroll-view用于滚动的id
  tabbar: [],
  allGoods: [],
  selCategotyGoods: [],
  menuItemPos: [],
  arr: [],
  scrollRightTop: 0, // 右边栏目scroll-view的滚动条高度
  timer: null, // 定时器
  topZhanwei: 136 + 24,
  // 选择用户
  vipUser: {
    id: "",
  },
  //餐桌号
  masterId: "",
  socketData: {
    type: "pad",
    account: uni.getStorageSync("shopId"),
    shop_id: uni.getStorageSync("shopId"),
    is_gift: 0,
  },
  table: {
    tableId: "",
  },
  historyOrder: [],
  userInfo: "",
  limitTimeDiscount: null,
});
// 获取账号信息
let $shop = ref({});
const layoutArr = {
  1: "single",
  2: "double",
  3: "L1-R2",
  4: "4-gird",
  6: "6-grid",
};
const tabsEle = reactive({
  scrollWidth: 0,
  scroViewllLeft: 0,
  tabsItems: [],
  scrollLeft: 0,
});

const popup = reactive({
  search: false,
  goodsDetail: false,
  data: {},
});
onHide(() => {
  uni.$off("is-socket-open");
  websocketUtil.offMessage();
});
onUnmounted(() => {
  uni.$off("is-socket-open");
  websocketUtil.offMessage();
});

function showDetail(goods) {
  changePop("goodsDetail", true, goods);
}
/**
 * socket消息监听
 */
function onMessage() {
  websocketUtil.offMessage();
  websocketUtil.onMessage(async (res) => {
    let msg = JSON.parse(res);
    let cartItem;
    let cartArr = [];
    if (msg.msg_id) {
      websocketUtil.send(
        JSON.stringify({
          type: "receipt",
          msg_id: msg.msg_id,
        })
      );
    }

    if (msg.status == 0 && msg.type != "time_discount") {
      infoBox.showToast(msg.msg || "添加失败");
      data.isGoodsAdd = true;
      // 如果是商品库存不足起售数量
      if (msg.type == "no_suit_num") {
        cartControls([], "del");
      }
      return;
    }
    if (msg.data) {
      cartArr = data.tabbar.reduce((prve, cur) => {
        prve = [...prve, ...cur.foods];
        return prve;
      }, []);
    }
    switch (msg.operate_type) {
      case "pad_init":
        cars.length = 0;
        if (!data.table.tableCode) {
          data.table.tableCode = msg.table_code;
          uni.setStorageSync("msg_id", msg.msg_id);
          data.limitTimeDiscount = limitTimeDiscountRes.value;
          websocketUtil.send(
            JSON.stringify({
              type: "shopping",
              operate_type: "time_discount_save",
              table_code: data.table.tableCode,
              shop_id: uni.getStorageSync("shopInfo").id,
              operate_type: "time_discount_save",
              data: data.limitTimeDiscount,
            })
          );
          // uni.setStorageSync("table_code", msg.table_code)
        }
        msg.data.map((item) => {
          cartItem = getNowCart(item, cartArr);
          if (cartItem.isGrounding || cartItem.is_temporary == 1) {
            cartControls(cartItem, "add");
          } else {
            delCart(cartItem.id);
          }
        });
        getHistoryOrderDetail();
        uni.hideLoading();
        break;
      case "pad_add":
      case "add":
        cartItem = getNowCart(msg.data, cartArr);
        cartControls(cartItem, "add");
        // infoBox.showToast('操作成功')
        break;
      case "pad_edit":
      case "edit":
        cartItem = getNowCart(msg.data, cartArr);
        cartControls(cartItem, "edit");
        // infoBox.showToast('操作成功')
        break;
      case "pad_del":
      case "del":
        cartItem = getNowCart(msg.data, cartArr);
        cartControls(cartItem, "del");
        break;
      case "pad_cleanup":
      case "cleanup":
        cars.length = 0;
        for (let i in data.tabbar) {
          for (let k in data.tabbar[i].foods) {
            data.tabbar[i].foods[k].chooseNumber = 0;
          }
        }
        getHistoryOrderDetail();
        break;
      case "init":
      case "rottable":
        if (data.table.tableCode == msg.table_code) {
          initCart();
        } else {
          data.table.tableCode = msg.table_code;
          let resData = await $returnTableDetail({
            tableCode: msg.table_code,
          });
          data.table = resData;
          initCart();
        }
        break;
      case "product_update":
        init();
        break;
      case "clearOrder":
        getHistoryOrderDetail();
        break;
    }
  });
}
/**
 * 删除购物车菜品
 */
function delCart(id) {
  let params = {
    ...data.socketData,
    id: id,
    operate_type: "del",
    table_code: data.table.tableCode,
  };
  console.log("购物车删除菜品参数===", params);
  websocketUtil.send(JSON.stringify(params));
}

/**
 * 获取订单详情
 */
async function getHistoryOrderDetail() {
  if (shopInfo.registerType == "before") {
    return;
  }
  data.historyOrder = [];
  let res = await getHistoryOrder({
    tableCode: data.table.tableCode,
  });
  if (!res.id) {
    return;
  }
  data.orderInfo = res;
  if (res) {
    data.historyOrder = Object.entries(data.orderInfo.detailMap).map(
      ([key, value]) => ({
        info: value,
        placeNum: key,
      })
    );
  }
}

/**
 * 初始化购物车
 */
function initCart() {
  let params = {
    ...data.socketData,
    operate_type: "init",
    table_code: data.table.tableCode || "",
  };
  // console.log("购物车初始化参数===", params)
  websocketUtil.send(JSON.stringify(params));
}

/**
 * 监听socket是否连接正常
 */
function watchSocketOpen() {
  uni.$off("is-socket-open");
  uni.$on("is-socket-open", (res) => {
    console.log(res, "wx断开后，执行的方法");
    lvhong.value = res;
    if (res) {
      data.isGoodsAdd = true;
      initCart();
    } else {
      uni.showLoading({
        title: "购物车加载中",
        mask: true,
      });
      data.isGoodsAdd = false;
    }
  });
}

/**
 * socket通知购物车商品数量修改处理
 */
function cartControls(cartItem, type) {
  if (!data.table.tableCode) {
    data.table.tableCode = cartItem.table_code;
  }
  data.isGoodsAdd = true;
  let cartIndex = 0;
  let product_id = cartItem.product_id;
  // console.log(cars, 'cars值，看id是否与cartItem匹配')
  cars.map((item, index) => {
    if (item.id == cartItem.id) {
      cartIndex = index;
      product_id = item.product_id;
      // sku_id = item.sku_id
    }
  });
  let $goods;
  console.log("layoutData.list", layoutData.list);
  console.log("type", type);
  console.log(cartItem, "cartItemid");
  console.log(product_id, "product_id");
  layoutData.list.forEach((ele) => {
    ele.productList.forEach((res) => {
      if (res.id == product_id) {
        $goods = res;
      }
    });
  });

  if (type == "del") {
    console.log("del", $goods);
    cars.splice(cartIndex, 1);
    if ($goods) $goods.chooseNumber = 0;
    return;
  }
  if (type == "add") {
    cars.push(cartItem);
    if ($goods) {
      $goods.chooseNumber = cartItem.number;
      console.log("$goods", $goods);
      console.log("cartItem", cartItem);
    }
  }
  if (type == "edit") {
    editItem.value = $goods;
    cars[cartIndex].number = cartItem.number;
    if ($goods) {
      $goods.chooseNumber = cartItem.number;
    }
  }
}

function changePop(key, show = true, data) {
  popup[key] = show;
  popup.data = data;
  if (!show) {
    data[key] = "";
    popup.data = {};
  }
}

const zhanweiStyle = reactive({
  style: "",
});
let safeBottom = ref(20);

function updateSafeBottom(e) {
  // safeBottom.value = e.height + 16
}
const computedSwiperItemStyle = computed(() => {
  return {
    "padding-bottom": safeBottom.value + "px",
  };
});

function tabsChange(e) {
  data.current = e.index;
}
const modal = reactive({
  login: false,
  key: "",
  clear: false,
  data: "",
});
let canXiadan = ref(false);
async function xiadanClick() {
  try {
    canXiadan.value = await hasPermission("允许下单");
  } catch (e) {
    modal.login = true;
    //TODO handle the exception
  }
}

function loginShow() {
  modal.login = true;
}

function loginShowOut() {
  uni.clearStorage();
  // go.to('PAGES_LOGIN')
  uni.redirectTo({
    url: "/pages/login/index",
  });
}

function loginSuccess() {
  data.noLogin = false;
  modal.login = false;
  init();
}

function skeletonClick() {
  // modal.login = true
  go.to("PAGES_LOGIN");
}

function scanCode() {
  // 只允许通过相机扫码
  console.log("scanCode");
  uni.scanCode({
    onlyFromCamera: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
    },
  });
}

function setTabBar(category, goods, carsC) {
  const goodsCategoryMap = goods.reduce((prve, cur) => {
    if (!prve.hasOwnProperty(cur.categoryId)) {
      prve[cur.categoryId] = [];
    }
    prve[cur.categoryId].push(cur);
    return prve;
  }, {});
  const chooseGoodsNumberMap = carsC.reduce((prve, cur) => {
    if (!prve.hasOwnProperty(cur.productId)) {
      prve[cur.productId] = 0;
    }
    prve[cur.productId] += cur.number;
    return prve;
  }, {});
  let tabbar = category.map((v) => {
    const foods = goodsCategoryMap[v.id] || [];
    return {
      ...v,
      foods: foods.map((fgoods, index) => {
        return {
          ...fgoods,
          chooseNumber: chooseGoodsNumberMap[fgoods.id],
          price: fgoods.lowPrice,
          isDan: fgoods.typeEnum !== "sku",
        };
      }),
    };
  });
  // tabbar.push({
  // 	name: '附加费',
  // 	foods: [{
  // 			name: "餐位费",
  // 			price:$shop.value.tableFee,
  // 			chooseNumber: 0,
  // 			isSeatFee:true,
  // 			isDan: true
  // 		}
  // 	]
  // })
  tabbar = tabbar.filter((v) => {
    return v.foods.length;
  });
  data.tabbar = tabbar;
  data.allGoods = tabbar.reduce((prve, cur) => {
    prve.push(cur.foods);
    return prve;
  }, []);
  // storageManage.cacheGoods(data.tabbar)
}

//request类
//获取分类
function getCategory(
  par = {
    page: 1,
    size: 300,
  }
) {
  return $tbShopCategory(par);
}
//获取商品列表
function getGoods(
  par = {
    page: 0,
    size: 300,
  }
) {
  return Api.getGoodsLists(par);
}

function objectToString(obj) {
  let result = "";
  for (const key in obj) {
    if (obj.hasOwnProperty(key)) {
      result += `${key}=${obj[key]}&`;
    }
  }
  // 去掉最后一个多余的 &
  return result.slice(0, -1);
}

//获取购物车数据
async function getCart() {
  let par = {
    type: "pad",
    account: uni.getStorageSync("shopInfo").id,
    operate_type: "init",
    table_code: uni.getStorageSync("wxInit").table_code || "",
    shop_id: uni.getStorageSync("shopInfo").id,
  };
  websocketUtil.send(JSON.stringify(par));
}
//获取取餐码
async function getMasterId() {
  const res = await Api.$getMasterId({
    tableId: data.table.tableId,
  });
  data.masterId = res.masterId;
  return res;
}

//更新购物车
function updateCartGoods(par) {
  const submitPar = {
    cartId: "",
    masterId: data.masterId,
    tableId: data.table.tableId,
    isPack: false,
    num: 1,
    productId: "",
    skuId: "",
    vipUserId: data.vipUser.id,
  };
  Object.assign(submitPar, par);
  return Api.$updateCart(submitPar);
}
//删除购物车某商品
function removeCartGoods(par) {
  const submitPar = {
    cartId: "",
    masterId: data.masterId,
    tableId: data.table.tableId,
  };
  Object.assign(submitPar, par);
  return Api.$removeCart(submitPar);
}
//更新选择用户
function setUser(par) {
  const submitPar = {
    masterId: data.masterId,
    tableId: data.table.tableId,
    vipUserId: data.vipUser.id ? data.vipUser.id : "",
    type: data.vipUser.id ? 0 : 1, //0 设置 1 取消
  };
  Object.assign(submitPar, par);
  return Api.$setUser(submitPar);
}

/**
 * 清除购物车
 */
async function cleaCart(e) {
  if (e == "cart") {
    let params = {
      ...data.socketData,
      operate_type: "cleanup",
      table_code: data.table.tableCode,
    };
    console.log("购物车清空菜品参数===", params);
    websocketUtil.send(JSON.stringify(params));
  } else if (e == "allHistoryOrder") {
    await cancelOrder({
      orderId: data.orderInfo.id,
      shopId: uni.getStorageSync("shopId"),
    });
    let params = {
      ...data.socketData,
      operate_type: "cleanup",
      table_code: data.table.tableCode,
    };
    websocketUtil.send(JSON.stringify(params));
    initCart();
  } else {
    // await rmPlaceOrder({
    // 	orderId: data.orderInfo.id||'',
    // 	placeNum: e||'',
    // 	shopId: uni.getStorageSync("shopId")
    // })
    let params = {
      ...data.socketData,
      operate_type: "cleanup",
      table_code: data.table.tableCode,
    };
    websocketUtil.send(JSON.stringify(params));
    initCart();
  }
  onClearCart();
}
//点击清空购物车
async function onClearCart() {
  cars.length = 0;
  for (let i in layoutData.list) {
    for (let k in layoutData.list[i].productList) {
      layoutData.list[i].productList[k].chooseNumber = 0;
    }
  }
}

let $originGoods = [];
let $category = [];
const layoutData = reactive({
  category: {
    list: [],
    sel: 0,
    selData: {
      page: 0,
      totalElements: 0,
    },
  },
  current: 0,
  nowData: {},
  list: [],
  prvePage: {
    padLayoutCode: "",
    productList: [],
  },
  currentPage: {
    padLayoutCode: "",
    productList: [],
  },
  nextPage: {
    padLayoutCode: "",
    productList: [],
  },
  query: {
    page: 1,
    size: 10,
    productCategoryId: "",
    padLayoutId: "",
  },
});
let isTapChangeCategorySel = false;
let isScrollChangeCategorySel = false;

function changeCategorySel(index) {
  layoutData.category.sel = index;
  setTabsCurrentPosition();
  isTapChangeCategorySel = true;
}

function setTabsCurrentPosition(position = "center") {
  const index = layoutData.category.sel;
  console.log(tabsEle.tabsItems[index]);
  console.log(tabsEle.scroViewllLeft);
  tabsEle.scrollLeft =
    tabsEle.tabsItems[index].left -
    tabsEle.scrollWidth / 2 +
    tabsEle.tabsItems[index].width / 2 -
    tabsEle.scroViewllLeft;
}
const shopInfo = uni.getStorageSync("shopInfo");

provide("shopInfo", shopInfo);
/**
 * 获取商品列表
 * @param max
 * @param isGetPrve
 */
async function getGoodsData(max = 6, isGetPrve = false) {
  const fuhao = !isGetPrve ? 1 : -1;
  for (let i = 0; i < max; i++) {
    if (layoutData.current + i > layoutData.list.length - 1) {
      break;
    } else {
      const pageData = layoutData.list[layoutData.current + i * fuhao];
      if (pageData && pageData.id && !pageData.hasAjax) {
        try {
          const res2 = await $productCategory(pageData.id);
          layoutData.list[layoutData.current + i * fuhao] = {
            ...res2,
            padLayoutCode: res2.padLayoutCode
              ? res2.padLayoutCode
              : res2.productList.length <= 4
              ? layoutArr[res2.productList.length]
              : "6-grid",
            productList: res2.productList.map((v) => {
              v.salePrice = v.lowPrice;
              const findGoodsInCar = cars.find((cars) => {
                return cars.productId == v.id;
              });
              if (findGoodsInCar) {
                return {
                  ...v,
                  chooseNumber: findGoodsInCar.number,
                };
              } else {
                return v;
              }
            }),
            hasAjax: true,
          };
        } catch (e) {
          layoutData.list[layoutData.current + i * fuhao].hasAjax = false;
          //TODO handle the exception
        }
      }
    }
  }
}
async function getLayoutGoodsInit(max = 6, isGetPrve = false) {
  await getGoodsData(max, isGetPrve);
  if (isGetPrve) {
    await getGoodsData(max, isGetPrve);
  }
}

function animationStart(e) {
  isScrollChangeCategorySel = true;
}
async function animationfinish(e) {
  if (isScrollChangeCategorySel) {
    try {
      layoutData.current = e.detail.current;
      const categoryId = layoutData.list[layoutData.current].productCategoryId
        ? layoutData.list[layoutData.current].productCategoryId
        : layoutData.list[layoutData.current].productList[0].categoryId;
      const index = layoutData.category.list.findIndex(
        (v) => v.id == categoryId
      );
      isScrollChangeCategorySel = true;
      layoutData.category.sel = index;
      await getLayoutGoodsInit();
    } catch (error) {}
  }
  isScrollChangeCategorySel = false;
  isTapChangeCategorySel = false;
}
/**
 * 添加套餐
 * @param {Object} d
 * @param {Object} item
 */
async function taocanConfirm(d, item) {
  const is_time_discount = yskUtils.limitUtils.canUseLimitTimeDiscount(
    {
      ...item,
      salePrice: item.lowPrice,
      memberPrice: item.memberPrice
        ? item.memberPrice
        : item.skuList[0].memberPrice,
    },
    data.limitTimeDiscount,
    shopInfo,
    null,
    "id"
  )
    ? 1
    : 0;
  editCart(
    {
      number: item.skuList[0].suitNum,
      product_id: item.id,
      product_type: item.type,
      sku_id: item.skuList[0].id,
      pro_group_info: JSON.stringify(d),
      is_temporary: 0, //是否是临时菜
      is_time_discount,
    },
    "add"
  );
  data.isGoodsAdd = false;
}
// 获取标题区域宽度，和每个子元素节点的宽度以及元素距离左边栏的距离
async function init() {
  if (option.type == "add") {
    setTabBar($category, $originGoods, []);
  }
  let shopInfo = await getShopInfo({
    id: uni.getStorageSync("shopInfo").id,
  });
  uni.setStorageSync("shopInfo", shopInfo);
  // 获取布局
  // const getLayoutData = await getLayout({})
  // 获取分类数据-获取商品分类
  const categoryRes = await getCategory();
  $category = categoryRes;

  let arr = [];
  for (let i = 0; i < $category.length; i++) {
    const res = await $layoutpage({
      page: 1,
      size: 999,
      productCategoryId: $category[i].id,
      padLayoutId: "",
    });
    // res.data.records = res.data.records.map(v => {
    // 	return {
    // 		...v,
    // 		hasAjax: false
    // 	}
    // })
    const content =
      res.records.length > 0
        ? res.records
        : [
            {
              productCategoryId: $category[i].id,
              padLayoutCode: "single",
              productList: [],
            },
          ];
    // const content = res.data.records.length > 0 ? res.data.records : [{
    // 	productCategoryId: $category[i].id,
    // 	padLayoutCode: "single",
    // 	productList: []
    // }];
    $category[i].startIndex = arr.length;
    for (let i of content) {
      arr.push(i);
    }

    $category[i].endIndex = arr.length + content.length - 2;
  }
  layoutData.category.list = $category;
  layoutData.list = arr;
  nextTick(() => {
    categoryEleInit();
  });
  getLayoutGoodsInit();
  // 获取商品数据
  const goodsRes = await getGoods();
  const goods = goodsRes.filter((v) => {
    let isShow = true;
    if (v.type != "sku") {
      isShow = v.skuList.length >= 1;
    }
    return isShow;
  });
  $originGoods = goods;
  if (option.type == "add") {
    cars.length = 0;
    initCart();
    setTabBar($category, goods, []);
    return;
  }
  setTabBar($category, goods, cars);
  initCart();
}

function categoryEleInit() {
  getElRect("content-scroll", instance.value, {
    rect: true,
  }).then((res) => {
    tabsEle.scrollWidth = res.width;
    tabsEle.scroViewllLeft = res.left;
  });
  for (let i in layoutData.category.list) {
    getElRect("u-tab-item" + i, instance.value, {
      rect: true,
    }).then((res) => {
      console.log(res);
      tabsEle.tabsItems[i] = {
        width: res.width,
        left: res.left,
      };
    });
  }
}
// 监听选择用户事件
const surcharge = ref(null);

function surchargeConfirm(e) {
  data.tabbar[data.tabbar.length - 1].foods.unshift({
    ...e,
    chooseNumber: 0,
  });
}

function surchargeShow() {
  surcharge.value.open();
}

let searchValue = ref("");
let isSearch = ref(false);
let searchResult = ref([]);

function chunkArray(array, chunkSize) {
  let result = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    result.push(array.slice(i, i + chunkSize));
  }
  return result;
}

function formatSearchGoods(arr) {
  const len = arr.length;

  const result = chunkArray(arr, 6);
  console.log(result);
  return result.map((v) => {
    return {
      productList: v,
      padLayoutCode: v.length <= 4 ? layoutArr[v.length] : "6-grid",
    };
  });
}

function returnSearchGoods() {
  const newval = searchValue.value;
  let arr = [];
  let goods = [];
  for (let i in layoutData.list) {
    const goodsArr = layoutData.list[i].productList || [];
    for (let k in goodsArr) {
      goods.push({
        ...goodsArr[k],
        index: i,
        goodsIndex: k,
      });
    }
  }
  if (newval == "") {
    arr = formatSearchGoods(goods);
  } else {
    const filterArr = goods.filter((v) => v.name.includes(newval.trim()));
    console.log(filterArr);
    arr = formatSearchGoods(filterArr);
  }
  return arr;
}

function search(e) {
  searchValue.value = e;
  console.log(searchResult.value);
  if (searchValue.value === "") {
    isSearch.value = false;
    return;
  }
  isSearch.value = true;
  searchResult.value = returnSearchGoods();
}

function clearSearch() {
  isSearch.value = false;
}

function chooseUser() {
  go.to("PAGES_CHOOSE_USER");
}

function chooseTable() {
  // changeCategorySel(1)
  // setTimeout(() => {
  // 	changeCategorySel(0)
  // }, 500)

  go.to("PAGES_INDEX_CHOOSE_TABLE");
  // go.to("PAGES_CHOOSE_TABLE", {
  //   ...data.table,
  // });
}

async function confirmModelConfirm(isCancel = false) {
  if (modal.key == "clear") {
    try {
      await $choseTable({
        masterId: data.masterId,
        tableId: modal.data.tableId,
        isClear: !isCancel ? true : false,
      });
    } catch (e) {
      console.log(e);
      //TODO handle the exception
    }
    data.table = modal.data;
    setModalShow("clear", false, "");
  }
}

function resetTable() {
  data.table = {
    tableId: "",
  };
  uni.removeStorageSync("table_code");
}

function setModalShow(key = "show", show = true, data) {
  modal.key = key;
  modal[key] = show;
  modal.data = data;
}
// 选择桌台完成
function watchChooseTable() {
  uni.$off("choose-table");
  uni.$on("choose-table", async (item) => {
    onChooseTable(item);
    // if (data.table.tableId || cars.length <= 0) {
    // 	data.table = item
    // 	return;
    // }
    // if (item.status != "idle") {
    // 	return infoBox.showToast('该台桌已在使用中')
    // }
    // const res = await $returnTableDetail({
    // 	tableId: item.tableId,
    // });
    // if (res.cartCount > 0) {
    // 	setModalShow('clear', true, item)
    // } else {
    // 	await $choseTable({
    // 		masterId: data.masterId,
    // 		tableId: item.tableId,
    // 		isClear: false
    // 	});
    // 	data.table = item
    // }
  });
}
/**
 * 选择桌台完成
 */
async function onChooseTable(item) {
  if (!item) {
    infoBox.showToast("桌台不存在或不是该店铺的桌台");
    return;
  }
  console.log("---table:detail-----", item);
  console.log("---table_code-----", data.table.tableCode);
  console.log("---new_table_code-----", item.tableCode);
  let params = {
    ...data.socketData,
    operate_type: "rottable",
    table_code: data.table.tableCode,
    // new_table_code: item.tableCode,
  };
  data.table = item;
  // uni.setStorageSync('tableCode', item.tableCode)
  // websocketUtil.send(JSON.stringify(params))
  initCart();
  // return
  // if (cars.length <= 0) {
  // 	data.table = {
  // 		...item
  // 	}
  // 	if (cars.length > 0) {
  // 		websocketUtil.send(JSON.stringify(params))
  // 	} else {
  // 		initCart()
  // 	}
  // 	return;
  // }

  // if (item.status == "unbind") {
  // 	return infoBox.showToast('该台桌未绑定，清先去桌台管理里绑定码牌')
  // }
  // if (item.status != "idle") {
  // 	return infoBox.showToast('该台桌已在使用中')
  // }
  // data.table = item
  // if (cars.length > 0) {
  // 	websocketUtil.send(JSON.stringify(params))
  // }
}

function toLinshi() {
  go.to("PAGES_ADD_TEMP_CUISINE");
}

const chooseGuigeModel = ref(null);
const guigeModelData = reactive({
  title: "",
  chooseGoods: {
    skuMap: {},
    item: "",
    skus: [],
  },
});

// 返回当前选中商品skuList
function returnSelGoodsSkuList(skuList, specSnap) {
  // const specSnapArr = specSnap ? specSnap.split(",") : [];
  let result = [];
  for (let v in skuList) {
    let obj = {
      name: v,
      sel: skuList[v][0],
      value: skuList[v].join(","),
      valueArr: skuList[v],
      values: valuesfilter(skuList[v]),
    };
    result.push(obj);
  }

  return result;
}
// 添加baluearr
function valuesfilter(d) {
  let arr = [];
  d.forEach((ele) => {
    let obj = {
      name: ele,
      disabled: false,
    };
    arr.push(obj);
  });
  return arr;
}
//返回当前选中商品skuMap
function returnSelGoodsSkuMap(specList) {
  const skuMap = {};
  for (let i in specList) {
    skuMap[specList[i].specInfo] = specList[i];
  }
  return skuMap;
}

//多规格商品弹窗时，找到默认可以下单的规格商品
function findGoods(skuList = [], goodsListMap = {}, specList) {
  const skuMapNumber = skuList.reduce((prve, cur) => {
    for (let i in cur.valueArr) {
      prve[cur.valueArr[i]] = i;
    }
    return prve;
  }, {});
  const canBudyGoods = specList
    .filter((v) => util.isCanBuy(v))
    .sort((a, b) => {
      // const aNumber = a.specSnap.split(",").reduce((prve, cur) => {
      // 	return prve + skuMapNumber[cur];
      // }, 0);
      // const bNumber = b.specSnap.split(",").reduce((prve, cur) => {
      // 	return prve + skuMapNumber[cur];
      // }, 0);
      // return aNumber - bNumber;
    });
  return canBudyGoods[0];
}

//设置商品默认选中,规格禁止以及选中
function setSkugoodsDefaultInit(goods, skuList, skuMap, specList) {
  guigeModelData.chooseGoods.item = goods;
  guigeModelData.chooseGoods.skus = skuList;
  guigeModelData.chooseGoods.skuMap = skuMap;
  const skuGoods = findGoods(skuList, skuMap, specList);
  if (skuGoods) {
    // this.skuGoods.data = skuGoods;
    // this.skuGoods.number = skuGoods.suit || 1;
    // skuGoods.specSnap.split(",").map((v, index) => {
    // 	guigeModelData.chooseGoods.skus[index].sel = v;
    // });
  }
  console.log(guigeModelData.chooseGoods.skus);
  // setTagDisabled();
}

//更新选中规格
function updateSkuSel(skusIndex, skdName) {
  const skuList = guigeModelData.chooseGoods.skus;
  const skuMap = guigeModelData.chooseGoods.skuMap;
  guigeModelData.chooseGoods.skus[skusIndex].sel = skdName;
  const specSnap = guigeModelData.chooseGoods.skus
    .reduce((prve, cur) => {
      prve.push(cur.sel);
      return prve;
    }, [])
    .join();
  setTagDisabled();
  // const canChooseGoods = skuList.every((v) => v.sel);
  // if (canChooseGoods) {
  // 	const skuGoods =skuMap[specSnap];
  // 	guigeModelData.chooseGoods.item = skuGoods
  // }
}
//设置规格按钮的禁止状态
function setTagDisabled() {
  const skuList = guigeModelData.chooseGoods.skus;
  const skuMap = guigeModelData.chooseGoods.skuMap;
  const selArr = skuList.reduce((prve, cur) => {
    if (cur.sel) {
      prve.push(cur.sel);
    } else {
    }
    return prve;
  }, []);

  console.log(selArr);
  let selArrAllGroup = util.generateCombinations(selArr, selArr.length - 1);
  console.log("selArrAllGroup");
  console.log(selArrAllGroup);
  const matchArr = [];
  for (let key in skuMap) {
    const goods = skuMap[key];
    const keyArr = key.split(",");
    for (let spe of selArrAllGroup) {
      if (util.arrayContainsAll(keyArr, spe)) {
        matchArr.push(goods);
        break;
      }
    }
  }
  //全部规格都已下架
  if (!matchArr.length) {
    for (let k in skuList) {
      for (let i in skuList[k].values) {
        skuList[k].values[i].disabled = true;
      }
    }
    return;
  }
  const includeSkuMap = matchArr.reduce((prve, cur) => {
    console.log("cur.specSnap", cur);
    const speArr = cur.specSnap.split(",");
    for (let i of speArr) {
      if (!prve.hasOwnProperty("i")) {
        prve[i] = matchArr
          .filter((v) => v.specSnap.match(i))
          .every((v) => {
            return !util.isCanBuy(v);
          });
      }
    }
    return prve;
  }, {});
  for (let i in includeSkuMap) {
    for (let k in skuList) {
      const index = skuList[k].valueArr.findIndex((val) => val === i);
      if (index !== -1) {
        skuList[k].values[index].disabled = includeSkuMap[i];
      }
    }
  }
}

let selGoods = ref({});
const taocanModelRef = ref();

function chooseGuige(foodsindex, index) {
  const $goods = layoutData.list[foodsindex].productList[index];
  selGoods.value = $goods;
  if ($goods.groupType == 1) {
    data.goodsData = $goods;
    taocanModelRef.value.open();
  } else {
    guigeModelData.title = $goods.name;
    const tagSnap = JSON.parse($goods.selectSpecInfo);
    const skuMap = returnSelGoodsSkuMap($goods.skuList);
    // 多规格,和套餐规格区分.groupType=1 套餐多规格
    const selectSpecInfo = returnSelGoodsSkuList(tagSnap);
    setSkugoodsDefaultInit($goods, selectSpecInfo, skuMap, $goods.skuList);
    chooseGuigeModel.value.open();
  }
}

async function guigeConfirm(sku, number, is_time_discount) {
  if (!data.isGoodsAdd) {
    return;
  }
  let goods = guigeModelData.chooseGoods.item;
  let sku_id = sku.id;
  let product_id = goods.id;
  let product_type = goods.type;
  let res = findGoodsInCar(goods, sku_id);

  if (res) {
    //更新
    let { index } = res;
    let carGoods = cars[index];
    let cartId = carGoods.id;
    let newNumber = carGoods.number * 1 + suitNum;
    let suitNum = goods.skuList[0].suitNum || 1;
    editCart(
      {
        suitNum,
        id: cartId,
        number: newNumber,
        product_id: product_id,
        sku_id: sku_id,
        is_temporary: carGoods.is_temporary, //是否是临时菜
        is_time_discount,
      },
      "edit"
    );
    data.isGoodsAdd = false;
  } else {
    //添加
    editCart(
      {
        number: number,
        product_id: product_id,
        product_type: product_type,
        sku_id: sku_id,
        is_temporary: 0, //是否是临时菜
        is_time_discount,
      },
      "add"
    );
    data.isGoodsAdd = false;
  }
}
/**
 * 购物车添加菜品
 */
function editCart(par, operate_type) {
  if (!data.isGoodsAdd) {
    return;
  }
  let params = {
    ...data.socketData,
    operate_type: operate_type,
    table_code: data.table.tableCode,
    product_id: "",
    is_print: 1,
    sku_id: "", //
    number: 1, //数量
  };
  Object.assign(params, par);
  console.log("购物车添加菜品参数===", params);
  websocketUtil.send(JSON.stringify(params));
  data.isGoodsAdd = false;
}
const $cacheGoods = {};

//修改购物车商品备注
function updateCartRemark(e) {
  let { remark, index, goods } = e;
  cars[index].note = remark;
  let params = {
    number: e.num,
    id: e.goods.id,
    product_id: e.goods.product_id,
    sku_id: e.goods.sku_id,
    is_temporary: e.goods.is_temporary,
    remark: remark,
  };
  editCart(params, "edit");
}

//购物车商品数量改变
async function carsNumberChange(e) {
  if (!data.isGoodsAdd) {
    return;
  }
  let $sku;
  let $goods;
  let params = {
    number: e.num,
    id: e.goods.id,
    product_id: e.goods.product_id,
    sku_id: e.goods.sku_id,
    is_temporary: e.goods.is_temporary,
  };
  if (e.goods.is_temporary != 1) {
    data.tabbar.map((tabbarItem) => {
      if (tabbarItem.foods.find((v) => v.id == e.goods.product_id)) {
        $goods = !e.goods.product_id
          ? undefined
          : tabbarItem.foods.find((v) => v.id == e.goods.product_id);
      }
    });
    if ($goods.type != "package") {
      //临时菜没有skuList
      $sku = !e.goods.product_id
        ? {
            suitNum: 1,
          }
        : $goods.skuList.find((v) => v.productId == e.goods.product_id);
    } else {
      $sku = !e.goods.product_id
        ? {
            suitNum: 1,
          }
        : $goods.skuList.find((v) => v.productId == e.goods.product_id);
    }
    if (e.num === 0 || e.num < $sku.suitNum) {
      //移除
      delCart(e.goods.id);
      return;
    }
  } else {
    if (e.num === 0) {
      //移除
      console.log(e.goods, "溢出购物车");
      delCart(e.goods.id);
      return;
    }
    params.product_name = e.goods.name;
    params.sku_name = e.goods.sku_name;
  }
  let suitNum = $goods.skuList[0].suitNum || 1;
  params.suitNum = suitNum;
  editCart(params, "edit");
  data.isGoodsAdd = false;
}

// 找到该规格商品在购物车中是否存在并返回index值以及对应的数据
function findGoodsInCar($goods, skuId) {
  const productId = $goods.id;
  const goodsInCarIndex = cars.findIndex((carsGoods) => {
    return carsGoods.skuId == skuId && carsGoods.productId == productId;
  });
  const carGoods = cars[goodsInCarIndex];
  return carGoods
    ? {
        index: goodsInCarIndex,
        carGoods,
      }
    : false;
}

function searchGoodsUpdate(goodsItem, goodsIndex, isAdd) {
  goodsUpdate(goodsItem.goodsIndex, goodsItem.index, isAdd, goodsIndex);
}

function setSearchGoods(index, chooseNumber) {
  if (index !== undefined) {
    console.log(searchResult.value[index]);
    searchResult.value[index].chooseNumber = chooseNumber;
  }
}
async function goodsUpdate(
  foodsindex,
  index,
  isAdd,
  searchGoodsIndex,
  showCurrentInput,
  is_time_discount
) {
  console.log(foodsindex, index, isAdd, searchGoodsIndex, "11111");
  if (!data.isGoodsAdd) {
    return;
  }
  const $goods = layoutData.list[foodsindex].productList[index];
  console.log($goods);
  if (is_time_discount === undefined) {
    is_time_discount = yskUtils.limitUtils.canUseLimitTimeDiscount(
      { ...$goods, salePrice: $goods.lowPrice },
      data.limitTimeDiscount,
      shopInfo,
      null,
      "id"
    )
      ? 1
      : 0;
  }

  if ($goods.type != "sku") {
    const step = isAdd ? 1 : -1;
    //增加
    let isShop = cars.find((ele) => ele.product_id == $goods.id);
    if (isShop) {
      let { sku_id, product_id, id, number, discount_sale_amount } = isShop;
      // 数量加减
      let num = number + step;
      if (num == 0 || num < $goods.skuList[0].suitNum) {
        let params = {
          ...data.socketData,
          id: id,
          table_code: uni.getStorageSync("wxInit").table_code || "",
          operate_type: "del",
        };
        websocketUtil.send(JSON.stringify(params));
        $goods.chooseNumber = num;
      } else {
        let suitNum = $goods.skuList[0].suitNum || 1;
        if (showCurrentInput) {
          //单规格
          let goodsInCarIndex = cars.findIndex((carsGoods) => {
            return carsGoods.product_id == $goods.skuList[0].productId;
          });
          let cartItem = cars[goodsInCarIndex];
          num = cartItem.number * 1 + Number(showCurrentInput);
        }

        websocketUtil.send(
          JSON.stringify({
            ...data.socketData,
            discount_sale_amount,
            suitNum: suitNum,
            number: num,
            id,
            product_id,
            sku_id: sku_id,
            table_code: uni.getStorageSync("wxInit").table_code,
            sku_name: "", // 临时菜规格
            operate_type: "edit",
            pack_number: 0, //数量
            is_temporary: 0, //是否是临时菜
            is_time_discount,
          })
        );

        // $goods.chooseNumber = 1
        $goods.chooseNumber = num;
      }
    } else {
      // 起售数量
      let suitNum = $goods.skuList[0].suitNum || 1;
      console.log(suitNum, "起售数量");
      // showCurrentInput有值是称重
      let weightNum = suitNum;
      if (showCurrentInput) {
        weightNum = Number(showCurrentInput);
      }

      let params = {
        ...data.socketData,
        table_code: data.table.tableCode,
        operate_type: "add",
        product_id: $goods.id,
        sku_id: $goods.skuList[0].id,
        sku_name: "", // 临时菜规格
        number: weightNum,
        // discount_sale_amount: $goods.lowPrice,
        discount_sale_amount: 0,
        pack_number: 0, //数量
        is_temporary: 0, //是否是临时菜
        is_time_discount,
      };
      console.log(params, "发送消息");
      websocketUtil.send(JSON.stringify(params));
      // $goods.chooseNumber = 1
    }
  }
}

let isTabClickOver = true;
// 点击左边的栏目切换
async function swichMenu(index) {
  data.current = index;
}

function watchChooseuser() {
  uni.$off("choose-user");
  uni.$on("choose-user", (user) => {
    data.vipUser = user
      ? user
      : {
          id: "",
        };
    setUser();
  });
}
watch(
  () => data.table.tableId,
  (newval, oldval) => {
    // onSelTable()
  }
);
watch(
  () => layoutData.category.sel,
  (newval, oldval) => {
    setTabsCurrentPosition();
    if (!isScrollChangeCategorySel) {
      layoutData.current = layoutData.category.list[newval].startIndex;
      getLayoutGoodsInit(6, true);
    }
  }
);
async function getLayoutGoods(isAdd) {}
async function onSelTable() {
  const { masterId } = await getMasterId();
  data.masterId = masterId;
  const cartRes = await getCart();
  cars.length = 0;
  const cartArr = getNowCart(cartRes);
  for (let i in cartArr) {
    cars.push(cartArr[i]);
  }
  setTabBar($category, $originGoods, cars);
}
onBeforeUnmount(() => {});

function watchUpdate() {
  uni.$off("update:createOrderIndex");
  uni.$off("get:table");
  uni.$on("update:createOrderIndex", () => {
    // data.table = {
    // 	tableId: ""
    // }
    cars.length = 0;
    init();
  });
  // 添加临时菜到购物车
  uni.$on("add:cashCai", async (data) => {
    $originGoods.push(data);
    data.isGoodsAdd = false;
  });
}
onShow(() => {
  let shopif = uni.getStorageSync("shopInfo");
  if (shopif) {
    if (shopif.code) {
      data.userInfo = shopif.data;
    } else {
      data.userInfo = shopif;
    }
  }
  // 判断是否token过期,是否有名字
  if (!data.userInfo.shopName) {
    loginShowOut();
  }
  nextTick(() => {
    uni.showLoading({
      title: "购物车加载中",
      mask: true,
    });
    // layoutData.current = 0;
    watchChooseTable();
    watchUpdate();
    watchSocketOpen();
    data.isGoodsAdd = true;
    init();
    onMessage();
    uni.hideLoading();
  });
});
let isCreateOrderToDetail = ref(false);
// let option = {
// 	type: ''
// }

let sysInfo = ref({
  windowWidth: 0,
  windowHeight: 0,
});
const limitTimeDiscountRes = ref(null);
async function getLimit() {
  const res = await limitTimeDiscountApi.limitTimeDiscount();
  limitTimeDiscountRes.value = res;
  if (data.table.tableCode) {
    data.limitTimeDiscount = limitTimeDiscountRes.value;

    websocketUtil.send(
      JSON.stringify({
        type: "shopping",
        operate_type: "time_discount_save",
        table_code: data.table.tableCode,
        shop_id: uni.getStorageSync("shopInfo").id,
        operate_type: "time_discount_save",
        data: limitTimeDiscountRes.value,
      })
    );
    console.log("limitTimeDiscount", data.limitTimeDiscount);
  }
}

async function getTableDetail() {
  let res = await $returnTableDetail({
    tableCode: data.table.tableCode,
  });
  console.log(res, "getTableDetail");
  if (res && res.tableCode) {
    data.table = res;
  }
}
onLoad(async (opt) => {
  sysInfo.value = uni.getSystemInfoSync();
  uni.hideTabBar();
  // option = opt
  Object.assign(data.table, opt);
  await getTableDetail();
  await getLimit();
  if (opt.useType) {
    uni.setStorageSync("useType", opt.useType);
  }
  if (JSON.stringify(opt) == "{}") {
    isCreateOrderToDetail.value = true;
  }

  websocketUtil.initializeWebSocket();

  xiadanClick();
});
</script>

<style lang="scss" scoped>
.choose-user {
  background: #f9f9f9;
  padding: 22rpx 28rpx;
}

.top {
  position: fixed;
  background-color: #fff;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
  min-height: 40px;
  padding-top: calc(var(--status-bar-height));
  padding-bottom: 6px;
  z-index: 5;
}

.top {
  .search-box {
    // position: absolute;
    // right: 0;
    // top: 0;
    // bottom: 0;
    padding-right: 58rpx;
    background-color: #fff;
    white-space: nowrap;
  }
}

.swiper-item-box {
  height: 100%;
  box-sizing: border-box;
  padding-bottom: 20px;
  padding-left: 20px;
  padding-right: 20px;
  padding-top: calc(var(--status-bar-height) + 40px + 16px);
}

.search {
  padding-right: 28rpx;
}

.icon-saoma {
  margin-left: 20rpx;
  width: 34rpx;
  height: 32rpx;
}

$u-tips-color: $my-main-color;
$u-primary: $my-main-color;
$u-main-color: $my-main-color;

.u-wrap {
  display: flex;
  flex-direction: column;
}

.headeimg {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  background-color: #eee;
  border-radius: 12rpx;
  overflow: hidden;

  .img {
    width: 60rpx;
    height: 60rpx;
  }
}

.u-menu-wrap {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.u-search-inner {
  // background-color: rgb(234, 234, 234);
  background-color: #fff;
  border-radius: 100rpx;
  display: flex;
  align-items: center;
  padding: 10rpx 16rpx;
}

.u-search-text {
  font-size: 26rpx;
  color: $u-tips-color;
  margin-left: 10rpx;
}

.u-tab-view {
  width: 100%;
  background-color: #fff;
}

.u-tab-item {
  padding: 28rpx 20rpx;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #444;
  font-weight: 400;
  line-height: 1;
  margin-right: 56rpx;
}

.u-tab-item-active {
  position: relative;
  color: $my-main-color;
  font-size: 16px;
  background: #fff;
}

.u-tab-item-active::before {
  content: "";
  display: block;
  position: absolute;
  border-bottom: 2px solid $my-main-color;
  left: 4px;
  right: 4px;
  bottom: 0;
}

.addCai {
  width: 250rpx;
  height: 272rpx;
  border-radius: 8rpx 8rpx 8rpx 8rpx;
  box-sizing: border-box;
  border: 4rpx solid #90bdf6;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.lingshi {
  width: 250rpx;
  height: 136px;
  background: #ffffff;
  border-radius: 8rpx 8rpx 8rpx 8rpx;
  border: 4rpx solid #90bdf6;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

::v-deep .uni-searchbar {
  padding-top: 12px !important;
  padding-bottom: 16px !important;
}

.right-box {
  width: 572rpx;
  // background-color: rgb(250, 250, 250);
  background-color: rgb(255, 255, 255);
}

.page-view {
  // padding: 24rpx 28rpx 24rpx 24rpx;
}

.class-item {
  margin-bottom: 30rpx;
  background-color: #fff;
  border-radius: 8rpx;
}

.class-item:last-child {
  min-height: 50vh;
}

.item-title {
  font-size: 26rpx;
  font-weight: bold;

  &.active {
    color: $my-main-color;
  }
}

.item-menu-name {
  font-weight: normal;
  font-size: 24rpx;
  color: $u-main-color;
}

.item-container {
  // display: flex;
  // flex-direction: row;
  // justify-content: center;
  // align-items: center;
  // flex-wrap: wrap;
  width: 100%;

  &.layout-single {
    width: 100%;
    height: 100%;

    .div1 {
      width: 100%;
      height: 100%;
    }
  }

  &.layout-double {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: 1fr;
    grid-column-gap: 20px;
    grid-row-gap: 20px;

    .div1 {
      grid-area: 1 / 1 / 2 / 2;
    }

    .div2 {
      grid-area: 1 / 2 / 2 / 3;
    }
  }

  &.layout-L1-R2 {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
    grid-column-gap: 10px;
    grid-row-gap: 10px;

    .div1 {
      grid-area: 1 / 1 / 3 / 2;
    }

    .div2 {
      grid-area: 1 / 2 / 2 / 3;
    }

    .div3 {
      grid-area: 2 / 2 / 3 / 3;
    }
  }

  &.layout-4-gird {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-template-rows: repeat(2, 1fr);
    grid-column-gap: 20px;
    grid-row-gap: 20px;

    .div1 {
      grid-area: 1 / 1 / 2 / 2;
    }

    .div2 {
      grid-area: 1 / 2 / 2 / 3;
    }

    .div3 {
      grid-area: 2 / 1 / 3 / 2;
    }

    .div4 {
      grid-area: 2 / 2 / 3 / 3;
    }
  }

  &.layout-6-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(2, 1fr);
    grid-column-gap: 20px;
    grid-row-gap: 20px;

    .div1 {
      grid-area: 1 / 1 / 2 / 2;
    }

    .div2 {
      grid-area: 1 / 2 / 2 / 3;
    }

    .div3 {
      grid-area: 1 / 3 / 2 / 4;
    }

    .div4 {
      grid-area: 2 / 3 / 3 / 4;
    }

    .div5 {
      grid-area: 2 / 2 / 3 / 3;
    }

    .div6 {
      grid-area: 2 / 1 / 3 / 2;
    }
  }
}

.thumb-box {
}

.item-menu-image {
  width: 120rpx;
  height: 120rpx;
}

.lvstyle,
.hongstyle {
  width: 10px;
  height: 10px;
  border-radius: 50%;
}

.lvstyle {
  background-color: green;
}

.hongstyle {
  background-color: red;
}
</style>
