import * as echarts from '../../ec-canvas/echarts.min';
import request from '~/api/request';

import { heightList, weightList } from '../../assets/js/heightWeight';

const app = getApp();


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,
    xAxis: [],
    carList: [],
    carLength: 0,
    
  },
  standardHeight:[],
  standardWeight:[],
  // Helper function to strip HTML tags and convert to plain text
  stripHtml(html) {
    if (!html) return '';
    return html.replace(/<[^>]*>/g, '');
  },
  async getPersonalInfo() {
    const info = await request('patient/basic/0').then((res) => res);
    if(info.sex == 1){
      this.standardHeight = heightList.boy
      this.standardWeight = weightList.boy
    }else{
      this.standardHeight = heightList.girl
      this.standardWeight = weightList.girl
    }
  },
  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.slice(0, 3).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 = []
    const xAxis = []
    if(res.list.length > 0){
      res.list.forEach(item => {
        heightData.push(item.height)
        weightData.push(item.weight)
        xAxis.push(item.age)
      })
    }

    this.setData({
      heightData,
      weightData,
      xAxis
      
    });
    this.initHeightChart()
  },

  

  onLoad(){
    
  },

  onReady() {
    
  },
  onShow(){
    this.getSfList()
    this.getChartData()
    this.getPersonalInfo()
  },

  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 standardHeight = this.standardHeight

    let totalList = []
    standardHeight.forEach(item => {
        this.data.xAxis.forEach(item2 => {
            if(item.age == item2) {
                totalList.push(item.value)
            }
            
        })
    })
    const standardLower = totalList.map(item => item[0]);
    const standardUpper = totalList.map(item => item[1]);
    // const standardRange = standardUpper.map((up, i) => up - standardLower[i]);
  
    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 },
          grid: { containLabel: true, top: '5%', left: '5%', right: '5%', bottom: '3%' },
          tooltip: {
            show: true,
            trigger: 'axis',
            formatter: function (params) {
              const param = params[0];
              return `${param.axisValue}\n${param.seriesName}: ${param.value} cm`;
            }
          },
          xAxis: { type: 'category', boundaryGap: false, data: this.data.xAxis },
          yAxis: { x: 'center', type: 'value', splitLine: { lineStyle: { type: 'dashed' } } },
          series: [
            {
              name: '实际身高',
              type: 'line',
              smooth: true,
              data: this.data.heightData
            },
            {
              name: '标准上界',
              type: 'line',
              symbol: 'none',
              data: standardUpper,
              lineStyle: { opacity: 0 },
              stack: '标准范围',
              areaStyle: { opacity: 0 },
              tooltip: { show: true }
            },
            {
              name: '标准下界',
              type: 'line',
              symbol: 'none',
              data: standardLower,
              lineStyle: { opacity: 0 },
              stack: '标准范围',
              areaStyle: { color: 'rgba(135,206,250,0.3)' },
              tooltip: { show: true }
            }
          ]
        });
        return chart;
      });
    }
  },

  // 初始化体重图表
  initWeightChart() {
    const standardWeight = this.standardWeight

    let totalList = []
    standardWeight.forEach(item => {
        this.data.xAxis.forEach(item2 => {
            if(item.age == item2) {
                totalList.push(item.value)
            }
            
        })
    })

    const standardLower = totalList.map(item => item[0]);
    const standardUpper = totalList.map(item => item[1]);
    const standardRange = standardUpper.map((up, i) => up - standardLower[i]);
  
    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: 6 },
          grid: { containLabel: true, top: '5%', left: '5%', right: '5%', bottom: '3%' },
          tooltip: {
            show: true,
            trigger: 'axis',
            formatter: function (params) {
              const param = params[0];
              return `${param.axisValue}\n${param.seriesName}: ${param.value} kg`;
            }
          },
          xAxis: { type: 'category', boundaryGap: false, data: this.data.xAxis },
          yAxis: { x: 'center', type: 'value', splitLine: { lineStyle: { type: 'dashed' } } },
          series: [
            {
              name: '实际体重',
              type: 'line',
              smooth: true,
              data: this.data.weightData
            },
            {
              name: '标准上界',
              type: 'line',
              symbol: 'none',
              data: standardUpper,
              lineStyle: { opacity: 0 },
              stack: '标准范围',
              areaStyle: { opacity: 0 },
              tooltip: { show: true }
            },
            {
              name: '标准下界',
              type: 'line',
              symbol: 'none',
              data: standardUpper,
              lineStyle: { opacity: 0 },
              stack: '标准范围',
              areaStyle: { color: 'rgba(135,206,250,0.3)' },
              tooltip: { show: true }
            }
          ]
        });
        return chart;
      });
    }
  },
});