// index.js
// 获取应用实例
import * as echarts from '../../ec-canvas/echarts';

const app = getApp()
const $api = require('../../utils/api.js').API
const $push = require('../../utils/api.js').PUSH
var records = []

Page({
  data: {
    loading:0,
    notices:[],
    tabs:['今日留言','我的关注'],
    tabs1:['收益榜','盈利榜','亏损榜','跌幅榜'],
    cur:0,
    cur1:0,
    date:'2024-09-09',
    explist:[],   //留言
    total1:0,
    page1:1,
    followList:[],  //关注
    total2:-1,
    page2:1,
    banners:[],
    winLost:{},
    baikeList:[],
    articleList1:[],
    articleList2:[],
    articleList3:[],
    articleList4:[],
    groups:{},
    role:0,
    match_day:0,
    socore:[
      { name: '10',  checked: false },
      { name: '9',  checked: false },
      { name: '8',  checked: false },
      { name: '7',  checked: false },
      { name: '6',  checked: false },
      { name: '5',  checked: false },
      { name: '4',  checked: false },
      { name: '3',  checked: false },
      { name: '2',  checked: false },
      { name: '1',  checked: false }
    ],
    isScore:0,
    isWeek:0,
    scoredays:[],
    nochoose:false,
    cangwei:[],
    ec: {
      onInit: null
    },
  },
  
  onLoad() {
    var w=new Date().getDay()
    if(w == 0 || w == 6){
      this.setData({
        isWeek:1
      })
    }
    wx.getStorage({
      key: 'user',
      complete: res => {
        this.setData({
          role: res.data.role,
        })
      }
    })

    $api.getDate().then(res=>{
      this.setData({
        date:res.data.data
      })
      $api.getNotoice().then(res=>{
        this.setData({
          notices:res.data.data
        })
      })
      // 是否打分
      var y=new Date().getFullYear() 
      var m=Number(new Date().getMonth() + 1)
      var d = new Date().getDate()
      m=m>9?m:'0'+m;
      d=d>9?d:'0'+d
      var date = y+'-'+m+'-'+d

      if(!this.data.isWeek){
        $api.checkMark({stock_date:date}).then(res=>{
          if(res.data.data){
            this.setData({
              isScore:1
            })
          }
        })
      }
      
    })
    this.getFollow()
    this.getIndexData()
    this.getExp()
    this.getWeekAvg()
   
  },
  getWeekAvg:function(){
    $api.getMark().then(res=>{
      var days=res.data.data.reverse(),weeks=[]
      var pre=0
        days.forEach(item=>{
          item.week=getYearWeek(item.stock_date)
          if(item.week < pre){
            if(item.week == 1){
              item.week=pre
            }
          }else{
            pre=item.week
          }
          item.date=(new Date(item.stock_date).getMonth()+1)+'/'+(new Date(item.stock_date).getDate())
        })
        days=days.reverse()
        
        // days.forEach((item,i)=>{
         
        // })
        const result = days.reduce((acc, curr) => {
          let weekGroup = acc.find(item => item.name === curr.week);
          if (!weekGroup) {
            weekGroup = { name: curr.week, data: [] };
            acc.push(weekGroup);
          }
          weekGroup.data.push({ avg_score: curr.avg_score,date:curr.date});
          return acc;
        }, []);
        result.forEach(item=>{
          item.data=item.data.reverse()
        })
        // var scoredays=[]
        // for (let key in weeks) {
        //   scoredays.push({
        //     name:key,
        //     data:weeks[key].reverse()
        //   })
        // }
        this.setData({
          scoredays:result
        })
    })
    
    function getYearWeek(endDate) {
        //本年的第一天
        endDate=new Date(endDate)
        var beginDate = new Date(endDate.getFullYear(), 0, 1);
        //星期从0-6,0代表星期天，6代表星期六
        var endWeek = endDate.getDay();
        if (endWeek == 0) endWeek = 7;
        var beginWeek = beginDate.getDay();
        if (beginWeek == 0) beginWeek = 7;
        //计算两个日期的天数差
        var millisDiff = endDate.getTime() - beginDate.getTime();
        var dayDiff = Math.floor(( millisDiff + (beginWeek - endWeek) * (24 * 60 * 60 * 1000)) / 86400000);
        return Math.ceil(dayDiff / 7) + 1;
    } 

  },
  radioChange:function(e){
    if(!$api.checkUser()){
      this.setData({
        socore:[
          { name: '10',  checked: false },
          { name: '9',  checked: false },
          { name: '8',  checked: false },
          { name: '7',  checked: false },
          { name: '6',  checked: false },
          { name: '5',  checked: false },
          { name: '4',  checked: false },
          { name: '3',  checked: false },
          { name: '2',  checked: false },
          { name: '1',  checked: false }
        ],
      })
      return
    }
    
    var y=new Date().getFullYear() 
    var m=Number(new Date().getMonth() + 1)
    var d = new Date().getDate()
    m=m>9?m:'0'+m;
    d=d>9?d:'0'+d
    var date = y+'-'+m+'-'+d

    this.setData({
      s:e.detail.value
    })
    $api.markScore({stock_date:date,score:e.detail.value}).then(res=>{
      console.log(res)
      if(res.data.code == 0){
          wx.showToast({
            title: '打分成功',
          })
          this.setData({
            isScore:1
          })
          this.getWeekAvg()
      }
    })
  },
  fresh: function () {

  },
  // 获取首页数据
  getIndexData:function(){
    
    $api.getChampionlList({isbanner:1}).then(res=>{
      this.setData({
        banners:res.data.data.list
      })
    })
    $api.getWinList({new:1}).then(res=>{
      let day = res.data.data[0].valid_dates.indexOf(res.data.data[0].date)
      this.setData({
        winLost:res.data.data[0],
        match_day:day,
      })
      $api.getAvg({match_id:res.data.data[0].match_id}).then(res=>{
        var days=res.data.data.list,weeks=[]
        days=days.reverse()
        for(let i=0;i<100;i++){
          weeks.push({
            name:'',
            data:[],
            total:0
          })
        }
        var pre=0;
        days.forEach(item=>{
          var w=this.getWeekNumber(item.stock_date)
          if(w<pre){
            if(w==1){
              weeks[pre-1].data.push(item)
            }else{
              weeks[pre+w-2].data.push(item)
            }
          }else{
            weeks[w-1].data.push(item)
            pre=w
          } 
        })
        weeks=weeks.filter(item=>item.data.length>0)
        
        var w_text=['一','二','三','四','五','六','七','八','九','十','十一','十二','十三','十四','十五']
        weeks.forEach((item,index)=>{
          if(item.data.length>0){
            item.name='第'+w_text[index]+'周'
            var total=0
            var money = 10000.0
            item.data.forEach(i=>{
              var incom=Number(i.today_income.replace('%',''))
              money += money*incom/100.0
              i.date=(new Date(i.stock_date).getMonth()+1)+'/'+(new Date(i.stock_date).getDate())
            })
            total = (money-10000)*100.0/10000.0
            item.total=total.toFixed(2)
          }
        })
        this.setData({
          days:weeks.reverse()
        })
      })
      
      this.getCangwei(res.data.data[0].match_id)

      $api.getWinLose({match_id:res.data.data[0].match_id}).then(res1=>{
          this.setData({
            groups:res1.data.data
          })
      })
    })
    $api.getBaikeRandom().then(res=>{
      this.setData({
        baikeList:res.data.data
      })
    })
    $api.getChampionlList({category:'每日点评',page:1}).then(res=>{
      this.setData({
        articleList1:res.data.data.list
      })
    })
    $api.getChampionlList({category:'冠军交割',page:1}).then(res=>{
      this.setData({
        articleList2:res.data.data.list
      })
    })
    $api.getChampionlList({category:'牛人专场',page:1}).then(res=>{
      this.setData({
        articleList3:res.data.data.list
      })
    })
    $api.getChampionlList({category:'妖股列传',page:1}).then(res=>{
      this.setData({
        articleList4:res.data.data.list
      })
    })
  },
  getCangwei(mid){
    $api.getCangweiList({match_id:mid}).then(res=>{
      var days=res.data.data.list,weeks=[]
      days=days.reverse()
      var ncangwei = []

      for(let i=0;i<100;i++){
        ncangwei.push({
          name:'',
          data:[],
          total:0
        })
      }
      var pre=0;
      days.forEach(item=>{
        var w=this.getWeekNumber(item.stock_date)
        if(w<pre){
          if(w==1){
            ncangwei[pre-1].data.push(item)
          }else{
            ncangwei[pre+w-2].data.push(item)
          }
        }else{
          ncangwei[w-1].data.push(item)
          pre=w
        } 
      })
      
      ncangwei=ncangwei.filter(item=>item.data.length>0)
      
      var w_text=['一','二','三','四','五','六','七','八','九','十','十一','十二','十三','十四','十五']
      ncangwei.forEach((item,index)=>{
        if(item.data.length>0){
          item.name='第'+w_text[index]+'周'
          var total=0
          var money = 10000.0
          item.data.forEach(i=>{
            i.date=(new Date(i.stock_date).getMonth()+1)+'/'+(new Date(i.stock_date).getDate())
          })
        }
      })

      records = res.data.data.list
      this.setData({
        ec: {
          onInit:initChart
        },
        cangwei:ncangwei.reverse()
      })

    })
  },
  //计算周数
  getWeekNumber:function(dateString) {
    const date = new Date(dateString);
    const year = date.getFullYear();
    // 将年份的第一个周一作为第一周的开始
    const firstWeekStart = new Date(year, 0, 1);
    firstWeekStart.setDate(firstWeekStart.getDate() - firstWeekStart.getDay() + 1);
    // 计算给定日期是一年中的第几周
    const currentDate = new Date(date);
    currentDate.setDate(currentDate.getDate() - currentDate.getDay() + 1);
    let milliseconds = currentDate.getTime() - firstWeekStart.getTime();
    const weeks = Math.round(milliseconds / (7 * 24 * 60 * 60 * 1000));
    return weeks + 1; // 因为getWeek返回的是年初至今的周数，所以加1得到完整的周数
  },
  //获取今日留言
  getExp:function(){
    var list = this.data.explist
    $api.getExperience({page:this.data.page1,page_size:20}).then(res=>{
      res.data.data.list.forEach(item => {
        list.push(item)
      })
      this.setData({
        explist: list,
        total1: res.data.data.total
      })
    })
  },
  //留言分页
  next1: function () {
    if (this.data.explist.length < this.data.total1) {
      const page = this.data.page1 + 1
      this.setData({
        page1: page
      })
      this.getExp()
    }
  },
  //我的关注
  getFollow(){
    var followList = this.data.followList
    if(this.data.loading){
      followList=[]
    }
    $api.getMyFollowV3({
      page: this.data.page2, page_size: 20
    }).then(res => {
      res.data.data.list.forEach(item => {
        followList.push(item)
      })
      this.setData({
        followList: followList,
        total2:res.data.data.total,
        error:0,
        loading: 0
      })
      app.globalData.follow = 0
    })
    .catch(err=>{
      this.setData({
        error:1
      })
    })
  },
  //关注分页
  next2: function () {
    if (this.data.followList.length < this.data.total2) {
      const page = this.data.page2 + 1
      this.setData({
        page2: page
      })
      this.getFollow()
    }
  },
  tabChange(e){
      this.setData({
        cur:e.target.dataset.id
      })
      this.renew()
  },
  tabChange1(e){
    this.setData({
      cur1:e.target.dataset.id
    })
},
tapGroup(e){
  wx.navigateTo({
    url: '../avg/avg?index='+e.currentTarget.dataset.index + '&match_id=' + this.data.groups.group_win_lose_list[0].match_id +
    '&match_name=' + this.data.groups.group_win_lose_list[0].match_name,
  })
},

tapAvg(e){
  wx.navigateTo({
    url: '../avg/avg?index=0' + '&match_id=' + this.data.groups.group_win_lose_list[0].match_id +
    '&match_name=' + this.data.groups.group_win_lose_list[0].match_name,
  })
},
  //预览
  preview(e){
    wx.previewImage({
      urls: e.target.dataset.urls,
      current: e.target.dataset.src
    })
  },
  curChange(e){
    if (e.detail.source == "touch"){
        this.setData({
          cur: e.detail.current
        })
        this.renew()
    }
  },
  curChange1(e){
    if (e.detail.source == "touch"){
        this.setData({
          cur1: e.detail.current
        })
    }
  },
  renew(){
    this.setData({
      followList:[],
      explist:[],
      page1: 1,
      total1: 0,
      page2: 1,
      total2: -1
    })
    switch(this.data.cur){
      case 0:
        this.data.page1 = 1
        this.getExp()
        break;
      case 1:
        this.data.page2 = 1
        this.getFollow()
        break;
    }
  },
  pushToday(e){
    $push.pushToday(e.currentTarget.dataset)
  },
  
  pushArticleWeb(e){
    if($api.checkUserRole()){
      wx.navigateTo({
        url: '../articleweb/articleweb?id=' + e.currentTarget.dataset.id,
      })
    }
  },

  pushBaike(e){
    if($api.checkUserRole()){
      wx.navigateTo({
        url: '../detail/detail?type=百科&id=' + e.currentTarget.dataset.id,
      })
    }
  },

  pushOther(e){
    switch(e.currentTarget.dataset.id){
      case "0":{
        wx.navigateTo({
          url: '../stock/stock?type=1&stock_date='+this.data.date,
        })
      }
      break;
      case "1":{
        wx.navigateTo({
          url: '../hotuser/hotuser',
        })
      }
        break;
      case "2":{
        wx.navigateTo({
          url: '../tlb/tlb?match_id='+this.data.winLost.match_id,
        })
      }
        break;
      case "3":{
        wx.navigateTo({
          url: '../baike/baike',
        })
      }
      break;

      case "4":{
        wx.navigateTo({
          url: '../todayExp/todayExp',
        })
      }
      break;

      case "5":{
        wx.navigateTo({
          url: '../myfollow/myfollow',
        })
      }
      break;

    }
  },
  
  onShow: function (e) {
    $api.initUser()
    
    $api.getsignup().then(res => {
      this.setData({
        info: res.data.data
      })
    })
    
    if(this.data.cur == 0 && app.globalData.follow == 1){
      this.data.loading = 1
      this.data.page2    = 1
      this.data.total2   = -1,
      this.getFollow()
    }
  },
})
function initChart(canvas, width, height, dpr) {
  var xdata = [], ydata = [];
  records = records
  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: 50,
      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: {
        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;
}