<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { getGoodsByCate } from '@/services/goods'
import { useRoute, useRouter } from 'vue-router'

import { useCartStore } from "@/store/Cart.js";
import { storeToRefs } from "pinia";

import { showToast } from "vant";
import "vant/es/toast/style";

import Nav from './component/nav.vue'
import Goods from './component/goods.vue'

const route = useRoute()
const router = useRouter()

const cartStore = useCartStore();
const { cartItems: items } = storeToRefs(cartStore);

const cate_id = ref(1)

const goods = ref({})
const goods_id = ref({})

const goodsNumber = ref({})

const showBottom = ref(false)

const state = reactive(
  {
    table_no: 0,
    type: 0,
  }
)

onMounted(async () => {

  if (route.query.type) {
    cartStore.type = parseInt(route.query.type)
    if (cartStore.type === 1) {
      if (route.query.table_no) {
        cartStore.table_no = route.query.table_no
      }
    }
  }

  let res = await getGoodsByCate(cate_id.value)

  if (res.code === 200) {
    goods.value = res.data
  }


})

const type_name = {
  1: '內用',
  2: '外帶',
  3: '外送',
  // 4: '宵夜'
}

const type = computed(() => {
  return type_name[cartStore.type]
})


//將item的key改為goods_id
const cartItems = computed(() => {
  return items.value.reduce((acc, cur) => {
    acc[cur.goods_pid] = cur;
    return acc;
  }, {});
});

const cartNum = (id) => {
  let rtn = Object.keys(cartItems.value).reduce((acc, key) => {

    if (cartItems.value[key].goods_id == id) {
      acc += cartItems.value[key].goods_number;
    }
    return acc;
  }, 0);

  return rtn;
};

const handleClickItem = async (cat_id) => {
  let res = await getGoodsByCate(cat_id)
  if (res.code === 200) {
    cate_id.value = cat_id
    goods.value = res.data
  }
}

const changeItemNum = (goods, num) => {
  //用goods_id取得item
  let item = cartItems.value[goods.goods_id];

  if (!item) {
    return addToCart(goods, num);
  }
  if (item.goods_number + num <= 0) {
    cartStore.delCart(item.goods_pid);
  } else {
    cartStore.updateCart(item, item.goods_number + num);
  }
};

//計算購物車總量
const cartTotal = computed(() => {
  return items.value.reduce((acc, cur) => {
    acc += cur.goods_number;
    return acc;
  }, 0);
})

const addToCart = async (goods, num, type = 0) => {

  //上傳產品至購物車

  let gs = {
    goods_pid: goods.goods_pid || goods.goods_id,
    add_info: '',
    buymax: goods.buymax,
    cat_id: goods.cat_id,
    goods_id: goods.goods_id,
    goods_name: goods.goods_name,
    goods_number: 1,
    goods_price: goods.shop_price,
    goods_sn: goods.goods_sn,
    goods_thumb: goods.goods_thumb
  };

  let res = await cartStore.addCart(gs);

  if (!res) {
    return showToast("添加失敗！");
  }

  if (type === 0) {
    // showToast("添加成功！");
  } else {
    router.push("/cart");
  }

  return;
};

const selectedCoods = ref({})

const handleShowGoods = (goods) => {
  goods_id.value = goods.goods_id
  selectedCoods.value = goods
  showBottom.value = true
}

const handlePopupClose = (value) => {
  console.log('value',value)
  if(value){
    goodsNumber.value[value.id] = value.num
  }
  
  showBottom.value = false
}

const columns = [
  { text: '1', value: '1' },
  { text: '2', value: '2' },
  { text: '3', value: '3' },
  { text: '4', value: '4' },
  { text: '5', value: '5' },
];

const fieldValue = ref('');
const showPicker = ref(false);

const onConfirm = ({ selectedOptions }) => {
  console.log(selectedOptions)
  showPicker.value = false;
  cartStore.table_no = selectedOptions[0].value;
};

const onSubmit = () => {
  router.push("/checkout");
};
</script>

<template>
  <!-- Main Start -->
  <main class="main-wrap catagories-wide mb-xxl">
    <!-- Search Box Start -->
    <!-- <div class="search-box">
      <i class="icon-search icli search"></i>
      <input class="form-control" type="search" placeholder="搜尋..." speech x-webkit-speech />
    </div> -->
    <!-- Search Box End -->

    <!-- Search Box Start -->
    <div class="category-header">
      <van-field v-model="type" readonly size="large" label="點餐類型" />
      <van-field v-model="cartStore.table_no" is-link readonly size="large" label="桌號" placeholder="請選擇桌號"
        @click="showPicker = true" v-if="cartStore.type === 1" />
      <van-popup v-model:show="showPicker" round position="bottom">
        <van-picker :columns="columns" @cancel="showPicker = false" confirm-button-text="確定" cancel-button-text="取消"
          @confirm="onConfirm" />
      </van-popup>
    </div>

    <!-- Search Box End -->

    <!-- Catagories Section Start -->
    <section class="pb-0">
      <div class="catagories-wrap">
        <Nav @item-click="handleClickItem" />
        <!-- Catagories Content Start -->
        <div class="tab-content ratio2_1" id="catagories-tabContent">
          <div class="tab-pane fade show active" id="catagories1" role="tabpanel" aria-labelledby="catagories1">
            <div class="banner-box">
              <!-- <img src="@/assets/images/banner/catagories-banner.jpg" alt="banner" class="bg-img" /> -->
              <div class="content-box">
                <h1 class="title-color heading">Season’s exotic Fruits</h1>
                <p class="content-color font-sm">Upto 20% OFF</p>
                <a href="shop.html" class="btn-solid">Shop Now</a>
              </div>
            </div>

            <div class="row g-3">
              <!-- Staples Box Start -->
              <div class="col-12" v-for="v in goods" :key="v.goods_id">
                <div class="staples-box">
                  <div class="goods-info">
                    <div>
                      <img class="img-fluid" :src="v.goods_thumb" alt="vegi" />
                    </div>
                    <div>
                      <div>
                        <h4>{{ v.goods_name }}</h4>
                      </div>
                    </div>
                  </div>
                  <div class="add-cart">
                    <div>
                      <p class="price">${{ v.shop_price }}</p>
                    </div>
                    <div v-if="v.goods_type > 0">
                      <van-button type="primary" size="small" @click="handleShowGoods(v)">
                        <template v-if="cartNum(v.goods_id) > 0">
                          <van-badge :content="cartNum(v.goods_id)">
                            加入購物車
                          </van-badge>
                        </template>
                        <template v-else>
                          加入購物車
                        </template>
                      </van-button>
                    </div>
                    <div v-else>
                      <van-stepper theme="round" v-model="goodsNumber[v.goods_id]" :min="0"
                        :default-value="cartNum(v.goods_id)" button-size="22" isable-input @plus="changeItemNum(v, 1)"
                        @minus="changeItemNum(v, -1)" />
                    </div>
                  </div>

                </div>
              </div>
              <!-- Staples Box End -->

            </div>
          </div>
        </div>
        <!-- Catagories Content End -->
      </div>
    </section>
    <!-- Catagories Section End -->
  </main>
  <!-- Main End -->
  <van-action-bar>
    <van-action-bar-icon icon="shop-o" text="回首頁" @click="$router.push('/')" />
    <van-action-bar-icon icon="cart-o" text="購物車" :badge="cartTotal" @click="$router.push('/checkout')" />
    <div class="total-amount">
      共 ${{ cartStore.totalAmount }} 元
    </div>
    <van-action-bar-button type="danger" text="選好了" @click="onSubmit" />
  </van-action-bar>

  <!-- 彈窗 -->
  <van-popup v-model:show="showBottom" position="bottom" :style="{ height: '100%' }">
    <div class="popup-content">
      <goods :goods="selectedCoods" @close="handlePopupClose" />
    </div>
  </van-popup>
</template>

<style lang="less">
.category-header {
  font-size: 16px;

  .info-box {
    display: flex;
    flex-wrap: wrap;
    // justify-content: space-between;
    margin: 0 0px;
    color: #666;

    div {
      padding: 0 5px;
    }
  }
}

.price {
  color: red;
  font-weight: 700;

}

.staples-box {

  .goods-info {
    display: flex;
    width: 100%;

    div:nth-child(1) {
      width: 50%;

      img {
        width: 100%;
      }
    }

    div:nth-child(2) {
      width: 70%;
      padding: 10px 10px;

      div:nth-child(1) {
        width: 100%;

        h4 {
          font-size: 16px;
          font-weight: bold;
          margin: 0;
        }
      }
    }

  }

  .add-cart {
    display: flex;
    width: 100%;
    justify-content: space-between;

    div:nth-child(1) {
      flex: 1;

      p {
        margin: 0;
      }
    }

    div:nth-child(2) {
      width: 100px;
      text-align: right;
    }

  }
}

.popup-content {
  // margin-top: 50px;
  // padding: 0 20px;
}

.total-amount {
  padding: 0 10px;
  font-size: 16px;
}
</style>