<template>
  <view class="confirm">
    <!-- 地址 -->
    <self-mention
      v-if="$config('qinghai')"
      :shipment-type-list="shipmentTypeList"
      :promoter-phone-no.sync="promoterPhoneNo"
      @confirm-order="mentionChangeOrderInfo"
    >
      <address-temp :class-name="shipmentTypeList[1] ? 'not-radius' : ''" :order-info="orderInfo" />
    </self-mention>
    <address-temp v-else :order-info="orderInfo" />
    <view class="confirm-body">
      <view v-for="(item, idx) in orderInfo.shopSkuList" :key="idx" class="confirm-goods">
        <image class="confirm-goods__left" :src="item.skuImg" />
        <view class="confirm-goods__middle">
          <view class="Cg-middle__title">
            <text class="Cg-middle__name"> {{ item.skuName }} </text>
            <text class="Cg-middle__price">¥{{ item.salePrice || "0.00" }}</text>
          </view>
          <view class="Cg-middle__sku">
            <view>{{ item.skuAttr }}</view>
            <!-- <image v-if="detailInfo.activityTagImg" src="https://img.lkbang.net/xcx/newUser.png" alt="" mode="widthFix" /> -->
          </view>
          <!-- <view class="Cg-middle__tags">
            <image src="https://img.lkbang.net/xcx/newUser.png" alt="" mode="widthFix" />
          </view> -->
          <view class="Cg-middle__stepper">
            <view>
              <image
                v-if="item.activityType && item.activityType == 8 && item.newComersLabel"
                class="new_user_tag"
                :src="item.newComersLabel.icon"
                alt=""
                mode="heightFix"
              />
              <view v-if="item.commonLimitCount" class="Cg-middle__warn">
                <text>限购{{ item.commonLimitCount }}件</text>
              </view>
              <view v-else-if="item.invalidStatusDesc" class="Cg-middle__warn">
                <text>{{ item.invalidStatusDesc }}</text>
              </view>
            </view>
            <stepper
              :value="item.count"
              :min="1"
              :index="idx"
              disabled
              :can-subtract="item.count === 1"
              :can-add="item.canAdd"
              :max="getMaxStockByCanAdd(item)"
              @change="handleCountChange"
            />
          </view>
        </view>
      </view>
    </view>
    <template v-if="orderInfo.calcFeeInfo.totalSkuFee !== '0.00'">
      <FeeInfo
        :coupon-activity-info-list="orderInfo.couponActivityInfoList"
        :calc-fee-info="orderInfo.calcFeeInfo"
        @coupon-show="handleCouponShow"
        @giftGard-pop="giftGardPop"
      />
    </template>
    <view v-if="orderInfo.invalidSkuList.length" class="confirm-body">
      <view class="confirm-goods__head">失效商品</view>
      <view
        v-for="(item, index) in orderInfo.invalidSkuList"
        :key="index"
        class="confirm-goods invalid"
      >
        <image class="confirm-goods__left" :src="item.skuImg" />
        <view class="confirm-goods__middle">
          <view class="Cg-middle__title">
            <text class="Cg-middle__name">
              {{ item.skuName }}
            </text>
            <text class="Cg-middle__price">¥{{ item.salePrice || "0.00" }}</text>
          </view>
          <view class="Cg-middle__sku">{{ item.skuAttr }}</view>
          <view class="Cg-middle__stepper">
            <view v-if="item.invalidStatusDesc" class="Cg-middle__warn">
              <text>{{ item.invalidStatusDesc }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 底部 -->
    <bottom-nav
      v-if="orderInfo.shopSkuList.length"
      type="submitOrder"
      :info="orderInfo.calcFeeInfo"
      @buy="handleBuy"
    />
    <uni-popup ref="commonPopup" type="bottom" :closeable="true">
      <coupon-list
        ref="couponList"
        :coupon-id="couponId"
        :goods-info="orderInfo.shopSkuList"
        :coupon-type="couponType"
        :coupon-activity-info-list="orderInfo.couponActivityInfoList"
        @select="handleSelectCoupon"
      />
    </uni-popup>
    <uni-popup ref="giftPopup" type="bottom" :closeable="true">
      <GiftList v-if="giftDataList.length" :gift-list="giftDataList" @handleGiftOk="handleGiftOk" />
    </uni-popup>
    <uni-popup ref="mentionModal">
      <uni-popup-dialog
        type="base"
        title=" "
        content="推广员手机号不匹配暂不支持自提，请您与推广员确认后重新填入"
        :duration="2000"
        :before-close="true"
        confirm-txt="重新填写"
        :hide-cancel-btn="true"
      />
    </uni-popup>
    <!-- 礼品卡弹框 -->
    <uni-popup ref="giftGardPopup" type="dialog">
      <giftGardPop :info="generalProp" @giftGard-close="giftGardPop" />
    </uni-popup>
    <tougdunCanvas />
  </view>
</template>

<script>
import adApi from "@/api/ad.api";
import { confirmOrder, orderSubmit, checkPromoterByMobile } from "@/api/order.api";
import bottomNav from "@/components/bottomNav";
import couponList from "@/components/coupon-list";
import stepper from "@/components/uni-number-box/sample";
import { saTrackEvent } from "@/utils/sa.js";
import { kaFlow } from "@/api/ka.api.js";
import FeeInfo from "./components/feeInfo.vue";
import GiftList from "./components/giftList";
import { getCouponChooseList } from "@/api/home.api";
import { DISCOUNT, FREIGHT, CASH, REDUCTION, HAS_DISCOUNT } from "@/constants/order.js";
import { GIFT, SHIP_USE } from "@/constants/order.js";
import addressTemp from "./components/addressTemp";
import selfMention from "./components/selfMention";
import { isPhone } from "@/utils";
const couponTypeDesc = ["满减券", "优惠券"];
import UniPopup from "@/components/uni-popup/uni-popup.vue";
import uniPopupDialog from "@/components/uni-popup/uni-popup-dialog";
import giftGardPop from "./components/giftGardPop.vue";
import tougdunCanvas from "@/components/tougdunCanvas.vue";
import { paymentConfig } from "@/utils/mpConfig/types";
import { smTrackEvent } from "@/utils/shumei";
export default {
  components: {
    bottomNav,
    stepper,
    couponList,
    FeeInfo,
    GiftList,
    addressTemp,
    selfMention,
    UniPopup,
    uniPopupDialog,
    giftGardPop,
    tougdunCanvas
  },
  data() {
    return {
      query: {},
      prevCanAdd: true,
      isOutBuy: false,
      couponType: 1,
      isCoupon: false,
      orderData: {},
      giftId: 0,
      giftCardFee: 0,
      hasDiscount: HAS_DISCOUNT,
      couponId: 0,
      selectCoupon: [],
      giftDataList: [],
      orderInfo: {
        addrReceiverInfo: {},
        couponActivityInfoList: [],
        calcFeeInfo: {},
        invalidSkuList: [],
        shopSkuList: []
      },
      promoterPhoneNo: "",
      shipmentTypeList: [],
      generalProp: {}
    };
  },
  onLoad() {
    const eventChannel = this.getOpenerEventChannel();
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    eventChannel.on("onDetailConfirmInfo", data => {
      this.orderData = data;
      this.getConfirmOrderInfo(data);
    });
    uni.$on("confirmPageUpdateAddress", data => {
      this.handleAddressChange(data);
    });
  },
  onUnload() {
    uni.$off("confirmPageUpdateAddress");
  },
  onShow() {
    // perf 首次进去会请求两次，但是从其他页面返回需要刷新数据
    // if (this.orderData !== {}) {
    if (Object.keys(this.orderData).length) {
      this.getConfirmOrderInfo();
    }
  },
  methods: {
    giftGardPop(val) {
      if (val) {
        this.$refs.giftGardPopup.open();
      } else {
        this.$refs.giftGardPopup.close();
      }
    },
    mentionChangeOrderInfo(active) {
      // 处理是否为自营信息
      this.$set(this.orderData, "shipmentType", active);
      this.getConfirmOrderInfo();
    },
    async getGiftCardList() {
      if (!this.orderInfo.shopSkuList.length) return;
      const selectedSkuList = this.orderInfo.shopSkuList.map(item => {
        const { skuSource, count, skuId } = item;
        return {
          skuNo: skuId,
          skuNum: count,
          skuSource
        };
      });
      this.giftDataList = [];
      const selectedCouponActivityList = [];
      this.orderInfo.couponActivityInfoList.forEach(item => {
        selectedCouponActivityList.push({
          couponActivityType: item.couponActivityType,
          couponActivityUseId: item.couponActivityUseId
        });
      });
      setTimeout(() => {
        this.getGiftCard(selectedSkuList, selectedCouponActivityList);
      });
    },
    async getGiftCard(selectedSkuList, selectedCouponActivityList) {
      const [res] = await getCouponChooseList({
        selectedSkuList,
        couponActivityType: GIFT,
        selectedCouponActivityList
      });
      const { userCardInfoVoList } = res || {};
      userCardInfoVoList.forEach(d => {
        d.checked = d.id === this.giftId;
      });
      this.giftDataList = userCardInfoVoList || [];
    },
    handleGiftOk([checkItem]) {
      this.$refs.giftPopup.close();
      this.orderData.couponActivityUseIdList = this.getCouponUserIdList(checkItem);
      if (!checkItem) {
        this.orderData.couponActivityUseIdList.forEach((item, idx) => {
          if (item.couponActivityType === GIFT) {
            this.orderData.couponActivityUseIdList.splice(idx, 1);
          }
        });
      }
      this.orderData.defaultUseGiftCard = false;
      this.getConfirmOrderInfo();
    },
    giftActivityUseIdList(checkItem) {
      const { couponActivityUseIdList = [] } = this.orderData;
      const giftIndex = couponActivityUseIdList.findIndex(item => item.couponActivityType === GIFT);
      if (checkItem) {
        const giftActivity = { couponActivityUseId: checkItem?.id, couponActivityType: GIFT };
        // 选中状态：替换或者增加
        if (giftIndex !== -1) {
          couponActivityUseIdList[giftIndex] = giftActivity;
          return couponActivityUseIdList;
        }
        return [...couponActivityUseIdList, giftActivity];
      }
      // 未选中状态：删除或为原数据
      if (giftIndex === -1) return couponActivityUseIdList;
      couponActivityUseIdList.splice(giftIndex, 1);
      return couponActivityUseIdList;
    },
    // 选择完地址后触发更新
    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.$set(this, "couponType", couponActivityType);
      if (couponActivityType === GIFT && this.isAvailableFn(hasCouponActivity)) {
        this.$set(this, "giftId", data.couponActivityUseId || "");
        this.getGiftCardList();
        this.$refs.giftPopup.open();
        return;
      }

      const isCouponType =
        couponActivityType == DISCOUNT ||
        couponActivityType == REDUCTION ||
        (couponActivityType == FREIGHT && this.orderInfo.calcFeeInfo.totalFreightFee != "0.00") ||
        couponActivityType == CASH;
      if (!isCouponType || !this.isAvailableFn(hasCouponActivity)) {
        return;
      }
      this.$set(this, "couponId", data.couponActivityUseId || "");
      this.$refs.commonPopup.open();
    },
    isAvailableFn(type) {
      return type === this.hasDiscount;
    },
    handleSelectCoupon([couponItem]) {
      this.$refs.commonPopup.close();
      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();
    },
    getCouponUserIdList(couponItem) {
      const { couponType } = this;
      const { couponActivityInfoList } = this.orderInfo;
      const { activityId, pickupId, couponCategory, id } = couponItem || {};
      const isActivity = couponType === REDUCTION;
      const couponKey = isActivity ? "activityTemplateDetailId" : "couponActivityUseId";
      const couponId = isActivity ? activityId : pickupId;
      let couponList = [];
      couponActivityInfoList.forEach(item => {
        if (item.couponActivityType != couponCategory && item.couponActivityType != GIFT) {
          couponList.push({
            [couponKey]: item.couponActivityUseId,
            couponActivityType: item.couponActivityType
          });
        }
      });
      if (couponItem) {
        couponList.push({
          couponActivityUseId: couponId || id,
          couponActivityType: couponType
        });
        return couponList;
      }
      return couponList.filter(c => c.couponActivityType !== couponType);
    },
    // ! 需要注意stepper的value是从接口获取的，max会受影响
    getMaxStockByCanAdd(item) {
      const { count, canAdd, commonLimitCount } = item;
      // 限购
      if (commonLimitCount) {
        this.isOutBuy = count >= commonLimitCount;
        return commonLimitCount;
      }
      let finalCount = canAdd ? count + 1 : count;
      if (this.prevCanAdd != item.canAdd) finalCount = count;
      this.prevCanAdd = item.canAdd;
      return finalCount;
    },
    // stepper变化处理
    handleCountChange(e) {
      const { count, commonLimitCount } = this.orderInfo.shopSkuList[e.index];
      let skuNum = count;
      skuNum = e.type === "add" ? skuNum + 1 : skuNum - 1;
      if (skuNum < 1) return;
      if (commonLimitCount && skuNum > commonLimitCount) {
        skuNum--;
        uni.showToast({
          title: `您当前购买的商品限购${commonLimitCount}件`,
          icon: "none"
        });
        return;
      }
      uni.showLoading({
        /* #ifdef MP-WEIXIN */
        mask: true,
        /* #endif */
        title: "加载中"
      });
      this.resetOrderParams();
      this.$set(this.orderData.selectedSkuList[e.index], "skuNum", skuNum);
      this.getConfirmOrderInfo();
    },
    resetOrderParams() {
      this.orderData.defaultUseFreightFeeCoupon = true;
      this.orderData.defaultUseActivityCoupon = true;
      this.orderData.defaultUseCashCoupon = true;
      this.orderData.defaultUseCoupon = true;
      this.orderData.defaultUseGiftCard = true;
      this.orderData.couponActivityUseIdList = [];
    },
    // 获取确认订单信息
    async getConfirmOrderInfo() {
      const [data, error] = await confirmOrder(this.orderData);
      if (data) {
        let {
          addrReceiverInfo,
          couponActivityInfoList,
          calcFeeInfo,
          invalidSkuList,
          shopSkuList,
          // generalProp,
          shipmentTypeList = []
        } = data;
        // invalidSkuList = shopSkuList[0].skuList; // delete
        const orderInfo = {
          addrReceiverInfo,
          couponActivityInfoList,
          calcFeeInfo,
          invalidSkuList,
          shopSkuList: []
        };
        this.generalProp = data.generalProp;
        shopSkuList.forEach(item => {
          if (!item) return;
          orderInfo.shopSkuList = [...orderInfo.shopSkuList, ...item.skuList];
        });
        const giftItem = couponActivityInfoList.filter(g => {
          return g.couponActivityType === GIFT;
        });
        if (giftItem.length) {
          this.giftId = giftItem[0].couponActivityUseId;
          this.giftCardFee = giftItem[0].couponActivityAmt;
        }
        this.$set(this, "orderInfo", orderInfo);
        this.$set(this, "shipmentTypeList", shipmentTypeList);
        this.isOutBuy = false;
        uni.hideLoading();
      } else {
        this.isOutBuy = true;
        uni.hideLoading();
        uni.showToast({ icon: "none", title: error.message });
      }
    },
    async validateShipNumber() {
      if (this.orderData.shipmentType === SHIP_USE) {
        if (!isPhone(this.promoterPhoneNo)) {
          this.$api.msg("请输入正确的推广员手机号码");
          return true;
        }
        const [res] = await checkPromoterByMobile(this.promoterPhoneNo);
        if (!res?.available) {
          this.$refs.mentionModal.open();
          return true;
        }
      }
      return false;
    },
    // 是否授信
    async kaFlowState(params) {
      if (uni.getStorageSync("channlFlag") === "ka") {
        const [data] = await kaFlow();
        if (data.value) {
          /* #ifdef MP-WEIXIN */
          uni.setStorageSync("vccChannel", "159913");
          uni.setStorageSync("sonVccChannel", "");
          /* #endif */
        }
      }
      this.orderSubmit(params);
    },
    // 点击立即下单
    async handleBuy() {
      saTrackEvent("PD_YXMMAEC_UserClickOrderConfirmPageSubmitOrderBtn");
      uni.reportAnalytics("c_orderconfirmpagesubmitorderbtn", {
        uuid: uni.getStorageSync("userAuthInfo").uuid || "",
        channel_id: uni.getStorageSync("vccChannel") || ""
      });
      if (this.$config("qinghai")) {
        const shipPhone = await this.validateShipNumber();
        if (shipPhone) return;
      }
      if (
        !this.orderInfo?.addrReceiverInfo?.addrReceiverId &&
        this.orderData.shipmentType !== SHIP_USE
      ) {
        uni.showToast({ icon: "none", title: "请选择地址信息" });
        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 };
        })
      };
      if (this.giftId) {
        params.giftCardId = this.giftId;
      }
      if (this.giftCardFee) {
        params.giftCardFee = this.giftCardFee;
      }
      if (this.$config("qinghai") && this.orderData.shipmentType === SHIP_USE) {
        params.shipmentType = this.orderData.shipmentType;
        params.promoterPhoneNo = this.promoterPhoneNo;
      }
      console.log("params--params", params);
      this.kaFlowState(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 recordOrderInfoForAd(orderNo) {
      // 订单信息录入 以便后端上报腾讯广告
      if (!orderNo) return;
      try {
        const openId = uni.getStorageSync("openid");
        if (!openId) return;
        const [res, err] = await adApi.getGDTVID(openId);
        if (err) return;
        const gdt_vid = res;
        if (!gdt_vid || !openId) return;
        await adApi.createOrderRecord({
          clickId: gdt_vid,
          wechatOpenId: openId,
          orderNo,
          actionType: "COMPLETE_ORDER"
        });
      } catch (e) {}
    },
    async orderSubmit(params) {
      const [data, err] = await orderSubmit(params);
      // 46014 === 礼品卡失效

      if (err && err.response.businessCode === "46014") {
        this.resetOrderParams();
        this.getConfirmOrderInfo();
      }
      if (data && data.orderNo) {
        // #ifdef MP-WEIXIN
        await this.recordOrderInfoForAd(data.orderNo);
        // #endif
        smTrackEvent({
          eventId: "order",
          orderId: data.orderNo
        });
        setTimeout(() => {
          uni.redirectTo({
            url: `${paymentConfig.payUrl}?orderNo=${data.orderNo}`,
            complete: res => console.log(res)
          });
        }, 300);
      }
    },
    handleSelectItemCoupon(isSelect, couponInfo) {
      saTrackEvent("PD_YXMMAEC_UserClickOrderConfirmPageSelectCoupon", {
        check_or_not: isSelect ? "勾选" : "取消",
        coupon_type: couponTypeDesc[this.couponType - 1],
        coupon_id: couponInfo.pickupId || ""
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "@/style/var.scss";
.confirm {
  .mg-bottom-20 {
    margin-bottom: $padding-lg;
  }
  min-height: 100%;
  margin: 0;
  padding: $padding-sm $padding-sm $padding-lg * 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;
      @include text-size(26);
      padding: $padding-sm;
    }
    &__left {
      width: 170rpx;
      height: 170rpx;
      border-radius: $border-radius-md;
      margin-right: $padding-xs + 4;
    }
    &__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;
    // &.freight-discount {
    // margin-bottom: 0;
    // }
    text {
      @include text-size(26);
      &:first-child {
        color: $gray-4;
        margin-right: auto;
      }
      &:last-child {
        color: $black;
      }
      &.free-ship {
        color: $gray-4;
      }
      &.has-coupon {
        color: $black;
      }
    }
    &__bold {
      color: $red !important;
    }
    .icon-arrow {
      font-size: 24rpx;
      color: $gray-4;
    }
  }
}
.Cg-middle {
  &__title {
    @include text-size(26);
    color: $black;
    display: flex;
    justify-content: space-between;
    // align-items: center;
    margin-bottom: $padding-xs - 4;
  }
  &__name {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    overflow: hidden;
    margin-right: $padding-unit + 4;
  }
  &__price {
    // width: 130px;
    text-align: right;
    margin-left: auto;
  }
  &__sku {
    display: flex;
    justify-content: space-between;
    align-items: center;
    min-height: 36rpx;
    margin-bottom: 0;
    @include text-size(24);
    color: $gray-4;
  }
  &__stepper {
    display: flex;
    justify-content: space-between;
    .new_user_tag {
      height: 26rpx;
      width: auto;
    }
    // stepper {
    //   margin-left: auto;
    // }
  }
  &__warn {
    display: flex;
    align-items: center;
    image {
      margin-right: $padding-unit;
      width: 24rpx;
      height: 24rpx;
    }
    text {
      font-size: 26rpx;
      color: $red-dark;
    }
  }
}
</style>
