waterassaydata4.vue 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. <template>
  2. <div class="region-average-chart">
  3. <!-- 重金属选择器 -->
  4. <div class="metal-selector" v-if="!loading && !error && metals.length > 0">
  5. <label for="metal-select">选择重金属:</label>
  6. <select id="metal-select" v-model="selectedMetal">
  7. <option v-for="metal in metals" :key="metal" :value="metal">{{ metal }}</option>
  8. </select>
  9. </div>
  10. <!-- 图表容器 -->
  11. <div ref="chartRef" class="chart-box"></div>
  12. <!-- 状态信息 -->
  13. <div v-if="loading" class="status">数据加载中...</div>
  14. <div v-else-if="error" class="status error">{{ error }}</div>
  15. <div v-else-if="metals.length === 0" class="status">没有有效的重金属数据</div>
  16. </div>
  17. </template>
  18. <script setup>
  19. import { ref, onMounted, onUnmounted, watch } from 'vue';
  20. import * as echarts from 'echarts';
  21. import axios from 'axios';
  22. // ========== 接口配置 ==========
  23. const SAMPLING_API = 'http://localhost:3000/table/Water_sampling_data';
  24. const ASSAY_API = 'http://localhost:3000/table/Water_assay_data';
  25. // ========== 配置项 ==========
  26. const EXCLUDE_FIELDS = [
  27. 'water_assay_ID', 'sample_code', 'assayer_ID', 'assay_time',
  28. 'assay_instrument_model', 'water_sample_ID', 'pH'
  29. ];
  30. const COLORS = [
  31. '#FF6B6B', '#4ECDC4', '#FFD166', '#6A4C93', '#1982C4',
  32. '#FF9F1C', '#2EC4B6', '#E71D36', '#3A86FF', '#FF006E'
  33. ];
  34. // 韶关市下属行政区划
  35. const SG_REGIONS = [
  36. '浈江区', '武江区', '曲江区', '乐昌市',
  37. '南雄市', '始兴县', '仁化县', '翁源县',
  38. '新丰县', '乳源瑶族自治县'
  39. ];
  40. // ========== 响应式数据 ==========
  41. const chartRef = ref(null);
  42. const loading = ref(true);
  43. const error = ref('');
  44. // 修复 selectedMetal 未定义问题:提前声明变量
  45. const selectedMetal = ref('');
  46. const metals = ref([]);
  47. const chartData = ref(null);
  48. let myChart = null;
  49. // ========== 地区提取函数 ==========
  50. const extractRegion = (location) => {
  51. if (!location || typeof location !== 'string') return null;
  52. // 1. 精确匹配官方区县名称
  53. const officialMatch = SG_REGIONS.find(region =>
  54. location.includes(region)
  55. );
  56. if (officialMatch) return officialMatch;
  57. // 2. 处理嵌套格式(如"韶关市-浈江区")
  58. const nestedMatch = location.match(/(韶关市)([^市]+?[区市县])/);
  59. if (nestedMatch && nestedMatch[2]) {
  60. const region = nestedMatch[2].replace("韶关市", "").trim();
  61. // 验证是否为合法区县
  62. const validRegion = SG_REGIONS.find(r => r.includes(region));
  63. if (validRegion) return validRegion;
  64. }
  65. // 3. 特殊格式处理(如"韶关市浈江区")
  66. const shortMatch = location.match(/韶关市([区市县][^市]{2,5})/);
  67. if (shortMatch && shortMatch[1]) return shortMatch[1];
  68. // 4. 修正常见拼写错误
  69. if (location.includes('乐昌')) return '乐昌市';
  70. if (location.includes('乳源')) return '乳源瑶族自治县';
  71. console.warn(`⚠️ 未识别地区: ${location}`);
  72. return '未知区县';
  73. };
  74. // ========== 数据处理流程 ==========
  75. const processMergedData = (samplingData, assayData) => {
  76. // 1. 构建采样点ID到区县的映射
  77. const regionMap = new Map();
  78. const uniqueSampleIds = new Set();
  79. samplingData.forEach(item => {
  80. const region = extractRegion(item.sampling_location || '');
  81. if (region && region !== '未知区县') {
  82. regionMap.set(item.water_sample_ID, region);
  83. }
  84. });
  85. // 2. 关联重金属数据与区县
  86. const mergedData = assayData.map(item => ({
  87. ...item,
  88. region: regionMap.get(item.water_sample_ID) || '未知区县'
  89. }));
  90. // 3. 识别重金属字段
  91. const detectedMetals = Object.keys(mergedData[0] || {})
  92. .filter(key => !EXCLUDE_FIELDS.includes(key) && !isNaN(parseFloat(mergedData[0][key])));
  93. metals.value = detectedMetals;
  94. if (detectedMetals.length > 0 && !selectedMetal.value) {
  95. selectedMetal.value = detectedMetals[0];
  96. }
  97. // 4. 按区县分组统计
  98. const regionGroups = {};
  99. mergedData.forEach(item => {
  100. const region = item.region;
  101. const sampleId = item.water_sample_ID;
  102. if (sampleId) uniqueSampleIds.add(sampleId);
  103. // 初始化区县数据
  104. if (!regionGroups[region]) {
  105. regionGroups[region] = {};
  106. detectedMetals.forEach(metal => {
  107. regionGroups[region][metal] = { sum: 0, count: 0 };
  108. });
  109. }
  110. // 统计重金属数据
  111. detectedMetals.forEach(metal => {
  112. const val = parseFloat(item[metal]);
  113. if (!isNaN(val)) {
  114. regionGroups[region][metal].sum += val;
  115. regionGroups[region][metal].count++;
  116. }
  117. });
  118. });
  119. // 5. 构建扇形图数据
  120. const pieSeriesData = detectedMetals.map(metal => {
  121. // 该重金属在各区县的平均浓度总和
  122. let totalAverage = 0;
  123. // 收集各区县该重金属的平均值
  124. const regionAverages = SG_REGIONS.map(region => {
  125. if (!regionGroups[region]) return null;
  126. const group = regionGroups[region][metal];
  127. const avg = group.count ? group.sum / group.count : 0;
  128. totalAverage += avg;
  129. return {
  130. name: region,
  131. value: avg
  132. };
  133. }).filter(Boolean);
  134. // 计算占比
  135. const seriesData = regionAverages.map(item => ({
  136. name: item.name,
  137. value: totalAverage > 0 ? (item.value / totalAverage) * 100 : 0,
  138. rawValue: item.value // 保留原始浓度值用于显示
  139. }));
  140. return {
  141. metal,
  142. seriesData
  143. };
  144. });
  145. return {
  146. regions: SG_REGIONS,
  147. pieSeriesData,
  148. totalSamples: uniqueSampleIds.size
  149. };
  150. };
  151. // ========== 初始化/更新图表 ==========
  152. const initChart = () => {
  153. if (!chartRef.value || !selectedMetal.value || !chartData.value) return;
  154. if (myChart) myChart.dispose();
  155. myChart = echarts.init(chartRef.value);
  156. // 获取当前重金属的数据
  157. const currentMetalData = chartData.value.pieSeriesData.find(
  158. item => item.metal === selectedMetal.value
  159. );
  160. if (!currentMetalData) return;
  161. const option = {
  162. title: {
  163. text: `韶关市${selectedMetal.value}平均浓度区域占比`,
  164. left: 'center',
  165. subtext: `数据来源: ${chartData.value.totalSamples}个有效检测样本`
  166. },
  167. tooltip: {
  168. trigger: 'item',
  169. formatter: function(params) {
  170. return `${params.name}<br/>
  171. ${selectedMetal.value}: ${params.data.rawValue.toFixed(4)} mg/L<br/>
  172. 占比: ${params.percent}%`;
  173. }
  174. },
  175. legend: {
  176. orient: 'vertical',
  177. right: 10,
  178. top: 'center',
  179. data: currentMetalData.seriesData.map(item => item.name)
  180. },
  181. series: [
  182. {
  183. name: selectedMetal.value,
  184. type: 'pie',
  185. radius: ['35%', '65%'],
  186. center: ['45%', '50%'],
  187. avoidLabelOverlap: false,
  188. itemStyle: {
  189. borderRadius: 10,
  190. borderColor: '#fff',
  191. borderWidth: 2
  192. },
  193. label: {
  194. show: false,
  195. position: 'center'
  196. },
  197. emphasis: {
  198. label: {
  199. show: true,
  200. fontSize: '16',
  201. fontWeight: 'bold',
  202. formatter: '{b}\n{c}%'
  203. }
  204. },
  205. labelLine: {
  206. show: false
  207. },
  208. data: currentMetalData.seriesData
  209. }
  210. ],
  211. color: COLORS
  212. };
  213. myChart.setOption(option);
  214. };
  215. // ========== 生命周期钩子 ==========
  216. onMounted(async () => {
  217. try {
  218. // 修复请求超时问题:将超时时间延长至10秒
  219. const [samplingRes, assayRes] = await Promise.all([
  220. axios.get(SAMPLING_API, { timeout: 10000 }), // 10秒超时
  221. axios.get(ASSAY_API, { timeout: 10000 })
  222. ]);
  223. chartData.value = processMergedData(samplingRes.data, assayRes.data);
  224. initChart();
  225. } catch (err) {
  226. // 处理超时错误
  227. if (err.code === 'ECONNABORTED') {
  228. error.value = '请求超时:服务器响应时间超过10秒';
  229. } else {
  230. error.value = '数据加载失败: ' + (err.message || '未知错误');
  231. }
  232. console.error('接口错误:', err);
  233. } finally {
  234. loading.value = false;
  235. }
  236. });
  237. // 监听重金属选择变化
  238. watch(selectedMetal, (newVal) => {
  239. if (newVal && myChart && chartData.value) {
  240. initChart();
  241. }
  242. });
  243. // 响应式布局
  244. const resizeHandler = () => myChart && myChart.resize();
  245. onMounted(() => window.addEventListener('resize', resizeHandler));
  246. onUnmounted(() => window.removeEventListener('resize', resizeHandler));
  247. </script>
  248. <style scoped>
  249. .region-average-chart {
  250. width: 100%;
  251. max-width: 1200px;
  252. margin: 20px auto;
  253. position: relative;
  254. }
  255. .chart-box {
  256. width: 100%;
  257. height: 600px;
  258. min-height: 400px;
  259. background-color: white;
  260. border-radius: 8px;
  261. box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
  262. }
  263. .status {
  264. position: absolute;
  265. top: 50%;
  266. left: 50%;
  267. transform: translate(-50%, -50%);
  268. padding: 15px;
  269. background: rgba(255,255,255,0.8);
  270. border-radius: 4px;
  271. text-align: center;
  272. }
  273. .error {
  274. color: #ff4d4f;
  275. font-weight: bold;
  276. }
  277. .metal-selector {
  278. margin-bottom: 15px;
  279. text-align: center;
  280. padding: 10px;
  281. }
  282. .metal-selector label {
  283. margin-right: 10px;
  284. font-weight: bold;
  285. }
  286. .metal-selector select {
  287. padding: 8px 15px;
  288. border-radius: 4px;
  289. border: 1px solid #ddd;
  290. background-color: #f8f8f8;
  291. font-size: 14px;
  292. min-width: 150px;
  293. cursor: pointer;
  294. transition: border 0.3s;
  295. }
  296. .metal-selector select:hover {
  297. border-color: #1890ff;
  298. }
  299. </style>