import * as echarts from '../../ec-canvas/echarts.min';
import request from '~/api/request';
const app = getApp();

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

  var option = {
    title: {
      text: '',
      left: 'left',
      fontSize: 6
    },
    legend: {
      data: ['实际身高', '标准范围'],
      bottom: 0,
      left: 'center',
      z: 100
    },
    grid: {
      containLabel: true,
      top: '5%',
      left: '1%',
      right: '5%',
      bottom: '10%'
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['出生', '1月', '2月', '3月', '4月', '5月'],
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '实际身高',
      type: 'line',
      smooth: true,
      data: []
    }, {
      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
  });
  canvas.setChart(chart);

  var option = {
    title: {
      text: '',
      left: 'left', 
      fontSize: 12
    },
    legend: {
      data: ['实际体重', '标准范围'],
      bottom: 0,
      left: 'center',
      z: 100
    },
    grid: {
      containLabel: true,
      top: '5%',
      left: '1%',
      right: '5%',
      bottom: '10%'
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: ['出生', '1月', '2月', '3月', '4月', '5月'],
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '实际体重',
      type: 'line',
      smooth: true,
      data: []
    }, {
      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: {
      lazyLoad: true
    },
    ec2: {
      lazyLoad: true
    },
    activeIndex: 0,
    sfData:{},
    sfListLength: 0,
    articles:[],
    articlesLength: 0,
    heightData: [],
    weightData: [],
    heightChart: null,
    weightChart: null,
    carList: [],
    carLength: 0
  },

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

  async getSfList(){
    
    this.followPlans()
    this.getArticleList()
    this.getCarList()
  },
  async followPlans(){ 
    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
      }
    })
  },
  async getArticleList(){
    const res2 = await request('patient/articles', 'get', { title: '', page: 1, page_size: 2 });
    // Convert rich text content to plain text
    const plainTextContent = this.stripHtml(res2.list[0].content);
    const articleList = res2.list.map(item => {
      return {
        ...item,
        contentText: this.stripHtml(item.content)
      }
    })
    this.setData({
      articlesLength: res2.total,
      articles: articleList
    })
  },

  async getCarList() { 
    const res3 = await request('patient/medicine_records', 'get', {
      time_type: 1,
      status: 0,
      page: 1,
      page_size: 10
    })
    const carList = res3.list.map(item => {
      item.detail = JSON.parse(item.detail)
      return item
    })
    setTimeout(() => {
      this.setData({
        carLength: res3.total,
        carList: carList
      })
    })
  },

  async medicineRecord(e){
    const {id, status} = e.currentTarget.dataset
    if(status == 1){
      await request('patient/medicine_record/'+id, 'put', {})
      wx.showToast({
        type: 'success',
        title: '打卡成功',
      })
      this.getCarList()
    }
  },

  async getChartData(){
    const res = await request('patient/chat/0', 'get')
    const heightData = []
    const weightData = []
    
    if(res.list.length > 0){
      res.list.forEach(item => {
        heightData.push(item.height)
        weightData.push(item.weight)
      })
    }

    this.setData({
      heightData,
      weightData
    }, () => {
      this.initCharts();
    });
  },

  initCharts() {
    // 初始化身高图表
    if (!this.heightChart) {
      const chart1 = this.selectComponent('#mychart-dom-height');
      if (chart1) {
        chart1.init((canvas, width, height, dpr) => {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
          });
          canvas.setChart(chart);

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

          chart.setOption(option);
          this.heightChart = chart;
          return chart;
        });
      }
    }

    // 初始化体重图表
    if (!this.weightChart) {
      const chart2 = this.selectComponent('#mychart-dom-weight');
      if (chart2) {
        chart2.init((canvas, width, height, dpr) => {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height,
            devicePixelRatio: dpr
          });
          canvas.setChart(chart);

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

          chart.setOption(option);
          this.weightChart = chart;
          return chart;
        });
      }
    }
  },
  toBack(){
    wx.navigateBack({
      delta: 1
    })
  },
  onLoad(){
    // this.getSfList()
    // setTimeout(() => {
    //   this.getChartData().then(() => {
    //     if (this.data.activeIndex === 0) {
    //       this.initHeightChart();
    //     } else {
    //       this.initWeightChart();
    //     }
    //   });
    // }, 500);
  },

  onReady() {
    // setTimeout(() => {
    //   this.getChartData().then(() => {
    //     if (this.data.activeIndex === 0) {
    //       this.initHeightChart();
    //     } else {
    //       this.initWeightChart();
    //     }
    //   });
    // }, 500);
  },

  changeChart(e) {
    const index = e.currentTarget.dataset.index;
    if(index == this.data.activeIndex){
      return
    }
    this.setData({
      activeIndex: index
    }, () => {
      setTimeout(() => {
        if (index == 0) {
          this.initHeightChart();
        } else {
          this.initWeightChart();
        }
      }, 100);
    });
  },

  toClockIn(){
    wx.navigateTo({
      url: '/pages/clockIn/index',
    })
  },
  toEmergency(){
    wx.navigateTo({
      url: '/pages/emergency/index',
    })
  },
  toArticle(){
    wx.navigateTo({
      url: '/pages/articleList/index',
    })
  },
  async toArticleDelit(e){
    const index = e.currentTarget.dataset.index;
    await wx.setStorageSync('article',JSON.stringify(this.data.articles[index]));
    wx.navigateTo({
      url: '/pages/article/index',
    })
  },

  onUnload() {
    // 页面卸载时销毁图表实例
    if (this.heightChart) {
      this.heightChart.dispose();
      this.heightChart = null;
    }
    if (this.weightChart) {
      this.weightChart.dispose();
      this.weightChart = null;
    }
  },

  // 初始化身高图表
  initHeightChart() {
    const chartComp = this.selectComponent('#mychart-dom-height');
    if (chartComp) {
      chartComp.init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr });
        canvas.setChart(chart);
        chart.setOption({
          title: { text: '', left: 'left', fontSize: 6 },
          legend: { data: ['实际身高', '标准范围'], bottom: 0, left: 'center', z: 100 },
          grid: { containLabel: true, top: '5%', left: '1%', right: '5%', bottom: '10%' },
          tooltip: { show: true, trigger: 'axis' },
          xAxis: { type: 'category', boundaryGap: false, data: ['出生', '1月', '2月', '3月', '4月', '5月'] },
          yAxis: { x: 'center', type: 'value', splitLine: { lineStyle: { type: 'dashed' } } },
          series: [
            { name: '实际身高', type: 'line', smooth: true, data: this.data.heightData },
            { name: '标准范围', type: 'line', smooth: true, data: [120, 130, 140, 150, 160, 170] }
          ]
        });
        return chart;
      });
    }
  },

  // 初始化体重图表
  initWeightChart() {
    const chartComp = this.selectComponent('#mychart-dom-weight');
    if (chartComp) {
      chartComp.init((canvas, width, height, dpr) => {
        const chart = echarts.init(canvas, null, { width, height, devicePixelRatio: dpr });
        canvas.setChart(chart);
        chart.setOption({
          title: { text: '', left: 'left', fontSize: 12 },
          legend: { data: ['实际体重', '标准范围'], bottom: 0, left: 'center', z: 100 },
          grid: { containLabel: true, top: '5%', left: '1%', right: '5%', bottom: '10%' },
          tooltip: { show: true, trigger: 'axis' },
          xAxis: { type: 'category', boundaryGap: false, data: ['出生', '1月', '2月', '3月', '4月', '5月'] },
          yAxis: { x: 'center', type: 'value', splitLine: { lineStyle: { type: 'dashed' } } },
          series: [
            { name: '实际体重', type: 'line', smooth: true, data: this.data.weightData },
            { name: '标准范围', type: 'line', smooth: true, data: [120, 130, 140, 150, 160, 170] }
          ]
        });
        return chart;
      });
    }
  },
});