statistics_region.php 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  1. <?php
  2. /**
  3. * 地区统计分析模块
  4. *
  5. * 包含与地区相关的数据分析功能
  6. */
  7. require_once 'statistics_utils.php';
  8. /**
  9. * 获取客户国家分布
  10. *
  11. * @param mysqli $conn 数据库连接
  12. * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  13. * @return mysqli_result 客户国家分布数据结果集
  14. */
  15. function getCustomerCountryDistribution($conn, $employee_filter = null) {
  16. $employee_condition = "";
  17. // 如果有业务员过滤条件
  18. if ($employee_filter !== null) {
  19. if (is_array($employee_filter) && !empty($employee_filter)) {
  20. // 处理数组形式的业务员ID列表
  21. $emp_ids = [];
  22. foreach ($employee_filter as $emp_id) {
  23. if (is_numeric($emp_id)) {
  24. $emp_ids[] = intval($emp_id);
  25. }
  26. }
  27. if (!empty($emp_ids)) {
  28. $emp_ids_str = implode(',', $emp_ids);
  29. $employee_condition = " WHERE cu.cs_belong IN ($emp_ids_str)";
  30. }
  31. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  32. // 处理单个业务员ID
  33. $employee_filter = intval($employee_filter);
  34. $employee_condition = " WHERE cu.cs_belong = $employee_filter";
  35. }
  36. }
  37. $sql = "SELECT
  38. c.countryName,
  39. COUNT(cu.id) as customer_count
  40. FROM customer cu
  41. JOIN country c ON cu.cs_country = c.id
  42. $employee_condition
  43. GROUP BY cu.cs_country
  44. ORDER BY customer_count DESC
  45. LIMIT 10";
  46. return $conn->query($sql);
  47. }
  48. /**
  49. * 获取不同地区的订单数量
  50. *
  51. * @param mysqli $conn 数据库连接
  52. * @param string $start_date 开始日期
  53. * @param string $end_date 结束日期
  54. * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  55. * @param int $country_filter 国家/地区ID,默认为0表示全部地区
  56. * @return mysqli_result 地区订单数据结果集
  57. */
  58. function getOrdersByRegion($conn, $start_date, $end_date, $employee_filter = null, $country_filter = 0) {
  59. $employee_condition = "";
  60. $country_condition = "";
  61. $params = [$start_date, $end_date];
  62. $types = "ss";
  63. // 如果有业务员过滤条件
  64. if ($employee_filter !== null) {
  65. if (is_array($employee_filter) && !empty($employee_filter)) {
  66. // 处理数组形式的业务员ID列表
  67. $emp_ids = [];
  68. foreach ($employee_filter as $emp_id) {
  69. if (is_numeric($emp_id)) {
  70. $emp_ids[] = intval($emp_id);
  71. }
  72. }
  73. if (!empty($emp_ids)) {
  74. $emp_ids_str = implode(',', $emp_ids);
  75. $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
  76. }
  77. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  78. // 处理单个业务员ID
  79. $employee_filter = intval($employee_filter);
  80. $employee_condition = " AND cu.cs_belong = $employee_filter";
  81. }
  82. }
  83. // 添加国家/地区筛选条件
  84. if (is_numeric($country_filter) && $country_filter > 0) {
  85. $country_filter = intval($country_filter);
  86. $country_condition = " AND cu.cs_country = $country_filter";
  87. }
  88. // 如果选择了特定国家/地区,则SQL语句不需要分组和排序,直接返回该国家/地区的数据
  89. if ($country_filter > 0) {
  90. $sql = "SELECT
  91. c.countryName,
  92. COUNT(DISTINCT o.id) as order_count,
  93. SUM(o.total_amount) as total_amount
  94. FROM orders o
  95. JOIN customer cu ON o.customer_id = cu.id
  96. JOIN country c ON cu.cs_country = c.id
  97. WHERE o.is_deleted = 0 AND o.order_date BETWEEN ? AND ?
  98. $employee_condition
  99. $country_condition
  100. GROUP BY cu.cs_country";
  101. } else {
  102. // 否则返回前10个地区的数据
  103. $sql = "SELECT
  104. c.countryName,
  105. COUNT(DISTINCT o.id) as order_count,
  106. SUM(o.total_amount) as total_amount
  107. FROM orders o
  108. JOIN customer cu ON o.customer_id = cu.id
  109. JOIN country c ON cu.cs_country = c.id
  110. WHERE o.is_deleted = 0 AND o.order_date BETWEEN ? AND ?
  111. $employee_condition
  112. GROUP BY cu.cs_country
  113. ORDER BY total_amount DESC
  114. LIMIT 10";
  115. }
  116. $stmt = $conn->prepare($sql);
  117. $stmt->bind_param($types, ...$params);
  118. $stmt->execute();
  119. return $stmt->get_result();
  120. }
  121. /**
  122. * 获取地区销售同比环比数据
  123. *
  124. * @param mysqli $conn 数据库连接
  125. * @param string $current_start 当前周期开始日期
  126. * @param string $current_end 当前周期结束日期
  127. * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  128. * @param int $country_filter 国家/地区ID,默认为0表示全部地区
  129. * @return array 地区销售同比环比数据
  130. */
  131. function getRegionSalesComparison($conn, $current_start, $current_end, $employee_filter = null, $country_filter = 0) {
  132. // 计算上一个相同时长的周期
  133. $current_start_date = new DateTime($current_start);
  134. $current_end_date = new DateTime($current_end);
  135. $interval = $current_start_date->diff($current_end_date);
  136. $prev_end_date = clone $current_start_date;
  137. $prev_end_date->modify('-1 day');
  138. $prev_start_date = clone $prev_end_date;
  139. $prev_start_date->sub($interval);
  140. $prev_start = $prev_start_date->format('Y-m-d');
  141. $prev_end = $prev_end_date->format('Y-m-d') . ' 23:59:59';
  142. // 如果有业务员过滤条件
  143. $employee_condition = "";
  144. if ($employee_filter !== null) {
  145. if (is_array($employee_filter) && !empty($employee_filter)) {
  146. // 处理数组形式的业务员ID列表
  147. $emp_ids = [];
  148. foreach ($employee_filter as $emp_id) {
  149. if (is_numeric($emp_id)) {
  150. $emp_ids[] = intval($emp_id);
  151. }
  152. }
  153. if (!empty($emp_ids)) {
  154. $emp_ids_str = implode(',', $emp_ids);
  155. $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
  156. }
  157. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  158. // 处理单个业务员ID
  159. $employee_filter = intval($employee_filter);
  160. $employee_condition = " AND cu.cs_belong = $employee_filter";
  161. }
  162. }
  163. // 添加国家/地区筛选条件
  164. $country_condition = "";
  165. if (is_numeric($country_filter) && $country_filter > 0) {
  166. $country_filter = intval($country_filter);
  167. $country_condition = " AND cu.cs_country = $country_filter";
  168. }
  169. // 如果选择了特定国家/地区,就不需要LIMIT了
  170. $limit_clause = ($country_filter > 0) ? "" : "LIMIT 5";
  171. // 获取当前周期数据
  172. $sql = "SELECT
  173. c.countryName,
  174. COUNT(o.id) as order_count,
  175. SUM(o.total_amount) as total_amount
  176. FROM orders o
  177. JOIN customer cu ON o.customer_id = cu.id
  178. JOIN country c ON cu.cs_country = c.id
  179. WHERE o.is_deleted = 0 AND o.order_date BETWEEN ? AND ?
  180. $employee_condition
  181. $country_condition
  182. GROUP BY cu.cs_country
  183. ORDER BY total_amount DESC
  184. $limit_clause";
  185. $stmt = $conn->prepare($sql);
  186. $stmt->bind_param("ss", $current_start, $current_end);
  187. $stmt->execute();
  188. $current_result = $stmt->get_result();
  189. $current_data = [];
  190. while ($row = $current_result->fetch_assoc()) {
  191. $current_data[$row['countryName']] = [
  192. 'order_count' => $row['order_count'],
  193. 'total_amount' => $row['total_amount']
  194. ];
  195. }
  196. // 获取上一个周期数据
  197. $stmt = $conn->prepare($sql);
  198. $stmt->bind_param("ss", $prev_start, $prev_end);
  199. $stmt->execute();
  200. $prev_result = $stmt->get_result();
  201. $prev_data = [];
  202. while ($row = $prev_result->fetch_assoc()) {
  203. $prev_data[$row['countryName']] = [
  204. 'order_count' => $row['order_count'],
  205. 'total_amount' => $row['total_amount']
  206. ];
  207. }
  208. // 计算同比变化
  209. $comparison_data = [];
  210. foreach ($current_data as $country => $current) {
  211. $prev = $prev_data[$country] ?? ['order_count' => 0, 'total_amount' => 0];
  212. $order_growth = $prev['order_count'] > 0
  213. ? (($current['order_count'] - $prev['order_count']) / $prev['order_count']) * 100
  214. : 100;
  215. $amount_growth = $prev['total_amount'] > 0
  216. ? (($current['total_amount'] - $prev['total_amount']) / $prev['total_amount']) * 100
  217. : 100;
  218. $comparison_data[] = [
  219. 'countryName' => $country,
  220. 'current_orders' => $current['order_count'],
  221. 'prev_orders' => $prev['order_count'],
  222. 'order_growth' => $order_growth,
  223. 'current_amount' => $current['total_amount'],
  224. 'prev_amount' => $prev['total_amount'],
  225. 'amount_growth' => $amount_growth
  226. ];
  227. }
  228. return $comparison_data;
  229. }
  230. /**
  231. * 渲染客户国家分布图
  232. *
  233. * @param array $country_labels 国家标签
  234. * @param array $country_data 国家数据
  235. * @return void
  236. */
  237. function renderCustomerCountryDistributionChart($country_labels, $country_data) {
  238. ?>
  239. <div class="chart-container country-distribution-chart">
  240. <div class="chart-header">
  241. <h2 class="chart-title">客户国家分布</h2>
  242. </div>
  243. <canvas id="countryDistributionChart"></canvas>
  244. </div>
  245. <style>
  246. /* 响应式布局:手机端全宽,PC端1/3宽度 */
  247. .country-distribution-chart {
  248. width: 100%;
  249. margin: 0 auto;
  250. }
  251. @media (min-width: 768px) {
  252. .country-distribution-chart {
  253. max-width: 33.333%;
  254. }
  255. }
  256. </style>
  257. <script>
  258. // 客户国家分布图
  259. var countryDistributionCtx = document.getElementById('countryDistributionChart').getContext('2d');
  260. var countryDistributionChart = new Chart(countryDistributionCtx, {
  261. type: 'pie',
  262. data: {
  263. labels: <?php echo json_encode($country_labels); ?>,
  264. datasets: [{
  265. data: <?php echo json_encode($country_data); ?>,
  266. backgroundColor: [
  267. 'rgba(255, 99, 132, 0.7)',
  268. 'rgba(54, 162, 235, 0.7)',
  269. 'rgba(255, 206, 86, 0.7)',
  270. 'rgba(75, 192, 192, 0.7)',
  271. 'rgba(153, 102, 255, 0.7)',
  272. 'rgba(255, 159, 64, 0.7)',
  273. 'rgba(199, 199, 199, 0.7)',
  274. 'rgba(83, 102, 255, 0.7)',
  275. 'rgba(40, 159, 64, 0.7)',
  276. 'rgba(210, 199, 199, 0.7)'
  277. ],
  278. borderWidth: 1
  279. }]
  280. },
  281. options: {
  282. responsive: true,
  283. plugins: {
  284. legend: {
  285. position: 'right',
  286. }
  287. }
  288. }
  289. });
  290. </script>
  291. <?php
  292. }
  293. /**
  294. * 渲染地区订单分析图
  295. *
  296. * @param array $region_labels 地区标签
  297. * @param array $region_orders 地区订单数量
  298. * @return void
  299. */
  300. function renderRegionOrdersChart($region_labels, $region_orders) {
  301. ?>
  302. <div class="chart-header">
  303. <h2 class="chart-title">地区订单分析</h2>
  304. </div>
  305. <div class="region-orders-chart-container">
  306. <canvas id="regionOrdersChart"></canvas>
  307. </div>
  308. <style>
  309. /* 响应式布局:调整图表高度 */
  310. .region-orders-chart-container {
  311. width: 100%;
  312. height: auto;
  313. }
  314. @media (min-width: 768px) {
  315. .region-orders-chart-container {
  316. height: 33vh; /* 视窗高度的1/3 */
  317. }
  318. }
  319. </style>
  320. <script>
  321. // 地区订单分析图
  322. var regionOrdersCtx = document.getElementById('regionOrdersChart').getContext('2d');
  323. var regionOrdersChart = new Chart(regionOrdersCtx, {
  324. type: 'bar',
  325. data: {
  326. labels: <?php echo json_encode($region_labels); ?>,
  327. datasets: [
  328. {
  329. label: '订单数量',
  330. data: <?php echo json_encode($region_orders); ?>,
  331. backgroundColor: 'rgba(54, 162, 235, 0.6)',
  332. borderColor: 'rgba(54, 162, 235, 1)',
  333. borderWidth: 1
  334. }
  335. ]
  336. },
  337. options: {
  338. responsive: true,
  339. maintainAspectRatio: false, // 允许图表高度自适应
  340. scales: {
  341. x: {
  342. title: {
  343. display: true,
  344. text: '地区'
  345. }
  346. },
  347. y: {
  348. title: {
  349. display: true,
  350. text: '订单数量'
  351. },
  352. beginAtZero: true
  353. }
  354. }
  355. }
  356. });
  357. </script>
  358. <?php
  359. }
  360. /**
  361. * 渲染地区销售同比环比表格
  362. *
  363. * @param array $comparison_data 比较数据
  364. * @return void
  365. */
  366. function renderRegionSalesComparisonTable($comparison_data) {
  367. ?>
  368. <div class="chart-container">
  369. <div class="chart-header">
  370. <h2 class="chart-title">地区销售同比分析</h2>
  371. </div>
  372. <div class="region-sales-comparison-container">
  373. <table class="data-table">
  374. <thead>
  375. <tr>
  376. <th>国家/地区</th>
  377. <th>当前订单数</th>
  378. <th>上期订单数</th>
  379. <th>订单增长率</th>
  380. <th>当前销售额</th>
  381. <th>上期销售额</th>
  382. <th>销售额增长率</th>
  383. </tr>
  384. </thead>
  385. <tbody>
  386. <?php foreach ($comparison_data as $row): ?>
  387. <tr>
  388. <td><?php echo htmlspecialchars($row['countryName']); ?></td>
  389. <td><?php echo number_format($row['current_orders']); ?></td>
  390. <td><?php echo number_format($row['prev_orders']); ?></td>
  391. <td class="<?php echo $row['order_growth'] >= 0 ? 'positive' : 'negative'; ?>">
  392. <?php echo number_format($row['order_growth'], 2); ?>%
  393. </td>
  394. <td>¥<?php echo number_format($row['current_amount'], 2); ?></td>
  395. <td>¥<?php echo number_format($row['prev_amount'], 2); ?></td>
  396. <td class="<?php echo $row['amount_growth'] >= 0 ? 'positive' : 'negative'; ?>">
  397. <?php echo number_format($row['amount_growth'], 2); ?>%
  398. </td>
  399. </tr>
  400. <?php endforeach; ?>
  401. </tbody>
  402. </table>
  403. </div>
  404. </div>
  405. <style>
  406. /* 响应式布局:调整表格容器 */
  407. .region-sales-comparison-container {
  408. width: 100%;
  409. overflow-x: auto;
  410. }
  411. @media (min-width: 768px) {
  412. .region-sales-comparison-container {
  413. max-height: 33vh; /* 视窗高度的1/3 */
  414. overflow-y: auto;
  415. }
  416. }
  417. </style>
  418. <?php
  419. }
  420. /**
  421. * 获取地区总销售额
  422. *
  423. * @param mysqli $conn 数据库连接
  424. * @param string $start_date 开始日期
  425. * @param string $end_date 结束日期
  426. * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  427. * @param int $country_filter 国家/地区ID,默认为0表示全部地区
  428. * @return array 总销售额和增长率
  429. */
  430. function getRegionTotalSales($conn, $start_date, $end_date, $employee_filter = null, $country_filter = 0) {
  431. // 如果有业务员过滤条件
  432. $employee_condition = "";
  433. if ($employee_filter !== null) {
  434. if (is_array($employee_filter) && !empty($employee_filter)) {
  435. // 处理数组形式的业务员ID列表
  436. $emp_ids = [];
  437. foreach ($employee_filter as $emp_id) {
  438. if (is_numeric($emp_id)) {
  439. $emp_ids[] = intval($emp_id);
  440. }
  441. }
  442. if (!empty($emp_ids)) {
  443. $emp_ids_str = implode(',', $emp_ids);
  444. $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
  445. }
  446. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  447. // 处理单个业务员ID
  448. $employee_filter = intval($employee_filter);
  449. $employee_condition = " AND cu.cs_belong = $employee_filter";
  450. }
  451. }
  452. // 添加国家/地区筛选条件
  453. $country_condition = "";
  454. if (is_numeric($country_filter) && $country_filter > 0) {
  455. $country_condition = " AND cu.cs_country = " . intval($country_filter);
  456. }
  457. // 计算当前周期销售额
  458. $sql = "SELECT SUM(o.total_amount) as total_amount
  459. FROM orders o
  460. JOIN customer cu ON o.customer_id = cu.id
  461. WHERE o.is_deleted = 0 AND o.order_date BETWEEN ? AND ?
  462. $employee_condition
  463. $country_condition";
  464. $stmt = $conn->prepare($sql);
  465. $stmt->bind_param("ss", $start_date, $end_date);
  466. $stmt->execute();
  467. $result = $stmt->get_result();
  468. $row = $result->fetch_assoc();
  469. $current_amount = $row['total_amount'] ?? 0;
  470. // 计算上一个相同时长的周期
  471. $current_start_date = new DateTime($start_date);
  472. $current_end_date = new DateTime($end_date);
  473. $interval = $current_start_date->diff($current_end_date);
  474. $prev_end_date = clone $current_start_date;
  475. $prev_end_date->modify('-1 day');
  476. $prev_start_date = clone $prev_end_date;
  477. $prev_start_date->sub($interval);
  478. $prev_start = $prev_start_date->format('Y-m-d');
  479. $prev_end = $prev_end_date->format('Y-m-d') . ' 23:59:59';
  480. // 获取上一周期销售额
  481. $stmt = $conn->prepare($sql);
  482. $stmt->bind_param("ss", $prev_start, $prev_end);
  483. $stmt->execute();
  484. $result = $stmt->get_result();
  485. $row = $result->fetch_assoc();
  486. $prev_amount = $row['total_amount'] ?? 0;
  487. // 计算增长率
  488. $growth = 0;
  489. if ($prev_amount > 0) {
  490. $growth = (($current_amount - $prev_amount) / $prev_amount) * 100;
  491. }
  492. return [
  493. 'total_amount' => $current_amount,
  494. 'growth' => $growth
  495. ];
  496. }
  497. /**
  498. * 获取活跃国家数
  499. *
  500. * @param mysqli $conn 数据库连接
  501. * @param string $start_date 开始日期
  502. * @param string $end_date 结束日期
  503. * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  504. * @param int $country_filter 国家/地区ID,默认为0表示全部地区
  505. * @return array 活跃国家信息
  506. */
  507. function getActiveCountries($conn, $start_date, $end_date, $employee_filter = null, $country_filter = 0) {
  508. // 如果有业务员过滤条件
  509. $employee_condition = "";
  510. if ($employee_filter !== null) {
  511. if (is_array($employee_filter) && !empty($employee_filter)) {
  512. // 处理数组形式的业务员ID列表
  513. $emp_ids = [];
  514. foreach ($employee_filter as $emp_id) {
  515. if (is_numeric($emp_id)) {
  516. $emp_ids[] = intval($emp_id);
  517. }
  518. }
  519. if (!empty($emp_ids)) {
  520. $emp_ids_str = implode(',', $emp_ids);
  521. $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
  522. }
  523. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  524. // 处理单个业务员ID
  525. $employee_filter = intval($employee_filter);
  526. $employee_condition = " AND cu.cs_belong = $employee_filter";
  527. }
  528. }
  529. // 添加国家/地区筛选条件
  530. $country_condition = "";
  531. if (is_numeric($country_filter) && $country_filter > 0) {
  532. $country_condition = " AND cu.cs_country = " . intval($country_filter);
  533. // 如果指定了国家/地区,则活跃国家数为1或0
  534. $sql = "SELECT COUNT(*) as country_count
  535. FROM orders o
  536. JOIN customer cu ON o.customer_id = cu.id
  537. WHERE o.is_deleted = 0 AND o.order_date BETWEEN ? AND ?
  538. $employee_condition
  539. $country_condition
  540. LIMIT 1";
  541. } else {
  542. // 否则计算所有活跃国家
  543. $sql = "SELECT COUNT(DISTINCT cu.cs_country) as country_count
  544. FROM orders o
  545. JOIN customer cu ON o.customer_id = cu.id
  546. WHERE o.is_deleted = 0 AND o.order_date BETWEEN ? AND ?
  547. $employee_condition";
  548. }
  549. $stmt = $conn->prepare($sql);
  550. $stmt->bind_param("ss", $start_date, $end_date);
  551. $stmt->execute();
  552. $result = $stmt->get_result();
  553. $row = $result->fetch_assoc();
  554. return [
  555. 'count' => $row['country_count'] ?? 0
  556. ];
  557. }
  558. /**
  559. * 获取各地区平均订单金额
  560. *
  561. * @param mysqli $conn 数据库连接
  562. * @param string $start_date 开始日期
  563. * @param string $end_date 结束日期
  564. * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  565. * @return array 各地区平均订单金额数据
  566. */
  567. function getAverageOrderByRegion($conn, $start_date, $end_date, $employee_filter = null) {
  568. // 如果有业务员过滤条件
  569. $employee_condition = "";
  570. if ($employee_filter !== null) {
  571. if (is_array($employee_filter) && !empty($employee_filter)) {
  572. // 处理数组形式的业务员ID列表
  573. $emp_ids = [];
  574. foreach ($employee_filter as $emp_id) {
  575. if (is_numeric($emp_id)) {
  576. $emp_ids[] = intval($emp_id);
  577. }
  578. }
  579. if (!empty($emp_ids)) {
  580. $emp_ids_str = implode(',', $emp_ids);
  581. $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
  582. }
  583. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  584. // 处理单个业务员ID
  585. $employee_filter = intval($employee_filter);
  586. $employee_condition = " AND cu.cs_belong = $employee_filter";
  587. }
  588. }
  589. $sql = "SELECT
  590. c.countryName,
  591. AVG(o.total_amount) as avg_amount,
  592. COUNT(o.id) as order_count
  593. FROM orders o
  594. JOIN customer cu ON o.customer_id = cu.id
  595. JOIN country c ON cu.cs_country = c.id
  596. WHERE o.is_deleted = 0 AND o.order_date BETWEEN ? AND ?
  597. $employee_condition
  598. GROUP BY cu.cs_country
  599. HAVING order_count >= 5
  600. ORDER BY avg_amount DESC
  601. LIMIT 10";
  602. $stmt = $conn->prepare($sql);
  603. $stmt->bind_param("ss", $start_date, $end_date);
  604. $stmt->execute();
  605. $result = $stmt->get_result();
  606. $regions = [];
  607. $total_avg = 0;
  608. $total_orders = 0;
  609. while ($row = $result->fetch_assoc()) {
  610. $regions[] = [
  611. 'countryName' => $row['countryName'],
  612. 'avg_amount' => $row['avg_amount'],
  613. 'order_count' => $row['order_count']
  614. ];
  615. $total_avg += $row['avg_amount'] * $row['order_count'];
  616. $total_orders += $row['order_count'];
  617. }
  618. // 计算全球平均订单金额
  619. $global_avg = $total_orders > 0 ? $total_avg / $total_orders : 0;
  620. return [
  621. 'regions' => $regions,
  622. 'global_avg' => $global_avg
  623. ];
  624. }
  625. /**
  626. * 获取各地区产品类别偏好
  627. *
  628. * @param mysqli $conn 数据库连接
  629. * @param string $start_date 开始日期
  630. * @param string $end_date 结束日期
  631. * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  632. * @return array 各地区产品类别偏好数据
  633. */
  634. function getRegionCategoryPreferences($conn, $start_date, $end_date, $employee_filter = null) {
  635. // 如果有业务员过滤条件
  636. $employee_condition = "";
  637. if ($employee_filter !== null) {
  638. if (is_array($employee_filter) && !empty($employee_filter)) {
  639. // 处理数组形式的业务员ID列表
  640. $emp_ids = [];
  641. foreach ($employee_filter as $emp_id) {
  642. if (is_numeric($emp_id)) {
  643. $emp_ids[] = intval($emp_id);
  644. }
  645. }
  646. if (!empty($emp_ids)) {
  647. $emp_ids_str = implode(',', $emp_ids);
  648. $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
  649. }
  650. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  651. // 处理单个业务员ID
  652. $employee_filter = intval($employee_filter);
  653. $employee_condition = " AND cu.cs_belong = $employee_filter";
  654. }
  655. }
  656. $sql = "SELECT
  657. c.countryName,
  658. pc.name as category_name,
  659. SUM(oi.quantity) as total_quantity
  660. FROM orders o
  661. JOIN customer cu ON o.customer_id = cu.id
  662. JOIN country c ON cu.cs_country = c.id
  663. JOIN order_items oi ON o.id = oi.order_id
  664. JOIN products p ON oi.product_id = p.id
  665. JOIN product_categories pc ON p.category_id = pc.id
  666. WHERE o.is_deleted = 0 AND oi.is_deleted = 0 AND o.order_date BETWEEN ? AND ?
  667. $employee_condition
  668. GROUP BY cu.cs_country, p.category_id
  669. ORDER BY c.countryName, total_quantity DESC";
  670. $stmt = $conn->prepare($sql);
  671. $stmt->bind_param("ss", $start_date, $end_date);
  672. $stmt->execute();
  673. $result = $stmt->get_result();
  674. $preferences = [];
  675. $current_country = '';
  676. $country_data = [];
  677. while ($row = $result->fetch_assoc()) {
  678. if ($current_country != $row['countryName']) {
  679. if (!empty($current_country)) {
  680. $preferences[$current_country] = $country_data;
  681. }
  682. $current_country = $row['countryName'];
  683. $country_data = [];
  684. }
  685. $country_data[] = [
  686. 'category' => $row['category_name'],
  687. 'quantity' => $row['total_quantity']
  688. ];
  689. }
  690. // 添加最后一个国家的数据
  691. if (!empty($current_country)) {
  692. $preferences[$current_country] = $country_data;
  693. }
  694. // 只保留前5个主要市场
  695. $top_markets = array_slice(array_keys($preferences), 0, 5);
  696. $filtered_preferences = [];
  697. foreach ($top_markets as $market) {
  698. $filtered_preferences[$market] = array_slice($preferences[$market], 0, 5);
  699. }
  700. return $filtered_preferences;
  701. }
  702. /**
  703. * 获取地区销售增长趋势
  704. *
  705. * @param mysqli $conn 数据库连接
  706. * @param string $start_date 开始日期
  707. * @param string $end_date 结束日期
  708. * @param string $period 时间粒度 (day/week/month)
  709. * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  710. * @param int $country_filter 国家/地区ID,默认为0表示全部地区
  711. * @return array 地区销售增长趋势数据
  712. */
  713. function getRegionGrowthTrends($conn, $start_date, $end_date, $period = 'month', $employee_filter = null, $country_filter = 0) {
  714. $period_format = getPeriodFormat($period);
  715. // 如果有业务员过滤条件
  716. $employee_condition = "";
  717. if ($employee_filter !== null) {
  718. if (is_array($employee_filter) && !empty($employee_filter)) {
  719. // 处理数组形式的业务员ID列表
  720. $emp_ids = [];
  721. foreach ($employee_filter as $emp_id) {
  722. if (is_numeric($emp_id)) {
  723. $emp_ids[] = intval($emp_id);
  724. }
  725. }
  726. if (!empty($emp_ids)) {
  727. $emp_ids_str = implode(',', $emp_ids);
  728. $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
  729. }
  730. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  731. // 处理单个业务员ID
  732. $employee_filter = intval($employee_filter);
  733. $employee_condition = " AND cu.cs_belong = $employee_filter";
  734. }
  735. }
  736. // 添加国家/地区筛选条件
  737. $country_condition = "";
  738. if (is_numeric($country_filter) && $country_filter > 0) {
  739. $country_filter = intval($country_filter);
  740. $country_condition = " AND cu.cs_country = $country_filter";
  741. }
  742. $sql = "SELECT
  743. c.countryName,
  744. DATE_FORMAT(o.order_date, ?) as time_period,
  745. SUM(o.total_amount) as total_amount
  746. FROM orders o
  747. JOIN customer cu ON o.customer_id = cu.id
  748. JOIN country c ON cu.cs_country = c.id
  749. WHERE o.is_deleted = 0 AND o.order_date BETWEEN ? AND ?
  750. $employee_condition
  751. $country_condition
  752. GROUP BY cu.cs_country, time_period
  753. ORDER BY c.countryName, time_period";
  754. $stmt = $conn->prepare($sql);
  755. $stmt->bind_param("sss", $period_format, $start_date, $end_date);
  756. $stmt->execute();
  757. $result = $stmt->get_result();
  758. $trends = [];
  759. $time_periods = [];
  760. while ($row = $result->fetch_assoc()) {
  761. if (!in_array($row['time_period'], $time_periods)) {
  762. $time_periods[] = $row['time_period'];
  763. }
  764. if (!isset($trends[$row['countryName']])) {
  765. $trends[$row['countryName']] = [];
  766. }
  767. $trends[$row['countryName']][$row['time_period']] = $row['total_amount'];
  768. }
  769. // 只有在没有国家/地区筛选条件时才筛选前10个市场
  770. if ($country_filter == 0) {
  771. // 只保留前10个主要市场
  772. $top_markets = array_slice(array_keys($trends), 0, 10);
  773. $filtered_trends = [];
  774. foreach ($top_markets as $market) {
  775. $filtered_trends[$market] = $trends[$market];
  776. }
  777. $trends = $filtered_trends;
  778. }
  779. return [
  780. 'time_periods' => $time_periods,
  781. 'trends' => $trends
  782. ];
  783. }
  784. /**
  785. * 获取地区季节性销售分析
  786. *
  787. * @param mysqli $conn 数据库连接
  788. * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  789. * @param int $country_filter 国家/地区ID,默认为0表示全部地区
  790. * @return array 地区季节性销售分析数据
  791. */
  792. function getRegionSeasonalAnalysis($conn, $employee_filter = null, $country_filter = 0) {
  793. // 如果有业务员过滤条件
  794. $employee_condition = "";
  795. if ($employee_filter !== null) {
  796. if (is_array($employee_filter) && !empty($employee_filter)) {
  797. // 处理数组形式的业务员ID列表
  798. $emp_ids = [];
  799. foreach ($employee_filter as $emp_id) {
  800. if (is_numeric($emp_id)) {
  801. $emp_ids[] = intval($emp_id);
  802. }
  803. }
  804. if (!empty($emp_ids)) {
  805. $emp_ids_str = implode(',', $emp_ids);
  806. $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
  807. }
  808. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  809. // 处理单个业务员ID
  810. $employee_filter = intval($employee_filter);
  811. $employee_condition = " AND cu.cs_belong = $employee_filter";
  812. }
  813. }
  814. // 添加国家/地区筛选条件
  815. $country_condition = "";
  816. if (is_numeric($country_filter) && $country_filter > 0) {
  817. $country_filter = intval($country_filter);
  818. $country_condition = " AND cu.cs_country = $country_filter";
  819. }
  820. $sql = "SELECT
  821. c.countryName,
  822. MONTH(o.order_date) as month,
  823. SUM(o.total_amount) as total_amount
  824. FROM orders o
  825. JOIN customer cu ON o.customer_id = cu.id
  826. JOIN country c ON cu.cs_country = c.id
  827. WHERE o.is_deleted = 0 AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 2 YEAR)
  828. $employee_condition
  829. $country_condition
  830. GROUP BY cu.cs_country, month
  831. ORDER BY c.countryName, month";
  832. $result = $conn->query($sql);
  833. $seasonal = [];
  834. $months = range(1, 12);
  835. while ($row = $result->fetch_assoc()) {
  836. if (!isset($seasonal[$row['countryName']])) {
  837. $seasonal[$row['countryName']] = array_fill(1, 12, 0);
  838. }
  839. $seasonal[$row['countryName']][$row['month']] += $row['total_amount'];
  840. }
  841. // 只有在没有国家/地区筛选条件时才筛选前10个市场
  842. if ($country_filter == 0) {
  843. // 只保留前10个主要市场
  844. $top_markets = array_slice(array_keys($seasonal), 0, 10);
  845. $filtered_seasonal = [];
  846. foreach ($top_markets as $market) {
  847. $filtered_seasonal[$market] = array_values($seasonal[$market]);
  848. }
  849. $seasonal = $filtered_seasonal;
  850. } else {
  851. // 如果有国家筛选,转换为数组值形式
  852. $filtered_seasonal = [];
  853. foreach ($seasonal as $market => $months_data) {
  854. $filtered_seasonal[$market] = array_values($months_data);
  855. }
  856. $seasonal = $filtered_seasonal;
  857. }
  858. return [
  859. 'months' => ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'],
  860. 'data' => $seasonal
  861. ];
  862. }
  863. /**
  864. * 获取地区销售预测数据
  865. *
  866. * @param mysqli $conn 数据库连接
  867. * @param string $start_date 开始日期
  868. * @param string $end_date 结束日期
  869. * @param array|int|null $employee_filter 业务员ID或ID数组,用于过滤数据
  870. * @param int $country_filter 国家/地区ID,默认为0表示全部地区
  871. * @return array 地区销售预测数据
  872. */
  873. function getRegionSalesForecast($conn, $start_date, $end_date, $employee_filter = null, $country_filter = 0) {
  874. // 如果有业务员过滤条件
  875. $employee_condition = "";
  876. if ($employee_filter !== null) {
  877. if (is_array($employee_filter) && !empty($employee_filter)) {
  878. // 处理数组形式的业务员ID列表
  879. $emp_ids = [];
  880. foreach ($employee_filter as $emp_id) {
  881. if (is_numeric($emp_id)) {
  882. $emp_ids[] = intval($emp_id);
  883. }
  884. }
  885. if (!empty($emp_ids)) {
  886. $emp_ids_str = implode(',', $emp_ids);
  887. $employee_condition = " AND cu.cs_belong IN ($emp_ids_str)";
  888. }
  889. } else if (is_numeric($employee_filter) && $employee_filter > 0) {
  890. // 处理单个业务员ID
  891. $employee_filter = intval($employee_filter);
  892. $employee_condition = " AND cu.cs_belong = $employee_filter";
  893. }
  894. }
  895. // 添加国家/地区筛选条件
  896. $country_condition = "";
  897. if (is_numeric($country_filter) && $country_filter > 0) {
  898. $country_filter = intval($country_filter);
  899. $country_condition = " AND cu.cs_country = $country_filter";
  900. }
  901. // 获取过去12个月的销售数据作为基础
  902. $sql = "SELECT
  903. c.countryName,
  904. MONTH(o.order_date) as month,
  905. YEAR(o.order_date) as year,
  906. SUM(o.total_amount) as total_amount
  907. FROM orders o
  908. JOIN customer cu ON o.customer_id = cu.id
  909. JOIN country c ON cu.cs_country = c.id
  910. WHERE o.is_deleted = 0 AND o.order_date >= DATE_SUB(CURDATE(), INTERVAL 12 MONTH)
  911. $employee_condition
  912. $country_condition
  913. GROUP BY cu.cs_country, year, month
  914. ORDER BY c.countryName, year, month";
  915. $result = $conn->query($sql);
  916. $historical = [];
  917. while ($row = $result->fetch_assoc()) {
  918. $period = $row['year'] . '-' . str_pad($row['month'], 2, '0', STR_PAD_LEFT);
  919. if (!isset($historical[$row['countryName']])) {
  920. $historical[$row['countryName']] = [];
  921. }
  922. $historical[$row['countryName']][$period] = $row['total_amount'];
  923. }
  924. // 生成未来6个月的预测
  925. $forecast = [];
  926. $periods = [];
  927. $current_month = (int)date('m');
  928. $current_year = (int)date('Y');
  929. // 收集所有历史数据点时间
  930. $all_periods = [];
  931. foreach ($historical as $country => $data) {
  932. foreach (array_keys($data) as $period) {
  933. $all_periods[$period] = true;
  934. }
  935. }
  936. $all_periods = array_keys($all_periods);
  937. sort($all_periods);
  938. // 生成未来6个月的预测点
  939. $future_periods = [];
  940. for ($i = 1; $i <= 6; $i++) {
  941. $forecast_month = ($current_month + $i) % 12;
  942. $forecast_month = $forecast_month == 0 ? 12 : $forecast_month;
  943. $forecast_year = $current_year + floor(($current_month + $i - 1) / 12);
  944. $period = $forecast_year . '-' . str_pad($forecast_month, 2, '0', STR_PAD_LEFT);
  945. $future_periods[] = $period;
  946. }
  947. // 合并历史和预测时间点
  948. $all_chart_periods = array_merge($all_periods, $future_periods);
  949. // 只有在没有国家/地区筛选条件时才筛选前10个市场
  950. $top_markets = array_keys($historical);
  951. if ($country_filter == 0) {
  952. // 只选取主要的10个市场做预测
  953. $top_markets = array_slice($top_markets, 0, 10);
  954. }
  955. $forecast_data = [];
  956. foreach ($top_markets as $market) {
  957. $forecast_data[$market] = [];
  958. // 为每个市场生成简单的预测
  959. // 这里使用简单的线性增长预测
  960. // 实际应用中可以采用更复杂的时间序列预测算法
  961. // 计算过去几个月的平均增长率
  962. $growth_rate = 0.05; // 默认月度增长率为5%
  963. if (count($historical[$market]) >= 2) {
  964. $values = array_values($historical[$market]);
  965. $start_val = array_shift($values);
  966. $end_val = array_pop($values);
  967. if ($start_val > 0) {
  968. $periods_count = count($historical[$market]) - 1;
  969. $total_growth = ($end_val / $start_val) - 1;
  970. $growth_rate = pow(1 + $total_growth, 1 / $periods_count) - 1;
  971. // 限制增长率在合理范围内
  972. $growth_rate = max(-0.2, min(0.2, $growth_rate));
  973. }
  974. }
  975. // 对于历史数据,直接使用实际值
  976. foreach ($all_periods as $period) {
  977. $forecast_data[$market][$period] = [
  978. 'value' => $historical[$market][$period] ?? null,
  979. 'is_forecast' => false
  980. ];
  981. }
  982. // 对于预测数据,基于最后一个历史数据点和增长率计算
  983. $last_period = end($all_periods);
  984. $last_value = $historical[$market][$last_period] ?? array_values($historical[$market])[count($historical[$market])-1];
  985. foreach ($future_periods as $i => $period) {
  986. $forecast_value = $last_value * pow(1 + $growth_rate, $i + 1);
  987. $forecast_data[$market][$period] = [
  988. 'value' => $forecast_value,
  989. 'is_forecast' => true
  990. ];
  991. }
  992. }
  993. return [
  994. 'periods' => $all_chart_periods,
  995. 'forecast' => $forecast_data
  996. ];
  997. }
  998. /**
  999. * 渲染平均订单金额分析图表
  1000. *
  1001. * @param array $region_data 地区平均订单金额数据
  1002. * @return void
  1003. */
  1004. function renderAverageOrderByRegionChart($region_data) {
  1005. $region_labels = [];
  1006. $avg_amounts = [];
  1007. $order_counts = [];
  1008. foreach ($region_data as $region) {
  1009. $region_labels[] = $region['countryName'];
  1010. $avg_amounts[] = $region['avg_amount'];
  1011. $order_counts[] = $region['order_count'];
  1012. }
  1013. ?>
  1014. <div class="chart-header">
  1015. <h2 class="chart-title">地区平均订单金额分析</h2>
  1016. </div>
  1017. <canvas id="avgOrderChart"></canvas>
  1018. <script>
  1019. // 地区平均订单金额分析图
  1020. var avgOrderCtx = document.getElementById('avgOrderChart').getContext('2d');
  1021. var avgOrderChart = new Chart(avgOrderCtx, {
  1022. type: 'bar',
  1023. data: {
  1024. labels: <?php echo json_encode($region_labels); ?>,
  1025. datasets: [
  1026. {
  1027. label: '平均订单金额',
  1028. data: <?php echo json_encode($avg_amounts); ?>,
  1029. backgroundColor: 'rgba(75, 192, 192, 0.6)',
  1030. borderColor: 'rgba(75, 192, 192, 1)',
  1031. borderWidth: 1,
  1032. yAxisID: 'y-amount'
  1033. },
  1034. {
  1035. type: 'line',
  1036. label: '订单数量',
  1037. data: <?php echo json_encode($order_counts); ?>,
  1038. backgroundColor: 'rgba(255, 159, 64, 0.6)',
  1039. borderColor: 'rgba(255, 159, 64, 1)',
  1040. borderWidth: 2,
  1041. fill: false,
  1042. yAxisID: 'y-count'
  1043. }
  1044. ]
  1045. },
  1046. options: {
  1047. responsive: true,
  1048. scales: {
  1049. x: {
  1050. title: {
  1051. display: true,
  1052. text: '地区'
  1053. }
  1054. },
  1055. 'y-amount': {
  1056. type: 'linear',
  1057. position: 'left',
  1058. title: {
  1059. display: true,
  1060. text: '平均订单金额'
  1061. }
  1062. },
  1063. 'y-count': {
  1064. type: 'linear',
  1065. position: 'right',
  1066. title: {
  1067. display: true,
  1068. text: '订单数量'
  1069. },
  1070. grid: {
  1071. drawOnChartArea: false
  1072. }
  1073. }
  1074. }
  1075. }
  1076. });
  1077. </script>
  1078. <?php
  1079. }
  1080. /**
  1081. * 渲染地区产品类别偏好图表
  1082. *
  1083. * @param array $preferences 地区产品类别偏好数据
  1084. * @return void
  1085. */
  1086. function renderRegionCategoryPreferencesChart($preferences) {
  1087. ?>
  1088. <div class="chart-header">
  1089. <h2 class="chart-title">各地区产品类别偏好</h2>
  1090. </div>
  1091. <div class="grid-row">
  1092. <?php foreach ($preferences as $country => $categories): ?>
  1093. <?php
  1094. $category_labels = [];
  1095. $category_data = [];
  1096. foreach ($categories as $cat) {
  1097. $category_labels[] = $cat['category'];
  1098. $category_data[] = $cat['quantity'];
  1099. }
  1100. ?>
  1101. <div class="grid-column">
  1102. <div class="subchart-container">
  1103. <h3 class="subchart-title"><?php echo $country; ?></h3>
  1104. <canvas id="categoryChart<?php echo md5($country); ?>"></canvas>
  1105. </div>
  1106. </div>
  1107. <script>
  1108. // <?php echo $country; ?> 产品类别偏好
  1109. var categoryCtx<?php echo md5($country); ?> = document.getElementById('categoryChart<?php echo md5($country); ?>').getContext('2d');
  1110. var categoryChart<?php echo md5($country); ?> = new Chart(categoryCtx<?php echo md5($country); ?>, {
  1111. type: 'doughnut',
  1112. data: {
  1113. labels: <?php echo json_encode($category_labels); ?>,
  1114. datasets: [{
  1115. data: <?php echo json_encode($category_data); ?>,
  1116. backgroundColor: [
  1117. 'rgba(255, 99, 132, 0.7)',
  1118. 'rgba(54, 162, 235, 0.7)',
  1119. 'rgba(255, 206, 86, 0.7)',
  1120. 'rgba(75, 192, 192, 0.7)',
  1121. 'rgba(153, 102, 255, 0.7)'
  1122. ],
  1123. borderWidth: 1
  1124. }]
  1125. },
  1126. options: {
  1127. responsive: true,
  1128. plugins: {
  1129. legend: {
  1130. position: 'right',
  1131. }
  1132. }
  1133. }
  1134. });
  1135. </script>
  1136. <?php endforeach; ?>
  1137. </div>
  1138. <?php
  1139. }
  1140. /**
  1141. * 渲染地区销售增长趋势图表
  1142. *
  1143. * @param array $growth_data 地区销售增长趋势数据
  1144. * @return void
  1145. */
  1146. function renderRegionGrowthTrendsChart($growth_data) {
  1147. $time_periods = $growth_data['time_periods'];
  1148. $trends = $growth_data['trends'];
  1149. $datasets = [];
  1150. $colors = [
  1151. ['rgba(255, 99, 132, 0.6)', 'rgba(255, 99, 132, 1)'],
  1152. ['rgba(54, 162, 235, 0.6)', 'rgba(54, 162, 235, 1)'],
  1153. ['rgba(255, 206, 86, 0.6)', 'rgba(255, 206, 86, 1)'],
  1154. ['rgba(75, 192, 192, 0.6)', 'rgba(75, 192, 192, 1)'],
  1155. ['rgba(153, 102, 255, 0.6)', 'rgba(153, 102, 255, 1)']
  1156. ];
  1157. $i = 0;
  1158. foreach ($trends as $country => $data) {
  1159. $dataset = [
  1160. 'label' => $country,
  1161. 'data' => [],
  1162. 'backgroundColor' => $colors[$i % count($colors)][0],
  1163. 'borderColor' => $colors[$i % count($colors)][1],
  1164. 'borderWidth' => 2,
  1165. 'fill' => false,
  1166. 'tension' => 0.1
  1167. ];
  1168. foreach ($time_periods as $period) {
  1169. $dataset['data'][] = $data[$period] ?? null;
  1170. }
  1171. $datasets[] = $dataset;
  1172. $i++;
  1173. }
  1174. ?>
  1175. <div class="chart-header">
  1176. <h2 class="chart-title">地区销售增长趋势</h2>
  1177. </div>
  1178. <div class="region-growth-chart-container">
  1179. <canvas id="growthTrendsChart"></canvas>
  1180. </div>
  1181. <style>
  1182. /* 响应式布局:调整图表高度 */
  1183. .region-growth-chart-container {
  1184. width: 100%;
  1185. height: auto;
  1186. }
  1187. @media (min-width: 768px) {
  1188. .region-growth-chart-container {
  1189. height: 33vh; /* 视窗高度的1/3 */
  1190. }
  1191. }
  1192. </style>
  1193. <script>
  1194. // 地区销售增长趋势图
  1195. var growthTrendsCtx = document.getElementById('growthTrendsChart').getContext('2d');
  1196. var growthTrendsChart = new Chart(growthTrendsCtx, {
  1197. type: 'line',
  1198. data: {
  1199. labels: <?php echo json_encode($time_periods); ?>,
  1200. datasets: <?php echo json_encode($datasets); ?>
  1201. },
  1202. options: {
  1203. responsive: true,
  1204. maintainAspectRatio: false, // 允许图表高度自适应
  1205. scales: {
  1206. x: {
  1207. title: {
  1208. display: true,
  1209. text: '时间段'
  1210. }
  1211. },
  1212. y: {
  1213. title: {
  1214. display: true,
  1215. text: '销售额'
  1216. }
  1217. }
  1218. }
  1219. }
  1220. });
  1221. </script>
  1222. <?php
  1223. }
  1224. /**
  1225. * 渲染地区季节性分析图表
  1226. *
  1227. * @param array $seasonal_data 地区季节性分析数据
  1228. * @return void
  1229. */
  1230. function renderRegionSeasonalAnalysisChart($seasonal_data) {
  1231. $months = $seasonal_data['months'];
  1232. $data = $seasonal_data['data'];
  1233. $datasets = [];
  1234. $colors = [
  1235. ['rgba(255, 99, 132, 0.6)', 'rgba(255, 99, 132, 1)'],
  1236. ['rgba(54, 162, 235, 0.6)', 'rgba(54, 162, 235, 1)'],
  1237. ['rgba(255, 206, 86, 0.6)', 'rgba(255, 206, 86, 1)'],
  1238. ['rgba(75, 192, 192, 0.6)', 'rgba(75, 192, 192, 1)'],
  1239. ['rgba(153, 102, 255, 0.6)', 'rgba(153, 102, 255, 1)']
  1240. ];
  1241. $i = 0;
  1242. foreach ($data as $country => $values) {
  1243. $datasets[] = [
  1244. 'label' => $country,
  1245. 'data' => $values,
  1246. 'backgroundColor' => $colors[$i % count($colors)][0],
  1247. 'borderColor' => $colors[$i % count($colors)][1],
  1248. 'borderWidth' => 2,
  1249. 'fill' => false,
  1250. 'tension' => 0.1
  1251. ];
  1252. $i++;
  1253. }
  1254. ?>
  1255. <div class="chart-header">
  1256. <h2 class="chart-title">地区季节性销售分析</h2>
  1257. </div>
  1258. <div class="region-seasonal-chart-container">
  1259. <canvas id="seasonalAnalysisChart"></canvas>
  1260. </div>
  1261. <style>
  1262. /* 响应式布局:调整图表高度 */
  1263. .region-seasonal-chart-container {
  1264. width: 100%;
  1265. height: auto;
  1266. }
  1267. @media (min-width: 768px) {
  1268. .region-seasonal-chart-container {
  1269. height: 33vh; /* 视窗高度的1/3 */
  1270. }
  1271. }
  1272. </style>
  1273. <script>
  1274. // 地区季节性销售分析图
  1275. var seasonalCtx = document.getElementById('seasonalAnalysisChart').getContext('2d');
  1276. var seasonalChart = new Chart(seasonalCtx, {
  1277. type: 'line',
  1278. data: {
  1279. labels: <?php echo json_encode($months); ?>,
  1280. datasets: <?php echo json_encode($datasets); ?>
  1281. },
  1282. options: {
  1283. responsive: true,
  1284. maintainAspectRatio: false, // 允许图表高度自适应
  1285. scales: {
  1286. x: {
  1287. title: {
  1288. display: true,
  1289. text: '月份'
  1290. }
  1291. },
  1292. y: {
  1293. title: {
  1294. display: true,
  1295. text: '销售额'
  1296. }
  1297. }
  1298. }
  1299. }
  1300. });
  1301. </script>
  1302. <?php
  1303. }
  1304. /**
  1305. * 渲染地区销售预测图表
  1306. *
  1307. * @param array $forecast_data 地区销售预测数据
  1308. * @return void
  1309. */
  1310. function renderRegionSalesForecastChart($forecast_data) {
  1311. $periods = $forecast_data['periods'];
  1312. $forecast = $forecast_data['forecast'];
  1313. $datasets = [];
  1314. $colors = [
  1315. ['rgba(255, 99, 132, 0.6)', 'rgba(255, 99, 132, 1)'],
  1316. ['rgba(54, 162, 235, 0.6)', 'rgba(54, 162, 235, 1)'],
  1317. ['rgba(255, 206, 86, 0.6)', 'rgba(255, 206, 86, 1)'],
  1318. ['rgba(75, 192, 192, 0.6)', 'rgba(75, 192, 192, 1)'],
  1319. ['rgba(153, 102, 255, 0.6)', 'rgba(153, 102, 255, 1)']
  1320. ];
  1321. $i = 0;
  1322. foreach ($forecast as $country => $data) {
  1323. $historical_data = [];
  1324. $forecast_data = [];
  1325. foreach ($periods as $period) {
  1326. if (isset($data[$period])) {
  1327. if ($data[$period]['is_forecast']) {
  1328. $historical_data[] = null;
  1329. $forecast_data[] = $data[$period]['value'];
  1330. } else {
  1331. $historical_data[] = $data[$period]['value'];
  1332. $forecast_data[] = null;
  1333. }
  1334. } else {
  1335. $historical_data[] = null;
  1336. $forecast_data[] = null;
  1337. }
  1338. }
  1339. $datasets[] = [
  1340. 'label' => $country . ' (历史)',
  1341. 'data' => $historical_data,
  1342. 'backgroundColor' => $colors[$i % count($colors)][0],
  1343. 'borderColor' => $colors[$i % count($colors)][1],
  1344. 'borderWidth' => 2,
  1345. 'fill' => false
  1346. ];
  1347. $datasets[] = [
  1348. 'label' => $country . ' (预测)',
  1349. 'data' => $forecast_data,
  1350. 'backgroundColor' => $colors[$i % count($colors)][0],
  1351. 'borderColor' => $colors[$i % count($colors)][1],
  1352. 'borderWidth' => 2,
  1353. 'borderDash' => [5, 5],
  1354. 'fill' => false
  1355. ];
  1356. $i++;
  1357. }
  1358. ?>
  1359. <div class="chart-header">
  1360. <h2 class="chart-title">地区销售预测 (未来6个月)</h2>
  1361. </div>
  1362. <div class="region-forecast-chart-container">
  1363. <canvas id="forecastChart"></canvas>
  1364. </div>
  1365. <style>
  1366. /* 响应式布局:调整图表高度 */
  1367. .region-forecast-chart-container {
  1368. width: 100%;
  1369. height: auto;
  1370. }
  1371. @media (min-width: 768px) {
  1372. .region-forecast-chart-container {
  1373. height: 33vh; /* 视窗高度的1/3 */
  1374. }
  1375. }
  1376. </style>
  1377. <script>
  1378. // 地区销售预测图
  1379. var forecastCtx = document.getElementById('forecastChart').getContext('2d');
  1380. var forecastChart = new Chart(forecastCtx, {
  1381. type: 'line',
  1382. data: {
  1383. labels: <?php echo json_encode($periods); ?>,
  1384. datasets: <?php echo json_encode($datasets); ?>
  1385. },
  1386. options: {
  1387. responsive: true,
  1388. maintainAspectRatio: false, // 允许图表高度自适应
  1389. scales: {
  1390. x: {
  1391. title: {
  1392. display: true,
  1393. text: '时间段'
  1394. }
  1395. },
  1396. y: {
  1397. title: {
  1398. display: true,
  1399. text: '销售额'
  1400. }
  1401. }
  1402. },
  1403. plugins: {
  1404. tooltip: {
  1405. callbacks: {
  1406. title: function(tooltipItems) {
  1407. return tooltipItems[0].label;
  1408. }
  1409. }
  1410. }
  1411. }
  1412. }
  1413. });
  1414. </script>
  1415. <?php
  1416. }
  1417. /**
  1418. * 渲染热门地区表格
  1419. *
  1420. * @param array $region_labels 地区标签
  1421. * @param array $region_order_counts 地区订单数量
  1422. * @param array $region_amounts 地区销售金额
  1423. * @return void
  1424. */
  1425. function renderTopRegionsTable($region_labels, $region_order_counts, $region_amounts) {
  1426. ?>
  1427. <div class="top-regions-table-container">
  1428. <table class="data-table">
  1429. <thead>
  1430. <tr>
  1431. <th>排名</th>
  1432. <th>国家/地区</th>
  1433. <th>订单数</th>
  1434. <th>销售金额</th>
  1435. <th>平均订单金额</th>
  1436. </tr>
  1437. </thead>
  1438. <tbody>
  1439. <?php for ($i = 0; $i < count($region_labels); $i++): ?>
  1440. <tr>
  1441. <td><?php echo $i + 1; ?></td>
  1442. <td><?php echo htmlspecialchars($region_labels[$i]); ?></td>
  1443. <td><?php echo number_format($region_order_counts[$i]); ?></td>
  1444. <td>¥<?php echo number_format($region_amounts[$i], 2); ?></td>
  1445. <td>¥<?php echo number_format($region_order_counts[$i] > 0 ? $region_amounts[$i] / $region_order_counts[$i] : 0, 2); ?></td>
  1446. </tr>
  1447. <?php endfor; ?>
  1448. </tbody>
  1449. </table>
  1450. </div>
  1451. <style>
  1452. /* 响应式布局:调整表格容器 */
  1453. .top-regions-table-container {
  1454. width: 100%;
  1455. overflow-x: auto;
  1456. }
  1457. @media (min-width: 768px) {
  1458. .top-regions-table-container {
  1459. max-height: 33vh; /* 视窗高度的1/3 */
  1460. overflow-y: auto;
  1461. }
  1462. }
  1463. </style>
  1464. <?php
  1465. }