<template>
	<el-drawer v-model="modelValue" :before-close="handleClose" :title="`${title}${loading ? '（思考中...）' : ''}`" direction="ltr">
		<el-scrollbar ref="scrollbarRef">
			<div ref="scrollBox">
				<template v-for="(item, i) in chatList" :key="item.time">
					<template v-if="item.isMe">
						<div class="flex justify-end">
							<div class="padding-sm radius bg-el-border-color-lighter" style="display: inline-block">
								{{ item.content }}
							</div>
						</div>
						<div class="text-el-placeholder text-xs text-right margin-bottom margin-top-xs">{{ formatTime(item.time) }}</div>
					</template>

					<template v-else>
						<div class="flex justify-start">
							<div class="padding-sm radius bg-el-color-primary text-white" style="display: inline-block">
								{{ item.content }}
							</div>
						</div>
						<div class="text-el-placeholder text-xs margin-bottom margin-top-xs">{{ formatTime(item.time) }}</div>
					</template>
				</template>
			</div>
		</el-scrollbar>

		<template #footer>
			<div class="flex">
				<el-input v-model="queryText" placeholder="说点什么" class="flex-sub" :disabled="loading" @keyup.enter="handleSentChat">
					<template #append>
						<el-button :disabled="loading" @click="handleSentChat">发送</el-button>
					</template>
				</el-input>
			</div>
		</template>
	</el-drawer>
</template>

<script setup>
import { getAccessToken, requestChat } from '@/api/baidubce/unit';
import { parseStrEmpty } from '@/utils/ruoyi';
import ErrorCode from '@/utils/errorCode';
import { formatTime } from '@/utils/index';

const { proxy } = getCurrentInstance();
const loading = ref(false);
const modelValue = ref(false);
const title = ref('智能客服');
const queryText = ref('你好');
const access_token = ref(null);
const terminal_id = ref(`${proxy.$store.state.user.user.userId}-${new Date().getTime()}`);
const log_id = ref(`${proxy.$store.state.user.user.userId}-${new Date().getTime()}`);
const chatList = ref([
	{
		isMe: false,
		content: '你好呀，有什么问题需要提问呢？',
		time: new Date().getTime()
	}
	// {
	// 	isMe: true,
	// 	content: '你好',
	// 	time: 1697165377846
	// },
	// {
	// 	isMe: false,
	// 	content: '你好，需要我为你做什么',
	// 	time: 1697165379743
	// },
	// {
	// 	isMe: true,
	// 	content: '广州天气',
	// 	time: 1697165388446
	// },
	// {
	// 	isMe: false,
	// 	content: '初春天气暖如和,万里广州同放歌,岭上梅花开烂漫,东风一夜满山坡',
	// 	time: 1697165390537
	// },
	// {
	// 	isMe: true,
	// 	content: '广州天气',
	// 	time: 1697165392714
	// },
	// {
	// 	isMe: false,
	// 	content: '东风昨夜送春回,万树梅花次第开,天气清和人意好,广州城里有楼台',
	// 	time: 1697165394617
	// },
	// {
	// 	isMe: true,
	// 	content: '广州天气',
	// 	time: 1697165397156
	// },
	// {
	// 	isMe: false,
	// 	content: '一夜西风到帝州,广寒宫里月如钩,气吞云梦三千界,血染将军十二楼',
	// 	time: 1697165399043
	// },
	// {
	// 	isMe: true,
	// 	content: '广州天气',
	// 	time: 1697165401210
	// },
	// {
	// 	isMe: false,
	// 	content: '广州城中春日长,天气清和草木香,梅花落尽见桃李,一夜东风吹海棠',
	// 	time: 1697165402664
	// },
	// {
	// 	isMe: true,
	// 	content: '广州天气',
	// 	time: 1697165404399
	// },
	// {
	// 	isMe: false,
	// 	content: '广州城西白玉楼,江南天气正清秋,梅花落尽无人管,付与东风自在流',
	// 	time: 1697165406401
	// },
	// {
	// 	isMe: true,
	// 	content: '广州天气',
	// 	time: 1697165407700
	// },
	// {
	// 	isMe: false,
	// 	content: '西风昨夜到瀛州,广厦千间一望收,气爽天高云淡日,将军何处觅封侯',
	// 	time: 1697165409617
	// }
]);

// const props = defineProps({
// 	modelValue: {
// 		type: Boolean,
// 		default: true
// 	}
// });

// const modelValue = computed({
// 	get: () => {
// 		return props.modelValue;
// 	},
// 	set: (value) => {
// 		proxy.$emit('update:modelValue', value);
// 	}
// });
const show = () => {
    modelValue.value = true;
}

const handleClose = () => {
    modelValue.value = false;
}

const handleSentChat = () => {
	let query = parseStrEmpty(queryText.value);
	// console.log(query.length);
	if (query.length === 0) {
		proxy.$modal.msgWarning(ErrorCode.noText);
		return;
	}
	chatList.value.push({
		isMe: true,
		content: query,
		time: new Date().getTime()
	});
	// console.log(`aaaaaaaaaaaa`);
	loading.value = true;
	requestChat({
		access_token: access_token.value,
		version: '2.0',
		service_id: 'S100210',
		 // service_id: 'S100654',
		session_id: '',
		log_id: log_id.value,
		request: {
			user_id: proxy.$store.state.user.user.userId,
			terminal_id: terminal_id.value,
			query: query
		}
	})
		.then((response) => {
			loading.value = false;
			queryText.value = '';
			console.log(response);
			let responseTextList = response.result.response_list.map((item) => {
				if (Array.isArray(item.action_list)) {
					console.log(item.action_list[0].say);
					return item.action_list[0].say;
				}
				// console.log();
				else return '不会';
			});
			responseTextList = responseTextList.filter((item) => item.indexOf('不会') == -1 && item.indexOf('不知道') == -1 && item.indexOf('没有') == -1);
			console.log(response.result.response_list[0].action_list[0].say);
			console.log(responseTextList);
			chatList.value.push({
				isMe: false,
				content: responseTextList[1] || responseTextList[0] || `不好意思，我没有理解您的问题`,
				time: new Date().getTime()
			});
			console.log(chatList.value);
			nextTick(() => {
				proxy.$refs['scrollbarRef'].setScrollTop(proxy.$refs['scrollBox'].offsetHeight);
				console.log(proxy.$refs);
				console.log(proxy.$refs['scrollBox']);
			});
		})
		.catch(() => {
			loading.value = false;
		});
};

getAccessToken({
	grant_type: 'client_credentials',
	client_id: 'lfYAuSUCSppblSobMFMtBg0E',
	client_secret: 'RaikBXs8RY7lGuU13UFVsyMnMQWhG6XU',
	// grant_type: 'client_credentials',
	// client_id: 'Q59ZgZ2fkwyRA6NgCTBDdnoB',
	// client_secret: '1Z9UTHCRt6nyyhM9Xyl0b3Bn5xpp0YFn'
}).then((response) => {
	// console.log(response);
	access_token.value = response.access_token;
});

defineExpose({
    show,
    handleClose,
});
</script>
