<template>
  <view class="dec-goodList" v-if="showGoods.length > 0">
    <view class="group-wrap">
      <view
        v-for="key in groups"
        :key="key"
        class="group"
        :style="styleW"
        :class="className"
      >
        <goodWrap
          v-for="code in showGoods"
          :key="code"
          :arg="arg.listStyle"
          :groupKey="key"
          :goodKey="code"
        />
        <view class="group-bottom" />
      </view>
    </view>
    <li-load-more v-if="arg.autoLoad == 'Y'" :status="loadMore" />
  </view>
</template>

<script>
// 设置列表
import variable from "../style/variable.js";
import goodWrap from "./goodWrap";
export default {
  inject: ["decAxios", "decImgDomain"],
  components: { goodWrap },
  props: {
    tab: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      loading: false,
      loadMore: "",
      arg: {},
      show: null,
      isStatic: false,
      groups: [], //数据组
      styleW: "",
      className: "",
      allGoods: {}, //所有数据集合
      showGoods: [], //显示的商品数据
      styleMap: {
        "scroll-two": ["left"],
        "scroll-three": ["left"],
        join: ["left"],
        concat: ["left"],
        big: ["left"],
        one: ["left"],
        double: ["left", "right"],
        two: ["left", "right"],
        three: ["left", "middle", "right"],
      },
      pager: {
        pages: 0,
        pageNo: 0, //页面页码
        pageSize: 30,
      },
      img: {
        h1: "",
        h2: "",
        h3: "",
        w40: "",
        url: "",
      },
    };
  },
  onUnload() {
    this.loadMore = "";
  },
  created() {
    this.arg = this.tab.arg;
    this.show = this.arg.show || this.arg.goodShow;
    const addFun = this.arg.styleArg || "";
    this.groups = this.styleMap[this.arg.listStyle] || ["left"];
    this.styleW = `width:${parseInt(10000 / this.groups.length) / 100}%`;
    const map2 = ["one", "two", "three"];
    this.className = `${map2[this.groups.length - 1] || "other"}-group`;

    // 初始化数据
    if (addFun === "api") {
      this.pager.pageNo = 0;
      this.initApiData(true);
    } else {
      this.initData(this.reachBottomFn);
    }
  },
  methods: {
    initData(callback) {
      if (!this.loading) {
        this.loading = true;
        const ids = this.arg.ids || [];
        this.isStatic =
          this.arg.styleArg == "fix" && (ids.length == 0 || this.arg.static);
        const api = this.decAxios.getGoodListData;
        const promiseArr = !this.isStatic
          ? api({
              getType: "0",
              ids: ids.map((item) => item._id || item.id || item).join(","),
            })
          : new Promise((resolve) => {
              resolve({
                code: 200,
                result: ids.length > 0 ? [...ids] : [],
              });
            });
        const that = this;
        promiseArr.then((res) => {
          const result =
            res.code == "200" ? res.result.records || res.result || [] : [];
          const goodList = that.listStyleChange(result);
          //加入到数据源中
          const pageKey = `0-${that.pager.pageSize}`;
          that.groups.forEach((val) => {
            const key = `${val}-${pageKey}`;
            that.allGoods[key] = goodList[val];
          });
          that.loading = false;
          that.pager.pageNo = 0;
          if (typeof callback == "function") callback();
        });
      }
    },
    initApiData(isInit) {
      if (!this.loading) {
        this.loading = true;
        //处理参数
        const api = this.decAxios.getGoodListData;
        const { pageSize } = this.pager;
        let pageNo = this.pager.pageNo + 1;

        let params = { getType: "1" };
        if (this.arg.autoLoad == "Y") {
          params = Object.assign({}, params, { pageNo, pageSize });
        } else {
          params.getCount = this.arg.dataNum || 10;
        }
        //获取数据
        api(params).then((res) => {
          this.loading = false;
          const result = res.result || {};
          const records =
            res.code == "200" ? result.records || result || [] : [];
          const that = this;
          this.judgeWhoShort((offset) => {
            const goodList = that.listStyleChange(records, offset) || {
              left: [],
            };
            const pageKey = `${pageNo}-${that.pager.pageSize}`;
            //加入到数据源中
            that.groups.forEach((val) => {
              const key = `${val}-${pageKey}`;
              that.allGoods[key] = goodList[val];
            });
            //页码更新
            that.pager.pages = result.pages || 1;
            that.pager.pageNo = params.pageNo || 1;
            //初次加载需要进行额外请求一次
            if (isInit) that.reachBottomFn();
            else that.loadMore = "";
          }, isInit);
        });
      }
    },
    reachBottomFn() {
      const { pageNo, pageSize, pages } = this.pager;
      const showKey = `${pageNo}-${pageSize}`;
      this.loadMore = "";
      if (this.arg.autoLoad != "Y" || this.loading) {
        if (!this.showGoods.includes(showKey)) this.showGoods.push(showKey);
      } else if (pageNo > 0 && pageNo == pages) {
        if (!this.showGoods.includes(showKey)) this.showGoods.push(showKey);
        this.loadMore = "noMore";
      } else {
        this.loadMore = "loading";
        if (!this.showGoods.includes(showKey)) this.showGoods.push(showKey);
        this.initApiData();
      }
      //图片初始化
      const key = `left-${this.showGoods[0]}`;
      let imgObj = this.allGoods[key][0];
      //多层处理
      imgObj = (Array.isArray(imgObj) ? imgObj[0] : imgObj) || {};
      //组图或拼团逻辑处理
      if (imgObj.big && imgObj.big.productImg) imgObj = imgObj.big;
      let firstImg = (imgObj && imgObj.productImg) || "";
      firstImg = firstImg ? this.decImgDomain(firstImg) : "";
      this.initImgH(firstImg, firstImg == this.img.url);
      this.img.url = firstImg;
    },
    initImgH(url, same) {
      if (!!url && !!same) return;
      //计算图片实际宽高-默认1:1的图片
      const img = { height: 200, width: 200 };
      const w1 = variable["@phoneWidth"] - variable["@space2"] * 4,
        w2 = variable["@phoneWidth"] - variable["@space2"] * (2 * 2 + 2),
        w3 = variable["@phoneWidth"] - variable["@space2"] * (2 * 3 + 2),
        w40 = w1 * 0.4;
      //X100
      let h1 = parseInt((100 * w1 * img.height) / img.width),
        h2 = parseInt((50 * w2 * img.height) / img.width),
        h3 = parseInt((33.33 * w3 * img.height) / img.width),
        h40 = parseInt(100 * w40);
      //upx2px
      h1 = uni.upx2px(h1) / 100;
      h2 = uni.upx2px(h2) / 100;
      h3 = uni.upx2px(h3) / 100;
      h40 = uni.upx2px(h40) / 100;

      //确定图片变量值[等高或者是流式布局]
      const imgH1 = h1 + "px",
        imgH2 = h2 + "px",
        imgH3 = h3 + "px",
        imgH4 = h40 + "px";

      console.log(
        "handerImgSize:",
        uni.upx2px(100),
        imgH1,
        imgH2,
        imgH3,
        imgH4
      );
      const map2 = ["two", "three", "double"];
      const isFluid = this.arg.layout == "fluid";
      if (map2.includes(this.arg.listStyle) && isFluid) {
        this.img.h2 = "";
        this.img.h3 = "";
      } else {
        this.img.h1 = imgH1 || this.img.h1;
        this.img.h2 = imgH2 || this.img.h2;
        this.img.h3 = imgH3 || this.img.h3;
        this.img.w40 = imgH4 || this.img.h40;
      }
      // uni.getImageInfo({
      //   src: url,
      //   success: function(img){
      //     handerImgSize(img);
      //   },
      //   fail: function(e){
      //     handerImgSize({height: 200, width: 200});
      //   }
      // })
    },
    listStyleChange(res, offset) {
      const val = this.arg.listStyle;
      if (val == "scroll-two") {
        let newRes = [];
        res.forEach((item, i) => {
          if ((i + 1) % 2 == 0) {
            newRes.push([res[i - 1], item]);
          }
        });
        return { left: newRes };
      } else if (val == "scroll-three") {
        let newRes = [];
        res.forEach((item, i) => {
          if ((i + 1) % 3 == 0) {
            newRes.push([res[i - 2], res[i - 1], item]);
          }
        });
        return { left: newRes };
      } else if ("join,concat".indexOf(val) > -1) {
        let newRes = [];
        res.forEach((item, i) => {
          if ((i + 1) % 3 == 0) {
            newRes.push({
              big: res[i - 2],
              small: [res[i - 1], item],
            });
          }
        });
        return { left: newRes };
      } else if (["double", "two"].includes(val)) {
        let newRes = { right: [], left: [] },
          j = offset || 0;
        res.forEach((item, i) => {
          if ((i + 1 + j) % 2 == 1) {
            newRes.left.push(item);
          } else {
            newRes.right.push(item);
          }
        });
        return newRes;
      } else if (val == "three") {
        let newRes = { right: [], middle: [], left: [] },
          j = offset || 0;
        res.forEach((item, i) => {
          if ((i + 1 + j) % 3 == 1) {
            newRes.left.push(item);
          } else if ((i + 1 + j) % 3 == 2) {
            newRes.middle.push(item);
          } else {
            newRes.right.push(item);
          }
        });
        return newRes;
      } else {
        return { left: res || [] };
      }
    },
    judgeWhoShort(callback, isInit) {
      if (isInit) return callback(0);
      const query = uni
        .createSelectorQuery()
        .in(this)
        .selectAll(".group-bottom");
      query
        .boundingClientRect((doms) => {
          let shortIndex = 0,
            min = 0;
          if (doms && doms.length > 0) {
            doms.forEach((dom, i) => {
              if (i == 0) min = dom.top;
              if (dom.top < min) {
                min = dom.top;
                shortIndex = i;
              }
            });
          }
          callback(shortIndex);
        })
        .exec();
    },
  },
};
</script>
