<template>
	<div class="NCC-common-layout sb-records-page">
		<div class="NCC-common-layout-center">
			<!-- 1. 筛选区：紧凑卡片 -->
			<section class="sb-records-filter">
				<el-form @submit.native.prevent class="sb-records-form">
					<el-row :gutter="16">
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="关联设备">
								<el-select v-model="query.reId" placeholder="请选择" clearable filterable style="width:100%">
									<el-option v-for="item in reIdOptions" :key="item.id" :label="item.fullName" :value="item.id" />
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="查看客户">
								<el-input v-model="query.customerName" placeholder="客户名称" clearable />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="查看用户">
								<userSelect v-model="query.addUser" placeholder="请选择" />
							</el-form-item>
						</el-col>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label="记录类型">
								<el-input v-model="query.type" placeholder="记录类型" clearable />
							</el-form-item>
						</el-col>
						<template v-if="showAll">
							<el-col :xs="24" :sm="12" :md="8" :lg="6">
								<el-form-item label="设备名称">
									<el-input v-model="query.deviceName" placeholder="设备名称" clearable />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="6">
								<el-form-item label="查看内容">
									<el-input v-model="query.contentName" placeholder="故障代码、知识名等" clearable />
								</el-form-item>
							</el-col>
							<el-col :xs="24" :sm="12" :md="8" :lg="6">
								<el-form-item label="记录时间">
									<el-date-picker v-model="query.addTime" type="datetimerange" value-format="timestamp" format="yyyy-MM-dd HH:mm:ss" start-placeholder="开始" end-placeholder="结束" style="width:100%" />
								</el-form-item>
							</el-col>
						</template>
						<el-col :xs="24" :sm="12" :md="8" :lg="6">
							<el-form-item label-width="0" class="sb-records-form-actions">
								<el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
								<el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
								<el-button type="text" @click="showAll=!showAll">
									{{ showAll ? '收起' : '展开' }}
									<i :class="showAll ? 'el-icon-arrow-up' : 'el-icon-arrow-down'" style="margin-left:4px" />
								</el-button>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</section>

			<!-- 2. 主内容区：统计 + 列表 -->
			<div class="sb-records-scroll-wrap">
				<section class="sb-records-content">
					<!-- 统计卡片 -->
					<div class="sb-records-summary">
						<el-row :gutter="16">
							<el-col :xs="12" :sm="12" :md="6">
								<div class="stat-card stat-card-primary">
									<div class="stat-card-label">记录总数</div>
									<div class="stat-card-value">{{ statistics.totalCount }}</div>
								</div>
							</el-col>
							<el-col :xs="12" :sm="12" :md="6">
								<div class="stat-card stat-card-success">
									<div class="stat-card-label">完整记录</div>
									<div class="stat-card-value">{{ statistics.completeCount }}</div>
								</div>
							</el-col>
							<el-col :xs="12" :sm="12" :md="6">
								<div class="stat-card stat-card-warning">
									<div class="stat-card-label">总停留时长</div>
									<div class="stat-card-value">{{ formatDuration(statistics.totalDurationSeconds) }}</div>
								</div>
							</el-col>
							<el-col :xs="12" :sm="12" :md="6">
								<div class="stat-card stat-card-info">
									<div class="stat-card-label">平均停留</div>
									<div class="stat-card-value">{{ formatDuration(Math.round(statistics.avgDurationSeconds || 0)) }}</div>
								</div>
							</el-col>
						</el-row>
					</div>

					<!-- 列表区 -->
					<div class="sb-records-list">
						<h3 class="sb-records-list-title">查看记录列表</h3>
						<div class="sb-records-table-wrap">
							<NCC-table v-loading="listLoading" :data="list" :has-n-o="false" class="sb-records-table">
								<el-table-column type="index" label="序号" width="60" align="center" :index="indexMethod" />
								<el-table-column label="记录类型" align="left" width="100">
									<template slot-scope="scope">{{ scope.row.type || '无' }}</template>
								</el-table-column>
								<el-table-column label="设备名称" align="left" min-width="120" show-overflow-tooltip>
									<template slot-scope="scope">{{ scope.row.deviceName || scope.row.equipmentName || scope.row.reId || '无' }}</template>
								</el-table-column>
								<el-table-column label="查看内容" align="left" min-width="120" show-overflow-tooltip>
									<template slot-scope="scope">{{ scope.row.contentName || '无' }}</template>
								</el-table-column>
								<el-table-column label="查看客户" align="left" min-width="100" show-overflow-tooltip>
									<template slot-scope="scope">{{ scope.row.customerName || '无' }}</template>
								</el-table-column>
								<el-table-column label="查看用户" align="left" min-width="100">
									<template slot-scope="scope">{{ scope.row.addUser || '无' }}</template>
								</el-table-column>
								<el-table-column prop="addTime" label="记录时间" align="left" width="160" :formatter="ncc.tableDateFormat" />
							</NCC-table>
						</div>
						<pagination :total="total" :page.sync="listQuery.currentPage" :limit.sync="listQuery.pageSize" @pagination="initData" />
					</div>
				</section>

				<!-- 3. 统计图表：可折叠 -->
				<section class="sb-records-charts">
					<el-collapse v-model="chartsExpanded" @change="handleChartsExpand">
						<el-collapse-item name="charts">
							<template slot="title">
								<span class="charts-collapse-title">
									<i class="el-icon-data-analysis"></i>
									统计图表
								</span>
							</template>
							<el-row :gutter="16">
								<el-col :xs="24" :sm="24" :md="12">
									<div class="chart-card">
										<div class="chart-title">按记录类型</div>
										<div ref="chartByType" class="chart-dom"></div>
									</div>
								</el-col>
								<el-col :xs="24" :sm="24" :md="12">
									<div class="chart-card">
										<div class="chart-title">按设备名称（Top10）</div>
										<div ref="chartByEquipment" class="chart-dom"></div>
									</div>
								</el-col>
								<el-col :xs="24" :sm="24" :md="12">
									<div class="chart-card">
										<div class="chart-title">按查看内容（Top10）</div>
										<div ref="chartByContent" class="chart-dom"></div>
									</div>
								</el-col>
								<el-col :xs="24" :sm="24" :md="12">
									<div class="chart-card">
										<div class="chart-title">按客户（Top10）</div>
										<div ref="chartByCustomer" class="chart-dom"></div>
									</div>
								</el-col>
								<el-col :xs="24" :sm="24" :md="12">
									<div class="chart-card">
										<div class="chart-title">按查看用户（Top10）</div>
										<div ref="chartByUser" class="chart-dom"></div>
									</div>
								</el-col>
							</el-row>
						</el-collapse-item>
					</el-collapse>
				</section>
			</div>
		</div>
		<NCC-Form v-if="formVisible" ref="NCCForm" @refresh="refresh" />
	</div>
</template>

<script>
import request from '@/utils/request'
import NCCForm from './Form'
import echarts from 'echarts'

export default {
	components: { NCCForm },
	data() {
		return {
			showAll: false,
			query: {
				addUser: undefined,
				addTime: undefined,
				reId: undefined,
				customerName: undefined,
				type: undefined,
				deviceName: undefined,
				contentName: undefined
			},
			list: [],
			listLoading: true,
			total: 0,
			listQuery: {
				currentPage: 1,
				pageSize: 20,
				sort: 'desc',
				sidx: ''
			},
			formVisible: false,
			chartsExpanded: [], // 默认折叠；['charts'] 则展开统计图表
			statistics: {
				totalCount: 0,
				completeCount: 0,
				totalDurationSeconds: 0,
				avgDurationSeconds: 0,
				byType: [],
				byEquipment: [],
				byContent: [],
				byCustomer: [],
				byUser: []
			},
			charts: {},
			reIdOptions: []
		}
	},
	created() {
		this.getreIdOptions()
		this.initData()
		this.loadStatistics()
	},
	beforeDestroy() {
		Object.values(this.charts).forEach(chart => chart && chart.dispose())
	},
	methods: {
		indexMethod(index) {
			return (this.listQuery.currentPage - 1) * this.listQuery.pageSize + index + 1
		},
		getreIdOptions() {
			request({
				url: '/api/Extend/SbRecords/Actions/EquipmentOptions',
				method: 'GET'
			}).then(res => {
				this.reIdOptions = res.data || []
			})
		},
		loadStatistics() {
			const query = this.buildQuery()
			request({
				url: '/api/Extend/SbRecords/Actions/Statistics',
				method: 'GET',
				data: query
			}).then(res => {
				const d = res.data || {}
				this.statistics = {
					totalCount: d.totalCount != null ? d.totalCount : (d.TotalCount != null ? d.TotalCount : 0),
					completeCount: d.completeCount != null ? d.completeCount : (d.CompleteCount != null ? d.CompleteCount : 0),
					totalDurationSeconds: d.totalDurationSeconds != null ? d.totalDurationSeconds : (d.TotalDurationSeconds != null ? d.TotalDurationSeconds : 0),
					avgDurationSeconds: d.avgDurationSeconds != null ? d.avgDurationSeconds : (d.AvgDurationSeconds != null ? d.AvgDurationSeconds : 0),
					byType: d.byType || d.ByType || [],
					byEquipment: d.byEquipment || d.ByEquipment || [],
					byContent: d.byContent || d.ByContent || [],
					byCustomer: d.byCustomer || d.ByCustomer || [],
					byUser: d.byUser || d.ByUser || []
				}
				this.$nextTick(() => {
					this.renderCharts()
				})
			}).catch(() => {
				this.$nextTick(() => this.renderCharts())
			})
		},
		handleChartsExpand() {
			this.$nextTick(() => this.renderCharts())
		},
		buildQuery() {
			const _query = { ...this.listQuery, ...this.query }
			const query = {}
			for (const key in _query) {
				if (Array.isArray(_query[key])) {
					query[key] = _query[key].join()
				} else {
					query[key] = _query[key]
				}
			}
			return query
		},
		renderCharts() {
			if (!this.chartsExpanded.includes('charts')) return
			this.$nextTick(() => {
				this.renderPie('chartByType', this.statistics.byType, '记录类型')
				this.renderBar('chartByEquipment', this.statistics.byEquipment, '设备名称')
				this.renderBar('chartByContent', this.statistics.byContent, '查看内容')
				this.renderBar('chartByCustomer', this.statistics.byCustomer, '客户')
				this.renderBar('chartByUser', this.statistics.byUser, '查看用户')
			})
		},
		formatDuration(seconds) {
			if (seconds == null || seconds < 0) return '0秒'
			if (seconds < 60) return seconds + '秒'
			if (seconds < 3600) return Math.floor(seconds / 60) + '分' + (seconds % 60 ? seconds % 60 + '秒' : '')
			const h = Math.floor(seconds / 3600)
			const m = Math.floor((seconds % 3600) / 60)
			const s = seconds % 60
			return h + '时' + (m ? m + '分' : '') + (s ? s + '秒' : '')
		},
		renderPie(refName, data, title) {
			const el = this.$refs[refName]
			if (!el || !data || data.length === 0) {
				if (el && this.charts[refName]) this.charts[refName].dispose()
				this.charts[refName] = null
				return
			}
			if (this.charts[refName]) this.charts[refName].dispose()
			const chart = echarts.init(el)
			this.charts[refName] = chart
			const option = {
				tooltip: { trigger: 'item', formatter: '{b}: {c} ({d}%)' },
				series: [{ type: 'pie', radius: '60%', data: data.map(d => ({ name: d.name || d.Name || '-', value: d.value != null ? d.value : (d.Value != null ? d.Value : 0) })) }]
			}
			chart.setOption(option)
		},
		renderBar(refName, data, title) {
			const el = this.$refs[refName]
			if (!el) return
			if (this.charts[refName]) this.charts[refName].dispose()
			const chart = echarts.init(el)
			this.charts[refName] = chart
			const names = (data || []).map(d => ((d.name || d.Name || '-') + '').substring(0, 12))
			const values = (data || []).map(d => d.value != null ? d.value : (d.Value != null ? d.Value : 0))
			const option = {
				tooltip: { trigger: 'axis' },
				grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
				xAxis: { type: 'category', data: names.length ? names : ['暂无'] },
				yAxis: { type: 'value' },
				series: [{ type: 'bar', data: values.length ? values : [0] }]
			}
			chart.setOption(option)
		},
		initData() {
			this.listLoading = true
			const query = this.buildQuery()
			request({
				url: '/api/Extend/SbRecords',
				method: 'GET',
				data: query
			}).then(res => {
				this.list = res.data.list || []
				this.total = (res.data.pagination && res.data.pagination.total) || 0
				this.listLoading = false
			}).catch(() => {
				this.listLoading = false
			})
		},
		search() {
			this.listQuery.currentPage = 1
			this.initData()
			this.loadStatistics()
		},
		reset() {
			Object.keys(this.query).forEach(k => { this.query[k] = undefined })
			this.listQuery = { currentPage: 1, pageSize: 20, sort: 'desc', sidx: '' }
			this.initData()
			this.loadStatistics()
		},
		addOrUpdateHandle(id, isDetail) {
			this.formVisible = true
			this.$nextTick(() => this.$refs.NCCForm.init(id, isDetail))
		},
		refresh(isrRefresh) {
			this.formVisible = false
			if (isrRefresh) {
				this.initData()
				this.loadStatistics()
			}
		}
	}
}
</script>

<style lang="scss" scoped>
/* 页面整体：Data-Dense Dashboard 风格 */
.sb-records-page .NCC-common-layout-center {
	background: #F8FAFC;
	padding: 16px;
}

/* 1. 筛选区 */
.sb-records-filter {
	background: #fff;
	border-radius: 12px;
	padding: 20px;
	margin-bottom: 16px;
	box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
	flex-shrink: 0;
}
.sb-records-form {
	.el-form-item { margin-bottom: 16px; }
	.el-form-item__label { padding-right: 12px; }
}
.sb-records-form-actions {
	.el-button + .el-button { margin-left: 8px; }
}

/* 2. 可滚动内容区 */
.sb-records-scroll-wrap {
	flex: 1;
	min-height: 0;
	overflow-y: auto;
	overflow-x: hidden;
}

/* 3. 主内容区：统计 + 列表 */
.sb-records-content {
	background: #fff;
	border-radius: 12px;
	padding: 20px;
	margin-bottom: 16px;
	box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
}

/* 统计卡片 */
.sb-records-summary {
	margin-bottom: 20px;
	.el-row { margin: 0 -8px; }
	.el-col { padding: 0 8px; margin-bottom: 16px; }
	.stat-card {
		height: 100px;
		padding: 12px;
		border-radius: 12px;
		display: flex;
		flex-direction: column;
		justify-content: center;
		box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
		transition: box-shadow 0.2s ease, transform 0.2s ease;
		cursor: default;
		&:hover {
			box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
		}
		.stat-card-label {
			font-size: 13px;
			color: rgba(255, 255, 255, 0.9);
			margin-bottom: 6px;
			letter-spacing: 0.3px;
		}
		.stat-card-value {
			font-size: 22px;
			font-weight: 600;
			color: #fff;
			letter-spacing: 0.5px;
		}
		&.stat-card-primary { background: linear-gradient(135deg, #409EFF 0%, #66b1ff 100%); }
		&.stat-card-success { background: linear-gradient(135deg, #67C23A 0%, #85ce61 100%); }
		&.stat-card-warning { background: linear-gradient(135deg, #E6A23C 0%, #ebb563 100%); }
		&.stat-card-info { background: linear-gradient(135deg, #909399 0%, #a6a9ad 100%); }
	}
}

/* 列表区 */
.sb-records-list {
	.sb-records-list-title {
		font-size: 16px;
		font-weight: 600;
		color: #303133;
		margin: 0 0 16px;
		padding-bottom: 12px;
		border-bottom: 1px solid #ebeef5;
		letter-spacing: 0.3px;
	}
}
.sb-records-table-wrap {
	margin-bottom: 16px;
}
::v-deep .sb-records-table .el-table__row:hover {
	background-color: #f5f7fa;
}

/* 4. 统计图表 */
.sb-records-charts {
	background: #fff;
	border-radius: 12px;
	padding: 0;
	margin-bottom: 16px;
	box-shadow: 0 1px 4px rgba(0, 0, 0, 0.06);
	overflow: hidden;
}
.sb-records-charts .charts-collapse-title {
	font-size: 14px;
	font-weight: 600;
	letter-spacing: 0.3px;
	i { margin-right: 8px; color: #409EFF; }
}
.sb-records-charts .el-row { margin: 0 -8px; }
.sb-records-charts .el-col { padding: 0 8px; margin-bottom: 16px; }
.sb-records-charts .chart-card {
	background: #fafbfc;
	border-radius: 8px;
	padding: 16px 20px;
	border: 1px solid #ebeef5;
	.chart-title {
		font-size: 14px;
		color: #303133;
		margin-bottom: 12px;
		font-weight: 500;
	}
	.chart-dom { height: 260px; }
}

::v-deep .el-collapse-item__header {
	height: 52px;
	font-size: 14px;
	padding: 0 20px;
	background: #fff;
}
::v-deep .el-collapse-item__content {
	padding: 20px;
	background: #fff;
}
</style>
