// packageE/newDiy/newDiy.js
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    page_id: "",
    is_store: false, // 门店装修
    store_id: "", // 门店装修
    clientWidth: "375",
    page_name: "",
    showPage: true,

    btnFlag: false,
    fullShow: false,
    popShow: false,
    advertising: {},
    full_screen: {},
    top_info: {},
    bottom_info: {},
    components: [],
    mailInfo: {}, // 商城信息
    foot_type: "",

    current_page: 1,
    total_page: 0,
    decorate_isLoadMore: true,

    isWatch: true, //会员浏览权限
    bottomShowBol: false,
    bottomShowBolIndex: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.page_id) {
      this.setData({
        page_id: options.page_id,
      });
    }
    if (options.store_id) {
      this.setData({
        is_store: true,
        store_id: options.store_id,
      });
    }
    if (options.scene) {
      let scene = decodeURIComponent(options.scene);
      if (scene) {
        var info_arr = [];
        info_arr = scene.split(",");
        for (let i = 0; i < info_arr.length; i++) {
          let chil_arr = [];
          chil_arr = info_arr[i].split("=");
          if (chil_arr[0] == "mid") {
            app._setMid(chil_arr[1]);
          }
          if (chil_arr[0] == "page_id") {
            this.setData({
              page_id: chil_arr[1],
            });
          }
          if (chil_arr[0] == "store_id") {
            this.setData({
              store_id: chil_arr[1],
            });
          }
        }
      }
    }
    if (options.mid) {
      app._setMid(options.mid);
    }
    this.getNewDesinger();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.setData({
      clientWidth: wx.getSystemInfoSync().windowWidth,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  getNewDesinger() {
    const that = this;
    this.setData({
      showPage: false,
    });

    let jsons = {
      page_id: this.data.page_id,
    };

    let urlStr = app.getNetAddresss("home-page.index");

    if(this.data.store_id) {
      urlStr = app.getNetAddresss("plugin.store-cashier.frontend.store.get-store-info.get-the-provider");
      jsons = { page_id: this.data.page_id, store_id: this.data.store_id };
    }
    app._getNetWork({
      url: urlStr,
      data: jsons,
      success: (resdata) => {
        var res = resdata.data;
        if (res.result == 1) {
          if(this.data.is_store) {
            this.setData({
              showPage: true,
              components: res.data.store_decorate.datas,
              page_name: res.data.store_decorate?.page_info?.page_title || '商家',
              foot_type: res.data.store_decorate.foot_type
            });

            // 装修的底部有三种情况
            if (res.data.store_decorate.foot_type == -1) {
              // 不显示
              this.setData({
                bottom_info: {},
              });
            } else if (res.data.store_decorate.foot_type == 1) {
              // 显示默认
              if (!res.data.store_decorate.foot_id || !res.data.store_decorate.foot_id.page_info) {
                // 显示系统默认
                this.setData({
                  bottom_info: {},
                });
              } else {
                // 显示列表设置的默认
                this.setData({
                  bottom_info: JSON.parse(res.data.store_decorate.foot_id.page_info),
                });
              }
            } else if (res.data.store_decorate.foot_type == 2) {
              // 显示自定义的底部导航
              if (!res.data.store_decorate.foot_id || res.data.store_decorate.foot_id instanceof Array) {
                this.setData({
                  bottom_info: {},
                });
              } else {
                this.setData({
                  bottom_info: JSON.parse(res.data.store_decorate.foot_id.page_info),
                });
              }
            }

            if (this.data.page_name) {
              wx.setNavigationBarTitle({
                title: this.data.page_name,
              });
            }
            return;
          }
          if (res.data.item) {
            this.setData({
              showPage: true,
            });
            let mailInfo = wx.getStorageSync('yz_basic_info');
            if(mailInfo){
              mailInfo = mailInfo.home.mailInfo;
            }
            this.setData({
              components: res.data.item.datas,
              page_name: res.data.item.page_info?.page_title,
              mailInfo: mailInfo?mailInfo:'',
              foot_type: res.data.item.foot_type,
              decorate_isLoadMore: true,
            });

            if (res.data.item.page) {
              this.setData({
                total_page: res.data.item.page.total_page,
                current_page: res.data.item.page.current_page,
                bottomShowBolIndex: res.data.item.page.count - 1,
              });
            }

            if (res.data.item.page_info) {
              that.setData({
                advertising: res.data.item.page_info.advertising_id,
                full_screen: res.data.item.page_info.full_screen_id,
              });

              if (that.data.advertising.id && that.data.advertising.datas) {
                that.data.advertising.datas = JSON.parse(
                  that.data.advertising.datas
                );
                that.setData({
                  advertising: that.data.advertising,
                });
              }
            }

            if (res.data.item.top && res.data.item.top.id) {
              this.setData({
                top_info: JSON.parse(res.data.item.top.page_info),
              });
            }

            // 装修的底部有三种情况
            if (res.data.item.foot_type == -1) {
              // 不显示
              this.setData({
                bottom_info: {},
              });
            } else if (res.data.item.foot_type == 1) {
              // 显示默认
              if (!res.data.item.foot || !res.data.item.foot.page_info) {
                // 显示系统默认
                this.setData({
                  bottom_info: {},
                });
              } else {
                // 显示列表设置的默认
                this.setData({
                  bottom_info: JSON.parse(res.data.item.foot.page_info),
                });
              }
            } else if (res.data.item.foot_type == 2) {
              // 显示自定义的底部导航
              if (!res.data.item.foot || res.data.item.foot instanceof Array) {
                this.setData({
                  bottom_info: {},
                });
              } else {
                this.setData({
                  bottom_info: JSON.parse(res.data.item.foot.page_info),
                });
              }
            }

            if (this.data.full_screen && this.data.full_screen.id) {
              let value = wx.getStorageSync("page_idFull_screens");
              if (!value) {
                value = [];
              }

              if (!value.includes(this.data.page_id)) {
                value.push(this.data.page_id);
                wx.setStorageSync("page_idFull_screens", value);
                this.setData({
                  fullShow: true,
                });
                this.countDown(this.data.full_screen.show_time);
              }
            }

            if (this.data.advertising && this.data.advertising.id) {
              let value = wx.getStorageSync("page_idAdvertisings");
              if (!value) {
                value = [];
              }

              if (!value.includes(this.data.page_id)) {
                value.push(this.data.page_id);
                wx.setStorageSync("page_idAdvertisings", value);
                this.setData({
                  popShow: true,
                });
              }
            }

            // 小程序标题栏
            if (res.data.item.page_info && res.data.item.page_info.preview_color) {
              wx.setNavigationBarColor({
                backgroundColor: res.data.item.page_info.preview_color,
                frontColor:
                  res.data.item.page_info.font_color == 1
                    ? "#ffffff"
                    : "#000000",
                animation: {
                  duration: 400,
                  timingFunc: "easeIn",
                },
              });
            }

            that.setData({
              isWatch:
                res.data.item.pageinfo.params.allowauth == 0 ? false : true,
            });
            if(!that.data.isWatch && res.data.item.page_info &&res.data.item.page_info.member_level_url && res.data.item.page_info.member_level_url.link) {
              that.timer = setTimeout(() => {
                wx.redirectTo({
                  url: res.data.item.page_info.member_level_url.link,
                });
              }, 3000);

            }
            console.log("会员是否可浏览装修页", that.data.isWatch);

            if (this.data.page_name) {
              wx.setNavigationBarTitle({
                title: this.data.page_name,
              });
            } else {
              wx.setNavigationBarTitle({
                title: "默认标题",
              });
            }
          }
        } else {
          wx.showToast({
            title: res.msg,
            icon: "none",
          });
          console.log(res.msg);
        }
      },
    });
  },

  getMoreDecorate() {
    let that = this;
    that.setData({
      decorate_isLoadMore: false,
    });

    if (that.data.current_page < that.data.total_page) {
      that.setData({
        current_page: that.data.current_page + 1,
      });
      let urlStr = app.getNetAddresss(
        "plugin.decorate.frotend.decorate-api.get-page"
      );
      app._postNetWork({
        url: urlStr,
        data: {
          decorate_page: this.data.current_page,
          decorate_id: this.data.page_id,
        },
        success: (resdata) => {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              decorate_isLoadMore: true,
              components: that.data.components.concat(res.data.datas),
            });
          } else {
            that.setData({
              decorate_isLoadMore: false,
              current_page: that.data.current_page - 1,
            });
            console.log(res.msg);
          }
        },
      });
    }
  },

  turnFullTo() {
    let url = this.data.full_screen.minapp_link;
    try {
      wx.navigateTo({
        url: url,
      });
    } catch (e) {
      wx.showToast({
        title: "链接设置错误",
        icon: "none",
        duration: 2000,
      });
    }
  },
  turnTo() {
    let item = this.data.advertising;
    if (item.is_minapp == 2) {
      if (item.minapp_sid) {
        if (item.minapp_link2) {
          try {
            wx.navigateToMiniProgram({
              appId: item.minapp_sid,
              path: item.minapp_link2,
              extraData: {},
              envVersion: "release",
              success(res) {
                // 打开成功
              },
              fail(res) {
                wx.showToast({
                  title: "小程序跳转失败",
                  icon: "none",
                  duration: 2000,
                });
              },
            });
          } catch (e) {
            wx.showToast({
              title: "小程序跳转失败",
              icon: "none",
              duration: 2000,
            });
          }
        } else {
          wx.showToast({
            title: "请设置跳转小程序后的跳转链接",
            icon: "none",
            duration: 2000,
          });
        }
      } else {
        wx.showToast({
          title: "请设置小程序所需跳转appId",
          icon: "none",
          duration: 2000,
        });
      }
    } else {
      let url = item.minapp_link;
      try {
        wx.navigateTo({
          url: url,
        });
      } catch (e) {
        wx.showToast({
          title: "链接设置错误",
          icon: "none",
          duration: 2000,
        });
      }
    }
  },
  closePop() {
    this.setData({
      popShow: false,
    });
  },
  closeFull() {
    this.setData({
      fullShow: false,
    });
  },
  countDown(num) {
    let numberNum = num;
    this.setData({
      "full_screen.show_time": numberNum,
    });
    numberNum--;

    let cleartime = setTimeout(() => {
      if (numberNum <= 0) {
        this.setData({
          fullShow: false,
        });
        clearInterval(cleartime);
        return;
      } else {
        this.countDown(numberNum);
      }
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.timer);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  // 获取滚动条当前位置
  onPageScroll: function (e) {
    // 节流
    if (e.scrollTop > 80) {
      if (!this.data.btnFlag) {
        this.setData({
          btnFlag: true,
        });
      }
    } else {
      if (this.data.btnFlag) {
        this.setData({
          btnFlag: false,
        });
      }
    }

    if (this.data.bottomShowBol) {
      this.setData({
        bottomShowBol: false,
      });
    }
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.setData({
      bottomShowBol: true,
    });

    if (this.data.decorate_isLoadMore) {
      this.getMoreDecorate();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareTimeline:function(){
    var value = wx.getStorageSync('yz_uid');
    let mid = '';
    let path = `/packageG/newDiy/newDiy?page_id=${this.data.page_id}`;
    if(this.data.is_store) {
      path = path + '&store_id' + this.data.store_id;
    }
    if (value) {
      mid = value;
      path = path + '&mid' + mid;
    }
    this.data.components.forEach(element => {
      if(element.component_key == 'U_lottery'){
        if(e.from == "menu"){
          this.getShare(element.remote_data.lottery.id);
          return {
            title: this.data.page_name ? this.data.page_name : "",
            path: path,
          };
        }
      }
    });
    return {
      title: this.data.page_name ? this.data.page_name : "",
      path: path,
    };
  },
  onShareAppMessage: function (e) {
    var value = wx.getStorageSync('yz_uid');
    let mid = '';
    if (value) {
      mid = value;
    }
    this.data.components.forEach(element => {
      if(element.component_key == 'U_lottery'){
        if(e && e.from == "menu"){
          this.getShare(element.remote_data.lottery.id);
          return {
            title: this.data.page_name ? this.data.page_name : "",
            path: `/packageG/newDiy/newDiy?page_id=${this.data.page_id}&mid=${mid}`,
          };
        }
      }
    });
    
    if(e && e.from == 'button' && e.target.dataset.tag == "shareTag"){
      // 拼团活动二开#73727 弹窗邀请朋友
      if(e.target.dataset.item == '1'){
        let _path = '/packageB/member/group/GroupDetail/GroupDetail?id=' + e.target.dataset.info.id + '&mid=' + mid;
        let _title = e.target.dataset.title;
        if(e.target.dataset.store){
          _path = '/packageB/member/group/GroupDetail/GroupDetail?id=' + e.target.dataset.info.id +'store='+ e.target.dataset.store + '&mid=' + mid;
        }
        if(app.globalData.store_alone_temp == 1 && that.globalData.STORE_ID){
          _path = `${_path}&store_alone_id=${app.globalData.STORE_ID}`;
        }
        return{
          path:_path,
          title:_title
        };
      }
    }
    if(this.data.store_id){
      // 门店装修
      return {
        title: this.data.page_name ? this.data.page_name : "",
        path: `/packageG/newDiy/newDiy?page_id=${this.data.page_id}&mid=${mid}&store_id=${this.data.store_id}`,
      };
    }
    return {
      title: this.data.page_name ? this.data.page_name : "",
      path: `/packageG/newDiy/newDiy?page_id=${this.data.page_id}&mid=${mid}`,
    };
  },
  getShare(id){
    let urlStr = app.getNetAddresss("plugin.lucky-draw.frontend.draw.getShare");
    app._getNetWork({
      url: urlStr,
      data: {
        lotteryId: id
      },
      success: resdata => {
        // var res = resdata.data;
        this.getNewDesinger();
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
});
