<template>
  <view class="container">
    <!-- 有数据 -->
    <view v-if="shopList.length > 0">
      <view class="topStatus u-flex-center-sb u-plr30" :style="{ top: tabTop + 'px' }">
        <text class="u-1A1A1A u-font30">共{{ totalNum }}件商品</text>
        <text class="u-1A1A1A u-font30" @click="editorBtn">{{
          editorStatus ? "完成" : "编辑"
        }}</text>
      </view>
      <view class="carbox">
        <view class="shopList u-mt20" v-for="(item, index) in shopList" :key="item.businessId">
          <view class="u-flex-center-sb">
            <view class="u-flex-center">
              <view class="check u-mr10" @click="shopChecked(index)">
                <text class="iconfont iconbox u-font32 u-FF0000" v-if="item.flag">&#xe646;</text>
                <view class="radios" v-else></view>
              </view>
              <text class="iconfont3 u-bold u-ml10" style="color: #fa6138">&#xe655;</text>
              <text class="u-1A1A1A u-font30 u-ml15 u-text1 name-width">{{
                item.businessName
              }}</text>
              <text class="u-CCC right-icon iconfont">&#xe6c7;</text>
            </view>
          </view>

          <view class="goodsItem u-border-one-one u-flex-center" v-for="children in item.userShoppingCartList" :key="children.id">
            <view class="check u-mr10" @click="goodsChecked(index, children.id)">
              <text class="iconfont iconbox u-font32 u-FF0000" v-if="children.flag">&#xe646;</text>
              <view class="radios" v-else></view>
            </view>
            <view class="u-goods200 u-ml15 positionRetave">
              <!-- <view
                class="positinAble"
                v-if="!children.goods_valid || !children.sku_valid"
                >已失效</view
              > -->
              <!-- ?x-oss-process=style/w_350 -->
              <image :src="`${children.productCover}`" class="u-goods200" mode="scaleToFill">
              </image>
            </view>
            <!-- u-flex-column-start -->
            <view class="u-flex1 right-box rightText u-ml30">
              <view class="u-text2 u-1A1A1A u-font28">
                <!-- <view class="tipsStatus" v-if="children.platform_store"
                  >自营</view
                >
                <view class="thirdTag" v-if="children.third">第三方</view> -->
                <text>{{ children.productTitle }}</text>
              </view>
              <view class="u-flex-column-start">
                <text class="u-font22 u-999" v-if="children.skuSetName">规格： {{ children.skuSetName }}</text>
                <view class="u-flex-center-sb botPrice">
                  <view class="u-FF0000 u-font32 u-flex1">
                    <rich-text :nodes="$mUtil.priceBigSmall(children.salePrice)"></rich-text>
                  </view>
                  <view class="rightAddRes u-flex-center">
                    <text class="btnTag" @click="resNum(children, children.id)">-</text>
                    <text class="u-flex1 centertext u-font28 u-999">{{
                      children.num
                    }}</text>
                    <text class="btnTag" @click="addNum(children, children.id)">+</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 底部 -->

      <view v-if="ispay" class="botfixed u-flex-center-sb">
        <view class="leftAll u-flex-center" @click="allChecked">
          <view class="check u-mr10">
            <text class="iconfont iconbox u-font32 u-FF0000" v-if="checkAggrement">&#xe646;</text>
            <view class="radios" v-else></view>
          </view>
          <text class="u-ml5 u-font24 u-999">{{
            checkAggrement ? "反选" : "全选"
          }}</text>
        </view>
        <view class="rightP u-flex-center">
          <view class="u-flex-center" v-if="!editorStatus">
            <text class="u-font30 u-333 u-bold">合计：</text>
            <view class="u-FF0000 u-bold">
              <rich-text :nodes="$mUtil.priceBigSmall(totalPrice)"></rich-text>
            </view>
          </view>
          <view class="u-btn-two btnWidth u-ml30" v-if="!editorStatus" @click="surePay">去结算({{ checkNum }})</view>
          <view class="u-btn-two btnWidth u-ml30" v-else @click="delCart">删除</view>
        </view>
      </view>
    </view>

    <!-- 没有数据 -->
    <view class="nogoods u-mt30 u-flex-column-center" v-if="shopList.length == 0">
      <image :src="$handleImageUrl('/common/noGoods.png')" mode="" class="noImg"></image>
      <text class="u-font26 u-999">您的购物车空空如也~</text>
      <view class="btnview" @click="gotoshop">
        <button class="u-DCCDA4 shop-btn u-font30">
          {{ isLogin ? "去逛逛" : "去登录" }}
        </button>
      </view>
    </view>

    <!--页面加载动画-->
    <ldLoading isFullScreen :active="loading"></ldLoading>
  </view>
</template>

<script setup>
import { ref } from "vue";
import { onShow, onLoad } from "@dcloudio/uni-app";
import {
  userShoppingCartList_Api,
  userShoppingCartAdd_Api,
  userShoppingCartDel_Api,
  oneClickClear_Api,
} from "@/api/shop";
import utils from "@/util/index.js";

const totalPrice = ref(0);
const totalNum = ref(0);
const checkNum = ref(0);
const checkAggrement = ref(false);
const loading = ref(false);
const shopList = ref([]);
const arrLenid = ref([]);
const editorStatus = ref(false);
const isLogin = ref(false);
const tabTop = ref(0);
const ispay = ref(true);

const gotoshop = () => {
  if (!utils.isLoginTo(true)) {
    uni.switchTab({
      url: "/pages/tabtar/home",
    });
  }
};

const shopChecked = (index) => {
  shopList.value[index].flag = !shopList.value[index].flag;
  shopList.value[index].userShoppingCartList.forEach((j) => {
    if (shopList.value[index].flag) {
      j.flag = true;
    } else {
      j.flag = false;
    }
  });
  checkTotalNum();
};

const goodsChecked = (index, id) => {
  shopList.value[index].userShoppingCartList.forEach((j) => {
    if (j.id == id) {
      j.flag = !j.flag;
    }
  });
  shopHeightLaign(index);
  checkTotalNum();
};

const allChecked = () => {
  checkAggrement.value = !checkAggrement.value;
  shopList.value.forEach((k) => {
    k.flag = checkAggrement.value;
    k.userShoppingCartList.forEach((j) => {
      j.flag = checkAggrement.value;
    });
  });
  checkTotalNum();
};

const setGoodsNum = (item, type) => {
  // console.log("setGoodsNum", item, type);
  let obj = {
    isSet: true,
    productId: item.productId,
    skuHashCode: item.skuHashCode,
    skuSetName: item.skuSetName,
    num: item.num || 1,
    // effectiveStatus: 1,
    businessId: item.businessId,
  };
  // return;
  // console.log("obj", obj);
  userShoppingCartAdd_Api(obj)
    .then((res) => {
      if (res && res.code == 200) {
        checkTotalNum();
      }
    })
    .catch((err) => {
      item.num = type == "add" ? item.num - 1 : item.num + 1;
    });
};

const resNum = (item, id) => {
  shopList.value.forEach((k) => {
    k.userShoppingCartList.forEach((j) => {
      if (j.id == id) {
        if (j.num > 1) {
          j.num--;
        } else {
          uni.$uv.toast("不能再减了~");
        }
      }
    });
  });
  setGoodsNum(item, "subtract");
};

const addNum = (item, id) => {
  shopList.value.forEach((k) => {
    k.userShoppingCartList.forEach((j) => {
      if (j.id == id) {
        if (j.num >= j.limit_buy_num && j.limit_buy_num > 0) {
          uni.$uv.toast("商品库存只有" + j.limit_buy_num + "件");
        } else {
          j.num++;
        }
      }
    });
  });
  setGoodsNum(item, "add");
};

const editorBtn = () => {
  console.log("editorBtn");
  editorStatus.value = !editorStatus.value;
};

const checkTotalNum = () => {
  checkNum.value = 0;
  let arrLenids = [];
  let total = 0;
  shopList.value.forEach((k) => {
    k.userShoppingCartList.forEach((j) => {
      if (j.flag) {
        arrLenids.push(j.id);
        total += j.salePrice * j.num;
      }
    });
  });
  totalPrice.value = total.toFixed(2);
  arrLenid.value = arrLenids;
  checkNum.value = arrLenids.length;
  if (checkNum.value == totalNum.value) {
    checkAggrement.value = true;
  } else {
    checkAggrement.value = false;
  }
};

const shopHeightLaign = (index) => {
  let arr = [];
  shopList.value[index].userShoppingCartList.forEach((j) => {
    arr.push(j.flag);
  });
  if (arr.indexOf(false) == -1) {
    shopList.value[index].flag = true;
  } else {
    shopList.value[index].flag = false;
  }
};

const getIsHaveOnline = () => {
  return new Promise((resolve, reject) => {
    let arr = [];
    for (let item of shopList.value) {
      for (let el of item.userShoppingCartList) {
        for (let i of arrLenid.value) {
          if (i == el.id) {
            arr.push(el.businessId);
          }
        }
      }
    }
    let value = arr.every((item) => {
      return item == arr[0];
    });
    resolve(value);
  });
};

const surePay = async () => {
  if (arrLenid.value.length > 0) {
    let isBoolean = await getIsHaveOnline();
    if (!isBoolean) return uni.$uv.toast("不支持多店铺商品一起下单");
    let flagKeys = [];
    shopList.value.map((res, i) => {
      res.userShoppingCartList.map((keys, j) => {
        if (keys.flag) {
          if (!keys.skuValid) {
            flagKeys.push("false");
          } else {
            flagKeys.push("true");
          }
        }
      });
    });
    if (flagKeys.indexOf("false") == -1) {
      psotJson();
    } else {
      uni.$uv.toast("已失效的商品不能结算");
    }
  } else {
    uni.$uv.toast("请选择需要购买的商品");
  }
};

const delCart = () => {
  if (arrLenid.value.length > 0) {
    uni.showModal({
      title: "提示",
      content: "确定删除选中的商品？",
      success: function (e) {
        if (e.confirm) {
          userShoppingCartDel_Api(arrLenid.value.toString()).then((res) => {
            if (res && res.code == 200) {
              uni.$uv.toast("删除成功");
              rest();
              cartList();
            }
          });
        }
      },
    });
  } else {
    uni.$uv.toast("请选择需要删除的商品");
  }
};

const rest = () => {
  arrLenid.value = [];
  totalPrice.value = 0;
  checkNum.value = 0;
  checkAggrement.value = false;
};

const cartList = () => {
  loading.value = true;
  userShoppingCartList_Api()
    .then((res) => {
      loading.value = false;
      if (res && res.code == 200) {
        if (res.data.length > 0) {
          let nums = 0;
          let shopLists = [...shopList.value]
          let list = [];
          res.data.forEach((k) => {
            k.flag = false;
            nums += k.userShoppingCartList.length;
            let objs = shopLists.find((item) => item.businessId == k.businessId) || {};

            k.userShoppingCartList.forEach((j) => {
              let obj = objs.userShoppingCartList ? objs.userShoppingCartList.find((item) => item.id == j.id) || {} : {};
              if (obj.flag) {
                j.flag = true;
              } else {
                j.flag = false;
              }
            });
            if (k.userShoppingCartList.length) {
              list.push(k);
            }
          });
          totalNum.value = nums;
          shopList.value = [...list];
          checkAggrement.value = false;
        } else {
          shopList.value = [];
        }
      }
    })
    .catch((err) => {
      loading.value = false;
    });
};

const psotJson = () => {
  let parendArr = [];
  // let childArr = [[], [], [], [], [], [], [], [], []];
  let dataJson = {};
  let businessId = '';
  let num = 0;
  shopList.value.map((res, i) => {
    res.userShoppingCartList.map((keys, j) => {
      if (keys.flag) {
        if (businessId == '') {
          businessId = res.businessId;
        } else {
          if (businessId != res.businessId) {
            num++
          }
        }
        parendArr.push({
          userShoppingCardId: keys.id,
          skuHashCode: keys.skuHashCode,
          productNum: keys.num,
          productId: keys.productId,
        });
      }
    });
  });
  if (num) {
    uni.$uv.toast("不支持多店铺商品一起下单");
    return
  }
  dataJson = {
    shippingMethod: 0, //0物流，10自提
    createOrderDetailBos: parendArr,
    marketingType: 0, //0无活动，1秒杀，2拼团
    orderType: 0,
    channelType: 5,
    exchange: false,
    userUsePoint: true,
    businessId: businessId,
  };
  // console.log(dataJson);
  // return;
  uni.setStorageSync("dataJson", dataJson);
  uni.navigateTo({
    url: "/pages/surePay/surePay",
  });
};

onShow(() => {
  let token = uni.getStorageSync("apiToken");
  if (token) {
    cartList();
    isLogin.value = true;
  } else {
    isLogin.value = false;
  }
});
</script>

<style lang="scss">
page {
  background-color: #f5f5f5;
}

// 宽度相关
.u-goods200 {
  width: 200rpx;
  height: 200rpx;
}

// 原有样式
.shop-btn {
  width: 300rpx;
  height: 86rpx;
  background: #fa6138;
  border-radius: 43rpx;
  font-size: 30rpx;
  color: #fff;
  text-align: center;
  line-height: 86rpx;
  margin-top: 30rpx;
}

.right-icon {
  font-size: 25rpx;
}

.border {
  border-bottom: 3rpx solid #e7e7e7;
}

.right-box {
  display: flex;
  flex-direction: column;
  // align-items: flex-start;
  justify-content: space-between;
}

.name-width {
  max-width: 420rpx;
}

.positionRetave {
  position: relative;

  .positinAble {
    position: absolute;
    width: 200rpx;
    height: 40rpx;
    text-align: center;
    background-color: rgba($color: #000000, $alpha: 0.5);
    color: #fff;
    font-size: 26rpx;
    line-height: 40rpx;
    bottom: 0;
    left: 0;
  }
}

.tipsStatus {
  display: inline-block;
  // width: 102rpx;
  // height: 28rpx;
  padding: 0 10rpx;
  background: #ff0000;
  border-radius: 10rpx 0px 10rpx 0px;
  line-height: 28rpx;
  text-align: center;
  margin-right: 10rpx;
  color: #fff;
  font-size: 20rpx;
}

.thirdTag {
  display: inline-block;
  background: #30b885;
  border-radius: 10rpx;
  line-height: 28rpx;
  text-align: center;
  margin-right: 10rpx;
  padding: 6rpx 10rpx;
  color: #fff;
  font-size: 20rpx;
}

.check {
  position: relative;
  width: 32rpx;
  height: 32rpx;

  .radios {
    width: 30rpx;
    height: 30rpx;
    display: block;
    border: 1px solid #ccc;
    border-radius: 50%;
    position: absolute;
    left: 0;
    top: 0;
    z-index: 1;
  }

  .iconbox {
    position: relative;
    z-index: 2;
  }
}

.topStatus {
  height: 80rpx;
  background-color: #fff;
  position: fixed;
  z-index: 9;

  width: 100%;
  box-sizing: border-box;
}

.goodsItem {
  padding: 60rpx 0;
  border-bottom: 3rpx solid #f7f7f7;
}

.goodsItem:last-child {
  border-bottom: none;
}

.noImg {
  width: 490rpx;
  height: 556rpx;
}

.btnview {
  // width: 300rpx;
  // margin: 30rpx auto 0;
}

.carbox {
  padding: 80rpx 0 160rpx 0;

  .shopList {
    background-color: #fff;
    padding: 30rpx 30rpx 0;
  }
}

.rightText {
  justify-content: space-between;
  // height: 200rpx;
}

.bottext,
.botPrice {
  width: 100%;
}

.bottext {
  margin-top: 36rpx;
}

.rightAddRes {
  width: 172rpx;
  height: 50rpx;
  border-radius: 8rpx;
  border: 1px solid #e5e5e5;

  .centertext {
    text-align: center;
  }

  .btnTag {
    width: 50rpx;
    height: 50rpx;
    line-height: 50rpx;
    text-align: center;
    background-color: #dedede;
    font-size: 46rpx;
    color: #888;
  }
}

.btnWidth {
  width: 208rpx;
}

.botfixed {
  position: fixed;
  background-color: #fff;
  width: 100%;
  height: 138rpx;
  bottom: 0;
  left: 0;
  z-index: 9;
  padding: 0 30rpx;
  box-sizing: border-box;
}
</style>
