<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 && orderInfo.calcFeeInfo.totalSkuFee !== '0.00'">
      <FeeInfo :calc-fee-info="orderInfo.calcFeeInfo" />
    </template>
    <div v-if="orderInfo.invalidSkuList && orderInfo.invalidSkuList.length" class="confirm-body">
      <div class="confirm-goods__head">失效商品</div>
      <div
        v-for="(item, index) in orderInfo.invalidSkuList"
        :key="index"
        class="confirm-goods invalid"
      >
        <image 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">{{ item.skuAttr }}</div>
          <div class="Cg-middle__stepper">
            <div v-if="item.invalidStatusDesc" class="Cg-middle__warn">
              <!-- <image src="@/assets/images/notice.png" /> -->
              <span>{{ item.invalidStatusDesc }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 底部 -->
    <bottom-nav
      v-if="orderInfo.shopSkuList.length && !isPrimordialBrowser && !isWeixinBrowser"
      type="submitOrder"
      :info="orderInfo.calcFeeInfo"
      @buy="handleBuy"
    />
  </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 stepper from '@/components/sample';
import localStorage from '@/service/localStorage.service';
import historyRecordMixins from '@/mixins/historyRecord.mixins';
import FeeInfo from './components/feeInfo.vue';
import { HAS_DISCOUNT } from '@/constants/order';
import { isApp, isWxMp } from '@/service/validation.service';
import { mapState } from 'vuex';
import { saTrackEvent } from '@/service/sa.service';
import { firstGroupShare } from '@/service/utils.service';
export default {
  name: 'CreateOrder',
  components: {
    bottomNav,
    // stepper,
    FeeInfo
  },
  mixins: [historyRecordMixins],
  data() {
    return {
      nativeBridge: null,
      // 以下是原有data
      query: {},
      prevCanAdd: true,
      isOutBuy: false,
      orderData: {},
      hasDiscount: HAS_DISCOUNT,
      selectCoupon: [],
      orderInfo: {
        addrReceiverInfo: {},
        calcFeeInfo: {},
        invalidSkuList: [],
        shopSkuList: []
      }
    };
  },
  computed: {
    ...mapState({
      isPrimordialBrowser: state => state.pay.isPrimordialBrowser,
      isWeixinBrowser: state => state.pay.isWeixinBrowser
    })
  },
  mounted() {
    firstGroupShare();
    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();
      }
    },
    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();
    },
    isAvailableFn(type) {
      return type === this.hasDiscount;
    },
    // 获取确认订单信息
    async getConfirmOrderInfo() {
      console.log(this.orderData, 11223);
      const [data] = await order.confirmOrder(this.orderData);
      if (data) {
        const { addrReceiverInfo, calcFeeInfo, invalidSkuList, shopSkuList } = data;
        const orderInfo = {
          addrReceiverInfo,
          calcFeeInfo,
          invalidSkuList,
          shopSkuList: []
        };

        if (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;
      }
    },

    // 点击立即下单
    handleBuy() {
      this.$store.dispatch('change_loading', true);
      if (!this.orderInfo.addrReceiverInfo?.addrReceiverId) {
        this.$dialog({
          closeOnClickOverlay: true,
          message: '你还没有选择收货地址哦！',
          showCancelButton: false,
          confirmButtonText: '去添加',
          onConfirm: () => {
            this.handleToAddress();
          }
        });
        this.$store.dispatch('change_loading', false);
        return;
      }
      saTrackEvent('H5_UserClickOrderConfirmPageSubmitOrderBtnClick', {
        order_type: '0元购'
      });
      try {
        const {
          addrReceiverInfo: { addrReceiverId: receiverId },
          calcFeeInfo: { totalFreightFee, totalPayFee: totalFee },
          shopSkuList
        } = this.orderInfo;
        const params = {
          receiverId,
          totalFreightFee,
          totalFee,
          activityId: localStorage.get('templateId') || '',
          activityHundredGroupId: localStorage.get('groupBuyGroupId') || '',
          skuList: shopSkuList.map(item => {
            const { skuId: skuNo, count } = item;
            return { skuNo, count };
          })
        };
        this.orderSubmit(params);
      } catch (e) {
        this.$store.dispatch('change_loading', false);
      }
    },
    async orderSubmit(params) {
      console.log(params);
      const [data] = await order.orderSubmit(params);
      if (data && data.orderNo) {
        if (isWxMp) {
          this.nativeBridge.openNewUrl({
            newUrl: `/pages/pay/index?orderNo=${data.orderNo}`
          });
          return;
          // const wx = require('weixin-js-sdk');
          // wx.miniProgram.redirectTo();
        } else if (isApp) {
          this.$router.replace({ path: `/pay?orderNo=${data.orderNo}` });
          return;
        } else {
          return; // todo 处理纯h5情况
          // 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>
