<!--
 * @Author: wrh
 * @Date: 2025-04-07 14:14:05
 * @LastEditors: wrh
 * @LastEditTime: 2025-06-12 17:01:55
-->
<template>
  <div class="app-container">
    <!-- 最外层页面于窗口同宽，使聊天面板居中 -->
    <div class="home-view">
      <!-- 整个聊天面板 -->
      <div class="chat-panel">
        <!-- 左侧的会话列表 -->
        <div class="session-panel">
          <el-row :gutter="20">
            <el-col :span="12" :offset="3">
              <div class="top-plus-button">
                <el-button :icon="Plus" type="primary">开启新对话</el-button>
              </div>
            </el-col>
          </el-row>
          <el-divider />
          <el-scrollbar max-height="800px">
            <div id="recent-containers">
              <div v-if="classifiedRecent.today.length > 0">
                <div class="category-title">今天</div>
                <div v-for="item in classifiedRecent.today" :key="item.topicId"
                  class="record">
                  <span @click="enableEdit(item)" v-if="!item.isEditing">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)"
                    @keyup.enter="disableEdit(item)" />
                  <el-button class="right-delete-button" :icon="Delete" style="border: none;"></el-button>
                </div>
              </div>
              <div class="spacer" v-if="classifiedRecent.today.length > 0"></div>

              <div v-if="classifiedRecent.yesterday.length > 0">
                <div class="category-title">昨天</div>
                <div v-for="item in classifiedRecent.yesterday" :key="item.topicId"
                  class="record">
                  <span @click="enableEdit(item)" v-if="!item.isEditing">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)"
                    @keyup.enter="disableEdit(item)" />
                  <el-button class="right-delete-button" :icon="Delete" style="border: none;"></el-button>
                </div>
              </div>
              <div class="spacer" v-if="classifiedRecent.yesterday.length > 0"></div>

              <div v-if="classifiedRecent.dayBeforeYesterday.length > 0">
                <div class="category-title">前天</div>
                <div  v-for="item in classifiedRecent.dayBeforeYesterday" :key="item.topicId"
                  class="record">
                  <span @click="enableEdit(item)" v-if="!item.isEditing">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)"
                    @keyup.enter="disableEdit(item)" />
                  <el-button class="right-delete-button" :icon="Delete" style="border: none;"></el-button>
                </div>
              </div>
              <div class="spacer" v-if="classifiedRecent.dayBeforeYesterday.length > 0"></div>

              <div v-if="classifiedRecent.within7Days.length > 0">
                <div class="category-title">7天内</div>
                <div  v-for="item in classifiedRecent.within7Days" :key="item.topicId"
                  class="record">
                  <span @click="enableEdit(item)" v-if="!item.isEditing">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)"
                    @keyup.enter="disableEdit(item)" />
                  <el-button class="right-delete-button" :icon="Delete" style="border: none;"></el-button>
                </div>
              </div>
              <div class="spacer" v-if="classifiedRecent.within7Days.length > 0"></div>

              <div v-if="classifiedRecent.within30Days.length > 0">
                <div class="category-title">30天内</div>
                <div  v-for="item in classifiedRecent.within30Days" :key="item.topicId"
                  class="record">
                  <span @click="enableEdit(item)" v-if="!item.isEditing">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)"
                    @keyup.enter="disableEdit(item)" />
                  <el-button class="right-delete-button" :icon="Delete" style="border: none;"></el-button>
                </div>
              </div>
              <div class="spacer" v-if="classifiedRecent.within30Days.length > 0"></div>
            </div>

            <!-- 按月记录容器 -->
            <div v-if="sortedMonthlyKeys.length > 0">
              <div v-for="monthKey in sortedMonthlyKeys" :key="monthKey">
                <div class="category-title">{{ formatMonth(monthKey) }}</div>
                <div v-for="item in classifiedMonthly[monthKey]" :key="item.topicId"
                  class="record">
                  <span @click="enableEdit(item)" v-if="!item.isEditing">{{ item.topic }}</span>
                  <el-input v-else v-model="item.topic" @blur="disableEdit(item)"
                    @keyup.enter="disableEdit(item)" />
                  <el-button class="right-delete-button" :icon="Delete" style="border: none;"></el-button>
                </div>
              </div>
              <div class="spacer"></div>
            </div>

            <!-- 空状态 -->
            <div v-if="!hasRecords" class="empty">
              暂无记录
            </div>
          </el-scrollbar>
        </div>
        <!-- 右侧的消息记录 -->

        <div class="message-panel">

        </div>
      </div>
    </div>
  </div>
</template>

<script setup name=''>
import { reactive, toRefs, onBeforeMount, onMounted } from 'vue'
import { Plus, Delete } from '@element-plus/icons-vue'
import { listTopic, getTopic, delTopic, addTopic, updateTopic } from "@/api/llm/topic";
const { proxy } = getCurrentInstance();

const topicList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const hasRecords = ref(false);
const classifiedRecent = ref({
  today: [],
  yesterday: [],
  dayBeforeYesterday: [],
  within7Days: [],
  within30Days: []
});
const classifiedMonthly = ref({});

const enableEdit = (item) => {
  item.isEditing = true;
};

const disableEdit = (item) => {
  item.isEditing = false;
};
const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 99999,
    topic: null,
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询cmc聊天主题列表 */
const getList = async () => {
  try {
    loading.value = true;
    let response = await listTopic(queryParams.value);
    if (response.total > 0) {
      topicList.value = response.rows;
      total.value = response.total;
      loading.value = false;
      hasRecords.value = true;
      // 分类近期记录

      const today = new Date()
      today.setHours(0, 0, 0, 0)

      const yesterday = new Date(today)
      yesterday.setDate(yesterday.getDate() - 1)

      const dayBeforeYesterday = new Date(today)
      dayBeforeYesterday.setDate(dayBeforeYesterday.getDate() - 2)

      const sevenDaysAgo = new Date(today)
      sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7)

      const thirtyDaysAgo = new Date(today)
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30)

      topicList.value.forEach(record => {
        const recordDate = new Date(record.createTime)
        recordDate.setHours(0, 0, 0, 0)

        if (recordDate.getTime() === today.getTime()) {
          classifiedRecent.value.today.push(record)
        } else if (recordDate.getTime() === yesterday.getTime()) {
          classifiedRecent.value.yesterday.push(record)
        } else if (recordDate.getTime() === dayBeforeYesterday.getTime()) {
          classifiedRecent.value.dayBeforeYesterday.push(record)
        } else if (recordDate > sevenDaysAgo) {
          classifiedRecent.value.within7Days.push(record)
        } else if (recordDate > thirtyDaysAgo) {
          classifiedRecent.value.within30Days.push(record)
        } else if (recordDate <= thirtyDaysAgo) {
          const monthKey = getMonthKey(recordDate)

          if (!classifiedMonthly.value[monthKey]) {
            classifiedMonthly.value[monthKey] = []
          }

          classifiedMonthly.value[monthKey].push(record)
        }
      })
    }
  } catch (err) {
    console.error('获取数据失败:', err)
  } finally {
    loading.value = false
  }
}
// 获取排序后的月份键
const sortedMonthlyKeys = computed(() => {
  return Object.keys(classifiedMonthly.value).sort((a, b) => new Date(b) - new Date(a))
})

// 获取月份键 (yyyy-MM)
const getMonthKey = (date) => {
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  return `${year}-${month}`
}

// 格式化月份显示
const formatMonth = (monthKey) => {
  const [year, month] = monthKey.split('-')
  return `${year}-${month}`
}

// 日期格式化
const formatDate = (date) => {
  const d = new Date(date)
  return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
}
onMounted(() => {
  getList();
})
</script>
<style lang="scss" scoped>
.home-view {
  display: flex;
  /* 与窗口同宽 */
  width: 100vw;

  .chat-panel {
    /* 聊天面板flex布局，让会话列表和聊天记录左右展示 */
    display: flex;
    /* 让聊天面板圆润一些 */
    border-radius: 4px;
    background-color: white;
    /* 给一些阴影 */
    box-shadow: 0 0 4px 4px rgba(black, 0.05);
    /* 与上方增加一些间距 */
    margin-top: 4px;

    /* 左侧聊天会话面板*/
    .session-panel {
      background-color: rgb(249 251 255);
      width: 12vw;
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
      position: relative;
      border-right: 1px solid rgba(black, 0.07);
    }

    /* 右侧消息记录面板*/
    .message-panel {
      width: 88vw;
      height: 90vh;
    }
  }
}

.category-title {
  padding: 0 10px;
  font-size: 12px;
  font-weight: bold;
  line-height: 30px;
  color: #333;
  background-color: rgb(249 251 255);
}

.record {
  z-index: 1;
  white-space: nowrap;
  line-height: 30px;
  color: #4c4c4c;
  background-color: rgb(249 251 255);
  cursor: pointer;
  border-radius: 12px;
  align-items: center;
  padding: 0 10px;
  font-size: 12px;
  display: flex;
  position: relative;
}

.spacer {
  height: 20px;
  clear: both;
}

.empty {
  padding: 0 10px;
  color: #909399;
}

.top-plus-button {
  margin-top: 20px;
}

.right-delete-button {
  opacity: 0;
  z-index: 2;
  justify-content: left;
  align-items: center;
  width: 12px;
  height: 12px;
  display: flex;
  position: absolute;
  top: 50%;
  right: 0px;
  transform: translateY(-50%);
}

.right-delete-button:hover {
  opacity: 1;
  z-index: 2;
  background: linear-gradient(90deg, rgba(255, 255, 255, 0.6), rgba(255, 255, 255, 1), rgba(255, 255, 255, 1));
  color: rgb(70, 70, 70);
  justify-content: left;
  align-items: center;
  width: 12px;
  height: 12px;
  display: flex;
  position: absolute;
  top: 50%;
  right: 0px;
  transform: translateY(-50%);
}
</style>