<template>
  <page-wrapper @loadFirstScreen="loadFirstScreen">
    <template slot="first-screen">
      <div v-if="orderInfo != null" class="confirm">
        <!-- 地址 -->
        <SelfMention
          :promoter-phone-no.sync="promoterPhoneNo"
          :shipment-type-list="shipmentTypeList"
          @confirm-order="mentionChangeOrderInfo"
        >
          <AddressTemp
            :radius="shipmentTypeList.length > 1 ? 'not-radius' : ''"
            :addr-receiver-info="orderInfo.addrReceiverInfo"
          />
        </SelfMention>
        <!--    有效商品-->
        <ProductPanel
          v-if="orderInfo.shopSkuList.length"
          :data-list="orderInfo.shopSkuList"
          @getConfirmOrderInfo="handleCountChange"
        />
        <!--    优惠信息-->
        <FeeInfo
          v-if="!checkEqualZero(orderInfo.calcFeeInfo.totalSkuFee)"
          :coupon-activity-info-list="orderInfo.couponActivityInfoList"
          :calc-fee-info="orderInfo.calcFeeInfo"
          :general-prop="generalProp"
          @coupon-show="handleCouponShow"
        />
        <!--    失效商品-->
        <ProductPanel
          v-if="orderInfo.invalidSkuList.length"
          :data-list="orderInfo.invalidSkuList"
          type="invalidSkuList"
        />
        <!-- 提交订单 -->
        <BottomNav
          type="submitOrder"
          :info="orderInfo.calcFeeInfo"
          :goods-list="orderInfo.shopSkuList"
          @buy="handleBuy"
        />
      </div>
    </template>
    <template slot="other-screen">
      <!-- 优惠券 popup -->
      <CouponList
        v-if="orderInfo != null"
        v-model="isCoupon"
        v-bind="couponData"
        :select-activity-info="selectActivityInfo"
        :goods-info="orderInfo.shopSkuList"
        :coupon-activity-info-list="orderInfo.couponActivityInfoList"
        @coupon-select="handleSelectCoupon"
      />
    </template>
  </page-wrapper>
</template>

<script>
// API
import order from '@/api/order.api';
// 公共方法
import localStorage from '@/service/localStorage.service';
import { encryption } from '@/service/encrypt';
import cookies from '@/service/cookieStorage.service';
import { checkEqualZero } from '@/service/utils.service';
import { isPhone } from '@/service/validation.service';
// 组件
import BottomNav from '@/components/bottomNav';
import CouponList from './components/couponList.vue';
import FeeInfo from './components/feeInfo.vue';
import AddressTemp from './components/addressTemp.vue';
import ProductPanel from './components/productPanel/index.vue';
import SelfMention from './components/selfMention';
import { smTrackEvent } from '@/service/shumei.service';
// 类型常量
import {
  GIFT,
  defaultCoupon,
  SHIP_USE,
  REDUCTION,
  DISCOUNT,
  FREIGHT,
  CASH
} from '@/constants/order';

import { mapGetters, mapActions, mapMutations } from 'vuex';
import PageWrapper from '@/components/base/PageWrapper.vue';

export default {
  name: 'CreateOrder',
  components: {
    PageWrapper,
    BottomNav,
    SelfMention,
    CouponList,
    FeeInfo,
    AddressTemp,
    ProductPanel
  },
  data() {
    return {
      isCoupon: false,
      couponData: {
        couponType: 1,
        couponId: 0,
        couponIds: [],
        hasCouponActivity: 0,
        extObj: null
      },
      orderData: {},
      selectActivityInfo: [], // 选中的活动信息
      promoterPhoneNo: '', // 推广员手机号
      shipmentTypeList: [], // 配送方式列表
      generalProp: {} // 通用属性
    };
  },
  computed: {
    ...mapGetters('createOrderStore', ['orderInfo', 'preTag'])
  },
  watch: {
    preTag: {
      immediate: true,
      handler(v) {
        if (v === 2) {
          this.refreshView(true);
        }
      }
    }
  },
  created() {
    this.init();
  },
  mounted() {},
  methods: {
    ...mapActions('createOrderStore', ['fetchOrderInfo']),
    ...mapMutations('createOrderStore', ['setPreTag']),

    checkEqualZero,
    init() {
      // 获取订单信息
      const orderData = localStorage.get('orderData');
      if (orderData) {
        this.orderData = orderData;
      }
      // 获取从地址列表中选中地址
      const addressList = localStorage.get('addressList');
      this.handleAddressChange(addressList);
      // 埋点
      this.$track.registeredEvents('H5_2B_OrderConfirmPageExposure');
    },
    mentionChangeOrderInfo(active) {
      // 处理是否为自营信息
      this.orderData.shipmentType = active;
      this.getConfirmOrderInfo();
    },
    // 选择完地址后触发更新
    handleAddressChange(e) {
      if (e && this.orderData.addrReceiverId !== e.addrReceiverId) {
        let addrReceiverId = e.addrReceiverId || '';
        // e.noAddr && (addrReceiverId = '');
        this.orderData.addrReceiverId = addrReceiverId;
      }
      this.getConfirmOrderInfo();
    },

    // 显示弹窗
    async handleCouponShow(data) {
      const {
        targetActivityType: couponActivityType,
        targetActivityUseIds,
        hasCouponActivity,
        isVisibleIcon
      } = data || {};
      if (!isVisibleIcon) {
        return;
      }
      this.couponData.hasCouponActivity = hasCouponActivity;
      this.couponData.couponType = couponActivityType;
      this.couponData.couponIds = targetActivityUseIds;
      this.couponData.extObj = data;
      this.isCoupon = true;
    },
    // 选中券后处理
    handleSelectCoupon(list) {
      this.isCoupon = false;
      this.orderData.couponActivityUseIdList = list;
      // 告诉后端那些属性发生了变化
      this.couponData.extObj.targetKeys.forEach(key => {
        this.orderData[defaultCoupon[key]] = false;
      });
      this.getConfirmOrderInfo();
    },
    // 购买数量变更
    handleCountChange(data) {
      this.resetOrderParams();
      this.$set(this.orderData.selectedSkuList[data.index], 'skuNum', data.skuNum);
      localStorage.set('orderData', this.orderData);
      this.getConfirmOrderInfo();
    },
    // 重置订单券参数
    resetOrderParams() {
      Object.values(defaultCoupon).forEach(item => {
        this.orderData[item] = true;
      });
      this.orderData.couponActivityUseIdList = [];
    },
    // 获取确认订单信息
    async getConfirmOrderInfo() {
      if (this.preTag) {
        return;
      }
      const reqObj = {
        ...this.orderData,
        cartInfoList: [
          {
            activityInfo: null,
            skus: this.orderData.selectedSkuList
          }
        ]
      };
      // 调用接口 更新订单信息 做数据适配
      await this.fetchOrderInfo(reqObj);
      // 接口请求回来后,设置预加载为false
      this.refreshView(false);
    },
    // 数据回来之后刷新视图
    refreshView(isPreTag = false) {
      if (!this.orderInfo) return;

      this.isOutBuy = true;
      let { shipmentTypeList, generalProp = {}, selectActivityInfo } = this.orderInfo;
      this.shipmentTypeList = shipmentTypeList;
      this.generalProp = generalProp;
      this.selectActivityInfo = selectActivityInfo;
      this.isOutBuy = false;
      if (isPreTag) {
        // 视图刷新完成后更新预加载状态
        this.$nextTick(() => {
          this.setPreTag(0);
        });
      }
    },
    // 验证推广员手机号
    async validateShipNumber() {
      if (this.orderData.shipmentType === SHIP_USE) {
        if (!isPhone(this.promoterPhoneNo)) {
          this.$toast('请输入正确的推广员手机号码');
          return true;
        }
        const [res] = await order.checkPromoterByMobile(this.promoterPhoneNo);
        if (!res?.available) {
          this.$dialog({
            message: '推广员手机号不匹配暂不支持自提，请您与推广员确认后重新填入',
            confirmButtonText: '重新填写',
            showCancelButton: false
          });
          return true;
        }
      }
      return false;
    },
    // 点击立即下单
    async handleBuy() {
      if (this.$config.qinghai) {
        const shipPhone = await this.validateShipNumber();
        if (shipPhone) return;
      }

      if (
        !this.orderInfo.addrReceiverInfo?.addrReceiverId &&
        this.orderData.shipmentType !== SHIP_USE
      ) {
        this.$dialog({
          message: '你还没有选择收获地址哦',
          confirmButtonText: '去添加',
          showCancelButton: false,
          onConfirm: () => {
            let _params = {
              name: 'addressManage',
              query: { from: 'order' }
            };
            this.$router.push(_params);
          }
        });
        return;
      }
      const {
        addrReceiverInfo: { addrReceiverId: receiverId } = { addrReceiverId: '' },
        calcFeeInfo: { totalFreightFee, totalPayFee: totalFee },
        couponActivityInfoList,
        shopSkuList
      } = this.orderInfo;
      const cid3s = [];
      const goodsItems = [];
      const params = {
        receiverId,
        totalFreightFee,
        totalFee,
        ...this.getDiscountIds(couponActivityInfoList),
        skuList: shopSkuList.map(item => {
          const { skuId: skuNo, count, cid3 } = item;
          cid3s.push(cid3);
          goodsItems.push(skuNo);
          return { skuNo, count };
        })
      };
      await this.orderSubmit(encryption(params), params);
    },
    // 获取选中的优惠券ids
    getDiscountIds(list) {
      const obj = {
        [DISCOUNT]: [],
        [FREIGHT]: [],
        [CASH]: [],
        [REDUCTION]: [],
        [GIFT]: []
      };
      const params = {};
      list.forEach(c => {
        const { couponActivityType, couponActivityUseId, couponActivityAmt } = c;
        // 过滤组合活动和组合全
        if ([10, 9].includes(couponActivityType)) {
          return;
        }
        obj[couponActivityType].push(couponActivityUseId);
        if (couponActivityType === FREIGHT) {
          this.orderData.defaultUseFreightFeeCoupon = false;
        } else if (couponActivityType === GIFT && couponActivityAmt) {
          params.giftCardFee = couponActivityAmt;
        }
      });
      return Object.assign(
        {
          freightCouponIds: obj[FREIGHT].join(''),
          orderCouponIds: obj[DISCOUNT].join(''),
          activityId: obj[REDUCTION].join(''),
          cashCouponIds: obj[CASH].join(''),
          giftCardId: obj[GIFT].join('')
        },
        params
      );
    },
    async orderSubmit(query, params) {
      const [data, err] = await order.orderSubmit(query);
      // console.log(data, err, err.response.businessCode);
      // 46014 === 礼品卡失效
      if (Number(err?.response?.businessCode) === 46014) {
        this.resetOrderParams();
        this.getConfirmOrderInfo();
      }
      if (data && data.orderNo) {
        this.$track.registeredEvents('H5_2BConfirmPageSubmitOrderBtnClick', {
          order_no: data.orderNo,
          order_fee: params.totalFee
        });
        smTrackEvent({
          eventId: 'order',
          orderId: data.orderNo
        });
        cookies.set('skuID', data.orderNo);
        setTimeout(() => {
          this.$router.replace({ name: 'pay', query: { orderNo: data.orderNo } });
        }, 300);
      }
    },
    loadFirstScreen() {
      console.log('jhb 首屏渲染完成');
    }
  }
};
</script>

<style lang="less" src="./style/order.less" scoped />
