<template>
  <view class="page-gray color-333 u-font-28">
    <template v-if="true">
      <view
        class="block u-p-t-32 u-p-b-32"
        v-if="pageData.table && pageData.table.id"
      >
        <view>桌位号</view>
        <view class="font-bold u-font-32 u-m-t-16">
          {{ pageData.table.name || "" }}
        </view>
      </view>
      <view class="block">
        <view class="u-p-b-24 u-m-b-24 border-bottom">
          <view>选择用户</view>
          <view class="u-m-t-24 u-flex u-row-between" @tap="chooseUser">
            <view v-if="!pageData.user || !pageData.user.id">选择用户</view>
            <view class="u-flex" v-if="pageData.user && pageData.user.id">
              <up-avatar
                :src="pageData.user.headImg"
                shape="square"
                :size="30"
              ></up-avatar>

              <view class="u-m-l-20">
                <view class="">{{ pageData.user.nickName }}</view>
              </view>
              <view class="u-font-24 u-m-l-30 u-text-center"
                ><text>余额：</text
                ><text class="color-main">{{ pageData.user.amount }}</text>
              </view>
              <view class="u-font-24 u-m-l-30 u-text-center"
                ><text>积分：</text
                ><text class="color-main">{{
                  pageData.user.accountPoints
                }}</text></view
              >
            </view>
            <uni-icons type="right" color="#999" size="20" bold></uni-icons>
          </view>
        </view>
        <view class="  ">
          <view>就餐类型</view>
          <view class="u-m-t-24 u-flex">
            <view class="u-flex color-666">
              <up-radio-group
                :disabled="option.type == 'add'"
                v-model="pageData.eatTypes.active"
                placement="row"
              >
                <up-radio
                  :customStyle="{ marginRight: '30px' }"
                  v-for="(item, index) in pageData.eatTypes.list"
                  :key="index"
                  :label="item.name"
                  :name="item.value"
                >
                </up-radio>
              </up-radio-group>
            </view>
          </view>
        </view>
      </view>

      <template v-if="pageData.user && pageData.user.id">
        <view class="block">
          <view class="">
            <view class="u-flex border-bottom u-p-b-24">
              <up-avatar
                :src="pageData.user.headImg"
                shape="square"
                :size="60"
              ></up-avatar>
              <!-- <image class="headeimg" src="@/static/uni.png" mode=""></image> -->
              <view class="u-m-l-32">
                <view class="">{{ pageData.user.nickName }}</view>
                <view class="color-main u-font-24">{{
                  pageData.user.isVip ? "会员" : ""
                }}</view>
              </view>
            </view>
            <view class="u-flex u-m-t-24 u-row-between u-font-24 color-999">
              <view class="u-flex">
                <view>余额</view>
                <view class="color-333 u-m-l-10">
                  {{ pageData.user.amount }}</view
                >
              </view>
              <view class="u-flex">
                <view>积分</view>
                <view class="color-333 u-m-l-10">
                  {{ pageData.user.accountPoints }}</view
                >
              </view>
              <view class="u-flex">
                <view class="u-text-center">订单数量</view>
                <view class="color-333 u-m-l-10">{{
                  pageData.user.orderNumber || 0
                }}</view>
              </view>
            </view>
          </view>
        </view>
      </template>
      <template
        v-if="
          !pageData.shopInfo.isTableFee && pageData.table && pageData.table.id
        "
      >
        <!-- 不免餐位费 -->
        <view class="block">
          <view class="   ">
            <view>用餐人数（人）</view>
            <picker
              @change="userNumberChange"
              :value="userNumbers.defaultCateIndex"
              :range="userNumbers.list"
            >
              <view class="u-m-t-24 u-flex u-row-between">
                <view class="color-333">{{
                  userNumbers.defaultCateIndex * 1 + 1 + "人"
                }}</view>
                <uni-icons type="right" color="#999" size="16"></uni-icons>
              </view>
            </picker>
          </view>
        </view>
      </template>
      <!-- 	<template v-if="goods.list[0].tableId&&goods.list[0].orderId">
				<view class="block" @tap="rotatingTables"
					style="display: flex;align-items: center;justify-content: space-between;">
					<view>转桌/并桌</view>
					<uni-icons type="right" color="#999" size="16"></uni-icons>
				</view>
			</template> -->
    </template>

    <view class="block">
      <view class="u-p-b-24">
        <view class="font-bold">订单备注</view>
        <view class="u-m-t-32 u-flex">
          <uni-easyinput
            type="textarea"
            v-model="pageData.form.note"
            placeholder="请输入备注"
          ></uni-easyinput>
        </view>
      </view>
    </view>

    <view class="block u-m-b-0">
      <view class="u-flex">
        <view>共</view>
        <view class="fen font-bold">{{ allGoodsList.length }}</view>
        <view>份菜品</view>
      </view>

      <view class="goods u-m-t-32">
        <view
          class="item u-m-b-48"
          @click="changeGoodsSel(index)"
          v-for="(item, index) in goods.list"
          :key="index"
        >
          <view class="u-flex u-row-between">
            <view class="u-flex">
              <view v-if="item.coverImg" class="u-relative">
                <view class="limit-discount" v-if="item.is_time_discount"
                  >限时折扣</view
                >
                <image class="img" :src="item.coverImg" mode=""></image>
              </view>
              <view
                style="
                  background-color: #3f9eff;
                  width: 84rpx;
                  height: 84rpx;
                  line-height: 84rpx;
                  text-align: center;
                  color: #fff;
                "
                v-else
              >
                临时菜
              </view>
              <view class="u-m-l-32">
                <view class="u-flex">
                  <view
                    class="u-flex u-m-r-20"
                    v-if="item.is_wait_call"
                    style="flex-shrink: 0"
                  >
                    <uni-tag
                      text="等叫"
                      custom-style="background-color: #FFF0DF; border-color: #FFF0DF; color: #FF9F2E;"
                    >
                    </uni-tag>
                  </view>
                  <view
                    class="u-m-r-20 u-flex"
                    v-if="item.is_gift"
                    style="flex-shrink: 0"
                  >
                    <uni-tag
                      text="赠送"
                      custom-style="background-color: #FFF0DF; border-color: #FFF0DF; color: #FF9F2E;"
                    >
                    </uni-tag>
                  </view>
                  <view
                    class="u-m-r-20 u-flex"
                    v-if="item.pack_number > 0"
                    style="flex-shrink: 0"
                  >
                    <uni-tag
                      custom-style="background-color: #E6F0FF; border-color: #E6F0FF; color: #318AFE;"
                      size="small"
                      text="打包"
                      inverted
                      type="success"
                    />
                  </view>
                  <view
                    class="u-m-r-20 u-flex"
                    v-if="item.is_print"
                    style="flex-shrink: 0"
                  >
                    <uni-tag
                      custom-style="background-color: #E6F0FF; border-color: #E6F0FF; color: #318AFE;"
                      size="small"
                      text="打印"
                      inverted
                      type="success"
                    />
                  </view>
                  <view>
                    {{ item.name }}
                  </view>
                </view>
                <view class="u-font-24 color-999 u-m-t-10">{{
                  item.specInfo || " "
                }}</view>
              </view>
            </view>
            <view class="">
              <view class="u-relative">
                <template v-if="item.is_gift">
                  <text class="line-th color-999"
                    >￥{{ toFixed(item.lowPrice * item.number, item) }}</text
                  >
                  <view class="u-absolute" style="right: 0; bottom: 100%">
                    <text class="font-bold">￥0</text>
                  </view>
                </template>
                <template v-else>
                  <template
                    v-if="
                      item.discount_sale_amount &&
                      item.discount_sale_amount * 1 > 0
                    "
                  >
                    <text class="line-th color-999"
                      >￥{{ toFixed(item.lowPrice * item.number, item) }}</text
                    >
                    <view class="u-absolute" style="right: 0; bottom: 100%">
                      <text class="font-bold"
                        >￥{{
                          toFixed(item.discount_sale_amount * item.number, item)
                        }}</text
                      >
                    </view>
                  </template>
                  <template v-else-if="item.is_time_discount">
                    <text class="line-th color-999"
                      >￥{{ toFixed(item.lowPrice * item.number, item) }}</text
                    >
                    <view
                      class="u-absolute xianshi"
                      style="right: 0; bottom: 100%"
                    >
                      <text class="font-bold"
                        >￥{{ returnLimitTotalMoney(item) }}</text
                      >
                    </view>
                  </template>
                  <template
                    v-else-if="
                      isVip &&
                      item.memberPrice &&
                      item.memberPrice *1!=0
                    "
                  >
                    <text class="line-th color-999"
                      >￥{{ toFixed(item.lowPrice * item.number, item) }}</text
                    >
                    <view class="u-absolute" style="right: 0; bottom: 100%">
                      <text class="font-bold"
                        >￥{{
                          toFixed(item.lowMemberPrice * item.number, item)
                        }}</text
                      >
                    </view>
                  </template>
                  <template v-else>
                    <view class="font-bold">
                      <text>￥</text>
                      <text class="">{{
                        toFixed(item.lowPrice * item.number, item)
                      }}</text>
                    </view>
                  </template>
                </template>
              </view>
              <view class="color-999 u-text-right u-font-24 u-m-t-12"
                >×{{ item.number }}</view
              >
            </view>
          </view>
          <template v-if="item.remark">
            <view class="u-p-20 bg-gray u-m-t-16">
              {{ item.remark }}
            </view>
          </template>
          <scroll-view
            class="u-m-t-32"
            scroll-x="true"
            v-if="index == goods.sel"
          >
            <view class="u-flex no-wrap">
              <view class="u-flex u-m-r-20" v-if="!item.is_gift">
                <button
                  class="tag"
                  hover-class="hover-class"
                  @tap="showModel('discount', index)"
                >
                  单品打折
                </button>
              </view>
              <view class="u-flex u-m-r-20">
                <!-- <button class="tag" hover-class="hover-class" @tap="showModel('giveFood')">赠菜</button> -->
                <button
                  class="tag"
                  hover-class="hover-class"
                  @tap="toggleItem(item, 'is_gift')"
                >
                  {{ item.is_gift ? "取消赠送" : "赠送" }}
                </button>
              </view>
              <view class="u-flex u-m-r-20">
                <button
                  class="tag"
                  hover-class="hover-class"
                  @tap="showModel('packNumber', index, item)"
                >
                  {{ item.pack_number > 0 ? "取消打包" : "打包" }}
                </button>
              </view>
              <view class="u-flex u-m-r-20">
                <button
                  class="tag"
                  hover-class="hover-class"
                  @tap="toggleItem(item, 'is_wait_call')"
                >
                  {{ item.is_wait_call ? "取消等叫" : "等叫" }}
                </button>
              </view>
              <view class="u-flex u-m-r-20">
                <button
                  class="tag"
                  hover-class="hover-class"
                  @tap="toggleItem(item, 'is_print')"
                >
                  {{ item.is_print ? "免厨打" : "打印" }}
                </button>
              </view>
              <view class="u-flex u-m-r-20">
                <button
                  class="tag"
                  hover-class="hover-class"
                  @tap="showModel('remark', index)"
                >
                  单品备注
                </button>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
      <!-- 历史订单 -->
      <orderList :orderInfo="pageData.orderInfo"></orderList>

      <view class="border-bottom">
        <template v-if="orderCostSummary.seatFee > 0">
          <view class="u-flex u-row-between u-m-t-18 u-p-b-34">
            <view>
              <text>桌位费</text>
            </view>
            <view>￥{{ orderCostSummary.seatFee }}</view>
          </view>
        </template>

        <template v-if="orderCostSummary.packFee > 0">
          <view class="u-flex u-row-between u-m-t-18 u-p-b-34">
            <view>
              <text>打包费</text>
            </view>
            <view>￥{{ orderCostSummary.packFee }}</view>
          </view>
        </template>
      </view>

      <view class="u-flex u-row-between u-m-t-38">
        <view class="u-flex">
          <view
            class="u-flex price"
            v-if="orderCostSummary.totalDiscountAmount"
          >
            <view class="">优惠金额</view>
            <view class="font-bold u-font-32 u-m-r-16"
              >￥{{ orderCostSummary.totalDiscountAmount }}</view
            >
            <up-icon
              name="question-circle"
              color="#666"
              @click="showDiscountInfo = true"
            ></up-icon>
          </view>
        </view>

        <view class="u-flex price u-m-l-32">
          <view class="">实收金额</view>
          <view class="font-bold u-font-32"
            >￥{{ orderCostSummary.finalPayAmount }}</view
          >
        </view>
      </view>
    </view>

    <view :style="{ height: bottomHeight + 'px' }"></view>
    <view class="safe-bottom fixed">
      <view class="btn">
        <my-button shape="circle" @click="createAnOrder">
          <view class="font-bold u-font-32">
            <text v-if="pageData.shopInfo.registerType == 'before'">
              下单
            </text>
            <text v-if="pageData.shopInfo.registerType == 'after'">
              {{ goods.list.length > 0 ? "下单" : "结算" }}
            </text>
          </view>
        </my-button>
      </view>
    </view>
    <model-discount
      title="菜品减免"
      :ref="setModel"
      name="discount"
      :price="modelData.data.salePrice"
      @confirm="discountconfirm"
    ></model-discount>
    <give-food title="赠菜" :ref="setModel" name="giveFood"></give-food>
    <one-remark
      @confirm="goodsOneRemarkConfirm"
      title="单品备注"
      :ref="setModel"
      name="remark"
    ></one-remark>
    <pack-number
      @confirm="goodsOnePackNumberConfirm"
      title="打包"
      :ref="setModel"
      name="packNumber"
    ></pack-number>
    <up-popup :show="showDiscountInfo" mode="center" round="16rpx" @close="showDiscountInfo = false"  closeOnClickOverlay >
      <view class="u-p-30 u-flex u-flex-col gap-20" style="min-width: 300rpx;">
        <view class="u-flex gap-20 u-row-between w-full" v-if="orderCostSummary.goodsDiscountAmount">
          <text>商品优惠</text>
          <text class="color-red">-￥{{ orderCostSummary.goodsDiscountAmount }}</text>
        </view>
        <view class="u-flex gap-20 u-row-between w-full" v-if="orderCostSummary.newUserDiscount">
          <text>新客立减</text>
          <text class="color-red">-￥{{ orderCostSummary.newUserDiscount }}</text>
        </view>
        <view class="u-flex gap-20 u-row-between w-full" v-if="orderCostSummary.fullReduction.actualAmount">
          <text>满减活动</text>
          <text class="color-red">-￥{{ orderCostSummary.fullReduction.actualAmount }}</text>
        </view>
        <view class="u-flex gap-20 u-row-between w-full" v-if="orderCostSummary.vipDiscountAmount">
          <text>会员折扣</text>
          <text class="color-red">-￥{{ orderCostSummary.vipDiscountAmount }}</text>
        </view>
      </view>
    </up-popup>
    <!-- <edit-discount title="优惠金额" :ref="setModel" name="editMoney" :price="allPrice"></edit-discount> -->
  </view>
</template>

<script setup>
import { onLoad, onReady, onShow, onHide } from "@dcloudio/uni-app";
import yskUtils from "ysk-utils";
// import yskUtils from "@/lib/index";
const limitUtils = yskUtils.limitUtils;

import {
  ref,
  inject,
  onUnmounted,
  nextTick,
  reactive,
  computed,
  watch,
  provide,
} from "vue";
provide("yskUtils", yskUtils);

import modelDiscount from "./components/discount";
import giveFood from "./components/give-food";
import packNumber from "./components/pack-number";
import oneRemark from "./components/remark";
import orderList from "./components/list";
// import editDiscount from '@/pagesCreateOrder/components/edit-discount.vue'

import { getSafeBottomHeight } from "@/commons/utils/safe-bottom.js";
import go from "@/commons/utils/go.js";
import { hasPermission } from "@/commons/utils/hasPermission.js";
import { getNowCart } from "@/pagesCreateOrder/util.js";

import { getShopTableDetail } from "@/http/api/table.js";
import { getShopInfo } from "@/http/api/shop.js";
import { getProductList } from "@/http/api/product.js";
import { createOrder, getHistoryOrder } from "@/http/api/order.js";
import { shopUserDetail } from "@/http/yskApi/shop-user.js";
import { discountActivity } from "@/http/yskApi/market/discountActivity.js";
import BigNumber from "bignumber.js";
import * as limitTimeDiscountApi from "@/http/yskApi/limitTimeDiscount.js";

const showDiscountInfo=ref(false)
const models = new Map();
const modelData = reactive({
  data: {},
  selIndex: -1,
});
const option = reactive({
  id: "",
  tableId: "",
});
const shopInfo = uni.getStorageSync("shopInfo");
provide("shopInfo", shopInfo);

function returnLimitTotalMoney(data) {
  // const price = yskUtils.limitUtils.returnPrice({
  const price = limitUtils.returnPrice({
    goods: data,
    shopInfo: shopInfo,
    limitTimeDiscountRes: pageData.limitTimeDiscount,
    shopUserInfo: pageData.user,
    idKey: "product_id",
  });
  return BigNumber(price).times(data.number).toNumber();
}
/**
 * 用餐人数
 */
const userNumbers = reactive({
  list: new Array(100).fill(1).map((v, index) => {
    // return index === 0 ? '无' : index + '人'
    return index + 1 + "人";
  }),
  defaultCateIndex: 0,
});
const f = reactive({});

let $goods = [];
const goods = reactive({
  list: [],
  sel: 0,
});
const pageData = reactive({
  shopInfo: {},
  table: {},
  user: {},
  eatTypes: {
    list: [
      {
        name: "堂食",
        value: "dine-in",
      },
      {
        name: "外带",
        value: "take-out",
      },
      // ,
      // {
      // 	name: "外卖",
      // 	value: "take-away",
      // }
    ],
    active: "dine-in",
    isShow: false,
  },
  form: {
    note: "",
  },
  orderInfo: {},
  limitTimeDiscount: null, //限时折扣
});

provide("pageData", pageData);

async function getDiscountActivity() {
  let res = await discountActivity({
    shopId: uni.getStorageSync("shopId"),
  });
  if (res.code == 200) {
    fullReductionActivities.value = res.data?[res.data]:[];
  }
}
const websocketUtil = inject("websocketUtil"); // 注入 WebSocket 工具类实例

const limitTimeDiscountRes = ref(null);
async function getLimit() {
  const res = await limitTimeDiscountApi.limitTimeDiscount();
  limitTimeDiscountRes.value = res.data;
  if (pageData.table.tableCode) {
    pageData.limitTimeDiscount  = limitTimeDiscountRes.value;

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

onLoad(async (opt) => {
  Object.assign(option, opt);
  console.log("opt====", opt);
  if (opt.tableId || opt.tableCode) {
    pageData.table.id = opt.tableId;
    pageData.table.tableCode = opt.tableCode;
  }
  //获取限时折扣
  await getLimit();
  //获取满减活动
  await getDiscountActivity();
  pageData.shopInfo = uni.getStorageSync("shopInfo");
  getTbShopInfo();
});
let bottomHeight = ref(100);
onReady(() => {
  getSafeBottomHeight("safe-bottom").then((res) => {
    bottomHeight.value = res + 40;
  });
});
watch(
  () => userNumbers.defaultCateIndex,
  (newval) => {
    updateChoseCount();
  }
);

watch(
  () => pageData.eatTypes.active,
  (newval) => {
    pageData.eatTypes.isShow = true;
    changeUseType();
  }
);
onShow(() => {
  init();
  watchChooseuser();
  watchChooseTable();
});
onHide(() => {
  console.log("onHide");
  websocketUtil.offMessage();
});
onUnmounted(() => {
  console.log("onUnmounted");
  websocketUtil.offMessage();
});

/**
 * 获取订单详情
 * @param {Object} tableCode
 */
async function getHistoryOrderDetail(tableCode) {

  let res = await getHistoryOrder({
    tableCode: tableCode,
  });
  pageData.orderInfo = res.data;
}

//餐位费
const $seatFee = reactive({
  totalNumber: 0,
  totalAmount: 0,
});

/**
 * 判断是否是会员
 */
const isVip = computed(() => {
  return pageData.shopInfo.isMemberPrice &&
    pageData.user &&
    pageData.user.id &&
    pageData.user.isVip
    ? true
    : false;
});

function toFixed(price, item) {
  if (item) {
    if (item.productType == "weight" || item.type == "weight") {
      return (Math.floor(price * 100) / 100).toFixed(2);
    } else {
      return parseFloat(price).toFixed(2);
    }
  } else {
    return parseFloat(price).toFixed(2);
  }
}

async function init() {
  nextTick(() => {
    onMessage();
  });
  // 获取商品列表
  let res = await getProductList({}, "product", false);
  $goods = res.data;
  // console.log("商品列表===",$goods)
  getTableInfo(pageData.table);
}

/**
 * socket消息监听
 */
function onMessage() {
  websocketUtil.offMessage();
  websocketUtil.onMessage((res) => {
    let msg = JSON.parse(res);
    let cartItem;
    if (msg.msg_id) {
      websocketUtil.send(
        JSON.stringify({
          type: "receipt",
          msg_id: msg.msg_id,
        })
      );
    }
    if (msg.status == 0) {
      infoBox.showToast("添加失败");
      return false;
    }

    switch (msg.operate_type) {
      case "pad_init":
        goods.list = [];

        msg.data.map((item) => {
          cartItem = getNowCart(item, $goods, pageData.user);
          if (cartItem.isGrounding || cartItem.is_temporary == 1) {
            cartControls(cartItem, "add");
          } else {
            delCart(cartItem.id);
          }
        });

        if (pageData.eatTypes.isShow) {
          if (pageData.eatTypes.active == "take-out") {
            cartItem.pack_number = cartItem.number;
          } else {
            cartItem.pack_number = 0;
          }
          let par = {
            type: "onboc",
            account: uni.getStorageSync("iToken").loginId,
            shop_id: uni.getStorageSync("shopInfo").id,
            operate_type: "batch",
            table_code: pageData.table.tableCode,
            is_pack: pageData.eatTypes.active == "take-out" ? 1 : 0,
          };
          updateCart(par);
        }
        // 是否更新就餐人数
        if (!$seatFee.totalNumber) {
          updateChoseCount();
        }

        pageData.eatTypes.isShow = false;
        pageData.limitTimeDiscount = msg.time_dis_info;
        break;
      case "pad_add":
      case "add":
        cartItem = getNowCart(msg.data, $goods, pageData.user);
        cartControls(cartItem, "add");
        break;
      case "pad_edit":
      case "edit":
        getCart();
        break;
      case "pad_del":
      case "del":
        cartItem = getNowCart(msg.data, $goods, pageData.user);
        cartControls(cartItem, "del");
        break;
      case "pad_cleanup":
      case "cleanup":
        goods.list = [];
        $seatFee.totalNumber = 0;
        $seatFee.totalAmount = 0;
        userNumbers.defaultCateIndex = 0;
        init();
        break;
      case "product_update":
        init();
        break;
      case "pad_batch":
        init();
        break;
    }
  });
}

/**
 * 删除购物车菜品
 */
function delCart(cartItem) {
  let params = {
    type: "pad",
    account: uni.getStorageSync("shopId"),
    shop_id: uni.getStorageSync("shopId"),
    is_gift: 0,
    id: cartItem.id,
    operate_type: "del",
  };
  websocketUtil.send(JSON.stringify(params));
}

/**
 * socket通知购物车商品数量修改处理
 */
function cartControls(cartItem, type) {
  if (!pageData.table.tableCode) {
    pageData.table.tableCode = cartItem.table_code;
  }
  let cartIndex = 0;

  goods.list.map((item, index) => {
    if (item.id == cartItem.id) {
      cartIndex = index;
    }
  });

  if (type == "del") {
    goods.list.splice(cartIndex, 1);
    return;
  }
  if (type == "add") {
    goods.list.push({ ...cartItem, packNumber: cartItem.pack_number });
  }
  if (type == "edit") {
    goods.list[cartIndex].number = cartItem.number;
    goods.list[cartIndex].pack_number = cartItem.pack_number;
    goods.list[cartIndex].packNumber = cartItem.pack_number;
  }
}

/**
 * 获取购物车数据
 */
function getCart() {
  // 初始化购物车
  websocketUtil.send(
    JSON.stringify({
      type: "pad",
      account: uni.getStorageSync("shopInfo").id,
      shop_id: uni.getStorageSync("shopInfo").id,
      operate_type: "init",
      table_code: pageData.table.tableCode,
    })
  );
}

/**
 * 获取店铺信息
 */
async function getTbShopInfo() {
  const res = await getShopInfo({
    id: uni.getStorageSync("shopId"),
  });
  pageData.shopInfo = res.data;
  seatFeeConfig.pricePerPerson = res.data.tableFee || 0;
  uni.setStorageSync("shopInfo", res.data);
}

/**
 * 获取桌台信息
 */
async function getTableInfo(opt) {
  const { data: res } = await getShopTableDetail({
    id: opt.id,
    tableCode: opt.tableCode,
  });
  Object.assign(pageData.table, res);
  if (!pageData.shopInfo.isTableFee && pageData.table && pageData.table.id) {
    userNumbers.list = new Array(res.maxCapacity ? res.maxCapacity * 1 : 100)
      .fill(1)
      .map((v, index) => {
        return index + 1 + "人";
      });
  }
  // 获取购物车数据
  getCart();
  // 获取购物车数据
  if(shopInfo.registerType==='before'){
    return 
  }
  getHistoryOrderDetail(opt.tableCode);
}

/**
 * 更新选择用户
 */
function watchChooseuser() {
  uni.$off("choose-user");
  uni.$on("choose-user", async (data) => {
    if (pageData.user.id == data.id) {
      return;
    }
    if (data.id) {
      const res = await shopUserDetail({
        userId: data.userId,
      });
      pageData.user = res.data;
    } else {
      pageData.user = data;
    }
    // 更新购物车和历史订单数据
    uodateCartAndHistory();
  });
}

/**
 * 更新购物车和历史订单数据
 */
function uodateCartAndHistory() {
  let newData = {
    history: [],
    cart: [],
  };
  console.log("uodateCartAndHistory", pageData.user);
  for (let cart of goods.list) {
    const canUseLimitTimeDiscount = yskUtils.limitUtils.canUseLimitTimeDiscount(
      cart,
      pageData.limitTimeDiscount,
      pageData.shopInfo,
      pageData.user,
      "product_id"
    )
      ? 1
      : 0;
    console.log("uodateCartAndHistory", pageData.user);
    if (canUseLimitTimeDiscount != cart.is_time_discount) {
      newData.cart.push({
        id: cart.id,
        is_time_discount: canUseLimitTimeDiscount,
      });
    }
  }
  if (newData.history.length <= 0 && newData.cart.length <= 0) {
    return;
  }

  websocketUtil.send(
    JSON.stringify({
      type: "pad",
      account: uni.getStorageSync("shopInfo").id,
      shop_id: uni.getStorageSync("shopInfo").id,
      operate_type: "bulk_edit",
      table_code: pageData.table.tableCode,
      data: newData,
    })
  );
}

/**
 * 就餐类型切换监听
 */
async function changeUseType() {
  if (!goods.list.length) {
    return;
  }
  websocketUtil.send(
    JSON.stringify({
      type: "pad",
      is_pack: pageData.eatTypes.active == "take-out" ? 1 : 0,
      account: uni.getStorageSync("shopInfo").id,
      shop_id: uni.getStorageSync("shopInfo").id,
      operate_type: "batch",
      table_code: pageData.table.tableCode,
    })
  );

  // getCart();
}

/**
 * 购物车数据修改
 * @param {Object} par
 */
function updateCart(par) {
  websocketUtil.send(
    JSON.stringify({
      type: "pad",
      account: uni.getStorageSync("shopInfo").id,
      shop_id: uni.getStorageSync("shopInfo").id,
      operate_type: "edit",
      table_code: pageData.table.tableCode,
      ...par,
    })
  );
  getCart();
}

/**
 * 菜品赠送/等叫/打印修改
 * @param {Object} item
 */
function toggleItem(item, key) {
  let par = {
    id: item.id,
    product_id: item.product_id,
    sku_id: item.sku_id,
  };
  par[key] = item[key] == 0 ? 1 : 0;
  updateCart(par);
}

/**
 * 单品打折
 * @param {Object} form
 */
async function discountconfirm(form) {
  if (form.discountMoney != ".") {
    let str = "";
    if (form.notes) {
      form.notes.forEach((ele) => {
        if (ele.checked) {
          str = str + ele.name + ",";
        }
      });
    }
    let lowMemberPrice = modelData.data.lowMemberPrice
      ? modelData.data.lowMemberPrice
      : modelData.data.lowPrice;
    let tPrice = isVip.value ? lowMemberPrice : modelData.data.lowPrice;
    let discount_sale_amount = modelData.data.is_gift ? 0 : form.discountMoney;
    let par = {
      id: modelData.data.id,
      product_id: modelData.data.product_id,
      sku_id: modelData.data.sku_id,
      discount_sale_amount: discount_sale_amount,
      discount_sale_note: str + form.note,
    };
    updateCart(par);
  }
}

/**
 * 打包
 */
function goodsOnePackNumberConfirm(e) {
  let par = {
    id: modelData.data.id,
    product_id: modelData.data.product_id,
    sku_id: modelData.data.sku_id,
    pack_number: e,
  };
  updateCart(par);
}

/**
 * 单品备注确认
 * @param {Object} e
 */
async function goodsOneRemarkConfirm(e) {
  let par = {
    id: modelData.data.id,
    product_id: modelData.data.product_id,
    sku_id: modelData.data.sku_id,
    remark: e.remark,
  };
  updateCart(par);
}

/**
 * 设置弹窗信息
 * @param {Object} el
 */
function setModel(el) {
  if (el && el.$attrs["name"]) {
    models.set(el.$attrs["name"], el);
  }
}

/**
 * 打开弹窗
 * @param {Object} key
 * @param {Object} index
 */
function showModel(key, index, item) {
  modelData.data = goods.list[index];
  modelData.selIndex = index;
  const model = models.get(key);
  console.log("弹窗数据===", modelData.data);
  if (key == "packNumber") {
    if (modelData.data.type == "weight" && item.pack_number <= 0) {
      let par = {
        id: modelData.data.id,
        product_id: modelData.data.product_id,
        sku_id: modelData.data.sku_id,
        pack_number: 1,
      };
      updateCart(par);
      return false;
    }
    if (item.pack_number > 0) {
      let par = {
        id: modelData.data.id,
        product_id: modelData.data.product_id,
        sku_id: modelData.data.sku_id,
        pack_number: 0,
      };
      updateCart(par);
      return false;
    }
    model &&
      model.open({
        number: item.number,
      });
  } else {
    model &&
      model.open({
        packNumber: modelData.data.remark || "",
      });
  }
}

function formatPrice(n) {
  return (Math.floor(n * 100) / 100).toFixed(2);
}

function rotatingTables() {
  uni.navigateTo({
    url:
      "/pagesCreateOrder/confirm-order/rotatingTables?item=" +
      JSON.stringify(goods.list),
  });
}

/**
 * 更新就餐人数
 */
async function updateChoseCount() {
  const maxCapacity =
    pageData.table && pageData.table.id ? pageData.table.maxCapacity || 0 : 100;
  if (
    pageData.table &&
    pageData.table.id &&
    userNumbers.defaultCateIndex * 1 + 1 > maxCapacity
  ) {
    // uni.$utils.showToast('当前台桌最大人数为: ' + maxCapacity)
    userNumbers.defaultCateIndex = maxCapacity - 1;
    return;
  }
  console.log(pageData.shopInfo);
  console.log(!pageData.shopInfo.isTableFee);
  if (
    !pageData.shopInfo.isTableFee &&
    pageData.table &&
    pageData.table.id &&
    goods.list.length > 0
  ) {
    //不免餐位费
    console.log("不免餐位费");
    let seatFee = {
      totalNumber: userNumbers.defaultCateIndex * 1 + 1,
      totalAmount:
        (userNumbers.defaultCateIndex * 1 + 1) * pageData.shopInfo.tableFee,
    };
    Object.assign($seatFee, seatFee);
    userNumbers.defaultCateIndex = $seatFee.totalNumber - 1;
  }
}

/**
 * 选择就餐人数
 * @param {Object} e
 */
function userNumberChange(e) {
  userNumbers.defaultCateIndex = e.detail.value;
}

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

function chooseTable() {
  go.to("PAGES_CHOOSE_TABLE", {
    ...pageData.table,
  });
}

function watchChooseTable() {
  uni.$off("choose-table");
  uni.$on("choose-table", (data) => {
    pageData.table = data;
    console.log("台桌信息", pageData.table);
  });
}

function changeGoodsSel(index) {
  goods.sel = index;
}

/**
 * 创建订单
 */
async function createAnOrder() {
  if (
    pageData.shopInfo.registerType == "before" ||
    pageData.eatTypes.active == "take-out"
  ) {
    const canJiesuan = await hasPermission("允许收款");
    if (!canJiesuan) {
      return;
    }
  }

  let vipPrice = isVip.value ? 1 : 0;
  let placeNum = pageData.orderInfo ? pageData.orderInfo.placeNum + 1 : 1;
  let par = {
    shopId: pageData.shopInfo.id, //店铺Id
    userId: pageData.user.userId, //用户Id
    tableCode: pageData.table.tableCode, //台桌编码
    dineMode: pageData.eatTypes.active, //用餐模式 堂食 dine-in 外带 take-out 外卖 take-away
    remark: pageData.form.note, //备注
    seatNum:  pageData.eatTypes.active == "dine-in" ? seatFeeConfig.personCount : 0, //用餐人数
    packFee:orderCostSummary.value.packFee, //打包费
    originAmount: orderCostSummary.value.goodsRealAmount, //订单原金额（不包含打包费+餐位费）
    placeNum: placeNum, //当前订单下单次数
    waitCall: 0, //是否等叫 0 否 1 等叫
    vipPrice: vipPrice, //是否使用会员价
    limitRate: pageData.limitTimeDiscount,
  };
  if (!pageData.shopInfo.isTableFee && pageData.table && pageData.table.id) {
    par.seatNum = userNumbers.defaultCateIndex * 1 + 1;
  }
  if (pageData.orderInfo && pageData.shopInfo.registerType != "before") {
    par.orderId = pageData.orderInfo.id;
  }
  let res = {data:{id:''}};
  if (goods.list.length) {
     res = await createOrder(par);
    console.log(res, "创建订单");
    if (res.code != 200) {
      uni.showToast({
        title: res.msg || "创建订单失败！",
        icon: "none",
      });
      return;
    }
    uni.$emit("update:createOrderIndex");
    websocketUtil.send(
      JSON.stringify({
        type: "pad",
        account: uni.getStorageSync("shopInfo").id,
        shop_id: uni.getStorageSync("shopInfo").id,
        operate_type: "cleanup",
        table_code: pageData.table.tableCode,
      })
    );
    uni.removeStorageSync("table_code");
  }

  if (
    pageData.shopInfo.registerType == "before" ||
    pageData.eatTypes.active == "take-out"
  ) {
    //先付
    return go.to(
      "PAGES_ORDER_PAY",
      {
        orderId: res.data.id,
        isNowPay: true,
        dinnerType: pageData.eatTypes.active,
      },
      "redirect"
    );
  } else {
    if(!res.data.id&&pageData.orderInfo.id){
      return go.to(
      "PAGES_ORDER_PAY",
      {
        orderId: pageData.orderInfo.id,
        isNowPay: true,
        dinnerType: pageData.eatTypes.active,
      },
      "redirect"
    );
    }
    //后付
    if (option.isCreateOrderToDetail != "0") {
      go.to(
        "PAGES_ORDER_DETAIL",
        {
          id: res.data.id||pageData.orderInfo.id,
          dinnerType: pageData.eatTypes.active,
        },
        "redirect"
      );
    } else {
      uni.navigateBack({
        delta: 2,
      });
    }
  }
  uni.showToast({
    title: "提交成功",
    icon: "none",
  });
}

//选择的优惠券
const selCoupon = ref([]);
//活动列表
const activityList = ref([]);
// 商家减免，初始配置：默认无减免（固定金额 0 元）
const merchantReductionConfig = reactive({
  type: "fixed_amount",
  fixedAmount: 0,
});
//积分规则
const pointDeductionRule = reactive({
  pointsPerYuan: 0,
  maxDeductionAmount: Infinity,
});
//餐费费
const seatFeeConfig = reactive({
  pricePerPerson: pageData.shopInfo.tableFee || 0,
  personCount: 0, //就餐人数
  isEnabled: !pageData.shopInfo.isTableFee,
});
//使用积分数量
const userPoints = ref(0);
//是否使用会员价
const useVipPrice = computed(() => {
  if (pageData.shopInfo.isMemberPrice == 1 && pageData.user.isVip == 1) {
    return true;
  }
  return false;
});
//新客立减
const newUserDiscount = ref(0);
//满减活动
const fullReductionActivities = ref([]);
// 商家霸王餐配置
const freeDineConfig = ref(null);

const orderExtraConfig = computed(() => {
  return {
    // 引用扩展后的商家减免配置
    merchantReduction: merchantReductionConfig,
    additionalFee: 0,
    pointDeductionRule: pointDeductionRule,
    seatFeeConfig: seatFeeConfig,
    currentStoreId: "",
    userPoints: userPoints.value,
    isMember: useVipPrice.value,
    memberDiscountRate: 1,
    newUserDiscount: newUserDiscount.value,
    fullReductionActivities: fullReductionActivities.value,
    currentDinnerType: pageData.eatTypes.active,
    isFreeDine: false, //霸王餐
    freeDineConfig: freeDineConfig.value,
    limitTimeDiscount: pageData.limitTimeDiscount,
    shopUserInfo: pageData.user,
  };
});

const allGoodsList = computed(() => {
  if (!pageData.orderInfo || !pageData.orderInfo.detailMap) {
    return goods.list;
  }
  console.log(Object.values(pageData.orderInfo.detailMap));
  const historyGoodsList = Object.values(pageData.orderInfo.detailMap).reduce(
    (prve, cur) => {
      cur.map((v) => {
        v.number = v.num;
        v.salePrice = v.price;
      });
      prve.push(...cur);
      return prve;
    },
    []
  );
  return [...goods.list, ...historyGoodsList];
});

// 订单费用汇总
const orderCostSummary = computed(() => {
  console.log(goods.list, "购物车数据");
  const costSummary = yskUtils.OrderPriceCalculator.calculateOrderCostSummary(
    allGoodsList.value,
    pageData.eatTypes.active,
    selCoupon.value,
    activityList.value,
    orderExtraConfig.value,
    {},
    new Date()
  );
  console.log(" 订单费用汇总", costSummary);
  return costSummary;
});
watch(
  () => $seatFee.totalNumber,
  (newVal, oldVal) => {
    seatFeeConfig.personCount = newVal;
  },
  {
    immediate: true,
  }
);
</script>

<style lang="scss" scoped>
.fen {
  color: #ff9f2e;
}

.page-gray {
  padding: 32rpx 28rpx 0 28rpx;
}

.headeimg {
  width: 84rpx;
  height: 84rpx;
  border-radius: 12rpx 12rpx 12rpx 12rpx;
}

.block {
  background-color: #fff;
  padding: 32rpx 24rpx;
  border-radius: 18rpx;
  margin-bottom: 32rpx;
}

.textarea {
  border-radius: 12rpx 12rpx 12rpx 12rpx;
  padding: 32rpx 0 32rpx 24rpx;
  border: 1px solid #999999;
  overflow: hidden;
}

.goods {
  // padding-bottom: 30rpx;
  border-bottom: 1px dashed #e5e5e5;

  .item {
    .img {
      width: 120rpx;
      height: 120rpx;
      border-radius: 8rpx 8rpx 8rpx 8rpx;
    }
  }
}

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

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

.price {
  color: #eb4f4f;
}

.opacity0 {
  opacity: 0;
}

.fixed {
  position: fixed;
}

.safe-bottom {
  padding: 34rpx 28rpx;
  background-color: #fff;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10;

  .btn {
    padding: 0 88rpx 56rpx 88rpx;
  }
}

.tag {
  background-color: #fff;
  border: 1px solid #e5e5e5;
  line-height: inherit;
  font-size: 24rpx;
  color: #666666;
  padding: 6rpx 16rpx;
  border-radius: 100rpx;
}

.hover-class {
  background-color: #e5e5e5;
}
.limit-discount {
  background-color: #cc5617;
  padding: 2rpx 10rpx;
  white-space: nowrap;
  text-align: center;
  position: absolute;
  top: 0;
  left: 0;
  font-weight: 400;
  font-size: 24rpx;
  color: #ffffff;
  border-radius: 20rpx 0rpx 20rpx 0rpx;
  z-index: 9;
  color: #fff;
}
.u-row-between {
  justify-content: space-between;
}
.w-full{
  width: 100%;
}
</style>