<template>
  <div class="left" :data-isCollapse="!isCollapse" :class="{ 'left-collapse': !isCollapse }">
    <transition>
      <div class="left-title" v-if="isCollapse">
        <span>对话历史</span>
        <img src="@/assets/agent/chat/shouqi.svg" alt="" @click="isCollapse = !isCollapse">
      </div>
      <img v-else class="top-icon" src="@/assets/agent/chat/shouqi.svg" alt="" @click="isCollapse = !isCollapse">
    </transition>
    <div class="flex-1">
      <div class="left-content">
        <!--对话历史卡片-->
        <!-- <transition-group name="fade" tag="div"> -->
          <ChatHistoryItem 
            v-for="item in chat.historyList" 
            :key="item.id" 
            :item="item" 
            :title="item.question"
            :avatar="chat.agentInfo?.imgRelUrl || '/images/def_agent.svg'" 
            :date="formatDateTime(item.createdTime)"
            @delete="deleteLog" 
            @topPosition="topPosition" 
            @click="clickListHandle(item)" 
          />
        <!-- </transition-group> -->
      </div>
    </div>
    <!--新建对话-->
    <div class="left-add" :class="{ 'left-add-border': isCollapse }">
      <el-button v-if="isCollapse" class="button" :icon="Plus" round @click="dialogAgentVisible = true">
        新建对话
      </el-button>
      <el-icon v-else :size="32" color="#3067EF" style="cursor: pointer">
        <CirclePlus @click="dialogAgentVisible = true" />
      </el-icon>
    </div>

    <DialogAgentList @tab-click="handleTabClick" @tab-close="dialogAgentVisible = false"
      :dialogVisible="dialogAgentVisible" :title="'选择智能体以新建对话'" />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { CirclePlus, Plus } from '@element-plus/icons-vue'
import ChatHistoryItem from './ChatHistoryItem.vue'
import DialogAgentList from './DialogAgentList.vue'
import { useRouter } from 'vue-router'
import useStore from '@/stores'
import { formatDateTime } from '@/utils/time'
import { ElMessage } from 'element-plus'
import { historySession, delete16, top, cancelTop } from '@/servers/finyx/api/zhinengtiduihuajilu';
import { MsgConfirmCustom } from '@/utils/message'

const router = useRouter()
const { chat } = useStore()

/** 是否收起， 默认展开 */
const isCollapse = ref(true)
/** 新建智能体弹框 */
const dialogAgentVisible = ref(false)

const emit = defineEmits(['list-click', 'tab-click'])

/** 切换智能体 */
const handleTabClick = (item: any) => {
  dialogAgentVisible.value = false
  if(item.id !== chat.info.agentId) {
    // 清空聊天内容
    chat.questionList = []
    // 清空对话内容
    chat.historyList = []
    setTimeout(() => {
      router.push({ path: `/chat/${item.id}/index` })
    }, 500)
    emit('tab-click', {
      ...item,
    })
  }
}

/** 切换历史记录 */
const clickListHandle = (item: any) => {
  if (chat.info?.historyId !== item.sessionId) {
    chat.addInfo({
      historyId: item.sessionId,
      agentId: item.applicationId
    })
    // 获取聊天内容
    chat.questionList = []
    item.sessionId && getQuestionList()
    emit('list-click', {
      ...item,
    })
  }
}

/** 获取对话内容列表 */
const getQuestionList = () => {
  const params = {
    size: 200,
    current: 1,
    sessionId: chat.info?.historyId || ''
  }
  chat.info.pageLoading = true
  historySession(params)
    .then((res: any) => {
      const { records } = res
      chat.addQuestionList(records)
    })
    .finally(() => {
      chat.info.pageLoading = false
    })
}

/** 删除 */
const deleteLog = async (item: any) => {
  const confirm = await MsgConfirmCustom(
    '确定删除当前对话历史', 
    '对话历史删除后不可恢复，请谨慎操作',
  )

  if (confirm) { 
    chat.info.pageLoading = true
    delete16([item.id])
      .then(() => {
        /* 如果删除的是当前对话，则切换到最新对话*/
        if (item.sessionId === chat.info?.historyId) {
          chat.info.historyId = ''
          chat.questionList = [];
        }
        chat.getHistoryList(chat.info.agentId)
        setTimeout(() => {
          ElMessage.success('操作成功！')
        }, 500)
      })
      .finally(() => {
          setTimeout(() => {
            chat.info.pageLoading = false
          }, 300)
      })
  }
}

/** 置顶 取消置顶 */
const topPosition = (item: any) => {
  if(item.topUp === '0') {
    top({ id: item.id })
    .then(() => {
      chat.getHistoryList(chat.info.agentId)
      ElMessage.success('操作成功！')
    })
    .finally(() => {
      chat.info.pageLoading = false
    })
  } else {
    cancelTop({ id: item.id })
    .then(() => {
      chat.getHistoryList(chat.info.agentId)
      ElMessage.success('操作成功！')
    })
    .finally(() => {
      chat.info.pageLoading = false
    })
  }
}

  
</script>

<style lang="scss" scoped>
.left {
  width: 224px;
  background: #fff;
  border-radius: 16px;
  padding: 12px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  align-items: center;
  transition: width .3s ease;

  /* 添加过渡效果 */
  .top-icon {
    width: 14px;
    height: 14px;
    cursor: pointer;
    margin-bottom: 12px;
    margin-top: 4px;
    transform: rotate(180deg);
  }

  &-title {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    color: #191919;
    font-size: 14px;
    padding-left: 4px;
    margin-bottom: 12px;

    img {
      margin-right: 6px;
      cursor: pointer;
    }
  }

  &-content {
    scrollbar-width: none;
    /* Firefox */
    -ms-overflow-style: none;
    /* IE/Edge */

    height: 100%;
    overflow: auto;
    cursor: pointer;
  }

  &-content::-webkit-scrollbar {
    display: none;
    /* Chrome/Safari */
  }

  .flex-1 {
    width: 100%;
    flex: 1;
    overflow-y: auto;
  }

  /** 新建对话 */
  .left-add {
    width: 100%;
    height: 32px;
    margin-top: 20px;
    border-radius: 20px 20px 20px 20px;
    margin-bottom: 10px;

    .button {
      color: #3067EF;
      width: 100%;
    }
  }

  /* 进入过渡的开始状态和结束状态 */
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 1s;
    /* 定义过渡效果，这里是透明度的变化 */
  }

  /* 进入过渡的结束状态 */
  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
    /* 开始时完全透明 */
  }
}

/* 折叠 */
.left-collapse {
  width: 80px;

  .left-content-item {
    padding: 12px;
  }

  .left-add {
    text-align: center;
  }
}

.left-add-border {
  border: 1px solid rgba(48, 103, 239, 0.6);
}

.active {
  background: #F4F8FF;
}
</style>