import httpRequestApi from '../../utils/APIClient';
import {
  formatDate
} from '../../utils/util';
export const hotInit = (that) => {
  if (!that.data.hotData) {
    that.setData({
      hotData: {
        title: '热门',
        autoplay: false,
        swiperCurrent: 0,
        interval: 5000,
        duration: 700,
        circular: true,
        hotWareCardFirst: 'hotWareCardFirst',
        hotWareCard: 'hotWareCard',
        hotSearch: '',
        banner: [],
        recommend: [],
        hotWorks: [],
        winH: that.data.winH,
        searchIcon: true,
        unReadMessageNum: 0,
        myCourse: [],
        inputFocus: false,
        inputValue: '',
        baiduFlag: false
        // circular: true
      }
    })
  }
  // 搜索方法
  that.searchHandler = () => {
    if (that.data.hotInput.lenght !== 0) {
        wx.navigateTo({
          url: `../main/searchResult/searchResult?keyWords=${that.data.hotInput}`
        })
      }
      const str = 'hotData.inputValue';
      that.setData({
        [str]: ''
      })
    };
    // 输入框获取焦点 放大镜消失
    that.searchIconDisappear = () => {
      const str = 'hotData.searchIcon'
      that.setData({
        [str]: false
      })
    };
    that.searchIconCome = () => {
      const str = 'hotData.searchIcon'
      that.setData({
        [str]: true
      })
    };
    // 百度弹窗弹出
    that.clickBaidu = () => {
      const str = 'hotData.baiduFlag'
      that.setData({
        [str]: true
      });
    };
    // 百度弹窗关闭
    that.xiaoduClick = () => {
      const str = 'hotData.baiduFlag'
      that.setData({
        [str]: false
      });
    };
    // 百度保存图片
    that.PreservationXiaodu =  () => {
      wx.getImageInfo({
        src: 'https://reader.image.lingjiao.cn/reader/resource/海报.png',
        success (res) {
          wx.saveImageToPhotosAlbum({
            filePath: res.path,
            success: (res) => {
              wx.showModal({
                title: '海报已保存至相册',
                content: '快去分享给小伙伴吧',
                confirmText: '我知道了',
                showCancel: false,
                success(res) {
                  console.log('用户点击确定')
                }
              })
              const str = 'hotData.baiduFlag'
              that.setData({
                [str]: false
              });
            },
            fail: res => {
              console.log(res)
              wx.getSetting({
                success(res) {
                  if (!res.authSetting['scope.writePhotosAlbum']) {
                    wx.showModal({
                      title: '无法保存分享图片到相册',
                      content: '点击右上角浮点按钮->设置，进行授权',
                      confirmText: '我知道了',
                      showCancel: false,
                      success(res) {
                        console.log('用户点击确定')
                      }
                    })
                  }
                }
              })
            }
          })
        }
      })

    };
  // 输入框输入
  that.inputHandler = (e) => {
      that.setData({
        hotInput: e.detail.value
      });
    };
    // 输入框聚焦
    that.inputFocus = () => {
      const str = 'hotData.inputFocus'
      that.setData({
        [str]: true
      });
      console.log(that.data.hotData.inputFocus)
    };
    // 打开全部课本
    that.openBooks = (e) => {
      wx.navigateTo({
        url: `../main/books/books`
      })
    }
  // 打开更多页面
  that.openMore = () => {
    wx.navigateTo({
      url: `../main/week/week`
    })
  }
  // 打开课程页面
  that.openClass = (e, lessonId) => {
    if (lessonId) {
      wx.navigateTo({
        url: `../main/class/class?id=${lessonId}`
      })
    } else {
      let id = e.currentTarget.dataset.classid;
      let title = e.currentTarget.dataset.title;
      wx.navigateTo({
        url: `../main/class/class?id=${id}&title=${title}`
      })
    }
  }
  // 打开用户作品页面
  that.openWorks = (e) => {
    let readId = e.currentTarget.dataset.readid;
    let title = e.currentTarget.dataset.title;
    wx.navigateTo({
      url: `../social/works/works?id=${readId}&title=${title}`
    })
  }
  that.getIndex = () => {
    const uid = wx.getStorageSync('uid');
    httpRequestApi.getIndex(
      uid
    ).success((res) => {
      const recommend = res.data.data.recommendLesson;
      const recommendTemp = [];
      recommend.forEach(item => {
        const oTemp = {};
        oTemp.img = item.boothContent;
        oTemp.classId = item.operationContent;
        oTemp.title = item.title;
        oTemp.summary = item.summary;
        recommendTemp.push(oTemp);
      });
      let recommendIndex = 'hotData.recommend';
      that.setData({
        [recommendIndex]: recommendTemp
      });
      httpRequestApi.userIntoPage('pages/index/index', '首页推荐').success((res) => {

      })
    })
  }
  that.getHotRecommend = (uid) => {
    httpRequestApi.getHotRecommend(
      uid
    ).success((res) => {
      // 点击切换按钮时 只刷新我的课程和未读消息 官方推荐和热门不加载
      const recommendRes = res.data.data;
      console.log(that.data.hotData.hotWorks.length)
      if (that.data.hotData.hotWorks.length > 0) {
        const myCourseStr = 'hotData.myCourse'
        const isMessageNormal = 'hotData.isMessageNormal'
        const unReadMessageContent = 'hotData.unReadMessageContent'
        // unread为true时显示 未读消息，unread为false时显示通知消息，并且通知消息不可读
        that.setData({
          [myCourseStr]: recommendRes.myCourse,
          [isMessageNormal]: recommendRes.unread,
          // [unReadMessageContent]: recommendRes.unread ? recommendRes.unreadMsg.title : '',
          // [unReadMessageContent]: recommendRes.unread ? recommendRes.unreadMsg.title : recommendRes.annunciateMsg.title
          [unReadMessageContent]: ''
        })

        return;
      }
      recommendRes.hotReader.forEach(item => {
        const temp = {};
        temp.title = item.userRead ? 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.classId = item.userRead.id;
        temp.time = formatDate(item.userRead.gmtCreated, 3);
        temp.avatar = item.user ? item.user.avatar : '';
        temp.profession = item.user ? item.user.profession : '';
        temp.uid = item.user ? item.user.uid : '';
        // temp.avatar = item.user.avatar;
        temp.nickName = item.user ? item.user.wechatName : '';
        // recommendWorks.push(temp);
        that.data.hotData.hotWorks.push(temp);
      });
      const hotStr = 'hotData.hotWorks'
      const myCourseStr = 'hotData.myCourse'
      const isMessageNormal = 'hotData.isMessageNormal'
      const unReadMessageContent = 'hotData.unReadMessageContent'
      that.setData({
        [hotStr]: that.data.hotData.hotWorks,
        [myCourseStr]: recommendRes.myCourse,
        [isMessageNormal]: recommendRes.unread,
        // [unReadMessageContent]: recommendRes.unread ? recommendRes.unreadMsg.title : recommendRes.annunciateMsg.title,
        [unReadMessageContent]: '',
        unfinishedCount: recommendRes.unfinishedCount
      })
    })
  }

  that.getHotRecommendSecond = (uid, pageNo, pageSize) => {
    httpRequestApi.getHotRecommendSecond(uid, 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.classId = item.userRead.id;
        temp.time = formatDate(item.userRead.gmtCreated, 3);
        temp.avatar = item.user.avatar;
        temp.profession = item.user.profession;
        temp.uid = item.user.uid;
        // temp.avatar = item.user.avatar;
        temp.nickName = item.user.wechatName;
        // recommendWorks.push(temp);
        that.data.hotData.hotWorks.push(temp);
      });
      const hotStr = 'hotData.hotWorks'
      that.setData({
        [hotStr]: that.data.hotData.hotWorks,
        recommendTotalNo: res.data.data.totalNo
      })
    })
  }
  // 去全部课本
  that.goToBooks = () => {
    wx.navigateTo({
      url: `../main/books/books`
    })
  }
  that.bannerTap = (e) => {
      const type = e.currentTarget.dataset.type;
      const id = e.currentTarget.dataset.id;
      switch (type) {
        case 'LESSON':
          that.openClass('tap', id);
          break;
      }
    },
    that.goToUsers = (e) => {
      console.log(e)
      let uid = e.currentTarget.dataset.uid;
      wx.navigateTo({
        url: `../../pages/user/myworks/myworks?uid=${uid}`
      });
    }
  // 下拉加载
  that.scrollUpdate = (e) => {
    console.log(e)
  }
  console.log(that.data.hotData.recommend)

  if (wx.getStorageSync('uid')) {
    that.getIndex();
    that.getHotRecommend(wx.getStorageSync('uid'));
  }
  // that.getIndex();

  // 获取全部课本
  // that.getBookList();
  // that.swiperChange = (e) => {
  //   const str = 'hotData.swiperCurrent'
  //   that.setData({
  //     [str]: e.detail.current
  //   });
  // }
  //跳转到课程详情
  that.goToBook = function (e) {
    console.log(e.currentTarget.dataset)
    let id = e.currentTarget.dataset.id;
    let title = e.currentTarget.dataset.title;
    console.log(id)
    wx.navigateTo({
      url: `/pages/groupPage/grade-details/grade-details?productId=${id}&title=${title}`
    })
  }
  that.swiperChange = (e) => {
    const str = 'hotData.swiperCurrent'
    that.setData({
      [str]: e.detail.current
    });
  }
}