// pages/zl_detail/index.js
const { request, serverName, imgServer } = require('../../utils/services');
const WxParse = require('../../common/component/wxParse/wxParse.js');

const { Toast, removeArrItem } = require('../../utils/util.js');
const { defaultImg } = require('../../utils/images');
const app = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    logo_img: "../../imgs/logo.jpg",
    half_star_img: "../../imgs/icon/half.png",
    empty_star_img: "../../imgs/icon/empty.png",
    full_star_img: "../../imgs/icon/full.png",
    testImg: '../../imgs/testImg/thumbSmallImg2.jpg',
    avatar: '../../imgs/testImg/1.jpg',
    icon_quanping: '../../imgs/quanping.png',
    active: false,
    readActive: false,
    isLike: false,
    likeNum: 526,
    animationData: {},
    imgServer,

    tour_info_data: [{
      title: '地址：',
      txt: '北京市朝阳区崔各乡庄各庄村顺白马路马嘻路口100米路北'
    }, {
      title: '开放时间',
      txt: '周二到周日10：00-18：00 （每周一闭馆）'
    }, {
      title: '电话：',
      txt: '+86 10 8456654654'
    }]

  },
  clickCell: function () {
    console.log(this.data.active);
    this.setData({
      active: !this.data.active
    })
  },
  readMore: function () {
    this.setData({
      readActive: true
    })
  },
  fix_starImg: function (points) {
    let strPoints = String(Number(points).toFixed(2));
    let show_Arr = [];

    let ten = strPoints.split('.')[0] || 0;
    let unit = strPoints.split('.')[1] || 0;
    let surPlus = 0;
    if (strPoints < 0) {
      return
    }
    if (ten) {
      for (let i = 0; i < Number(ten); i++) {
        show_Arr.push({
          'img': this.data.full_star_img
        })
      }
      surPlus = 5 - Number(ten);
    }

    if (unit && surPlus > 0) {
      let numUnit = Number(unit.substr(0, 1)) || 0
      if (numUnit > 0) {
        // let fix_unit = Math.round(numUnit);
        switch (true) {
          case numUnit > 5:
            show_Arr.push({
              'img': this.data.full_star_img
            })
            break;
          case numUnit <= 5:
            show_Arr.push({
              'img': this.data.half_star_img
            })
            break;
          default:
            break
        }
      } else if (numUnit == 0) {
        show_Arr.push({
          'img': this.data.empty_star_img
        })
      } else {
        return
      }
    }
    if (surPlus > 0) {
      for (let i = 0; i < surPlus - 1; i++) {
        show_Arr.push({
          'img': this.data.empty_star_img
        })
      }
    }

    return show_Arr
  },
  tapToCommentDetail: function () {
    let {
      exhibitionId
    } = this.data;
    wx.navigateTo({
      // url: `../../zl_detail/create_evaluation/index?id=${exhibitionId}`,

      url: `../yuezhan/comment_detail/index?id=${exhibitionId}`,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  addCommentLike: function (e) {
    let {
      type,
      id,
      idx
    } = e.currentTarget.dataset;
    console.log(idx, type, id)
    let {
      comments
    } = this.data;

    Toast.showToast2('loading');

    let loginSessionKey = wx.getStorageSync('token') || "";
    // if (loginSessionKey){
    request['commentLike']({
      loginSessionKey,
      commentId: id,
      type: Number(type),
    }, "post", res => {
      if (res.data.code > -1) {
        comments.content[idx].hasLike = res.data.data.hasLike
        if (res.data.data.hasLike) {
          comments.content[idx].likeCount += 1;
        } else {
          comments.content[idx].likeCount -= 1;

        }
        this.setData({
          comments: comments
        })
      }

    }, err => {

    }, complete => {

      Toast.hideLoading();
    })
    // }


  },


  addLike: function () {
    // if (this.data.isLike) {
    //   this.setData({
    //     isLike: !this.data.isLike,
    //     likeNum: this.data.likeNum - 1
    //   })
    // } else {
    //   this.setData({
    //     isLike: !this.data.isLike,
    //     likeNum: this.data.likeNum + 1
    //   })
    // }

    let loginSessionKey = wx.getStorageSync('token') || "";
    let {
      exhibitionId,
      exhibitionDetail,
      type: isChange
    } = this.data;
    let {
      collectedArr,
      collectedChange
    } = app.globalData, hasItem = true;
    let type = exhibitionDetail.hasCollect
    // if (loginSessionKey){
    request['isCollect']({
      loginSessionKey,
      exhibitionId: exhibitionId,
      type: Number(type),
    }, "post", res => {
      if (res.data.code > -1) {
        for (let i = 0; i < collectedArr.length; i++) {
          if (collectedArr[i].collectedId && exhibitionId == collectedArr[i].collectedId) {
            console.log("true")
            collectedArr[i] = {
              collectedId: exhibitionId,
              status: res.data.data.hasCollect,
            }
            hasItem = false;
          }
        }
        if (hasItem) {
          collectedArr.push({
            collectedId: exhibitionId,
            status: res.data.data.hasCollect,
          })
        }

        app.globalData.collectedArr = collectedArr;
        console.log(isChange, res.data.data.hasCollect)
        if (isChange == res.data.data.hasCollect) {
          app.globalData.collectedChange = false;
        } else {
          app.globalData.collectedChange = true;

        }


        exhibitionDetail.hasCollect = res.data.data.hasCollect
        if (exhibitionDetail.hasCollect) {
          exhibitionDetail.collectionsCount += 1;
        } else {
          exhibitionDetail.collectionsCount -= 1;
        }
        this.setData({
          exhibitionDetail: exhibitionDetail,
        })
      }

    }, err => {

    }, complete => {
      Toast.hideLoading();
    })
    // }
  },
  
  clickCell: function () {
    console.log(this.data.active);
    this.setData({
      active: !this.data.active
    })
  },

  navigateToLocation: function () {
    let { latitude, longitude, addressName } = this.data;
    console.log("dasdw",latitude,longitude)
    wx.openLocation({
      // exhibitionId: 0,
      latitude: latitude,
      longitude: longitude,
      scale: 28,
      name: addressName,
      success: function (res) {
        console.log('success')
       },
      fail: function (res) { },
      complete: function (res) { }
    });
  },

  tapToComement: function () {
    let {
      exhibitionId
    } = this.data;
    wx.navigateTo({
      url: `./create_evaluation/index?id=${exhibitionId}`,
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      defaultImg,
      exhibitionId: options.id,
      serverName
    })

    let { cookieIDs=[] } = app.globalData;
    let id = options.id;
    let hasItem = true;

    for (let i = 0; i < cookieIDs.length; i++) {
      if (cookieIDs[i] && id == cookieIDs[i]) {
        cookieIDs = removeArrItem(cookieIDs, cookieIDs[i])
      }
    }
    if (hasItem && id != undefined && (typeof(Number(id)) == 'number')) {
      cookieIDs.unshift(id)
    }

    app.globalData.cookieIDs = cookieIDs
 
  },

  getExhibitionDetail: function () {
    let exhibitionId = this.data.exhibitionId;
    request["getExhibitionDetail"]({
      exhibitionId: exhibitionId
    }, "", res => {
      let { data: exhibitionDetail } = res.data;
      let { description, openTime, comments } = exhibitionDetail;
      let _show_star = this.fix_starImg(exhibitionDetail.score || '0.0');
      if (comments) {
        let commentsCon = comments;
        for (let i = 0; i < commentsCon.length; i++) {
          let comments_star = this.fix_starImg(commentsCon[i].score || '0.0')
          commentsCon[i]['imgObj'] = comments_star
        }
      }
      this.setData({
        exhibitionDetail,
        likeNum: exhibitionDetail.collectionsCount,
        latitude: exhibitionDetail.latitude || 23.099994,
        addressName: exhibitionDetail.address,
        longitude: exhibitionDetail.longitude || 113.324520,
        type: exhibitionDetail.hasCollect,
        comments,
        _show_star: _show_star,
        markers: [
          {
            iconPath: '../../imgs/icon/mapIcon.png',
            id: 0,
            latitude: exhibitionDetail.latitude,
            longitude: exhibitionDetail.longitude,
            width: 15,
            height: 20,
            callout: {
              content: exhibitionDetail.address,
              borderRadius: 4,
              display: 'ALWAYS',
              padding: 8
            }
          }
        ]
      });
      WxParse.wxParse('description', 'html', description, this, 5);
      WxParse.wxParse('openTime', 'html', openTime, this, 5);
      
      if (exhibitionDetail.name){
        wx.setNavigationBarTitle({
          title: exhibitionDetail.name
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getExhibitionDetail();
  },

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

  },

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

  },

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

  },

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

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})