<template>
<view class="historyList padding30">
  <z-paging
    ref="pagingRef"
    class="paginng-contaner"
    :default-page-size="20"
    :use-refresher-status-bar-placeholder="true"
    v-model="list"
    @query="handleQuery"
  >
		<view class="bg_color_fff padding20 border_radius_20">
			<u-search placeholder="查找对话内容" v-model="keyword" 
      @search="reloadList" @custom="reloadList" @clear="reloadList"
      :showAction="false" borderColor="#ffffff"></u-search>
		</view>
    <view class="padding20" v-for="group in groupedList" :key="group.date">
      <view>{{group.date}}</view>
      <view class="flex-between padding20 bg_color_fff border_radius_20 mt10" 
      v-for="message in group.messages" :key="message.sessionId">
        <view class="payment-radio  mr20" @click="checkboxChange(message.sessionId)">
            <view
						class="radio-circle"
						:class="{ checked: selected.includes(message.sessionId) }"
					></view>
				</view>
        <image src="/static/img/wenhua.png" class="mr20" mode="" style="width: 40rpx;height: 40rpx;"/>
        <view class="flex_1 mr20" @click="add(message.sessionId)">{{message.firstMessageContent}}</view>
        <text class="gray font_size20">{{message.HS}}</text>
      </view>
    </view>
    <view class="footplaceholder"></view>
     <!-- foot -->
    <view class="foot bg_color_fff flex-center-between">
			<view class="order_btn paddingTB20 flex_1 text_align_center mr20 plain" @click="del">删除</view>
			<view class="order_btn paddingTB20 flex_1 text_align_center" @click="add">新增会话</view>
		</view>
  </z-paging>
</view>
</template>
<script setup> 
import { ref, computed } from 'vue'
import dayjs from 'dayjs'
import { chatHistoryList, delChatHistoryList } from '@/api/ai'
import { useAppStore } from '@/stores/app'
const appStore = useAppStore();

const pagingRef = ref();
const keyword = ref('');
const list = ref([]);
const selected = ref([]);

function checkboxChange(sessionId){
  if(selected.value.includes(sessionId)){
    selected.value = selected.value.filter(item => item !== sessionId);
  }else{
    selected.value.push(sessionId);
  }
}
function del(){
  if(selected.value.length==0){
    uni.showToast({
      title: '请选择要删除的会话',
      icon: 'none'
    });
    return;
  }
  uni.showModal({
    title: '提示',
    content: '确定要删除吗？',
    success: function (res) {
      if (res.confirm) {
        delChatHistoryList(selected.value).then(res => {
          if(res.code == 200){
            uni.showToast({
              title: '删除成功',
              icon: 'success'
            });
            selected.value = [];
            reloadList();
          }
        })
      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    }
  });
}
//跳转ai页面
function add(sessionId){
  if(sessionId) appStore.sessionId = sessionId;
  uni.switchTab({
    url: '/pages/ai/ai'
  });
}
function reloadList(item) {
  pagingRef.value.reload();
}
// 下拉刷新和滚动底部会自动触发此方法
async function handleQuery(page, pageSize, from) {
  try {
    const params = {
      pageNum: page,
      pageSize,
			agentId:appStore.agentId,
    };
    const { rows } = await chatHistoryList(params);
    pagingRef.value.complete(rows);
  } catch (e) {
		console.log('msg-comment',e)
    pagingRef.value.complete(false);
  }
}
const groupedList = computed(() => {
  const groups = {};
  
  list.value.forEach(message => {
    const date = dayjs(message.firstMessageTime);
    const today = dayjs().startOf('day');
    const yesterday = today.subtract(1, 'day');
    message.HS=date.format('HH:mm');
    
    let groupKey;
    if (date.isSame(today, 'day')) {
      groupKey = '今天';
    } else if (date.isSame(yesterday, 'day')) {
      groupKey = '昨天';
    } else {
      groupKey = date.format('YYYY-MM-DD');
    }
    
    if (!groups[groupKey]) {
      groups[groupKey] = [];
    }
    groups[groupKey].push(message);
  });
  
  // 转换并排序
  return Object.keys(groups)
    .map(key => ({
      date: key,
      messages: groups[key]
    }))
    .sort((a, b) => {
      // 按日期倒序排列
      if (a.date === '今天') return -1;
      if (b.date === '今天') return 1;
      if (a.date === '昨天') return -1;
      if (b.date === '昨天') return 1;
      return new Date(b.date) - new Date(a.date);
    });
});
</script>
<style lang="less" scoped>
.historyList{
}
</style>
