<template>
  <view v-if="myPageData.home_pages" :style="[myPageData.home_pages.navs[active].templateBg]">
    <view
      class="content"
      :style="{ 'padding-bottom': showtabs==ture? '100rpx':0,paddingTop:pagePaddingBottom }"
    >
      <view
        class="index-title"
        :style="[myPageData.home_pages.navs[active].templateBg,titleStyle,{color:myPageData.home_pages.navs[active].templateBg?myPageData.home_pages.navs[active].templateBg.titleColor:''}]"
      >
        <text>{{pageTitleStr}}</text>
        <view class="back-arrow" v-if="showBack" @click="goback">
          <u-icon name="arrow-left" size="44"></u-icon>
        </view>
      </view>
      <u-tabs
        v-if="myPageData.home_pages && myPageData.home_pages.navs.length > 1"
        name="name"
        :list="myPageData.home_pages.navs"
        :is-scroll="true"
        :active-color="mainColor"
        :current="active"
        :bar-width="80"
        :font-size="32"
        :bold="false"
        @change="changeHandler"
      ></u-tabs>
      <template v-for="(item, i) in myPageData.home_pages.navs">
        <view :key="i" v-if="active == i">
          <template v-for="(d, di) in item.template.data">
            <search v-if="d.id == 'search'" :style-str="d.data" :key="di"></search>
            <swiper v-if="d.id == 'banner'" :swipers="d.data" :key="di"></swiper>
            <empty v-if="d.id == 'empty'" :block="d.data" :key="di"></empty>
            <rubik v-if="d.id == 'rubik'" :ad="d.data" :key="di"></rubik>
            <goods v-if="d.id == 'goods'" :goods="d.data" :key="di"></goods>
            <notice v-if="d.id == 'notice'" :notice="d.data" :key="di"></notice>
            <gridnav v-if="d.id == 'nav'" :navs="d.data" :key="di"></gridnav>
            <pagetitle v-if="d.id == 'link'" :ts="d.data" :key="di"></pagetitle>
            <videopage v-if="d.id == 'video'" :video="d.data" :key="di"></videopage>
            <copyright v-if="d.id == 'copyright'" :cop="d.data" :key="di"></copyright>
            <checkin v-if="d.id == 'check-in'" :check="d.data" :key="di"></checkin>
            <userbox v-if="d.id == 'user-info'" :ts="d.data" :key="di"></userbox>
            <view v-if="d.id == 'image-text'" class="imageText" :key="di">
              <view v-html="d.data.content"></view>
            </view>
            <userorder v-if="d.id == 'user-order'" :uo="d.data" :key="di"></userorder>
            <mapi v-if="d.id == 'map'" :mapi="d.data" :key="di"></mapi>
            <checkform v-if="d.id == 'form'" :forms="d.data" :key="di"></checkform>
            <addialog v-if="d.id == 'modal' && d.data.opened" :ads="d.data" :key="di"></addialog>
            <quicknav v-if="d.id == 'quick-nav' && d.data.navSwitch == 1" :navs="d.data" :key="di"></quicknav>
            <pingtuan v-if="d.id == 'pintuan'" :goods="d.data" :key="di"></pingtuan>
            <shopinfo v-if="d.id == 'shop-info' " :ad="d.data" :key="di" ref='son'></shopinfo>
            
			
          </template>
        </view>
      </template>
      <view v-if="showtabs==true">
        <tabbar></tabbar>
      </view>

      <view
        class="tips_t"
        v-if="add_show==1&& JSON.stringify(setting) != '{}'  "
        :style="{
		'border-radius':setting.add_app_bg_radius+'rpx',
		'opacity':setting.add_app_bg_transparency/100,
		'top':pagePaddingBottom,
		}"
      >
        <u-icon name="cross" color="#fff" @click="close"></u-icon>
        <view style="width: 1px;height: 20px;margin:0 10px;background: #fff;"></view>
        <Text style="color: #fff;">{{setting.add_app_text}}</Text>
        <view class="triangle-up" :style="{'top':pagePaddingBottom}"></view>
      </view>
      <coupon
        v-if="showCoupons"
        :coupon-message="couponMessage"
        @goLook="goLook"
        @closeBtn="closeBtn"
      ></coupon>
	  <auth v-if="showAuth" @changeuserinfo="reloadUserinfo" @gbAuth= 'gbAuth'></auth>
    </view>
  </view>
</template>

<script>
import tabbar from "@/components/tabbar/index";
import search from "@/components/search/index";
import swiper from "@/components/swiper/index";
import empty from "@/components/empty/index";
import rubik from "@/components/rubik/index";
import goods from "@/components/goods/index";
import notice from "@/components/notice/index";
import gridnav from "@/components/gridnav/index";
import pagetitle from "@/components/pagetitle/index";
import videopage from "@/components/videopage/index";
import copyright from "@/components/copyright/index";
import checkin from "@/components/checkin/index";
import userbox from "@/components/userbox/index";
import userorder from "@/components/userorder/index";
import mapi from "@/components/mapi/index";
import checkform from "@/components/checkform/index";
import addialog from "@/components/addialog/index";
import quicknav from "@/components/quicknav/index";
import coupon from "@/components/coupons/coupons";
import pingtuan from "@/components/pingtuan/index";
import shopinfo from "@/components/shopinfo/shopinfo";
import auth from "@/components/auth/index.vue";

export default {
  data() {
    return {
      title: "Hello",
      myPageData: {},
      indexPageData: {},
      mainColor: "",
      active: 0,
      contentHeight: 0,
      pageId: 0,
      setting: {},
      add_show: 1,
      showtabs: true,
      showCoupons: false,
      couponMessage: "",
      pageTitleStr: "",
      titleStyle: "",
      pagePaddingBottom: "0px",
      showBack: false,
	  showAuth:false,
	  U:{},
    };
  },
  components: {
    tabbar,
    search,
    swiper,
    empty,
    rubik,
    goods,
    notice,
    gridnav,
    pagetitle,
    videopage,
    copyright,
    checkin,
    userbox,
    userorder,
    mapi,
    checkform,
    addialog,
    quicknav,
    coupon,
    pingtuan,
	shopinfo,
	auth
  },
  onLoad(options) {
    console.log(options, "option");
    let that = this;
    uni.getSystemInfo({
      success(res) {
        that.titleStyle = {
          height: "45px",
          paddingTop: `${res.statusBarHeight}px`,
        };
        that.pagePaddingBottom = 45 + res.statusBarHeight + "px";
      },
    });
    let c = this.$uiConfig.is_bang ? 78 : 50;
    this.contentHeight = this.$utils.calcContentHeight(c);
    if (options && options.page_id) {
      this.pageId = options.page_id;
      let queryString = "";
      for (var k in options) {
        queryString += `&${k}=${options[k]}`;
      }
      if (queryString != "") {
        queryString =
          "/pages/index/index?" + queryString.substring(1, queryString.length);
      }
      let p = 0;
      if (uni.getStorageSync("navs")) {
        uni.getStorageSync("navs").forEach(x=>{
          if (x.url == queryString) {
            p=1;
          }
        })
      }
      if (p == 0) {
        this.showtabs = false;
        this.contentHeight = this.$utils.calcContentHeight();
      }
      
    }
    if (options && options.custom_params) {
      let custom_params = JSON.parse(decodeURIComponent(options.custom_params));
      console.log(custom_params);
      if (custom_params.user_id) {
        uni.setStorageSync("pid", { pid: custom_params.user_id });
      }
    }
    if (options && options.user_id) {
      uni.setStorageSync("pid", { pid: options.user_id });
    }
	if (options && options.SmallShopId) {
	  uni.setStorageSync("SmallShopId", { SmallShopId: options.SmallShopId });
	  console.log(uni.getStorageSync("SmallShopId"))
	}
	
	

    if (options && options.scene) {
      //兼容之前小程序的调转
      this.getjump(options.scene);
    }

    // #ifdef MP-WEIXIN
    wx.showShareMenu({
      withShareTicket: true,
      menus: ["shareAppMessage", "shareTimeline"],
    });
    
      that.u = uni.getStorageSync("mall_UserInfo")
      wx.getUserInfo({
        success: function (res) {
			if (uni.getStorageSync("mall_UserInfo")) {
			  let uid = uni.getStorageSync("mall_UserInfo").UserId;
			  let msg = {
				Id: uid,
				AliasName: res.userInfo.nickName,
				Photo: res.userInfo.avatarUrl,
			  };
			  that.updateuserinfo(msg);
			}else{
			  //静默登录操作
			  uni.login({
			  	provider: 'weixin',
			  	success: info => {
			  		let obj ={
						Name: res.userInfo.nickName,
						Photo: res.userInfo.avatarUrl,
						code: info.code
					}
			  		that.getCode(obj)
			  	},
			  	fail: () => {
			  		uni.showToast({ title: '微信登录授权失败', icon: 'none' });
					if (!that.u) {
					  that.u = {
						nickName: "未登录",
						avatarUrl: ""
					  };
					  that.showAuth = true;
					}
			  	}
			  });
		  }
        },
		fail:function(e){
			uni.showToast({ title: '微信登录授权失败', icon: 'none' });
			if (!that.u) {
			  that.u = {
				nickName: "未登录",
				avatarUrl: ""
			  };
			  that.showAuth = true;
			}
		}
	  });
    
	
	
    // #endif
    this.init();
    let set = uni.getStorageSync("basedata")
      ? uni.getStorageSync("basedata").mall.setting
      : {};
    if (!uni.getStorageSync("add_top_app")) {
      uni.setStorageSync("add_top_app", { add_top_app_show: 1 });
    }
    this.add_show = uni.getStorageSync("add_top_app")
      ? uni.getStorageSync("add_top_app").add_top_app_show
      : 1;
    this.setting = set;
    // console.log(this.setting)
    console.log(uni.getStorageSync("basedata"));
    this.isShowBack();
    uni.showNavigationBarLoading();
  },
  // #ifdef MP-WEIXIN
  onShareTimeline() {
    setTimeout(() => {
      console.log("分享调用");
      this.getReceive();
    }, 2500);
    let uid = uni.getStorageSync("mall_UserInfo")
      ? uni.getStorageSync("mall_UserInfo").UserId
      : 0;
	  if(uid==0){
	  	uid = uni.getStorageSync("pid")?uni.getStorageSync("pid").pid:0
	  }
	  let SmallShopId = uni.getStorageSync("mall_UserInfo")
	    ? uni.getStorageSync("mall_UserInfo").SmallShopId
	    : 0;
		if(SmallShopId == 0){//如果微店id为0 去找所属微店id
			SmallShopId = uni.getStorageSync("mall_UserInfo")
			  ? uni.getStorageSync("mall_UserInfo").UserSmallShopId
			  : 0;
		}
    console.log(uid);
    return {
      title: "",
      query: "user_id=" + uid+"&SmallShopId=" + SmallShopId,
      imageUrl: "",
    };
  },
  onShareAppMessage(res) {
    setTimeout(() => {
      console.log("分享调用");
      this.getReceive();
    }, 2500);
    let uid = uni.getStorageSync("mall_UserInfo")
      ? uni.getStorageSync("mall_UserInfo").UserId
      : 0;
	  if(uid==0){
		  uid = uni.getStorageSync("pid")?uni.getStorageSync("pid").pid:0
	  }
	  let SmallShopId = uni.getStorageSync("mall_UserInfo")
	    ? uni.getStorageSync("mall_UserInfo").SmallShopId
	    : 0;
		if(SmallShopId == 0){//如果微店id为0 去找所属微店id
			SmallShopId = uni.getStorageSync("mall_UserInfo")
			  ? uni.getStorageSync("mall_UserInfo").UserSmallShopId
			  : 0;
		}
    return {
      title: this.setting.share_title
        ? this.setting.share_title
        : uni.getStorageSync("basedata").mall.name,
      path: "/pages/index/index?user_id=" + uid+"&SmallShopId=" + SmallShopId,
      imageUrl: this.setting.share_pic ? this.setting.share_pic : "",
    };
  },
  // #endif
  onShow() {
    setTimeout(() => {
      uni.hideNavigationBarLoading();
    }, 500);
    this.mainColor = this.$uiConfig.mainColor;
    this.init();
  },

  methods: {
	  //调用获取code
	  getCode(obj) {
	  	var that = this;
			//这里请求接口
			that.request2(
				{
					url: '/api/mall/GetWeChatOpenId',
					data: {
						Code: obj.code
					}
				},
				res => {
					if (res.resultCode == 1) {
						obj.OpenId = res.data;
						that.getLogin(obj);
					}
				}
			);
	  	
	  },
	  getLogin(obj) {
	  	var that = this;
	  	let pid = uni.getStorageSync("pid")?uni.getStorageSync("pid").pid:0;
	  	let SmallShopId = uni.getStorageSync("SmallShopId")?uni.getStorageSync("SmallShopId").SmallShopId:0;
	  	that.request2(
	  		{
	  			url: '/api/AppletLogin/Login',
	  			data: {
	  				Source: 1,
	  				OpenId: obj.OpenId,
	  				Name: obj.Name,
	  				Photo: obj.Photo,
	  				Moblie: '',
	  				SuperiorId: pid,
	  				SmallShopId:SmallShopId,
	  			}
	  		},
	  		res => {
	  			if (res.resultCode == 1) {
	  				uni.setStorageSync('mall_UserInfo', res.data);
	  				if(res.couponResultCode==1){
	  					that.showCoupons = true;
	  					that.couponMessage = res.couponMessage;
	  				}
					that.u = res.data
	  				uni.removeStorageSync('pid');
	  				uni.removeStorageSync('SmallShopId');
	  			}else{
					if (!that.u) {
					  that.u = {
						nickName: "未登录",
						avatarUrl: ""
					  };
					  that.showAuth = true;
					}
				}
	  		}
	  	);
	  },
    updateuserinfo(msg) {
      this.request2(
        {
          url: "/api/MemberUser/SetMemberPhoto",
          data: msg,
        },
        (res) => {
          //静默处理不做任何提示
        },
        (error) => {}
      );
    },
    goback() {
      uni.navigateBack({
        delta: 1,
      });
    },
    isShowBack() {
      let navs = uni.getStorageSync("navs") ?? [];
      if (navs) {
        let t = getCurrentPages();
        let query = t[t.length - 1].__displayReporter.query;
        let queryString = "";
        for (var k in query) {
          queryString += `&${k}=${query[k]}`;
        }
        if (queryString != "") {
          queryString = "?" + queryString.substring(1, queryString.length);
        }
        let crtPath = "/" + t[t.length - 1].route + queryString;
        let isExsit = false;
        navs.forEach((x, i) => {
          if (x.url == crtPath) {
            isExsit = true;
          }
        });
        this.showBack = !isExsit;
      }
    },
    getjump(scene) {
      let a = "YZnsGuRojCKBkb1siP3VwkhkPFvh-D"; //测试数据
      this.request(
        {
          url: "",
          data: {
            r: "api/default/qr-code-parameter",
            token: scene,
          },
        },
        (res) => {
          console.log(res.data.detail.path);
          uni.setStorageSync("pid", {
            pid: res.data.detail.user_id ? res.data.detail.user_id : 0,
          }); //存储上级的id
          let objurl = this.ObjectToUrl(res.data.detail.data);
          uni.navigateTo({
            url: "/" + res.data.detail.path + "?" + objurl,
          });
        }
      );
    },
    ObjectToUrl(e, t) {
      var n = "";
      for (var i in e)
        n += "&" + i + "=" + (t ? encodeURIComponent(e[i]) : e[i]);
      return n.substr(1);
    },
    init() {
      this.request2(
        {
          url: "/api/Mall/GetHome",
          data: {
            page_id: this.pageId,
          },
        },
        (res) => {
          this.indexPageData = res.data.home_pages.navs[0].template.data;
          this.myPageData = res.data;
          if (res.data.navbar.navs) {
            uni.setStorageSync("navs", res.data.navbar.navs);
          }
          uni.setStorageSync("basedata", res.data);
          if (res.data.home_pages.title != "") {
            if (this.pageId == 0) {
              uni.setNavigationBarTitle({
                title: res.data.home_pages.title,
              });
              this.pageTitleStr = res.data.home_pages.title;
            } else {
              uni.setNavigationBarTitle({
                title: res.data.home_pages.navs[0].name,
              });
              this.pageTitleStr = res.data.home_pages.navs[0].name;
            }

            // uni.setNavigationBarColor({
            //   //字体颜色
            //   frontColor: res.data.navbar.top_text_color,
            //   //背景颜色
            //   backgroundColor: res.data.navbar.top_background_color,
            // });
            this.titleStyle.color = res.data.navbar.top_text_color;
            this.titleStyle.backgroundColor =
              res.data.navbar.top_background_color;

            this.isShowBack();
          }
          this.formatBg();
        },
        (error) => {}
      );
    },
    close() {
      this.add_show = 2;
      uni.setStorageSync("add_top_app", { add_top_app_show: 2 });
    },
    changeHandler(i) {
      this.active = i;
    },
    formatBg() {
      this.myPageData.home_pages.navs.forEach((y) => {
        y.template.data.forEach((x) => {
          if (x.id == "background") {
            let t = "";
            y.templateBg = {};
            if (x.data.showImg) {
              y.templateBg.backgroundColor = x.data.backgroundColor;
              y.templateBg.backgroundImage = `url('${x.data.backgroundPicUrl}')`;
              y.templateBg.backgroundPosition = x.data.positionText;
              y.templateBg.backgroundRepeat = x.data.repeatText ?? "no-repeat";
              y.templateBg.backgroundSize = `${
                x.data.backgroundWidth == 0
                  ? "auto"
                  : x.data.backgroundWidth + "%"
              } ${
                x.data.backgroundHeight == 0
                  ? "auto"
                  : x.data.backgroundHeight + "%"
              }`;
            } else {
              y.templateBg.background = x.data.backgroundColor;
              y.templateBg.titleColor = "#000 !important";
            }
            if (this.myPageData.home_pages.navs.length > 1) {
              y.templateBg.overflowY = "auto";
              y.templateBg.height = this.contentHeight + "px";
            } else {
              y.templateBg.overflowY = "auto";
              y.templateBg.height = this.contentHeight + 40 + "px";
            }
            if (x.data.titleColor) {
              y.templateBg.titleColor = x.data.titleColor + " !important";
            }
            // y.templateBg +="padding-bottom:"+(this.$uiConfig.is_bang ? '88px' : '60px')+";box-sizing: border-box;";
          }
        });
        if (!y.templateBg) {
          y.templateBg = { titleColor: "#000" };
        }
      });
      // this.myPageData.home_pages.navs[0].template.data.push({
      //   id: "pintuan",
      //   permission_key: "pintuan",
      //   data: {
      //     buttonColor: "#ff4544",
      //     list: [
      //       {
      //         id: 179402,
      //         name:
      //           "日本POLA宝丽黑BA限定小礼盒（黑ba水20ml +黑ba乳液15ml +黑ba面霜5g +黑ba唇颊膏2g）",
      //         picUrl:
      //           "https://cdnimg.iotweixin.com/uploads/mall1285/20200506/904171cab7db2201f6f35c0ca5bb0a93.png",
      //         price: "388.00",
      //         peopleNum: 2,
      //         pintuanPrice: "348.00",
      //       },
      //       {
      //         id: 178355,
      //         name:
      //           "日本珂润（Curel）润浸保湿 滋养乳霜 40g 敏感肌专用 神经酰胺护理 抵抗外部刺激",
      //         picUrl:
      //           "https://cdnimg.iotweixin.com/uploads/mall1285/20200503/979653726a7bc1df0e24464f94b404bd.jpg",
      //         price: "180.00",
      //         peopleNum: 2,
      //         pintuanPrice: "180.00",
      //       },
      //       {
      //         id: 178352,
      //         name: "500g 干羊肚菌 干货 煲汤菌 菌中之王  包邮",
      //         picUrl:
      //           "https://cdnimg.iotweixin.com/uploads/mall1285/20200311/358dd9acf5dafd3cab2c05be3354400c.png",
      //         price: "780.00",
      //         peopleNum: 3,
      //         pintuanPrice: "680.00",
      //       },
      //     ],
      //     listStyle: 1,
      //     textStyle: 1,
      //     fill: 1,
      //     goodsCoverProportion: "1-1",
      //     goodsStyle: 1,
      //     showGoodsName: true,
      //     showBuyBtn: true,
      //     buyBtnStyle: 1,
      //     buyBtnText: "去拼团",
      //     showGoodsTag: false,
      //     customizeGoodsTag: false,
      //     goodsTagPicUrl: "",
      //     showImg: false,
      //     backgroundColor: "#fff",
      //     backgroundPicUrl: "",
      //     position: 5,
      //     mode: 1,
      //     backgroundHeight: 100,
      //     backgroundWidth: 100,
      //     borderBackground: "#ffffff",
      //   },
      // });
    },
    getReceive() {
      //分享进入调取领券接口
      // 1-分享，2-购买并付款
      this.request2(
        {
          url: "/api/AppletUser/ShareCoupon",
          data: {
            TriggerType: 1,
          },
        },
        (res) => {
          console.log(res, "res");
          if (res.couponResultCode == 1) {
            this.couponMessage = res.couponMessage;
            this.showCoupons = true;
          }
        }
      );
    },
    goLook() {
      this.showCoupons = false;
    },
    closeBtn() {
      this.showCoupons = false;
    },
	reloadUserinfo() {
	  this.u = uni.getStorageSync("mall_UserInfo");
	 this.$refs.son[0].getSmallShopById(2)//第一次登陆成功后去调取微店的信息
	  
	},
	//关闭登录窗口
	gbAuth(){
		this.showAuth=false;
	},
  },
};
</script>

<style>
.content {
  display: flex;
  flex-direction: column;
  /* align-items: center;
  justify-content: center; */
}
.content .tips_t {
  position: fixed;

  right: 6px;
  height: 36px;
  background: #000000;
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 0 10px;
  font-size: 12px;
  margin-top: 10px;
  z-index: 9999999;
}
.triangle-up {
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  border-bottom: 12px solid black;
  position: fixed;
  right: 65px;
}
.index-title {
  line-height: 45px !important;
  font-size: 16px;
  text-align: center;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  color: #fff;
  box-sizing: content-box;
  z-index: 5;
}
.back-arrow {
  position: absolute;
  left: 5px;
  bottom: 12.5px;
}
/* .logo {
  height: 200rpx;
  width: 200rpx;
  margin-top: 200rpx;
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 50rpx;
}

.text-area {
  display: flex;
  justify-content: center;
}

.title {
  font-size: 36rpx;
  color: #8f8f94;
} */
</style>
