import PageContainerBehavior from "../../core/behavior/page-container.behavior";
import { DraggableSheetBehavior, getDraggableSheetContext } from "../../core/behavior/draggableSheet.behavior";
import { login } from "../../lib/logic";
import { Post } from "../../lib/request/method";

const { shared, Easing, timing } = wx.worklet
const offset = shared(0);
const styleIds = [];

// pages/home/home.ts
import { getPatients, healthReportMethod, healthIndexMethod } from "./request";
import { toCertificationPage } from "./router";
Component({
  behaviors: [
    PageContainerBehavior,
    DraggableSheetBehavior('.draggable-sheet-wrapper'),
  ],
  lifetimes: {
    attached() { this.initFabAnimated(); }
  },
  pageLifetimes: {
    show() { this.load(); }
  },
  properties: {
    patientId: { type: String, value: '' },
    next: { type: String, value: '' },
  },
  data: {
    patients: [] as (App.Patient.Model & { isDefault: 'Y' | 'N' })[],
    patient: null as App.Patient.Model | null,

    healthId: '',
    healthReport: { data: null, message: '' },
    healthIndex: { data: [], message: '' },

    position: {} as AnyObject,
  },

  observers: {
    'patient'(model: { patientId: string }) {
      wx.setStorageSync('patientId', model.patientId);
      this._getHealthReport();
      this._getAbnormalHealthIndex();
    }
  },
  methods: {
    async load() {
      await login();
      wx.showLoading({ title: '加载中' });
      const { patient } = await getPatients(this.data.patientId);
      if (!patient) toCertificationPage();
      else this.setData({ patient });
    },

    async _getHealthReport() {
      wx.showLoading({ title: '加载中' });
      this.setData({ 'healthReport.loading': true, })
      try {
        const data = await healthReportMethod();
        this.setData({
          'healthReport.data': data,
          'healthReport.loading': false,
        });
      } catch (error) {
        this.setData({
          'healthReport.data': [],
          'healthReport.loading': false,
          'healthReport.message': error.errMsg,
        });
      }
      wx.hideLoading();
    },
    async _getAbnormalHealthIndex() {
      this.setData({ 'healthIndex.loading': true, })
      try {
        const data = await healthIndexMethod();
        this.setData({
          'healthIndex.data': data.map((item: AnyObject) => item.abnormalDesc).filter(Boolean),
          'healthIndex.loading': false,
        });
      } catch (error) {
        this.setData({
          'healthIndex.data': [],
          'healthIndex.loading': false,
          'healthIndex.message': error.errMsg,
        });
      }
    },
    onBodyModel(event: WechatMiniprogram.TouchEvent) {
      if (event.detail?.position === 'LB') { this.toReportPage(); }
      else if (event.detail?.position === 'LT') {
        const report = this.data.healthReport.data as unknown as AnyObject;
        this.setData({
          position: {
            LT: ['willillState', 'willillDegree', 'willillSocial', 'willillFunction'].map(key => {
              const title = report[`${key}Name`]
              const description = report[`${key}Description`]
              return title || description ? { title, description } : null
            }).filter(Boolean)
          },
        });
        this.showDraggableSheet();
      }
      else if (event.detail?.position === 'RT') {
        const report = this.data.healthReport.data as unknown as AnyObject;
        const get = (key: string) => ({ [key]: report[key] })
        this.setData({
          position: {
            RT: {
              ...get('constitutionGroupName'),
              ...get('constitutionGroupDefinition'),
              ...get('faceImg'),
              ...get('faceAnalysisResult'),
              ...get('tongueAnalysisResult'),
              ...get('upImg'),
              ...get('downImg'),
            }
          },
        });
        this.showDraggableSheet();
      }
      else if (event.detail?.position === 'RB') {
        const report = this.data.healthReport.data as unknown as AnyObject;
        const get = (key: string) => ({ [key]: report[key] })
        this.setData({
          position: {
            RB: {
              ...get('diagnoseSyndromeSummary'),
              ...get('diagnoseSyndromes'),
              ...get('factorItemSummary'),
              ...get('factorItems'),
            }
          },
        });
        this.showDraggableSheet();
      }
      else if (event.detail?.position === 'CT') {
        wx.showModal({
          title: '预警信息',
          content: this.data.healthIndex.data.map((item, index) => `${index + 1}、${item}`).join(''),
          showCancel: false,
        })
      }
    },

    initFabAnimated() {
      (<any>this).applyAnimatedStyle('.fab-1', () => {
        'worklet'
        return { transform: `translateY(${-offset.value}px)` };
      });
      (<any>this).applyAnimatedStyle('.fab-2', () => {
        'worklet'
        return { transform: `translateX(${-offset.value}px) translateY(${-offset.value / 2}px)` };
      });
      (<any>this).applyAnimatedStyle('.fab-3', () => {
        'worklet'
        return { transform: `translateX(${-offset.value}px) translateY(${offset.value / 2}px)` };
      });
      (<any>this).applyAnimatedStyle('.fab-4', () => {
        'worklet'
        return { transform: `translateY(${offset.value}px)` };
      });
    },
    onFabTap() {
      const value = Math.abs(offset.value - 72);
      offset.value = timing(value, { duration: 300, easing: (<any>Easing).linear }, () => {
        'worklet'
        if (offset.value > 0) offset.value = 72
      })
    },
    toChatsPage() {
      wx.navigateTo({ url: `/module/chats/pages/index/index` })
    },
    toHealthPage() {
      wx.navigateTo({ url: `/module/health/pages/home/home` })
    },
    toSchemePage() {
      const id = this.data.healthId;
      if (id) wx.navigateTo({ url: `/module/health/pages/scheme/scheme?id=${id}` })
      else wx.showToast({ title: '暂无调理方案', icon: 'none' });
    },
    toReportPage() {
      const id = this.data.healthId;
      if (id) wx.navigateTo({ url: `/module/health/pages/report/report?id=${id}` })
      else wx.showToast({ title: '暂无分析报告', icon: 'none' });
    },
    showDraggableSheet() {
      getDraggableSheetContext.call(this).scrollTo({
        size: 0.5,
        pixels: 600,
        animated: true,
        duration: 300,
        easingFunction: 'ease'
      });
    },
    hideDraggableSheet() {
      getDraggableSheetContext.call(this).scrollTo({
        size: 0,
        pixels: 600,
        animated: true,
        duration: 300,
        easingFunction: 'ease'
      });
      this.setData({ position: {} })
    }
  },
})