<template>
  <view>
    <cu-navbar class="cu-navbar" :background="{ background: '#f5f5f5' }" :border-bottom="false" :isBack="false" :title="`购物车(${cartList.length})`">
      <view slot="left" class="flex items-center pl-base text-xl font-medium text-txBase font-extrabold">
        <!-- 左边返回箭头 -->
        <view class="w-20rpx flex items-center mr-10rpx" @tap="back">
          <image class="w-20rpx" src="/static/images/user/left_arrow.png" mode="widthFix"></image>
        </view>
        <!-- <view>购物车<text class="text-md">({{ cartList.length }})</text></view> -->
      </view>
      <!-- <view slot="right" class="mx-base relative" @tap="$u.route('/pageA/news/index')">
        <u-icon name="chat" size="48"></u-icon>
        <u-badge :is-dot="true" size="16" :offset="[0, 2]" type="warning"></u-badge>
      </view> -->
      <view class="pl-base text-xl font-medium text-txBase" @tap="changeEdit">{{ navBarLeftText }}</view>
    </cu-navbar>
    <!-- 已登录 -->
    <block v-if="cartList.length > 0">
      <view class="bg-white rounded-xs card mx-base">
        <block v-for="(item, index) in cartList" :key="item.id">
          <cart-goods-item
            :data="item"
            :goods="item.sku"
            :disabled-input="true"
            :selected="isSelect(item)"
            @select="onSelect"
            @tap="onGoodsClick"
            @num-change="onNumChange"
            :isEdit="isEdit"
          ></cart-goods-item>
          <u-line color="#E5E5E5" v-if="index != cartList.length - 1" />
        </block>
      </view>
      <view class="fixed inset-x-0 bg-white px-18rpx py-20rpx bottom-card z-99">
        <view class="flex w-full items-end">
          <view class="flex items-end">
            <view class="flex items-center" @tap="selectAll = !selectAll">
              <image v-if="selectAll" class="w-32rpx h-32rpx flex-none mr-17rpx" src="/static/images/cart/check-round-fill.png" mode="scaleToFill" />
              <image v-else class="w-32rpx h-32rpx flex-none mr-17rpx" src="/static/images/cart/check-round.png" mode="scaleToFill" />
              <text class="text-lg">全选</text>
            </view>
            <view class="ml-30rpx">
              <text>共 {{ selectedCart.length }} 件</text>
            </view>
          </view>
          <block v-if="isEdit">
            <view class="flex-1"></view>
            <view>
              <view :disabled="selectedCart.length == 0" class="btn btn-primary rounded-full text-lg px-30rpx py-10rpx" @tap="delShow = true">
                移除
              </view>
            </view>
          </block>
          <block v-else>
            <view class="flex-1 text-right text-xl mr-20rpx">
              <text>合计:</text>
              <text class="text-txSvip">￥{{ calculate.amount }}</text>
            </view>
            <view>
              <view @tap="onSubmit" class="btn btn-primary rounded-full text-lg px-30rpx py-10rpx"> 确认下单 </view>
            </view>
          </block>
        </view>
      </view>
      <view class="box-shdow inset-x-0 h-2rpx fixed bottom-card z-99"></view>

      <view class="h-148rpx"></view>
    </block>
    <!-- 未登录 -->
    <block v-else>
      <view class="flex items-center justify-center flex-col bg-white py-100rpx">
        <image src="/static/images/cart/empty-cart.png" class="w-300rpx h-254rpx" mode="scaleToFill" />
        <view class="text-txGray text-md">购物车是空的</view>
      </view>
    </block>

    <!-- 删除提示 -->
    <cu-modal
      v-model="delShow"
      :content="`确定要删除${selectedCart.length}种商品吗？`"
      show-cancel-button
      async-close
      @confirm="delConfirm"
    ></cu-modal>
  </view>
</template>
<script>
import CartGoodsItem from '@/pages/shop_cart/components/cart-goods-item.vue';
import { add, mcl } from '@/utils';
export default {
  components: {
    CartGoodsItem,
  },
  data() {
    return {
      mid: '',
      delShow: false,
      isEdit: false,
      calculate: {
        amount: 0,
      },

      cartList: [],
      selectedCart: []
    };
  },
  onLoad(e) {
    this.mid = e.mid
    this.getCartList()
  },
  computed: {
    navBarLeftText() {
      return this.isEdit ? '完成' : '管理';
    },
    selectAll: {
      set(val) {
        this.selectedCart = val ? this.cartList.map(item => item.id) : []
        this.getCalculateAmount()
      },
      get() {
        return this.cartList.length > 0 && this.cartList.length == this.selectedCart.length;
      },
    },

    height() {
      const { windowHeight, statusBarHeight } = this.$u.sys();
      return windowHeight - statusBarHeight - 44 + 'px';
    },
  },
  methods: {
    getCartList() {
      uni.showLoading()
      this.$store.dispatch('storeCart/getCartList', { mid: 1 }).then(res => {
        this.cartList = res
        uni.hideLoading()
      })
    },
    //结算
    onSubmit() {
      if (this.selectedCart.length == 0) return this.$u.toast('请选择需要结算的商品');
      const cart = this.cartList.filter(item => this.selectedCart.indexOf(item.id) >= 0)
      const params = { store_id: this.mid, products: cart.map(item => {
        return {
          sku_id: item.id,
          quantity: item.quantity,
          send: item.quantity
        }
      })}
      uni.showLoading()
      this.$api.post(`/v1/order-pre`, params).then(res => {
        uni.hideLoading()
        this.$store.dispatch('storeCart/clear');
        this.$u.route('/pageB/code/index', { id: res.order_pre })
      })
    },
    // 数量改变
    onNumChange(value, id) {
      if (isNaN(value)) return;
      this.$store.dispatch('storeCart/update', { id, number: value }).then(res => {
        this.cartList = this.cartList.map(item => {
          if (item.id == id) {
            item.quantity = value
          }
          return item
        })
        this.getCalculateAmount()
      })
    },
    // 移除购物车
    delConfirm() {
      if (this.selectedCart.length == 0) return this.$u.toast('您还未选择商品哦');
      this.$store.dispatch('storeCart/delete', { id: this.selectedCart }).then(res => {
        this.delShow = false
        this.cartList = this.cartList.filter(item => this.selectedCart.indexOf(item.id) === -1)
        this.selectedCart = []
      })
    },
    // 编辑
    changeEdit() {
      this.isEdit = !this.isEdit;
    },
    // 复选框
    onSelect(id, selected) {
      if (selected) {
        this.selectedCart.push(id)
      } else {
        const index = this.selectedCart.indexOf(id)
        if (index >= 0) {
          this.selectedCart.splice(index, 1)
        }
      }
      this.getCalculateAmount()
    },
    // 商品点击
    onGoodsClick(e) {
      return false;
    },
    // 计算价格
    getCalculateAmount() {
      const { is_vip } = this.$store.getters?.user ?? false;
      const amount = this.cartList.reduce((pr, cu) => {
        if (this.selectedCart.findIndex((e) => e == cu.id) >= 0) pr = add(mcl(is_vip ? cu.sku.vip_price : cu.sku.sell_price, cu.quantity), pr);
        return pr;
      }, 0);
      this.calculate.amount = amount;
    },
    //是否勾选
    isSelect({ id }) {
      return this.selectedCart.some((item) => item == id);
    },
    back() {
      uni.navigateBack({
        delta: 1,
      });
    },
  }
};
</script>
<style lang="scss" scoped>
.card {
  box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.08);
}

.bottom-card {
  box-shadow: 0px -4rpx 8rpx rgba(0, 0, 0, 0.25);
  bottom: var(--window-bottom);
}

.bottom-h {
  padding: var(--window-bottom);
}

.box-shdow {
  box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.25);
  background: #ffffff;
}
</style>
