<template>
  <Theme>
    <view class="wrap">
      <Navbar fixed leftShow leftIconColor="var(--bg)">
        <template #center>
          <view class="nav_title">
            <trans _t="购物车" />
          </view>
          <view class="nav_title" v-if="cartNum">({{ cartNum }})</view>
        </template>
        <template #right>
          <view class="nav_right" @click.stop="delCart" v-if="ids.length">
            <trans _t="删除" />
          </view>
        </template>
      </Navbar>
      <view
        class="content"
        :style="{ '--height': footerHeight + tabbarHeight + 'px' }"
      >
        <view class="cont_wrap">
          <shop-model :list="cartList" ref="shopRef" @getIds="getIds" />
        </view>
        <view
          class="footer"
          id="footer"
          :style="{ '--tabbarHeight': tabbarHeight + 'px' }"
        >
          <view class="footer_left">
            <up-checkbox
              :label="t('全部')"
              :disabled="!cartList.length"
              activeColor="var(--black)"
              shape="circle"
              labelSize="14"
              labelColor="#676969"
              iconSize="16"
              name="agree"
              usedAlone
              v-model:checked="selectAllChecked"
              @change="selectAllChange"
            >
            </up-checkbox>
          </view>
          <view class="footer_right">
            <view class="total_info">
              <view class="total_price">
                <!-- {{ t(`已选${money.total_num}件,合计：`) }} -->
                <text
                  >{{ symbol.symbol }} {{ Moneyhtml(money.total_price) }}</text
                >
              </view>
              <view class="total_desc">
                <trans _t="不包括运费" />
              </view>
            </view>
            <view
              class="total_btn"
              @click.stop="submit"
              :style="{
                opacity: canCheckout ? 1 : 0.5,
                'pointer-events': canCheckout ? 'auto' : 'none',
              }"
            >
              <trans _t="去结算" />
            </view>
          </view>
        </view>
      </view>
    </view>
    <Tabbar page="shop" @getTabbarHeight="getTabbarHeight" />
  </Theme>
</template>

<script setup>
import { computed, ref, onMounted, nextTick, watch } from "vue";
import Tabbar from "@/components/tabbar";
import Navbar from "@/components/navbar";
import Tab from "@/components/tabs";
import { useUserStore, useShopStore, useSystemStore } from "@/store";
import { SELLER_DEL_CART } from "@/api";
import { t } from "@/locale";
import { onShow } from "@dcloudio/uni-app";
import shopModel from "@/pages/shop/components/shopModel";
import { query, Moneyhtml } from "@/utils";

const useUser = useUserStore();
const useShop = useShopStore();
const useSystem = useSystemStore();
const symbol = computed(() => useSystem.getSymbol);
const cartList = computed(() => useShop.getSellerList);
const cartNum = computed(() => useShop.getSellerNum);
const selectAllChecked = ref(true);
const shopRef = ref(null);
const footerHeight = ref(0);
const tabbarHeight = ref(0);
const ids = ref([]);
const idsObj = ref({});

const userInfo = computed(() => useUser.getuserInfo);
const token = computed(() => useUser.getToken);
const money = computed(() => {
  if (!cartList.value.length) {
    selectAllChecked.value = false;
  }
  let result = cartList.value.reduce(
    (acc, seller) => {
      const sellerId = seller.seller_id;
      if (idsObj.value[sellerId]) {
        const totalPrice = seller.goods
          .filter((good) => idsObj.value[sellerId].includes(good.id))
          .reduce((sum, good) => sum + parseFloat(good.price) * good.total, 0);
        acc.total_price = (acc.total_price - 0 + (totalPrice - 0)).toFixed(2);
        const totalNum = seller.goods
          .filter((good) => idsObj.value[sellerId].includes(good.id))
          .reduce((sum, good) => sum + good.total, 0);
        acc.total_num = acc.total_num - 0 + (totalNum - 0);
      }
      return acc;
    },
    {
      total_price: 0,
      total_num: 0,
      orginal_price: 0,
    }
  );
  return result;
});
const canCheckout = computed(() => {
  if (!ids.value.length) return false;
  return true;
});
watch(
  () => cartList.value,
  (list) => {
    const hasData = Array.isArray(list) && list.length > 0;
    if (!hasData) {
      selectAllChecked.value = false;
      return;
    }
    nextTick(() => {
      selectAllChecked.value = true;
      selectAllChange(true);
    });
  },
  { immediate: true, deep: true }
);
const selectAllChange = (e) => {
  shopRef.value && shopRef.value.allStatus(e);
};
const getIds = (arr, flag) => {
  ids.value = Object.values(arr).flat(1);
  idsObj.value = arr;
  selectAllChecked.value = flag;
};

const submit = () => {
  if (!canCheckout.value) return;
  uni.navigateTo({
    url: `/pagesBuyer/shop/shopConfirm?comfirmId=${ids.value.join(",")}`,
  });
};

const delCart = () => {
  removeCart();
};

const removeCart = async () => {
  try {
    let id = (ids.value.length && ids.value.join(",")) || "";
    await SELLER_DEL_CART(id);
    useShop.setSellerList();
    shopRef.value && shopRef.value.allStatus(false);
  } catch (error) {
    toast(error.msg);
  }
};
const getHeight = async () => {
  try {
    const res = await query("#footer");
    nextTick(() => {
      footerHeight.value = res.height;
    });
  } catch (error) {}
};
const getTabbarHeight = (height) => {
  tabbarHeight.value = height;
};

onMounted(() => {
  getHeight();
});

onShow(() => {
  token.value && useShop.setSellerList();
  setTimeout(() => {
    getHeight();
  }, 0);
});
</script>

<style lang="less" scoped>
@import url("@/style.less");

.wrap {
  min-height: 100bh;
  background: var(--bg);
  overflow: hidden;
  .flex();
  flex-direction: column;

  :deep(.u-navbar__content) {
    background-color: var(--black) !important;
  }

  .nav_title {
    color: var(--light);
  }

  .nav_right {
    color: var(--primary);
    .size(24rpx);
    font-weight: 500;
  }

  .content {
    flex-grow: 1;
    height: calc(100vh - 44px - var(--height));
    overflow-y: scroll;
    .flex();
    flex-direction: column;

    .cont_wrap {
      flex-grow: 1;
      overflow: hidden scroll;
    }

    .footer {
      .flex_position(space-between);
      flex-wrap: wrap;
      padding: 8px 12px;
      background-color: var(--light);
      box-shadow: 0 -4px 6px #0000000d;
      position: fixed;
      bottom: var(--tabbarHeight);
      // bottom: calc(var(--tabbarHeight) + constant(safe-area-inset-bottom));
      // bottom: calc(var(--tabbarHeight) + env(safe-area-inset-bottom));
      left: 0;
      right: 0;
      box-sizing: border-box;

      &_left {
      }

      &_right {
        .ver();

        .total_info {
          .total_price {
            text-align: right;
            color: var(--red);
            .size();
            font-weight: 700;
            line-height: 48rpx;
          }

          .total_desc {
            color: var(--text-01);
            .size(24rpx);
            line-height: 40rpx;
            text-align: right;

            .icon-font {
              .size();
            }
          }
        }

        .total_btn {
          .size(28rpx);
          font-weight: 700;
          height: 38px;
          margin-left: 16rpx;
          min-width: 180rpx;
          background-color: var(--black);
          color: var(--light);
          border-radius: 16rpx;
          padding: 16rpx 30rpx;
          text-align: center;
        }
      }
    }
  }
}
</style>
