<template>
  <view>
    <view class="car_list">
      <view v-for="(pItem, pIndex) in cartListByGroup" :key="pIndex" style="margin-bottom: 20rpx">
        <view class="business_name" v-if="pItem.products.length !== 0">
          <image @click="selectBussiness(pIndex)" class="checkbox" :src="pItem.checked ? '../../static/icon/checked.png' : '../../static/icon/checkbox.png'"></image>&nbsp;
          {{ pItem.business_name }}
        </view>
        <view class="product_group">
          <view v-for="(item, index) in pItem.products" @longpress="deleteCar(pIndex, index)" :key="index">
            <SwipeAction @clickItem="clickItem" :index="index" ref="swipeAction" :pIndex="pIndex">
              <view class="car_item">
                <view class="check_label" @click="checkedItem(pIndex, index, item.id)">
                  <image class="checkbox" src="@/static/icon/checkbox_disabled.png" style="width: 30rpx; height: 30rpx" v-if="item.product_status !== 0 || item.stock == 0" />
                  <image class="checkbox" :src="item.checked ? '../../static/icon/checked.png' : '../../static/icon/checkbox.png'" v-else></image>
                </view>
                <view class="box_left">
                  <navigator :url="'/pages/product/index?product_id=' + item.product_id">
                    <image class="car_image" :src="item.thumb" mode=""></image>
                    <view class="product_status" v-if="item.product_status !== 0">
                      {{ item.stock == 0 ? "已售罄" : "已下架" }}
                    </view>
                  </navigator>
                </view>
                <view class="box_center">
                  <navigator :url="'/pages/product/index?product_id=' + item.product_id" class="car_name">{{ item.name }}</navigator>
                  <navigator :url="'/pages/product/index?product_id=' + item.product_id" class="car_spec">{{ item.spec }}</navigator>
                  <view v-if="item.promo_title" class="promo_title">{{ item.promo_title }}</view>
                  <navigator :url="'/pages/product/index?product_id=' + item.product_id" class="car_price">
                    <text class="price">￥{{ item.price }}</text>
                    <text class="market_price">￥{{ item.market_price }}</text>
                  </navigator>
                </view>
                <view class="box_right">
                  <view class="buy_num_box">
                    <button class="buy_num_sub" @click="changeQuantity(pIndex, index, -1)" data-eventsync="true">
                      <image class="sub_icon" src="../../static/icon/sub_icon.png" mode=""></image>
                    </button>
                    <input type="number" class="buy_num" placeholder="数量" v-model="item.buy_num" @blur="changeQuantity(pIndex, index, 0)" />
                    <button class="buy_num_add" @click="changeQuantity(pIndex, index, +1)" data-eventsync="true">
                      <image class="add_icon" src="../../static/icon/add_icon.png" mode=""></image>
                    </button>
                  </view>
                </view>
              </view>
            </SwipeAction>
          </view>
        </view>
      </view>
    </view>
    <Empty v-if="cartList.length == 0" text="----- 还没有产品啦 -----" />
    <view class="to_bottom" v-if="cartList.length"> -----到底啦-----</view>
    <view class="bottom_box">
      <view class="check_all_label" @click="checkAll()">
        <image class="checkbox" :src="checkedAll ? '../../static/icon/checked.png' : '../../static/icon/checkbox.png'"></image>
        <text class="checkall">全选</text>
      </view>
      <view class="price_box">
        合计：<text class="price_total">￥{{ priceTotal }}</text>
      </view>
      <view class="to_order" @click="toOrder()">预约</view>
    </view>
  </view>
</template>

<script>
import Empty from "@/components/Empty/Empty.vue";
import SwipeAction from "@/components/SwipeAction/SwipeAction.vue";
export default {
  components: { Empty, SwipeAction },
  data() {
    return {
      // 请求参数
      requestParam: {},
      // 是否全选
      checkedAll: false,
      // 总价
      priceTotal: "0.00",
      // 是否请求中
      isReqing: false,
      //购物车列表
      cartListByGroup: [],
      cartList: [],
    };
  },
  onLoad() {
    // #ifdef MP-WEIXIN
    //分享按钮
    uni.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    // #endif
  },
  onShareAppMessage(obj) {
    // 获取分享信息
    let shareList = getApp().globalData.shareList;
    // 获取分享信息
    let shareObj = {
      title: "药优惠 得积分 兑豪礼",
      path: "/pages/index/index",
      imageUrl: "",
    };
    // 循环列表
    for (let i in shareList) {
      if (shareList[i].pages == "pages/car/index") {
        shareObj.path = shareList[i].path ? shareList[i].path : shareObj.path;
        shareObj.title = shareList[i].title ? shareList[i].title : shareObj.title;
        shareObj.imageUrl = shareList[i].image_url ? shareList[i].image_url : shareObj.imageUrl;
      }
    }
    // 返回分享信息
    return shareObj;
  },
  onShow() {
    // 登录提示
    if (!this.$checkAccess.alterLogin()) return;
    // 请求中，不允许刷新
    if (this.isReqing) return;
    // 设置请求中
    this.isReqing = true;
    // 非全选
    this.checkedAll = 0;
    // 请求列表
    this.$http.request("api/shop_cart/get_list", this.requestParam).then((re) => {
      // 设置非请求中
      this.isReqing = false;
      // 成功结果
      if (re.code == "success") {
        // 赋值

        this.cartListByGroup = this.formatGroupedData(re.data);

        this.cartList = re.data;
        // 计算价格
        this.priceHandler();
      }
    });
  },
  onPullDownRefresh() {
    // 登录提示
    if (!this.$checkAccess.alterLogin()) return;
    // 请求列表
    this.$http.request("api/shop_cart/get_list", this.requestParam).then((re) => {
      if (re.code == "success") {
        // 赋值
        this.cartListByGroup = this.formatGroupedData(re.data);

        this.cartList = re.data;

        // 计算价格
        this.priceHandler();
      }
    });
    uni.stopPullDownRefresh();
  },
  onReachBottom() {},
  methods: {
    // 转换为数组格式
    formatGroupedData(list) {
      const groupedData = list.reduce((result, item) => {
        const { business_id, business_name } = item;

        // 如果该 business_id 的分组不存在，则初始化该分组
        if (!result[business_id]) {
          result[business_id] = {
            business_id,
            business_name,
            products: [],
            checked: false,
          };
        }

        // 将商品添加到对应的 business_id 分组
        result[business_id].products.push(item);

        return result;
      }, {});

      return groupedData;
    },
    //选择商业公司下面的所有商品
    selectBussiness(index) {
      this.cartListByGroup[index].checked = !this.cartListByGroup[index].checked;
      this.cartListByGroup[index].products.forEach((item) => {
        item.checked = this.cartListByGroup[index].checked;
      });
      // 计算价格
      this.priceHandler();
    },
    // 数量调整
    changeQuantity(pIndex, index, number) {
      // 如果不是0.表示两侧按钮点击，0表示输入的修改
      if (number != 0) {
        // 计算个数
        this.cartListByGroup[pIndex].products[index].buy_num = this.cartListByGroup[pIndex].products[index].buy_num + number;
      }
      // 如果大于库存
      if (this.cartListByGroup[pIndex].products[index].buy_num > this.cartListByGroup[pIndex].products[index].stock) {
        // 设置为库存
        this.cartListByGroup[pIndex].products[index].buy_num = this.cartListByGroup[pIndex].products[index].stock;
        // 提示
        uni.showToast({
          title: "购买数量不能大于库存",
          icon: "none",
        });
        return;
      }
      // 如果小于1.设置为1
      if (this.cartListByGroup[pIndex].products[index].buy_num < 1) {
        // 恢复1
        this.cartListByGroup[pIndex].products[index].buy_num = 1;
        // 提示
        uni.showToast({
          title: "数量不可小于1",
          icon: "none",
        });
        return;
      }
      // 请求列表
      this.$http
        .request("api/shop_cart/edit", {
          id: this.cartListByGroup[pIndex].products[index].id,
          buy_num: this.cartListByGroup[pIndex].products[index].buy_num,
        })
        .then((re) => {
          if (re.code == "success") {
            // 计算价格
            this.priceHandler();
          } else {
            uni.showToast({
              title: re.msg,
              icon: "none",
            });
          }
        });
    },
    // 删除购物车
    deleteCar(pIndex, index) {
      uni.showModal({
        title: "是否删除？",
        success: (re) => {
          if (re.confirm) {
            // 请求列表
            this.$http
              .request("api/shop_cart/del", {
                id: this.cartListByGroup[pIndex].products[index].id,
              })
              .then((re) => {
                // 如果删除成功的话
                if (re.code == "success") {
                  this.cartListByGroup[pIndex].products.splice(index, 1);
                  // 计算价格
                  this.priceHandler();
                  if (this.$refs.swipeAction.length) {
                    this.$refs.swipeAction[this.$refs.swipeAction.length - 1]?.reset();
                  }
                }
              });
          } else {
            this.$refs.swipeAction[this.$refs.swipeAction.length - 1]?.reset();
          }
        },
      });
    },
    checkedItem(pIndex, index, product_id) {
      const product = this.cartListByGroup[pIndex].products[index];

      // 如果商品不可选中，直接返回
      if (product.product_status !== 0 || product.stock === 0) {
        return;
      }

      // 切换选中状态
      const isChecked = (product.checked = !product.checked);

      // 找到对应商家组中的商品并更新选中状态
      const productInGroup = this.cartListByGroup[pIndex].products.find((item) => item.id === product_id);
      if (productInGroup) {
        productInGroup.checked = isChecked;
      }

      // 检查该商家组内所有商品是否都已选中
      const checkedBussinessAll = this.cartListByGroup[pIndex].products.every((item) => item.checked);

      // 更新商家组的全选状态
      this.cartListByGroup[pIndex].checked = checkedBussinessAll;

      // 检查是否所有商品都已选中
      let checkedAll = true;
      for (const key in this.cartListByGroup) {
        if (!this.cartListByGroup[key].checked) {
          checkedAll = false;
        }
      }

      // 更新全选状态
      this.checkedAll = checkedAll ? 1 : 0;

      // 计算价格
      this.priceHandler();
    },
    checkAll() {
      // 设置全选/单选
      this.checkedAll = this.checkedAll ? 0 : 1;
      // 循环处理
      for (const index in this.cartListByGroup) {
        this.cartListByGroup[index].checked = this.checkedAll;
        this.cartListByGroup[index].products.forEach((item) => (item.checked = this.checkedAll));
      }
      // 计算价格
      this.priceHandler();
    },
    priceHandler() {
      // 总价格
      let priceTotal = 0;
      // 循环处理
      for (const index in this.cartListByGroup) {
        this.cartListByGroup[index].products.forEach((item) => {
          if (item.checked) {
            priceTotal = this.$decimal.add(priceTotal, this.$decimal.mul(item.price, item.buy_num));
          }
        });
      }
      // 小数点处理
      this.priceTotal = priceTotal.toFixed(2);
    },
    toOrder() {
      // 等待支付的信息
      let waitList = [];
      // 循环处理
      for (let index in this.cartListByGroup) {
        // 如果选中的
        for (const key in this.cartListByGroup[index].products) {
          if (this.cartListByGroup[index].products[key].checked) {
            // 如果库存不足
            if (this.cartListByGroup[index].products[key].buy_num < 1) {
              uni.showToast({ icon: "none", title: "选择的产品至少需要1个" });
              return;
            }
            // 如果库存不足
            if (this.cartListByGroup[index].products[key].buy_num > this.cartListByGroup[index].products[key].stock) {
              uni.showToast({ icon: "none", title: "产品库存不足" });
              return;
            }
            waitList.push(this.cartListByGroup[index].products[key].id);
          }
        }
      }
      // 如果没有选择
      if (!waitList.length) {
        uni.showToast({ icon: "none", title: "请选择需要结算的产品" });
        return;
      }
      // 如果没有选择
      if (waitList.length > 99) {
        uni.showToast({ icon: "none", title: "这么多产品一个预约单写不下哦" });
        return;
      }
      uni.navigateTo({
        url: "/pages/car/order?cart_ids=" + waitList.join(","),
      });
    },
    clickItem(e) {
      this.deleteCar(e.pIndex, e.index);
    },
  },
};
</script>

<style lang="less">
.car_list {
  display: block;
  overflow: hidden;
  margin: 0rpx auto;
  margin-top: 20rpx;
  padding-bottom: 110rpx;
  .business_name {
    padding: 8rpx 10rpx;
    border-bottom: 1px solid #f3f3f3;
    font-size: 32rpx;
    z-index: 1;
    display: flex;
    align-items: center;
    background-color: #fff;
    .checkbox {
      width: 40rpx;
      height: 40rpx;
    }
    .business_icon {
      width: 48rpx;
      height: 48rpx;
      margin-right: 10rpx;
    }
  }
  .car_item {
    height: 180rpx;
    display: block;
    background: #ffffff;
    margin: 0rpx auto;
    padding: 20rpx 0rpx 0;
    position: relative;
    .delete_btn {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      width: 80px;
      background-color: #f44336;
      color: #fff;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .swipe-content {
      transition: transform 0.3s ease;
    }
    .check_label {
      float: left;
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-top: 10rpx;
      padding: 50rpx 20rpx;
      .checkbox {
        float: left;
        width: 40rpx;
        height: 40rpx;
      }
    }
    .box_left {
      float: left;
      width: 140rpx;
      height: 200rpx;
      margin-top: 10rpx;
      position: relative;
      .car_image {
        width: 140rpx;
        height: 140rpx;
        border-radius: 5rpx;
      }
      .product_status {
        position: absolute;
        width: 100%;
        height: 40rpx;
        bottom: 60rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 24rpx;
        background-color: #999999;
      }
    }
    .box_center {
      float: left;
      width: 300rpx;
      margin-left: 25rpx;
      .car_name {
        max-height: 60rpx;
        font-size: 30rpx;
        line-height: 30rpx;
        overflow: hidden;
        white-space: nowrap; /* 不换行 */
        overflow: hidden; /* 隐藏超出的内容 */
        text-overflow: ellipsis; /* 用省略号表示被隐藏的部分 */
      }
      .promo_title {
        max-height: 80rpx;
        font-size: 20rpx;
        line-height: 40rpx;
        overflow: hidden;
        padding: 0rpx 0rpx;
        color: #dd524d;
      }
      .car_spec {
        color: #999999;
        font-size: 24rpx;
        max-height: 60rpx;
        line-height: 60rpx;
        overflow: hidden;
      }
      .car_price {
        font-size: 30rpx;
        line-height: 60rpx;
        .price {
          color: red;
        }
        .market_price {
          font-size: 24rpx;
          color: #999999;
          margin-left: 10rpx;
          padding-left: 10rpx;
          text-decoration: line-through;
          border-left: 2rpx solid #dddddd;
        }
      }
    }
    .box_right {
      float: right;
      width: 185rpx;
      padding-right: 15rpx;
      .buy_num_box {
        float: right;
        color: #333333;
        overflow: hidden;
        font-size: 24rpx;
        margin-top: 70rpx;
        text-align: center;
        .buy_num_sub {
          float: left;
          border: none;
          height: 36rpx;
          background: none;
          text-align: center;
          line-height: 36rpx;
          padding: 10rpx 10rpx;
          .sub_icon {
            width: 22rpx;
            height: 22rpx;
            display: block;
          }
        }
        .buy_num_sub::after {
          border: none;
          background: none;
        }
        .buy_num {
          float: left;
          width: 90rpx;
          height: 36rpx;
          font-size: 24rpx;
          min-height: 36rpx;
          line-height: 36rpx;
          padding: 0rpx 0rpx;
          border-radius: 8rpx;
          border: 2rpx solid #dddddd;
        }
        .buy_num_add {
          float: left;
          border: none;
          height: 36rpx;
          background: none;
          text-align: center;
          padding: 10rpx 10rpx;
          line-height: 36rpx;
          .add_icon {
            width: 22rpx;
            height: 22rpx;
            display: block;
          }
        }
        .buy_num_add::after {
          border: none;
          background: none;
        }
      }
    }
  }
}
.bottom_box {
  z-index: 999;
  left: 0rpx;
  width: 100%;
  height: 100rpx;
  display: block;
  position: fixed;
  overflow: hidden;
  background: #ffffff;
  padding: 0rpx 35rpx;
  bottom: var(--window-bottom);
  .check_all_label {
    float: left;
    width: 120rpx;
    height: 40rpx;
    font-size: 24rpx;
    line-height: 40rpx;
    padding: 30rpx 0rpx;
    .checkbox {
      float: left;
      width: 40rpx;
      height: 40rpx;
    }
    .checkbox.active {
      border: 2rpx solid red;
      .checkbox_active {
        background-color: #e03519;
      }
    }
    .checkall {
      float: left;
      height: 40rpx;
      display: block;
      margin-left: 10rpx;
      line-height: 40rpx;
    }
  }
  .price_box {
    float: left;
    width: 400rpx;
    display: block;
    color: #666666;
    font-size: 26rpx;
    text-align: right;
    line-height: 100rpx;
    margin-right: 20rpx;
    .price_total {
      color: red;
      font-size: 30rpx;
    }
  }
  .to_order {
    float: left;
    width: 140rpx;
    height: 60rpx;
    display: block;
    color: #ffffff;
    font-size: 28rpx;
    margin-top: 20rpx;
    line-height: 60rpx;
    padding: 0rpx 0rpx;
    text-align: center;
    border-radius: 30rpx;
    background-color: #e03519;
  }
}
</style>
