<template>
  <u-navbar :titleStyle="{ color: '#000' }" :autoBack="true" title="小天AI" :placeholder="true" :safeAreaInsetTop="true" bgColor="#fff">
    <template #left>
      <view class="u-navbar__content__left__item">
        <u-icon name="arrow-left" size="20" color="#000"></u-icon>
      </view>
    </template>
  </u-navbar>

  <oa-scroll
    customClass="doorList-container scroll-height"
    :isSticky="true"
    :customStyle="{
      //#ifdef APP-PLUS || MP-WEIXIN
      height: `calc(100vh - (44px + ${footerHeight}px + ${proxy.$settingStore.StatusBarHeight}))`,
      //#endif
      //#ifdef H5
      height: `calc(100vh - (44px + ${footerHeight}px))`,
      //#endif
    }"
    :refresherLoad="false"
    :refresherEnabled="false"
    :scrollTop="scrollTop"
    :scrollIntoView="scrollIntoView"
    :refresherDefaultStyle="'none'"
    :refresherBackground="'#fffff'"
    :data-theme="'theme-' + proxy.$settingStore.themeColor.name"
  >
    <template #default>
      <view class="mainArea">
        <view class="center-area">
          <view class="center-area-item">
            <viwe class="center-area-item__avatar">
              <image src="@/static/images/ai/ai-avatar.png" mode="widthFix"></image>
            </viwe>

            <view class="center-area-item__center">
              <view class="center-area-item__center__content">
                <span class="defaultQuestion-title">您好，我是智能助手小天！</span>
                作为您的智能助手，我能帮助您解决各种问题。 除此之外，小天还可以尝试帮助解决其他方面的问题或在您需要的时候陪您聊天！
                <!-- 您可以试着问我：
              <view class="defaultQuestion">
                <view class="defaultQuestion-item" @click="onClickDefaultQuestion($event, item)" v-for="item in defaultQuestion.list" :key="item.id" :span="12">
                  {{ item.value }}
                </view>
              </view> -->
              </view>
            </view>
          </view>

          <viwe v-for="(item, index) in answerList" :key="index" :class="['center-area-item', { roleUser: item.role === 'user' }]" :id="index == answerList.length - 1 ? 'bottomInfo' : ''">
            <viwe class="center-area-item__avatar">
              <image v-show="item.role === 'assistant'" src="@/static/images/ai/ai-avatar.png" mode="widthFix"></image>
              <image v-show="item.role === 'user'" src="@/static/images/ai/ai-question-avatar.png" mode="widthFix"></image>
            </viwe>

            <view class="center-area-item__center">
              <viwe v-if="item.role === 'user'" class="center-area-item__center__content">
                {{ item.content }}
              </viwe>
              <viwe v-else-if="item.role === 'assistant'" class="center-area-item__center__content">
                <!-- <viwe class="center-area-item__outputReasonContent">{{ item.reasoningContent }}</viwe> -->
                <zero-markdown-view :markdown="item.reasoningContent" themeColor="#05073b"></zero-markdown-view>
              </viwe>

              <view
                class="iconfont oaIcon-copy center-area-item__center__icon"
                @click="copy(item.role === 'user' ? item.content : item.reasoningContent)"
                :style="{
                  float: item.role === 'user' ? 'right' : 'left',
                  margin: item.role === 'user' ? '5px 5px 0 0' : '5px 0 0 5px',
                }"
              >
              </view>
            </view>
          </viwe>
        </view>
      </view>
    </template>
  </oa-scroll>

  <view class="footer-area">
    <view class="footer-area-top">
      <view class="footer-area-top__record" @click="handle('Record')">对话历史</view>
      <view class="footer-area-top__new" @click="handle('CreateChat')">新话题</view>
    </view>
    <view class="footer-area-center">
      <textarea
        class="footer-area-center-textarea"
        v-model="answerKeyword"
        placeholder="请输入问题，可通过回车换行"
        maxlength="500"
        @confirm="onSubmit"
        @linechange="linechange"
        auto-height
      ></textarea>
      <button class="footer-area-center-button" type="primary" :loading="submitLoading" @click="onSubmit">发送</button>
    </view>
    <view class="footer-area-prompt">以上内容均由AI大模型生成，仅供参考</view>
  </view>

  <uni-popup ref="popup" type="left" safeArea backgroundColor="#fff">
    <view class="chatArea">
      <view class="content">
        <view class="content-title">近30天</view>
        <view class="content-item" v-for="item in state.chatHistory.list" :key="item" @click="onClickChatItem(item)" @longpress="onLongPressChatItem(item)"> {{ item.question }}</view>
      </view>
    </view>
  </uni-popup>

  <u-action-sheet
    :actions="sheet.actions"
    :show="sheet.show"
    cancelText="取消"
    :round="10"
    :wrapMaxHeight="'50vh'"
    :closeOnClickOverlay="true"
    :safeAreaInsetBottom="true"
    @close="sheet.show = false"
    @select="changeSheet"
  ></u-action-sheet>

  <u-modal
    :show="modal.show"
    :title="modal.title"
    :showCancelButton="true"
    :closeOnClickOverlay="true"
    @confirm="handle(modal.type == '删除' ? 'Delete' : 'Update')"
    @cancel="modal.show = false"
    @close="modal.show = false"
  >
    <view class="slot-content" style="width: 100%">
      <view v-if="modal.type == '删除'"> {{ modal.content }}</view>
      <view v-if="modal.type == '重命名'">
        <textarea v-model="modal.content" placeholder="请输入" border="bottom" maxlength="50" auto-height style="width: 100%; border-bottom: 1px #cbcbcb solid"></textarea>
      </view>
    </view>
  </u-modal>

  <oa-chatSSEClient ref="chatSSEClientRef" @onOpen="openCore" @onError="errorCore" @onMessage="messageCore" @onFinish="finishCore" />
</template>

<script setup>
/*----------------------------------依赖引入-----------------------------------*/
import config from "@/config";
import { getToken } from "@/utils/auth";
import { onLoad, onShow, onReady, onHide, onLaunch, onUnload, onNavigationBarButtonTap, onPageScroll } from "@dcloudio/uni-app";
import { ref, reactive, computed, getCurrentInstance, toRefs, inject, nextTick } from "vue";
/*----------------------------------接口引入-----------------------------------*/
import { aiApi } from "@/api/business/ai.js";
/*----------------------------------组件引入-----------------------------------*/
/*----------------------------------store引入-----------------------------------*/
import { useStores, commonStores, controlStores } from "@/store/modules/index";
/*----------------------------------公共方法引入-----------------------------------*/
/*----------------------------------公共变量-----------------------------------*/
const { proxy } = getCurrentInstance();
const useStore = useStores();
const controlStore = controlStores();
/*----------------------------------变量声明-----------------------------------*/
const state = reactive({
  buffer: "", // 用于存储流式数据不完整的行
  defaultQuestion: {
    list: [
      { id: 2, value: "如何看待中国锂矿储量从全球占比6%升至16.5%，从世界第六跃至第二？" },
      { id: 3, value: "为什么特斯拉和理想，都不想承认自己是「汽车公司」？" },
      { id: 4, value: "全美第二大的城市洛杉矶大火，为什么能蔓延到无法控制的地步？" },
      { id: 4, value: "为什么主流都不再力推英特尔 CPU？" },
    ],
  },
  submitLoading: false,
  answerKeyword: undefined,
  answerList: [],
  // 会话记录
  chatHistory: {
    list: [],
    sessionId: undefined,
  },
  footerHeight: 0, //底部区域高度
  scrollIntoView: "", //滚动位置

  sheet: {
    show: false,
    actions: [
      {
        name: "删除",
      },
      {
        name: "重命名",
      },
    ],
    list: {},
  },
  modal: {
    show: false,
    title: "",
    content: "",
    type: "",
  },
});

const { buffer, defaultQuestion, submitLoading, answerKeyword, answerList, chatHistory, footerHeight, scrollIntoView, sheet, modal } = toRefs(state);

/** 操作 */
function handle(type) {
  if (type == "Record") {
    getChatList();
    proxy.$refs["popup"].open();
  } else if (type == "CreateChat") {
    if (state.chatHistory.list.length >= 10) {
      return uni.showToast({ title: "您最多可同时建立10个对话，如需新建对话，请先删除会话！", icon: "none" });
    }
    state.chatHistory.sessionId = undefined;
    state.answerList = [];
    state.answerKeyword = undefined;
  } else if (type == "Delete") {
    aiApi()
      .Delete(state.sheet.list.sessionId)
      .then((response) => {
        proxy.$modal.msg("删除成功");
        state.modal.show = false;
      });
  } else if (type == "Update") {
    aiApi()
      .Update({
        sessionId: state.sheet.list.sessionId,
        question: state.modal.content,
      })
      .then((response) => {
        proxy.$modal.msg("修改成功");
        state.modal.show = false;
      });
  }
}

/** 获取历史对话列表 */
function getChatList() {
  aiApi()
    .recordSelect()
    .then((response) => {
      state.chatHistory.list = response.data;
    });
}

/** 点击历史对话事件 */
function onClickChatItem(item) {
  state.scrollIntoView = "";
  state.chatHistory.sessionId = item.sessionId;
  state.answerList = item.itemList;

  nextTick(() => {
    state.scrollIntoView = "bottomInfo";
    proxy.$refs["popup"].close();
  });
}

/** 长按历史对话事件 */
function onLongPressChatItem(item) {
  proxy.$refs["popup"].close();
  state.sheet.show = true;
  state.sheet.list = item;
}

/** 当输入框行数发生变化 */
function linechange(event) {
  nextTick(() => {
    const query = uni.createSelectorQuery();
    query
      .select(".footer-area")
      .boundingClientRect((rect) => {
        state.footerHeight = rect.height;
      })
      .exec();
  });
}

/** 操作菜单回调事件 */
function changeSheet(event) {
  if (event.name == "删除") {
    state.modal.title = "永久删除对话";
    state.modal.content = "删除后，改对话将不可恢复。确认删除吗？";
    state.modal.type = "删除";
    state.modal.show = true;
  } else if (event.name == "重命名") {
    state.modal.title = "重命名会话";
    state.modal.content = state.sheet.list.question;
    state.modal.type = "重命名";
    state.modal.show = true;
  }
}

/** 复制粘贴板 */
function copy(value) {
  // 触发方法
  proxy.$common.uniCopy({
    content: value,
    success: (res) => {
      uni.showToast({
        title: res,
        icon: "none",
      });
    },
    error: (e) => {
      uni.showToast({
        title: e,
        icon: "none",
        duration: 3000,
      });
    },
  });
}

/** 点击默认提问事件 */
function onClickDefaultQuestion(event, item) {
  state.answerKeyword = item.value;
  onSubmit(event);
}

async function onSubmit(event) {
  if (event.keyCode === 13 || event.key === "Enter") {
    event.preventDefault(); // 阻止默认行为，即回车换行
    if (event.shiftKey) {
      state.answerKeyword += "\n";
    }
  }
  if (!state.answerKeyword) return uni.showToast({ title: "请输入内容", icon: "none" });
  if (state.submitLoading) return;

  state.submitLoading = true;
  state.answerList.push({
    role: "user",
    content: state.answerKeyword,
  });

  proxy.$refs["chatSSEClientRef"].startChat({
    // 将它换成你的地址
    url: config.baseUrl + "/service-ai/ai/aliTyqw",
    // 请求头
    headers: {
      Authorization: getToken(),
      "Content-Type": "application/json; charset=utf-8",
    },
    // 默认为 post
    method: "post",
    body: {
      sessionId: state.chatHistory.sessionId,
      content: state.answerKeyword,
    },
  });
}

//数据处理
function processSSEChunk(chunk) {
  state.scrollIntoView = "";

  try {
    const jsonData = JSON.parse(chunk);

    if (jsonData.sessionId && !state.chatHistory.sessionId) {
      state.chatHistory.sessionId = jsonData.sessionId;
    }
    if (jsonData.reasoningContent) {
      state.answerList[state.answerList.length - 1].reasoningContent += jsonData.reasoningContent;
    } else if (jsonData.content) {
      state.answerList[state.answerList.length - 1].content += jsonData.content;
    }
  } catch (error) {
    console.log("parsing JSON错误", jsonString, index);
    console.log("parsing JSON错误", error);
  }

  nextTick(() => {
    state.scrollIntoView = "bottomInfo";
  });
}

//开始回答回调事件
function openCore() {
  console.log("open sse");

  state.answerKeyword = undefined;

  // 定义一个函数来读取流数据
  state.answerList.push({
    role: "assistant",
    content: "",
    reasoningContent: "",
  });
}

//回答异常回调事件
function errorCore(err) {
  console.log("error sse：", err);
  state.answerKeyword = undefined;
}

//回答中回调事件
function messageCore(response) {
  processSSEChunk(response);
}

//回答完毕回调事件
function finishCore() {
  console.log("finish sse");
  state.submitLoading = false;
}

//停止回答
function stop() {
  proxy.$refs["chatSSEClientRef"].stopChat();
  console.log("stop");
}

onReady(() => {});

onShow(() => {});

onLoad((options) => {});

onUnload(() => {});
</script>

<style lang="scss" scoped>
.doorList-container {
  background-color: #ffffff;
}

.center-area {
  height: auto;
  overflow: auto;

  &-item {
    display: flex;
    color: #05073b;
    padding: 15px;

    &__avatar {
      width: 26px;
      margin-top: 2px;
      margin-right: 10px;

      uni-image {
        border-radius: 50%;
      }
    }

    &__center {
      &__content {
        background: #f4f5f9;
        border-radius: 8px;
        box-shadow: 0 5px 20px 0 #f4f5f9;
        display: flex;
        flex-direction: column;
        padding: 10px 10px;
        position: relative;
        font-size: 14px;
        line-height: 1.75;
        min-height: 44.5px;
        box-sizing: border-box;
        word-break: break-all; //文字默认换行
      }

      &__icon {
        color: #909399;
      }
    }
  }

  .roleUser {
    justify-content: end;
    margin-left: auto;

    .center-area-item__avatar {
      margin-right: 0;
      margin-left: 10px;
      order: 2;
    }
  }
}

.footer-area {
  position: fixed;
  bottom: 0;
  width: 100%;
  // height: 137px;
  background-color: #ffffff;

  &-top {
    display: flex;
    margin: 10px 20px 0 20px;
    color: #7f7f7f;

    &__record {
      margin-left: auto;
    }

    &__new {
      margin-left: 15px;
    }
  }

  &-center {
    display: flex;
    width: calc(100% - 30px);
    background-color: #f4f5f9;
    margin: 10px 15px 10px 15px;
    padding: 15px;
    border-radius: 8px;

    &-textarea {
      width: 100%;
      margin-right: 20px;
    }

    &-button {
      width: 54px;
      height: 33px;
      display: flex;
      justify-content: flex-end;
      font-size: 13px;
      white-space: nowrap;
    }
  }

  &-prompt {
    margin: 10px 0;
    color: #adadad;
    font-size: 20rpx;
    text-align: center;
  }
}

.chatArea {
  width: 70vw;
  overflow-y: auto;
  height: 100vh;
  padding: 15px;

  .content {
    &-title {
      color: #8b8b8b;
      margin-bottom: 5px;
    }

    &-item {
      padding: 10px 5px;
      border-radius: 5px;
      letter-spacing: 1px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis; /* 超出部分显示省略号 */
      position: relative; /* 为伪元素定位 */

      &:active {
        background-color: #e5e5e5;
      }

      &:hover {
        background-color: #e5e5e5;
      }
    }
  }
}
</style>
