import {moduleRequest} from '@/utils/request'
import Mock from 'mockjs'
import ForEach from "lodash-es/forEach";

const request = moduleRequest(`/api/webapp/`)

// 使用 Mock.js 生成动态数据
const generateMockData = (filters = {}) => {
	const Random = Mock.Random

	// 基础数据模板
	const types = ['航空教学', '部队管理', '政治工作', '地面维修', '其他']
	const departments = ['航空学院', '军事管理系', '政治工作部', '地面维修中心', '其他部门']
	const formats = ['mp4', 'pdf', 'docx', 'pptx', 'xlsx', 'jpg', 'avi', 'wmv', 'mkv', 'other']
	const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月']

	// 根据筛选条件调整数据规模
	const getScaleFactor = () => {
		if (filters.department === 'all') return 1.0
		return 0.15 + Math.random() * 0.25 // 单个院系占总数的15%-40%
	}

	const scaleFactor = getScaleFactor()

	// 固定总容量为10TB，已使用空间根据筛选条件调整
	const TOTAL_CAPACITY = 10.0 // 固定总容量10TB

	// 生成合理的基础总数
	const baseTotalResources = Mock.mock('@integer(1500, 2500)')
	const baseUsedStorage = Mock.mock('@float(4.0, 8.0, 1, 1)') // 已使用4-8TB
	const baseViews = Mock.mock('@integer(80000, 200000)')
	const baseFavorites = Mock.mock('@integer(15000, 40000)')

	// 根据筛选条件调整摘要数据
	const adjustedTotalResources = Math.floor(baseTotalResources * scaleFactor)
	const adjustedUsedStorage = (baseUsedStorage * scaleFactor).toFixed(1)
	const adjustedViews = Math.floor(baseViews * scaleFactor)
	const adjustedFavorites = Math.floor(baseFavorites * scaleFactor)

	// 生成资源类型分布 - 确保航空教学占主导地位
	const generateTypeCounts = () => {
		const total = adjustedTotalResources
		const counts = []

		// 航空教学占40-50%
		counts[0] = Math.floor(total * (0.4 + Math.random() * 0.1))

		// 其他类型按比例分配剩余资源
		const remaining = total - counts[0]
		const ratios = [0.25, 0.2, 0.15, 0.1] // 部队管理、政治工作、地面维修、其他

		for (let i = 1; i < types.length - 1; i++) {
			counts[i] = Math.floor(remaining * ratios[i - 1] * (0.8 + Math.random() * 0.4))
		}

		// 最后一项为剩余数量
		counts[types.length - 1] = total - counts.slice(0, -1).reduce((sum, count) => sum + count, 0)

		return counts
	}

	// 生成院系分布 - 确保航空学院占主导地位
	const generateDepartmentCounts = () => {
		const total = adjustedTotalResources
		const counts = []

		// 航空学院占45-55%
		counts[0] = Math.floor(total * (0.45 + Math.random() * 0.1))

		// 其他院系按比例分配
		const remaining = total - counts[0]
		const ratios = [0.2, 0.18, 0.15, 0.12] // 军事管理系、政治工作部、地面维修中心、其他部门

		for (let i = 1; i < departments.length - 1; i++) {
			counts[i] = Math.floor(remaining * ratios[i - 1] * (0.8 + Math.random() * 0.4))
		}

		counts[departments.length - 1] = total - counts.slice(0, -1).reduce((sum, count) => sum + count, 0)

		return counts
	}

	// 生成文件格式分布 - 视频和文档类型占主导
	const generateFormatCounts = () => {
		const total = adjustedTotalResources
		const counts = new Array(formats.length).fill(0)

		// 主要格式占比
		const mainFormats = {
			mp4: 0.25, // 视频最多
			pdf: 0.2, // PDF文档
			docx: 0.15, // Word文档
			pptx: 0.12, // PPT
			jpg: 0.08, // 图片
			avi: 0.06, // 其他视频格式
			xlsx: 0.05, // Excel
			wmv: 0.04, // 视频格式
			mkv: 0.03, // 视频格式
			other: 0.02 // 其他格式
		}

		formats.forEach((format, index) => {
			const ratio = mainFormats[format] || 0.01
			counts[index] = Math.floor(total * ratio * (0.8 + Math.random() * 0.4))
		})

		// 确保总数匹配
		const currentTotal = counts.reduce((sum, count) => sum + count, 0)
		const diff = total - currentTotal
		counts[0] += diff // 将差值加到mp4上

		return counts
	}

	const typeCounts = generateTypeCounts()
	const departmentCounts = generateDepartmentCounts()
	const formatCounts = generateFormatCounts()

	return {
		filterResponse: getFilterData(),
		// 摘要数据
		summaryData: {
			code: 200,
			data: {
				totalResources: adjustedTotalResources.toLocaleString(),
				totalStorage: `${adjustedUsedStorage} TB`,
				totalCapacity: `${TOTAL_CAPACITY} TB`,
				usageRate: `${((parseFloat(adjustedUsedStorage) / TOTAL_CAPACITY) * 100).toFixed(0)}%`,
				totalViews: adjustedViews.toLocaleString(),
				totalFavorites: adjustedFavorites.toLocaleString()
			}
		},

		// 资源类型分布数据
		resourceTypeData: {
			code: 200,
			data: {
				types: types,
				typeCounts: typeCounts,
				typeStorage: typeCounts.map((count) =>
					((count / adjustedTotalResources) * parseFloat(adjustedUsedStorage)).toFixed(1)
				)
			}
		},

		// 院系分布数据
		departmentData: {
			code: 200,
			data: {
				departments: departments,
				departmentCounts: departmentCounts,
				departmentStorage: departmentCounts.map((count) =>
					((count / adjustedTotalResources) * parseFloat(adjustedUsedStorage)).toFixed(1)
				)
			}
		},

		// 可见性和热度数据
		visibilityData: {
			code: 200,
			data: {
				visibility: ['公开', '非公开'],
				visibilityCounts: [
					Math.floor(adjustedTotalResources * 0.75), // 75%公开
					Math.floor(adjustedTotalResources * 0.25) // 25%非公开
				],
				hotness: ['热门', '非热门'],
				hotnessCounts: [
					Math.floor(adjustedTotalResources * 0.2), // 20%热门
					Math.floor(adjustedTotalResources * 0.8) // 80%非热门
				],
				recommended: ['已推荐', '未推荐'],
				recommendedCounts: [
					Math.floor(adjustedTotalResources * 0.15), // 15%已推荐
					Math.floor(adjustedTotalResources * 0.85) // 85%未推荐
				]
			}
		},

		// 文件格式数据
		formatData: {
			code: 200,
			data: {
				formats: formats,
				formatCounts: formatCounts,
				formatStorage: formatCounts.map((count) =>
					((count / adjustedTotalResources) * parseFloat(adjustedUsedStorage)).toFixed(2)
				),
				formatAvgSize: formats.map((format, index) => {
					// 根据文件类型设置合理的平均大小
					const sizeMap = {
						mp4: Mock.mock('@integer(200, 800)'),
						avi: Mock.mock('@integer(300, 1000)'),
						wmv: Mock.mock('@integer(150, 600)'),
						mkv: Mock.mock('@integer(400, 1200)'),
						pdf: Mock.mock('@integer(5, 50)'),
						docx: Mock.mock('@integer(2, 20)'),
						pptx: Mock.mock('@integer(10, 100)'),
						xlsx: Mock.mock('@integer(1, 15)'),
						jpg: Mock.mock('@integer(1, 10)'),
						other: Mock.mock('@integer(5, 200)')
					}

					const size = sizeMap[format] || Mock.mock('@integer(1, 100)')
					if (size > 1000) return `${(size / 1000).toFixed(1)}GB`
					return `${size}MB`
				})
			}
		},

		// 用户参与度数据
		engagementData: {
			code: 200,
			data: {
				engagement: ['观看', '收藏', '分享'],
				engagementCounts: [
					adjustedViews,
					adjustedFavorites,
					Math.floor(adjustedFavorites * 0.3) // 分享数约为收藏数的30%
				],
				typeViewCounts: typeCounts.map((count) => Math.floor(count * (2 + Math.random() * 3))) // 每个资源平均2-5次观看
			}
		},

		// 时间趋势数据
		trendData: {
			code: 200,
			data: {
				trendLabels: months,
				uploadTrend: months.map(() => Math.floor((adjustedTotalResources / 12) * (0.6 + Math.random() * 0.8))), // 月均上传量有波动
				viewTrend: months.map(() => Math.floor((adjustedViews / 12) * (0.7 + Math.random() * 0.6))) // 月均观看量有波动
			}
		}
	}
}

// API函数 - 每次调用都生成新的动态数据，传入筛选参数
export const getSummaryData = async (params = {}) => {
	// return new Promise((resolve) => {
	// 	setTimeout(() => {
	// 		const mockData = generateMockData(params)
	// 		resolve(mockData.summaryData)
	// 	}, Mock.mock('@integer(200, 500)')) // 随机延迟
	// })

	let res = await request('/resourceStatistic/totalStatistic', params, 'get')
	console.log('什么呢1233', res)
	let json = {
		code: 200,
		data: {
			totalResources: res.RESOURCE_TOTAL,
			totalStorage: `${kbToTb(res.storageSize)}TB`,
			totalCapacity: `${kbToTb(res.totalStorageSize)}TB`,
			usageRate: `${((parseFloat(res.storageSize) / res.totalStorageSize) * 100).toFixed(0)}%`,
			totalViews: res.WATCH_TOTAL,
			totalFavorites: res.COLLECT_TOTAL
		}
	}
	// {
	// 	"RESOURCE_TOTAL": 34,  总资源数
	// 	"TOTAL_STORAGE_SIZE": 20480, 总存储空间
	// 	"COLLECT_TOTAL": 9, 总收藏数
	// 	"WATCH_TOTAL": 471, 总观看数
	// 	"storageSize": 1726487824,
	// 	"totalStorageSize": 21474836480
	// }
	// totalResources: '0',
	// totalStorage: '0 TB',
	// totalCapacity: '10 TB',
	// usageRate: '0%',
	// totalViews: '0',
	// totalFavorites: '0'
	// 真实接口调用：
	// return request('/resource-library/summary', params, 'get')
	console.log('什么呢', json)
	return json
}

function kbToTb(kb) {
	const tb = kb / 1073741824;
	return parseFloat(tb.toFixed(2));
}

export const getFilterData = async (params = {}) => {
	let colleges = await request('resourceStatistic/selectOrgList', params, 'get')
	colleges.unshift({
		id: 'all',
		name: '全部院系'
	})
	console.log("什么呢sss", colleges)
	let json = {
		code: 200,
		data: colleges
	}

	return json
}

export const getResourceTypeData = async (params = {}) => {
	let resourceTypeStatistic = await request('resourceStatistic/resourceTypeStatistic', params, 'get')
	console.log('左面的', resourceTypeStatistic)
	let types = []
	let typeCounts = []
	ForEach(resourceTypeStatistic, (item) => {
		types.push(item.resourceTypeName)
		typeCounts.push(item.num)
	})

	// types: types,
	// 	typeCounts: typeCounts,
	let json = {
		code: 200,
		data: {
			types,
			typeCounts,
			typeStorage: []
		}
	}
	return json

	// return new Promise((resolve) => {
	// 	setTimeout(() => {
	// 		const mockData = generateMockData(params)
	// 		resolve(mockData.resourceTypeData)
	// 	}, Mock.mock('@integer(200, 500)'))
	// })
	// return request('/resource-library/type-distribution', params, 'get')

}

export const getDepartmentData = async (params = {}) => {
	let collegeStatistic = await request('resourceStatistic/collegeStatistic', params, 'get')
	let departments = []
	let departmentCounts = []
	ForEach(collegeStatistic, (item) => {
		departments.push(item.collegeName)
		departmentCounts.push(item.num)
	})
	let json = {
		code: 200,
		data: {
			departments,
			departmentCounts,
			departmentStorage: []
		}
	}
	return json

	// return new Promise((resolve) => {
	// 	setTimeout(() => {
	// 		const mockData = generateMockData(params)
	// 		resolve(mockData.departmentData)
	// 	}, Mock.mock('@integer(200, 500)'))
	// })
	//
	// departments: departments,
	// 	departmentCounts: departmentCounts,
	// 	departmentStorage: departmentCounts.map((count) =>
	// return request('/resource-library/department-distribution', params, 'get')
}

export const getVisibilityData = async (params = {}) => {
	// return new Promise((resolve) => {
	// 	setTimeout(() => {
	// 		const mockData = generateMockData(params)
	// 		resolve(mockData.visibilityData)
	// 	}, Mock.mock('@integer(200, 500)'))
	// })
	let resourcePublicStatistic = await request('resourceStatistic/resourcePublicStatistic', params, 'get')
	let visibility = ['非公开', '公开']
	let visibilityCounts = []
	ForEach(resourcePublicStatistic, (item) => {
		visibilityCounts.push(item.num)
	})
	let hotness = []
	let hotnessCounts = []
	let recommended = ['已推荐', '未推荐']

	let hotStatistic = await request('resourceStatistic/hotStatistic', params, 'get')
	ForEach(hotStatistic, (item) => {
		//1推荐  2热门  3推荐和热门
		if (item.type == 1) {
			hotness.push('推荐')
		}
		if (item.type == 2) {
			hotness.push('热门')
		}
		if (item.type == 3) {
			hotness.push('推荐和热门')
		}
		hotnessCounts.push(item.num)
	})


	console.log('接口看看', hotStatistic)
	let recommendedCounts = [12, 13]


	let json = {
		code: 200,
		data: {
			visibility,
			visibilityCounts,
			hotness,
			hotnessCounts,
			recommended,
			recommendedCounts
		}
	}
	return json
	// data: {
	// 	visibility: ['公开', '非公开'],
	// 		visibilityCounts: [
	// 		Math.floor(adjustedTotalResources * 0.75), // 75%公开
	// 		Math.floor(adjustedTotalResources * 0.25) // 25%非公开
	// 	],
	// 		hotness: ['热门', '非热门'],
	// 		hotnessCounts: [
	// 		Math.floor(adjustedTotalResources * 0.2), // 20%热门
	// 		Math.floor(adjustedTotalResources * 0.8) // 80%非热门
	// 	],
	// 		recommended: ['已推荐', '未推荐'],
	// 		recommendedCounts: [
	// 		Math.floor(adjustedTotalResources * 0.15), // 15%已推荐
	// 		Math.floor(adjustedTotalResources * 0.85) // 85%未推荐
	// 	]
	// }


	// return request('/resource-library/visibility-analysis', params, 'get')
}

export const getFormatData = async (params = {}) => {
	// return new Promise((resolve) => {
	// 	setTimeout(() => {
	// 		const mockData = generateMockData(params)
	// 		resolve(mockData.formatData)
	// 	}, Mock.mock('@integer(200, 500)'))
	// })
	let formatStatistic = await request('resourceStatistic/formatStatistic', params, 'get')
	let formats = []
	let formatCounts = []
	ForEach(formatStatistic, (item) => {
		formats.push(item.extendName)
		formatCounts.push(item.num)
	})
	let storageStatistic = await request('resourceStatistic/storageStatistic', params, 'get')
	console.log('内存', storageStatistic)
	let formatAvgSize = []
	ForEach(storageStatistic, (item) => {
		formatAvgSize.push(item.extendName)
	})

	let json = {
		code: 200,
		data: {
			formats,
			formatCounts,
			formatStorage: storageStatistic.map((item) => {
					let size = (item.FILESIZE) * parseFloat(1).toFixed(2)
					console.log("asdasd", item.FILESIZE)
					return `${(item.FILESIZE / 1000 / 1000).toFixed(2)}`
				}
			),
			formatAvgSize: storageStatistic.map((format, index) => {
				// 根据文件类型设置合理的平均大小
				const size = format.avgSize
				// if (size > 1000) return `${(size / 1000).toFixed(1)}MB`
				return `${(size / 1000 / 1000).toFixed(2)}MB`
			})
		}
	}
	return json

	// formatData: {
	// 	code: 200,
	// 		data: {
	// 		formats: formats,
	// 			formatCounts: formatCounts,
	// 			formatStorage: formatCounts.map((count) =>
	// 			((count / adjustedTotalResources) * parseFloat(adjustedUsedStorage)).toFixed(2)
	// 		),
	// 			formatAvgSize: formats.map((format, index) => {
	// 			// 根据文件类型设置合理的平均大小
	// 			const sizeMap = {
	// 				mp4: Mock.mock('@integer(200, 800)'),
	// 				avi: Mock.mock('@integer(300, 1000)'),
	// 				wmv: Mock.mock('@integer(150, 600)'),
	// 				mkv: Mock.mock('@integer(400, 1200)'),
	// 				pdf: Mock.mock('@integer(5, 50)'),
	// 				docx: Mock.mock('@integer(2, 20)'),
	// 				pptx: Mock.mock('@integer(10, 100)'),
	// 				xlsx: Mock.mock('@integer(1, 15)'),
	// 				jpg: Mock.mock('@integer(1, 10)'),
	// 				other: Mock.mock('@integer(5, 200)')
	// 			}
	//
	// 			const size = sizeMap[format] || Mock.mock('@integer(1, 100)')
	// 			if (size > 1000) return `${(size / 1000).toFixed(1)}GB`
	// 			return `${size}MB`
	// 		})
	// 	}
	// },


	// return request('/resource-library/format-distribution', params, 'get')
}

export const getEngagementData = async (params = {}) => {
	// return new Promise((resolve) => {
	// 	setTimeout(() => {
	// 		const mockData = generateMockData(params)
	// 		resolve(mockData.engagementData)
	// 	}, Mock.mock('@integer(200, 500)'))
	// })
	let selectResourceUse = await request('resourceStatistic/selectResourceUse', params, 'get')
	let selectResourceCans = await request('resourceStatistic/selectResourceCans', params, 'get')
	console.log('001 ', selectResourceUse)
	console.log('003 ', selectResourceCans)
	let engagement = []
	let engagementCounts = []
	let typeViewCounts = []
	ForEach(selectResourceUse, (item) => {
		//1、资源观看 2资源收藏 3资源分享
		if (item.type == 1) {
			engagement.push('资源观看')
			engagementCounts.push(item.num)
		}
		if (item.type == 2) {
			engagement.push('资源收藏')
			engagementCounts.push(item.num)
		}
		if (item.type == 3) {
			engagement.push('资源分享')
			engagementCounts.push(item.num)
		}
	})
	ForEach(selectResourceCans, (item) => {
		//1、资源观看 2资源收藏 3资源分享
		typeViewCounts.push(item.num)
	})


	let json = {
		code: 200,
		data: {
			engagement,
			engagementCounts,
			typeViewCounts
		}
	}
	return json
	// return request('/resource-library/engagement-analysis', params, 'get')
	// 用户参与度数据
	// engagementData: {
	// 	code: 200,
	// 		data: {
	// 		engagement: ['观看', '收藏', '分享'],
	// 			engagementCounts: [
	// 			adjustedViews,
	// 			adjustedFavorites,
	// 			Math.floor(adjustedFavorites * 0.3) // 分享数约为收藏数的30%
	// 		],
	// 			typeViewCounts: typeCounts.map((count) => Math.floor(count * (2 + Math.random() * 3))) // 每个资源平均2-5次观看
	// 	}
	// },

}

export const getTrendData = async (params = {}) => {
	// return new Promise((resolve) => {
	// 	setTimeout(() => {
	// 		const mockData = generateMockData(params)
	// 		resolve(mockData.trendData)
	// 	}, Mock.mock('@integer(200, 500)'))
	// })
	let selectResourceUpload = await request('resourceStatistic/selectResourceUpload', params, 'get')
	console.log('002 ',selectResourceUpload)
	let engagement = []
	let trendLabels = []
	let uploadTrend = []
	let viewTrend = []
	ForEach(selectResourceUpload, (item) => {
		//1、资源观看 2资源收藏 3资源分享
		trendLabels.push(item.createMonth)
		uploadTrend.push(item.uploadNum)
		viewTrend.push(item.seeNum)
	})



	let json = {
		code: 200,
		data : {
			trendLabels,
			uploadTrend,
			viewTrend
		}
	}
	return json
	// 时间趋势数据
	// trendData: {
	// 	code: 200,
	// 		data: {
	// 		trendLabels: months,
	// 			uploadTrend: months.map(() => Math.floor((adjustedTotalResources / 12) * (0.6 + Math.random() * 0.8))), // 月均上传量有波动
	// 			viewTrend: months.map(() => Math.floor((adjustedViews / 12) * (0.7 + Math.random() * 0.6))) // 月均观看量有波动
	// 	}
	// }
	// return request('/resource-library/trend-analysis', params, 'get')
}
