<script setup lang="ts">
import { fetchHistoryRecordDelete, fetchSessionHistoryRecordList } from '@/apis/home-agent'
import { computed, ref, nextTick, toValue } from 'vue'
import { useI18n } from 'vue-i18n'

interface Props {
  currentFetchEventSourceController: AbortController | null
  currentSessionId: string
}

interface SessionHistoryRecordItem {
  content: string
  dialogsId: string
}

const props = defineProps<Props>()

const emit = defineEmits<{
  getMessageRecordList: [recordId: string]
  createNewSession: []
  historyRecordListUpdate: []
  clearSessionReferenceFile: []
}>()

const isShowHistoryMenu = defineModel<boolean>({ default: true })
const isAgentResponding = defineModel<boolean>('isAgentResponding', { required: true })

const { t } = useI18n()

const sessionHistoryRecordList = ref<SessionHistoryRecordItem[]>([])
const isHistoryListEdit = ref(false)

const currentSelectHistoryRecordList = ref<SessionHistoryRecordItem['dialogsId'][]>([])

const isSelectAllRecord = computed(() => {
  return (
    currentSelectHistoryRecordList.value.length === sessionHistoryRecordList.value.length &&
    sessionHistoryRecordList.value.length !== 0
  )
})

;(function () {
  getSessionHistoryRecordList()
})()

function getSessionHistoryRecordList(isCreateNewSessionCheck = false) {
  fetchSessionHistoryRecordList<SessionHistoryRecordItem[]>().then((res) => {
    sessionHistoryRecordList.value = res.data

    if (
      isCreateNewSessionCheck &&
      props.currentSessionId &&
      (sessionHistoryRecordList.value.length === 0 ||
        sessionHistoryRecordList.value.every((item) => item.dialogsId !== props.currentSessionId))
    ) {
      emit('createNewSession')
    }
  })
}

function handleShowHistoryMenuSwitch() {
  isShowHistoryMenu.value = !isShowHistoryMenu.value
}

function handleHistoryListEditSwitch() {
  if (!isHistoryListEdit.value && sessionHistoryRecordList.value.length === 0) {
    window.$message.warning(t('home_module.there_is_currently_no_history_to_work_with'))
    return
  }

  isHistoryListEdit.value = !isHistoryListEdit.value

  if (!isHistoryListEdit.value) {
    currentSelectHistoryRecordList.value = []
  }
}

function handleHistoryRecordCheckSwitch(dialogsId: string) {
  if (!currentSelectHistoryRecordList.value.includes(dialogsId)) {
    currentSelectHistoryRecordList.value.push(dialogsId)
  } else {
    const index = currentSelectHistoryRecordList.value.findIndex((item) => item === dialogsId)

    if (index !== -1) {
      currentSelectHistoryRecordList.value.splice(index, 1)
    }
  }
}

function handleRecordSelectAll(checked: boolean) {
  if (checked) {
    currentSelectHistoryRecordList.value = sessionHistoryRecordList.value.map((item) => item.dialogsId)
  } else if (
    !checked &&
    currentSelectHistoryRecordList.value.length === sessionHistoryRecordList.value.length &&
    sessionHistoryRecordList.value.length !== 0
  ) {
    currentSelectHistoryRecordList.value = []
  }
}

function handleRecordDelete() {
  if (currentSelectHistoryRecordList.value.length === 0) {
    window.$message.warning(t('home_module.the_selected_list_cannot_be_empty'))
    return
  }

  window.$message.ctWarning(t('home_module.history_record_item_delete_tip'), t('common_module.tip')).then(() => {
    const loadingCtl = window.$message.loading(`${t('common_module.during_operation')}...`)

    fetchHistoryRecordDelete(toValue(currentSelectHistoryRecordList.value))
      .then(() => {
        nextTick(() => {
          window.$message.success(t('common_module.delete_success_message'))

          isHistoryListEdit.value = false
          currentSelectHistoryRecordList.value = []

          getSessionHistoryRecordList(true)
        })
      })
      .catch(() => {
        nextTick(() => {
          window.$message.error(t('common_module.deletion_failed_please_try_again'))
        })
      })
      .finally(() => {
        loadingCtl.destroy()
      })
  })
}

function onHistoryRecordListUpdate() {
  getSessionHistoryRecordList()
}

function handleRecordItemApply(dialogsId: string) {
  if (props.currentSessionId === dialogsId) return ''

  if (isAgentResponding.value) {
    window.$message.ctWarning(t('home_module.interrupt_the_conversation_and_apply_the_history_prompt')).then(() => {
      props.currentFetchEventSourceController && props.currentFetchEventSourceController.abort()

      isAgentResponding.value = false

      emit('getMessageRecordList', dialogsId)
      emit('clearSessionReferenceFile')

      /* 延时，避免页面刷新后，历史记录列表未刷新 */
      setTimeout(() => {
        emit('historyRecordListUpdate')
      }, 300)
    })
  } else {
    // window.$message.ctWarning(t('home_module.history_record_item_apply_tip'), t('common_module.tip')).then(() => {
    //   emit('getMessageRecordList', dialogsId)
    // })

    emit('getMessageRecordList', dialogsId)
    emit('clearSessionReferenceFile')
  }
}

defineExpose({
  historyRecordListUpdate: onHistoryRecordListUpdate,
})
</script>

<template>
  <Transition name="history-menu">
    <div v-show="isShowHistoryMenu" class="absolute bottom-0 right-[24px] top-0 z-10 py-[24px]">
      <div class="box-border h-full w-[269px] rounded-[10px] bg-[#ECEFFF] py-[15px] pl-[10px]">
        <n-scrollbar>
          <div class="pr-[10px]">
            <!-- <div class="select-none">
          <h2
            class="flex cursor-pointer items-center justify-between rounded-[8px] p-[10px] transition hover:bg-[#E4E4F2]"
          >
            <span class="flex items-center">
              <i class="iconfont icon-star mr-[4px] !text-[16px] text-[#333]"></i>
              <span class="font-600 text-[14px]">我的收藏</span>
            </span>

            <span class="iconfont icon-left inline-block rotate-90 text-[12px]"></span>
          </h2>
        </div> -->

            <div class="px-[4px]">
              <div class="h-[40px]" :class="[isHistoryListEdit ? 'sticky top-0 z-10' : '']">
                <Transition name="history-record-edit" mode="out-in">
                  <h2 v-if="!isHistoryListEdit" class="flex items-center justify-between">
                    <span class="flex items-center">
                      <i class="iconfont icon-history mr-[5px] !text-[14px] text-[#333]"></i>
                      <span class="font-600 text-[14px]">{{ t('home_module.historical_record') }}</span>
                    </span>

                    <span
                      class="iconfont icon-delete cursor-pointer text-[14px]"
                      @click="handleHistoryListEditSwitch"
                    ></span>
                  </h2>

                  <div v-else class="flex select-none justify-evenly rounded-[18px] bg-[#fff] py-[2px]">
                    <div class="rounded-[12px] px-[6px] py-[2px] transition hover:bg-[#f2f3f5]">
                      <n-checkbox size="small" :checked="isSelectAllRecord" :on-update:checked="handleRecordSelectAll">
                        <span class="!text-[14px]">{{ t('common_module.select_all') }}</span>
                      </n-checkbox>
                    </div>

                    <button
                      class="rounded-[12px] px-[6px] py-[2px] transition hover:bg-[#f2f3f5]"
                      @click="handleRecordDelete"
                    >
                      <span class="iconfont icon-delete cursor-pointer text-[14px]"></span>
                      <span class="ml-[5px] text-[14px]">{{ t('common_module.delete') }}</span>
                    </button>

                    <button
                      class="rounded-[12px] px-[6px] py-[2px] transition hover:bg-[#f2f3f5]"
                      @click="handleHistoryListEditSwitch"
                    >
                      <span class="iconfont icon-close cursor-pointer text-[14px]"></span>
                      <span class="ml-[5px] text-[14px]">{{ t('common_module.quit') }}</span>
                    </button>
                  </div>
                </Transition>
              </div>

              <ul class="select-none">
                <template v-for="recordItem in sessionHistoryRecordList" :key="recordItem.dialogsId">
                  <Transition name="history-record-edit" mode="out-in">
                    <li
                      v-if="!isHistoryListEdit"
                      class="group mb-[10px] flex cursor-pointer items-center rounded-[4px] px-[6px] py-[5px] transition last:mb-0"
                      :class="{
                        'hover:text-[#5D5D5D]': currentSessionId !== recordItem.dialogsId,
                        'bg-[#D7D9F8]': currentSessionId === recordItem.dialogsId,
                      }"
                      @click="handleRecordItemApply(recordItem.dialogsId)"
                    >
                      <i
                        class="iconfont icon-bubble mr-[5px] !text-[14px] text-[#010eff] transition"
                        :class="{ 'group-hover:text-[#000BDE]': currentSessionId !== recordItem.dialogsId }"
                      ></i>
                      <span class="flex-1 truncate text-[14px]">{{ recordItem.content }}</span>
                    </li>

                    <li v-else class="history-record-item mb-[18px] flex cursor-pointer items-center">
                      <n-checkbox
                        size="small"
                        class="history-record-item-checkbox"
                        :checked="currentSelectHistoryRecordList.includes(recordItem.dialogsId)"
                        :on-update:checked="() => handleHistoryRecordCheckSwitch(recordItem.dialogsId)"
                      >
                        <span class="max-w-[190px] items-center truncate !text-[14px]">{{ recordItem.content }}</span>
                      </n-checkbox>
                    </li>
                  </Transition>
                </template>
              </ul>
            </div>
          </div>
        </n-scrollbar>
      </div>
    </div>
  </Transition>

  <button
    class="flex-center absolute right-[298px] top-1/2 z-10 h-[24px] w-[24px] rounded-full bg-[#ECEFFF] transition-[right] duration-300 ease-in-out"
    :class="[isShowHistoryMenu ? [] : ['!right-[5px]']]"
    @click="handleShowHistoryMenuSwitch"
  >
    <span
      class="iconfont icon-left inline-block rotate-180 text-[10px] transition-[rotate] duration-300 ease-in-out"
      :class="{ '!rotate-0': !isShowHistoryMenu }"
    ></span>
  </button>
</template>

<style lang="scss" scoped>
.history-menu-enter-active,
.history-menu-leave-active {
  transition-timing-function: ease-in-out;
  transition-duration: 0.3s;
  transition-property: opacity, right;
}

.history-menu-enter-from,
.history-menu-leave-to {
  right: -273px;
  opacity: 0;
}

.history-record-edit-enter-active,
.history-record-edit-leave-active {
  transition-timing-function: ease-in-out;
  transition-duration: 0.3s;
  transition-property: opacity;
}

.history-record-edit-enter-from,
.history-record-edit-leave-to {
  opacity: 0;
}

:deep(.history-record-item-checkbox) {
  align-items: center;

  .n-checkbox__label {
    display: flex;
    align-items: center;
  }

  .n-checkbox-box {
    border-radius: 999px;
  }
}
</style>
