<script setup lang="js">
import { ref } from 'vue'
import { Search, Delete } from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { getConversation,delConversation } from '@/api/model.js'
import { storeToRefs } from 'pinia';
import { useMsgStore } from '@/store/modules/msg.ts'
import { useUserStore } from '@/store/modules/user';


const msgStore = useMsgStore()
const userStore = useUserStore()
const drawer = ref(false)


const count = ref(0)
const input = ref('')
const loading = ref(false)
const dataList = ref([])
// 获取父组件提供的 Hook 实例
const emit = defineEmits(['currentData'])
const { conversationId} = storeToRefs(useMsgStore())
const fetchList = async () => {
 try {
  loading.value = true
  const res =   await getConversation({
      page: 1,
      size: 100,
      sort: ['createTime,desc'],
      userId:userStore.userInfo.id
    })
  dataList.value = res.data.list
 } finally{
  loading.value = false
 }
}
onMounted(async () => {
  await fetchList()
  conversationId.value = dataList.value[0].id
})
watch(drawer, (newVal) => {
  if (newVal) {
    fetchList()
  }
})
const search = (keyword) => {
  const loop = (data) => {
    const result = []
    data.forEach((item) => {
      if (item.title?.toLowerCase().includes(keyword) || item.code?.toLowerCase().includes(keyword)) {
        result.push({...item})
      }
    })
    return result
  }
  return loop(dataList.value)
}
const searchList = computed(() => {
  if (!input.value) return dataList.value
  return search(input.value.toLowerCase())
})
function handleDeleteStore(e, item,name) {
  e.stopPropagation()
  ElMessageBox.confirm(
    '此操作无法撤销。',
    `要删【${name.substring(0,20)}】对话吗？`,
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      showClose: false,
      center: true
    }
  ).then(() => {
    delConversation(item).then(() => {
      fetchList()
      msgStore.setTitle(null)
      msgStore.setConvId(null)
    })
  })
}
defineExpose({
  drawer
})
</script>

<template>
  <el-drawer style="height: 70%" v-model="drawer" direction="btt" :show-close="true" :close-on-click-modal="false"
    :destroy-on-close="true"  class="custom_drawer">
    <template #header>
      <div class="his_flex"><span class="his_title">历史聊天</span><span class="his_count">({{ dataList.length }})</span>
      </div>
    </template>
    <div style="height: 100%;overflow: hidden;" v-loading="loading">
      <div class="his_delete">
         <el-input style="margin-right: 12px" v-model="input" placeholder="搜索" clearable :prefix-icon="Search"
           /> 
     
      </div>
      <div class="his_content">
       <template v-for="item in searchList" :key="item.id">
         <div :class="`his_list ${conversationId === item.id ? 'his_list_change' : '' }`"
           @click="() => { 
            msgStore.setTitle(item.title)
            msgStore.setConvId(item.id)
           }">
           <p class="ellipsis" style="color:#000000;font-weight: 900;">{{ item?.title ?? '&#45;&#45;' }}</p>
           <p class="his_list_op">
             <span style="color: #000">{{ item?.createTime }}</span>
             <el-tooltip effect="dark" content="删除" placement="top">
               <el-button  :icon="Delete" link
                 @click="(e) => handleDeleteStore(e, item.id, item?.title)" />
             </el-tooltip>
           </p>
         </div>
       </template>
      </div>
    </div>
  </el-drawer>
</template>

<style lang="scss">
.his_flex {
  display: flex;
  align-items: center;
}

.custom_drawer {
  height: 70vh !important;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;

  .el-drawer__header {
    padding: 16px;
    margin-bottom: 0;
  }

  .el-drawer__close-btn, .el-drawer__body {
    padding: 0;
  }

  .el-drawer__body {
    overflow: hidden;
    height: 100%;
  }
}

.his_title {
  display: inline-block;
  color: #000000;
  font-size: 20px;
  font-weight: 900;
  margin-right: 3px;
  height: 24px;
  line-height: 24px;
}

.his_count {
  display: inline-block;
  height: 24px;
  line-height: 24px;
}

.his_delete {
  padding: 0 12px 10px;
  display: flex;
  position: sticky;
  align-items: center;
  justify-content: space-between;

  .is-circle {
    border-radius: 8px;
  }
}

.his_content {
  height: calc(100% - 40px);
  overflow: auto;
  padding: 0 12px;

  .ellipsis {
    white-space: nowrap; /* 强制文本不换行 */
    overflow: hidden; /* 隐藏溢出内容 */
    text-overflow: ellipsis; /* 显示省略号 */
    width: 100%; /* 设置宽度（必须） */
  }

  .his_list {
    font-size: 12px;
    padding: 5px 10px;
    border-radius: 8px;
    margin-bottom: 4px;
    box-shadow: 0 0 6px rgba(122, 89, 255, .16);
    cursor: pointer;

    .his_list_op {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .his_list:hover {
    background-color: rgba(122, 89, 255, .06);
  }

  .his_list_change {
    background-color: rgba(122, 89, 255, .2) !important;
  }
}
</style>
