<template>
	<div class="left-nav" :class="{ collapse: isCollapse }">
		<div class="top">
			<img class="logo-img" src="@/assets/images/logo.png" alt="FiDA" v-show="!isCollapse" />
			<span class="logo-text" v-show="!isCollapse">FiDA</span>
			<div class="close" @click="onCollapse">
				<svg-icon name="shouqi" size="24" />
			</div>
		</div>
		<button class="create-btn" @click="onCreateProject">
			<span class="icon"><svg-icon name="add" size="16" /></span>
			<span v-show="!isCollapse" class="text">{{ $t('Home.newProject') }}</span>
		</button>
		<!-- <div class="menu-item" @click="onHome">
			<span class="icon"><svg-icon name="home" size="24" /></span>
			<span class="title" v-show="!isCollapse">{{ $t('Home.home') }}</span>
		</div> -->
		<div class="menu-item" @click="onHistory" :class="{ active: showHistory }">
			<span class="icon"><svg-icon name="history" size="18" /></span>
			<span class="title" v-show="!isCollapse">{{ $t('Home.history') }}</span>
			<span class="icon jiantou" v-show="!isCollapse"
				><svg-icon name="arrow-right" size="14" />
			</span>
		</div>
		<div class="history-list mini-scrollbar" v-show="!isCollapse && showHistory">
			<div v-for="item in list" :key="item.id" class="history-item">
				<div v-if="item.title" class="title">{{ item.name }}</div>
				<div
					v-else
					class="box"
					@click="onClickHistoryItem(item)"
					:class="{ active: item.id == id }"
				>
					<input
						v-show="item.edit"
						type="text"
						:value="item.name"
						ref="inputRef"
						:input-id="item.id"
						@click.stop
						@keyup.enter="(e) => onEnterHistoryItem(e, item)"
						@blur="(e) => onBlurHistoryItem(e, item)"
					/>
					<span class="label" v-show="!item.edit">{{ item.name }}</span>
					<el-popover
						ref="popoverRef"
						placement="right"
						trigger="click"
						width="10rem"
						popper-style="
							padding: .6rem 0.7rem;
							border-radius: 1rem;
							min-width: 10rem;
						"
					>
						<template #reference>
							<span @click.stop class="icon">
								<svg-icon name="more" size="16" />
							</span>
						</template>
						<div class="history-item-menu">
							<div class="rename" @click="onRenameHistoryItem(item)">
								<div class="icon">
									<svg-icon name="historyEdit" size="13" />
								</div>
								<span>
									{{ $t('Home.rename') }}
								</span>
							</div>
							<div class="delete" @click="onDeleteHistoryItem(item)">
								<div class="icon">
									<svg-icon name="historyDelete" size="13" />
								</div>
								<span>
									{{ $t('Home.delete') }}
								</span>
							</div>
						</div>
					</el-popover>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
	import { computed, ref, nextTick, onMounted, onUnmounted } from 'vue'
	import { useRoute, useRouter } from 'vue-router'
	import { useI18n } from 'vue-i18n'
	import { getProjectList, updateProject, deleteProject } from '@/api/agent'
	import { FormatDate } from '@/utils/tools'
	import MyEvent from '@/utils/myEvent'
	const { t: $t } = useI18n()
	const route = useRoute()
	const router = useRouter()
	import { useGlobalStore, useProjectStore } from '@/stores'
	const projectStore = useProjectStore()
	const id = computed(() => route.params.id)
	const globalStore = useGlobalStore()
	const isCollapse = computed(() => globalStore.state.homeLeftNavCollapse)
	const onCollapse = () => {
		globalStore.setHomeLeftNavCollapse(!isCollapse.value)
	}
	const showHistory = ref(true)
	const list = ref([])

	const onCreateProject = () => {
		router.push({ name: 'mainInput' })
	}
	const onHistory = () => {
		if (isCollapse.value) {
			globalStore.setHomeLeftNavCollapse(false)
			showHistory.value = true
		} else {
			showHistory.value = !showHistory.value
		}
	}
	const onClickHistoryItem = (item: any) => {
		router.push({ name: 'agent', params: { id: item.id } })
	}
	const inputRef = ref(null)
	const popoverRef = ref(null)
	const hidePopover = () => {
		popoverRef.value.forEach((v: any) => v.hide())
	}
	const onRenameHistoryItem = (item: any) => {
		hidePopover()
		item.edit = true
		nextTick(() => {
			inputRef.value.forEach((v: any) => {
				const id = v.getAttribute('input-id')
				if (id == item.id) v.focus()
			})
		})
	}
	const onEnterHistoryItem = (e: any, item: any) => {
		e.target.blur()
	}
	const onBlurHistoryItem = (e: any, item: any) => {
		item.edit = false
		const name = e.target.value
		if (!name) return console.warn('未输入名称，不允许重命名')
		item.name = name
		MyEvent.emit('renameConversation', item)
		updateProject(item.id, { name }).then(() => {
			GetProjectList()
		})
	}
	const onDeleteHistoryItem = (item: any) => {
		hidePopover()
		deleteProject(item.id).then(() => {
			GetProjectList()
			if (item.id == id.value) {
				router.push({ name: 'mainInput' })
			}
		})
	}

	const GetProjectList = async () => {
		const res = await getProjectList({
			page: 1,
			size: 100
		})
		const arr = res.records || []
		list.value = []
		const str = 'yyyyMMdd'
		const today = FormatDate(Date.now(), str)
		const yesterday = FormatDate(Date.now() - 24 * 60 * 60 * 1000, str)
		const todayList = []
		const yesterdayList = []
		const earlierChatList = []
		arr.forEach((item: any) => {
			const obj = { ...item, edit: false }
			const date = FormatDate(obj.updateTime * 1000, str)
			if (date == today) {
				todayList.push(obj)
			} else if (date == yesterday) {
				yesterdayList.push(obj)
			} else {
				earlierChatList.push(obj)
			}
		})
		if (todayList.length > 0) {
			list.value.push({
				id: 'today',
				title: true,
				name: $t('Home.today')
			})
			list.value.push(...todayList)
		}
		if (yesterdayList.length > 0) {
			list.value.push({
				id: 'yesterday',
				title: true,
				name: $t('Home.yesterday')
			})
			list.value.push(...yesterdayList)
		}
		if (earlierChatList.length > 0) {
			list.value.push({
				id: 'earlierChat',
				title: true,
				name: $t('Home.earlierChat')
			})
			list.value.push(...earlierChatList)
		}
	}
	MyEvent.add('updateProjectList', GetProjectList)
	GetProjectList()

	const replaceTitle = (data: { title: string; id: string | number }) => {
		list.value.forEach((item: any) => {
			if (String(item.id) === String(data.id)) {
				item.name = data.title
			}
		})
	}
	onMounted(() => {
		MyEvent.add('newTitle', replaceTitle)
	})
	onUnmounted(() => {
		MyEvent.remove('newTitle', replaceTitle)
	})
</script>

<style lang="less" scoped>
	.left-nav {
		width: var(--left-nav-collapse-width, 30rem);
		height: 100%;
		background-color: #fff;
		overflow: hidden;
		display: flex;
		flex-direction: column;
		&,
		& * {
			transition: width 0.2s ease-in-out;
		}
		&.collapse {
			--left-nav-collapse-width: 9.4rem;
			--collapse-top-padding: 4.6rem 0 0 0;
			--collapse-create-btn-width: 5.1rem;
			--collapse-menu-item-width: 50%;
			--collapse-menu-item-icon-margin-right: 0;
		}
		> .top {
			display: flex;
			align-items: center;
			justify-content: center;
			padding: var(--collapse-top-padding, 2.6rem 1.6rem 0 3.6rem);
			> .logo-img {
				width: 3.4rem;
				height: auto;
				margin-right: 1rem;
			}
			> .logo-text {
				font-family: SemiBold;
				font-weight: 600;
				font-size: 3rem;
				margin-right: auto;
			}
		}
		> .create-btn {
			margin: 4.5rem auto 2.5rem;
			width: var(--collapse-create-btn-width, 23rem);
			height: 5.1rem;
			border-radius: 5rem;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #fff;
			background-color: rgba(255, 122, 81, 1);
			border: none;
			outline: none;
			&:active {
				background-color: rgba(255, 122, 81, 0.8);
			}

			> .text {
				font-weight: 500;
				font-size: 1.8rem;
				margin-left: 1rem;
			}
		}
		> .menu-item {
			width: var(--collapse-menu-item-width, 23rem);
			margin: 2.5rem auto 0;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			border-radius: 8px;
			padding: 0.9rem 0.8rem;
			> * {
				margin-right: 1.6rem;
				&:last-child {
					margin-right: 0;
				}
			}
			&:hover {
				background-color: rgba(0, 0, 0, 0.06);
			}
			> .title {
				flex: 1;
				font-weight: 500;
				font-size: 2rem;
			}
			> .icon {
				transition: transform 0.2s ease-in-out;
				margin-right: var(--collapse-menu-item-icon-margin-right, 1.6rem);
			}
			&.active > .jiantou {
				transform: rotate(90deg);
			}
		}
		> .history-list {
			flex: 1;
			overflow-y: auto;
			width: 26.4rem;
			padding: 0 1.5rem;
			margin: 1rem auto 0;
			> .history-item {
				width: 100%;
				height: 4rem;
				margin-bottom: 0.4rem;
				> div {
					width: 100%;
					height: 100%;
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 0 0.8rem;
				}
				> .title {
					font-weight: 600;
					font-size: 1.6rem;
					font-family: SemiBold;
				}
				> .box {
					font-family: Regular;
					border-radius: 0.8rem;
					cursor: pointer;
					&.active,
					&:hover {
						background-color: rgba(0, 0, 0, 0.06);
					}
					&.active {
						font-family: SemiBold;
					}
					> .label {
						flex: 1;
						font-weight: 400;
						font-size: 1.6rem;
						text-overflow: ellipsis;
						white-space: nowrap;
						overflow: hidden;
					}
					> input {
						flex: 1;
						width: 0;
						height: 100%;
						border: none;
						outline: none;
						background-color: transparent;
					}
					> .icon {
						width: 2.5rem;
						height: 2.5rem;
					}
				}
			}
		}
	}
	.history-item-menu {
		user-select: none;

		> div {
			cursor: pointer;
			padding: 0.6rem 0.7rem;
			display: flex;
			font-size: 1.3rem;
			> .icon {
				margin-right: 0.8rem;
			}
			&:hover {
				background-color: rgba(0, 0, 0, 0.06);
			}
		}
		> .rename {
			color: #000;
		}
		> .delete {
			color: #ff4747;
		}
	}
</style>
