import PageContainerBehavior from "../../../../core/behavior/page-container.behavior";
import TickleBehavior, { getTickleContext } from "../../../../core/behavior/tickle.behavior";

import { Post } from "../../../../lib/request/method";
import { transformHealthIndex2Ruler } from "../../tools/health-index";

// module/health/pages/status/status.ts
type ResponseData = { id: string, name: string, options: App.Health.Index.Ruler[] }[];

Component({
  behaviors: [PageContainerBehavior, TickleBehavior],
  lifetimes: {
    attached() {
      this.getData()
    }
  },
  properties: {},
  data: {
    health: [] as ResponseData,
  },
  methods: {
    async getData() {
      wx.showLoading({ title: '加载中' });
      try {
        const health = await Post<ResponseData, App.Health.Index.Data[]>(`/patientQuota/getCurQuoval`, {}, {
          transform({ data }) {
            return transformHealthIndex2Ruler(data.map(item => ({ ...item, patientQuotaRecordDTOS: [] })))
          }
        });
        this.setData({ health })
      } catch (error) {
        getTickleContext.call(this).showErrorMessage(error.errMsg, 0)
      }
      wx.hideLoading()
    },

    async onSubmit(event: WechatMiniprogram.FormSubmit) {
      const values = event.detail.value;
      const model = Object
        .entries(values)
        .filter(([, value]) => value)
        .map(([quotaId, quotaVal]) => ({ quotaId, quotaVal }))

      if (model.length) {
        wx.showLoading({ title: `提交中` })
        try {
          const health = this.data.health
          const result = await Post(`/patientQuota/updateCurQuoval`, model, {
            transform() {
              return health
                .map(h => {
                  const value = h.options.map(option => {
                    const value = values[option.id];
                    return value && value != option.value ? `${value}${option.unit}` : ''
                  }).filter(Boolean).join(' / ')
                  return value ? `${h.name}: ${value}` : ''
                })
                .filter(Boolean)
            }
          })
          console.log('[TODO]: result-->', result);
          this.getOpenerEventChannel().emit('update', result);
          wx.navigateBack()
        } catch (error) {
          getTickleContext.call(this).showErrorMessage(error.errMsg)
        }
        wx.hideLoading()
      } else {
        wx.showToast({ title: `请至少填写一项`, icon: 'error' })
      }

      // console.log('[log]:-->', event.detail.value, data);


    }
  }
})