const util = require('../../utils/util.js');
const app = getApp();
Page({
  data: {
    img: util.config.imgPath,
    pickers:[],
    pickerIndex:0,
    tabsIndex: 0,
    queryData:{
      pageIndex: 1,
      pageSize: 10,
      cities: '永康',
    },
    info:{},
    list:[],
    total: 0,
    loadMore: true
  },
  onLoad: function () {
    // this.getCity();
    this.userInfo()
  },
  bindCityChange(e) {
    this.data.queryData.pageIndex = 1;
    this.data.queryData.cities = this.data.pickers[e.detail.value];
    this.setData({pickerIndex:e.detail.value,queryData: this.data.queryData})
    this.getList(false);
  },
  userInfo(){
    let that = this;
    util.ajax({
      func: "v2/user/info",
      load: false
    }, function (res) {
      if (res.code == 0 && res.data) {
        that.setData({info:res.data})
        that.getList(false);
      }
    });
  },
  setTabbar(e){
    let index = e.currentTarget.dataset.index;
    this.data.queryData.pageIndex = 1;
    this.setData({ tabsIndex :index, queryData: this.data.queryData, list: [] });
    this.getList(true);
  },
  stat() {
    let that = this;
    util.ajax({
      func: 'v2/user/stat',
      load: false
    }, data => {
      if (data.code == 0) {
        that.setData({ stat: data.data });
      }
    });
  },
  getList(load){
    let that = this;
    console.log(that.data.queryData)
    util.ajax({
      func:`v2/${that.data.info.roleType}/articles`,
      data:{...that.data.queryData, days: that.data.tabsIndex == 4 ? 5 : that.data.tabsIndex },
      load: load
    },function(res){
      if (res.code == 0) {
        let loadMore = true, newData = res.data.list || [], oldData = !load ? newData : [...that.data.list, ...newData];
        if (newData.length < that.data.queryData.pageSize && oldData.length > that.data.queryData.pageSize) loadMore = false;
        that.setData({ list: oldData, loadMore ,total: res.data.total});
      } else
        util.showTips(res.reason);
    });
  },
  errorImg(e){
    this.data.list[e.currentTarget.dataset.index].logo = "/images/noimg.png";
    this.setData({list:this.data.list });
  },
  onPullDownRefresh() {
    var self = this;
    wx.showNavigationBarLoading();
    setTimeout(function () {
      self.data.queryData.pageIndex = 1;
      self.setData({ queryData: self.data.queryData });
      self.getList(false);
      wx.hideNavigationBarLoading();
      wx.stopPullDownRefresh();
    }, 1000);
  },
  onReachBottom() {
    var self = this;
    if (self.data.loadMore == false || self.data.total <= self.data.queryData.pageSize) return false;

    setTimeout(function () {
      self.data.queryData.pageIndex = self.data.queryData.pageIndex + 1;
      self.setData({ queryData: self.data.queryData });
      self.getList(true);
    }, 1000);
  },
})