<template>
  <view class="xd-Layout" id="xd-Layout">
    <view
      v-if="initStatus && (websiteStatus === true && webApplyStatus === true)"
      class="xd-Layout__animation"
    >
      <!--topBar-->
      <view class="xd-Layout__top-height"
        :style="{
          height: (topHeight + navBarHeight + statusBarHeight) +'rpx',
          backgroundImage: getNavBackImage,
          backgroundPosition: 'top center',
          backgroundSize: '100%',
          backgroundRepeat: 'no-repeat',
        }"
      ></view>
      <view class="xd-Layout__bar"
        v-show="(showBar || isPreviewShowBar || isCustomNavigation)"
        :class="{isPreviewShowBar: isPreviewShowBar}"
        :style="{
          height: navBarHeight + statusBarHeight + 'rpx',
          width: '100%',
          backgroundColor: getBarBgColor,
          backgroundImage: backgroundImageComp,
          zIndex: ((showBar || isPreviewShowBar) ? 1300: 1000)
        }
      ">
        <xd-bar
          :scroll-detail="scrollDetail"
          :bar-nav-height="navBarHeight"
          :bar-status-height="statusBarHeight"
          :title="getTitle"
          :show-back="isShowBack"
          :color="getBarTextColor"
          :bg-color="getBarBgColor"
          :bg-image="!wiewType && navigationStyle ? bgImage: ''"
          :is-slot-top-bar="isSlotTopBar"
          :text-align="barTextAlign || tabbarData.barTextAlign "
          @back="backEvent"
        >
          <slot name="topBar" v-if="isSlotTopBar"></slot>
        </xd-bar>
      </view>
      <!--topBar-->
      <!--top-->
      <view class="xd-Layout__top animation-top"
        v-show="contentStatus"
        :style="{
          paddingTop: windowTop + 'rpx',
          height: topHeight + 'rpx',
          top: (navBarHeight + statusBarHeight) + 'rpx',
          zIndex: (wiewType ? 1490: 1000),
          backgroundImage: backgroundImageComp,
          backgroundColor: (customBg === null && getNavBackImage==='none' || getNavBackImage==='url()'  && this.scrollDetail > 5 ) ? '#fff': 'rgba(0,0,0,0)' ,
          backgroundPosition: getBodyTopImagePosition,
          backgroundSize: '100%'
        }"
      >
        <slot name="top"></slot>
      </view>
      <!--top-->
      <!--body-->
      <view
        class="xd-Layout__body animation-body"
        ref="xd-Layout__body"
        :style="{
          minHeight: getMinHeight,
          backgroundColor: background,
          backgroundImage: getBodyBackImage,
          backgroundPosition: getBodyBackImagePosition,
          zIndex: (wiewType ? 1500: 999)
        }"
      >
        <view v-show="contentStatus" :style="{minHeight: getMinHeight}">
          <view class="networkStatus" v-if="!networkStatus">网络异常，请检查网络设置是否正常！</view>
          <view v-if="isConsole" class="systemInfoSyn">{{gWindowHeight}}--{{systemInfoSyn}}--{{getMinHeight}}--{{min}}--{{onChange}}</view>
          <slot>
            <view v-if="0" class="loadingblock" :style="{minHeight: getMinHeight,backgroundImage: 'url('+ loadingUrl +')'}"></view>
          </slot>
        </view>
      </view>
      <!--body-->
      <!--bottom-->
      <view class="xd-Layout__bottom animation-bottom"
        v-if="bottomHeight"
        v-show="contentStatus"
        :style="{
          height: bottomHeight + 'rpx',
          bottom: getBottom + 'rpx',
          background: background,
          zIndex: (wiewType ? 1600: 1000)
        }"
      >
        <slot name="footer"></slot>
      </view>
      <!--bottom-->
      <!--tabBar-->
      <view class="xd-Layout__tabbar"
        v-show="showFooter"
        :style="[footerBoxComp]"
      >
        <template v-if="!isFooterSolt">
          <xd-footer-tabbar
            :tabbar="tabbarData"
            :height="100"
          ></xd-footer-tabbar>
        </template>
        <slot name="footerBar" v-else></slot>
      </view>
      <!--tabBar-->
      <view class="xd-Layout__footer-height" :style="{height: (bottomHeight + (isFooterSolt ? footerHeight: 110)) + 'rpx' }"></view>
    </view>
    <view v-if="websiteStatus === false" class="website-disable">
      <image :src="`${cdnHost}/common/server_closed.png?ver=1`" mode="widthFix"></image>
    </view>
    <view v-if="webApplyStatus === false" class="website-disable">
      <image :src="`${cdnHost}/common/server_closed.png?ver=1`" mode="widthFix"></image>
    </view>
    <xd-confirm v-if="getLayoutInfo" :get-layout-info="getLayoutInfo"></xd-confirm>
    <xd-loading v-if="getLayoutInfo" :get-layout-info="getLayoutInfo"></xd-loading>
    <xd-tips v-if="getLayoutInfo" :get-layout-info="getLayoutInfo"></xd-tips>
    <view class="xd-Layout__padding" id="xd-Layout__padding"></view>
    <view class="xd-Layout__padding-placeholder" v-if="!wiewType" :style="{backgroundColor: background}"></view>
    <xd-city-location v-if="open"></xd-city-location>
  </view>
</template>

<script>
  import XdBar from "@/components/XdBar/XdBar";
  import XdFooterTabbar from "@/components/XdFooterTabbar/XdFooterTabbar";
  import XdFontIcon from "@/components/XdFontIcon/XdFontIcon";
  import XdConfirm from "@/components/XdConfirm/XdConfirm";
  import XdLoading from "@/components/XdLoading/XdLoading";
  import XdTips from "@/components/XdTips/XdTips";
  import XdCityLocation from "@/components/XdCityLocation/XdCityLocation";
  import XdAppClass from "@/XdAppClass";
  import {mapState} from 'vuex';
  import supportLocation from "@/common/supportLocation";
  import {parsePath} from "@/utils/linkUrl";


  /**
   * XdLayout 全局Ui
   * @description Layout
   * 内容区域高度：（100vh - barHeight - searchHeight - topHeight - bottomHeight - footerHeight）
   * 内容区域支持普通view和scoll-view标签，使用scoll-view做滚动有性能问题
   * 使用view标签移除onPullUpRefresh，onScroll事件，可以使用页面级onReachBottom和onPageScroll
   * @tutorial
   * @property {Number} topHeight           顶部自定义高度 默认:0
   * @property {Number} bottomHeight        底部自定义高度 默认:0
   * @property {Boolean} showBack           显示返回按钮 默认：true
   * @property {Boolean} showBar            显示bar文字颜色 默认：true
   * @property {String}  title              当前页面标题名称 默认不显示标题
   * @property {String} barTextColor        bar标题颜色 默认：''
   * @property {String} background          bar背景颜色 默认：#fff
   * @property {Boolean} showFooter         是否展示底部tabbar 默认：true
   * @property {Boolean}  isAnimation       是否支持动画 默认：true
   * @property {Boolean}  isUseBgImage      内容区域是否使用背景图片 默认：false
   *
   * @event {Function} onDone               初始化完成事件 {bottom: 0, top: 0}
   * @event {Function} onBack               点击返回键事件
   *
   * 支持插槽（3个插槽） 默认，top, footer，bar
   */

  export default {
    name: "XdLayout",
    components: {
      XdTips,
      XdConfirm,
      XdLoading,
      XdFontIcon,
      XdFooterTabbar,
      XdBar,
      XdCityLocation
    },
    mixins: [],
    props: {
      //页面滚动的值
      scrollDetail:{
        type: Number,
        default: 0,
      },
      topHeight: {
        type: Number,
        default: 0,
      },

      footerHeight: {
        type: Number,
        default: 0,
      },

      isSlotTopBar:{
        type: Boolean,
        default: false
      },

      bottomHeight: {
        type: Number,
        default: 0,
      },

      showBack: {
        type: Boolean,
        default: true
      },

      showBar: {
        type: Boolean,
        default: true
      },

      title: {
        type: String,
        default: '',
      },

      barTextAlign:{
        type: String,
        default: 'center', //center,left
      },

      barTextColor: {
        type: String,
        default: '#fff',
      },

      barBackgroundColor: {
        type: String,
        default: '',
      },

      barBackgroundImage: {
        type: String,
        default: '',
      },

      background:{
        type: String,
        default: '#fff',
      },

      showFooter: {
        type: Boolean,
        default: true,
      },

      isAnimation:{
        type: Boolean,
        default: true,
      },

      //true => 导航区域显示  false => 全部显示
      isUseBgImage:{
        type: Boolean,
        default: false,
      },

      navigationStyle: {
        type: Boolean,
        default: false, //false=自定义 true=系统导航
      },

      //当前页面支持的组件
      componentAttr:{
        type: Object,
        default(){
          return {}
        },
      },

      pagesAttr:{
        type: Object,
        default(){
          return {}
        },
      }

    },
    data() {
      return {
        //定位
        open: false,
        layoutLoading: false,
        startTime: new Date().getTime(),
        websiteStatus: null, //站点已经禁用
        webApplyStatus: null, //应用已经禁用
        cdnHost: 'https://img.jufubao.cn',

        startAnimation : false, //开始动画效果
        doneAnimation: false, //完成动画效果
        // #ifdef H5
        defaultImage: '//img.jufubao.cn/common/empty.png?ver=1',
        //#endif
        //#ifdef MP-WEIXIN
        defaultImage: 'https://img.jufubao.cn/common/empty.png?ver=1',
        //#endif

        bgImage: '',
        barBgColor: '', //bar背景颜色
        systemInfoSyn: null,

        //底部
        tabbarBackground: '#fff',
        tabbarData: null, //底部数据

        //加载完成
        initStatus: false,
        contentStatus: false,


        time: 0,
        createTime: 0,
        mountedTime: 0,

        //需要计算的变量
        // #ifdef H5
        navBarHeight : 80, //顶部高度（rpx）
        //#endif
        //#ifdef MP-WEIXIN
        navBarHeight: 110, //顶部高度（rpx）
        //#endif
        statusBarHeight: 0, //状态栏高度(rpx)
        safeHeight: null, //底部安全高度

        //logs
        uiLogs: {},
        uiErrorLogs: {},
        isLogs: false,
        observer: null,

        //底部是否插槽模式
        isFooterSolt: true,
        wiewType: false,

        // #ifdef H5
        loadingUrl: '//img.jufubao.cn/loading-block.jpg?v=1',
        //#endif
        //#ifdef MP-WEIXIN
        loadingUrl: 'https://img.jufubao.cn/loading-block.jpg?v=1',
        //#endif

	      //自定义背景
        customBg: null,
	      //窗口高度
        gWindowHeight: 0,
        scrollHeight:0, //记录父级滚动高度
        mainHeight:725, //父级高度

        //调试信息
        isConsole: false,
        dataSystem: {},
        min:{},
        onChange:0,
      }
    },
    computed: {
      ...mapState([
        'errorLogs',
        'logs',
        'networkStatus',
        'brandInfo',
        'siteInfo'
      ]),

      footerBoxComp(){
        let css = {
          height: (this.isFooterSolt ? this.footerHeight : 110) + 'rpx',
          background: this.tabbarBackground,
          zIndex: (this.wiewType ? 1601: 1001)
        }
        if(this.wiewType) css['top'] = (this.mainHeight -  this.footerHeight/2 + this.scrollHeight - 4) + 'px';
        else css['bottom'] = 0;
        return css
      },

      backgroundImageComp(){
        // #ifdef H5
        return this.customBg === null ? this.getNavBackImage:(this.scrollDetail > 5 ?this.getNavBackImage : 'none');
        //#endif
        //#ifdef MP-WEIXIN
        return this.getNavBackImage;
        //#endif
      },

      isShowBack(){
        return this.showBack || this.isCustomNavigation
      },

      //微信小程序自定义不显示头处理
      isCustomNavigation(){
        // #ifdef MP-WEIXIN || APP-PLUS || MP-ALIPAY
        return !this.wiewType && this.navigationStyle && !this.showBar
        // #endif
        return false

      },

      isPreviewShowBar(){
        return this.wiewType && this.navigationStyle && !this.showBar;
      },
      getTitle(){
        if(this.isPreviewShowBar) return '该模块只有在预览模式显示';
        return this.title
      },
      getBarBgColor(){
        if(this.isPreviewShowBar) return 'rgba(255, 244, 191, 0.9)';
        return  this.barBgColor

      },
      getBarTextColor(){
        if(this.isPreviewShowBar) return '#333';
        return this.barTextColor;
      },


      getBodyBackImage(){
        //设置自定义背景
        if(!!this.customBg) {
          return `url("${this.customBg}")`;
        }

        //无背景返回值
        if(this.bgImage === '') return 'none';
        //自定义导航
        if (this.navigationStyle) {
          if(!this.isUseBgImage) return 'none';
          else{
            if(this.customBg !== null) {
              return `url("${this.customBg}")`;
            }
            return `url("${this.bgImage}")`
          }
        }
        //系统导航
        else {
          if(this.customBg !== null) {
            return `url("${this.customBg}")`;
          }
          return `url("${this.bgImage}")`
        }
      },

      windowTop(){
        return this.getRpx(uni.getSystemInfoSync().windowTop || 0) - 2; //-2防止两个元素之间有缝隙
      },

      getBodyTopImagePosition(){
        let windowTop = uni.getSystemInfoSync().windowTop || 0;
        let temp = 'center top'; //默认值
        let top = this.navBarHeight + this.statusBarHeight;
        //自定义 + 显示顶部导航 (微信模式不显示bar自定强制开启自定义头)
        if (this.navigationStyle && (this.showBar || this.isPreviewShowBar || this.isCustomNavigation) ) {
          temp = `center -${top + this.getRpx(windowTop)}rpx`;
        }
        return temp;
      },

      getBodyBackImagePosition(){
        let windowTop = uni.getSystemInfoSync().windowTop || 0;
        let temp = 'center top'; //默认值
        let top = this.topHeight + this.navBarHeight + this.statusBarHeight;

        //使用自定义导航不显示导航时候（预览模式生效）
        if(this.navigationStyle
          && !this.pagesAttr.showBar &&
          this.$configProject.isPreview
        ) {
          top = 0;
        }

        //自定义 + 显示顶部导航
        if(this.navigationStyle && (this.showBar || this.topHeight || this.isPreviewShowBar) ) {
          temp = `center -${top + this.getRpx(windowTop)}rpx`;
        }
        return temp;
      },

      getNavBackImage(){
        //设置自定义背景
        if(this.customBg !== null) {
          return `url("${this.customBg}")`;
        }

        //无背景返回值
        if (this.bgImage === '') return 'none';
        let bgImg = 'none';
        if(this.navigationStyle && (this.showBar || this.topHeight)) {
          bgImg = `url("${this.bgImage}")`
        }
        return bgImg
      },


      getBottom(){
        return this.footerHeight
      },

      getMinHeight(){
        if(this.initStatus) {
          let temp = uni.getSystemInfoSync();
          let windowHeight = this.gWindowHeight;
          let windowTop = temp.windowTop || 0;

          // #ifdef H5
          //预览端
          if(temp.model === 'PC' && parent.window) {
            windowHeight = (parent.window.innerHeight || parent.window.document.documentElement.clientHeight || parent.window.document.body.clientHeight) - 160;
          }

          //系统导航设置windowTop值
          if (this.navigationStyle === false) {
            windowTop = 0
          }

          //#endif
          let bar = this.navBarHeight;
          let nav = this.statusBarHeight;
          let bottom = this.bottomHeight;
          let top = this.topHeight;
          let footerBar = this.footerHeight;
          let safeBottom = this.safeHeight;
          // #ifdef H5
          if(this.systemInfoSyn.platform === 'ios') {
            safeBottom = this.gWindowHeight < uni.getStorageSync('xd-max-window-height')?0:this.safeHeight;
          }

          //#endif
          //console.log('getMinHeight', temp, bar, nav, bottom, top, footerBar, safeBottom, windowTop, windowHeight, this.navigationStyle)
          let min = this.getPX(bar + nav + bottom + top + footerBar + safeBottom) + windowTop;
          this.min = {bar,nav,bottom,top,footerBar,safeBottom,windowTop};
          return `${windowHeight - min}px`;
        }
        else {
          return 0
        }
      },

      /**
       * @description 打包框架数据
       * @returns {Object}
       */
      getLayoutInfo() {
        if(this.safeHeight === null) return  null;
        let windowTop = uni.getSystemInfoSync().windowTop || 0;
        return {
          bodyMinHeightPx: parseFloat(this.getMinHeight),
          bodyMinHeightRpx: this.getRpx(parseFloat(this.getMinHeight)),
          safeHeightRpx: this.safeHeight, //底部安全高度
          safeHeightPx: this.getPX(this.safeHeight), //底部安全高度
          bodyMinHeight: this.getMinHeight, //底部安全高度
          bottom: this.bottomHeight + this.footerHeight + this.bottomHeight + this.safeHeight, //底部已被占有高度（rpx)
          top: this.navBarHeight + this.statusBarHeight + this.topHeight + this.getRpx(windowTop), //距离顶部已被占有高度（rpx）
          topHeight: this.topHeight,
          bottomHeight: this.bottomHeight, //bottom 模块高度
          footerHeight: this.footerHeight, //footer 菜单高度
        }
      },
    },
    watch:{
      errorLogs(value){
        this.uiErrorLogs = value;
      },
      logs(value){
        this.uiLogs = value;
      },

      //框架加载完成
      layoutLoading(value){
        if(value === true) {
          this.$xdLog.setProject('Layout.loading.done', {
            time: new Date().getTime(),
            timeString: new Date().toLocaleString(),
          });
        }
        this.doneLayoutAndLocation()
      },
    },

    created() {
      this.wiewType = this.$configProject.isPreview;
      this.systemInfoSyn = uni.getSystemInfoSync();
      this.gWindowHeight =  uni.getSystemInfoSync().windowHeight;



      // #ifdef H5
      if(this.$configProject.isPreview) {
        if(window.parent && window.parent.document) {
          let main = window.parent.document.getElementsByClassName('xd-editx__body-main-auto')[0];
          this.mainHeight = main.height || main.clientHeight;
          main.addEventListener('scroll',(e)=>{
            this.scrollHeight = main.scrollTop;
          });
          window.parent.addEventListener('resize',()=>{
            this.mainHeight = main.height || main.clientHeight;
          })
        }
      }
      // #endif

      //测试环境
      if(this.$root['projectAttr']
        && this.$root['projectAttr']['host']
        && this.$root['projectAttr']['host'].indexOf('sandbox-') === 0
      ) {
        this.cdnHost = 'https://img.jufubao.cn';
      }
      //正式环境
      else {
        if(this.$root['projectAttr']['img_host']) {
          let cdnHost = this.$root['projectAttr']['img_host'].replace(/@index@/,'');
          if(cdnHost.indexOf('//') === 0) {
            cdnHost = cdnHost.replace(/\/\//,'https://');
          }
          this.cdnHost = cdnHost;
        }
        else this.cdnHost = 'https://img.jufubao.cn';
      }


      //判断站点与当前应用是否禁用

      //预览环境
      if(this.wiewType) {
        this.websiteStatus = true;
        this.webApplyStatus = true;
      }

      //打包环境
      else {
        this.websiteStatus = !!(this.siteInfo && this.siteInfo.site && this.siteInfo.site.status === 'Y');
        //站点已开启情况才能设置应用禁用
        if( this.websiteStatus  === true) {
          this.webApplyStatus = !(this.$root['projectAttr']['is_close'] === true)
        }
      }

      // #ifdef H5
      if(!uni.getStorageSync('xd-max-window-height')) {
        uni.setStorageSync('xd-max-window-height', uni.getSystemInfoSync().windowHeight);
      }

      this.isConsole = !!this.$xdUniHelper.getParmater('is-console')

      uni.onWindowResize(()=>{
        this.gWindowHeight =  uni.getSystemInfoSync().windowHeight;
        this.systemInfoSyn = uni.getSystemInfoSync();
        this.onChange++
      })
      // #endif

      //定位设置
      if (this.$configProject.isPreview === false
        && this.$configProject.extras
        && this.$configProject.extras.is_open_location === 'Y'
        && !this.checkPathIsLoginAndOrCard()
      ) {
        let com = Object.keys(this.componentAttr).filter(key=>{
          const name = key.split('-')[0];
          return supportLocation.includes(name)
        });

        //页面内部组有支持定位组件时候（组件内部进行定位）
        if(com.length > 0){
          this.open = false;
          console.warn(`has.support.location.component:${JSON.stringify(com)}`)
        }

        //页面内部无支持定位组件时候（在框架组进行定位）
        else {
          console.warn(`no.support.location.component:${JSON.stringify(com)}`)
          this.open = true;
        }
      }

      //切换页面之后数据清空
      this.uiErrorLogs = this.errorLogs;
      this.uiLogs = this.logs;
      this.isLogs = this.$settings.isLogs;

      this.isFooterSolt = this.$settings['isFooterUseSlot'] || true;

      //配置文件
      if(this.$webSetting) {
        //顶部背景图片
        if(this.$webSetting.barBackgroundImage) this.bgImage = this.$webSetting.barBackgroundImage;
        if(this.barBackgroundImage) this.bgImage = this.barBackgroundImage;

        this.tabbarData = this.$webSetting;
        this.tabbarBackground = this.$webSetting.backgroundColor;
      }

      //顶部背景颜色
      if (this.barBackgroundColor) this.barBgColor = this.barBackgroundColor;

      //获取胶囊相关数据
      this.setMenuButtonBounding();

      //重缓存中获取底部安全距离
      if(uni.getStorageSync('xd-layout')) {
        this.safeHeight = uni.getStorageSync('xd-layout')['safeHeight'];
        //修复刘海初始化值为0
        if(this.safeHeight === 0) {
          this.handleSafeBottom();
        }
        console.warn(`xd-layout.storage: ${JSON.stringify(this.safeHeight)}`);
        console.warn(`xd-layout.system: ${JSON.stringify(this.systemInfoSyn)}`);
        this.getSafeBottom();
      }

      //初始化
      getApp().globalData.$vm = getApp().globalData.$vm || this;
      let xdApp = getApp().globalData.$xd = XdAppClass(this);
      xdApp.xdInit((app) => {
        console.log(app)
      });

      //设置背景
      this.$xdRoot.$on('setLayoutPageBg', (bg)=>{
        console.warn(`${bg}:setLayoutPageBg`);
        this.customBg = bg || null;
      });


    },

    beforeMount() {
      if (this.safeHeight === null) this.getSafeBottom();
    },

    beforeDestroy(){
      if (this.observer !== null) this.observer.disconnect();
    },

    methods: {

      getSpPath(dir , path ){
        let reg = /@site_domain@/;
        if(!/@site_domain@/.test(path)) return `/${dir}${path}`;
        else return  path.replace(reg, '');
      },

      /**
       * @description 检查地址是否为登陆页面
       * @returns {boolean}
       */
      checkPathIsLoginAndOrCard() {
        let pages = this.$xdUniHelper.parseURL();
        let login_entry = this.brandInfo.login_entry|| this.$configProject.login_entry;
        let card_entry = this.brandInfo.card_entry|| this.$configProject.card_entry;

        // #ifdef H5
        let userLogin = this.getSpPath(this.brandInfo.deploy_dir, login_entry);
        let cardLogin = this.getSpPath(this.brandInfo.deploy_dir,card_entry);
        return pages.path === cardLogin || pages.path === userLogin;
        // #endif

        // #ifdef MP-WEIXIN
        let loginObj = parsePath(login_entry);
        let cardObj = parsePath(card_entry);
        return (cardObj.isSameApp && pages.path === cardObj.url)
          || (loginObj.isSameApp && pages.path === loginObj.url);
        // #endif
      },

      doneLayoutAndLocation(){
        if (this.layoutLoading) {
          console.log(this.$settings.defaultCity);
          this.$emit('onDone', this.getLayoutInfo);
          this.$emit('done', this.getLayoutInfo);
          this.$xdLog.setProject('Layout.done', {...this.getLayoutInfo, time: new Date().getTime() - this.startTime})
        }
      },

      /**
       * @description  获取胶囊相关数据
       */
      setMenuButtonBounding(){

        //#ifdef APP-PLUS
        this.navBarHeight = 80
        //#endif

        // #ifdef H5
        if (!this.showBar) this.navBarHeight = 0;
        if(this.isPreviewShowBar)  this.navBarHeight = 80;
        // #endif

        // 设置状态栏高度
        this.statusBarHeight = this.getRpx(this.systemInfoSyn.statusBarHeight);

        // MP-WEIXIN｜APP-PLUS｜mp-alipay
        // #ifdef  MP-WEIXIN || APP-PLUS || MP-ALIPAY
        // 获取胶囊的位置
        const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
        // (胶囊底部高度 - 状态栏的高度) + (胶囊顶部高度 - 状态栏内的高度) = 导航栏的高度
        //开启自定义导航
        if(this.navigationStyle === 'custom' || this.navigationStyle === true){
          this.navBarHeight = this.getRpx((menuButtonInfo.bottom - this.systemInfoSyn.statusBarHeight) + (menuButtonInfo.top - this.systemInfoSyn.statusBarHeight));
        }
        else{
          this.statusBarHeight =  0;
          this.navBarHeight = 0
        }
        // #endif

        //底部设置
        if(!this.showFooter) {
          this.tabbarHeigth = 0;
        }
        this.createTime = new Date().getTime() - this.startTime;
      },

      handleSafeBottom(){
        //未缓存安全距离
        this.$nextTick(() => {
          this.$xdUniHelper.getWindowHeight(['#xd-Layout__padding'], this)
            .then(res => {
              console.warn(`xd-layout.getWindowHeight: ${JSON.stringify(res)}`)
              console.log(this)
              this.safeHeight = Math.max(
                this.getRpx(res['#xd-Layout__padding']['height']),
                uni.getSystemInfoSync().safeAreaInsets.bottom
              );

              this.time = new Date().getTime() - this.startTime;
              this.initStatus = true;
              //保存计算属性
              uni.setStorageSync('xd-layout', {
                safeHeight: this.safeHeight
              });
              this.layoutDone();
            })
            .catch()
        })
      },

      /**
       * @description 获取底部安全距离数据
       */
      getSafeBottom(){
        //已缓存安全距离
        if(this.safeHeight !== null) {
          this.time = new Date().getTime() - this.startTime;
          this.initStatus = true;
          this.layoutDone();
          return
        }

        this.handleSafeBottom();

      },

      /**
       * @description 框架完成加载设置事件
       */
      layoutDone(){
        this.$nextTick(()=>{
          this.contentStatus = true;
          this.doneEvent();
          this.initAnimation()
        })
      },

      /**
       * @description rpx转px
       * @param num
       * @returns {number}
       */
      getPX(num){
        return this.$xdUniHelper.multiplyFloatNumber(num||0,this.$rpxNum);
      },

      /**
       * @description px转rpx
       * @param num
       * @returns {number}
       */
      getRpx(num){
        return this.$xdUniHelper.multiplyFloatNumber(num||0,this.$pxNum);
      },

      initAnimation() {
        //启动动画效果
        if (this.isAnimation) {
          //页面已加载时间
          let useTime = new Date().getTime() - this.startTime;
          let max = 50;

          //初始化使用事件小于50毫秒
          if (useTime < max) {
            setTimeout(() => {
              this.startAnimation = true;
            }, (max - useTime) < 10 ? 10 : (max - useTime));
          }

          //大于50毫秒直接开始动画
          else {
            this.startAnimation = true;
          }
        }
        //关闭动画效果
        else {
          this.$nextTick(()=>{
            this.doneAnimation = true;
          })
        }
      },

      backEvent() {
        // #ifdef  MP-WEIXIN || APP-PLUS || MP-ALIPAY
        if(this.isCustomNavigation) {
          this.$xdUniHelper.navigateBack();
          return
        }
        // #endif
        this.$emit('onBack');
        this.$emit('back');
      },

      doChange(){
        if (this.locationStatus && this.layoutLoading) {
          this.$emit('onChange', this.getLayoutInfo);
        }
      },

      doneEvent(){
        this.layoutLoading = true;
      },

    }
  }
</script>

<style scoped lang="less">
  .loadingblock {
    background-repeat: no-repeat;
    background-size: 100%;
    background-position: top center;
  }
  .networkStatus {
    background: rgba(255, 244, 191, 0.9);
    color: rgba(255, 102, 26, 1);
    font-size: unit(26, rpx);
    line-height: unit(50, rpx);
    text-align: center;
  }

  .systemInfoSyn {
    position: fixed;
    top: 160rpx;
    background: #fff;
    color: #000;
    z-index: 9999;
    font-size: 20rpx;
  }

  .xd-Layout {
    background-size: 100%;
    background-position: top center;
    min-height: calc(100vh - var(--window-top));
    background-repeat: no-repeat;

    &__padding {
      .safe-area();
      position: fixed;
      top: -9999px;
      left: -9999px;
      width: 100%;
      height: 0;

      &-placeholder {
        height: calc(constant(safe-area-inset-bottom) + 2px);
        height: calc(env(safe-area-inset-bottom) + 2px);
        position: fixed;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 1002;
        background: #fff;
      }
    }

    &__bar {
      position: fixed;
      z-index: 1300;
      background-color: #fff;
      background-position: top center;
      background-size: 100% auto;
      background-repeat: no-repeat;
      top: 0;
      right: 0;


      &.isPreviewShowBar /deep/ .xd-custom-bar__fixed-content-center{
        font-size: unit(24, rpx) !important;
        color: #dda450!important;
      }
    }

    &__body {
      z-index: 999;
      position: relative;
      background-size: 100%;
      background-position: top center;
      background-repeat: no-repeat;
    }

    &__top {
      position: fixed;
      z-index: 1001;
      right: 0;
      left: 0;
      width: 100%;
    }

    &__bottom {
      position: fixed;
      z-index: 1000;
      width: 100%;
      left: 0;
      right: 0;
      .safe-area();
    }

    &__footer {
      &-height {
        .safe-area();
      }
    }

    &__tabbar {
      position: fixed;
      left: 0;
      right: 0;
      z-index: 1200;
      .safe-area();
    }

    &__view {
      height: unit(100, rpx);
    }

    /**动画效果**/
    &__animation {
      width: 100vw;
      background-size: 100%;
      min-height: calc(100vh - var(--window-top));
      background-repeat: no-repeat;

      &.nohasanimation {
        margin-left: 0
      }

      &.animation {
        transition:margin-left 1s ease;
        margin-left: 0;

        & .animation-top, & .animation-bottom {
          transition:left 1s ease;
          left: 0;
        }

        & .animation-body {
          transition:margin-left 1s ease;
          margin-left: 0;
        }
      }

    }
  }

  .website-disable {
    width: 100%;
    min-height: calc(100vh - var(--window-top));
    display: flex;
    justify-content: center;
    align-items: center;

    & > image {
      max-width: 70vw;
    }
  }
</style>
