<template>
  <div class="confirm">
    <!-- 地址 -->
    <div class="confirm-header" @click="handleToAddress">
      <div class="confirm-header__left">
        <img src="https://img.lkbang.net/xcx/addr-icon.png" />
      </div>
      <div v-if="orderInfo.addrReceiverInfo" class="confirm-header__middle">
        <span>{{ orderInfo.addrReceiverInfo.addrFullName || '' }}</span>
        <span>
          {{ orderInfo.addrReceiverInfo.receiverName || '' }}
          {{ orderInfo.addrReceiverInfo.receiverPhoneNo || '' }}
        </span>
      </div>

      <div v-else class="confirm-header__middle">
        <span class="no-addr">请添加收货地址信息</span>
      </div>
      <span class="confirm-header__right iconfont icon-arrow" />
    </div>
    <div class="confirm-body">
      <div v-for="(item, idx) in orderInfo.shopSkuList" :key="idx" class="confirm-goods">
        <img class="confirm-goods__left" :src="item.skuImg" />
        <div class="confirm-goods__middle">
          <div class="Cg-middle__title">
            <span class="Cg-middle__name"> {{ item.skuName }} </span>
            <span class="Cg-middle__price">¥{{ item.salePrice || '0.00' }}</span>
          </div>
          <div class="Cg-middle__sku">
            <div>{{ item.skuAttr }}</div>
          </div>
        </div>
      </div>
    </div>
    <template v-if="orderInfo.calcFeeInfo.totalSkuFee !== '0.00'">
      <FeeInfo
        :coupon-activity-info-list="orderInfo.couponActivityInfoList"
        :calc-fee-info="orderInfo.calcFeeInfo"
        @coupon-show="handleCouponShow"
      />
    </template>
    <!-- 底部 -->
    <bottom-nav
      v-if="orderInfo.shopSkuList.length"
      type="submitOrder"
      :info="orderInfo.calcFeeInfo"
      @buy="handleBuy"
    />
    <cr-popup v-model="isCoupon" closeable round position="bottom">
      <coupon-list
        ref="couponList"
        :coupon-id="couponId"
        :goods-info="orderInfo.shopSkuList"
        :coupon-type="couponType"
        :coupon-activity-info-list="orderInfo.couponActivityInfoList"
        @coupon-select="handleSelectCoupon"
      />
    </cr-popup>
  </div>
</template>

<script>
import order from '@/api/order.api';
import bottomNav from '@/components/bottomNav';
import couponList from '@/components/coupon-list';
// import stepper from '@/components/sample';
import localStorage from '@/service/localStorage.service';
import historyRecordMixins from '@/mixins/historyRecord.mixins';
import FeeInfo from './components/feeInfo.vue';
import { DISCOUNT, FREIGHT, CASH, REDUCTION, HAS_DISCOUNT } from '@/constants/order';
import cookies from '@/service/cookieStorage.service';
export default {
  name: 'CreateOrder',
  components: {
    bottomNav,
    // stepper,
    couponList,
    FeeInfo
  },
  mixins: [historyRecordMixins],
  data() {
    return {
      query: {},
      prevCanAdd: true,
      isOutBuy: false,
      couponType: 1,
      isCoupon: false,
      orderData: {},
      hasDiscount: HAS_DISCOUNT,
      couponId: 0,
      selectCoupon: [],
      orderInfo: {
        addrReceiverInfo: {},
        couponActivityInfoList: [],
        calcFeeInfo: {},
        invalidSkuList: [],
        shopSkuList: []
      }
    };
  },
  mounted() {
    this.init();
  },
  activated() {
    this.init();
  },
  methods: {
    init() {
      const orderData = localStorage.get('orderData') || {};
      if (orderData) {
        this.orderData = orderData;
        this.getConfirmOrderInfo();
      }
      const orderAdder = this.$route.params.orderAdder;
      if (orderAdder) {
        this.handleAddressChange(this.$route.params.addressList);
        return false;
      }
      const addressList = localStorage.get('addressList') || {};
      if (addressList) {
        this.handleAddressChange(addressList);
      }
      // this.$track.registeredEvents('H5_2B_OrderConfirmPageExposure');
    },
    handleToAddress() {
      if (this.orderInfo.addrReceiverInfo) {
        // 默认地址信息，如没有则为没有地址列表
        this.$router.push({ name: 'address', query: { source: 1 } });
        return;
      }
      this.$router.push({
        name: 'addressManage',
        query: { type: 'order' }
      });
    },
    // 选择完地址后触发更新
    handleAddressChange(e) {
      if (e.noAddr) {
        this.$set(this.orderData, 'addrReceiverId', '');
        this.getConfirmOrderInfo();
      }
      if (this.orderData.addrReceiverId == e.addrReceiverId) return;
      this.$set(this.orderData, 'addrReceiverId', e.addrReceiverId || '');
      this.getConfirmOrderInfo();
    },
    handleCouponShow(data) {
      const { couponActivityType, hasCouponActivity } = data || {};
      this.couponType = couponActivityType;
      const isCouponType =
        couponActivityType == DISCOUNT ||
        couponActivityType == REDUCTION ||
        (couponActivityType == FREIGHT && this.orderInfo.calcFeeInfo.totalFreightFee != '0.00') ||
        couponActivityType == CASH;
      if (!isCouponType || !this.isAvailableFn(hasCouponActivity)) {
        return;
      }
      this.couponId = data.couponActivityUseId;
      this.isCoupon = true;
    },
    getCouponUserIdList(couponItem) {
      const { couponType } = this;
      const { couponActivityInfoList } = this.orderInfo;
      const { activityId, pickupId, couponCategory } = couponItem || {};
      const isActivity = couponType === REDUCTION;
      const couponKey = isActivity ? 'activityTemplateDetailId' : 'couponActivityUseId';
      const couponId = isActivity ? activityId : pickupId;
      let couponList = [];
      couponActivityInfoList.forEach(item => {
        if (item.couponActivityType != couponCategory) {
          couponList.push({
            [couponKey]: item.couponActivityUseId,
            couponActivityType: item.couponActivityType
          });
        }
      });
      if (couponItem) {
        couponList.push({
          couponActivityUseId: couponId,
          couponActivityType: couponType
        });
        return couponList;
      }
      return couponList.filter(c => c.couponActivityType !== couponType);
    },
    handleSelectCoupon([couponItem]) {
      this.isCoupon = false;
      const { couponType } = this;
      this.orderData.couponActivityUseIdList = this.getCouponUserIdList(couponItem);
      if (couponType === DISCOUNT) {
        this.orderData.defaultUseCoupon = false;
      }
      if (couponType === FREIGHT) {
        this.orderData.defaultUseFreightFeeCoupon = false;
      }
      if (couponType === CASH) {
        this.orderData.defaultUseCashCoupon = false;
      }
      if (couponType === REDUCTION) {
        this.orderData.defaultUseActivityCoupon = false;
      }
      this.getConfirmOrderInfo();
    },
    // // ! 需要注意stepper的value是从接口获取的，max会受影响
    // getMaxStockByCanAdd(item) {
    //   const { count, canAdd, activityCanBuyCount } = item;
    //   if (activityCanBuyCount) {
    //     this.isOutBuy = count >= activityCanBuyCount;
    //     return activityCanBuyCount;
    //   }
    //   let finalCount = canAdd ? count + 1 : count;
    //   if (this.prevCanAdd != item.canAdd) finalCount = count;
    //   this.prevCanAdd = item.canAdd;
    //   return finalCount;
    // },
    // // stepper变化处理
    // handleCountChange(e) {
    //   const { count, activityCanBuyCount } = this.orderInfo.shopSkuList[e.index];
    //   let skuNum = count;
    //   skuNum = e.type === 'add' ? skuNum + 1 : skuNum - 1;
    //   if (skuNum < 1) return;
    //   if (skuNum > activityCanBuyCount) {
    //     skuNum--;
    //     return;
    //   }
    //   this.$set(this.orderData.selectedSkuList[e.index], 'skuNum', skuNum);
    //   localStorage.set('orderData', this.orderData);
    //   this.getConfirmOrderInfo();
    // },
    isAvailableFn(type) {
      return type === this.hasDiscount;
    },
    // 获取确认订单信息
    async getConfirmOrderInfo() {
      const [data] = await order.confirmOrder(this.orderData);
      if (data) {
        const {
          addrReceiverInfo,
          couponActivityInfoList,
          calcFeeInfo,
          invalidSkuList,
          shopSkuList
        } = data;
        const orderInfo = {
          addrReceiverInfo,
          couponActivityInfoList,
          calcFeeInfo,
          invalidSkuList,
          shopSkuList: []
        };
        shopSkuList.forEach(item => {
          if (!item) return;
          orderInfo.shopSkuList = [...orderInfo.shopSkuList, ...item.skuList];
        });
        console.log(orderInfo);
        this.$set(this, 'orderInfo', orderInfo);
        this.isOutBuy = false;
      } else {
        this.isOutBuy = true;
      }
    },

    // 点击立即下单
    async handleBuy() {
      if (!this.orderInfo.addrReceiverInfo?.addrReceiverId) {
        this.$dialog({
          message: '请选择地址信息'
        });
        return;
      }
      const {
        addrReceiverInfo: { addrReceiverId: receiverId },
        calcFeeInfo: { totalFreightFee, totalPayFee: totalFee },
        couponActivityInfoList,
        shopSkuList
      } = this.orderInfo;
      const params = {
        receiverId,
        totalFreightFee,
        totalFee,
        ...this.getDiscountIds(couponActivityInfoList),
        skuList: shopSkuList.map(item => {
          const { skuId: skuNo, count } = item;
          return { skuNo, count };
        })
      };
      this.orderSubmit(params);
    },
    getDiscountIds(list) {
      const freightCouponIds = [],
        orderCouponIds = [],
        activityId = [],
        cashCouponIds = [];
      list.forEach(c => {
        const { couponActivityType, couponActivityUseId } = c;
        if (couponActivityType === DISCOUNT) {
          orderCouponIds.push(couponActivityUseId);
        }
        if (couponActivityType === FREIGHT) {
          freightCouponIds.push(couponActivityUseId);
          this.orderData.defaultUseFreightFeeCoupon = false;
        }
        if (couponActivityType === CASH) {
          cashCouponIds.push(couponActivityUseId);
        }
        if (couponActivityType === REDUCTION) {
          activityId.push(couponActivityUseId);
        }
      });
      return {
        freightCouponIds: freightCouponIds.join(''),
        orderCouponIds: orderCouponIds.join(''),
        activityId: activityId.join(''),
        cashCouponIds: cashCouponIds.join('')
      };
    },
    async orderSubmit(params) {
      const [data] = await order.orderSubmit(params);
      if (data && data.orderNo) {
        // this.$track.registeredEvents('H5_2BConfirmPageSubmitOrderBtnClick', {
        //   order_no: data.orderNo,
        //   order_fee: params.totalFee
        // });
        cookies.set('skuID', params.skuList[0].skuNo);
        this.$router.push({ name: 'pay', query: { orderNo: data.orderNo } });
      }
    }
  }
};
</script>

<style lang="less" scoped>
.cr-submit-bar__fixed {
  position: fixed !important;
}
.confirm {
  .mg-bottom-20 {
    margin-bottom: @padding-lg;
  }
  min-height: 100%;
  margin: 0;
  padding: @padding-sm @padding-sm @padding-lg * 3;
  &-header {
    display: flex;
    align-items: center;
    margin-bottom: @padding-sm;
    padding: @padding-xs + 4 @padding-xs + 2;
    width: 100%;
    min-height: 80px;
    background: @white;
    border-radius: @border-radius-md;
    box-sizing: border-box;
    &__left {
      width: 40px;
      height: 40px;
      img {
        width: 40px;
        height: 40px;
      }
    }
    &__middle {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      margin: 0 @padding-xs + 2;
      span {
        .text-13();
        color: @black;
        &:first-child {
          font-weight: @font-weight-bold;
          margin-bottom: @padding-unit + 2;
          word-break: break-all;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }
        &.no-addr {
          .text-16();
          color: #333333;
          line-height: 22px;
          font-weight: 400;
          margin-bottom: 0;
        }
      }
    }
    &__right {
      .text-13();
      color: @gray-3;
    }
  }
  &-body {
    background: @white;
    border-radius: @border-radius-md;
    margin-bottom: @padding-sm;
    overflow: hidden;
  }
  &-goods {
    display: flex;
    padding: @padding-xs @padding-xs @padding-sm;
    background: @white;
    &__head {
      color: @black;
      .text-13();
      padding: @padding-sm;
    }
    &__left {
      width: 85px;
      height: 85px;
      border-radius: @border-radius-md;
      margin-right: @padding-xs + 2;
    }
    &__middle {
      flex: 1;
    }
    &.invalid {
      .Cg-middle__title,
      .Cg-middle__sku,
      .confirm-goods__left {
        opacity: 0.7;
      }
    }
  }
  &-footer {
    background: @white;
    margin-bottom: @padding-sm;
    border-radius: @border-radius-md;
    padding: @padding-sm @padding-xs;
  }
  &-statistic {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    span {
      .text-13();
      &:first-child {
        color: @gray-4;
        margin-right: auto;
      }
      &:last-child {
        color: @black;
      }
      &.free-ship {
        color: @gray-4;
      }
      &.has-coupon {
        color: @red;
      }
    }
    &__bold {
      color: @red !important;
    }
    .icon-arrow {
      .text-12();
      color: @gray-4;
    }
  }
}
.Cg-middle {
  &__title {
    .text-13();
    color: @black;
    display: flex;
    justify-content: space-between;
    // align-items: center;
    margin-bottom: @padding-xs - 2;
  }
  &__name {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    margin-right: @padding-unit + 2;
  }
  &__price {
    text-align: right;
    margin-left: auto;
  }
  &__sku {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 18px;
    margin-bottom: 0;
    .text-12();

    color: @gray-4;
  }
  &__stepper {
    display: flex;
    .stepper {
      margin-left: auto;
    }
  }
  &__warn {
    display: flex;
    align-items: center;
    img {
      margin-right: @padding-unit;
      width: 12px;
      height: 12px;
    }
    span {
      .text-13();
      color: @red-dark;
    }
  }
}
</style>
