//index.js
//获取应用实例
// 获取授权登录
import {
  getOpenidSessionKey
} from '../../utils/httpUtil';
// 不用获取授权登录
import {
  getOpenidNoLogin
} from '../../utils/httpUtilNoLogin';
import {
  formatDate
} from '../../utils/util';

const app = getApp()

import {
  hotInit
} from '../../component/hot/hot';
import {
  groupInit
} from '../../component/group/group';
import {
  myInit
} from '../../component/my/my';
import httpRequestApi from '../../utils/APIClient';
import httputil from '../../utils/httpUtil';
import {
  GetQueryString
} from '../../utils/util';

Page({
  data: {
    tab: [{
        name: '推荐',
        templates: 'recommend',
      },
      {
        name: '关注',
        templates: 'follow',
      },
      {
        name: '资源',
        templates: 'courses',
      },
      {
        name: '我的',
        templates: 'my',
      }
    ],
    winH: 568,
    myIndex: 0,
    followData: [],
    recommendPageNo: 0,
    recommendTotalNo: 1,
    followPageNo: 1,
    followPageTotalNo: 1,
    myData: {},
    templates: '',
    title: 'index中的title',
    jurisdictionFlag: true,
    hotInput: '12345',
    mineSettingInfo: '528',
    hide: true,
    isIOS: app.globalData.isIOS,
    ifHaveMore: true,
    indexSignDialog: false,
    indexMissionDialog: false,
    unfinishedCount: 0,
    videoList: [],
    nextMargin: '400rpx', // 视频下边距
    commentShow: false,
    commentList: [],
    commentNum: 0,
    followPageNo: 1,
    followPageSize: 6,
    coursesData: []
  },
  jurisdiction: function () {
    //隐藏弹框
    this.setData({
      hide: !this.data.hide
    })
    //登录页信息
    this.updateData(0)
  },
  //tab点击
  switcher: function ({
    currentTarget
  }) {
    if (currentTarget.dataset.index === this.data.myIndex) return;
    this.updateData(currentTarget.dataset.index);
  },
  // 根据index 更新template
  updateData: function (index) {
    let myIndex = index;
    this.setData({
      myIndex,
    });
    // 获取推荐列表
    if (myIndex == 0) {
      this.setData({
        videoList: [],
        isSwiper: true
      }, () => {
        this.getHotRecommend(this.uid);
      })
      return;
    }

    /* 关注和我的需要登陆后查看 */

    if (!this.data.isLogin) {
      wx.navigateTo({
        url: `../../pages/login/login`
      });
      return;
    }

    console.log('继续')
    // 刷新关注列表
    if (myIndex == 1) {
      this.setData({
        videoList: [],
        isSwiper: true
      }, () => {
        this.getFollowData()
      })
      return;
    }
    // 刷新资源
    if (myIndex == 2) {
      this.setData({
        videoList: [],
        templates: 'courses'
      }, () => {
        this.getCoursesList();
      })
      return;
    }
    // 刷新我的
    if (myIndex == 3) {
      this.setData({
        videoList: [],
        templates: 'my',
        isSwiper: false
      }, () => {
        myInit(this);
      })
      return;
    }


  },
  showPage: function () {
    let options = this.data.options;
    if (options && options.index) {
      this.updateData(options.index)
    } else {
      this.updateData(0)
    }
    setTimeout(() => {
      if (wx.getStorageSync('uid')) {
        httpRequestApi.userLoginRecord().success(res => {
          if (res.data.data && res.data.data.length !== 0) {
            // 有数据弹签到
            if (this.data.unfinishedCount > 0) {
              this.setData({
                indexSignDialog: true
              })
            }

          } else {
            // 没数据弹任务
            let oldDay = wx.getStorageSync('oldDay');
            let newDate = new Date();
            let day = newDate.getDate() < 10 ? '0' + newDate.getDate() : newDate.getDate()
            let timeStep = (newDate.getMonth() + 1).toString() + day
            if (oldDay) {
              let temp = parseInt(timeStep) - parseInt(oldDay)
              if (temp > 0) {
                wx.setStorageSync('oldDay', timeStep);
                this.setData({
                  indexMissionDialog: true
                })
              }
            } else {
              wx.setStorageSync('oldDay', timeStep);
              this.setData({
                indexMissionDialog: true
              })
            }
          }
        })
      }
    }, 2800)
  },
  onLoad: function (options) {
    this.uid = wx.getStorageSync('uid');
    let grade = wx.getStorageSync('grade');

    let user = wx.getStorageSync('user');
    if (!this.uid || !grade) {
      this.setData({
        isGradeShow: true,
        options
      })
      console.log('没有uid 也不是游客,需要去授权')
      return;
    }
    this.showPage()
    if (this.uid && !user) {
      console.log('游客状态')
    }
    if (this.uid && user) {
      console.log('登陆状态')
    }
    wx.getSystemInfo({
      success: (res) => {
        console.log('系统', res)

        let winH = res.windowHeight * res.pixelRatio;
        let minusNumber = (winH * 920) / 1206;
        let nextMargin = parseInt(winH - minusNumber);
        app.globalData.nextMargin = nextMargin;

        this.setData({
          winH: winH,
          devicePixelRatio: res.pixelRatio,
          nextMargin: nextMargin + 'rpx'

        });

      }
    });

  },
  onShow: function () {
    wx.setNavigationBarTitle({
      title: '小学语文朗读配音'
    })
    const userInfo = wx.getStorageSync('user')
    if (userInfo.wechatName) {
      this.setData({
        isLogin: true
      })
    } else {
      this.setData({
        isLogin: false
      })
    }
  },

  onHide: function () {
    const str = 'hotData.inputFocus'
    this.setData({
      [str]: false
    });
  },
  /* 两个接口维护同一个数组,手动的结束后添加算法的 */
  // 推荐页信息 获取消息和手动推荐内容
  getHotRecommend: function (uid) {
    httpRequestApi.getHotRecommend(
      uid
    ).success((res) => {
      // 点击切换按钮时 只刷新我的课程和未读消息 官方推荐和热门不加载
      /*      const recommendRes = res.data.data;
           console.log(res)
           recommendRes.hotReader.forEach(item => {
             const temp = {};
             temp.title = item.userRead ? item.userRead.title : '';
             temp.img = item.userRead.iconImg;
             temp.plays = item.userRead.playAmount ? item.userRead.playAmount : 0;
             temp.likes = item.userRead.likeAmount ? item.userRead.likeAmount : 0;
             temp.commentAmount = item.userRead.commentAmount ? item.userRead.commentAmount : 0;
             temp.classId = item.userRead.lessonId;
             temp.time = formatDate(item.userRead.gmtCreated, 3);
             temp.avatar = item.user ? item.user.avatar : '';
             temp.uid = item.user ? item.user.uid : '';
             temp.url = item.userRead.originVideo;
             temp.type = item.userRead.type;
             // temp.avatar = item.user.avatar;
             temp.nickName = item.user ? item.user.wechatName : '';
             temp.id = item.userRead.id;
             temp.isLike = item.isLike;
             temp.isFavorite = item.isFavorites;
             this.data.videoList.push(temp);
           });
           this.setData({
             videoList: this.data.videoList
           }) */
      this.getHotRecommendSecond(1, 5)
    })
  },
  // 获取热门作品 算法出来的
  getHotRecommendSecond: function (pageNo, pageSize) {
    let grade = wx.getStorageSync('grade')
    httpRequestApi.getHotRecommendSecond(grade, pageNo, pageSize).success(res => {
      console.log(res)
      const recommendRes = res.data.data.list;
      if (recommendRes.length === 0) return;
      // const recommendWorks = [];
      recommendRes.forEach(item => {
        const temp = {};
        temp.title = item.userRead.title;
        temp.summary = item.userRead.summary;
        temp.img = item.userRead.iconImg;
        temp.plays = item.userRead.playAmount ? item.userRead.playAmount : 0;
        temp.likes = item.userRead.likeAmount ? item.userRead.likeAmount : 0;
        temp.commentAmount = item.userRead.commentAmount ? item.userRead.commentAmount : 0;
        temp.classId = item.userRead.exampleId ? item.userRead.exampleId : 1605097720036046;
        temp.time = formatDate(item.userRead.gmtCreated, 3);
        temp.avatar = item.user.avatar;
        temp.profession = item.user.profession;
        temp.uid = item.user.uid;
        temp.url = item.userRead.videoPath ? item.userRead.videoPath : item.userRead.originVideo;
        temp.id = item.userRead.id;
        temp.type = item.userRead.type;
        // temp.avatar = item.user.avatar;
        temp.nickName = item.user.wechatName;
        temp.isLike = item.isLike;
        temp.isFavorite = item.isFavorites;
        // recommendWorks.push(temp);
        this.data.videoList.push(temp);

      });
      this.setData({
        videoList: this.data.videoList
      })
      console.log('dangqian', this.data.videoList)
    })
  },
  // 获取用户信息
  getUserWorksInfo: function (flag) {
    console.log(flag)
    if (flag) {
      httpRequestApi.getUserWorksInfo().success(res => {
        // const str = 'myData.user.user.nickName';
        // const avatarStr = 'myData.user.user.avatar';
        // this.setData({
        //   [str]: res.data.data.user.nickName,
        //   [avatarStr]: res.data.data.user.avatar
        // })
      })
      return;
    }
    const userLocal = wx.getStorageSync('user')
    console.log(userLocal)
    const str = 'myData.user';
    this.setData({
      [str]: userLocal
    })
    httpRequestApi.getUserWorksInfo().success(res => {
      console.log('getUserWorksInfo', res)
      this.data.myData.user = res.data.data;
      httpRequestApi.userIntoPage('pages/index/index', '首页我的').success((res) => {})
      if (this.data.myData.user.myRead) {
        this.data.myData.user.myRead.gmtCreated = formatDate(this.data.myData.user.myRead.gmtCreated, 4)
      }
      this.setData({
        myData: this.data.myData,
        userInfo: res.data.data.user
      }, () => {
        this.getMyRead()
      });
    }).fail(error => {
      console.log(error)
    })
  },
  // 触底加载
  onReachBottom: function () {
    // console.log(this.data.myIndex)
    // if (this.data.myIndex === 0) {
    //   this.setData({
    //     followPageNo: this.data.followPageNo + 1
    //   })
    //   if (this.data.followPageNo <= this.data.followPageTotalNo) {
    //     this.getFollowWorks(this.data.followPageNo, 3);

    //   } else {
    //     console.log('没有更多')
    //     this.setData({
    //       ifHaveMore: false
    //     })
    //   }
    // }
    // // 当前在推荐页面 加载推荐
    // if (this.data.myIndex === 1) {
    //   console.log(this.data.recommendPageNo)
    //   console.log(this.data.recommendTotalNo)
    //   this.setData({
    //     recommendPageNo: this.data.recommendPageNo + 1
    //   })
    //   if (this.data.recommendPageNo <= this.data.recommendTotalNo) {
    //     this.getHotRecommendSecond(this.uid, this.data.recommendPageNo, 3);

    //   } else {
    //     console.log('没有更多')
    //   }
    // }

  },
  onPullDownRefresh: function () {
    //当前在团购页下拉加载
    if (this.data.myIndex === 0) {
      // groupInit(this);
    }

    wx.showNavigationBarLoading() //在标题栏中显示加载
    //模拟加载
    setTimeout(function () {
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 1500);
  },
  goToMessage: function () {
    wx.navigateTo({
      url: `../../pages/social/insideMessage/insideMessage`
    });
    const str = 'hotData.unReadMessageNum';
    this.setData({
      [str]: 0
    })
  },
  toMyCollage: function (e) {
    if (app.globalData.isIOS) {
      wx.navigateTo({
        url: `../../pages/groupPage/my-group/my-group?title=我的助力`
      });
    } else {
      wx.navigateTo({
        url: `../../pages/groupPage/my-group/my-group?title=我的拼团`
      });
    }

  },
  toMyCourse: function () {
    wx.navigateTo({
      url: `../../pages/user/mycourse/mycourse?title=我的课程`
    });
  },
  goToFlower: function () {
    wx.navigateTo({
      url: `../../pages/social/littleFlower/littleFlower`
    });
  },
  signInBtn: function (e) {
    this.setData({
      indexSignDialog: false
    })
    console.log(e.detail.formId)
    httpRequestApi.postFormId(e.detail.formId).success(res => {
      console.log(res)
    })
    this.goToFlower();
  },
  missionBtn: function () {
    this.setData({
      indexMissionDialog: false
    })
    this.goToFlower();
  },
  getUserAuth: function () {
    httpRequestApi.getUserAuth().success(res => {
      console.log(res)
      const str = 'myData.isVIP'
      if (res.data.data) {
        this.setData({
          [str]: true
        })
      } else {
        this.setData({
          [str]: false
        })
      }
    })
  },
  // 获取我的朗读
  getMyRead: function () {
    httpRequestApi.myRead().success(res => {
      console.log(123123, res)
      console.log('mydata', this.data.myData)
      const myList = res.data.data;
      if (myList.length === 0) return;
      // const recommendWorks = [];
      myList.forEach(item => {
        console.log('mydata', this.data.myData)
        console.log('mydata', this.data.userInfo.user)

        const temp = {};
        temp.title = item.title;
        temp.summary = item.summary;
        temp.img = item.iconImg;
        temp.plays = item.playAmount;
        temp.likes = item.likeAmount;
        temp.classId = item.exampleId ? item.exampleId : 1605097720036046;
        temp.time = formatDate(item.gmtCreated, 3);
        temp.avatar = this.data.userInfo.avatar;
        temp.uid = this.uid;
        temp.url = item.videoPath;
        temp.id = item.id;
        // temp.avatar = item.user.avatar;
        temp.nickName = this.data.userInfo.wechatName;
        // recommendWorks.push(temp);
        this.data.videoList.push(temp);
      });
      this.setData({
        videoList: this.data.videoList
      })
    })
  },
  // 评论区点击
  commentTap: function (e) {
    console.log('点击评论区', e)
    if (e.target.dataset.type === 'blank') {
      this.setData({
        commentShow: false
      })
    }
  },
  // 打开评论
  openComment: function (e) {
    // 
    console.log('id', e.detail.activeId)
    this.setData({
      commentShow: !this.data.commentShow,
      commentId: e.detail.activeId,
      // commentList: []
    });
    // this.getReply(e.detail.activeId);
  },
  // 获取评论信息
  getReply: function (columnId) {
    // let columnId = this.data.id;
    console.log(123123123, columnId)
    // let pageNo = this.data.pageNo;
    // let pageSize = this.data.pageSize;
    httpRequestApi.getReply(this.uid, columnId, 1, 10).success((res) => {
      console.log('reply', res)
      const commentList = res.data.data.list;
      const commentNum = res.data.data.totalSize;
      console.log('评论数量', commentNum)
      commentList.forEach((item) => {
        const temp = {};
        temp.nickName = item.user.wechatName;
        temp.avatar = item.user.avatar;
        temp.uid = item.user.uid;
        temp.text = item.detailDesc;
        temp.id = item.id;
        temp.replyCount = item.replyCount;
        temp.time = formatDate(item.gmtCreated, 3);
        temp.likes = item.postsAttributeInfo.favors || 0;
        temp.isLike = item.isLike;
        temp.replyList = item.replyVOList;
        this.data.commentList.push(temp);
      });
      this.setData({
        commentList: this.data.commentList,
        commentNum: commentNum
      })
    });
  },
  // 发布回复
  sendReply: function (e) {
    console.log('triger', e.detail.content);
    let data = {
      columnId: this.data.commentId,
      colunmNames: 'what',
      detailDesc: e.detail.content,
      // productId: this.data.productId
    }
    httpRequestApi.postReply(this.uid, data).success(res => {
      console.log(res)
      this.setData({
        pageNo: 1,
        commentList: []
      }, () => {
        this.getReply(this.data.commentId);
      })
    });
  },
  gradeTap: function () {
    // console.log("组件回调,返回上一页");
    this.setData({
      isGradeShow: true
    })
  },
  // 修改年级
  changeGrade: function (e) {
    const grade = e.target.dataset.code;
    wx.setStorageSync('grade', grade)
    this.setData({
      isGradeShow: false,
    })
    getOpenidNoLogin((res) => {
      console.log('getOpenidNoLogin', res)
      // 登录或注册完成 展示页面
      this.showPage()
    }, (error) => {
      console.log('获取失败')
      wx.setStorageSync('userSourseType', 'normal')
      this.setData({
        hide: !this.data.hide
      })
    }, grade);
  },

  getFollowData: function () {
    httpRequestApi.getFollowWorks(this.data.followPageNo, this.data.followPageSize).success(res => {
      if (res.data.data.totalSize === 0) {
        this.setData({
          videoList: []
        })
        console.log('没有关注人或关注的人没有发过作品')
        return
      }
      console.log('关注列表', res)
      const followData = res.data.data.list;
      followData.forEach(item => {
        const temp = {};
        temp.title = item.userRead ? item.userRead.title : '';
        temp.img = item.userRead.iconImg;
        temp.plays = item.userRead.playAmount ? item.userRead.playAmount : 0;
        temp.likes = item.userRead.likeAmount ? item.userRead.likeAmount : 0;
        temp.classId = item.userRead.exampleId ? item.userRead.exampleId : 1605097720036046;
        temp.time = formatDate(item.userRead.gmtCreated, 3);
        temp.avatar = item.user ? item.user.avatar : '';
        temp.uid = item.user ? item.user.uid : '';
        temp.url = item.userRead.videoPath ? item.userRead.videoPath : item.userRead.originVideo;
        temp.nickName = item.user ? item.user.wechatName : '';
        temp.id = item.userRead.id;
        this.data.videoList.push(temp);
      });
      this.setData({
        videoList: this.data.videoList
      })
    });
  },
  // 点击用户头像区域
  headTapHandler: function (e) {
    console.log('点击头像', e)
    let tapId = e.detail.activeId;
    // 点击头像既关注 测试
    httpRequestApi.followUser(this.uid, tapId).success(res => {
      console.log(res)
    })
  },
  getCoursesList: function () {
    const grade = wx.getStorageSync('grade');
    const data = {
      grade,
      type: 'EXAMPLE'
    }
    httpRequestApi.getClassRead(data).success(res => {
      console.log('资源', res)
      this.setData({
        coursesData: res.data.data.list
      }, () => {
        console.log(this.data.coursesData)
      })
    })
  },
  goToReading: function (e) {
    console.log('去朗读', e)
    const id = e.detail.activeId ? e.detail.activeId : e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `../../pages/main/reading/reading?id=${id}`
    });
  },

})