<template>
  <view
    class="channel-wrap"
    :style="{ backgroundColor: backgroundColor ? backgroundColor : '#FC2E42' }"
  >
    <scroll-view
      :scroll-y="true"
      class="scroll-Y"
      enable-back-to-top
      @scrolltolower="getSearchGoodsList"
    >
      <view class="banner">
        <image :src="bannerImg" mode="widthFix" />
      </view>
      <view class="coupon-box">
        <view v-if="couponListData.length === 1" class="coupon-common coupon-one">
          <image src="https://img.lkbang.net/xcx/coupon-bg.png" />
          <view v-for="item in couponListData" :key="item" class="coupon-card">
            <view class="coupon-main">
              <text class="txt-til">{{ item.name }}</text>
              <text class="txt-price"
                >¥<text class="txt-num">{{ item.faceValue }}</text></text
              >
              <text class="txt-explain">{{ item.limitDesc }}</text>
            </view>
            <view class="coupon-slogan">
              <text class="til">开通享花卡即可使用</text>
              <text>领取优惠券 下单更优惠</text>
            </view>
          </view>
        </view>
        <view v-else-if="couponListData.length === 2" class="coupon-common coupon-two">
          <view v-for="item in couponListData" :key="item" class="coupon-list">
            <view class="coupon-main">
              <text class="txt-til">{{ item.name }}</text>
              <text class="txt-price"
                >¥<text class="txt-num">{{ item.faceValue }}</text></text
              >
              <text class="txt-explain">{{ item.limitDesc }}</text>
            </view>
          </view>
        </view>
        <!-- coupon-many -->
        <view v-else class="coupon-common">
          <view v-for="item in couponListData" :key="item" class="coupon-list">
            <view class="coupon-main">
              <text class="txt-til">{{ item.name }}</text>
              <text class="txt-price"
                >¥<text class="txt-num">{{ item.faceValue }}</text></text
              >
              <text class="txt-explain">{{ item.limitDesc }}</text>
            </view>
          </view>
        </view>
        <view v-if="couponsBtn" class="coupon-btn">
          <button v-if="!couponState" @click="getCouponPickup">一键领取</button>
          <button v-else @click="couponReceiveEnd">已领取</button>
        </view>
      </view>
      <view class="goods-list">
        <view
          v-for="item in searchGoodsListData"
          :key="item"
          class="goods-box"
          @click="goDoodsDetail(item)"
        >
          <image class="goods-img" :src="item.goods.goodsImage" />
          <view class="goods-text">
            <view class="goods-title">{{ item.goods.goodsName }}</view>
            <view v-if="couponsNull" class="goods-price">¥{{ item.goods.goodsSalePrice }}</view>
            <view class="goods-btn" :style="{ marginTop: couponsNull ? '0' : '50rpx' }">
              <image class="goods-btn-img" src="https://img.lkbang.net/xcx/btn.png" />
              <view v-if="!vccState" class="goods-btn-text" @click.stop="goVcc(item)">
                <text class="txt">
                  <template v-if="couponsNull">
                    <text>享花卡专享 ¥</text>
                    <text class="txt-price">{{ item.goods.goodsCouponPrice }}</text>
                  </template>
                  <template v-else>
                    <text>补贴价 ¥</text>
                    <text class="txt-price">{{ item.goods.goodsSalePrice }}</text>
                  </template>
                </text>
                <text class="txt-go" @click="rightAway">马上抢</text>
              </view>

              <view v-else class="goods-btn-text">
                <text class="txt">
                  <template v-if="couponsNull">
                    <text>享花卡专享 ¥</text>
                    <text class="txt-price">{{ item.goods.goodsCouponPrice }}</text>
                  </template>
                  <template v-else>
                    <text>补贴价 ¥</text>
                    <text class="txt-price">{{ item.goods.goodsSalePrice }}</text>
                  </template>
                </text>
                <!-- <text class="txt">
                  <text v-if="couponsNull">享花卡专享 ¥</text>
                  <text v-else>补贴价 ¥</text>
                  <text class="txt-price">{{ item.goods.goodsCouponPrice }}</text>
                </text> -->
                <text class="txt-go" @click="rightAway">马上抢</text>
              </view>
            </view>
          </view>
        </view>
        <uni-load-more
          v-if="searchGoodsListData.length > 0"
          :status="noMore ? 'loading' : 'noMore'"
        />
      </view>
    </scroll-view>

    <uni-popup ref="commonPopup" closeable @change="XHKPopupChange">
      <!-- hide-cancel-btn -->
      <uni-popup-dialog
        type="base"
        content="申请享花卡额度即可免费领取哦~~"
        message=""
        title=" "
        :duration="2000"
        :before-close="true"
        hide-cancel-btn
        confirm-txt="立即开通"
        @confirm="openVcc(true)"
      />
    </uni-popup>

    <uni-popup ref="subPopup">
      <uni-popup-dialog
        type="base"
        content="宝宝真的不考虑免费领取了么？过了这个村就没那个店咯~"
        message=""
        title=" "
        :duration="2000"
        :before-close="true"
        cancel-txt="残忍拒绝"
        confirm-txt="立即开通"
        @confirm="openVcc(false)"
        @cancel="goDoodsDetail"
      />
    </uni-popup>
    <login-popup ref="login-popup" @login="loginFinish" />
  </view>
</template>

<script>
import {
  couponList,
  couponPickup,
  searchGoodsList,
  searchCoupon,
  kaFlow,
  getKaData,
  getWhiteUser
} from "@/api/ka.api.js";
// import { addrList, getGoodsList } from "@/api/home.api.js";
import { getGoodsList } from "@/api/home.api.js";
import uniLoadMore from "@/components/uni-load-more/uni-load-more.vue";
import uniPopup from "@/components/uni-popup/uni-popup";
import uniPopupDialog from "@/components/uni-popup/uni-popup-dialog";
import loginPopup from "@/components/loginPopup";
import { saTrackEvent, setRegisterPage } from "@/utils/sa.js";
import { debounce } from "@/utils";
export default {
  components: {
    uniLoadMore,
    uniPopup,
    uniPopupDialog,
    loginPopup
  },
  data() {
    return {
      couponListData: [],
      searchGoodsListData: [],
      goodsListTempData: [],
      noMore: true,
      progress: "finished",
      params: {
        // rearCategoryIds: "1583,842",
        labelIds: "",
        pageSize: 10,
        pageNo: 1
      },
      goodsData: {
        pageSize: 10,
        pageNo: 1,
        pageType: 1010
      },
      couponState: false,
      popupSwitch: true,
      goodData: {},
      userInfo: {
        hasLogin: false
      },
      vccChannel: "",
      sonVccChannel: "",
      vccState: false,
      fromState: "",
      couponNum: 0,
      bannerImg: "",
      couponIds: "",
      couponPickupList: [],
      couponsNull: false,
      backgroundColor: "",
      couponsBtn: false,
      searchCouponIds: [],
      goodsListState: true,
      templateVersion: null,
      whiteUserState: false,
      backPageState: false
    };
  },
  onShow(option) {
    console.log(option, "onShow");
    if (uni.getStorageSync("token")) {
      this.userInfo.hasLogin = true;
      if (this.backPageState) {
        this.getWhiteUserBack();
      }
      this.kaFlowState();
    }
    setRegisterPage({
      parent_channelid: uni.getStorageSync("vccChannel") || "",
      son_channelid: uni.getStorageSync("sonVccChannel") || ""
    });
    // this.getKaDataFn() // 获取页面信息
  },
  async onLoad(option) {
    // option = {
    //   // lableInfoIds: "19",
    //   vccChannel: 400000181,
    //   sonVccChannel: 223186,
    //   templateVersion: 5
    //   // from: "h5ToMiniApp",
    //   // from: "webviewToMiniApp"
    // };
    console.log(option, "goodsList");
    if (option) {
      // this.params.labelIds = option.lableInfoIds
      this.templateVersion = option.templateVersion || "";
      // this.fromState = option.from;
    }
    if (option.vccChannel) {
      uni.setStorageSync("vccChannel", option.vccChannel);
      this.vccChannel = option.vccChannel;
    }
    if (option.sonVccChannel) {
      uni.setStorageSync("sonVccChannel", option.sonVccChannel);
      uni.setStorageSync("channlFlag", "ka");
      this.sonVccChannel = option.sonVccChannel;
    }
    if (option.templateVersion) {
      uni.setStorageSync("templateVersion", option.templateVersion);
    } else {
      this.templateVersion = uni.getStorageSync("templateVersion") || null;
    }
    this.getKaDataFn(); // 获取页面信息
    // this.getCouponList();
    uni.$on("login", () => {
      this.userInfo.hasLogin = true;
      // this.couponReceive();
      this.getWhiteUser();
      this.kaFlowState();
    });
  },
  onHide() {
    this.backPageState = true;
  },
  methods: {
    async getKaDataFn() {
      const [res] = await getKaData({
        vccChannel: this.vccChannel,
        sonVccChannel: this.sonVccChannel,
        pageType: "2"
      });
      if (res) {
        this.bannerImg = res.backgroundUrl; // 获取banner图片url
        this.params.labelIds = res.labelIds; // 获取商品labelId
        this.couponIds = res.couponBatchs; // 获取商品列表
        this.backgroundColor = res.backgroundColor; // 背景色
        this.getSearchGoodsList();
        this.getCouponList();
        // this.couponReceive()
      }
    },
    // 验证是否是白名单
    async getWhiteUser() {
      if (+this.templateVersion === 5) {
        const [res] = await getWhiteUser({
          vccChannel: this.vccChannel,
          sonVccChannel: this.sonVccChannel
        });
        this.whiteUserState = res.is_hit;
        if (!res.is_hit) {
          uni.showToast({
            title: "很遗憾，您不符合本次活动的领取条件哦",
            duration: 2500,
            icon: "none"
          });
        } else {
          uni.showToast({
            title: "已领取成功",
            icon: "none"
          });
          this.getKaDataFn(); // 获取页面信息
        }
      } else {
        this.getKaDataFn(); // 获取页面信息
      }
    },
    // 验证是否是白名单back
    async getWhiteUserBack() {
      if (+this.templateVersion === 5) {
        const [res] = await getWhiteUser({
          vccChannel: this.vccChannel,
          sonVccChannel: this.sonVccChannel
        });
        this.whiteUserState = res.is_hit;
        if (res.is_hit) {
          this.getKaDataFn(); // 获取页面信息
        }
      } else {
        this.getKaDataFn(); // 获取页面信息
      }
    },
    // 马上抢埋点
    rightAway() {
      saTrackEvent("MINI_KAChannelActivityPageBtnClick", {
        parent_channel_id: uni.getStorageSync("vccChannel") || "",
        son_channel_id: uni.getStorageSync("sonVccChannel") || "",
        buttons_name: "马上抢"
      });
    },
    // 判断登录
    loginPopupFn() {
      if (!uni.getStorageSync("token")) {
        this.$refs["login-popup"].open();
      }
    },
    // 已领取优惠券
    couponReceiveEnd() {
      uni.showToast({
        title: "已领取,快使用享花卡购物",
        icon: "none"
      });
    },
    // 跳转vcc流程
    openVcc(type) {
      const vm = this;
      vm.popupSwitch = false;
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/webview/webview?channel=ka&vccChannel=${vm.vccChannel}&sonVccChannel=${vm.sonVccChannel}`
        });
      }, 500);
      if (type) {
        saTrackEvent("MINI_KAChannelActivityPageApplyVccPopupBtnClick", {
          page_url: "pages/channel/goodsList",
          parent_channel_id: uni.getStorageSync("vccChannel") || "",
          son_channel_id: uni.getStorageSync("sonVccChannel") || "",
          buttons_name: "立即开通"
        });
      } else {
        saTrackEvent("MINI_KAChannelActivityPageVccRetainPopupBtnClick", {
          page_url: "pages/channel/goodsList",
          parent_channel_id: uni.getStorageSync("vccChannel") || "",
          son_channel_id: uni.getStorageSync("sonVccChannel") || "",
          buttons_name: "立即开通"
        });
      }
    },
    XHKPopupChange(val) {
      if (!val.show && this.popupSwitch) {
        this.$refs["subPopup"].open();
        saTrackEvent("MINI_KAChannelActivityPagePopupExposure", {
          page_url: "pages/channel/goodsList",
          parent_channel_id: uni.getStorageSync("vccChannel") || "",
          son_channel_id: uni.getStorageSync("sonVccChannel") || "",
          popupwindow_name: "挽留"
        });
        saTrackEvent("MINI_KAChannelActivityPageApplyVccPopupBtnClick", {
          page_url: "pages/channel/goodsList",
          parent_channel_id: uni.getStorageSync("vccChannel") || "",
          son_channel_id: uni.getStorageSync("sonVccChannel") || "",
          buttons_name: "取消"
        });
        this.popupSwitch = true;
      }
    },
    // 商品详情
    goDoodsDetail(good) {
      if (!good) {
        saTrackEvent("MINI_KAChannelActivityPageVccRetainPopupBtnClick", {
          page_url: "pages/channel/goodsList",
          parent_channel_id: uni.getStorageSync("vccChannel") || "",
          son_channel_id: uni.getStorageSync("sonVccChannel") || "",
          buttons_name: "残忍拒绝"
        });
      }
      if (!this.userInfo.hasLogin) {
        this.loginPopupFn();
        return false;
      }
      let channelState;
      if (!good) {
        good = this.goodData;
        channelState = "";
      } else if (good && this.vccState) {
        channelState = "";
      } else {
        channelState = "ka";
      }
      debounce(
        uni.navigateTo({
          url: `/pages/product/goodDetail?skuNo=${
            good.goods.goodsId
          }&count=1&receiverId=&goodsName=${encodeURIComponent(good.goods.goodsName)}&goodsImage=${
            good.goods.goodsImage
          }&channel=${channelState}`
        }),
        300
      );
    },

    goVcc(good) {
      saTrackEvent("PD_YXMMACP_UserClickKaPageCommodityPage", {
        parent_channel_id: uni.getStorageSync("vccChannel") || "",
        son_channel_id: uni.getStorageSync("sonVccChannel") || ""
      });
      if (!this.userInfo.hasLogin) {
        this.loginPopupFn();
        return false;
      }
      this.goodData = good;
      this.popupSwitch = true;
      this.$refs["commonPopup"].open();
      saTrackEvent("MINI_KAChannelActivityPagePopupExposure", {
        page_url: "pages/channel/goodsList",
        parent_channel_id: uni.getStorageSync("vccChannel") || "",
        son_channel_id: uni.getStorageSync("sonVccChannel") || "",
        popupwindow_name: "申请享花卡"
      });
    },
    // 获取ka流程是否走完
    async kaFlowState() {
      if (!this.userInfo.hasLogin) {
        this.loginPopupFn();
        return false;
      }
      const [data] = await kaFlow();
      this.vccState = data.value;
      // this.vccState = false;
    },
    // 获取地址
    async getAddr() {
      const token = uni.getStorageSync("token") || "";
      if (token) {
        // const [addressInfo] = await addrList();
      }
    },
    //查询优惠券列表
    async getCouponList() {
      let couponData = [];
      const vm = this;
      const result = [];
      const obj = {};
      vm.searchCouponIds = [];
      vm.couponListData = [];
      vm.couponsNull = false;
      const [res] = await couponList({
        couponIds: this.couponIds,
        queryCanReceiver: false
      });
      couponData =
        res?.coupons.filter(item => {
          return (
            item.pickupAble ||
            (!item.pickupAble &&
              item.endDate &&
              item.currentTime &&
              !item.publishCountFinished &&
              new Date(item.endDate.replace(/-/g, "/")).valueOf() >=
                new Date(item.currentTime.replace(/-/g, "/")).valueOf())
          );
        }) || [];
      if (!couponData.length) {
        vm.couponsBtn = false;
      } else {
        vm.couponsBtn = true;
        for (var i = 0; i < couponData.length; i++) {
          if (!obj[couponData[i].id]) {
            result.push(couponData[i]);
            obj[couponData[i].id] = true;
          }
        }
        vm.couponListData = result;
        vm.$forceUpdate();
        let couponObj = vm.couponListData.filter(item => {
          return item.couponCategory === 21;
        });
        vm.couponListData.forEach(item => {
          vm.searchCouponIds.push(item.id);
        });
        vm.searchCouponIds = vm.searchCouponIds.toString();
        if (couponObj.length) {
          vm.couponsNull = true;
          vm.couponNum = Number(couponObj[0].faceValue);
        } else {
          vm.couponsNull = false;
        }
        if (vm.couponListData.length) {
          if (vm.couponListData.length === 1) {
            vm.couponPickupList = [
              {
                couponId: vm.couponListData[0].id,
                pickupNum: vm.couponListData[0].receiverLimitCount || 1
              }
            ];
          } else {
            vm.couponListData.forEach(item => {
              vm.couponPickupList.push({
                couponId: item.id,
                pickupNum: item.receiverLimitCount || 1
              });
            });
          }
        }
        if (vm.userInfo.hasLogin) {
          vm.couponReceive();
        }
      }
    },
    //用户领取优惠券
    async getCouponPickup() {
      saTrackEvent("PD_YXMMACP_UserClickKaPageGetCoupon", {
        parent_channel_id: uni.getStorageSync("vccChannel") || "",
        son_channel_id: uni.getStorageSync("sonVccChannel") || ""
      });
      saTrackEvent("MINI_KAChannelActivityPageBtnClick", {
        parent_channel_id: uni.getStorageSync("vccChannel") || "",
        son_channel_id: uni.getStorageSync("sonVccChannel") || "",
        buttons_name: "一键领取"
      });
      if (!this.userInfo.hasLogin) {
        this.loginPopupFn();
        return false;
      }

      const [result] = await getWhiteUser({
        vccChannel: this.vccChannel,
        sonVccChannel: this.sonVccChannel
      });
      this.whiteUserState = result.is_hit;
      if (+this.templateVersion === 5) {
        if (!this.whiteUserState) {
          uni.showToast({
            title: "很遗憾，您不符合本次活动的领取条件哦",
            icon: "none"
          });
          return false;
        }
      }

      let person = [...this.couponPickupList];
      let obj = {};
      let peon = person.reduce((cur, next) => {
        obj[next.couponId] ? "" : (obj[next.couponId] = true && cur.push(next));
        return cur;
      }, []);
      const [res] = await couponPickup({
        couponPickupList: peon,
        systemSendCoupon: true
      });
      if (res) {
        // this.couponState = true;
        uni.showToast({
          title: "领取成功,使用享花卡购物",
          icon: "none"
        });
        this.couponReceive();
      }
    },
    // 领取优惠券状态
    async couponReceive() {
      const [res] = await searchCoupon({
        couponIds: this.searchCouponIds
      });
      this.couponState = res.allHasPickup;
      this.$forceUpdate();
    },
    //商品列表
    async getSearchGoodsList() {
      const vm = this;
      // vm.searchGoodsListData = []
      if (!this.noMore || this.progress === "loading") return;
      this.progress = "loading";
      if (this.goodsListState) {
        const [data = {}] = await searchGoodsList({ ...this.params });
        this.progress = "finished";
        this.params.pageNo++;
        this.goodsListTempData = data.goodsList || [];
        this.goodsListState = data.hasNext;
        if (data.goodsList !== undefined) {
          data.goodsList.forEach(item => {
            item.goods.goodsCouponPrice = vm.floatSub(item.goods.goodsSalePrice, vm.couponNum);
            if (Number(item.goods.goodsCouponPrice) < 0) {
              item.goods.goodsCouponPrice = 0;
            }
          });
        }
        this.searchGoodsListData = [...this.searchGoodsListData, ...this.goodsListTempData];
      }
      if (!this.goodsListState && +this.templateVersion !== 5) {
        const [goodsData = {}] = await getGoodsList(this.goodsData);
        this.goodsData.pageNo++;
        this.progress = "finished";
        goodsData.goodsList = goodsData.goodsList || [];
        goodsData.goodsList.forEach(item => {
          item.goods.goodsCouponPrice = vm.floatSub(item.goods.goodsSalePrice, vm.couponNum);
          if (Number(item.goods.goodsCouponPrice) < 0) {
            item.goods.goodsCouponPrice = 0;
          }
        });
        this.noMore = goodsData.hasNext;
        this.searchGoodsListData = [...this.searchGoodsListData, ...goodsData.goodsList];
      } else {
        this.noMore = false;
      }
      // this.noMore = goodsData.hasNext;
      // this.searchGoodsListData = [...this.searchGoodsListData, ...data.goodsList, ...goodsData.goodsList];
    },
    floatSub(arg1, arg2) {
      var r1, r2, m, n;
      try {
        r1 = arg1.toString().split(".")[1].length;
      } catch (e) {
        r1 = 0;
      }
      try {
        r2 = arg2.toString().split(".")[1].length;
      } catch (e) {
        r2 = 0;
      }
      m = Math.pow(10, Math.max(r1, r2));
      //动态控制精度长度
      n = r1 >= r2 ? r1 : r2;
      return ((arg1 * m - arg2 * m) / m).toFixed(n);
    }
  }
};
</script>

<style lang="scss">
@import "./index";
</style>
