// pages/member/article/articleContent/articleContent.js
//var WxParse = require('../../../../wxParse/wxParse');
var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    article_id: "",
    articleData: {},
    is_liked: 0,
    like_num: "",
    read_num: "",
    article_content: "",

    codeUrl: "",
    // 评论功能
    replyName: "",
    commentPage: 1,
    commentList: [],
    last_page: 1,
    commenMember: [],
    keyInd: 0,
    comment_id: 0,
    // commentOn: false,
    comment: false,
    commentNum: 0,
    imgList: [],
    maincomment: "",
    replyContent: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.mid) {
      app._setMid(options.mid);
    }
    this.setData({
      article_id: options.article_id,
    });
    this._getData();
    // this._getQrCode();
  },

  _getData: function (success) {
    var that = this;
    // 初次获取数据
    let urlStr = app.getNetAddresss("plugin.article.api.article.get-article");
    urlStr += "&article_id=" + that.data.article_id;
    app._getNetWork({
      url: urlStr,
      success: function (res) {
        if (res.data.result == 1) {
          let _data = res.data.data;
          _data.content = _data.content.replace(/<img/gi, '<img style="max-width:100%;height:auto;display:block" ');
          if (_data.has_one_article_pay) {
            if (!_data.has_one_record) {
              wx.showToast({
                title: '您尚未购买该文章内容,无法观看',
                icon: 'none',
                duration: 1000,
                success: function (res) {
                  setTimeout(() => {
                    wx.navigateTo({
                      url: '/packageD/article/articleList/articleList?article_id=' + that.data.article_id
                    });
                  }, 500);
                }
              });
              return;
            }
          }
          that.setData({
            articleData: _data,
            article_content: _data.content,
            is_liked: _data.liked,
            like_num: _data.like_num + _data.virtual_like_num,
            read_num: _data.read_num + _data.virtual_read_num,
            miQrCodeUrl: _data.miQrCodeUrl,
            qr: _data.qr,
          });
          if (_data.comment) {
            // 文章评论功能有开启才请求
            that.setData({
              comment: _data.comment
            });
            that.getComment();
          }
          // 设置页面标题
          wx.setNavigationBarTitle({
            title: _data.title,
          });
          if (success != undefined) {
            success(res);
          }
        } else {
          if (res.data.msg == "您尚未购买该文章内容,无法观看") {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 1500,
              success: function () {
                setTimeout(function () {
                  //要延时执行的代码
                  wx.redirectTo({
                    url: "/packageD/article/articleList/articleList?article_id=" + that.data.article_id,
                  });
                }, 1500); //延迟时间
              },
            });
          } else {
            wx.showToast({
              title: res.data.msg,
              icon: "none",
              duration: 1500,
              success: function () {
                setTimeout(function () {
                  //要延时执行的代码
                  wx.navigateBack({
                    delta: 1,
                  });
                }, 1500); //延迟时间
              },
            });
          }
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },

  _getQrCode: function (success) {
    var that = this;
    // 获取二维码
    app._getNetWork({
      url: app.getNetAddresss("member.member.getArticleQr"),
      success: function (res) {
        if (res.data.result == 1) {
          let _data = res.data.data;
          that.setData({
            codeUrl: _data,
          });
          if (success != undefined) {
            success(res);
          }
        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  _toLike: function (success) {
    var that = this;
    // 点赞
    app._getNetWork({
      url: app.getNetAddresss("plugin.article.api.article.like"),
      data: {
        article_id: that.data.article_id,
      },
      success: function (res) {
        if (res.data.result == 1) {
          let _data = res.data.data;
          if (_data.liked == 1) {
            that.setData({
              is_liked: true,
              like_num: that.data.like_num + 1,
            });
            wx.showToast({
              title: "点赞成功",
            });
          } else {
            that.setData({
              is_liked: false,
              like_num: that.data.like_num - 1,
            });
            if (that.data.like_num < 0) {
              that.setData({
                like_num: 0,
              });
            }
            wx.showToast({
              title: "取消点赞",
              icon: "none",
            });
          }

          success && success(res);
        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },

  clickLike: function () {
    this._toLike();
  },

  toAdv: function () {
    console.log("跳转到广告");
    if (!app._isTextEmpty(this.data.articleData) && app._isTextEmpty(this.data.articleData.min_app_advs_link)) {
      return;
    }
    wx.navigateTo({
      url: this.data.articleData.min_app_advs_link,
    });
  },

  toLink: function (e) {
    let url = e.currentTarget.dataset.link;
    wx.navigateTo({
      url: url,
    });
  },

  toReport: function () {
    wx.navigateTo({
      url: "/packageA/member/article/noticeReport/noticeReport?article_id=" + this.data.article_id,
    });
  },

  previewImage: function (e) {
    var current = e.target.dataset.src; //这里获取到的是一张本地的图片
    wx.previewImage({
      current: current, //需要预览的图片链接列表
      urls: [current], //当前显示图片的链接
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showShareMenu({
      withShareTicket: false,
      menus: ["shareAppMessage", "shareTimeline"],
    });
  },

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

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

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

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareTimeline() {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      title: this.data.articleData.desc,
      query: `mid=${mid}&article_id=${this.data.article_id}`,
      imageUrl: this.data.articleData.thumb ? this.data.articleData.thumb : "",
    };
  },
  onShareAppMessage: function () {
    var value = wx.getStorageSync("yz_uid");
    var mid = "";
    if (value) {
      mid = value;
    }
    return {
      path: "/packageA/member/article/articleContent/articleContent?article_id=" + this.data.article_id + "&mid=" + mid,
      title: this.data.articleData.desc,
      imageUrl: this.data.articleData.thumb ? this.data.articleData.thumb : "",
    };
  },
  // ==============================    文章评论二开    ===============================
  // commentOpen(){
  //   this.setData({
  //     commentOn:!this.data.commentOn
  //   });
  // },
  // 上传图片
  uploaderFun(e) {
    wx.showLoading({
      title: "加载中",
    });
    let that = this;
    let urlStr = app.getNetAddresss("upload.uploadPic");
    wx.chooseImage({
      count: 1,
      sizeType: ["original", "compressed"],
      sourceType: ["album", "camera"],
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        let photourl = tempFilePaths[0];
        wx.uploadFile({
          url: urlStr,
          filePath: photourl,
          name: "file",
          success(resdata) {
            var res = JSON.parse(resdata.data);
            wx.hideLoading();
            if (res.result == 1) {
              let imgList = that.data.imgList;
              imgList.push(res.data.img_url);
              that.setData({
                imgList,
              });
            } else {
              wx.showToast({
                icon: "none",
                title: res.msg,
                duration: 1500,
              });
            }
          },
        });
      },
      fail: function (res) {
        wx.hideLoading({
          success: (res) => {},
        });
      }
    });
  },
  delCommentIMg(e) {
    let val = e.target.dataset.index;
    this.data.imgList.splice(val, 1);
    this.setData({
      imgList: this.data.imgList,
    });
  },
  getComment() {
    let that = this;
    app._getNetWork({
      url: app.getNetAddresss("plugin.article.api.comment.comment-list"),
      data: {
        page: this.data.commentPage,
        article_id: this.data.article_id,
      },
      success: function (res) {
        if (res.data.result == 1) {
          let list = res.data.data.list.data;
          for (let i = 0; i < list.length; i++) {
            if (list[i].reply_num > 0) {
              list[i].commentShow = true;
            } else {
              list[i].commentShow = false;
            }
            list[i].commenMorePage = 1;
            list[i].child = [];
          }
          that.setData({
            last_page: res.data.data.list.last_page,
            commenMember: res.data.data.member,
            commentList: res.data.data.list.data,
            commentNum: res.data.data.num
          });
        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      },
    });
  },
  watchImg(e) {
    // 评论图片预览
    let item = e.currentTarget.dataset.item;
    wx.previewImage({
      current: item[0], // 当前显示图片的http链接
      urls: item // 需要预览的图片http链接列表
    });
  },
  getMore() {
    let that = this;
    this.setData({
      commentPage: this.data.commentPage + 1,
    });
    wx.showLoading({
      title: '加载中',
      duration: 1000,
      icon: 'none'
    });
    app._getNetWork({
      url: app.getNetAddresss("plugin.article.api.comment.comment-list"),
      data: {
        page: this.data.commentPage,
        article_id: this.data.article_id,
      },
      success: function (res) {
        if (res.data.result == 1) {
          let dataMore = res.data.data.list.data;
          for (let i = 0; i < dataMore.length; i++) {
            if (dataMore[i].reply_num > 0) {
              dataMore[i].commentShow = true;
            } else {
              dataMore[i].commentShow = false;
            }
            dataMore[i].commenMorePage = 1;
            dataMore[i].child = [];
          }
          that.setData({
            commentList: that.data.commentList.concat(dataMore),
            last_page: res.data.data.list.last_page,
          });
        } else {
          console.error(res);
        }
        wx.hideLoading({
          success: (res) => {},
        });
      },
      fail: function (res) {
        console.error(res);
        wx.hideLoading({
          success: (res) => {},
        });
      },
    });
  },
  // 评论功能
  subMainCommentBtn() {
    this.setData({
      maincomment: "",
      mainCommentShow: true,
    });
  },
  // 遮罩关闭
  mainCommentShowClose() {
    this.setData({
      mainCommentShow: false,
    });
  },
  replyshowClose() {
    this.setData({
      replyshow: false,
    });
  },
  // 输入框事件 主评论文字
  maincommentinp(e) {
    let val = e.detail.value;
    this.setData({
      maincomment: val,
    });
  },
  replyContentinp(e) {
    let val = e.detail.value;
    this.setData({
      replyContent: val,
    });
  },
  // 回复
  replyBtn(e) {
    let item = e.currentTarget.dataset.item;
    let name = item.nick_name;
    this.setData({
      keyInd: e.currentTarget.dataset.kind,
      replyshow: true,
      replyId: item.id,
      comment_id: item.comment_id == 0 ? item.comment_id : item.id,
      replyName: name,
      commentManagement: false,
    });
  },
  // 发送按钮
  subMainBtn(e) {
    let type = e.currentTarget.dataset.type;
    this.getReplyComments(type);
  },
  // 发送请求
  getReplyComments(type) {
    let that = this;
    let urlStr;
    let dataJson = {
      images: that.data.imgList,
      content: "",
    };
    console.log(type);
    if (type == "main") {
      if (app._isTextEmpty(this.data.maincomment)) {
        wx.showToast({
          title: "请输入评论内容",
          icon: "none",
          duration: 1000,
        });
        return;
      }
      urlStr = "plugin.article.api.comment.create-comment";
      dataJson.article_id = that.data.article_id;
      dataJson.content = that.data.maincomment;
    } else if (type == "reply") {
      if (app._isTextEmpty(this.data.replyContent)) {
        wx.showToast({
          title: "请输入评论内容",
          icon: "none",
          duration: 1000,
        });
        return;
      }
      urlStr = "plugin.article.api.comment.reply-comment";
      dataJson.content = that.data.replyContent;
      dataJson.comment_id = that.data.replyId;
    }
    wx.showLoading({
      title: '加载中',
      duration: 1000,
      icon: 'none'
    });
    app._getNetWork({
      url: app.getNetAddresss(urlStr),
      data: dataJson,
      success: function (res) {
        if (res.data.result == 1) {
          if (type == "main") {
            that.setData({
              commentPage: 1,
              mainCommentShow: false,
              replyshow: false,
              maincomment: ''
            });
            that.getComment();
          } else if (type == 'reply') {
            that.updateInfo(res.data.data, that.data.keyInd);
          }
        } else {
          console.error(res);
        }
        wx.hideLoading({
          success: (res) => {},
        });
      },
      fail: function (res) {
        wx.hideLoading({
          success: (res) => {},
        });
        console.error(res);
      },
    });
  },
  // 回复后更新数据
  updateInfo(data, ind) {
    console.log(data, ind);
    let arr = [];
    arr.push(data);
    if (this.data.commentList[ind].child) {
      this.data.commentList[ind].child.unshift(arr[0]);
    } else {
      this.data.commentList[ind].child = arr;
    }
    this.setData({
      commentList: this.data.commentList,
      mainCommentShow: false,
      replyshow: false,
      replyContent: ''
    });
  },
  // 加载子评论
  moreCommentLis(e) {
    console.log(e);
    wx.showLoading({
      title: '加载中',
      icon: 'none',
      duration: 1000
    });
    let that = this;
    let id = e.currentTarget.dataset.item.id;
    let ind = e.currentTarget.dataset.ind;
    let urlStr = "plugin.article.api.comment.get-replys";
    console.log(this.data.commentList);
    let is_page = Number(this.data.commentList[ind].commenMorePage);
    let dataJson = {
      page: is_page,
      comment_id: id,
    };
    app._getNetWork({
      url: app.getNetAddresss(urlStr),
      data: dataJson,
      success: function (res) {
        if (res.data.result == 1) {
          let resdata = res.data.data;
          console.log(resdata);
          let childs = resdata.data;
          let num = that.data.commentList[ind].reply_num - resdata.data.length;
          that.data.commentList[ind].reply_num = num;
          let arr = that.data.commentList[ind].child.concat(childs);
          that.data.commentList[ind].child = arr;
          let moreLast_page = resdata.data.last_page;
          if (is_page >= moreLast_page) {
            is_page = 1;
          } else {
            is_page = is_page + 1;
          }
          that.data.commentList[ind].commenMorePage = is_page;
          that.setData({
            commentList: that.data.commentList,
          });
        } else {
          console.error(res);
        }
        wx.hideLoading({
          success: (res) => {},
        });
      },
      fail: function (res) {
        wx.hideLoading({
          success: (res) => {},
        });
        console.error(res);
      },
    });
  },
  // 删除评论
  delComment(e) {
    console.log(e);
    let myUid;
    try {
      myUid = wx.getStorageSync('uid');
    } catch (error) {
      myUid = '';
    }
    let item = e.currentTarget.dataset.item;
    let ind = e.currentTarget.dataset.ind;
    let index;
    try {
      index = e.currentTarget.dataset.index;
    } catch (error) {
      index = null;
    }
    console.log(item, ind, index);
    if (this.data.commentList[ind].child.length > 0) {
      if (item.uid == myUid) {
        console.log('子评论是我的，可以删');
        this.delRequst(item.id, ind, index, 'child');
      }
    } else {
      if (myUid == item.uid) {
        console.log('主评论是我的，可以删');
        this.delRequst(item.id, ind, index, 'list');
      }
    }

  },
  delRequst(id, ind, index, key) {
    let that = this;

    wx.showModal({
      content: '是否删除评论',
      success: function (res) {
        if (res.confirm) {
          console.log('删除');
          wx.showLoading({
            title: '加载中',
            duration: 1000,
            icon: 'none'
          });
          app._getNetWork({
            url: app.getNetAddresss("plugin.article.api.comment.del"),
            data: {
              comment_id: id,
            },
            success: function (res) {
              if (res.data.result == 1) {
                if (key == 'child') {
                  that.data.commentList[ind].child.splice(index, 1);
                } else {
                  that.data.commentList.splice(ind, 1);
                }
                that.setData({
                  commentList: that.data.commentList
                });
                wx.showToast({
                  title: res.data.data,
                  icon: 'none',
                  duration: 1000
                });
              } else {
                console.error(res);
              }
              wx.hideLoading({
                success: (res) => {},
              });
            },
            fail: function (res) {
              console.error(res);
              wx.hideLoading({
                success: (res) => {},
              });
            },
          });
        }
      }
    });
  }
});