CostCalculation.php 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949
  1. <?php
  2. namespace app\api\controller;
  3. use app\common\controller\Api;
  4. class CostCalculation extends Api
  5. {
  6. protected $noNeedLogin = ['*'];
  7. protected $noNeedRight = ['*'];
  8. // 车间常量
  9. const WORKSHOP_ROLLER_PRESS = '03、卷凹机组';
  10. const WORKSHOP_LIST_ALL = ['凹丝印车间', '胶印车间', '印后车间', '检验车间'];
  11. // 科目名称关键词
  12. const SUBJECT_WASTE_GAS = '废气处理';
  13. const SUBJECT_BOILER = '锅炉';
  14. const SUBJECT_HOT_WATER_BOILER = '热水锅炉';
  15. const SUBJECT_AIR_COMPRESSOR_A = '空压机A';
  16. const SUBJECT_AIR_COMPRESSOR_B = '空压机B';
  17. const SUBJECT_VACUUM_BLOWER_A = '真空鼓风机A';
  18. const SUBJECT_VACUUM_BLOWER_B = '真空鼓风机B';
  19. const SUBJECT_CENTRAL_AIR_CONDITIONER_A = '中央空调A';
  20. const SUBJECT_CENTRAL_AIR_CONDITIONER_B = '中央空调B';
  21. const SUBJECT_TOTAL_TO_APPORTION = '待分摊总额';
  22. /**
  23. * 统一的安全数值获取方法
  24. * 处理空字符串和null值,转换为0
  25. */
  26. protected function getSafeNumericValue($value)
  27. {
  28. if ($value === null || $value === '' || $value === false) {
  29. return 0;
  30. }
  31. return floatval($value);
  32. }
  33. /**
  34. * 安全的金额计算
  35. */
  36. protected function calculateSafeAmount($quantity, $unitPrice)
  37. {
  38. $safeQuantity = $this->getSafeNumericValue($quantity);
  39. $safeUnitPrice = $this->getSafeNumericValue($unitPrice);
  40. return $safeQuantity * $safeUnitPrice;
  41. }
  42. public function costCalculation()
  43. {
  44. if (!$this->request->isGet()) {
  45. $this->error('请求错误');
  46. }
  47. $param = $this->request->param();
  48. if (empty($param['month'])) {
  49. $this->error('请选择月份');
  50. }
  51. $month = $param['month'];
  52. // 计算车间水电气分摊(返回统计结果)
  53. $apportionmentResults = $this->apportionmentOne($month);
  54. // 格式化最终结果
  55. $formattedResults = $this->formatFinalResults($apportionmentResults,$month,$param['sys_id']);
  56. $machine = [];
  57. foreach ($formattedResults as $formattedResult) {
  58. $machine[] = $formattedResult['设备编号'];
  59. }
  60. $machineList = array_unique($machine);
  61. $machineWorkOrder = [];
  62. foreach ($machineList as $machine) {
  63. $machineWorkOrder[$machine] = $this->getMachineWorkOrder($machine, $month);
  64. }
  65. $apportionData = db('成本_各月分摊系数')->where(['Sys_ny' => $month])->select();
  66. if (!empty($apportionData)) {
  67. db('成本_各月分摊系数')->where(['Sys_ny' => $month])->delete();
  68. }
  69. $apportionSql = db('成本_各月分摊系数')->fetchSql(true)->insertAll($formattedResults);
  70. $apportionResults = db()->query($apportionSql);
  71. //查询车间机台色度数
  72. $machineTotal = $this->getMachineTotal($month);
  73. $data = [];
  74. foreach ($machineWorkOrder as $machineCode => $orders) {
  75. // 检查机台编号是否存在于第二个数组中
  76. if (!isset($machineTotal[$machineCode])) {
  77. continue; // 如果机台在分摊数组中不存在,跳过
  78. }
  79. $machineRates = $machineTotal[$machineCode]; // 获取该机台的费用单价
  80. // 遍历该机台下的所有工单
  81. foreach ($orders as $order) {
  82. $occupationHours = (float)$order['占用机时']; // 占用机时
  83. // 创建新记录(基础信息)
  84. $newRecord = [
  85. 'sczl_gdbh' => $order['工单编号'],
  86. 'sczl_yjno' => $order['印件号'],
  87. 'sczl_gxh' => $order['工序号'],
  88. 'sczl_jtbh' => $order['机台编号']
  89. ];
  90. // 动态添加所有科目分摊金额(基于第二个数组中的科目名称)
  91. foreach ($machineRates as $subject => $rate) {
  92. if ($subject === '待分摊总额') {
  93. $subject = '分摊水电';
  94. }
  95. $newRecord[$subject] = round($occupationHours * $rate, 2);
  96. $newRecord['直接水电'] = round($occupationHours * 0.69, 2);
  97. }
  98. $data[] = $newRecord;
  99. }
  100. }
  101. $i = 0;
  102. foreach ($data as $item) {
  103. $gdbh = $item['sczl_gdbh'];
  104. $yjno = $item['sczl_yjno'];
  105. $gxh = $item['sczl_gxh'];
  106. $jtbh = $item['sczl_jtbh'];
  107. unset($item['sczl_gdbh'], $item['sczl_yjno'], $item['sczl_gxh'], $item['sczl_jtbh']);
  108. $sql = db('成本v23_月度成本明细')
  109. ->where([
  110. 'sys_ny' => $month,
  111. 'sczl_gdbh' => $gdbh,
  112. 'sczl_yjno' => $yjno,
  113. 'sczl_gxh' => $gxh,
  114. 'sczl_jtbh' => $jtbh,
  115. ])
  116. ->fetchSql(true)
  117. ->update($item);
  118. $res = db()->query($sql);
  119. if ($res === false) {
  120. $i++;
  121. }
  122. }
  123. if ($i > 0) {
  124. $this->error('失败');
  125. }
  126. }
  127. /**
  128. * 计算水电气分摊费用(优化版)
  129. */
  130. protected function apportionmentOne($month)
  131. {
  132. $utilityList = db('成本_各月水电气')
  133. ->where('Sys_ny', $month)
  134. ->whereLike('费用类型', '%分摊%')
  135. ->select();
  136. if (empty($utilityList)) {
  137. return [];
  138. }
  139. // 初始化统计数据结构
  140. $machineSummary = []; // 按机台统计
  141. $subjectSummary = []; // 按科目统计
  142. $workshopSummary = []; // 按车间统计
  143. $apportionmentResults = []; // 原始分摊结果
  144. $allMachineData = []; // 所有机台数据
  145. // 先处理所有分摊项目
  146. foreach ($utilityList as $item) {
  147. // 确保数值安全
  148. $item['耗电量'] = $this->getSafeNumericValue($item['耗电量']);
  149. $item['单位电价'] = $this->getSafeNumericValue($item['单位电价']);
  150. $item['耗气量'] = $this->getSafeNumericValue($item['耗气量']);
  151. $item['单位气价'] = $this->getSafeNumericValue($item['单位气价']);
  152. $result = $this->processUtilityItem($item, $month);
  153. if ($result) {
  154. $apportionmentResults[] = $result;
  155. // 合并所有机台数据
  156. $this->mergeMachineData($result['data'], $allMachineData, $item['科目名称']);
  157. }
  158. }
  159. // 按机台+科目进行汇总统计
  160. $this->summarizeByMachineAndSubject($allMachineData, $machineSummary, $subjectSummary, $workshopSummary);
  161. // 对统计结果进行排序
  162. ksort($machineSummary);
  163. return $machineSummary;
  164. }
  165. /**
  166. * 合并所有机台数据
  167. */
  168. protected function mergeMachineData($machineData, &$allMachineData, $subjectName)
  169. {
  170. if (empty($machineData)) {
  171. return;
  172. }
  173. foreach ($machineData as $machine) {
  174. $machineId = $machine['机台编号'] ?? '';
  175. $workshop = $machine['车间名称'] ?? '未知车间';
  176. $workOrder = $machine['工单编号'] ?? '';
  177. $processNo = $machine['工序号'] ?? '';
  178. $printNo = $machine['印件号'] ?? '';
  179. $machineTime = floatval($machine['占用机时'] ?? 0);
  180. $uniqid = $machine['Uniqid'] ?? '';
  181. if (empty($machineId)) {
  182. continue;
  183. }
  184. // 初始化机台数据
  185. if (!isset($allMachineData[$machineId])) {
  186. $allMachineData[$machineId] = [
  187. '机台编号' => $machineId,
  188. '车间名称' => $workshop,
  189. '占用机时' => $machineTime,
  190. '工单编号' => $workOrder,
  191. '工序号' => $processNo,
  192. '印件号' => $printNo,
  193. 'Uniqid' => $uniqid,
  194. '科目明细' => [],
  195. '工单列表' => [],
  196. '科目总计' => 0
  197. ];
  198. }
  199. // 更新机台基础信息(如果有更完整的信息)
  200. if (empty($allMachineData[$machineId]['工单编号']) && !empty($workOrder)) {
  201. $allMachineData[$machineId]['工单编号'] = $workOrder;
  202. }
  203. if (empty($allMachineData[$machineId]['工序号']) && !empty($processNo)) {
  204. $allMachineData[$machineId]['工序号'] = $processNo;
  205. }
  206. if (empty($allMachineData[$machineId]['印件号']) && !empty($printNo)) {
  207. $allMachineData[$machineId]['印件号'] = $printNo;
  208. }
  209. // 记录工单(去重)
  210. if (!empty($workOrder) && !in_array($workOrder, $allMachineData[$machineId]['工单列表'])) {
  211. $allMachineData[$machineId]['工单列表'][] = $workOrder;
  212. }
  213. // 合并科目金额
  214. $apportionmentTypes = ['分摊水电', '废气处理', '锅炉', '热水锅炉',
  215. '空压机A', '空压机B', '真空鼓风机A', '真空鼓风机B',
  216. '中央空调A', '中央空调B'];
  217. $machineTotal = 0;
  218. foreach ($apportionmentTypes as $type) {
  219. if (isset($machine[$type]) && floatval($machine[$type]) > 0) {
  220. $amount = floatval($machine[$type]);
  221. $machineTotal += $amount;
  222. // 初始化科目明细
  223. if (!isset($allMachineData[$machineId]['科目明细'][$type])) {
  224. $allMachineData[$machineId]['科目明细'][$type] = [
  225. 'subject_name' => $type,
  226. 'total_amount' => 0,
  227. 'source_count' => 0,
  228. 'source_subjects' => ''
  229. ];
  230. }
  231. // 累加金额
  232. $allMachineData[$machineId]['科目明细'][$type]['total_amount'] += $amount;
  233. $allMachineData[$machineId]['科目明细'][$type]['source_count']++;
  234. // 记录来源科目
  235. $allMachineData[$machineId]['科目明细'][$type]['source_subjects'] = $subjectName;
  236. }
  237. }
  238. // 更新机台总计
  239. $allMachineData[$machineId]['科目总计'] += $machineTotal;
  240. }
  241. }
  242. /**
  243. * 按机台+科目进行汇总统计
  244. */
  245. protected function summarizeByMachineAndSubject($allMachineData, &$machineSummary, &$subjectSummary, &$workshopSummary)
  246. {
  247. foreach ($allMachineData as $machineId => $machineInfo) {
  248. $workshop = $machineInfo['车间名称'];
  249. // 1. 按机台统计
  250. $machineSummary[$machineId] = [
  251. '机台编号' => $machineId,
  252. '车间名称' => $workshop,
  253. '工单数量' => count($machineInfo['工单列表']),
  254. '占用机时' => $machineInfo['占用机时'],
  255. '科目总计' => round($machineInfo['科目总计'], 2),
  256. '科目明细' => [],
  257. '工单列表' => $machineInfo['工单列表']
  258. ];
  259. // 处理科目明细
  260. foreach ($machineInfo['科目明细'] as $subjectType => $subjectDetail) {
  261. $amount = round($subjectDetail['total_amount'], 2);
  262. $machineSummary[$machineId]['科目明细'][$subjectType] = [
  263. 'amount' => $amount,
  264. 'source_count' => $subjectDetail['source_count'],
  265. 'source_subjects' => $subjectDetail['source_subjects'],
  266. 'percentage' => $machineInfo['科目总计'] > 0
  267. ? round(($subjectDetail['total_amount'] / $machineInfo['科目总计']) * 100, 2)
  268. : 0
  269. ];
  270. }
  271. // 2. 按科目统计
  272. foreach ($machineInfo['科目明细'] as $subjectType => $subjectDetail) {
  273. $amount = round($subjectDetail['total_amount'], 2);
  274. // 初始化科目统计
  275. if (!isset($subjectSummary[$subjectType])) {
  276. $subjectSummary[$subjectType] = [
  277. 'subject_name' => $subjectType,
  278. 'total_amount' => 0,
  279. 'machine_count' => 0,
  280. 'workshop_distribution' => [],
  281. 'machine_list' => []
  282. ];
  283. }
  284. // 累加科目总计
  285. $subjectSummary[$subjectType]['total_amount'] += $subjectDetail['total_amount'];
  286. $subjectSummary[$subjectType]['machine_count']++;
  287. // 按车间分布
  288. if (!isset($subjectSummary[$subjectType]['workshop_distribution'][$workshop])) {
  289. $subjectSummary[$subjectType]['workshop_distribution'][$workshop] = 0;
  290. }
  291. $subjectSummary[$subjectType]['workshop_distribution'][$workshop] += $subjectDetail['total_amount'];
  292. // 机台列表
  293. $subjectSummary[$subjectType]['machine_list'][] = [
  294. 'machine_id' => $machineId,
  295. 'workshop' => $workshop,
  296. 'amount' => $amount,
  297. 'percentage' => $subjectSummary[$subjectType]['total_amount'] > 0
  298. ? round(($subjectDetail['total_amount'] / $subjectSummary[$subjectType]['total_amount']) * 100, 2)
  299. : 0
  300. ];
  301. }
  302. // 3. 按车间统计
  303. if (!isset($workshopSummary[$workshop])) {
  304. $workshopSummary[$workshop] = [
  305. 'workshop_name' => $workshop,
  306. 'machine_count' => 0,
  307. 'total_amount' => 0,
  308. 'subject_distribution' => [],
  309. 'machine_list' => []
  310. ];
  311. }
  312. $workshopSummary[$workshop]['machine_count']++;
  313. $workshopSummary[$workshop]['total_amount'] += $machineInfo['科目总计'];
  314. // 车间内科目分布
  315. foreach ($machineInfo['科目明细'] as $subjectType => $subjectDetail) {
  316. if (!isset($workshopSummary[$workshop]['subject_distribution'][$subjectType])) {
  317. $workshopSummary[$workshop]['subject_distribution'][$subjectType] = 0;
  318. }
  319. $workshopSummary[$workshop]['subject_distribution'][$subjectType] += $subjectDetail['total_amount'];
  320. }
  321. // 车间内机台列表
  322. $workshopSummary[$workshop]['machine_list'][] = [
  323. 'machine_id' => $machineId,
  324. 'total_amount' => round($machineInfo['科目总计'], 2),
  325. 'subject_count' => count($machineInfo['科目明细']),
  326. 'work_order_count' => count($machineInfo['工单列表'])
  327. ];
  328. }
  329. // 对科目统计进行后处理
  330. $this->processSubjectSummary($subjectSummary);
  331. // 对车间统计进行后处理
  332. $this->processWorkshopSummary($workshopSummary);
  333. }
  334. /**
  335. * 处理科目统计
  336. */
  337. protected function processSubjectSummary(&$subjectSummary)
  338. {
  339. foreach ($subjectSummary as &$subject) {
  340. // 金额四舍五入
  341. $subject['total_amount'] = round($subject['total_amount'], 2);
  342. // 车间分布百分比
  343. foreach ($subject['workshop_distribution'] as $workshop => &$amount) {
  344. $amount = round($amount, 2);
  345. }
  346. // 按金额排序机台列表
  347. usort($subject['machine_list'], function($a, $b) {
  348. return $b['amount'] <=> $a['amount'];
  349. });
  350. // 计算机台平均金额
  351. $subject['avg_per_machine'] = $subject['machine_count'] > 0
  352. ? round($subject['total_amount'] / $subject['machine_count'], 2)
  353. : 0;
  354. }
  355. }
  356. /**
  357. * 处理车间统计
  358. */
  359. protected function processWorkshopSummary(&$workshopSummary)
  360. {
  361. foreach ($workshopSummary as &$workshop) {
  362. // 金额四舍五入
  363. $workshop['total_amount'] = round($workshop['total_amount'], 2);
  364. // 科目分布百分比
  365. $workshop['subject_percentage'] = [];
  366. foreach ($workshop['subject_distribution'] as $subjectType => $amount) {
  367. $roundedAmount = round($amount, 2);
  368. $workshop['subject_distribution'][$subjectType] = $roundedAmount;
  369. if ($workshop['total_amount'] > 0) {
  370. $workshop['subject_percentage'][$subjectType] =
  371. round(($roundedAmount / $workshop['total_amount']) * 100, 2);
  372. }
  373. }
  374. // 按金额排序机台列表
  375. usort($workshop['machine_list'], function($a, $b) {
  376. return $b['total_amount'] <=> $a['total_amount'];
  377. });
  378. // 计算机台平均金额
  379. $workshop['avg_per_machine'] = $workshop['machine_count'] > 0
  380. ? round($workshop['total_amount'] / $workshop['machine_count'], 2)
  381. : 0;
  382. // 统计科目种类数
  383. $workshop['subject_count'] = count($workshop['subject_distribution']);
  384. }
  385. }
  386. /**
  387. * 处理单个水电费用项
  388. */
  389. protected function processUtilityItem($item, $month)
  390. {
  391. $subjectName = $item['科目名称'];
  392. // 使用switch-like结构提高可读性
  393. $processMap = [
  394. self::SUBJECT_TOTAL_TO_APPORTION => 'processTotalApportionment',
  395. self::SUBJECT_WASTE_GAS => 'processWasteGas',
  396. self::SUBJECT_BOILER => 'processBoiler',
  397. self::SUBJECT_AIR_COMPRESSOR_A => 'processAirCompressorA',
  398. self::SUBJECT_AIR_COMPRESSOR_B => 'processAirCompressorB',
  399. self::SUBJECT_VACUUM_BLOWER_A => 'processVacuumBlowerA',
  400. self::SUBJECT_VACUUM_BLOWER_B => 'processVacuumBlowerB',
  401. self::SUBJECT_CENTRAL_AIR_CONDITIONER_A => 'processCentralAirConditionerA',
  402. self::SUBJECT_CENTRAL_AIR_CONDITIONER_B => 'processCentralAirConditionerB',
  403. self::SUBJECT_HOT_WATER_BOILER => 'processHotWaterBoiler',
  404. ];
  405. // 检查是否完全匹配
  406. if (isset($processMap[$subjectName])) {
  407. $method = $processMap[$subjectName];
  408. return $this->$method($item, $month);
  409. }
  410. // 检查是否包含关键词
  411. foreach ($processMap as $keyword => $method) {
  412. if (strpos($subjectName, $keyword) !== false) {
  413. // 特殊处理:如果包含"锅炉"但不包含"热水锅炉"
  414. if ($keyword === self::SUBJECT_BOILER && strpos($subjectName, self::SUBJECT_HOT_WATER_BOILER) !== false) {
  415. continue;
  416. }
  417. return $this->$method($item, $month);
  418. }
  419. }
  420. return null;
  421. }
  422. /**
  423. * 处理待分摊总额
  424. */
  425. protected function processTotalApportionment($item, $month)
  426. {
  427. $money = $this->calculateSafeAmount($item['耗电量'], $item['单位电价']);
  428. $data = $this->getMachineTime($item['部门名称'], $month);
  429. foreach ($data['machine'] as &$machine) {
  430. $machine['分摊水电'] = $this->calculateApportionment($money, $machine['占用机时'], $data['sist']);
  431. }
  432. return [
  433. 'type' => 'total_apportionment',
  434. 'data' => $data['machine']
  435. ];
  436. }
  437. /**
  438. * 处理废气处理
  439. */
  440. protected function processWasteGas($item, $month)
  441. {
  442. $electricityMoney = $this->calculateSafeAmount($item['耗电量'], $item['单位电价']);
  443. $gasMoney = $this->calculateSafeAmount($item['耗气量'], $item['单位气价']);
  444. $data = $this->getMachineTime(self::WORKSHOP_ROLLER_PRESS, $month);
  445. foreach ($data['machine'] as &$machine) {
  446. $machine['分摊水电'] = $this->calculateApportionment($electricityMoney, $machine['占用机时'], $data['sist']);
  447. $machine['废气处理'] = $this->calculateApportionment($gasMoney, $machine['占用机时'], $data['sist']);
  448. }
  449. return [
  450. 'type' => 'waste_gas',
  451. 'data' => $data['machine']
  452. ];
  453. }
  454. /**
  455. * 处理锅炉
  456. */
  457. protected function processBoiler($item, $month)
  458. {
  459. $electricityMoney = $this->calculateSafeAmount($item['耗电量'], $item['单位电价']);
  460. $gasMoney = $this->calculateSafeAmount($item['耗气量'], $item['单位气价']);
  461. $data = $this->getMachineTime(self::WORKSHOP_ROLLER_PRESS, $month);
  462. foreach ($data['machine'] as &$machine) {
  463. $machine['分摊水电'] = $this->calculateApportionment($electricityMoney, $machine['占用机时'], $data['sist']);
  464. $machine['锅炉'] = $this->calculateApportionment($gasMoney, $machine['占用机时'], $data['sist']);
  465. }
  466. return [
  467. 'type' => 'boiler',
  468. 'data' => $data['machine']
  469. ];
  470. }
  471. /**
  472. * 处理空压机A
  473. */
  474. protected function processAirCompressorA($item, $month)
  475. {
  476. return $this->processGeneralElectricEquipment($item, $month, self::SUBJECT_AIR_COMPRESSOR_A);
  477. }
  478. /**
  479. * 处理空压机B
  480. */
  481. protected function processAirCompressorB($item, $month)
  482. {
  483. return $this->processGeneralElectricEquipment($item, $month, self::SUBJECT_AIR_COMPRESSOR_B);
  484. }
  485. /**
  486. * 处理真空鼓风机A
  487. */
  488. protected function processVacuumBlowerA($item, $month)
  489. {
  490. return $this->processGeneralElectricEquipment($item, $month, self::SUBJECT_VACUUM_BLOWER_A);
  491. }
  492. /**
  493. * 处理真空鼓风机B
  494. */
  495. protected function processVacuumBlowerB($item, $month)
  496. {
  497. return $this->processGeneralElectricEquipment($item, $month, self::SUBJECT_VACUUM_BLOWER_B);
  498. }
  499. /**
  500. * 处理中央空调A
  501. */
  502. protected function processCentralAirConditionerA($item, $month)
  503. {
  504. return $this->processGeneralElectricEquipment($item, $month, self::SUBJECT_CENTRAL_AIR_CONDITIONER_A);
  505. }
  506. /**
  507. * 处理中央空调B
  508. */
  509. protected function processCentralAirConditionerB($item, $month)
  510. {
  511. return $this->processGeneralElectricEquipment($item, $month, self::SUBJECT_CENTRAL_AIR_CONDITIONER_B);
  512. }
  513. /**
  514. * 处理热水锅炉
  515. */
  516. protected function processHotWaterBoiler($item, $month)
  517. {
  518. return $this->processGeneralElectricEquipment($item, $month, '热水锅炉');
  519. }
  520. /**
  521. * 通用电气设备处理(适用于所有车间)
  522. */
  523. protected function processGeneralElectricEquipment($item, $month, $equipmentType)
  524. {
  525. $money = $this->calculateSafeAmount($item['耗电量'], $item['单位电价']);
  526. $data = $this->getMachineTime(self::WORKSHOP_LIST_ALL, $month);
  527. foreach ($data['machine'] as &$machine) {
  528. $machine[$equipmentType] = $this->calculateApportionment($money, $machine['占用机时'], $data['sist']);
  529. }
  530. return [
  531. 'type' => $equipmentType,
  532. 'data' => $data['machine']
  533. ];
  534. }
  535. /**
  536. * 计算分摊金额
  537. */
  538. protected function calculateApportionment($totalAmount, $machineTime, $totalTime)
  539. {
  540. if ($totalTime <= 0) {
  541. return 0;
  542. }
  543. return round($totalAmount * ($machineTime / $totalTime), 2);
  544. }
  545. /**
  546. * 查询车间机台通电机时数据(优化版)
  547. */
  548. protected function getMachineTime($workshop, $month)
  549. {
  550. $where = [
  551. 'a.sys_ny' => $month,
  552. 'b.sys_sbID' => ['<>','']
  553. ];
  554. // 构建车间查询条件
  555. if (is_array($workshop)) {
  556. $where['a.车间名称'] = ['in', $workshop];
  557. } else {
  558. if (strpos($workshop, '机组') !== false) {
  559. $where['b.设备编组'] = $workshop;
  560. } elseif (strpos($workshop, '车间') !== false) {
  561. $where['a.车间名称'] = $workshop;
  562. }
  563. }
  564. // 查询机台数据
  565. $machine = db('成本v23_月度成本明细')
  566. ->alias('a')
  567. ->join('设备_基本资料 b', 'a.sczl_jtbh = b.设备编号', 'left')
  568. ->field('rtrim(车间名称) as 车间名称,a.sczl_gdbh as 工单编号,a.sczl_yjno as 印件号,a.sczl_gxh as 工序号,a.sczl_jtbh as 机台编号,a.占用机时,a.Uniqid')
  569. ->where($where)
  570. ->select();
  571. // 查询总时长
  572. $totalTime = db('成本v23_月度成本明细')
  573. ->alias('a')
  574. ->join('设备_基本资料 b', 'a.sczl_jtbh = b.设备编号', 'left')
  575. ->where($where)
  576. ->value('sum(a.占用机时) as 占用机时', 0);
  577. return [
  578. 'machine' => $machine,
  579. 'sist' => $totalTime
  580. ];
  581. }
  582. /**
  583. * 统计分摊结果
  584. */
  585. protected function summarizeApportionment($result, $department, $subject,
  586. &$summaryByDepartment, &$summaryBySubject,
  587. &$summaryByDepartmentSubject)
  588. {
  589. $resultType = $result['type'];
  590. $machineData = $result['data'];
  591. if (empty($machineData)) {
  592. return;
  593. }
  594. // 清洗部门名称
  595. $cleanDepartment = trim($department);
  596. $cleanSubject = trim($subject);
  597. // 初始化统计键
  598. if (!isset($summaryByDepartment[$cleanDepartment])) {
  599. $summaryByDepartment[$cleanDepartment] = [];
  600. }
  601. if (!isset($summaryBySubject[$resultType])) {
  602. $summaryBySubject[$resultType] = [];
  603. }
  604. if (!isset($summaryByDepartmentSubject[$cleanDepartment])) {
  605. $summaryByDepartmentSubject[$cleanDepartment] = [];
  606. }
  607. if (!isset($summaryByDepartmentSubject[$cleanDepartment][$resultType])) {
  608. $summaryByDepartmentSubject[$cleanDepartment][$resultType] = [
  609. 'department' => $cleanDepartment,
  610. 'subject' => $cleanSubject,
  611. 'result_type' => $resultType,
  612. 'total_amount' => 0,
  613. 'machine_count' => 0,
  614. 'work_order_count' => 0
  615. ];
  616. }
  617. // 按车间和机台统计
  618. foreach ($machineData as $machine) {
  619. // 获取车间名称(已使用rtrim清洗过)
  620. $workshop = isset($machine['车间名称']) ? $machine['车间名称'] : '未知车间';
  621. // 统计按部门
  622. if (!isset($summaryByDepartment[$cleanDepartment][$workshop])) {
  623. $summaryByDepartment[$cleanDepartment][$workshop] = [
  624. 'total_amount' => 0,
  625. 'machine_count' => 0,
  626. 'subjects' => []
  627. ];
  628. }
  629. // 统计按科目
  630. if (!isset($summaryBySubject[$resultType][$workshop])) {
  631. $summaryBySubject[$resultType][$workshop] = [
  632. 'total_amount' => 0,
  633. 'machine_count' => 0,
  634. 'departments' => []
  635. ];
  636. }
  637. // 计算此机台的总分摊金额
  638. $machineTotal = 0;
  639. $apportionmentTypes = ['分摊水电', '废气处理', '锅炉', '热水锅炉',
  640. '空压机A', '空压机B', '真空鼓风机A', '真空鼓风机B',
  641. '中央空调A', '中央空调B'];
  642. foreach ($apportionmentTypes as $type) {
  643. if (isset($machine[$type])) {
  644. $amount = floatval($machine[$type]);
  645. $machineTotal += $amount;
  646. // 按部门+车间统计各科目金额
  647. if (!isset($summaryByDepartment[$cleanDepartment][$workshop]['subjects'][$type])) {
  648. $summaryByDepartment[$cleanDepartment][$workshop]['subjects'][$type] = 0;
  649. }
  650. $summaryByDepartment[$cleanDepartment][$workshop]['subjects'][$type] += $amount;
  651. // 按科目+车间统计各部门金额
  652. if (!in_array($cleanDepartment, $summaryBySubject[$resultType][$workshop]['departments'])) {
  653. $summaryBySubject[$resultType][$workshop]['departments'][] = $cleanDepartment;
  654. }
  655. }
  656. }
  657. // 更新统计信息
  658. if ($machineTotal > 0) {
  659. $summaryByDepartment[$cleanDepartment][$workshop]['total_amount'] += $machineTotal;
  660. $summaryByDepartment[$cleanDepartment][$workshop]['machine_count']++;
  661. $summaryBySubject[$resultType][$workshop]['total_amount'] += $machineTotal;
  662. $summaryBySubject[$resultType][$workshop]['machine_count']++;
  663. $summaryByDepartmentSubject[$cleanDepartment][$resultType]['total_amount'] += $machineTotal;
  664. $summaryByDepartmentSubject[$cleanDepartment][$resultType]['machine_count']++;
  665. // 统计工单数(去重)
  666. if (!isset($summaryByDepartmentSubject[$cleanDepartment][$resultType]['work_orders'])) {
  667. $summaryByDepartmentSubject[$cleanDepartment][$resultType]['work_orders'] = [];
  668. }
  669. if (isset($machine['工单编号'])) {
  670. $summaryByDepartmentSubject[$cleanDepartment][$resultType]['work_orders'][] = $machine['工单编号'];
  671. }
  672. }
  673. }
  674. // 计算工单数(去重)
  675. foreach ($summaryByDepartmentSubject[$cleanDepartment] as $type => &$data) {
  676. if (isset($data['work_orders'])) {
  677. $data['work_order_count'] = count(array_unique($data['work_orders']));
  678. unset($data['work_orders']);
  679. }
  680. }
  681. // 为部门统计添加汇总信息
  682. $this->addSummaryToDepartment($summaryByDepartment[$cleanDepartment]);
  683. // 为科目统计添加汇总信息
  684. $this->addSummaryToSubject($summaryBySubject[$resultType]);
  685. }
  686. /**
  687. * 为部门统计添加汇总信息
  688. */
  689. protected function addSummaryToDepartment(&$departmentData)
  690. {
  691. $totalAmount = 0;
  692. $totalMachines = 0;
  693. foreach ($departmentData as $workshop => $data) {
  694. if ($workshop === 'summary') continue;
  695. $totalAmount += $data['total_amount'];
  696. $totalMachines += $data['machine_count'];
  697. }
  698. $departmentData['summary'] = [
  699. 'total_amount' => round($totalAmount, 2),
  700. 'total_machines' => $totalMachines,
  701. 'workshop_count' => count($departmentData) - 1
  702. ];
  703. }
  704. /**
  705. * 为科目统计添加汇总信息
  706. */
  707. protected function addSummaryToSubject(&$subjectData)
  708. {
  709. $totalAmount = 0;
  710. $totalMachines = 0;
  711. $allDepartments = [];
  712. foreach ($subjectData as $workshop => $data) {
  713. if ($workshop === 'summary') continue;
  714. $totalAmount += $data['total_amount'];
  715. $totalMachines += $data['machine_count'];
  716. $allDepartments = array_merge($allDepartments, $data['departments']);
  717. }
  718. $subjectData['summary'] = [
  719. 'total_amount' => round($totalAmount, 2),
  720. 'total_machines' => $totalMachines,
  721. 'workshop_count' => count($subjectData) - 1,
  722. 'department_count' => count(array_unique($allDepartments))
  723. ];
  724. }
  725. /**
  726. * 格式化最终统计结果
  727. */
  728. protected function formatFinalResults($apportionmentResults,$month,$sys)
  729. {
  730. $data = [];
  731. foreach ($apportionmentResults as $key => $value) {
  732. foreach ($value['科目明细'] as $item) {
  733. $data[] = [
  734. 'Sys_ny' => $month,
  735. '科目名称' => $item['source_subjects'],
  736. '设备编号' => $key,
  737. '分摊系数' => 1,
  738. '分摊金额' => $item['amount'],
  739. 'Sys_id' => $sys,
  740. 'Sys_rq' => date('Y-m-d H:i:s',time()),
  741. ];
  742. }
  743. }
  744. return $data;
  745. }
  746. /**
  747. * 获取车间机台生产工单
  748. * @param $sist
  749. * @param $month
  750. * @return bool|\PDOStatement|string|\think\Collection
  751. * @throws \think\db\exception\DataNotFoundException
  752. * @throws \think\db\exception\ModelNotFoundException
  753. * @throws \think\exception\DbException
  754. */
  755. protected function getMachineWorkOrder($machine,$month)
  756. {
  757. $list = db('成本v23_月度成本明细')
  758. ->where([
  759. 'sys_ny' => $month,
  760. 'sczl_jtbh' => $machine,
  761. ])
  762. ->field([
  763. 'sczl_gdbh' => '工单编号',
  764. 'sczl_yjno' => '印件号',
  765. 'sczl_gxh' => '工序号',
  766. 'sczl_jtbh' => '机台编号',
  767. '占用机时',
  768. ])
  769. ->group('工单编号,印件号,工序号')
  770. ->select();
  771. return $list;
  772. }
  773. /**
  774. * 查询车间机台色度数
  775. * @param $month
  776. * @return bool|\PDOStatement|string|\think\Collection
  777. * @throws \think\db\exception\DataNotFoundException
  778. * @throws \think\db\exception\ModelNotFoundException
  779. * @throws \think\exception\DbException
  780. */
  781. protected function getMachineTotal($month)
  782. {
  783. $list = db('成本_各月分摊系数')
  784. ->alias('a')
  785. ->join('成本v23_月度成本明细 b', 'b.sys_ny = a.Sys_ny and b.sczl_jtbh = a.设备编号','LEFT')
  786. ->where([
  787. 'a.Sys_ny' => $month,
  788. 'b.车间名称' => ['in', self::WORKSHOP_LIST_ALL],
  789. ])
  790. ->field([
  791. 'b.sczl_jtbh' => '机台编号',
  792. 'sum(b.占用机时)' => '占用机时',
  793. 'a.分摊金额',
  794. 'a.科目名称',
  795. ])
  796. ->group('机台编号,a.科目名称')
  797. ->select();
  798. foreach ($list as $key => $item) {
  799. $list[$key]['金额'] = round($item['分摊金额']/$item['占用机时'], 2);
  800. }
  801. $data = [];
  802. foreach ($list as $item) {
  803. $machineCode = $item['机台编号'];
  804. $subjectName = explode('(',$item['科目名称']);
  805. $amount = $item['金额'];
  806. // 如果这个机台编号还没有在结果数组中,初始化它
  807. if (!isset($data[$machineCode])) {
  808. $data[$machineCode] = [];
  809. }
  810. // 将科目名称和金额添加到对应的机台编号下
  811. $data[$machineCode][$subjectName[0]] = $amount;
  812. }
  813. return $data;
  814. }
  815. }