<template>
  <section class="coupon-list-wrapper" :class="{'no-pt': isWeb}">
    <CommonNavbar
      :isWeb="isWeb"
      ref="navBarCom"
      :bgColor="bgColor"
      v-if="isShowNavbar"
      :title="navTitle"
      :isFixNavbar="isFixNavbar"
      :isInMergeDetail="isInMergeDetail"
      borderStyle="1px solid #fff"
    ></CommonNavbar>
    <CouponList
      v-if="dataList.length"
      :dataList="dataList"
      @revieveOrUse="revieveOrUse"
      :fromPage="fromPage"
    ></CouponList>
    <no-coupon v-else></no-coupon>
  </section>
</template>
<script>
import CommonNavbar from "@/components/common/common-navbar";
import CouponList from "@/components/coupon/component-list";
import NoCoupon from "@/components/coupon/no-coupon";
import { getWebPageUrl, getHactiveUrl } from "@/utils";
import { mapGetters, mapActions } from "vuex";
import { Toast } from "vant";
import { setCookie, getCookie, delCookie } from "@/utils/index";

export default {
  components: {
    CommonNavbar,
    CouponList,
    NoCoupon
  },
  data() {
    return {
      token: "",
      isWeb: window.__isWeb,
      bgColor: "#fff",
      isShowNavbar: true,
      navTitle: "优惠券",
      isFixNavbar: true,
      shareUrl: "",
      dataList: [],
      provinceId: "",
      fromPage: "",
      isInMergeDetail: false
    };
  },
  computed: {
    ...mapGetters(["webUserInfo"])
  },

  watch: {
    webUserInfo: {
      handler(userInfo) {
        console.log("userInfo", userInfo);
        if (userInfo.id) {
          this.getAllCoupons();
        }
      },
      deep: true
    }
  },

  created() {
    let _this = this;
    let href = location.href;
    this.couponId = this.$route.query.couponId || "";
    this.fromPage = this.$route.query.fromPage || "";
    this.couponToken = this.$route.query.couponToken || "";

    this.navTitle = this.fromPage ? "我的优惠券" : "优惠券";
    this.shareUrl = getWebPageUrl(
      `profexam/#/coupon-list?couponId=${this.couponId}`
    );
    if (href.indexOf("singlemessage") >= 0 || href.indexOf("wx_code") >= 0) {
      location.replace(this.shareUrl);
    }
    localStorage.setItem("returnUrl", this.shareUrl);

    if (this.fromPage) {
      this.$sendBuriedData({
        component_tag: `506#50601`
      });
    }

    window.__getUserInfo4CouponList = function(param) {
      console.log("__getUserInfo4CouponList", param);
      _this.token = param.userToken;
      _this.setUserInfo(param);
      _this.getAllCoupons();
    };

    window.__refresh = function() {
      _this.getUserInfo();
    };
  },

  mounted() {
    // 如果在浏览器或微信里
    if (this.isWeb) {
      const { token, info } = this.$store.state.user;
      this.token =
        token ||
        this.couponToken ||
        localStorage.getItem("couponToken") ||
        getCookie("couponToken");
      if (this.token && !info.id) {
        console.log("4444 this.token", this.token);
        // this.$store.dispatch('setToken', this.token);
        this.commonCheckToken(() => {
          this.$store.dispatch("setToken", this.token);
          // this.$store.dispatch("getUserInfo");
        });
        return;
      }
      // 从登陆页面过来的
      this.getAllCoupons();
    } else {
      this.getUserInfo();
    }
  },
  methods: {
    //获取用户信息
    getUserInfo() {
      rocNative.getUserInfo({
        __funcName: "__getUserInfo4CouponList"
      });
    },

    // 获取我的优惠券列表
    getMyCoupons() {
      this.commonCheckToken(() => {
        this.GET(`trade/coupon/app/myCoupons`, {}).then(res => {
          if (res.code == "000000") {
            this.provinceId = res.data.provinceId;
            this.dataList = this.handlerAllCouponList(
              res.data.baseCouponModelList || [],
              false
            );
          }
        });
      });
    },

    // 主动领取优惠券
    // 状态码：1已下架，请领取其他优惠券 2优惠券已失效 3已领取，快去使用优惠券 4优惠券已领完 5成功领取
    receiveCouponByid(couponId) {
      this.commonCheckToken(() => {
        this.POST(`trade/coupon/app/receive/${couponId}`, {}).then(
          ({ code, data }) => {
            if (code == "000000") {
              console.log("data.description", data.description);
              data.description && Toast(data.description);
              this.searchCoupons();
            }
          }
        );
      });
    },

    // 处理(所有)列表数据
    // couponStatus 优惠券状态：0去领取 1去使用 2已领取 3无库存 4未开始 5已过期 6已使用
    handlerAllCouponList(couponList, isAll) {
      if (!couponList.length) return [];
      let newList = [],
        obj = {};
      couponList.forEach(item => {
        // 是否是列表页面，否则是我的优惠券页面
        item.isAll = isAll;
        // 是否显示对应的规则
        item.showRules = false;
        // 是否可用
        item.disabled =
          item.couponStatus == 0 ||
          item.couponStatus == 1 ||
          item.couponStatus == 4;
        newList.push(item);
      });
      console.log(newList);
      return newList;
    },

    // 获取所有优惠券列表
    getAllCoupons() {
      console.log("getAllCoupons");
      this.commonCheckToken(() => {
        let couponId = this.couponId;
        if (couponId) {
          this.POST(`trade/coupon/app/receive/${couponId}`, {}).then(
            ({ code, data }) => {
              if (code == "000000") {
                if (data.description) {
                  this.$toast({ message: data.description, duration: 5000 });
                }
              }
              this.searchCoupons();
            }
          );
        } else {
          this.searchCoupons();
        }
      });
    },

    // 区分是否是我的优惠券
    searchCoupons() {
      this.wechatShare(
        {
          link: this.shareUrl,
          title: "我在抢优惠券，你也快来吧！",
          friendtitle: "限时优惠，机不可失！",
          desc: "限时优惠，机不可失！",
          imgUrl: "https://file.yunqueyi.com/logo.png"
        },
        () => {
          console.log("share success...");
        }
      );
      if (this.fromPage) {
        this.getMyCoupons();
      } else {
        this.searchCouponsAction();
      }
    },

    // 查询所有优惠券列表
    searchCouponsAction() {
      let params = {
        cardTypes: [],
        couponIds: [],
        goodsIds: [],
        goodsTypes: []
      };
      this.POST(`trade/coupon/app/searchCoupons`, params).then(res => {
        if (res.code == "000000") {
          this.provinceId = res.data.provinceId;
          this.dataList = this.handlerAllCouponList(
            res.data.baseCouponModelList || [],
            true
          );
        }
      });
    },

    // 领取或使用 couponStatus 0: 立即领取; 1: 去使用;
    revieveOrUse(item) {
      // 跳转到使用页面（如果只适用一个商品，则直接跳转到商品页面；否则跳转到商品列表页面）
      // 要根据用户信息，获取定位信息等，从而获取对应的商品
      // TODO

      if (this.fromPage) {
        this.$sendBuriedData({
          component_tag: `506#50602#${item.couponId}#${item.couponName}`
        });
      }
      // 去使用
      if (item.couponStatus == 1) {
        let couponList = item.couponMappingModelList, index = -1;
        index = couponList.findIndex( i => {
          return i.goodsType == 3;
        });
        // 在站内，如果是职称考卡，则直接跳转到职称考首页
        if(!this.isWeb && index >= 0) {
          let pageUrl = getWebPageUrl(`profexam/#/index`);
          this.jumpForCoupon(pageUrl);
          return;
        }

        let pageUrl = "";
        // 如果适用的商品（卡）个数多于一个，则跳转到商品列表
        if (item.couponMappingModelList.length > 1) {
          pageUrl = getHactiveUrl(
            `/message_push/#/study-card?origin=1&couponArea=${this.provinceId}&couponToken=${this.token}`
          );
          this.jumpForCoupon(pageUrl);
        } else {
          item.couponMappingModelList.length &&
            this.getCardInfoByProvinceId(item);
        }
        // 立即领取
      } else if (item.couponStatus == 0) {
        this.receiveCouponByid(item.couponId);
      }
    },

    // 根据省ID，获取学习卡信息
    getCardInfoByProvinceId(item) {
      let coupon = item.couponMappingModelList[0];
      let param = {
        area: this.provinceId + "",
        cardType: coupon.cardType || 3,
        cardTypeList: [coupon.cardType || 3],
        goodsType: coupon.goodsType
      };
      param.setEntry = true;
      this.POST("trade/goods/cardList_v2", param).then(res => {
        if (res.code == "000000") {
          let good = (res.data && res.data[0]) || {
            id: "",
            name: "职称考精讲课程卡"
          };
          if (good.id) {
            let pageUrl = getWebPageUrl(
              `profexam/#/goods-detail?goodsId=${good.id}`
            );
            this.jumpForCoupon(pageUrl);
          } else {
            Toast("相关商品已下架");
          }
        }
      });
    },

    // 根据环境跳转
    jumpForCoupon(pageUrl) {
      if (this.isWeb) {
        location.href = pageUrl;
      } else {
        let paramList = [
          {
            key: "pageUrl",
            value: pageUrl,
            type: 4,
            seqNo: 1
          }
        ];
        rocNative &&
          rocNative.dispatchEventByModuleCode({
            modeCode: "M300",
            jsonString: paramList
          });
      }
    }
  }
};
</script>
<style lang="less" scoped>
.coupon-list-wrapper {
  padding-top: 88px;
  min-height: 100vh;
  background: #f8f9fa;
  &.no-pt {
    padding-top: 10px;
  }
}
</style>