<template>
  <div class="order-confirm-con">
    <div class="content-scroll">
      <!-- <order-addr
        :data="orderInfo"
        :delivery.sync="delivery"
        @select="showAddr = true"
      /> -->
      <order-goods-item
        v-for="(item, index) of orderInfo.goodsMap"
        :key="`shop-item-${index}`"
        :data="item"
      />
      <order-info
        :total="total"
        @couponSelect="showCoupon = true"
        :couponList="couponList"
        :promotionList="promotionList"
        :orderTypeMap="orderTypeMap"
        :orderTypeObj="orderTypeObj"
      />
      <!-- <div class="invoice-con common flex-default">
        <div class="left">发票</div>
        <div class="right flex-default">
          <div class="text">电子</div>
          <m-icon icon="icon-more-light" className="more" :size="10" />
        </div>
      </div> -->
      <div class="empty" />
    </div>

    <div class="submit-con flex-default">
      <div class="text">实付款</div>
      <m-price class="price" :amt="total.price" />
      <div class="button" @click="handleSubmit">提交订单</div>
    </div>

    <addr-select-popup
      ref="addrSelectPopup"
      v-model="showAddr"
      :defaultSelect="orderInfo.selectAddrIndex"
      @confirm="handleAddrSelect"
    />
    <coupon-select-popup
      v-model="showCoupon"
      :goods="orderInfo.goodsMap"
      :list="couponList"
      @confirm="handleCouponConfirm"
    />
  </div>
</template>

<script>
import OrderAddr from "./order-addr";
import OrderGoodsItem from "./order-goods-item";
import OrderInfo from "./order-info";
import AddrSelectPopup from "@/components/addr-select-popup.vue";
import CouponSelectPopup from "./coupon-select-popup";
import { mapState, mapGetters, mapMutations } from "vuex";
import { expressCalc, promotionCalc } from "@/utils/mallCalc.js";
import { OrderConfirmType, OrderConfirmTypeObj,SalesType } from "@/enums";
export default {
  components: {
    OrderAddr,
    OrderGoodsItem,
    OrderInfo,
    AddrSelectPopup,
    CouponSelectPopup,
  },
  data() {
    return {
      showAddr: false,
      showCoupon: false,
      templateMap: {},
      delivery: false,
      disable: false,
      couponList: [],
      couponSelectList: [],
      promotionList: [],
      extData: {},
    };
  },
  computed: {
    ...mapState(["orderInfo", "shoppingCartCheckedList"]),
    addrLabel() {
      if (this.orderInfo.selectAddr) {
        return `${this.orderInfo.selectAddr.province}${this.orderInfo.selectAddr.city}${this.orderInfo.selectAddr.county}${this.orderInfo.selectAddr.street}`;
      } else {
        return "请填写地址";
      }
    },
    total() {
      let originalPrice = 0,
        price = 0,
        weight = 0,
        express = 0,
        coupon = 0,
        promotion = 0,
        goodsMap = {};

      for (let shop in this.orderInfo.goodsMap) {
        let shopOriginalPrice = 0,
          shopPrice = 0,
          shopWeight = 0,
          shopNum = 0;
        for (let sku of this.orderInfo.goodsMap[shop].skuList) {
          shopOriginalPrice += sku.originalPrice * sku.num;
          shopPrice += sku.price * sku.num;
          shopWeight += sku.weight * sku.num;
          shopNum += sku.num;
          goodsMap[sku.skuId] = { ...sku };
        }
        originalPrice += shopOriginalPrice;
        weight += shopWeight;
        let expressAdd = expressCalc(
          shopOriginalPrice,
          shopWeight,
          shopNum,
          this.templateMap[shop]
        );
        express += expressAdd;
      }

      express = this.delivery ? express : 0;
      this.couponSelectList.forEach((c) => {
        coupon += c.couponVal;
      });
      promotion = promotionCalc(goodsMap, this.promotionList);

      price = originalPrice + express - coupon - promotion;
      if (price < 0) {
        price = 0;
      }

      originalPrice = originalPrice.toFixed(2);
      weight = weight.toFixed(2);
      express = express.toFixed(2);

      return {
        originalPrice,
        price,
        weight,
        express,
        coupon,
        promotion,
      };
    },

    skuIdList() {
      let ret = [];
      let obj = this.orderInfo.goodsMap;
      Object.keys(obj).forEach((key) => {
        let arr = obj[key].skuList.map((s) => s.skuId);
        ret = ret.concat(arr);
      });

      return ret;
    },
    orderTypeObj() {
      let salesType=this.orderInfo.salesType || 1
      let obj = OrderConfirmTypeObj[salesType][this.orderInfo.type];
      return obj || OrderConfirmTypeObj[salesType][OrderConfirmType.NORMAL];
    },
    orderTypeMap() {
      let map = {};
      Object.keys(OrderConfirmType).forEach((key) => {
        map[key] = this.orderInfo.type == OrderConfirmType[key];
      });
      return map;
    },
  },
  methods: {
    ...mapMutations(["setOrderInfo", "setOrderInfoAddr"]),
    requestData() {
      let genEmptyP = () => {
        return new Promise((resolve, reject) => {
          resolve();
        });
      };
      this.$showLoading();
      let p1 = this.requestDistribution();
      let p2 = this.orderTypeObj.comm.coupon
        ? this.requestCoupon()
        : genEmptyP();
      let p3 = this.orderTypeObj.comm.promotion
        ? this.requestPromotion()
        : genEmptyP();
      Promise.all([p1, p2, p3]).then(this.$hideLoading);
    },
    requestDistribution() {
      let func = (resolve, reject) => {
        if (this.orderInfo.selectAddr) {
          let area = this.orderInfo.selectAddr.provinceCode;
          let mIdList = Object.keys(this.orderInfo.goodsMap);
          let len = mIdList.length;
          let flag = 0;
          mIdList.forEach((merchantId) => {
            this.$api({
              apiName: "getGoodsDistribution",
              postData: {
                area,
                merchantId,
              },
              success: (res) => {
                this.$set(this.templateMap, merchantId, res);
                ++flag == len && resolve();
                if (
                  res &&
                  res.distributionTemplateItem &&
                  res.distributionTemplateItem.pricingType == 5
                ) {
                  this.disable = true;
                  this.$toast("暂不支持该地区下单！");
                } else {
                  this.disable = false;
                }
              },
              error: (err) => reject(err),
              failed: (err) => reject(err),
            });
          });
        } else {
          resolve();
        }
      };

      return new Promise(func);
    },
    requestCoupon() {
      return new Promise((resolve, reject) => {
        this.$api({
          apiName: "getGoodsCouponList",
          postData: this.skuIdList,
          success: (res) => {
            this.couponList = res;
            resolve(res);
          },
          error: (err) => reject(err),
          failed: (err) => reject(err),
        });
      });
    },
    requestPromotion() {
      return new Promise((resolve, reject) => {
        this.$api({
          apiName: "getPromotionList",
          postData: this.skuIdList,
          success: (res) => {
            this.promotionList = res;
            resolve(res);
          },
          error: (err) => reject(err),
          failed: (err) => reject(err),
        });
      });
    },

    handleAddrSelect(selectAddrIndex, selectAddr) {
      this.setOrderInfoAddr({
        selectAddrIndex,
        selectAddr,
      });
      this.$showLoading();
      this.requestDistribution().then(this.$hideLoading);
    },
    handleCouponConfirm(list) {
      this.couponSelectList = list;
    },
    deleteSubmit() {
      this.$api({
        apiName: "delShoppingCartList",
        postData: this.shoppingCartCheckedList,
        success: (res) => {
          this.$store.dispatch("getShoppingCart");
        },
      });
    },
    handleSubmit() {
      if (this.disable) {
        return;
      }
      this.$showLoading();
      let { selectAddr, goodsMap,salesType } = this.orderInfo;
      let goodsIdCouponVos = this.couponSelectList.map((c) => c.couponId);
      let merchantGoodsVos = [];
      let goodsId=""
      Object.keys(goodsMap).forEach((shop) => {
        let orderSkuVos = [];
        let { vnote, merchantId } = goodsMap[shop];
        goodsMap[shop].skuList.forEach((sku) => {
          if(salesType===SalesType.BLINDBOX){
            goodsId=sku.goodsId
          }
          let { num, skuId } = sku;
          orderSkuVos.push({
            num,
            skuId,
          });
        });
        merchantGoodsVos.push({
          merchantId,
          orderSkuVos,
          vnote,
        });
      });

      let postData = {
        delivery: this.delivery ? 1 : 0,
        orderType: 1,
        merchantGoodsVos,
        goodsIdCouponVos,
      };
      if(salesType===SalesType.BLINDBOX){
        postData.goodsId=goodsId
        postData.delivery=0
      }else{
        if (this.orderTypeMap.TRANSFER) {
          let key = Object.keys(this.orderInfo.goodsMap)[0];
          postData.number = this.orderInfo.goodsMap[key].skuList[0].num;
          postData.tranId = this.orderInfo.extData.tranId;
        }
      }
      this.$api({
        apiName: this.orderTypeObj.api,
        postData,
        success: (res) => {
          this.$hideLoading();
          if (this.orderInfo.fromType === "shoppingCart") {
            this.deleteSubmit();
          }
          let pid = res,
            type = this.orderInfo.type;
          if (this.orderTypeMap.TRANSFER) {
            pid = res.payId;
          }
          let query = { pid, type };
          this.$router.replace({ name: "payment", query });
        },
        complete: () => {
          this.$hideLoading();
        },
      });
    },
  },
  mounted() {
    this.requestData();
  },
};
</script>

<style lang="less">
.order-confirm-con {
  background: #f5f7fb;
  height: 100%;

  .content-scroll {
    height: ~"calc(100% - 50px)";
    overflow-y: auto;
  }

  .common {
    padding: 16px;
    background: #ffffff;
    border-radius: 10px;
    margin-bottom: 10px;
    color: #2b2b3a;
  }

  .invoice-con {
    align-items: center;
    justify-content: space-between;

    .left {
      font-weight: bold;
      font-size: 14px;
    }

    .right {
      align-items: center;
    }

    .right .text {
      font-size: 13px;
      margin-right: 6px;
    }
  }

  .empty {
    width: 100%;
    height: 1px;
  }

  > .submit-con {
    // position: fixed;
    // bottom: 0;
    // left: 0;
    width: 100%;
    background: #ffffff;
    box-shadow: 0px 1px 14px 0px #efeff1;
    padding: 6px 16px;
    align-items: flex-end;
    height: 50px;

    .text {
      font-size: 14px;
      font-weight: bold;
      color: #2b2b3a;
      margin-right: 7px;
      line-height: 18px;
    }

    > .price {
      flex: 1;
    }

    .button {
      width: 96px;
      height: 36px;
      background: linear-gradient(295deg, #488FF7 0%, #2C66F5 100%);
      border-radius: 22px;
      line-height: 36px;
      color: #ffffff;
      text-align: center;
      font-size: 14px;
    }
  }
}
</style>
