<template>
  <view class="drawer-wrapper" v-if="visible">
    <view class="drawer-mask" @click="close"></view>
    <view class="drawer-panel" :style="{ width: panelWidth }">
      <view class="drawer-header">
        <view class="title">
          <trans _t="购物车预览" />
          <text v-if="cartNum"> ({{ cartNum }})</text>
        </view>
        <view class="close" @click="close">
          <up-icon name="close" size="18" color="var(--text)"></up-icon>
        </view>
      </view>
      <view class="tab">
        <Tab
          :active="actvieNum"
          size="24rpx"
          height="80rpx"
          :tabList="tabList"
          @confirm="tabClick"
        />
      </view>
      <view class="drawer-content">
        <shop-model
          :list="cartList"
          ref="shopRef"
          @getIds="getIds"
          :isFree="actvieNum"
          :key="actvieNum"
        />
      </view>

      <view class="drawer-footer">
        <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">
              <text
                >{{ symbol.symbol }} {{ Moneyhtml(money.total_price) }}</text
              >
            </view>
            <view class="total_desc">
              <trans _t="199包邮" v-if="actvieNum == 1" />
              <trans _t="不包括运费" v-else />
            </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>
</template>

<script setup>
import { ref, computed, watch, nextTick } from "vue";
import { useShopStore, useSystemStore, useUserStore } from "@/store";
import { Moneyhtml, systemInfo } from "@/utils";
import shopModel from "./shopModel.vue";
import Tab from "@/components/tabs";
import { t } from "@/locale";
import { onShow } from "@dcloudio/uni-app";

const props = defineProps({
  panelWidth: {
    type: String,
    default: "90vw",
  },
});

const emit = defineEmits(["close", "new-action"]);

const visible = ref(false);
const shopRef = ref(null);
const ids = ref([]);
const idsObj = ref({});
const actvieNum = ref(0);
const tabList = ["代购", "包邮"];

const useUser = useUserStore();
const useShop = useShopStore();
const useSystem = useSystemStore();
const symbol = computed(() => useSystem.getSymbol);
const cartList = computed(() => useShop.getCartList);
const cartNum = computed(() => useShop.getCartNum);
const token = computed(() => useUser.getToken);

const selectAllChecked = ref(true);
const top = systemInfo().statusBarHeight || 0;
const statusBarHeightRef = ref(top);

const headerStyle = computed(() => {
  return {
    paddingTop: `${statusBarHeightRef.value + 10}px`,
  };
});
const canCheckout = computed(() => {
  if (!ids.value.length) return false;
  const total = parseFloat(money.value.total_price || 0);
  if (actvieNum.value === 1) {
    return total >= 199;
  }
  return true;
});
const money = computed(() => {
  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;
});

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 open = () => {
  visible.value = true;
  // 默认全选
  nextTick(() => {
    selectAllChange(true);
  });
};
const close = () => {
  visible.value = false;
  emit("close");
};

const getIds = (arr, flag) => {
  ids.value = Object.values(arr).flat(1);
  idsObj.value = arr;
};

const onNewAction = () => {
  // 默认行为：关闭抽屉；也向外发出事件供页面自定义
  emit("new-action");
  close();
};
const tabClick = (item, index) => {
  if (actvieNum.value == index) return;
  actvieNum.value = index;
  useShop.setCartList(index);
};
const submit = () => {
  if (!canCheckout.value) return;
  close();
  uni.navigateTo({
    url: `/pages/shop/shopConfirm?comfirmId=${ids.value.join(",")}&isFree=${
      actvieNum.value
    }`,
  });
};
onShow(() => {
  token.value && useShop.setCartList(actvieNum.value);
});
defineExpose({ open, close });
</script>

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

.drawer-wrapper {
  position: fixed;
  inset: 0;
  z-index: 9999;
}

.drawer-mask {
  position: absolute;
  inset: 0;

  background: rgba(0, 0, 0, 0.4);
}

.drawer-panel {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  width: 90vw;
  max-width: 720rpx;
  background: var(--bg);
  display: flex;
  flex-direction: column;
  box-shadow: -8rpx 0 24rpx rgba(0, 0, 0, 0.14);
  animation: slideIn 0.2s ease;
  /*  #ifdef  APP-PLUS  */
  padding-top: 88rpx;
  /*  #endif  */
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
  }
  to {
    transform: translateX(0);
  }
}

.drawer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 24rpx;
  background: var(--light);
  border-bottom: 1px solid #eee;

  .title {
    .size(28rpx);
    font-weight: 700;
    color: var(--text);
  }
  .close {
    padding: 8rpx;
  }
}

.drawer-content {
  flex: 1;
  overflow: hidden auto;
  padding: 16rpx;
}

.drawer-footer {
  background: var(--light);
  border-top: 1px solid #eee;
  padding: 16rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
  .footer_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;
    }
  }

  .actions {
    display: flex;
    align-items: center;
    gap: 12rpx;

    .btn {
      .size(26rpx);
      font-weight: 700;
      height: 72rpx;
      padding: 0 28rpx;
      border-radius: 16rpx;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      white-space: nowrap;
    }
    .new {
      background: #f2f3f5;
      color: var(--text);
    }
    .checkout {
      background: var(--black);
      color: var(--light);
    }
  }
}
</style>
