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: {
      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()
    },
    _start() {
      this._createMessage({
        id: `start`, type: 'system',
        payload: { title: '对话管家 已进入聊天', date: this.data._timestamp },
      }, {
        [`_next.dialogId`]: '',
        [`_next.questions`]: [],
      })
      this._next();
    },
    _end() {
      this._createMessage({
        id: `end`, type: 'system',
        payload: { title: '对话管家 已结束聊天', date: Date.now() },
      }, {
        [`_next.dialogId`]: '',
        [`_next.questions`]: [],
      })
      this.triggerEvent('next', { component: 'guide', scroll: true });
    },
    async _next() {
      const { data } = await Post(`/dialogueManage/dialog`, this.data._next);
      data.nextQuestions?.forEach((question: any, index: number) => {
        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,
              multiple: question.css === 'checkbox',
            }
          })
        } 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.dialogId`]: data.dialogId,
        [`_next.questions`]: data.nextQuestions,
      })
      this.triggerEvent('to');
    },

    _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);

    }
  }
})