import { defineComponent } from "vue";
import { ElInput, ElButton } from "element-plus";
import runtime, * as RuntimeUtils from "/src/components/live-broadcast/runtime";
import styles from "./send-message.module.less";
import runtimeModel, * as RuntimeModel from './model/runtime'
import dayjs from "dayjs";


export default defineComponent({
  data() {
    return {
      message: ''
    }
  },
  methods: {
    onKeyDown(e: any) {
      if(e.keyCode === 13 && this.message.trim() !== '') {
        this.sendMessage()
      }
    },
    async sendMessage() {
      try {
        await RuntimeUtils.sendMessage(this.message);
        const userInfo = RuntimeUtils.getSendMessageUser();
        // 添加一条消息记录
        RuntimeModel.addMessage({
          id: userInfo.id,
          name: userInfo.name,
          content: this.message,
          isSelf: true,
          sendTime: dayjs(new Date()).format('HH:mm:ss')
        })
        this.message = '';
        this.scrollToBottom();
      } catch (error) {
      }
    },
    scrollToBottom() {
      // 默认滚动到底部
      this.$nextTick(() => {
        document.querySelector('#tabList')?.scrollTo(0, document.querySelector('#messageList')?.scrollHeight || 0)
      })
    }
  },
  render() {
    return (
      <div class={styles.sendMessage}>
        <div class={styles.form}>
          <ElInput modelValue={this.message} onKeydown={this.onKeyDown} onInput={val => this.message = val} placeholder="请输入消息" />
          <ElButton disabled={!this.message} onClick={this.sendMessage} round type="primary">发送</ElButton>
        </div>
      </div>
    )
  }
});
