<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 && !isPrimordialBrowser && !isWeixinBrowser"
      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 Bridge from '@qg/js-bridge';
import MpBridge from '@/service/mp';
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';
import { isApp, isWxMp } from '@/service/validation.service';
import { mapState } from 'vuex';
export default {
  name: 'CreateOrder',
  components: {
    bottomNav,
    // stepper,
    couponList,
    FeeInfo
  },
  mixins: [historyRecordMixins],
  data() {
    return {
      nativeBridge: null,
      // 以下是原有data
      query: {},
      prevCanAdd: true,
      isOutBuy: false,
      couponType: 1,
      isCoupon: false,
      orderData: {},
      hasDiscount: HAS_DISCOUNT,
      couponId: 0,
      selectCoupon: [],
      orderInfo: {
        addrReceiverInfo: {},
        couponActivityInfoList: [],
        calcFeeInfo: {},
        invalidSkuList: [],
        shopSkuList: []
      }
    };
  },
  computed: {
    ...mapState
  },
  mounted() {
    this.init();
  },
  activated() {
    this.init();
  },
  created() {
    if (isApp) this.nativeBridge = new Bridge();
    else if (isWxMp) this.nativeBridge = new MpBridge();
  },
  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) {
      console.log(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);

      // const data = {
      //   addrReceiverInfo: {
      //     addrReceiverId: 682,
      //     receiverName: 'ndjnn',
      //     addrFullName: '北京，石景山区，八角街道，nsnn',
      //     receiverPhoneNo: '18511117191'
      //   },
      //   invalidSkuList: [
      //     {
      //       skuName: '[自营]Apple AirPods Pro 主动降噪无线蓝牙耳机 适用iPhone/iPad/Apple Watch',
      //       tagList: [],
      //       skuImg:
      //         'http://img30.360buyimg.com/sku/jfs/t1/59411/33/15646/64951/5dd50baaE81702116/413160a74742f504.jpg',
      //       marketPrice: '1760.66',
      //       skuSource: 1,
      //       invalidStatus: 0,
      //       salePrice: '1599',
      //       count: 1,
      //       canAdd: true,
      //       invalidStatusDesc: '该地址暂无库存',
      //       skuId: 3732897275393,
      //       jumpUrl: 'xyqb://homepage/goodsdetail?skuNo=3732897275393'
      //     }
      //   ],
      //   shopSkuList: [
      //     {
      //       freightFee: '12.00运费',
      //       shopInfo: {
      //         shopId: 12,
      //         shopName: '店铺名称',
      //         shopImg: 'https://'
      //       },
      //       skuList: [
      //         {
      //           marketPrice: '35.60',
      //           invalidStatus: 0,
      //           salePrice: '34.4',
      //           count: 1,
      //           canAdd: true,
      //           invalidStatusDesc: '宝贝已失效，不能购买',
      //           jumpUrl: 'xyqb://homepage/goodsdetail?skuNo=7331961',
      //           skuName:
      //             '[别下单-开普勒]美加净 MAXAM 细嫩柔白隔离防晒乳100mlSPF30 PA+++ （面部身体户外鲜果防晒霜男女)',
      //           tagList: [],
      //           skuImg:
      //             'http://img11.360buyimg.com/n1/jfs/t21367/129/509809607/84163/17b4ed2e/5b0f8bdfNba3c4b43.jpg',
      //           skuSource: 2,
      //           skuAttr: '【防晒】细嫩柔白100ml',
      //           skuId: 7331961,
      //           goodsTypeImage: 'https://kdspstatic.q-gp.com/kdsp/goods/icon/best-selected3x.png'
      //         }
      //       ]
      //     }
      //   ],
      //   calcFeeInfo: {
      //     couponFee: '0.00',
      //     totalFreightFee: '10.00',
      //     totalPayFee: '10.00',
      //     couponFreightFee: '0.00',
      //     totalSkuFee: '10.00'
      //   },
      //   hasNext: false,
      //   couponActivityInfoList: [
      //     {
      //       hasCouponActivity: 1,
      //       couponActivityType: 4
      //     },
      //     {
      //       hasCouponActivity: 1,
      //       couponActivityType: 3
      //     },
      //     {
      //       hasCouponActivity: 1,
      //       couponActivityType: 2
      //     },
      //     {
      //       hasCouponActivity: 1,
      //       couponActivityType: 1
      //     }
      //   ]
      // };
      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: '你还没有选择收货地址哦！',
          showCancelButton: false,
          confirmButtonText: '去添加',
          onConfirm: () => {
            this.handleToAddress();
          }
        });
        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) {
        cookies.set('skuID', params.skuList[0].skuNo);
        if (isWxMp) {
          this.nativeBridge.openNewUrl({
            newUrl: `/pages/pay/index?orderNo=${data.orderNo}`
          });
        } else if (isApp) {
          this.nativeBridge.openNewUrl({
            newUrl: `/pay?orderNo=${data.orderNo}`
          });
        } else {
          this.$dialog({
            message: '请在App或小程序中参与活动~',
            title: '',
            showCancelButton: false,
            confirmButtonText: '我知道了'
          });
        }
      }
    }
  }
};
</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>
