import config from "@/api/config.js";



/**
 * DeepSeekAsk class
 */
class DeepSeekAsk {
  constructor(userId) {
    this.userId = userId;
    this.topic = `ask/${userId}/${Date.now()}`;
    this.contents = []
    this.end = false
    this.isStart= false
  }

  ask(userText, callback){
    let that = this;
    this.end = false
    this.contents.push({type:1, content: userText,reasoning:""})
    const message = {
      topic: this.topic,
      contents: this.contents
    }
    VE_API.deep_seek.ask(message).then(({code})=> {
      console.log("用户发送消息",message)
      callback(code)
      if(code === 0){
        that.res(that)
      }
    })
  }

  /**
   * 用户主动停止
   */
  stop(){
    this.end = true
    this.isStart = false
  }

  res(that){
    console.log("----------------------开始轮询结果------------")
    VE_API.deep_seek.res({topic: this.topic}).then(({code,data})=> {
      if(code === 0){
        that.isStart = true
        // console.log("接收到消息",data.msg)
        if(data.index > -1){
          if(that.contents[that.contents.length-1].type === 2){
            that.contents[that.contents.length-1].header += data.reasoning
            that.contents[that.contents.length-1].content += data.msg
          }else{
            that.contents.push({type:2, content: data.msg, header: data.reasoning})
          }
        }
        if(!data.end){
          setTimeout((that2)=> {
            that2.res(that2)
          },1000,that)
        }else{
          that.isStart = false
          that.end = true
        }
      }
    }).catch(e => {
      that.isStart = false
      that.end = true
      console.log("轮询结果失败",e)
    })
  }

  markdownToHtml(markdown) {
    if (!markdown) {
      return '';
    }
    // 转换标题（# 到 <h1>, ## 到 <h2> 等）
    markdown = markdown.replace(/^# (.+)$/mg, '<h1>$1</h1>');
    markdown = markdown.replace(/^## (.+)$/mg, '<h2>$1</h2>');
    markdown = markdown.replace(/^### (.+)$/mg, '<h3>$1</h3>');
    markdown = markdown.replace(/^#### (.+)$/mg, '<h4>$1</h4>');
    markdown = markdown.replace(/^##### (.+)$/mg, '<h5>$1</h5>');
    markdown = markdown.replace(/^###### (.+)$/mg, '<h6>$1</h6>');

    // 转换段落（两个换行符分隔）
    markdown = markdown.replace(/\n\s*\n/g, '</p><p>');

    // 转换粗体（** 或 __）
    markdown = markdown.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>');
    markdown = markdown.replace(/__(.+?)__/g, '<strong>$1</strong>');

    // 转换斜体（* 或 _）
    markdown = markdown.replace(/\*(.+?)\*/g, '<em>$1</em>');
    markdown = markdown.replace(/_(.+?)_/g, '<em>$1</em>');

    // 转换无序列表（- 或 *）
    markdown = markdown.replace(/^- (.+)$/mg, '<li>$1</li>');
    markdown = markdown.replace(/^\* (.+)$/mg, '<li>$1</li>');
    markdown = markdown.replace(/<li>(.+?)<\/li>/g, '<ul><li>$1</li></ul>');

    // 将第一个段落元素包裹在 <p> 标签中
    markdown = `<p>${markdown}</p>`;

    // 移除多余的 <ul> 标签
    markdown = markdown.replace(/<\/ul>\s*<ul>/g, '');

    return markdown;
  }

}

export default DeepSeekAsk;
