// pages/member/rankingListSecond/rankingListSecond.js
var app = getApp();
var currentTabIndex = "0";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    team_agent: "",
    language: "",
    mailLanguage: "",
    mailTeamDividendTitle: "",
    mailDividend: "",

    level_name: "",
    dividend_ratio: "",
    next_dividend_ratio: "",

    ratioDatas: [],

    activeName: 0,
    first_content: [],
    second_content: [],
    third_content: [],
    four_content: [],
    bonus_active: true,
    leveling_active: true,
    prize_active: true,
    extra_active: true,
    record_index: "",
    record_key: "",
    tab_name: "提成",
    bonus_lable: "",
    leveling_label: "",
    prize_label: "",
    bonus_save: [],
    leveling_save: [],
    prize_save: [],

    peopleCount: 0,
    teamPerformance: {},
    showRed: 0,
    dividend_amount: "", // 佣金名称
    dividend: {},
    flat_prize: {},
    award_gratitude: {},
    extra_award: {},

    // 分页
    loading: false,
    allLoaded: false,
    goload: true,
    isLoadMore: true,
    page: 1,
    total_page: 0,

    dividend_type: "0",
    is_activation_code: "0",
    display1: -1,
    teamDividendLang: {},
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.checkrouter();
    // this.isGratitude()
    this.initMailLanguage();
    this.getData(0); // 初始化数据
    // this.getPeople()
    this.getDividendList("0");
    // this.getTeamPerformance()
    // this.getShowRed()
    this.getTeamDividend();

    this.initPageData();
  },
  checkrouter() {
    try {
      // 推广中心是否开启该功能，没开启跳转到指定路径
      let basic_info = wx.getStorageSync("yz_basic_info");

      if (basic_info.lang.team_dividend) {
        this.setData({
          teamDividendLang: basic_info.lang.team_dividend,
        });
      }
      console.log(this.data.teamDividendLang);
      let stop_info = basic_info.popularize_page.mini.vue_route;
      for (let i = 0; i < stop_info.length; i++) {
        if (stop_info[i] == "teamAgentCenter") {
          console.log(basic_info.popularize_page.mini.mini_url + "跳转的路径");

          wx.showToast({
            title: "未开启推广权限",
            duration: 1000,
            icon: "none",
            success: function () {
              setTimeout(() => {
                wx.redirectTo({
                  url: basic_info.popularize_page.mini.mini_url,
                });
              }, 1000);
            },
          });
          return;
        }
      }
    } catch (e) {
      console.log(e);
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({
      language: language.en,
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    wx.getStorage({
      key: "yz_basic_info",
      success: function (res) {
        console.log(res);
        setTimeout(function () {
          that.setData({
            team_agent:
              res.data.lang.team_dividend &&
              res.data.lang.team_dividend.my_agent
                ? res.data.lang.team_dividend.my_agent
                : "我的客户",
          });
        }, 2000);
      },
    });
  },

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

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

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreDividendList();
    } else {
      wx.showToast({
        title: "没有更多数据",
        icon: "none",
      });
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  // setting Language
  initMailLanguage() {
    let mailLanguage;
    let urlStr = app.getNetAddresss("setting.get-lang-setting");
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        let resData = res.data;
        if (resData.result === 1) {
          mailLanguage = resData.data;
          let mailDividend = app.setMailLanguage(
            "提成",
            mailLanguage.team_dividend.dividend
          );
          let mailTeamDividendTitle = app.setMailLanguage(
            "经销商管理中心",
            mailLanguage.team_dividend.team_agent_centre
          );
          let dividend_amount = app.setMailLanguage(
            "佣金",
            mailLanguage.team_dividend.dividend_amount
          );
          let tab_name = app.setMailLanguage(
            "提成",
            mailLanguage.team_dividend.dividend
          );
          this.setData({
            mailLanguage,
            mailDividend,
            mailTeamDividendTitle,
            dividend_amount,
            tab_name,
          });

          console.log(this.data.mailLanguage, "语言");
          wx.setNavigationBarTitle({
            title: mailTeamDividendTitle ? mailTeamDividendTitle : "",
          });
          // this.isGratitude()
          this.initInfo(); // 初始化info数据
        } else {
          wx.showToast({
            title: resData.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getTeamDividend() {
    let urlStr = app.getNetAddresss(
      "plugin.team-dividend.api.team-dividend.getTeamDividend"
    );
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        let resData = res.data;
        if (resData.result === 1) {
          this.setData({
            dividend: resData.data.dividend,
            flat_prize: resData.data.flat_prize,
            award_gratitude: resData.data.award_gratitude,
            extra_award: resData.data.extra_award,
          });
        } else {
          wx.showToast({
            title: resData.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getPeople(data) {
    this.setData({
      peopleCount: data,
    });
    // let urlStr = app.getNetAddresss('plugin.team-dividend.api.team.getTeamChildCount')
    // app._getNetWork({
    // 	url: urlStr,
    // 	success: (res) => {
    // 		let resData = res.data;
    // 		if (resData.result === 1) {
    // 			this.setData({
    // 				peopleCount: resData.data.child_count
    // 			})
    // 		} else {
    // 			wx.showToast({
    // 				title: resData.msg,
    // 				icon: 'none'
    // 			})
    // 		}
    // 	},
    // 	fail: function(res) {
    // 		console.log(res)
    // 	}
    // })
  },
  getShowRed(data) {
    this.setData({
      showRed: data,
    });
    // let urlStr = app.getNetAddresss('plugin.team-dividend.api.red-pack.enable')
    // app._getNetWork({
    // 	url: urlStr,
    // 	success: (res) => {
    // 		let resData = res.data;
    // 		if (resData.result === 1) {
    // 			this.setData({
    // 				showRed: resData.data.redpack_enable
    // 			})
    // 		} else {
    // 			wx.showToast({
    // 				title: resData.msg,
    // 				icon: 'none'
    // 			})
    // 		}
    // 	},
    // 	fail: function(res) {
    // 		console.log(res)
    // 	}
    // })
  },
  getTeamPerformance(data) {
    this.setData({
      teamPerformance: data,
    });
    // let urlStr = app.getNetAddresss('plugin.team-dividend.api.results.index')
    // app._getNetWork({
    // 	url: urlStr,
    // 	success: (res) => {
    // 		let resData = res.data;
    // 		if (resData.result === 1) {
    // 			this.setData({
    // 				teamPerformance: resData.data
    // 			})
    // 		} else {
    // 			wx.showToast({
    // 				title: resData.msg,
    // 				icon: 'none'
    // 			})
    // 		}
    // 	},
    // 	fail: function(res) {
    // 		console.log(res)
    // 	}
    // })
  },

  // 是否出现感恩奖
  isGratitude(data) {
    // let urlStr = app.getNetAddresss('plugin.team-dividend.api.team-dividend.get-dividend-type')
    // app._postNetWork({
    // 	url: urlStr,
    // 	success: (response) => {
    // 		let resData = response.data;
    // 		if (resData.result === 1) {
    let bonus_lable = app.setMailLanguage(
      "提成",
      this.data.mailLanguage.team_dividend.dividend
    );
    let leveling_label = app.setMailLanguage(
      "平级奖",
      this.data.mailLanguage.team_dividend.flat_prize
    );
    let prize_label = app.setMailLanguage(
      "感恩奖",
      this.data.mailLanguage.team_dividend.award_gratitude
    );
    let extra_label = "额外分红";
    this.setData({
      bonus_lable,
      leveling_label,
      prize_label,
      extra_label,
      record_index: data.is_flat_prize || null,
      record_key: data.is_award_gratitude || null,
    });

    if (
      data.is_flat_prize == 1 &&
      data.is_award_gratitude == 1 &&
      data.is_extra_award == 1
    ) {
      this.setData({
        leveling_active: true,
        prize_active: true,
        extra_active: true,
      });
    } else if (
      data.is_flat_prize == 1 &&
      data.is_award_gratitude == 1 &&
      data.is_extra_award == 0
    ) {
      this.setData({
        leveling_active: true,
        prize_active: true,
        extra_active: false,
      });
    } else if (
      data.is_flat_prize == 0 &&
      data.is_award_gratitude == 1 &&
      data.is_extra_award == 1
    ) {
      this.setData({
        leveling_active: false,
        prize_active: true,
        extra_active: true,
      });
    } else if (
      data.is_flat_prize == 0 &&
      data.is_award_gratitude == 1 &&
      data.is_extra_award == 0
    ) {
      this.setData({
        leveling_active: false,
        prize_active: true,
        extra_active: false,
      });
    } else if (
      data.is_flat_prize == 1 &&
      data.is_award_gratitude == 0 &&
      data.is_extra_award == 0
    ) {
      this.setData({
        leveling_active: true,
        prize_active: false,
        extra_active: false,
      });
    } else if (
      data.is_flat_prize == 1 &&
      data.is_award_gratitude == 0 &&
      data.is_extra_award == 1
    ) {
      this.setData({
        leveling_active: true,
        prize_active: false,
        extra_active: true,
      });
    } else if (
      data.is_flat_prize == 0 &&
      data.is_award_gratitude == 0 &&
      data.is_extra_award == 1
    ) {
      this.setData({
        leveling_active: false,
        prize_active: false,
        extra_active: true,
      });
    } else if (
      data.is_flat_prize == 0 &&
      data.is_award_gratitude == 0 &&
      data.is_extra_award == 0
    ) {
      this.setData({
        leveling_active: false,
        prize_active: false,
        extra_active: false,
      });
    }
    // 		} else {
    // 			wx.showToast({
    // 				title: resData.msg,
    // 				icon: 'none'
    // 			})
    // 		}
    // 	},
    // 	fail: function(res) {
    // 		console.log(res)
    // 	}
    // })
  },

  // 初始化info数据
  initInfo() {
    let urlStr = app.getNetAddresss("plugin.team-dividend.api.index");
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        let resData = res.data;
        if (resData.result === 1) {
          if (resData.data.is_not_agent) {
            wx.showToast({
              title: "你不是经销商！",
              icon: "none",
            });
          }
          this.setData({
            is_activation_code: resData.data.is_activation_code,
            level_name: resData.data.level_name,
            dividend_ratio: resData.data.dividend_ratio,
            next_dividend_ratio: resData.data.next_dividend_ratio,
            is_customer: resData.data.is_customer,
            is_team_data: resData.data.is_team_data,
          });
          this.getPeople(resData.data.child_count);
          this.getShowRed(resData.data.redpack_enable);
          this.getTeamPerformance({
            team_goods_total: resData.data.team_goods_total,
            team_order_price: resData.data.team_order_price,
          });
          this.isGratitude({
            is_award_gratitude: resData.data.is_award_gratitude,
            is_extra_award: resData.data.is_extra_award,
            is_flat_prize: resData.data.is_flat_prize,
          });
        } else {
          wx.showToast({
            title: resData.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  // 初始化数据
  getData(value) {
    let urlStr = app.getNetAddresss(
      "plugin.team-dividend.api.team-dividend.get-dividend-statistic"
    );
    urlStr += "&dividend_type=" + value;
    app._getNetWork({
      url: urlStr,
      success: (response) => {
        let resData = response.data;
        if (resData.result === 1) {
          // 组装数据
          let arr = [];
          let itemDay = {};
          itemDay.money = resData.data.today;
          itemDay.data = "今日";
          itemDay.name = "data";
          arr.push(itemDay);

          let itemYesterday = {};
          itemYesterday.money = resData.data.yesterday;
          itemYesterday.data = "昨日";
          itemYesterday.name = "data";
          arr.push(itemYesterday);

          let itemWeek = {};
          itemWeek.money = resData.data.this_week;
          itemWeek.data = "本周";
          itemWeek.name = "data";
          arr.push(itemWeek);

          let itemMonth = {};
          itemMonth.money = resData.data.this_month;
          itemMonth.data = "本月累计" + this.data.tab_name;
          itemMonth.name = "mounth";
          arr.push(itemMonth);
          this.setData({
            ratioDatas: arr,
          });
          if (value == 0) {
            this.setData({
              bonus_save: arr,
            });
          } else if (value == 1) {
            this.setData({
              leveling_save: arr,
            });
          } else if (value == 2) {
            this.setData({
              prize_save: arr,
              ['award_gratitude.unliquidated']:resData.data.unliquidated,
              ['award_gratitude.liquidated']:resData.data.liquidated
            });
            console.log(this.data.award_gratitude,this.data.activeName);
          }
        } else {
          wx.showToast({
            title: resData.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  openDetail(e) {
    console.log(e.currentTarget.dataset.ind2);
    console.log(this.data.display1);
    if (e.currentTarget.dataset.ind2 == this.data.display1) {
      this.setData({
        display1: "-1",
      });
      return;
    }
    this.setData({
      display1: e.currentTarget.dataset.ind2,
    });
  },
  // setting sun

  // 获取佣金列表
  getDividendList(value) {
    let urlStr = app.getNetAddresss(
      "plugin.team-dividend.api.team-dividend.get-dividend-list"
    );
    urlStr += "&dividend_type=" + value + "&page=" + this.data.page;
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        let resData = res.data;
        if (resData.result === 1) {
          switch (this.data.dividend_type) {
          case "0":
            if (this.data.first_content.length <= 0) {
              this.setData({
                ["first_content[" +
                  this.data.first_content.length +
                  "]"]: resData.data.data,
              });
            }
            break;
          case "1":
            if (this.data.second_content.length <= 0) {
              this.setData({
                ["second_content[" +
                  this.data.second_content.length +
                  "]"]: resData.data.data,
              });
            }
            break;
          case "2":
            if (this.data.third_content.length <= 0) {
              this.setData({
                ["third_content[" +
                  this.data.third_content.length +
                  "]"]: resData.data.data,
              });
            }
            break;
          case "3":
            if (this.data.four_content.length <= 0) {
              this.setData({
                ["four_content[" +
                  this.data.four_content.length +
                  "]"]: resData.data.data,
              });
            }
            break;
          default:
            break;
          }
          this.setData({
            total_page: resData.data.lastpage,
            is_team_buyer: parseInt(resData.data.is_team_buyer),
            is_team_order_details: parseInt(resData.data.is_team_order_details),
          });
        } else {
          wx.showToast({
            title: resData.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  getMoreDividendList() {
    // let that = this;
    if (this.data.page == this.data.total_page) {
      wx.showToast({
        title: "没有更多",
        icon: "none",
        duration: 1000,
      });
      return;
    }

    if (this.data.page >= this.data.total_page) {
      this.setData({
        loading: true,
        allLoaded: true,
      });
      wx.showToast({
        title: "没有更多",
        icon: "none",
        duration: 1000,
      });
      return;
    } else {
      let page = this.data.page + 1;
      this.setData({
        page,
      });
      let urlStr = app.getNetAddresss(
        "plugin.team-dividend.api.team-dividend.get-dividend-list"
      );
      urlStr +=
        "&dividend_type=" + this.data.dividend_type + "&page=" + this.data.page;
      app._getNetWork({
        url: urlStr,
        success: (res) => {
          let resData = res.data;
          if (resData.result === 1) {
            this.setData({
              loading: false,
              allLoaded: false,
            });
            switch (this.data.dividend_type) {
            case "0":
              // let listOne = that.data.first_content.concat(resData.data.data)
              this.setData({
                ["first_content[" +
                  this.data.first_content.length +
                  "]"]: resData.data.data,
              });
              break;
            case "1":
              // let listTwo = that.data.second_content.concat(resData.data.data)
              this.setData({
                ["second_content[" +
                  this.data.second_content.length +
                  "]"]: resData.data.data,
              });
              break;
            case "2":
              // let listThree = that.data.third_content.concat(resData.data.data)
              this.setData({
                ["third_content[" +
                  this.data.third_content.length +
                  "]"]: resData.data.data,
              });
              break;
            default:
              break;
            case "3":
              this.setData({
                ["four_content[" +
                  this.data.four_content.length +
                  "]"]: resData.data.data,
              });
              break;
            }
            this.setData({
              total_page: resData.data.lastpage,
            });
          } else {
            let pagesO = this.data.page - 1;
            this.setData({
              page: pagesO,
              loading: true,
              allLoaded: true,
              isLoadMore: false,
            });
            return;
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  // setting sun
  // 直推奖
  getDividendListByType2() {
    let urlStr = app.getNetAddresss(
      "plugin.team-dividend.api.team-dividend.get-reward"
    );
    app._getNetWork({
      url: urlStr,
      success: (res) => {
        let resData = res.data;
        if (resData.result === 1) {
          this.setData({
            third_content: resData.data,
          });
        } else {
          wx.showToast({
            title: resData.msg,
            icon: "none",
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },

  // setting sun
  // 设置选择后的数据
  setDataByTabIndex(currtitle) {
    // setting sun
    // if (this.data.record_index == 0 && this.data.record_key == 1) {
    // 	if (currentTabIndex == 1) {
    // 		currentTabIndex = 2
    // 	}
    // }

    this.initPageData();
    console.log(currtitle, "currtitle");
    // 这里是根据导航名称来判断的  有些会不显示所以每个地方都要判断
    if (currentTabIndex == "0") {
      if (currtitle == "额外分红") {
        this.getDividendList("3");
        let tab_name = "额外分红";
        this.setData({
          dividend_type: "3",
          tab_name,
        });
        this.getData("3");
        return;
      }

      this.getDividendList("0");
      let tab_name = app.setMailLanguage(
        "提成",
        this.data.mailLanguage.team_dividend.dividend
      );
      this.setData({
        dividend_type: "0",
        tab_name,
      });
      this.getData("0");
    } else if (currentTabIndex == "1") {
      if (currtitle == "额外分红") {
        this.getDividendList("3");
        let tab_name = "额外分红";
        this.setData({
          dividend_type: "3",
          tab_name,
        });
        this.getData("3");
        return;
      }
      if (currtitle == "感恩奖") {
        this.getDividendList("2");
        let tab_name = "感恩奖";
        this.setData({
          dividend_type: "2",
          tab_name,
        });
        this.getData("2");
        return;
      }
      this.getDividendList("1");

      let tab_name = app.setMailLanguage(
        "平级奖",
        this.data.mailLanguage.team_dividend.flat_prize
      );
      this.setData({
        dividend_type: "1",
        tab_name,
      });
      this.getData("1");
    } else if (currentTabIndex == "2") {
      if (currtitle == "额外分红") {
        this.getDividendList("3");
        let tab_name = "额外分红";
        this.setData({
          dividend_type: "3",
          tab_name,
        });
        this.getData("3");
        return;
      }

      this.getDividendList("2");
      let tab_name = app.setMailLanguage(
        "感恩奖",
        this.data.mailLanguage.team_dividend.award_gratitude
      );
      this.setData({
        dividend_type: "2",
        tab_name,
      });
      this.getData("2");
    }else if(currentTabIndex == "3"){
      console.log('curr');
      if (currtitle == "额外奖励" || currtitle == this.data.teamDividendLang.extra_award) {
        let name = this.data.teamDividendLang.extra_award?this.data.teamDividendLang.extra_award:'额外奖励';
        this.getDividendList("3");
        let tab_name = name;
        this.setData({
          dividend_type: "3",
          tab_name,
        });
        this.getData("3");
        return;
      }
    }
  },
  initPageData() {
    this.setData({
      loading: false,
      allLoaded: false,
      goload: true,
      isLoadMore: true,
      page: 1,
      total_page: 0,
    });
  },
  // setting sun
  // tab 点击
  handleClick(tab) {
    console.log(tab);
    this.setData({
      activeName: currentTabIndex,
      page: 1,
    });

    if (currentTabIndex == tab.detail.index) {
      return;
    } else {
      currentTabIndex = tab.detail.index;
    }
    if(tab.detail.name == '3'){
      // 感恩奖name是2
      currentTabIndex = 2;
    }
    if(tab.detail.name == '4'){
      // 感恩奖name是2
      currentTabIndex = 3;
    }
    this.setData({
      activeName: currentTabIndex,
    });
    console.log(currentTabIndex, "currentTabIndex");
    let currtitle = tab.detail.title;
    this.setDataByTabIndex(currtitle);
  },
  // 跳转到激活码
  teamCode() {
    wx.navigateTo({
      url: "/packageB/member/income/teamCode/teamCode",
    });
  },
  // 跳转到我的客户
  TeamClient() {
    wx.navigateTo({
      url: "/packageB/member/income/TeamClient/TeamClient",
    });
  },
  // 跳转到红包奖励
  FranchiserRed() {
    wx.navigateTo({
      url: "/packageB/member/income/FranchiserRed/FranchiserRed",
    });
  },
  // 跳转到团队业绩
  teamPerformance() {
    wx.navigateTo({
      url: "/packageB/member/income/teamPerformance/teamPerformance",
    });
  },
});
