import {
  ilogin,
  ihome,
  iactivity,
  icommunity,
  imine
} from '../../api/api.js'
const app = getApp()

Page({
  loadMyinformation() {
    imine.loadMyinformation({reqdata: {id:1}},r => {
      this.setData({
        user: Object.assign(this.data.user, r.object)
      })
      wx.setStorage({
        key: 'user',
        data: this.data.user
      })
    })
  },
  loadMyActivities() {
    imine.loadMyActivities(this.data.mine.pagination, r => {
      this.setData({
        ['mine.curNav']: 3,
        ['mine.list']: this.data.mine.list.concat(r.list),
        ['mine.pagination.page']: r.list.length > 0 ? this.data.mine.pagination.page : --this.data.mine.pagination.page
      })
    })
  },
  loadMyComments() {
    imine.loadMyComments(this.data.mine.pagination, r => {
      for (let c of r.list) {
        c.showtime = new Date(c.comment_addtime).getDateName('hh:mm')
      }
      this.setData({
        ['mine.curNav']: 2,
        ['mine.list']: this.data.mine.list.concat(r.list),
        ['mine.pagination.page']: r.list.length > 0 ? this.data.mine.pagination.page : --this.data.mine.pagination.page
      })
    })
  },
  loadMyPubarticles() {
    imine.loadMyPubarticles(this.data.mine.pagination, r => {
      this.setData({
        ['mine.curNav']: 0,
        ['mine.list']: this.data.mine.list.concat(r.list),
        ['mine.pagination.page']: r.list.length > 0 ? this.data.mine.pagination.page : --this.data.mine.pagination.page
      })
    })
  },
  loadMyCollectedarticles() {
    imine.loadMyCollectedarticles(this.data.mine.pagination, r => {
      this.setData({
        ['mine.curNav']: 1,
        ['mine.list']: this.data.mine.list.concat(r.list).map(item => {
          item.status_attend = Date.now() < new Date(item.applyStartTime).valueOf() ? '未开始' : Date.now() > new Date(item.applyEndTime).valueOf() ? '已结束' :''
          return item
        }),
        ['mine.pagination.page']: r.list.length > 0 ? this.data.mine.pagination.page : --this.data.mine.pagination.page
      })
    })
  },
  data: {
    showAuthPanel: false,
    curNav: 0,
    imgUrl: app.globalData.imgUrl,
    navs: [{
      key: 'home',
      name: '首页'
    }, {
      key: 'activity',
      name: '活动动态'
    }, {
      key: 'community',
      name: '社区'
    }, {
      key: 'mine',
      name: '个人中心'
    }],
    searchOn: false,
    home: {},
    activity: {
      list: [],
      pagination: {
        page: 1,
        rows: 10,
        reqdata: {
          keyword: ''
        }
      }
    },
    community: {
      showAddtidings: false,
      acts: [{
        favorite: true
      }],
      list: [],
      pagination: {
        page: 1,
        rows: 10,
        reqdata: {
          keyword: ''
        }
      }
    },
    mine: {
      list: [],
      curNav: 0,
      pagination: {
        page: 1,
        rows: 10
      }
    }
  },
  loadArticles() {
    icommunity.loadArticles(this.data.community.pagination, r => {
      this.setData({
        ['community.list']: this.data.community.list.concat(r.list),
        ['community.pagination.page']: r.list.length > 0 ? this.data.community.pagination.page : --this.data.community.pagination.page
      })
      wx.stopPullDownRefresh()
    })
  },
  loadActivities() {
    iactivity.loadActivities(this.data.activity.pagination, r => {
      this.setData({
        ['activity.list']: this.data.activity.list.concat(r.list),
        ['activity.pagination.page']: r.list.length > 0 ? this.data.activity.pagination.page : --this.data.activity.pagination.page,
      })
      wx.stopPullDownRefresh()
    })
  },
  loadHome() {
    let count = 3
    ihome.loadBanners({},r => {
      console.log(r);
      this.setData({
        ['home.banners']: r.list
      })
      if (count == 1) {
        wx.stopPullDownRefresh()
      } else {
        count--
      }
    })
    ihome.loadPartners({},r => {
      this.setData({
        ['home.partners']: r.list
      })
      if (count == 1) {
        wx.stopPullDownRefresh()
      } else {
        count--
      }
    })
    ihome.loadHotnews({},r => {
      this.setData({
        ['home.hotnews']: r.list
      })
      if (count == 1) {
        wx.stopPullDownRefresh()
      } else {
        count--
      }
    })
  },
  onLoad(args) {
    this.loadHome()
    // this.loadConfig()
  },
  clickRemoveArticle(e) {
    console.log(e)
    wx.showModal({
      title: '确定删除？',
      content: '是否删除此动态？',
      confirmColor: '#f64f5f',
      success: r => {
        let {id,minenav,i} = e.currentTarget.dataset
        if (r.confirm) {
          icommunity[minenav==0?'loadDeleteArticle':'loadDeleteCollect']({
            reqdata:{id}
          }, r => {
            wx.showToast({
              title: '删除成功'
            })
            this.data.mine.list.splice(i, 1)
            this.setData({
              mine: this.data.mine
            })
          })
        }
      }
    })
  },
  clickFavorite(e) {
    let {id,isCollect} = e.currentTarget.dataset
    let scope = this.data.curNav == 2 ? 'community' : 'mine'
    let item = this.data[scope].list[e.currentTarget.dataset.i]
    icommunity[isCollect?'loadDeleteCollect':'loadAddArticle']({
      reqdata:{
        [isCollect?'id':'collectProjectId']:id,
        ['collectType']: isCollect?null:1
      }
    }, r => {
      item.isCollect = !item.isCollect
      item.collectNumber =item.isCollect? parseInt(item.collectNumber) + 1:  parseInt(item.collectNumber) - 1
      this.setData({
        [scope + '.list[' + e.currentTarget.dataset.i + ']']: item
      })
    })
  },
  clickActivity(e) {
    app.data.nav.activityDetails = this.data.activity.list[e.currentTarget.dataset.i]
    wx.navigateTo({
      url: '../activities/activityDetails/activityDetails?id=' + e.currentTarget.dataset.id
    })
  },
  clickArticle(e) {
    console.log(e)
    app.data.nav.newsDetails = this.data.home.hotnews[e.currentTarget.dataset.i]
    wx.navigateTo({
      url: '../hotnews/newsDetails/newsDetails?id=' + e.currentTarget.dataset.id
    })
  },
  clickHotnewsMore() {
    wx.navigateTo({
      url: '../hotnews/hotnews/hotnews'
    })
  },
  clickMyinfo() {
    wx.navigateTo({
      url: '../mine/myinfo/edit/edit'
    })
  },
  clickCommunityArticle(e) {
    app.data.nav.communityArticle = e.currentTarget.dataset.item 
    wx.navigateTo({
      url: e.currentTarget.dataset.item.fileType  == 2 ? '../community/videoDetails/videoDetails' : '../community/articleDetails/articleDetails'
    })
  },
  clickUploadpics() {
    wx.navigateTo({
      url: '../community/uploadPics/uploadPics'
    })
    this.setData({
      ['community.showAddtidings']: false
    })
  },
  clickUploadvideos() {
    wx.navigateTo({
      url: '../community/uploadVideos/uploadVideos'
    })
    this.setData({
      ['community.showAddtidings']: false
    })
  },
  clickClosetidings() {
    this.setData({
      ['community.showAddtidings']: false
    })
  },
  clickAddtidings() {
    if (!this.data.user) {
      return this.setData({
        showAuthPanel: true
      })
    }
    this.setData({
      ['community.showAddtidings']: true
    })
  },
  inputSearch(e) {
    if (this.data.curNav == 1) {
      this.setData({
        ['activity.pagination.reqdata.keyword']: e.detail.value,
        ['activity.pagination.page']: 1,
        ['activity.list']: [],
      })
      this.loadActivities()
    } else {
      this.setData({
        ['community.pagination.reqdata.keyword']: e.detail.value,
        ['community.pagination.page']: 1,
        ['community.list']: []
      })
      this.loadArticles()
    }
  },
  clickSearch() {
    this.setData({
      searchOn: true
    })
  },
  blurSearch(e) {
    if (!e.detail.value) {
      this.setData({
        searchOn: false
      })
    }
  },
  clickMinenav(e) {
    this.data.mine.pagination.page = 1
    this.data.mine.list = []
    switch (e.currentTarget.dataset.cur) {
      case '1':
        {
          this.loadMyCollectedarticles()
        };
        break;
      case '2':
        {
          this.loadMyComments()
        };
        break;
      case '3':
        {
          this.loadMyActivities()
        };
        break;
      default:
        {
          this.loadMyPubarticles()
        }
    }
  },
  clickNav(e) {
    switch (e.currentTarget.dataset.cur) {
      case '1':
        this.data.activity.pagination.page = 1
        this.data.activity.list = []
        this.loadActivities()
        break;
      case '2':
        this.data.community.pagination.page = 1
        this.data.community.list = []
        this.loadArticles()
        break;
      case '3':
        if (!this.data.user || this.data.user.is_finish_reg == 0) {
          return this.setData({
            showAuthPanel: true
          })
        }
        this.data.mine.pagination.page = 1
        this.data.mine.list = []
        this.loadMyinformation()
        // if (this.data.config.open_space == 1) {
        //   this.loadMyPubarticles()
        // } else {
          // this.loadMyCollectedarticles()
        // }
        // this.loadMyCollectedarticles()
        this.setData({
          ['mine.curNav']: 0
        },()=>{
          this.loadMyPubarticles()
        })
        break;
    }
    this.setData({
      curNav: e.currentTarget.dataset.cur
    })
    wx.setNavigationBarTitle({
      title: this.data.navs[e.currentTarget.dataset.cur].name
    })
  },
  clickHideAuthPanel() {
    this.setData({
      showAuthPanel: false
    })
  },
  // getUserinfo(e) {
  //   let {encryptedData,iv} = e.detail
  //   console.log(e);
  //   wx.login({
  //     success: r => {
  //       ilogin.loadAT({
  //         reqdata: {
  //           code: r.code,
  //           encryptedData,
  //           iv
  //         }
  //       }, r => {
  //         console.log(r)
  //       })
  //     }
  //   })
  // },
  getUserInfo (e) {
    wx.login({
      success: r => {
        wx.getUserInfo({
          success: e => {
            let {encryptedData,iv} = e
            ilogin.loadAT({
              reqdata: {
                code: r.code,
                encryptedData,
                iv
              }
            }, r => {
              console.log(r)
              // console.log(e);
              
            })
          },
        })
        // ilogin.loadAT({
        //   reqdata: {
        //     code: r.code,
        //     encryptedData,
        //     iv
        //   }
        // }, r => {
        //   console.log(r)
        // })
      }
    })
  },
  onShow() {
    wx.getStorage({
      key: 'user',
      complete: r => {
        if (r.data) {
          this.setData({
            user: r.data
          })
        }
      }
    })
  },
  onPullDownRefresh() {
    switch (this.data.curNav) {
      case 1:
      case '1':
        this.data.activity.pagination.page = 1
        this.data.activity.list = []
        this.loadActivities()
        break;
      case 2:
      case '2':
        this.data.community.pagination.page = 1
        this.data.community.list = []
        this.loadArticles()
        break;
      case 3:
      case '3':
        wx.stopPullDownRefresh()
        break;
      default:
        this.loadHome()
    }

  },
  onReachBottom() {
    if (this.data.curNav == 1) {
      this.data.activity.pagination.page += 1
      this.loadActivities()
    }
    if (this.data.curNav == 2) {
      this.data.community.pagination.page += 1
      this.loadArticles()
    }
    if (this.data.curNav == 3) {
      this.data.mine.pagination.page += 1
      switch (this.data.mine.curNav) {
        case 1:
        case '1':
          this.loadMyCollectedarticles();
          break;
        case 2:
        case '2':
          this.loadMyComments()
          break;
        case 3:
        case '3':
          this.loadMyActivities()
          break;
        default:
          this.loadMyPubarticles()
      }
    }
  },
  loadConfig() {
    ilogin.loadConfig({},r => {
      app.config = r
      this.setData({
        config: r
      })
    })
  },
  onShareAppMessage() {
    return {
      title: '冰雪小程序',
      path: '/pages/home/home',
      imageUrl: '../../imgs/share2.jpg',
      success: function(res) {},
      fail: function(res) {
        console.log(res, '失败')　　　　
      }
    }
  }
})