// pages/today/today.js
const app = getApp()
import * as echarts from '../../ec-canvas/echarts';
const $api = require('../../utils/api.js').API;
const $push = require('../../utils/api.js').PUSH;

var id, record_id, records = [], today_stock=[];
Page({

  /**
   * 页面的初始数据
   */
  data: {
    page:0,
    focus:false,
    date:'2021-11',
    text:'留言',
    days:[],
    author_user_id:'',
    ec: {
      onInit: null
    },
    ec1: {
      onInit: null
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    id = options.id, record_id = options.record_id
    this.setData({
      id: id,
      record_id: record_id,
      user_id: options.user_id ? options.user_id:''
    })

    wx.getStorage({
      key: 'user',
      complete: res => {
        this.setData({
          author_user_id: res.data.id,
        })
      }
    })

    this.getData();
  },
  getzan(){
    $api.getZanCount({record_id:this.data.record_id,match_id:this.data.id}).then(res=>{
      this.setData({
        zan_count:res.data.data
      })
    })
  },
  getComment(){
    $api.getComment({record_id:this.data.record_id,match_id:this.data.id}).then(res=>{
      if(res.data.code == 0){
          this.setData({
            comment_list:res.data.data.list,
            comment_count:res.data.data.total
          })
      }
    })
  },
  answer(e){
      this.setData({
          focus:true,
          text:'回复'+e.target.dataset.name,
          pid:e.target.dataset.id
      })
  },
  tab(e){
    this.setData({
        page:e.target.dataset.id
    })
},
  getDays(){
    $api.getCalendar({
      user_id: this.data.user_id,
      match_id:this.data.id,
      month: this.data.date
    }).then(res=>{
      var days = [], w = new Date(this.data.date + '-01').getDay();
      for (let i = 0; i < w; i++) {
        days.push({
          day: '',
          income: ''
        })
      }
      for (let i = 0; i < res.data.data.length; i++) {
        days.push({
          day: i+1,
          income: res.data.data[i].today_income,
          record_id:res.data.data[i].record_id,
        })
      }
      this.setData({
        days: days
      })
    })
  },
  getData(){
    wx.showNavigationBarLoading();
    var data = {}
    if (this.data.id) {
      data.id = this.data.id
    }
    if (this.data.user_id) {
      data.user_id = this.data.user_id
    }
    if (this.data.record_id) {
      data.record_id = this.data.record_id
    }
    $api.getPlayerMatch(data).then(res=>{
      let stock_date=res.data.data.today_record.stock_date.split('-')
      this.setData({
        datas: res.data.data,
        date: stock_date[0] + '-' + stock_date[1],
        is_follow: res.data.data.is_follow,
        user_id: res.data.data.today_record.user_id,
        followers:res.data.data.followers,
        fans:res.data.data.fans,
        record_id: this.data.record_id ? this.data.record_id:res.data.data.today_record.id,
        ec: {
          onInit: initChart
        },
        ec1: {
          onInit: initChart1
        }
      })
      records = res.data.data.records
      today_stock = res.data.data.today_record.today_stock
      this.getDays()
      this.getzan()
      this.getComment()
      wx.hideNavigationBarLoading()
    })
    .catch(err=>{
      wx.hideNavigationBarLoading()
    })
    //每日持股
    var parm={
      id: data.id, user_id: this.data.user_id
    }
    // $api.getRecordList(parm).then(res=>{
    //     this.setData({
    //       stockList:res.data.data.list
    //     })
    // })
  },
  bindDateChange(e){
    this.setData({
      date: e.detail.value
    })
    this.getDays()
  },
  prev(){
    var date=this.data.date.split('-'),y=date[0],m=date[1];
    if(m>1){
      m--
    }else{
      m=12
      y--
    }
    m=(m>9)?m:'0'+m
    this.setData({
      date: y+'-'+m
    })
    this.getDays()
  },
  next() {
    var date = this.data.date.split('-'), y = date[0], m = date[1];
    if (m < 12) {
      m++
    } else {
      m = 1
      y++
    }
    m = (m > 9) ? m : '0' + m
    this.setData({
      date: y + '-' + m
    })
    this.getDays()
  },
  //预览
  preview(e) {
    wx.previewImage({
      urls: e.target.dataset.urls,
      current: e.target.dataset.src
    })
  },
  followPlayer(e){
    let action = e.target.dataset.action;
    $api.follow({ follow_id: this.data.user_id, action:action}).then(res=>{
      wx.showToast({
        title: action?'取消成功':'已关注',
      })
      this.setData({
        is_follow: !this.data.is_follow
      })
      app.globalData.follow=1

    })
  },
  inputchange(e) {
    this.setData({
      comment: e.detail.value
    })
  },
  blur(){
    this.setData({
      comment:'',
      pid:null,
      text:'留言'
    })
  },
  sendmsg(){
    var data={
      record_id:this.data.record_id,
      cotent:this.data.comment,
      pid:this.data.pid,
      match_id:this.data.id
    }
    if(!data.cotent){
        return
    }
    $api.postcomment(data).then(res=>{
      this.getComment()
      this.setData({
        comment:'',
        pid:null,
        text:'留言'
      })
    })
  },
  delmsg(e){
    var data={
      id:e.target.dataset.id
    }
    $api.delcomment(data).then(res=>{
      this.getComment()
    })
  },
  zan(){
    $api.zan({record_id:this.data.record_id,match_id:this.data.id}).then(res=>{
      if(res.data.code == 0){
        this.getzan()
        this.setData({
          zan:1
        })
        setTimeout(()=>{
          this.setData({
            zan:0
          })
        },3000)
      }
    })
  },
  pushToday(e){
    $push.pushToday(e.currentTarget.dataset)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

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

  },

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

  },

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

  },

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

  },

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

  }
})


/**折线图 */
function initChart(canvas, width, height, dpr) {
    var xdata = [], ydata = [];
    for (let i = 0; i < records.length; i++) {
      let date = records[i].stock_date.split('-');
      xdata.push(date[1] + '/' + date[2])
      let y = records[i].total_income.replace('%', '')
      ydata.push(Number(y))
    }
    xdata = xdata.reverse()
    ydata = ydata.reverse()
    const chart = echarts.init(canvas, null, {
      width: width,
      height: height,
      devicePixelRatio: dpr // new
    });
    canvas.setChart(chart);
    var option = {
      legend: {
        show: false
      },
      grid: {
        x: 40,
        y: 10,
        x2: 10,
        y2: 35
      },
      tooltip: {
        show: true,
        trigger: 'axis',
        formatter: '{b0}: {c0}%',
      },
      xAxis: {
        type: 'category',
        data: xdata,
        axisLabel: {
          interval: 0,
          rotate: 40,
          color: '#999999',
          interval: 2
        }
      },
      yAxis: {
        axisLine: {
          show: true,
        },
        type: 'value',
        // name: '收益曲线',
        axisLabel: {
          color: '#999999',
          formatter: function (value, index) {//隐藏 0
            let texts = [];
            texts.push(value + '%')
            return texts;
          },
          show: true
        },
      },
      series: [{
        name: 'A',
        type: 'line',
        smooth: true,
        symbolSize: 4,
        lineStyle: {
          color: '#FF2D68'
          // color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [{
          //   offset: 0,
          //   color: '#FF2D68'
          // }, {
          //   offset: 1,
          //   color: '#4C4BFF'
          // }]),
        },
        itemStyle: {
          borderWidth: 5,
          borderColor: '#FFAD52',
          color: '#FFAD52'
        },
        data: ydata
      }]
    };

    chart.setOption(option);
    return chart;
}




function initChart1(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);
  today_stock.forEach(item=>{
    item.value = item.fund
  })
  var radius = today_stock.length<9?'65%':'50%';
  var option = {
    backgroundColor: "#ffffff",
    legend: {
      show: true,
      orient: 'vertical',
      right: '1%',
      formatter: function (name){
        var index = 0;
        today_stock.forEach(function (value, i) {
          if (value.name == name) {
            index = i;
          }
        });
        return name + "  " + today_stock[index].value;
      }
    },
    series: [{
      label: {
        
        normal: {
          show: true,
          fontSize: 12,
          formatter: function (a) {
            return Math.round(a.percent)+'%'
          }
        }
      },
      type: 'pie',
      center: ['37%', '40%'],
      radius: ['0%', radius],
      data: today_stock
      
    }]
  };

  chart.setOption(option);
  return chart;
}