import * as echarts from '../../ec-canvas/echarts.min';
import request from '~/api/request';
const app = getApp();
let height = []
let weight = []
function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    title: {
      text: '身高（cm）',
      left: 'left',
      fontSize: 6
    },
    legend: {
      data: ['实际身高', '标准范围'],
      bottom: 0,
      left: 'center',
      z: 100
    },
    grid: {
      containLabel: true,
      top: '12%',
      left: '5%',
      right: '5%',
      bottom: '10%'
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      // show: false
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
      // show: false
    },
    series: [{
      name: '实际身高',
      type: 'line',
      smooth: true,
      data: height
    }, {
      name: '标准范围',
      type: 'line',
      smooth: true,
      data: [120, 130, 140, 150, 160, 170]
    }]
  };

  chart.setOption(option);
  return chart;
}

function initChart2(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart);

  var option = {
    title: {
      text: '体重（kg）',
      left: 'left', 
      fontSize: 12
    },
    legend: {
      data: ['实际体重', '标准范围'],
      bottom: 0,
      left: 'center',
      z: 100
    },
    grid: {
      containLabel: true,
      top: '12%',
      left: '5%',
      right: '5%',
      bottom: '10%'
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
      // show: false
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
      // show: false
    },
    series: [{
      name: '实际体重',
      type: 'line',
      smooth: true,
      data: weight
    }, {
      name: '标准范围',
      type: 'line',
      smooth: true,
      data: [120, 130, 140, 150, 160, 170]
    }]
  };

  chart.setOption(option);
  return chart;
}

Page({
  onShareAppMessage: function (res) {
    return {
      title: 'ECharts 可以在微信小程序中使用啦！',
      path: '/pages/index/index',
      success: function () { },
      fail: function () { }
    }
  },
  data: {
    ec: {
      onInit: ''
    },
    ec2: {
      onInit: ''
    },
    activeIndex: 0,
    sfData:{},
    sfListLength: 0,
    article:{},
    articlesLength: 0
  },

  // Helper function to strip HTML tags and convert to plain text
  stripHtml(html) {
    if (!html) return '';
    return html.replace(/<[^>]*>/g, '');
  },

  async getSfList(){
    const res = await request('patient/follow_plans', 'get', {
      page: 1,
      page_size: 10,
      type: 1
    })
    
    // Calculate days between today and plan_date
    const today = new Date()
    const planDate = new Date(res.list[0].plan_date)
    const diffTime = planDate - today
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    this.setData({
      sfListLength: res.total,
      sfData: {
        ...res.list[0],
        daysUntilPlan: diffDays
      }
    })

    const res2 = await request('patient/articles', 'get', { title: '', page: 1, page_size: 10 });
    // Convert rich text content to plain text
    const plainTextContent = this.stripHtml(res2.list[0].content);
    this.setData({
      articlesLength: res2.total,
      article: {
        ...res2.list[0],
        contentText: plainTextContent
      }
    })
  },

  async getChartData(){
    const res = await request('patient/chat/0', 'get')
    if(res.list.length > 0){
      res.list.forEach(item => {
        height.push(item.height)
        weight.push(item.weight)
      })
    }
    this.setData({
      ec: {
        onInit: initChart
      },
      ec2: {
        onInit: initChart2
      },
    })
  },
  onLoad(){
    this.getChartData()
    this.getSfList()
  },

  changeChart(e) {
    const index = e.currentTarget.dataset.index;
    console.log(index);
    this.setData({
      activeIndex: index
    })
  },

  onReady() {
  },

  toClockIn(){
    wx.navigateTo({
      url: '/pages/clockIn/index',
    })
  },
  toEmergency(){
    wx.navigateTo({
      url: '/pages/emergency/index',
    })
  },
  toArticle(){
    wx.navigateTo({
      url: '/pages/articleList/index',
    })
  },
  async toArticleDelit(){
    await wx.setStorageSync('article',JSON.stringify(this.data.article));
    wx.navigateTo({
      url: '/pages/article/index',
    })
  },
});