const app = getApp();
const { goodsApi, DFSImg, $themeToLink } = app;
const componentOptions = {
  // 组件选项
  options: {
    multipleSlots: true
  },
  behaviors: [],
  properties: {
    datas: {
      type: Object
    }
  },
  // 组件数据
  data: {
    isPageHidden: false, // 页面是否处于隐藏状态
    titleIcon: "",
    classificationLoadPage: 1,
    classificationLoadNum: 10,
    queryProductInfoLoading: false,
    loading: false,
    finished: false
  },
  // 数据监听器
  observers: {},
  // 组件生命周期
  lifetimes: {
    created() {},
    ready() {},
    moved() {},
    detached() {}
  },
  attached() {
    this.init();
  },
  definitionFilter() {},
  // 页面生命周期
  pageLifetimes: {
    // 页面被展示
    show() {
      const { isPageHidden } = this.data;

      // show事件发生前,页面不是处于隐藏状态时
      if (!isPageHidden) {
        return;
      }

      // 重新执行定时器等操作
    },
    // 页面被隐藏
    hide() {
      this.setData({
        isPageHidden: true
      });

      // 清除定时器等操作
    },
    // 页面尺寸变化时
    resize() {}
  },
  // 组件方法
  methods: {
    init() {
      let {
        goodsType,
        goodsSource,
        angleSignImg,
        titleIcon
      } = this.data.datas.componentData;
      angleSignImg = DFSImg(angleSignImg);
      if (titleIcon) {
        titleIcon = DFSImg(titleIcon);
      }
      this.setData({
        "data.datas.componentData.angleSignImg": angleSignImg,
        titleIcon
      });
      console.log(this.data.titleIcon, "----------------------------68");
      if (goodsType == 0) {
        if (goodsSource == "classify") {
          //商品分类
          this.getProductList(1, 1);
        } else {
          //指定商品
          this.getProductList(2);
        }
      } else if (goodsType == 1) {
        if (goodsSource == "classify") {
          //商品分类
          this.getInterList(1);
        } else {
          //指定商品
          this.getInterList(2);
        }
      }
    },
    getProductList(code, type) {
      let { goodsList, goodsSort } = this.data.datas.componentData;
      let {
        classificationLoadPage,
        loading,
        finished,
        queryProductInfoLoading
      } = this.data;
      if (queryProductInfoLoading == true) {
        return;
      }
      this.setData({ queryProductInfoLoading: true });
      // type 1初始化 2滚动加载
      //分类查
      if (code == 1) {
        if (type == 1) {
          classificationLoadPage = 1;
        } else {
          classificationLoadPage++;
          loading = true;
        }
        this.setData({ classificationLoadPage, loading });
        let query = {
          categoryId: this.data.datas.componentData.categoryId,
          page: this.showRowNum() ? classificationLoadPage : 1,
          rows: this.showRowNum()
            ? this.data.classificationLoadNum
            : this.getItemNum(),
          sortColumn: goodsSort,
          sortType: goodsSort != 2 ? 1 : 0,
          whetherShowSoldOutGoods: this.data.datas.componentData
            .whetherShowSoldOutGoods,
          whetherQueryCollectCount: true,
          whetherUseVirtualSalesQty: true,
          whetherUseVirtualCollectCount: true,
          whetherFindDistributionCommission: this
            .whetherFindDistributionCommission,
          whetherFindRecommendedCardFlag: this.data.datas.componentData.vipPrice
            ? 1
            : 0,
          whetherShowGoodsDefaultTagFlag: this.data.datas.componentData
            .marketingTag
            ? 1
            : 0,
          whetherFindMultiShopFlag: 1
        }; // 当前页 // 一页多少条 //查询销售数量 //查询收藏数 //是否使用虚拟销售数量 //是否使用虚拟收藏人数 //是否查询商品佣金(0:不查询,1:展示,为空不查佣金) //是否查询会员价  1是  0否 //是否展示营销标签  1是  0否 //是否查询多商户   //商城使用
        goodsApi.queryProductInfo(query).then(res => {
          this.setData({ loading: false, queryProductInfoLoading: false });
          if (res.data.code == 200) {
            let goodsLists = res.data.data.list;
            if (type == 1) {
              goodsList = goodsLists;
            } else {
              goodsList = [...goodsList, ...goodsLists];
            }
            if (goodsLists && goodsLists.length < 10) {
              this.setData({ finished: true });
            }
            this.goodsListVal(goodsList, type);
          }
        });
      } else {
        // 商品产品详情
        let terminalProductIds = goodsList.map(element => {
          return element.terminalProductId;
        });
        if (terminalProductIds.length == 0) {
          return;
        }
        let briefQuery = {
          sortColumn: goodsSort,
          sortType: goodsSort != 2 ? 1 : 0,
          page: 1,
          rows: terminalProductIds.length,
          terminalProductIds: terminalProductIds,
          whetherShowSoldOutGoods: this.whetherShowSoldOutGoods
        }; // 当前页 // 一页多少条
        this.briefProduct(briefQuery);
      }
    },
    async briefProduct(query) {
      await goodsApi.queryBriefProductInfo(query).then(res => {
        if (res.data.code == 200) {
          let data = res.data.data.list;
          let ids = data.map(element => {
            let goodsList = this.render ? res.data.list : res.data.data.list;
            return element.terminalProductId;
          });
          this.moreProduct(ids);
        }
      });
    },
    async moreProduct(terminalProductIds) {
      let {
        vipPrice,
        marketingTag,
        whetherFindDistributionCommission,
        goodsList
      } = this.data.datas.componentData;
      let moreQuery = {
        terminalProductIds,
        whetherQueryCollectCount: true, //查询收藏数
        whetherUseVirtualSalesQty: true, //是否使用虚拟销售数量
        whetherUseVirtualCollectCount: true, //是否使用虚拟收藏人数
        whetherFindDistributionCommission: whetherFindDistributionCommission, //是否查询商品佣金(0:不查询,1:展示,为空不查佣金)
        whetherFindRecommendedCardFlag: vipPrice ? 1 : 0, //是否查询会员价  1是  0否
        whetherShowGoodsDefaultTagFlag: marketingTag ? 1 : 0, //是否展示营销标签  1是  0否
        whetherFindMultiShopFlag: 1 //是否查询多商户   //商城使用
      };
      goodsApi.queryMoreProductInfo(moreQuery).then(res => {
        if (res.data.code == 200) {
          goodsList = res.data.data;
          this.goodsListVal(goodsList, 1);
        }
      });
    },
    goodsListVal(goodsList, type) {
      console.log(goodsList, "------------goodsListVal");
      goodsList.forEach((item, index) => {
        item.marketingTag = item.defaultTags
          ? this.filtermark(
              item.defaultTags,
              this.data.datas.componentData.marketingTagList
            )
          : [];
        item.shopLogoUrl = DFSImg(item.shopLogoUrl);
        item.coverImage = DFSImg(item.coverImage, 100, 100, 0);
        item.productImgUrl = DFSImg(item.productImgUrl, 100, 100, 0);
        item.minPrice = Number(item.minPrice).toFixed(2);
        item.qty = Number(item.qty);
        item.saleQty = Number(item.saleQty);
        item.totalCollectionCount = Number(item.totalCollectionCount) || 0;
        item.minPriceAfterRecommendedCardPriceTable = item.minPriceAfterRecommendedCardPriceTable
          ? Number(item.minPriceAfterRecommendedCardPriceTable)
          : "";
        item.minProductGoodsCommission = item.minProductGoodsCommission
          ? Number(item.minProductGoodsCommission).toFixed(2)
          : 0;
        item.minGoodsSuggestedRetailPrice = item.minGoodsSuggestedRetailPrice
          ? Number(item.minGoodsSuggestedRetailPrice).toFixed(2)
          : "";
        item.showVipPrice = this.showVipPrice(item, index);
        item.showVipTag = this.showVipTag(item, index);
        if (item.saleTime) {
          item.getSaleTime = 0;
          item.getSaleTime = this.getSaleTime(item.saleTime);
        }
      });
      setTimeout(() => {
        this.setData({
          "datas.componentData.goodsList": goodsList
        });
        if (type == 1) {
          // 初始化
          if (this.selectComponent("#waterfallFlow")) {
            this.selectComponent("#waterfallFlow").initList();
          }
        } else {
          // 滚动加载
          if (this.selectComponent("#waterfallFlow")) {
            this.selectComponent("#waterfallFlow").reLoadPro();
          }
        }
      }, 0);
    },
    getSaleTime(val) {
      return new Date(val.replace(/-/g, "/")).getTime() - new Date().getTime();
    },
    getItemNum() {
      //数量
      if (
        this.data.datas.componentData.style === "list" &&
        this.data.datas.componentData["goodsSource"] != "assign"
      ) {
        //网格模式
        if (
          this.data.datas.componentData.rowNum *
            this.data.datas.componentData.columnNum >=
          this.data.datas.componentData.goodsList.length
        ) {
          return this.data.datas.componentData.goodsList.length;
        } else {
          return (
            this.data.datas.componentData.rowNum *
            this.data.datas.componentData.columnNum
          );
        }
      } else {
        return this.data.datas.componentData.goodsList.length;
      }
    },
    showRowNum() {
      return (
        this.data.datas.componentData.moreShow == false &&
        this.data.datas.componentData.style == "waterfall" &&
        this.data.datas.componentData.goodsSource == "classify"
      );
    },
    filtermark(newlist, marketingTagList) {
      let list = [];
      if (newlist.length <= 0) return;
      if (marketingTagList.length > 0) {
        marketingTagList.forEach((item, index) => {
          newlist.forEach((item1, index1) => {
            if (item1 == item.key) {
              list.push(item);
            }
          });
        });
      }
      return list;
    },
    showVipPrice(item, index) {
      // 索引 0 显示价格 1显示名称
      let showFlag = false;
      let vipPrice = item["minPriceAfterRecommendedCardPriceTable"];
      if (vipPrice && Number(vipPrice) < Number(item["minPrice"])) {
        showFlag = true;
      }
      return showFlag;
    },
    showVipTag(item, index) {
      // 索引 0 显示价格 1显示名称
      let showFlag = false;
      let vipPrice = item["minPriceAfterRecommendedCardPriceTable"];
      let showTag = item["recommendedCardMinPricePriceTableName"];
      if (vipPrice && showTag && Number(vipPrice) <= Number(item["minPrice"])) {
        showFlag = true;
      }
      return showFlag;
    },
    getScroll(el) {
      // 是指定分类且不显示查看更多的瀑布流组件滚动加载
      let { goodsSource, moreShow, style } = this.data.datas.componentData;
      if (
        goodsSource == "classify" &&
        moreShow == false &&
        style == "waterfall"
      ) {
        this.selectComponent("#waterfallFlow").getScroll(el);
      }
    },
    // 分页加载
    onLoad() {
      console.log("---触发分页加载");
      this.getProductList(1, 2);
    },
    viewMore() {
      let { goodsType,style, categoryName, categoryId } = this.data.datas.componentData;
      let linkVal = "";
      if (goodsType != 1) {
        if (style == "list") {
          linkVal = `/goods/commodityMenu?categoryName=${categoryName}&categoryId=${categoryId}`;
        } else {
          linkVal = `/goods/commodityMenu`;
        }
      } else {
        linkVal = `/pointShop/productList?categoryName=${categoryName}&categoryId=${categoryId}`;
      }
      $themeToLink({
        type: 1,
        link:linkVal,
      });
    }
  }
};

Component(componentOptions);