<template>
  <div class="pocAi">
    <bar tit="智能学伴"></bar>
    <div class="pa_background">
      <img src="../../assets/images/pocAiClassroom/bg3.png" />
    </div>

    <div class="pa_goIndex" v-if="chatStatusType == 5">
      <span @click.stop="courseSelection()">{{ userInfo.userId?'開始學習':'開始選課' }}</span>
    </div>
    <div class="pa_chatArea" v-if="!showOpeningRemarks">
      <div class="pa_ca_chat" v-loading="loading">
        <div class="pa_ca_c_list" ref="chatListRef">
          <div v-for="(item, index) in chatList" :key="index">
            <div class="userChat" v-if="item.content">
              <div class="uc_left">
                <div class="chatName">科科</div>
                <div class="chatMessage">
                  <span v-text="item.content"></span>
                  <div class="cm_btnArea">
                    <span @click.stop="copy(item.content)">
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path
                          fill-rule="evenodd"
                          clip-rule="evenodd"
                          d="M2.76904 1.3171C2.76904 0.588877 3.35938 -0.00146484 4.08761 -0.00146484H10.6804C11.4087 -0.00146484 11.999 0.588876 11.999 1.3171V7.90992C11.999 8.63814 11.4087 9.22849 10.6804 9.22849H4.08761C3.35938 9.22849 2.76904 8.63814 2.76904 7.90992V1.3171ZM4.08761 0.987458C3.90555 0.987458 3.75797 1.13504 3.75797 1.3171V7.90992C3.75797 8.09198 3.90555 8.23956 4.08761 8.23956H10.6804C10.8625 8.23956 11.0101 8.09198 11.0101 7.90992V1.3171C11.0101 1.13504 10.8625 0.987458 10.6804 0.987458H4.08761Z"
                          fill="#333333"
                        />
                        <path
                          fill-rule="evenodd"
                          clip-rule="evenodd"
                          d="M1.31856 3.75748C1.13651 3.75748 0.988923 3.90506 0.988923 4.08712V10.6799C0.988923 10.862 1.13651 11.0096 1.31856 11.0096H7.91139C8.09344 11.0096 8.24103 10.862 8.24103 10.6799V9.85584C8.24103 9.58275 8.46241 9.36138 8.73549 9.36138C9.00857 9.36138 9.22995 9.58275 9.22995 9.85584V10.6799C9.22995 11.4082 8.63961 11.9985 7.91139 11.9985H1.31856C0.590342 11.9985 0 11.4082 0 10.6799V4.08712C0 3.3589 0.590341 2.76855 1.31856 2.76855H2.14267C2.41575 2.76855 2.63713 2.98993 2.63713 3.26302C2.63713 3.5361 2.41575 3.75748 2.14267 3.75748H1.31856Z"
                          fill="#333333"
                        />
                      </svg>
                    </span>
                  </div>
                </div>
              </div>
              <div class="uc_right">
                <el-avatar
                  class="chatAvatar"
                  :src="require('../../assets/images/pocAiClassroom/defaultAvatar.png')"
                ></el-avatar>
              </div>
            </div>
            <div class="aiChat">
              <div class="ac_left">
                <el-avatar
                  class="chatAvatar"
                  :src="require('../../assets/images/pocAiClassroom/character1.png')"
                ></el-avatar>
              </div>
              <div class="ac_right">
                <div class="chatName"><span>圆鼓鼓的大胖鱼</span></div>

                <div class="chatMessage" v-if="[0, 2, 3].includes(item.chatStatusType)">
                  <div v-if="item.chatStatusType == 0">
                    <div class="chatStatusMessage">
                      為咗更了解你同提供更啱你嘅幫助，我想先問你幾個問題：你而家讀緊邊一級呀？🎓
                    </div>
                    <div class="chatStatusMessageInputArea">
                      <span>年级：</span>
                      <el-select
                        class="chatStatusMessageInputAreaSelect"
                        v-model="choseGrade"
                        placeholder="快来选择你的年级"
                        :disabled="chatStatusType != 0"
                        @change="gradeChange()"
                      >
                        <el-option
                          v-for="(item, index) in gradeList"
                          :disabled="![6].includes(index)"
                          :key="index"
                          :label="item"
                          :value="item"
                        >
                        </el-option>
                      </el-select>
                    </div>
                  </div>
                  <div v-if="item.chatStatusType == 2">
                    <div class="csm_message">
                      <span>明白晒，而家我對你熟悉多咗喇，噉我哋宜家可以開始做啲咩呢？ </span>
                      <span>
                        💬開始聊天：如果你想要隨意啲，我哋可以邊聊邊學，你可以問我任何學習上嘅問題，或者分享下你最近學到嘅有趣知識。</span
                      >
                      <span
                        >📚開始選課：如果你想開始系統噉學習，我哋可以選擇一個具體嘅科目和章節，我會根據你嘅需要提供詳細嘅講解，用你最喜歡嘅講解方式嚟幫你學習，令到學習過程更加開心。</span
                      >
                      <span>
                        你想要點樣開始呢？係想隨性啲聊天，定係有目標噉學習特定嘅內容？揀選你嘅方式，我哋一齊開始啦！🌟</span
                      >
                    </div>
                    <div class="chatStatusMessageInputArea" v-if="chatStatusType == 2">
                      <span class="csmia_btn" @click.stop="goChat()">開始聊天</span>
											<span class="csmia_btn" @click.stop="courseSelection()">{{ userInfo.userId?'開始學習':'開始選課' }}</span>
                    </div>
                  </div>

                  <div v-if="item.chatStatusType == 3">
                    <div class="chatStatusMessage">好嘞，咁我哋就一齊嚟揀揀你今日想學嘅科目、教材同埋章節啦~📔</div>
										<div class="csm_inputArea">
											<div class="csm_ia_item">
												<span>学科</span>
												<el-select
                        class="chatStatusMessageInputAreaSelect"
												style="width: 100%;margin-top: 5px;"
                        v-model="type3Form.subject"
                        placeholder="请选择授课科目"
                        :disabled="chatStatusType != 3"
                      >
                        <el-option
                          v-for="(item, index) in subjectList"
                          :disabled="item.disabled"
                          :key="index"
                          :label="item.label"
                          :value="item.label"
                        >
                        </el-option>
                      </el-select>
											</div>

											<div class="csm_ia_item">
												<span>章节</span>
												<el-select
                        class="chatStatusMessageInputAreaSelect"
                        v-model="type3Form.chapter"
												style="width: 100%;margin-top: 5px;"
                        placeholder="请选择授课章节"
                        :disabled="chatStatusType != 3"
                      >
                        <el-option
                          v-for="(item, index) in classList"
                          :disabled="item.disabled"
                          :key="index"
                          :label="item.title"
                          :value="index"
                        >
                        </el-option>
                      </el-select>
											</div>

											<div class="csm_ia_item">
												<span>版本</span>
												<el-select
                        class="chatStatusMessageInputAreaSelect"
                        v-model="type3Form.edition"
												style="width: 100%;margin-top: 5px;"
                        placeholder="请选择授课版本"
                        :disabled="chatStatusType != 3"
                      >
                        <el-option
                          v-for="(item, index) in editionList"
                          :disabled="item.disabled"
                          :key="index"
                          :label="item.label"
                          :value="item.label"
                        >
                        </el-option>
                      </el-select>
											</div>

											<div class="csm_ia_btnArea">
												<span @click.stop="resetType3Form()">重置</span>
												<span @click.stop="type3FormSubmit()">開始學習</span>
												
											</div>
										</div>
                  </div>
                </div>
                <div class="chatMessage" v-loading="item.loading" :style="item.loading ? 'border:none;padding:20px;border-radius:8px;overflow:hidden' : ''" v-else>
                  <span v-html="item.aiContent"></span>
                  <div class="cm_btnArea">
                    <span @click.stop="copy(item.aiContent)">
                      <svg width="12" height="12" viewBox="0 0 12 12" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path
                          fill-rule="evenodd"
                          clip-rule="evenodd"
                          d="M2.76904 1.3171C2.76904 0.588877 3.35938 -0.00146484 4.08761 -0.00146484H10.6804C11.4087 -0.00146484 11.999 0.588876 11.999 1.3171V7.90992C11.999 8.63814 11.4087 9.22849 10.6804 9.22849H4.08761C3.35938 9.22849 2.76904 8.63814 2.76904 7.90992V1.3171ZM4.08761 0.987458C3.90555 0.987458 3.75797 1.13504 3.75797 1.3171V7.90992C3.75797 8.09198 3.90555 8.23956 4.08761 8.23956H10.6804C10.8625 8.23956 11.0101 8.09198 11.0101 7.90992V1.3171C11.0101 1.13504 10.8625 0.987458 10.6804 0.987458H4.08761Z"
                          fill="#333333"
                        />
                        <path
                          fill-rule="evenodd"
                          clip-rule="evenodd"
                          d="M1.31856 3.75748C1.13651 3.75748 0.988923 3.90506 0.988923 4.08712V10.6799C0.988923 10.862 1.13651 11.0096 1.31856 11.0096H7.91139C8.09344 11.0096 8.24103 10.862 8.24103 10.6799V9.85584C8.24103 9.58275 8.46241 9.36138 8.73549 9.36138C9.00857 9.36138 9.22995 9.58275 9.22995 9.85584V10.6799C9.22995 11.4082 8.63961 11.9985 7.91139 11.9985H1.31856C0.590342 11.9985 0 11.4082 0 10.6799V4.08712C0 3.3589 0.590341 2.76855 1.31856 2.76855H2.14267C2.41575 2.76855 2.63713 2.98993 2.63713 3.26302C2.63713 3.5361 2.41575 3.75748 2.14267 3.75748H1.31856Z"
                          fill="#333333"
                        />
                      </svg>
                    </span>
                  </div>
                  <!-- <template v-html="item.aiContent"></template> -->
                </div>
                <div class="ac_r_btnArea">
                  <div class="ac_r_ba_box" v-if="item.chatStatusType == 1">
                    <span
                      :class="[chosePleaseList.includes(item) ? 'ac_r_ba_boxActive' : '']"
                      v-for="(item, index) in pleaseList"
                      :key="index"
                      @click.stop="chosePlease(item)"
                      >{{ item }}</span
                    >
                  </div>
                  <!-- <span @click.stop="checkFile()">查看文件</span> -->
                  <!-- <span @click.stop="sendChat('A')">A：不知道</span>
                  <span @click.stop="sendChat('B')">B：选A</span>
                  <span @click.stop="sendChat('C')">C：选B</span> -->
                </div>
                <!-- <div class="ac_r_time">2024-08-26 14:31:45</div> -->
              </div>
            </div>
          </div>
        </div>
        <div class="pa_ca_c_bottom">
          <div class="pa_ca_c_b_inputArea">
            <el-input
              class="pa_ca_c_b_ia_input"
              v-model="chatValue"
              ref="textAreaRef"
              placeholder="请在此输入您想了解的内容"
              :disabled="source != null || isChatStatus"
            ></el-input>
            <!-- <textarea
              id="myTextarea"
              ref="textAreaRef"
              min-rows="1"
              max-rows="5"
              v-model="chatValue"
              placeholder="你有任何想法，可以随时告诉我呀"
              autosize="none"
              :disabled="source != null"
            ></textarea> -->
            <div class="pa_ca_c_b_btnArea">
              <span :class="['pa_ca_c_b_ba_btn', source ? 'pa_ca_c_b_ba_btnDisabled' : '']" @click="sendChat">
                <svg
                  t="1724748020468"
                  class="icon"
                  viewBox="0 0 1024 1024"
                  version="1.1"
                  xmlns="http://www.w3.org/2000/svg"
                  p-id="7309"
                  width="200"
                  height="200"
                >
                  <path
                    d="M931.392 11.264L45.12 530.688c-28.736 16.896-43.52 39.424-45.12 61.248v8.128c2.048 26.112 23.04 49.984 61.632 60.416l171.968 46.592a34.304 34.304 0 0 0 41.28-25.536 35.584 35.584 0 0 0-23.808-43.136L79.68 592l873.408-511.872-95.232 703.488c-1.408 10.432-9.152 15.68-18.752 12.992l-365.632-100.288 296.32-305.856a36.416 36.416 0 0 0 0-50.24 33.728 33.728 0 0 0-48.704 0l-324.8 335.36a110.72 110.72 0 0 0-7.872 9.088 35.52 35.52 0 0 0-16.128 30.784 104 104 0 0 0-5.248 32.64v206.4c0 49.664 53.568 79.168 93.568 51.712l166.272-114.368c10.24-6.976 16-19.136 15.232-31.872a35.712 35.712 0 0 0-19.2-29.504 33.28 33.28 0 0 0-34.24 2.304L435.84 937.856v-178.432l385.472 105.6c49.6 13.632 97.472-19.072 104.576-71.808l97.152-717.568c8.448-60.48-40-94.72-91.648-64.384z"
                    p-id="7310"
                  ></path>
                </svg>
              </span>
              <!-- <el-button
                class="pa_ca_c_b_ba_btn"
                type="primary"
                @click="sendChat"
                >发送</el-button
              > -->
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="pa_openingRemarks" v-if="showOpeningRemarks" @click.stop="openingRemarksAllFn()">
      <div class="pa_or_character">
        <img :src="require('../../assets/images/pocAiClassroom/character1.png')" />
      </div>
      <div class="pa_or_bottom">
        <span>
          <span v-if="typeof openingRemarksMessage[0]=='object'" v-for="(item, index) in openingRemarksMessage[0]" :key="0 + '-' + index" v-text="item"></span>
					<span v-if="typeof openingRemarksMessage[0]!='object'" v-text="openingRemarksMessage[0]"></span>
        </span>
        <span>
          <span v-if="typeof openingRemarksMessage[1]=='object'" v-for="(item, index) in openingRemarksMessage[1]" :key="1 + '-' + index" v-text="item"></span>
					<span v-if="typeof openingRemarksMessage[1]!='object'" v-text="openingRemarksMessage[1]"></span>
        </span>
        <span>
          <span v-if="typeof openingRemarksMessage[2]=='object'" v-for="(item, index) in openingRemarksMessage[2]" :key="2 + '-' + index" v-text="item"></span>
					<span v-if="typeof openingRemarksMessage[2]!='object'" v-text="openingRemarksMessage[2]"></span>
        </span>
      </div>
    </div>
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid'
import MarkdownIt from 'markdown-it'
import { getChatListRequest, insertChatListRequest, aiChatRequest, aiRoleChatRequest } from '@/api/pocAiClassroom'
import bar from './component/bar.vue'

export default {
  data() {
    return {
      userId: this.$store.state.user.userinfo.userid,
      org: this.$store.state.user.userinfo.org,
      oid: this.$store.state.user.userinfo.organizeid,
      showOpeningRemarks: true,
      chatValue: '',
      source: null,
      loading: false,
      chatList: [],
      openingRemarksMessage: [[], [], []],
      isAllOpeningRemarks: false,
      chatStatusType: 0,
      isChatStatus: true,
      gradeList: ['小一', '小二', '小三', '小四', '小五', '小六', '中一', '中二', '中三', '中四', '中五', '中六'],
      subjectList: [
        // { value: 0, label: '语文' },
        // { value: 1, label: '数学' },
        // { value: 2, label: '英语' },
        // { value: 3, label: '物理' },
        // { value: 4, label: '化学' },
        // { value: 5, label: '生物' },
        // { value: 6, label: '历史' },
        // { value: 7, label: '地理' },
        // { value: 8, label: '政治' }
        { value: 0, label: '中國語文', disabled: true },
        { value: 1, label: '英國語文 ', disabled: true },
        { value: 2, label: '數學', disabled: true },
        { value: 3, label: '公民與社會發展', disabled: true },
        { value: 4, label: '科學', disabled: false },
        { value: 5, label: '物理', disabled: true },
        { value: 6, label: '化學', disabled: true },
        { value: 7, label: '生物', disabled: true },
        { value: 8, label: '中國歷史', disabled: true }
      ],
      editionList: [
        { value: 0, label: '牛津大學', disabled: false },
        { value: 1, label: '聯合培進', disabled: true }
        // { value: 0, label: "人教版" },
        // { value: 1, label: "教科版" },
        // { value: 2, label: "北师大版" },
        // { value: 3, label: "苏教版" },
        // { value: 4, label: "沪教版" },
        // { value: 5, label: "浙教版" },
        // { value: 6, label: "冀教版" },
        // { value: 7, label: "鲁教版" },
        // { value: 8, label: "人教A版" },
        // { value: 9, label: "人教B版" }
      ],
			classList: [
        {
          title: '第一章：科學入門',
					disabled: true,
          allClass: [
            {
              title: '學習科學',
              type: 0,
              isComplete: true,
              subject: 4,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8741724834676182.png'
            },
            {
              title: '科學的實踐',
              type: 0,
              subject: 4,
              isComplete: true,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8731724834767532.png'
            },
            {
              title: '實驗室安全',
              type: 0,
              subject: 4,
              isComplete: false,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8721724834685472.png'
            },
            {
              title: '實驗室儀器及基本實驗技巧',
              type: 0,
              subject: 4,
              isComplete: false,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8751724834771676.png'
            },
            {
              title: '綜合練習',
              type: 1,
              subject: 4,
              isComplete: false,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8711724834666052.png'
            }
          ]
        },
        {
          title: '第二章：水',
					disabled: false,
          allClass: [
            {
              title: '水的物熊變化',
              type: 0,
              subject: 4,
              isComplete: true,
							disabled:false,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8761724834777931.png'
            },
            {
              title: '水循環',
              type: 0,
              subject: 4,
              isComplete: true,
							disabled:false,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8771724834845597.png'
            },
            {
              title: '溶解',
              type: 0,
              subject: 4,
              isComplete: true,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8781724834847977.png'
            },
            {
              title: '水的淨化',
              type: 0,
              subject: 4,
              isComplete: true,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8791724834873373.png'
            },
            {
              title: '食水的進一步處理',
              type: 0,
              subject: 4,
              isComplete: false,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8761724834777931.png'
            },
            {
              title: '節約用水和水污染',
              type: 0,
              subject: 4,
              isComplete: false,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8771724834845597.png'
            },
            {
              title: '綜合練習',
              type: 1,
              subject: 4,
              isComplete: false,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8721724834685472.png'
            },
          ]
        },
        {
          title: '第三章：观察生物',
					disabled: true,
          allClass: [
            {
              title: '生物',
              type: 0,
              isComplete: true,
              subject: 4,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8741724834676182.png'
            },
            {
              title: '生物的分類',
              type: 0,
              subject: 4,
              isComplete: true,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8731724834767532.png'
            },
            {
              title: '檢索表',
              type: 0,
              subject: 4,
              isComplete: false,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8721724834685472.png'
            },
            {
              title: '生物多樣性',
              type: 0,
              subject: 4,
              isComplete: false,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8751724834771676.png'
            },
            {
              title: '綜合練習',
              type: 1,
              subject: 4,
              isComplete: false,
							disabled:true,
              image: 'https://ccrb.s3.cn-northwest-1.amazonaws.com.cn/%E5%9B%BE%E7%89%8711724834666052.png'
            }
          ]
        }
      ],
      pleaseList: [
        '講解細致',
        '講很多不同的例子',
        '講一些故事和笑話',
        '提很多問题，啟發思考',
        '提供具體的圖像和視频',
        '提供詳細的操作示範',
        '提供鼓勵和表揚'
      ],
      chosePleaseList: [],
      choseGrade: '',
      userInfo: {
        grade: '',
        pleaseList: [],
				subject: '',
        chapter: '',
        edition: '',
				userName:"科科",
				choseCharacter:0,
				userAvatar: require('../../assets/images/pocAiClassroom/defaultAvatar.png'),
      },
      type3Form: {
        subject: '',
        chapter: '',
        edition: ''
      }
    }
  },
  components: {
    bar
  },
  methods: {
    chatListScrollBottom() {
      this.$nextTick(() => {
        this.$refs.chatListRef.scrollTop = this.$refs.chatListRef.scrollHeight
      })
    },
    sendChat(_text = this.chatValue) {
      if ([0, 1].includes(this.chatStatusType)) {
        if ([0].includes(this.chatStatusType)) {
          this.chatStatusType = 1
        } else if ([1].includes(this.chatStatusType)) {
          this.chatStatusType = 2
        }

        this.startChat()
        return
      }
      if (this.source) return this.$toast('还在对话中，请稍等')
      if (typeof _text !== 'string') _text = this.chatValue
      if (!_text.trim()) return
      this.chatValue = ''
      var OpenCC = require('opencc-js')
      let converter = OpenCC.Converter({
        from: 'cn',
        to: 'hk'
      })
      const _uuid = uuidv4()
      this.chatList.push({
        role: 'user',
        content: `${_text}`,
        uid: _uuid,
        AI: 'AI',
        aiContent: '',
        oldContent: '',
        isShowSynchronization: false,
        filename: '',
        index: this.chatList.length,
        is_mind_map: false,
        createtime: new Date().toLocaleString().replaceAll('/', '-'),
        loading: true
      })
      this.chatListScrollBottom()

      // 连续对话设置
      let _historyMessage = []

      _historyMessage.push({ role: 'user', content: _text })

      let params = {
        assistant_id: '1601e39b-6dbf-11ef-8ce0-12e77c4cb76b',
        userId: this.userId,
        message: _text,
        session_name: `${_uuid}-pocAi-md`,
        uid: _uuid,
        file_ids: [],
        model: 'gpt-4o-2024-08-06'
      }

      aiRoleChatRequest(params)
        .then(res => {
          if (converter(res.FunctionResponse.result) == converter('发送成功')) {
          } else {
            console.log(res.FunctionResponse.result)
          }
        })
        .catch(e => {
          console.log(e)
        })
      this.getAtAuContent(_uuid)
    },
    getAtAuContent(_uid) {
      this.source = new EventSource(`https://gpt4.cocorobo.cn/question/${_uid}`)
      let _allText = ''
      let _mdText = ''
      const md = new MarkdownIt()
      this.source.onmessage = _e => {
        let _eData = JSON.parse(_e.data)
        if (_eData.content.replace("'", '').replace("'", '') == '[DONE]') {
          let _result = []
          if ('result' in _eData) {
            _result = _eData.result
            for (let i = 0; i < _result.length; i++) {
              _mdText = _mdText.replace(_result[i].text, _result[i].fileName)
            }
          }
          _mdText = _mdText.replace('_', '')
          this.chatList.find(i => i.uid == _uid).aiContent = _mdText
          this.chatList.find(i => i.uid == _uid).isalltext = true
          this.chatList.find(i => i.uid == _uid).isShowSynchronization = true
          this.chatList.find(i => i.uid == _uid).loading = false
          this.source.close()
          this.source = null
          this.chatListScrollBottom()
          // this.insertChat(_uid);
        } else {
          // _index += 1;
          let _text = _eData.content.replace("'", '').replace("'", '')
          if (_allText == '') {
            _allText = _text.replace(/^\n+/, '') //去掉回复消息中偶尔开头就存在的连续换行符
          } else {
            _allText += _text
          }
          _mdText = _allText + '_'
          _mdText = _mdText.replace(/\\n/g, '\n')
          _mdText = _mdText.replace(/\\/g, '')

          if (_allText.split('```').length % 2 == 0) _mdText += '\n```\n'
          //转化返回的回复流数据
          _mdText = md.render(_mdText)
          // if (_index == 10) {
          this.chatList.find(i => i.uid == _uid).aiContent = _mdText
          this.chatList.find(i => i.uid == _uid).loading = false
          this.chatListScrollBottom()
          // _index = 0;
          // }
          // 处理流数据
        }
      }
    },
    //保存消息
    insertChat(_uid) {
      if (_uid == '') return
      let _data = this.chatList.find(i => i.uid == _uid)
      if (!_data) return
      let params = {
        userId: this.userId,
        userName: 'qgt',
        groupId: 'qwertyuiop-poc',
        answer: _data.aiContent,
        problem: _data.content,
        file_id: _data.fileid ? _data.fileid : '',
        alltext: _data.aiContent,
        type: 'chat',
        filename: _data.filename,
        session_name: `pocAi-md` //这是对话记录位置
      }
      insertChatListRequest(params).then(res => {})
    },
    // 获取对应的聊天记录
    getChatList() {
      return new Promise((resolve, reject) => {
        if (this.loading) return this.$toast('请稍等...')
        this.chatList = []
        this.loading = true
        let params = {
          userid: this.userId,
          groupid: 'qwertyuiop-poc',
          // session_name:``
          session_name: `pocAi-md`
        }
        getChatListRequest(params)
          .then(res => {
            let _data = JSON.parse(res.FunctionResponse)
            if (_data.length > 0) {
              let _chatList = []
              for (let i = 0; i < _data.length; i++) {
                _chatList.push({
                  loading: false,
                  role: 'user',
                  content: _data[i].problem,
                  uid: _data[i].id,
                  AI: 'AI',
                  aiContent: _data[i].answer,
                  oldContent: _data[i].answer,
                  isShowSynchronization: false,
                  filename: _data[i].filename,
                  index: i,
                  is_mind_map: false,
                  fileid: _data[i].fileid
                })
              }
              this.chatList = _chatList
              this.loading = false
            } else {
              //没有对话记录
              this.loading = false
            }
            this.chatListScrollBottom()
            resolve()
          })
          .catch(err => {
            console.log(err)
            this.$toast.fail('获取对话记录失败')
            this.loading = false
            resolve()
          })
      })
    },
    copy(_content) {
      // 创建临时textarea元素
      const tempInput = document.createElement('textarea')
      tempInput.value = _content.replace(/<[^>]+>/g, '') // 设置要复制的内容
      // 隐藏元素
      tempInput.style.position = 'absolute'
      tempInput.style.left = '-9999px'
      // 将元素添加到DOM中
      document.body.appendChild(tempInput)
      // 选中元素内容
      tempInput.select()
      // 执行复制操作
      document.execCommand('copy')
      // 移除临时元素
      document.body.removeChild(tempInput)
      this.$toast.success('复制成功')
    },
    setOpeningRemarksMessage() {
      this.openingRemarksMessage = [[], [], []]
			
      let timer1 = null
      let timer2 = null
      let timer3 = null
      let openingRemarksMessage1 = [
        '👋📚 親愛嘅同學，哈囉！👋',
        '我係你嘅專屬學習夥伴，希望能夠陪住你喺學習旅程中一齊進步。🚀🌟',
        '我對好多知識都有認識📚，仲有唔會厭煩嘅耐心👀，無論你係想學嘢，定係需要啲情感支持💖或者生活建議🛠，我都好樂意做你嘅聆聽者同指導者，成為你嘅最佳拍檔🧚‍♂️。'
      ]
			let openingRemarksMessage = [[],[],[]]
      openingRemarksMessage[0] = Array.from(openingRemarksMessage1[0])
      openingRemarksMessage[1] = Array.from(openingRemarksMessage1[1])
      openingRemarksMessage[2] = Array.from(openingRemarksMessage1[2])

      let timer1Index = openingRemarksMessage[0].length
      let timer2Index = openingRemarksMessage[1].length
      let timer3Index = openingRemarksMessage[2].length

      let index1 = 0
      let index2 = 0
      let index3 = 0

      let time = 50

      timer1 = setInterval(() => {
        if (this.isAllOpeningRemarks) {
          clearInterval(timer1)
          timer1 = null
          return
        }
        if (timer1Index > index1) {
          this.openingRemarksMessage[0].push(openingRemarksMessage[0][index1])
          index1++
          // this.$forceUpdate()
        } else {
          clearInterval(timer1)
          timer1 = null
          timer2 = setInterval(() => {
            if (this.isAllOpeningRemarks) {
              clearInterval(timer2)
              timer2 = null
              return
            }
            if (timer2Index > index2) {
              this.openingRemarksMessage[1].push(openingRemarksMessage[1][index2])
              index2++
            } else {
              clearInterval(timer2)
              timer2 = null
              timer3 = setInterval(() => {
                if (this.isAllOpeningRemarks) {
                  clearInterval(timer3)
                  timer3 = null
                  return
                }
                if (timer3Index > index3) {
                  this.openingRemarksMessage[2].push(openingRemarksMessage[2][index3])
                  index3++
                } else {
                  clearInterval(timer3)
                  timer3 = null
									this.openingRemarksMessage[2] = openingRemarksMessage[2];
                  this.isAllOpeningRemarks = true
                  setTimeout(() => {
                    this.openingRemarksAllFn()
                  }, 5000)
                }
              }, time)
            }
          }, time)
        }
      }, time)
    },
    openingRemarksAllFn() {
      if (!this.isAllOpeningRemarks) {
        this.isAllOpeningRemarks = true
        this.openingRemarksMessage = [
          '👋📚 親愛嘅同學，哈囉！👋',
          '我係你嘅專屬學習夥伴，希望能夠陪住你喺學習旅程中一齊進步。🚀🌟',
          '我對好多知識都有認識📚，仲有唔會厭煩嘅耐心👀，無論你係想學嘢，定係需要啲情感支持💖或者生活建議🛠，我都好樂意做你嘅聆聽者同指導者，成為你嘅最佳拍檔🧚‍♂️。'
        ]
      } else {
				if(this.userInfo.userId && this.userInfo.userId==this.userId){
					window.localStorage.setItem('showDialog',JSON.stringify({type:2,time:new Date().getTime()}))
					if(this.$route.name=='pocStartIndex')this.$router.push('/pocAiClassroom')
					return 
				}
        if (!this.showOpeningRemarks) return;
        this.showOpeningRemarks = false;
				if(this.userInfo.userId)this.chatStatusType = 2;
        this.startChat()
      }
    },
    startChat() {
      if (this.chatStatusType == 0) {
        this.chatList.push({
          role: 'user',
          content: ``,
          uid: '',
          AI: 'AI',
          aiContent: '',
          chatStatusType: this.chatStatusType,
          oldContent: '',
          isShowSynchronization: false,
          filename: '',
          createtime: new Date().toLocaleString().replaceAll('/', '-'),
          loading: false
        })
        this.chatListScrollBottom()
      } else if (this.chatStatusType == 1) {
        if (!this.choseGrade) {
          this.chatStatusType = 0
          return this.$toast('請選擇年級')
        }
        this.chatList.push({
          role: 'user',
          content: `${this.choseGrade}`,
          uid: '',
          AI: 'AI',
          aiContent:
            '你有冇鍾意嘅上堂方式，好似你鍾意邊種教學風格？係耐心細緻、例子講解更多啲，定係鍾意通過故事嚟學習？🤔可以揀多個選項㗎~ ',
          chatStatusType: this.chatStatusType,
          oldContent: '',
          isShowSynchronization: false,
          filename: '',
          createtime: new Date().toLocaleString().replaceAll('/', '-'),
          loading: false
        })

        this.chatValue = ''
        this.chatListScrollBottom()
      } else if (this.chatStatusType == 2) {
        if (this.userInfo.pleaseList.length == 0) {
          this.chatStatusType = 1
          return this.$toast('請選擇教學風格')
        }
        this.chatList.push({
          role: 'user',
          content: `${this.chatValue}`,
          uid: '',
          AI: 'AI',
          aiContent: '',
          chatStatusType: this.chatStatusType,
          oldContent: '',
          isShowSynchronization: false,
          filename: '',
          createtime: new Date().toLocaleString().replaceAll('/', '-'),
          loading: false
        })
        this.chatValue = ''
        this.chatListScrollBottom()
      } else if (this.chatStatusType == 3) {
        this.chatList.push({
          role: 'user',
          content: `開始選課`,
          uid: '',
          AI: 'AI',
          aiContent: '',
          chatStatusType: this.chatStatusType,
          oldContent: '',
          isShowSynchronization: false,
          filename: '',
          createtime: new Date().toLocaleString().replaceAll('/', '-'),
          loading: false
        })

        this.chatValue = ''
        this.chatListScrollBottom()
      }
    },
    gradeChange() {
      // this.startChat();
      this.userInfo.grade = this.gradeList.findIndex(i=>i==this.choseGrade);
      this.chatValue = this.choseGrade
    },
    chosePlease(item) {
      if (this.chatStatusType != 1) return
      if (this.chosePleaseList.includes(item)) {
        this.chosePleaseList = this.chosePleaseList.filter(item1 => item1 != item)
      } else {
        this.chosePleaseList.push(item)
      }
			this.userInfo.pleaseList = this.chosePleaseList;
      this.chatValue = this.chosePleaseList.join('、')
			
      // this.chosePleaseList.push(item)
    },
    goChat() {
      if (this.chatStatusType == 5) return
      this.chatStatusType = 5
      this.isChatStatus = false
      this.$nextTick(() => {
        this.$refs.textAreaRef.focus()
      })
    },
    courseSelection() {
			if(this.userInfo.userId){
				this.$router.push('/pocAiClassroom')
				return;
			}
      if (this.chatStatusType == 5) {
        this.chatStatusType = 3
        this.startChat()
      } else if (this.chatStatusType == 2) {
        this.chatStatusType = 3
        this.startChat()
      }
    },
		resetType3Form(){
			this.type3Form = {
				subject: '',
        chapter: '',
        edition: ''
			}
		},
		type3FormSubmit(){
			if(this.type3Form.subject==''){
				return this.$toast("请选择学科")
			}else if(this.type3Form.chapter==''){
				return this.$toast("请选择章节")
			}else if(this.type3Form.edition==''){
				return this.$toast("请选择版本")
			}
			this.userInfo.subject = this.type3Form.subject;
			this.userInfo.chapter = this.type3Form.chapter;
			this.userInfo.edition = this.type3Form.edition;
			this.userInfo.userId = this.userId;
			this.userInfo.phone = "";
			this.userInfo.birthday = "";
			window.localStorage.setItem('userInfo', JSON.stringify(this.userInfo));

			this.$router.push('/pocAiClassroom')
		},
		getUserInfoData(){
			let data  = window.localStorage.getItem('userInfo');
			if(data){
				data = JSON.parse(data);
				if(data.userId==this.userId){
					this.userInfo = data;
				}
			}
		}
  },
  mounted() {
    this.setOpeningRemarksMessage();
		this.getUserInfoData()
  }
}
</script>

<style scoped>
.pocAi {
  width: 100vw;
  height: 100vh;
  display: flex;
  /* background-image: radial-gradient(#bbcdff 0%, #bbcdff 1%, #e6dee9 100%); */
  box-sizing: border-box;
  background-color: black;
  padding-top: 40px;
}

.pa_background {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  /* opacity: 0.7; */
  z-index: 1;
}

.pa_background > img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.pa_chatArea {
  width: 100vw;
  height: 100%;
  overflow: auto;
  box-sizing: border-box;
  position: relative;
  z-index: 2;
}

.pa_ca_header {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-sizing: border-box;
}

.pa_ca_chat {
  width: 100%;
  box-sizing: border-box;
  height: calc(100%);
}

.pa_ca_c_list {
  width: 100%;
  height: calc(100% - 60px);
  overflow: auto;
  padding-top: 50px;
  padding-bottom: 50px;
  /* padding: 50px 0; */
  box-sizing: border-box;
  /* background-color: red; */
}

.pa_ca_c_bottom {
  width: 100%;
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  background-color: #fff;
}

.pa_ca_c_b_inputArea {
  width: 95%;

  height: 70%;
  /* background-color: #fff; */
  border-radius: 100px;
  /* box-shadow: 0 0 10px #ccc; */
  display: flex;
  align-items: center;
}
.pa_ca_c_b_btnArea {
  width: 60px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

.pa_ca_c_b_ia_input >>> .el-input__inner {
  border-radius: 50px;
  background: #f3f3f3 !important;
  color: black !important;
}

.pa_ca_c_b_ba_btn {
  width: 40px;
  height: 40px;
  margin-right: 5px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  /* background-color: red; */
  background-image: linear-gradient(to left, #4977eb 0%, #005bea 100%);
}

.pa_ca_c_b_ba_btn > svg {
  fill: #fff;
  width: 20px;
  height: 20px;
}

.pa_ca_c_b_ba_btnDisabled {
  opacity: 0.5;
}

.pa_ca_c_b_inputArea > textarea {
  resize: none;
  min-height: 50px;
  height: calc(100% - 40px);
  background: none;
  margin: 7px 0;
  width: calc(100% - 60px);
  font-size: 16px;
  border: none;
  outline: none;
  resize: none;
  overflow: auto;
  margin-left: 20px;
}

#myTextarea::-webkit-input-placeholder {
  /* Chrome, Opera, Safari */
  font-size: 14px; /* 修改placeholder字体大小 */
  color: grey; /* 修改placeholder文字颜色 */
}

#myTextarea:-moz-placeholder {
  /* Firefox 18- */
  font-size: 14px; /* 修改placeholder字体大小 */
  color: grey; /* 修改placeholder文字颜色 */
  opacity: 1; /* 修复Firefox的透明度问题 */
}

#myTextarea::-moz-placeholder {
  /* Firefox 19+ */
  font-size: 14px; /* 修改placeholder字体大小 */
  color: grey; /* 修改placeholder文字颜色 */
  opacity: 1; /* 修复Firefox的透明度问题 */
}

#myTextarea:-ms-input-placeholder {
  /* Internet Explorer 10-11 */
  font-size: 14px; /* 修改placeholder字体大小 */
  color: grey; /* 修改placeholder文字颜色 */
}

.userChat {
  width: 100%;
  height: auto;
  display: flex;
  justify-content: flex-end;
  align-items: flex-start;
}

.uc_left {
  max-width: 90vw;
  width: auto;
  height: auto;
  padding: 10px 0px 10px 0;
}

.uc_left > .chatName {
  text-align: right;
}

.uc_left > .chatMessage {
  border-radius: 10px 2px 10px 10px;
  background-color: #e0eafb;
  padding: 10px;
}

.uc_left > .chatMessage > .cm_btnArea {
  left: -35px;
}

.uc_right {
  padding: 10px 10px 10px 10px;
}

.aiChat {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: flex-start;
  /* padding: 20px 0; */
}

.ac_left {
  padding: 10px 10px 10px 10px;
}

.ac_right {
  width: auto;
  height: auto;
  padding: 10px 0px 10px 0;
}

.chatMessage {
  max-width: 65vw;
  background-color: #ffffff;
  border: solid 1px #000000e5;
  color: black;
  padding: 0px 20px;
  border-radius: 2px 8px 8px 8px;
  font-size: 14px;
  position: relative;
  box-shadow: 0px 4px 10px 0px #1d398314;
  box-shadow: 1px 1px 20px 4px #1d39830d;
  word-break: break-all;
}

.cm_btnArea {
  width: 30px;
  height: 100%;
  position: absolute;
  right: -35px;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}

.cm_btnArea > span {
  width: 15px;
  height: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-bottom: 5px;
}

.cm_btnArea > span > svg {
  width: 100%;
  height: 100%;
}

.chatMessage >>> ol {
  margin-left: 25px;
}

.chatMessage >>> ul {
  margin-left: 25px;
}

.ac_r_time {
  margin-top: 10px;
  font-size: 16px;
  color: #8f8f8f;
}

.ac_r_btnArea {
  margin-top: 5px;
  width: auto;
  display: flex;
  align-items: center;
  height: auto;
}
.ac_r_btnArea > span {
  max-height: 60px;
  padding: 5px 10px 5px 10px;
  background: #ffffff8c;
  border: 1px solid #ffffff8c;
  border-radius: 6px;
  cursor: pointer;
  color: black;
  font-size: 14px;
  margin-right: 20px;
}

.chatAvatar {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
  background: #fff;
  border-radius: 100%;
}

.chatName {
  font-size: 14px;
  /* color: rgb(80, 80, 80); */
  color: #ffffff8c;
  margin-bottom: 8px;
}

.pa_openingRemarks {
  width: 100vw;
  height: 100vh;
  position: fixed;
  bottom: 0px;
  left: 0;
  z-index: 3;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-end;
}

.pa_or_character {
  width: 300px;
  height: 200px;
  position: relative;
}

.pa_or_character > img {
  width: 100%;
  position: absolute;
  bottom: -24px;
}
.pa_or_bottom {
  width: 100%;
  background: #ffffff8c;
  height: 250px;
  display: flex;
  flex-direction: column;
  /* align-items: center; */
  justify-content: flex-start;
  box-sizing: border-box;
  padding: 30px;
}

.pa_or_bottom > span {
  font-size: 16px;
  margin: 4px 0;
}

.chatStatusMessage {
  margin-bottom: 10px;
}
.chatStatusMessageInputArea {
  width: 100%;
  height: auto;
  display: flex;
  align-items: center;
}

.chatStatusMessageInputArea > span {
  width: 3em;
}

.csm_message {
  display: flex;
  flex-direction: column;
}

.csm_message > span {
  margin-bottom: 10px;
}

.csmia_btn {
  flex: 1;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  background-color: #f0f2f5;
  color: #00000099;
  margin-top: 10px;
  border-radius: 6px;
}

.chatStatusMessageInputArea > .csmia_btn:nth-of-type(2) {
  margin-left: 10px;
  background-color: #3681fc;
  color: #fff;
}

.chatStatusMessageInputArea >>> .chatStatusMessageInputAreaSelect {
  flex: 1;
  border-top: none;
  border-left: none;
  border-right: none;
}

.chatStatusMessageInputArea >>> .chatStatusMessageInputAreaSelect .el-input__inner {
  border-top: none;
  border-left: none;
  border-right: none;
  border-radius: 0;
}

.ac_right > .chatMessage {
  padding: 10px;
}

.ac_r_ba_box {
  width: 100%;
  height: auto;
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.ac_r_ba_box > span {
  padding: 5px 10px;
  border-radius: 6px;
  background-color: #ffffff;
  color: #00000099;
  margin: 5px 10px 5px 0;
  font-size: 14px;
  border: 1px solid #ffffff;
  transition: 0.3s;
}

.ac_r_ba_boxActive {
  border: 1px solid #3681fc !important;
  background-color: #e0eafb !important;
  color: #3681fc !important;
}

.pa_goIndex {
  position: fixed;
  top: 55px;
  right: 10px;
  width: auto;
  height: auto;
  z-index: 5;
}

.pa_goIndex > span {
  padding: 10px 15px;
  background-color: #3681fc;
  color: #fff;
  font-size: 16px;
  border-radius: 6px;
}

.csm_ia_item{
	margin-top: 10px;
}

.csm_ia_item>span{
	margin: 5px 0;
}

.csm_ia_btnArea{
	display: flex;
	align-items: center;
	margin-top: 10px;
}

.csm_ia_btnArea>span{
	flex: 1;
	height: 40px;
	font-size: 16px;
	border-radius: 6px;
	background-color: #F0F2F5;
	color: #00000099;
	display: flex;
	align-items: center;
	justify-content: center;
}

.csm_ia_btnArea>span:nth-of-type(2){
	background-color: #3681FC;
	color: #fff;
	margin-left: 10px;
}
</style>
