<template>
	<div>
		<PerformanceReport
			title="慢查询"
			:site="name"
			:reportOptions="slowQueriesOptions"
		/>
		<SiteSlowQueryDialog
			v-if="show"
			v-model="show"
			:query="selectedQuery"
			:duration="selectedQueryDuration"
		/>
	</div>
</template>

<script>
import AlertBanner from '../../AlertBanner.vue';
import PerformanceReport from './PerformanceReport.vue';
import SiteSlowQueryDialog from './SiteSlowQueryDialog.vue';

export default {
	props: ['name', 'siteVersion'],
	components: {
		PerformanceReport,
		AlertBanner,
		SiteSlowQueryDialog
	},
	data() {
		return {
			show: false,
			selectedQuery: '',
			selectedQueryDuration: 0
		};
	},
	computed: {
		slowQueriesOptions() {
			return {
				experimental: true,
				documentation: 'https://jingrow.com/docs/performance-tuning',
				data: () => this.$resources.slowQueries.data.data,
				onRowClick: row => {
					this.selectedQuery = row.query;
					this.selectedQueryDuration = row.duration;
					this.show = true;
				},
				emptyStateMessage: '未找到慢查询',
				columns: [
					{
						label: '查询',
						fieldname: 'query',
						class: 'font-mono',
						width: '600px'
					},
					{
						label: '持续时间',
						fieldname: 'duration',
						class: 'text-gray-600',
						width: 0.3,
						align: 'right',
						format: value => value.toFixed(2)
					},
					{
						label: '检查行数',
						fieldname: 'rows_examined',
						class: 'text-gray-600',
						align: 'right',
						width: 0.3
					},
					{
						label: '发送行数',
						fieldname: 'rows_sent',
						class: 'text-gray-600',
						align: 'right',
						width: 0.3
					},
					{
						label: '计数',
						fieldname: 'count',
						class: 'text-gray-600',
						align: 'right',
						width: 0.3
					}
				],
				actions: () => [
					{
						label: '刷新',
						icon: 'refresh-ccw',
						loading: this.$resources.slowQueries.loading,
						onClick: () => this.$resources.slowQueries.reload()
					}
				]
			};
		}
	},
	methods: {
		getDateTimeRange() {
			const formatDateTime = date => {
				return this.$dayjs(date).format('YYYY-MM-DD HH:mm:ss');
			};

			const now = new Date();
			const startDateTime = new Date(now.getTime() - 24 * 60 * 60 * 1000);
			const endDateTime = formatDateTime(now);
			const startDateTimeFormatted = formatDateTime(startDateTime);

			return {
				startDateTime: startDateTimeFormatted,
				endDateTime: endDateTime
			};
		}
	},
	resources: {
		slowQueries() {
			const { startDateTime, endDateTime } = this.getDateTimeRange();
			return {
				url: 'jcloud.api.analytics.mariadb_slow_queries',
				params: {
					name: this.name,
					start_datetime: startDateTime,
					stop_datetime: endDateTime,
					max_lines: 10,
					search_pattern: '.*',
					normalize_queries: true,
					analyze: false
				},
				auto: true,
				initialData: { columns: [], data: [] }
			};
		}
	}
};
</script>