import dayjs from "dayjs";
import { Post } from "../../../../lib/request/method";

// module/chats/components/questionnaire/questionnaire.ts

interface Message {
  id: string;
  type: 'system' | 'analysis' | 'select' | 'text' | 'report';
  payload: AnyObject;
}

interface HandleEvent {
  target: { id: string; };
  detail: AnyObject;
  type: 'next';
}

Component({
  lifetimes: {
    attached() { this._start(); }
  },
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    messages: {} as Record<number, Message>,
    lastId: '',
    _next: {
      classify: "",
      dialogId: "",
      questions: []
    } as AnyObject,

    _timestamp: Date.now(),
  },
  observers: {
    'messages.**'(messages) {
      const message = Object.values(messages).pop() as Message;
      this.setData({ lastId: message?.id });
    }
  },
  methods: {
    handle(event: HandleEvent) {
      const index = event.target.id.split('.').pop() ?? 0;
      console.log(index, event.target.id);


      const questions = this.data._next.questions;
      Object.assign(questions[index], event.detail);
      this.setData({ '_next.questions': questions })
      console.log(this.data._next);

      this._next()
    },
    async _start() {
      try {
        const count = await Post(`/patientInfoManage/rechargeUseDetail`, {}, {
          transform({ data }: any) {
            return data?.residuedCou
          }
        });
        if (count > 0) {
          this.setData({
            [`_next.classify`]: '',
            [`_next.dialogId`]: '',
            [`_next.questions`]: [],
            _timestamp: Date.now(),
          })
          this._next();
        } else {
          throw { errMsg: `您的健康分析次数已用完，请联系工作人员。` }
        }
      } catch (error) {
        this._createMessage({
          id: `system-start`, type: 'system',
          payload: { date: Date.now(), title: error.errMsg ?? `分析错误，请重试！`, }
        });
        this._end();
      }
    },
    _end() {
      this.setData({
        [`_next.classify`]: '',
        [`_next.dialogId`]: '',
        [`_next.questions`]: [],
      })
      this.triggerEvent('next', { component: 'guide', scroll: true });
    },
    async _next() {
      if (this.data._next.classify === 'tongue') {
        this._createMessage({
          id: `tongue-loading.${Date.now()}`, type: 'text',
          payload: { title: '分析中', loading: true }
        });
        this.triggerEvent('to');
      }
      try {
        const { data } = await Post(`/dialogueManage/dialog`, this.data._next);
        data.nextQuestions?.forEach((question: any, index: number) => {
          if (question.classify === 'tongue_result') {
            this._updateMessage({
              id: `${question.classify}.${question.id}.${index}`, type: 'text',
              payload: { title: question.content }
            })
          } else {
            if (question.css === 'tongue') {
              this._createMessage({
                id: `${question.classify}.${question.id}.${index}`, type: 'analysis',
                payload: { title: question.title }
              });
            } else if (question.css === 'text') {
              this._createMessage({
                id: `${question.classify}.${question.id}.${index}`, type: 'text',
                payload: { title: question.content }
              });
            } else if (['select', 'checkbox'].includes(question.css)) {
              this._createMessage({
                id: `${question.classify}.${question.id}.${index}`, type: 'select',
                payload: {
                  title: question.title,
                  options: question.options.map((item: AnyObject) => {
                    if (Array.isArray(item.options)) {
                      item.options = item.options.map(item => {
                        return { ...item, hide: item.css === 'hide' }
                      })
                    }
                    return { ...item, hide: item.css === 'hide' }
                  }),
                  multiple: question.css === 'checkbox',
                  required: question.required
                }
              })
            } else if (question.over) {
              return this._end();
            }
          }
        });
        if (data.classify === 'report') {
          const diff = dayjs().diff(this.data._timestamp, 'm');
          this._createMessage({
            id: 'report', type: 'report',
            payload: {
              title: `本次问答已结束，历史${diff || 1}分钟，非常感谢您的配合！请查看您本次的健康评估情况。`,
              url: `/module/health/pages/report/report?id=${data.healthAnalysisReportId}`
            }
          })
        }
        if (data.over) return this._end();

        this.setData({
          [`_next.classify`]: data.classify,
          [`_next.dialogId`]: data.dialogId,
          [`_next.questions`]: data.nextQuestions,
        })
        this.triggerEvent('to');
      } catch (error) {
        if (this.data._next.classify === 'tongue') {
          this._updateMessage({
            id: `tongue-error-${Date.now()}`, type: 'text',
            payload: { title: error.errMsg ?? `图像检测失败，请重新拍摄上传`, }
          });
          this.triggerEvent('to');
          setTimeout(() => this._start(), 20);
        } else {
          const date = Date.now();
          this._createMessage({
            id: `system-${date}`, type: 'system',
            payload: { date, title: error.errMsg ?? `分析错误，请重试！`, }
          });
          this._end();
        }
      }
    },

    _createMessage(body: Message, data?: Record<string, any>) {
      const messages = this.data.messages;
      const index = Object.keys(messages).length;
      this.setData({
        [`messages.${index}`]: body,
        ...data,
      })

      console.log(this.data.messages);

    },

    _updateMessage(body: Message) {
      const messages = this.data.messages;
      const index = Object.keys(messages).length;
      this.setData({
        [`messages.${index - 1}`]: body,
      })
    },
  }
})