<template>
  <view id="decoraterId" v-if="tabs && tabs.length > 0" :style="globalStyle">
    <shopHead
      v-if="header == 'in'"
      :tab="shopBase"
      :title="pageSet.pageName"
      @inited="headInited"
      @decEventHandler="headFn"
    />
    <view v-for="(item, i) in tabs" :key="item.id" class="decorater-item">
      <shopFront :tab="item" v-if="item.type === 'shopFront'" />
      <shopSearch :tab="item" v-else-if="item.type === 'shopSearch'" />
      <showBlank :tab="item" v-else-if="item.type === 'showBlank'" />
      <showLines :tab="item" v-else-if="item.type === 'showLines'" />
      <shopNav :tab="item" v-else-if="item.type === 'shopNav'" />
      <goodList
        ref="autoLoadRef"
        :class="autoLoadAtBottom.ref == item.id ? 'autoLoadId' : 'noAuto'"
        @inited="autoLoadInited"
        :tab="item"
        v-else-if="item.type === 'goodList'"
      />
      <blockTitle :tab="item" v-else-if="item.type === 'blockTitle'" />
      <descText :tab="item" v-else-if="item.type === 'descText'" />
      <richText :tab="item" v-else-if="item.type === 'richText'" />
      <imageLink :tab="item" v-else-if="item.type === 'imageLink'" />
      <voiceLink :tab="item" v-else-if="item.type === 'voiceLink'" />
      <videoLink :tab="item" v-else-if="item.type === 'videoLink'" />
      <shopNotice :tab="item" v-else-if="item.type === 'shopNotice'" />
      <shopTel :tab="item" v-else-if="item.type === 'shopTel'" />
      <imageBlock :tab="item" v-else-if="item.type === 'imageBlock'" />
      <goodDiscount :tab="item" v-else-if="item.type === 'goodDiscount'" />
      <goodSpecial :tab="item" v-else-if="item.type === 'goodSpecial'" />
      <goodFine :tab="item" v-else-if="item.type === 'goodFine'" />
      <goodIntegral
        ref="autoLoadRef"
        :class="autoLoadAtBottom.ref == item.id ? 'autoLoadId' : 'noAuto'"
        @inited="autoLoadInited"
        :tab="item"
        v-else-if="item.type === 'goodIntegral'"
      />
    </view>
  </view>
</template>

<script>
import shopHead from "./shopHead";
/** 店招 **/
import shopFront from "./shopFront";
/** 搜索框 **/
import shopSearch from "./shopSearch";
/** 空白 **/
import showBlank from "./showBlank";
/** 辅助线 **/
import showLines from "./showLines";
/** 导航栏 **/
import shopNav from "./shopNav";
/** 商品列表 **/
import goodList from "./goodList";
/** 标题 **/
import blockTitle from "./blockTitle";
/** 文本 **/
import descText from "./descText";
/** 富文本 **/
import richText from "./richText";
/** 广告 **/
import imageLink from "./imageLink";
/** 语音 **/
import voiceLink from "./voiceLink";
/** 视频 **/
import videoLink from "./videoLink";
/** 公告 **/
import shopNotice from "./shopNotice";
/** 客服电话 **/
import shopTel from "./shopTel";
/** 图块区 **/
import imageBlock from "./imageBlock";
/** 限时抢购 **/
import goodDiscount from "./goodDiscount";
/** 商品专区 **/
import goodSpecial from "./goodSpecial";
/** 优惠限购 **/
import goodFine from "./goodFine";
/** 积分商品 **/
import goodIntegral from "./goodIntegral";

export default {
  name: "shop-decorater",
  components: {
    shopHead,
    /** 装修组件start **/
    shopFront,
    shopSearch,
    showBlank,
    showLines,
    shopNav,
    goodList,
    blockTitle,
    descText,
    richText,
    imageLink,
    voiceLink,
    videoLink,
    shopNotice,
    shopTel,
    imageBlock,
    goodDiscount,
    goodSpecial,
    goodFine,
    goodIntegral,
    /** 装修组件end **/
  },
  inject: ["decAxios", "decImgDomain"],
  props: {
    header: {
      type: String,
      default: "in",
    },
  },
  computed: {
    globalStyle() {
      if (this.header == "in") {
        return this.getGlobalStyle();
      } else {
        return "";
      }
    },
  },
  data() {
    return {
      waiting: false,
      tabs: [], // 左侧组件参数数组
      paddingTop: 0,
      autoLoadTop: 0,
      autoLoadTopUpdate: 0,
      autoLoadAtBottom: {},
      componentMap: {},
      pageSet: {
        id: "0",
        type: "pageSet",
        name: "页面配置",
        pageName: "首页", // 页面名称
        pageDesc: "页面描述", // 页面描述
        bgColor: "", // 页面背景色
      },
      shopBase: {
        type: "shopBase",
        mode: "", // 原生-高级custom
        styleArg: "", //fix
        fontColor: "black",
        lIcon: "",
        lIconImg: "",
        lIconLink: {},
        title: "",
        search: false,
        searchBg: "",
        rIcon: false,
        rIconFn: [],
        rIconImg: "",
        rIconCc: true,
        rIconLink: {},
      },
    };
  },
  methods: {
    initData(json) {
      // 获取保存好的数据
      let layout = [],
        autoLoadAtBottom = {},
        componentMap = {};
      try {
        const templateJson = JSON.parse(json); //JSON.parse(unescape(result.pageLayout));
        let len = templateJson.length,
          hasPageSet = false;
        let pageSet, shopBase;
        for (let i = len; i > 0; i--) {
          const name = templateJson[i - 1].type;
          if (name == "pageSet") {
            hasPageSet = true;
            pageSet = templateJson.splice(i - 1, 1);
          } else if (name == "shopBase") {
            shopBase = templateJson.splice(i - 1, 1);
          }
        }

        layout = templateJson;
        if (hasPageSet) {
          this.pageSet = Object.assign({}, this.pageSet, pageSet[0]);
          this.shopBase = Object.assign({}, this.shopBase, shopBase[0]);
        } else {
          this.pageSet = Object.assign({}, this.pageSet, shopBase[0]);
          this.shopBase = this.shopBase;
        }
        //记录组件位置
        const distance = this.header == "in" ? 1 : 0;
        layout.forEach((item, i) => {
          const name = item.type;
          if (!componentMap[name]) componentMap[name] = [];
          componentMap[name].push(i);
          //判断最后组件是否是无限加载组件
          if (layout.length == i + 1) {
            if (["goodList", "goodIntegral"].includes(item.type)) {
              if (item.arg.autoLoad == "Y") {
                autoLoadAtBottom = {
                  name: item.type,
                  index: i - distance,
                  ref: item.id,
                };
              }
            }
          }
        });
      } catch (err) {
        console.log("initData-err:", err);
      }
      console.log("initData-layout:", layout);
      this.tabs = layout;
      this.$emit("inited", {
        count: layout.length,
        pageName: this.pageSet.pageName,
        navMode: this.shopBase.mode,
        pageSet: this.pageSet,
        shopBase: this.shopBase,
        globalStyle: this.getGlobalStyle(),
        autoLoadAtBottom,
      });
      this.componentMap = componentMap;
      this.autoLoadAtBottom = autoLoadAtBottom;
    },
    getGlobalStyle() {
      const arr = [
        `background-color:${this.pageSet.bgColor};`,
        `background-image: url('${this.pageSet.bgImg}')`,
        `background-repeat:${this.pageSet.repeat ? "repeat" : "no-repeat"}`,
        `background-size:${this.pageSet.repeat ? "" : "100% auto"}`,
      ];
      return arr.join(";");
    },
    headInited(obj) {
      this.paddingTop = (obj && obj.height) || 57;
    },
    autoLoadInited() {
      //获取高度
      const that = this;
      const query = uni.createSelectorQuery().in(this);
      query.select("#decoraterId").boundingClientRect();
      query.select("#decoraterId .autoLoadId").boundingClientRect();
      query.exec((res) => {
        const totalH = res[0].height;
        const loadH = res[1].height;
        const autoLoadTop = totalH - loadH;
        that.autoLoadTop = autoLoadTop;
        that.autoLoadTopUpdate += 1;
      });
    },
    pageScroll(top, fixTop) {
      if (!this.waiting) {
        this.waiting = true;
        const i = this.autoLoadAtBottom.index || -1;
        if (i > -1) {
          const autoLoads = this.$refs.autoLoadRef;
          const target = autoLoads[autoLoads.length - 1];
          if (!target.setTabFixed) return;
          if (this.autoLoadTopUpdate == 1 && this.autoLoadTop * 0.5 < top) {
            this.autoLoadInited();
          }
          if (this.autoLoadTop < top) {
            target.setTabFixed(true, fixTop || this.paddingTop); //设置tab固定
          } else {
            target.setTabFixed(false);
          }
          this.waiting = false;
        }
      }
    },
    pageShow() {
      //现采用全局事件通信，此方法待用
      console.log("$children-$children:", this.$children);
      const findChild = (j) => {
        const distance = this.header == "in" ? 1 : 0;
        const i = j - distance;
        let children = {};
        // #ifdef H5
        children = this.$children[0];
        children = children[i];
        // #endif
        // #ifndef H5
        children = this.$children[i];
        // #endif
        return children;
      };
    },
    reachBottom() {
      const i = this.autoLoadAtBottom.index || -1;
      if (i > -1) {
        console.log("autoLoad-reachBottom:", i);
        const autoLoads = this.$refs.autoLoadRef;
        const target = autoLoads[autoLoads.length - 1];
        target.reachBottomFn && target.reachBottomFn();
      }
    },
    headFn(params, link) {
      this.decAxios.decEventHandler(params, link);
    },
  },
};
</script>
