<template>
  <div class="shopping-cart-con flex-default">
    <div class="header-title">购物车</div>
    <div class="header flex-default">
      <div class="edit" v-if="mode === 'settlement'" @click="mode = 'normal'">
        编辑
      </div>
      <div class="confirm" v-else @click="mode = 'settlement'">完成</div>
    </div>
    <mescroll-vue
      class="goods-scroll"
      ref="mescrollRef"
      @init="mescrollInit"
      :down="downOptions"
      :up="upOptions"
    >
      <!-- <div class="empty-top" /> -->
      <div v-if="showList" class="list-con-wrap">
        <shop-item
          class="shop-item"
          v-for="(item, index) of effectiveList"
          @changeShops="changeShops"
          :key="`effectiveList-${index}`"
          :shopData="item"
          :shopIndex="index"
          listType="effectiveList"
          :mode="mode"
        />
        <div class="tips" v-if="invalidList && invalidList.length > 0">
          失效商品
        </div>
        <shop-item
          class="shop-item"
          v-for="(item, index) of invalidList"
          :key="`invalidList-${index}`"
          :shopData="item"
          :shopIndex="index"
          listType="invalidList"
          :mode="mode"
        />
      </div>
      <!-- <div class="empty-bottom" /> -->
    </mescroll-vue>
    <shopping-footer
      :getFooterData="getFooterData"
      @buy="confirmBuy"
      @deleteSubmit="deleteSubmit"
      @changeRadio="changeRadio"
      :mode="mode"
      :allChecked="allChecked"
    />
  </div>
</template>
<script>
import ShoppingFooter from "./shopping-footer.vue";
import ShopItem from "./shop-item.vue";
import { mapState, mapGetters, mapMutations } from "vuex";
import { MathADD, MathMul } from "@/utils";
import { MescrollMixin } from "@/mixins";
export default {
  mixins: [MescrollMixin],
  components: {
    ShopItem,
    ShoppingFooter,
  },
  data() {
    return {
      mode: "settlement",
      downOptions: {
        autoShowLoading: false,
        auto: true,
        callback: this.downCallback,
      },
      upOptions: {
        auto: false,
        textNoMore: " ",
        use: true,
        callback: this.upCallback,
      },
      checkedList: [],
      effectiveList: [], // 有效
      invalidList: [], //
      loading: false,
      showList: true,
      selectAddrList: [],
    };
  },
  watch: {
    shoppingCart() {
      this.getData();
    },
  },
  computed: {
    ...mapState(["shoppingCart", "shoppingCartCheckedList"]),
    getFooterData() {
      let obj = {
        price: 0,
        num: 0,
      };
      let price = 0;
      if (this.effectiveList instanceof Array) {
        for (let item of this.effectiveList) {
          if (item.listData instanceof Array) {
            for (let goods of item.listData) {
              if (goods.isChecked) {
                obj.num++;
                obj.price = MathADD(
                  obj.price,
                  MathMul(goods.number || 0, goods.amount || 0)
                );
              }
            }
          }
        }
      }
      return obj;
    },
    allChecked() {
      if (this.effectiveList && this.effectiveList.length > 0) {
        return this.effectiveList.every((x) => {
          return x.isChecked;
        });
      } else {
        return false;
      }
    },
  },
  methods: {
    ...mapMutations(["setOrderInfo", "setShoppingCartCheckedList"]),
    requestDataAddress() {
      this.$api({
        apiName: "getAddrList",
        success: (res) => {
          this.selectAddrList = res;
        },
      });
    },
    getData() {
      this.checkedList = this.shoppingCartCheckedList;
      let effectiveList = [];
      let invalidList = [];
      if (this.shoppingCart && this.shoppingCart.length > 0) {
        effectiveList = this.shoppingCart.filter((x) => {
          return x.stock > 0;
        });
        invalidList = this.shoppingCart.filter((x) => {
          return x.stock === 0;
        });
        this.effectiveList = this.getArrayList(effectiveList);
        this.invalidList = this.getArrayList(invalidList);
        this.mescroll.endBySize(
          this.shoppingCart.length,
          this.shoppingCart.length
        );
      } else {
        this.effectiveList = [];
        this.invalidList = [];
        this.mescroll.endBySize(0, 0);
      }
    },
    getArrayList(list, type) {
      let arr = [];
      if (list && list.length > 0) {
        for (let item of list) {
          if (item.stock < item.number) {
            item.number = item.stock;
          }
          if (
            arr.find((x) => {
              return x.merchantId === item.merchantId;
            })
          ) {
            if (this.checkedList && this.checkedList.length > 0) {
              item.isChecked = this.checkedList.includes(item.skuId);
            } else {
              item.isChecked = false;
            }
            let itemData = arr.find((x) => {
              return x.merchantId === item.merchantId;
            });
            itemData.listData.push(item);
            itemData.isChecked = itemData.listData.every((x) => {
              return x.isChecked;
            });
          } else {
            if (this.checkedList && this.checkedList.length > 0) {
              item.isChecked = this.checkedList.includes(item.skuId);
            } else {
              item.isChecked = false;
            }
            let obj = {
              enterpriseName: item.enterpriseName,
              merchantId: item.merchantId,
              isChecked: false,
              listData: [item],
            };
            obj.isChecked = obj.listData.every((x) => {
              return x.isChecked;
            });
            arr.push(obj);
          }
        }
      }

      return arr;
    },
    downCallback() {
      this.mescroll.resetUpScroll();
    },
    upCallback() {
      if (this.hasLogin) {
        this.$store.dispatch("getShoppingCart");
        this.checkedList = this.shoppingCartCheckedList;
        this.getData();
        this.requestDataAddress();
      } else {
        this.mescroll.endBySize(0, 0);
      }
    },
    changeShops(obj) {
      this.$set(this.effectiveList, obj.shopIndex, obj.data);
    },
    changeRadio() {
      let checkedList = [];
      if (!this.allChecked) {
        for (let item of this.shoppingCart) {
          if (item.stock > 0) {
            checkedList.push(item.skuId);
          }
        }
      }
	    this.setShoppingCartCheckedList(checkedList)
      this.getData();
    },
    deleteSubmit() {
      this.checkedList = this.shoppingCartCheckedList;
      if (this.checkedList.length === 0) return;
      if (this.loading) return;
      this.loading = true;
      this.$api({
        apiName: "delShoppingCartList",
        postData: this.checkedList,
        success: (res) => {
          this.loading = false;
          this.$store.dispatch("getShoppingCart");
          this.getData();
        },
      });
    },
    confirmBuy() {
      let skuList = [];
      let selectAddrIndex = 0;
      let selectAddr = null;
      for (let shop of this.effectiveList) {
        if (shop.listData && shop.listData.length > 0) {
          for (let goods of shop.listData) {
            if (goods.isChecked) {
              goods.thumb = goods.picture;
              goods.originalPrice = goods.amount;
              goods.num = goods.number;
              goods.skuProps = goods.goodSkuProp;
              goods.merchantName = goods.enterpriseName;
              skuList.push(goods);
            }
          }
        }
      }
      if (this.selectAddrList.length > 0) {
        selectAddr = this.selectAddrList[0];
      }
      this.setOrderInfo({
        selectAddrIndex,
        selectAddr,
        skuList,
        fromType: "shoppingCart",
      });
	  this.$router.push({name: "order-confirm"})
    },
  },
};
</script>

<style lang="less">
.shopping-cart-con {
  // height: 100vh;
  background: #f5f7fb;
  flex-direction: column;
  > .header-title{
	  width: 100%;
	  height: 45px;
	  line-height: 45px;
	  text-align: center;
	  background: #ffffff;
	  font-size: 16px;
	  font-weight: bold;
  }
  > .header {
    // position: absolute;
    width: 100%;
    height: 30px;
    // top: 0;
    // left: 0;
    background: #ffffff;
    align-items: center;
    justify-content: flex-end;
    padding: 0 16px;
    z-index: 2;
    box-shadow: 0px 3px 5px 0px rgba(243, 243, 243, 1);
    margin-bottom: 10px;

    .edit,
    .confirm {
      font-size: 14px;
    }

    .normal {
      color: #140603;
    }

    .confirm {
    }
  }

  > .goods-scroll {
    // height: 100%;
    width: 100%;
    flex: 1;
  }

  > .goods-scroll {
    .empty-top {
      height: 10px;
    }
  }
  .list-con-wrap {
    .tips {
      margin: 0 0 5px;
      padding: 0 16px;
      font-size: 16px;
    }
  }
}
</style>
