<template>
  <!-- 支付成功页 -->
  <div class="paySuccess" v-if="showPage" :style="{'--main-color':themeColor['--main-color'],'--minor-color':themeColor['--minor-color']}">
    <ThemeDataPlant :pageCode="11"></ThemeDataPlant>
    <PayElectronCard v-if="orderDetail.orderType==15" :orderDetail="orderDetail"></PayElectronCard>
    <div v-else>
      <div style="margin-top: 60px;"></div>
      <div v-for="(item, index) in pageData" :key="index">
        <!-- 其他组件 -->
        <div
          v-if="item.componentCode == 'text-text' && item.componentInfo.visible == 1"
        >
          <text-text :datas="item"></text-text>
        </div>
        <div
          v-if="item.componentCode == 'rich-text' && item.componentInfo.visible == 1"
        >
          <rich-text :datas="item"></rich-text>
        </div>
        <div
          v-if="item.componentCode == 'photo-gallery' &&item.componentInfo.visible == 1"
        >
          <photo-gallery :datas="item"></photo-gallery>
        </div>
        <div
          v-if="item.componentCode == 'interval' && item.componentInfo.visible == 1"
        >
          <interval :datas="item"></interval>
        </div>
        <div
          v-if="item.componentCode == 'partition' && item.componentInfo.visible == 1"
        >
          <partition :datas="item"></partition>
        </div>
        <div
          v-if="item.componentCode == 'notice' && item.componentInfo.visible == 1"
        >
          <notice :datas="item"></notice>
        </div>
        <!-- 营销组件 -->
        <div v-if="item.componentCode == 'coupon' && item.componentInfo.visible == 1">
          <coupon :datas="item"></coupon>
        </div>
        <div v-if="item.componentCode == 'time-limited-discount' && item.componentInfo.visible == 1">
          <time-limited-discount :class="'time-limited-discount'+index" :datas="item" :k="index"></time-limited-discount>
        </div>
        <div v-if="item.componentCode == 'integral-turntable' && item.componentInfo.visible == 1">
          <integralTurntable :datas="item"></integralTurntable>
        </div>
        <div v-if="item.componentCode == 'live-broadcast' && item.componentInfo.visible == 1">
          <live-broadcast :datas="item"></live-broadcast>
        </div>
        <div v-if="item.componentCode == 'spell-group' && item.componentInfo.visible == 1">
          <spell-group :datas="item"></spell-group>
        </div>
        <div v-if="item.componentCode == 'official-account' && item.componentInfo.visible == 1">
          <official-account></official-account>
        </div>
        <pay-success-info
          v-if="item.componentCode=='pay-success-info'  && item.componentInfo.visible==1"
          :render="true"
          :datas="item"
          :giftsKey="giftsKey"
          :routeQuery="routeQuery"
          :orderDetail="orderDetail"
          :totalMoney="totalMoney"
          :whetherOpenEnterprisesWantGoods="whetherOpenEnterprisesWantGoods"
          :whetherOpenApproval="whetherOpenApproval"
        />
      </div>
    </div>
    <automati-Card :showReceiveCard="showReceiveCard" @closeHandle="closeHandle" :cardInfo="cardInfo"></automati-Card>
    <!-- 分销员弹框入口 -->
    <van-popup
      class="spokemanEntry"
      closeable
      :show="showspokmanEntry"
      position="center"
      :close-on-click-overlay="false"
      close-icon="close"
      @close="closeSpokenman"
    >
      <!-- <div class="ent_box"> -->
      <div class="ent-top">
        <p style="font-size:45px;color:rgba(83,37,26,1);">恭喜</p>
        <p style="font-size:16px;color:rgba(83,37,26,1);">您获得分销员申请指标</p>
        <p style="font-size:11px;color:#53251A;">提示:可以在【我的】-【分销员中心】查看</p>
      </div>
      <div style="width:100%;display:flex;justify-content: center;">
        <p class="reviwBtn" @click="toSpokesmanCenter">立即查看</p>
      </div>
      <p class="ignore" @click="showspokmanEntry=false">跳过</p>
      <!-- </div> -->
    </van-popup>
  </div>
</template>

<script type="text/ecmascript-6">
import shop from "@/api/shop";
import order from "@/api/order";
import promote from "@/api/promote";
import spokesman from "@/api/spokesman";
import { getMiniProgram, query_isEntry } from "@/utils/mayi_fenxiao";
import { serialize } from "@/utils/index";
import { checkTabbarPage, checkShowConditionIds, themeColor } from "@/utils/mayi";
import ThemeDataPlant from "@/components/ThemeDataPlant";
import paySuccessInfo from "@/components/paySuccess/paySuccessInfo";
import PayElectronCard from "@/components/paySuccess/PayElectronCard";
import automatiCard from "@/components/paySuccess/automatiCard";
import text from "@/components/content/text";
import richText from "@/components/basicTool/rich-text";
import interval from "@/components/basicTool/interval/index.vue";
import partition from "@/components/basicTool/partition/index.vue";
import coupon from '@/components/activity/coupon'
import integralTurntable from '@/components/activity/integralTurntable'
import spellGroup from '@/components/activity/spellGroup'
import tool from '@/utils/tool.js'
const app = getApp();
const { log } = app;
export default {
  name: "",
  data() {
    return {
      query: {
        orderSn: "",
      },
      routeQuery: {},
      title: "",
      inviteelShow: false,
      isGroupBuy: false, //是否是拼团订单
      totalMoney: 0,
      orderDetail: {},
      showGuide: false,
      showspokmanEntry: false, //分销员弹框
      goodsId: "",
      orderId: "",
      orgName: "",
      splitStatus: "0", //拆单状态(0:未拆单;1:已拆单)已拆单时付款后跳订单列表
      giftsKey: 0,
      showReceiveCard: false,
      cardInfo: {},
      cardTime: null,
      cardnum: 0,
      pageInfo: {},
      pageData: {},
      showPage: false,
      systemInfo : {},
      tabbarHeight : 0,
      themeColor:{
        '--main-color':"",
        '--minor-color':"",
      },
    };
  },
  components: {
    ThemeDataPlant,
    "text-text": text,
    "rich-text": richText,
    interval,
    partition,
    paySuccessInfo,
    PayElectronCard,
    automatiCard,
    coupon,
    integralTurntable,
    spellGroup,
  },
  computed: {
    // 是否开启企业要货
    whetherOpenEnterprisesWantGoods() {
      let { shopInfo } = this.mpApp.globalData;
      let whetherOpenEnterprisesWantGoods = shopInfo ? shopInfo.whetherOpenEnterprisesWantGoods : 0
      return whetherOpenEnterprisesWantGoods;
    },
    // 是否开启待审核
    whetherOpenApproval() {
      let whetherOpenApproval = this.mpApp.shop_configuration ? this.mpApp.shop_configuration.whetherOpenApproval : 0;
      return whetherOpenApproval;
    },
  },
  onLoad(options) {
    console.log(options, "--paySuccess-onLoad");
    this.query.orderSn = options.orderSn;
    this.routeQuery = options;
    this.orderMsg();
    this.setGiftsKey(); //设置码表
    this.getIsReceiveGift()
    // 获取页面数据
    if (this.mpApp.globalData.pageList) {
      console.log(
        this.mpApp.globalData.pageList,
        "-----------------this.mpApp.globalData.pageList"
      );
      this.init(this.mpApp.globalData.pageList);
    } else {
      this.mpApp.pageCallBack = (params) => {
        console.log(params, "-----------------this.mpApp.globalData.pageList");
        that.init(params);
      };
    }
    this.systemInfo = wx.getSystemInfoSync()
    console.log(this.systemInfo,'-----------systemInfo')
    let menuButtonInfo = wx.getMenuButtonBoundingClientRect()
    console.log(menuButtonInfo,'menuButtonInfo')
    this.tabbarHeight = (menuButtonInfo.top - this.systemInfo.statusBarHeight) * 2 + menuButtonInfo.height + this.systemInfo.statusBarHeight
    console.log(this.tabbarHeight,'-----------tabbarHeight')
    if(themeColor['--main-color']!='#ffffff'){
      this.themeColor = themeColor
    }else {
      this.mpApp.themeColorCallBack=(res)=>{
        this.themeColor = res
      }
    }
  },
  onShow() {
    console.log("--paySuccess-onShow");
  },
  // 滚动节流方法
  onPageScroll: tool.throttle(function (el) {
  console.log(el,'--onPageScroll');
  this.scrolls(el[0])
  },200),
  methods: {
    scrolls(el){
      // this.setFooterShow(el);
      if (this.pageData) {
        for (let i = 0; i < this.pageData.length; i++) {
          const element = this.pageData[i]
          if(element.componentCode=="time-limited-discount"){
            let com=this.$mp.page.selectComponent(".time-limited-discount"+i) ;
            com && com.getScroll(el);
          }
          if(element.componentCode=="goods-list"){
            let com=this.$mp.page.selectComponent(".goodsListItem"+i) ;
            com && com.getScroll(el);
          }
          if(element.componentCode=="merchants-list"){
            let com=this.$mp.page.selectComponent(".merchants-list"+i) ;
            com && com.getScroll(el);
          }
          if(element.componentCode=="video-player"){
            console.log("视频组件滚动")
            let com=this.$mp.page.selectComponent(".VideoPlayer"+i);
            console.log(com,i,'--com')
            com && com.getScroll(el);
          }

        }
      }

      if(this.$mp.page && this.$mp.page.selectComponent(".getIndexHomePage")){
        this.$mp.page.selectComponent(".getIndexHomePage").getScroll(el);
      }
      if(this.$mp.page && this.$mp.page.selectComponent(".goodsListItem")){
        this.$mp.page.selectComponent(".goodsListItem").getScroll(el);
      }
      if(this.$mp.page && this.$mp.page.selectAllComponents(".transverse-label-goodsListItem")){
        this.$mp.page.selectAllComponents(".transverse-label-goodsListItem").forEach(item=>{
          console.log(item,'-this.$mp.page.selectComponent(".goodsListItem")')
          item.getScroll(el)
        })
      }
    },
    orderMsg() {
      order.orderDetail(this.query).then(res1 => {
        let res = res1.data;
        if (res.code == 200) {
          console.log("----------------------------------2")
          if(res.data.orderType == '14') {
            this.isGroupBuy = true;
            let url = `/pages/index/main?from=home&backpath=${encodeURIComponent(`/groupBuying/invite?orderSn=${this.query.orderSn}&isReplace=true`)}`
            wx.redirectTo({
              url,
            });
            this.title = "拼团详情"
          }else {
            this.title = "支付成功"
            this.showPage = true;
          }
          this.splitStatus=res.data.splitStatus;
          this.orderId = res.data.orderId;
          this.orgName = res.data.orgName;
          if(res.data.noShipmentOrderItems&&res.data.noShipmentOrderItems.length) {
            this.goodsId =
              res.data.noShipmentOrderItems[0].terminalProductGoodsId;
          }

          //查询是否是分销员
          getMiniProgram().then(res1 => {
            console.log(res1,'---------------------------res1143')
            let res = res1.data;
            if (
              res.code == "200" &&
              (!res.data || res.data.spokesmanFlag !== "1")
            ) {
              query_isEntry().then(res1 => {
                let res = res1.data;
              if (
                res.code == "200" &&
                res.data &&
                res.data != "null" &&
                res.data != "false"
              ) {
                if (res.data.displayEntry == 'true'&&res.data.remind == "true") {
                  //查询是否达标
                  spokesman.subordinateSpokesmanProfit(res.data.distributionModel).then(res1 => {
                    let res = res1.data;
                    if (
                      res.code == "200" &&
                      res.data &&
                      res.data.thresholdToStandard == "1"
                    ) {
                      this.showspokmanEntry = true;
                    }
                  });
                } else {
                  this.showspokmanEntry = false;
                }
              }
            });
            }
          });
          this.orderDetail = res.data;
          if (
            this.orderDetail.orderType == 5
          ) {
            this.initWxShare();
          }
          this.totalMoney = Number(res.data.totalAmountPayable).toFixed(2);
          console.log(Number(res.data.totalAmountPayable).toFixed(2),'--Number(res.data.totalAmountPayable).toFixed(2)')
          this.inviteelShow = true;
        }else {
          this.inviteelShow = true;
        }
      });
    },
    setGiftsKey() {
      shop.get_system_config_by_code({code:'GIFTS_KEY'}).then(res1 => {
        let res = res1.data;
        if(res.code == '200'){
          this.giftsKey = res.data;
          console.log(this.giftsKey,'-----giftsKey')
        }
      })
    },
    closeSpokenman() {
      this.quitWarn();
    },
    quitWarn() {
      apply_for_withdraw({type:'remindFlag'}).then(res => {
        if (res.data.data == "true") {
        }
      });
    },
    toSpokesmanCenter() {
      let url = `/pages/index/main?from=home&backpath=${encodeURIComponent(`/personalCenter/spokesmanCenter`)}`
       wx.redirectTo({
        url,
      });
    },
    getIsReceiveGift(){
      this.cardTime =  setInterval(() => {
        if(this.cardnum >5){
          clearInterval(this.cardTime);
        }
        promote.queryisReceiveGift().then(res1 =>{
          let res = res1.data;
          if(res.code == 200){
            this.cardnum++;
              console.log(res.data,'parmas=====')
              if(res.data){
                clearInterval(this.cardTime);
                if(res.data.receiveStatus == 1 && res.data.cardGiftGoods && res.data.cardGiftGoods.length>0){
                  this.showReceiveCard = true;
                  this.cardInfo = res.data;
                }
              }
          } else {
            clearInterval(this.cardTime);
          }
        })
      }, 2000);
    },
    closeHandle(){
      this.showReceiveCard = false;
    },
    async initWxShare() {
      return
      let this_ = this;
      console.log(this.$store.state.spokemanInfo,'分销员信息---=====');
      let spokesmanRelId;
      let spokesmanGroupId;
      let spokesmanShopId
      let spokemanInfo=this.$store.state.spokemanInfo;
      if (spokemanInfo) {
        if (spokemanInfo.hasInvitationStatus == 1) {
          spokesmanRelId=spokemanInfo.spokesmanId;
          spokesmanGroupId=spokemanInfo.groupId;
          spokesmanShopId=spokemanInfo.shopId;
        }
      }

      console.log(spokesmanRelId,'分销员信息---=====',spokesmanGroupId,spokesmanShopId);
      let newWindowHref = '';
       if(getTokenmu() && spokesmanRelId){
        newWindowHref = `${process.env.BASE_URL}/activty/receivingGift?mixid=${this.$route.query.mixid}&orderId=${this.orderDetail.orderId}&spokesmanGroupId=${spokesmanGroupId}&spokesmanShopId=${spokesmanShopId}&spokesmanRelId=${spokesmanRelId}&userId=${getTokenmu()}`;
      }else {
        newWindowHref = `${process.env.BASE_URL}/activty/receivingGift?mixid=${this.$route.query.mixid}&orderId=${this.orderDetail.orderId}&userId=${getTokenmu()}`;
      }

      let shareImgUrl = DFSImg(
        this.orderDetail.noShipmentOrderItems[0].specificationPictureUrl,
        500,
        400
      );
      let orgName = this.orderDetail.orgName;
      let shareData="";
      await shop.indexWxShare({storeRouterUrl : '/activty/receivingGift'}).then(res => {
        if(res.code == 200){
          shareData = res.data
        }
      })
      let shareText=shareData&&shareData.shareText?shareData.shareText:'我选了一份小礼物送你,赶紧收下吧!免费的哦~';
      this.$customShare.customShare(
        shareText,
        newWindowHref,
        '',
        DFSImg('https://mayi-newshop.oss-cn-shanghai.aliyuncs.com/public/png/b9f3fdd1-513f-46df-aed2-7f42330beaca.png',500,460),
        this.$store.state.wechatSignUrl
      )
    },
    init() {
      console.log("----------------------207");
      this.setVisible(this.mpApp.globalData.pageList, (res) => {
        console.log(res,'-----------------------res120')
        this.pageInfo = res;
        this.pageData = JSON.parse(this.pageInfo.pageData);
        console.log(this.pageData, "----------pageData");
      });
    },
    async setVisible(pageList, cb) {
      // 首页显示条件
      let pageInfo = pageList.filter((item) => item.pageCode == 11)[0];
      console.log(pageInfo, "-----------pageInfo");
      let pageData = JSON.parse(pageInfo.pageData);
      // 查询显示条件id
      let showConditionIds = checkShowConditionIds(pageData);
      // 查询可显示的条件
      let { data: ids, isAreaNavigation } = await this.checkCondition(
        showConditionIds
      );
      console.log(ids,'--------------showConditionIds')
      // 没有定位组件
      // if (!isAreaNavigation) {
      //   cb()
      //   return
      // }
      // 设置visible
      pageInfo.pageData = this.updateCondition(pageData, ids);
      log.info(showConditionIds, "--------------5454", ids, pageInfo);
      cb(pageInfo);
    },
    checkCondition({ allCondition }) {
      console.log('---checkCondition')
      return new Promise((resolve, reject) => {
        // 获取
        let params = { showConditionIds: allCondition, region: "" };
        shop
          .checkShowCondition(params)
          .then((res) => {
            console.log('-------------------157')
            log.info(params, "check显示条件", res.data);
            if (res.data.code == 200) {
              resolve(res.data);
            }
          })
          .catch((err) => {
            log.info("check显示条件失败", err);
          });
      });
    },
    updateCondition(pageData, ids) {
      pageData.forEach((item) => {
        pollCondition(item);
      });
      function pollCondition(data) {
        if (Object.prototype.toString.call(data) === "[object Object]") {
          if (
            data.visible &&
            data.visible > 1 &&
            data.visibleCopy == undefined
          ) {
            data.visibleCopy = data.visible;
            console.log(data.visibleCopy, "--data.visibleCopy");
          }
          if (
            (data.visibleCopy == 2 && wx.getStorageSync("sessionid")) ||
            (data.visibleCopy == 3 && !wx.getStorageSync("sessionid"))
          ) {
            data.visible = 1;
          } else if (
            (data.visibleCopy == 2 && !wx.getStorageSync("sessionid")) ||
            (data.visibleCopy == 3 && wx.getStorageSync("sessionid"))
          ) {
            data.visible = 0;
          } else {
            if (data.condition != "" && data.condition != undefined) {
              data.visible = ids.some((item) => {
                return item == data.condition;
              })
                ? 1
                : 0;
            }
          }
          for (const key in data) {
            if (data.hasOwnProperty(key)) {
              const element = data[key];
              if (
                Object.prototype.toString.call(element) === "[object Object]"
              ) {
                if (
                  element.visible &&
                  element.visible > 1 &&
                  element.visibleCopy == undefined
                ) {
                  element.visibleCopy = element.visible;
                }
                if (
                  (element.visibleCopy == 2 &&
                    wx.getStorageSync("sessionid")) ||
                  (element.visibleCopy == 3 && !wx.getStorageSync("sessionid"))
                ) {
                  element.visible = 1;
                } else if (
                  (element.visibleCopy == 2 &&
                    !wx.getStorageSync("sessionid")) ||
                  (element.visibleCopy == 3 && wx.getStorageSync("sessionid"))
                ) {
                  element.visible = 0;
                } else {
                  if (
                    element.condition != "" &&
                    element.condition != undefined
                  ) {
                    console.log("979797", element.condition);
                    element.visible = ids.some((item) => {
                      return item == element.condition;
                    })
                      ? 1
                      : 0;
                  }
                }
                pollCondition(element);
              } else if (
                Object.prototype.toString.call(element) === "[object Array]" &&
                element.length > 0
              ) {
                element.forEach((item) => {
                  pollCondition(item);
                });
              }
            }
          }
        }
      }

      return JSON.stringify(pageData);
    },
  },
};
</script>

<style lang="scss" scoped>
.paySuccess {
  position: relative;
  width: 100vw;
  height: auto;
  .tabbar{
    position: sticky;
    top: 0;
    z-index: 9999;
    width: 100%;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    padding-left: 12px;
    .tab-back{
      /deep/.van-icon-arrow-left{
        font-size: 22px;
      }
    }
  }
}
.spokemanEntry {
  /deep/.van-popup{
    width: 85%!important;
    height: 50%!important;
    // padding:12px;
    border-radius: 3px;
    background: url("http://mayi-newshop.oss-cn-shanghai.aliyuncs.com/public/png/d6c8ce5a-574b-4191-81ea-843d15a30b68.png") no-repeat!important;
    background-size: 100% 100%!important;
    padding-left: 38px!important;
    padding-top: 50px!important;
    padding-right: 38px!important;

    // height: 100px;
    .ent-top {
      // background:#DFDFDF;
      // height: 150px;
      // padding:45px 0;
      p {
        // text-align: center;
        line-height: 30px;
      }
      p:nth-child(1) {
        text-align: left;
      }
      p:nth-child(2) {
        margin-top: 17px;
        margin-bottom: 55px;
      }
    }
    .reviwBtn {
      width: 200px;
      height: 44px;
      // background: var(--main-color);
      background: linear-gradient(
        -90deg,
        rgba(83, 37, 26, 1) 0%,
        rgba(130, 71, 56, 1) 100%
      );
      border-radius: 25px;
      font-size: 14px;
      // color:#fff;
      color: #fff;
      margin-top: 10px;
      display: flex;
      justify-content: center;
      align-items: center;
      // margin-left:45px;
    }
    .ignore {
      // color:var(--minor-color);
      color: #53251a;
      font-size: 12px;
      text-align: center;
      margin-top: 20px;
    }
    p {
      // text-align:center;
    } 
  }
}
</style>