Service.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838
  1. <?php
  2. namespace App\Service;
  3. use App\Jobs\OperationLog;
  4. use App\Model\Depart;
  5. use App\Model\Employee;
  6. use Illuminate\Support\Facades\Redis;
  7. use Illuminate\Support\Facades\Storage;
  8. /**
  9. * 公用的公共服务
  10. * @package App\Models
  11. */
  12. class Service
  13. {
  14. public $log;
  15. public $total = 0;
  16. public function __construct()
  17. {
  18. }
  19. //分页共用
  20. public function limit($db, $columns, $request)
  21. {
  22. $per_page = $request['page_size'] ?? 100;
  23. $page = $request['page_index'] ?? 1;
  24. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  25. $data['total'] = $return['total'];
  26. $data['data'] = $return['data'];
  27. return $data;
  28. }
  29. //分页共用2
  30. public function limitData($db, $columns, $request)
  31. {
  32. $per_page = $request['page_size'] ?? 1000;
  33. $page = $request['page_index'] ?? 1;
  34. $return = $db->paginate($per_page, $columns, 'page', $page)->toArray();
  35. return $return['data'];
  36. }
  37. //抽象一个查询条件,省的每天写很多行
  38. protected function is_exist_db($data, $word, $words, $db, $formula = '=', $type = '')
  39. {
  40. if (isset($data[$word]) && ($data[$word] !== null && $data[$word] !== '' && $data[$word] !== [])) {
  41. switch ($type) {
  42. case 'time':
  43. $data[$word] = ctype_digit($data[$word]) ? $data[$word] : strtotime($data[$word]);
  44. if ($formula == '<'||$formula == '<=') $data[$word] += 86400;
  45. $db = $db->where($words, $formula, $data[$word]);
  46. break;
  47. case 'like':
  48. $db = $db->where($words, $type, '%' . $data[$word] . '%');
  49. break;
  50. case 'in':
  51. if (is_array($data[$word])) {
  52. $db = $db->wherein($words, $data[$word]);
  53. } else {
  54. $db = $db->wherein($words, explode(',', $data[$word]));
  55. }
  56. break;
  57. default:
  58. $db = $db->where($words, $formula, $data[$word]);
  59. break;
  60. }
  61. return $db;
  62. }
  63. return $db;
  64. }
  65. //判断是否为空
  66. protected function isEmpty($data, $word)
  67. {
  68. if (isset($data[$word]) && (!empty($data[$word]) || $data[$word] === '0'|| $data[$word] === 0)) return false;
  69. return true;
  70. }
  71. //递归处理数据成子父级关系
  72. public function makeTree($parentId, &$node)
  73. {
  74. $tree = [];
  75. foreach ($node as $key => $value) {
  76. if ($value['parent_id'] == $parentId) {
  77. $tree[$value['id']] = $value;
  78. unset($node[$key]);
  79. if (isset($tree[$value['id']]['children'])) {
  80. $tree[$value['id']]['children'] = array_merge($tree[$value['id']]['children'], $this->makeTree($value['id'], $node));
  81. } else {
  82. $tree[$value['id']]['children'] = $this->makeTree($value['id'], $node);
  83. }
  84. }
  85. }
  86. return $tree;
  87. }
  88. //进行递归处理数组的排序问题
  89. public function set_sort_circle($data){
  90. foreach ($data as $k=>$v){
  91. // var_dump($v);die;
  92. if(isset($v['children'])&&!empty($v['children'])){
  93. $data[$k]['children'] = $this->set_sort_circle($v['children']);
  94. }
  95. }
  96. $data = array_merge($data);
  97. return $data;
  98. }
  99. //根据编码规则获取每一级的code
  100. public function get_rule_code($code, $rule)
  101. {
  102. $rules = [];
  103. $num = 0;
  104. foreach ($rule as $v) {
  105. $num += $v['num'];
  106. $code = substr($code, 0, $num);
  107. if (strlen($code) != $num) continue;
  108. $rules[] = $code;
  109. }
  110. return $rules;
  111. }
  112. function curlOpen($url, $config = array())
  113. {
  114. $arr = array('post' => false,'referer' => $url,'cookie' => '', 'useragent' => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; customie8)', 'timeout' => 100, 'return' => true, 'proxy' => '', 'userpwd' => '', 'nobody' => false,'header'=>array(),'gzip'=>true,'ssl'=>true,'isupfile'=>false,'returnheader'=>false,'request'=>'post');
  115. $arr = array_merge($arr, $config);
  116. $ch = curl_init();
  117. curl_setopt($ch, CURLOPT_URL, $url);
  118. curl_setopt($ch, CURLOPT_RETURNTRANSFER, $arr['return']);
  119. curl_setopt($ch, CURLOPT_NOBODY, $arr['nobody']);
  120. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  121. curl_setopt($ch, CURLOPT_USERAGENT, $arr['useragent']);
  122. curl_setopt($ch, CURLOPT_REFERER, $arr['referer']);
  123. curl_setopt($ch, CURLOPT_TIMEOUT, $arr['timeout']);
  124. curl_setopt($ch, CURLOPT_HEADER, $arr['returnheader']);//��ȡheader
  125. if($arr['gzip']) curl_setopt($ch, CURLOPT_ENCODING, 'gzip,deflate');
  126. if($arr['ssl'])
  127. {
  128. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  129. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
  130. }
  131. if(!empty($arr['cookie']))
  132. {
  133. curl_setopt($ch, CURLOPT_COOKIEJAR, $arr['cookie']);
  134. curl_setopt($ch, CURLOPT_COOKIEFILE, $arr['cookie']);
  135. }
  136. if(!empty($arr['proxy']))
  137. {
  138. //curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  139. curl_setopt ($ch, CURLOPT_PROXY, $arr['proxy']);
  140. if(!empty($arr['userpwd']))
  141. {
  142. curl_setopt($ch,CURLOPT_PROXYUSERPWD,$arr['userpwd']);
  143. }
  144. }
  145. //ip�Ƚ����⣬�ü�ֵ��ʾ
  146. if(!empty($arr['header']['ip']))
  147. {
  148. array_push($arr['header'],'X-FORWARDED-FOR:'.$arr['header']['ip'],'CLIENT-IP:'.$arr['header']['ip']);
  149. unset($arr['header']['ip']);
  150. }
  151. $arr['header'] = array_filter($arr['header']);
  152. if(!empty($arr['header']))
  153. {
  154. curl_setopt($ch, CURLOPT_HTTPHEADER, $arr['header']);
  155. }
  156. if($arr['request'] === 'put'){
  157. curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");
  158. curl_setopt($ch, CURLOPT_POSTFIELDS,$arr['post']);
  159. }elseif($arr['post'] != false)
  160. {
  161. curl_setopt($ch, CURLOPT_POST, true);
  162. if(is_array($arr['post']) && $arr['isupfile'] === false)
  163. {
  164. $post = http_build_query($arr['post']);
  165. }
  166. else
  167. {
  168. $post = $arr['post'];
  169. }
  170. curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
  171. }
  172. $result = curl_exec($ch);
  173. curl_close($ch);
  174. return $result;
  175. }
  176. function getAllIdsArr($data, $pid = 0, $prefix = '', &$result = []) {
  177. foreach ($data as $node) {
  178. if ($node['parent_id'] == $pid) {
  179. $id = $prefix . $node['id'];
  180. $result[] = $id;
  181. $this->getAllIdsArr($data, $node['id'], $id . ',', $result);
  182. }
  183. }
  184. return $result;
  185. }
  186. function getLongestStr($arr = [], $searchStr){
  187. if(empty($arr) || ! $searchStr) return '';
  188. if(! is_string($searchStr)) $searchStr = (string)$searchStr;
  189. $longest = '';
  190. foreach ($arr as $str) {
  191. if (strpos($str, $searchStr) !== false && strlen($str) > strlen($longest)) {
  192. $longest = $str;
  193. }
  194. }
  195. return $longest;
  196. }
  197. function getAllDescendants($data, $id) {
  198. $result = array(); // 存储结果的数组
  199. foreach ($data as $node) {
  200. if ($node['parent_id'] == $id) { // 如果当前节点的父 ID 等于指定 ID,则将该节点添加到结果中
  201. $result[] = $node['id'];
  202. // 递归查询该节点的所有子孙节点,并将结果合并到结果数组中
  203. $result = array_merge($result, $this->getAllDescendants($data, $node['id']));
  204. }
  205. }
  206. return $result;
  207. }
  208. //后台端 某些需要限制请求频率的接口
  209. //需要主动删除 Redis::del($key)
  210. public function limitingSendRequest($key,$value=0){
  211. $prefix = config('app.name') . ':';
  212. $key = $prefix . $key;
  213. if(! empty($value)) $value = 1;
  214. // 使用Redis Facade设置,当键名不存在时才设置成功
  215. if (Redis::setnx($key, $value)) return [true, ''];
  216. return [false,'操作频繁!'];
  217. }
  218. public function delLimitingSendRequest($key){
  219. $prefix = config('app.name') . ':';
  220. $key = $prefix . $key;
  221. Redis::del($key);
  222. }
  223. //后台端 某些需要限制请求频率的接口 有过期时间
  224. public function limitingSendRequestBackgExpire($key,$ttl = 5){
  225. $prefix = config('app.name') . ':';
  226. $key = $prefix . $key;
  227. if($ttl < 5) $ttl = 5;
  228. // 使用Redis Facade设置,当键名不存在时才设置成功
  229. if (Redis::setnx($key, 1)) {
  230. Redis::expire($key, $ttl); //多少秒后过期
  231. return [true, ''];
  232. }
  233. return [false,'操作频繁, 请在 ' . $ttl . '秒后重试'];
  234. }
  235. //前端传来的时间段 转换为时间戳
  236. //精确到秒
  237. function changeDateToTimeStampAboutRange($time_range, $is_end = true){
  238. if(empty($time_range[0]) || empty($time_range[1])) return [];
  239. // 创建一个 DateTime 对象并设置时区为 UTC
  240. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  241. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  242. // 将时区设置为 PRC
  243. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  244. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  245. // 将日期时间格式化为特定格式
  246. $formattedDate = $dateTime->format('Y-m-d');
  247. $formattedDate1 = $dateTime1->format('Y-m-d');
  248. $str = " 23:59:59";
  249. if(! $is_end) $str = " 00:00:00";
  250. $return = [];
  251. $return[] = strtotime($formattedDate . " 00:00:00");
  252. $return[] = strtotime($formattedDate1 . $str);
  253. return $return;
  254. }
  255. //前端传来的时间段 转换为时间戳
  256. //精确到日
  257. function changeDateToNewDate($time_range){
  258. if(empty($time_range[0]) || empty($time_range[1])) return [];
  259. // 创建一个 DateTime 对象并设置时区为 UTC
  260. $dateTime = new \DateTime($time_range[0], new \DateTimeZone('UTC'));
  261. $dateTime1 = new \DateTime($time_range[1], new \DateTimeZone('UTC'));
  262. // 将时区设置为 PRC
  263. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  264. $dateTime1->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  265. // 将日期时间格式化为特定格式
  266. $formattedDate = $dateTime->format('Y-m-d');
  267. $formattedDate1 = $dateTime1->format('Y-m-d');
  268. $return = [];
  269. $return[] = strtotime($formattedDate);
  270. $return[] = strtotime($formattedDate1);
  271. return $return;
  272. }
  273. function changeDateToNewDate2($time){
  274. if(empty($time_range)) return [];
  275. // 创建一个 DateTime 对象并设置时区为 UTC
  276. $dateTime = new \DateTime($time_range, new \DateTimeZone('UTC'));
  277. // 将时区设置为 PRC
  278. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  279. // 将日期时间格式化为特定格式
  280. $formattedDate = $dateTime->format('Y-m-d 00:00:00');
  281. $formattedDate1 = $dateTime->format('Y-m-d 23:59:59');
  282. $return = [];
  283. $return[] = strtotime($formattedDate);
  284. $return[] = strtotime($formattedDate1);
  285. return $return;
  286. }
  287. //前端传来的时间 转为时间戳
  288. //精确到分
  289. function changeDateToDateMin($time){
  290. if(empty($time)) return '';
  291. // 创建一个 DateTime 对象并设置时区为 UTC
  292. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  293. // 将时区设置为 PRC
  294. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  295. // 将日期时间格式化为特定格式
  296. $formattedDate = $dateTime->format('Y-m-d H:i');
  297. return strtotime($formattedDate);
  298. }
  299. //前端传来的时间 转为时间戳
  300. //精确到日
  301. function changeDateToDate($time, $is_end = false){
  302. if(empty($time)) return '';
  303. // 创建一个 DateTime 对象并设置时区为 UTC
  304. $dateTime = new \DateTime($time, new \DateTimeZone('UTC'));
  305. // 将时区设置为 PRC
  306. $dateTime->setTimezone(new \DateTimeZone('Asia/Shanghai'));
  307. $str = "00:00:00";
  308. if($is_end) $str = "23:59:59";
  309. // 将日期时间格式化为特定格式
  310. $formattedDate = $dateTime->format('Y-m-d ' . $str);
  311. return strtotime($formattedDate);
  312. }
  313. /**
  314. * 检查数字是否合法,并可验证其正负性和小数位数
  315. *
  316. * @param mixed $number 要检查的值
  317. * @param int $decimals 允许的最大小数位数(默认 2)
  318. * @param string|null $sign 要求的符号:'positive', 'negative', 'zero', 'non-negative', 'non-positive' null 表示不限制
  319. * @param bool $strict 是否严格模式(不允许整数传字符串等)
  320. * @return array ['valid' => bool, 'error' => string|null, 'info' => array]
  321. */
  322. public function checkNumber($number, $decimals = 2, $sign = null, $strict = false)
  323. {
  324. $result = [
  325. 'valid' => false,
  326. 'error' => null,
  327. 'info' => []
  328. ];
  329. // 1. 类型检查
  330. if ($strict) {
  331. if (!is_numeric($number) || is_bool($number)) {
  332. $result['error'] = '必须是数字类型';
  333. return $result;
  334. }
  335. } else {
  336. // 宽松模式:允许字符串数字
  337. if (!is_numeric($number)) {
  338. $result['error'] = '不是有效数字';
  339. return $result;
  340. }
  341. }
  342. $num = (float)$number; // 统一转为浮点数处理
  343. // 2. 正负号检查
  344. if ($sign !== null) {
  345. switch ($sign) {
  346. case 'positive':
  347. if ($num <= 0) {
  348. $result['error'] = '数字必须大于 0';
  349. return $result;
  350. }
  351. break;
  352. case 'negative':
  353. if ($num >= 0) {
  354. $result['error'] = '数字必须小于 0';
  355. return $result;
  356. }
  357. break;
  358. case 'zero':
  359. if ($num != 0) {
  360. $result['error'] = '数字必须等于 0';
  361. return $result;
  362. }
  363. break;
  364. case 'non-negative': // 大于等于 0
  365. if ($num < 0) {
  366. $result['error'] = '数字必须大于或等于 0';
  367. return $result;
  368. }
  369. break;
  370. case 'non-positive': // 小于等于 0
  371. if ($num > 0) {
  372. $result['error'] = '数字必须小于或等于 0';
  373. return $result;
  374. }
  375. break;
  376. default:
  377. $result['error'] = "不支持的符号类型: '{$sign}'";
  378. return $result;
  379. }
  380. }
  381. // 3. 小数位数检查
  382. // 将数字转为标准格式,避免科学计数法
  383. $numStr = rtrim(rtrim(sprintf('%.10F', $num), '0'), '.'); // 去除末尾无意义的0
  384. if ($numStr === '' || $numStr === '-') {
  385. $numStr = '0';
  386. }
  387. // 检查是否有小数点
  388. if (strpos($numStr, '.') === false) {
  389. $decimalPlaces = 0;
  390. } else {
  391. $parts = explode('.', $numStr);
  392. $decimalPlaces = strlen($parts[1]);
  393. }
  394. if ($decimalPlaces > $decimals) {
  395. $result['error'] = "小数位数超过 {$decimals} 位(实际 {$decimalPlaces} 位)";
  396. return $result;
  397. }
  398. // 4. 附加信息
  399. $result['valid'] = true;
  400. $result['info'] = [
  401. 'original' => $number,
  402. 'value' => $num,
  403. 'decimal_places' => $decimalPlaces,
  404. 'sign' => $num > 0 ? 'positive' : ($num < 0 ? 'negative' : 'zero'),
  405. ];
  406. return $result;
  407. }
  408. public function getTopId($id, $data) {
  409. foreach ($data as $item) {
  410. if ($item['id'] == $id) {
  411. if ($item['parent_id'] == 0) {
  412. // 找到最顶级的id
  413. return $item['id'];
  414. } else {
  415. // 继续递归查找父级
  416. return $this->getTopId($item['parent_id'], $data);
  417. }
  418. }
  419. }
  420. // 如果没有找到匹配的id,则返回null或者其他你希望的默认值
  421. return 0;
  422. }
  423. // 递归查找所有父级id
  424. public function findParentIds($id, $data) {
  425. $parentIds = [];
  426. foreach ($data as $item) {
  427. if ($item['id'] == $id) {
  428. $parentId = $item['parent_id'];
  429. if ($parentId) {
  430. $parentIds[] = $parentId;
  431. $parentIds = array_merge($parentIds, $this->findParentIds($parentId, $data));
  432. }
  433. break;
  434. }
  435. }
  436. return $parentIds;
  437. }
  438. // 递归查找所有子级id
  439. public function findChildIds($id, $data) {
  440. $childIds = [];
  441. foreach ($data as $item) {
  442. if ($item['parent_id'] == $id) {
  443. $childId = $item['id'];
  444. $childIds[] = $childId;
  445. $childIds = array_merge($childIds, $this->findChildIds($childId, $data));
  446. }
  447. }
  448. return $childIds;
  449. }
  450. public function getDataFile($data){
  451. foreach ($data as $key => $value){
  452. if($key == 'depart_id' || $key == 'top_depart_id') unset($data[$key]);
  453. }
  454. return $data;
  455. }
  456. // 校验域名是否通畅可达
  457. // $domain baidu.com 不要带http这些协议头
  458. // gethostbyname() 函数可能会受到 PHP 配置中的 allow_url_fopen 和 disable_functions 选项的限制
  459. function isDomainAvailable($domain) {
  460. $ip = gethostbyname($domain);
  461. // 如果解析失败或者返回的 IP 地址与输入的域名相同,则说明域名无效
  462. if ($ip === $domain || filter_var($ip, FILTER_VALIDATE_IP) === false) return false;
  463. return true;
  464. }
  465. public function delStorageFile($old, $new = [], $dir = "upload_files/"){
  466. foreach ($old as $value){
  467. if(! in_array($value, $new)){
  468. $filename_rep = "/api/uploadFiles/";
  469. $filename = str_replace($filename_rep, "", $value);
  470. $filePath = $dir . $filename;
  471. if (Storage::disk('public')->exists($filePath)) {
  472. // 文件存在 进行删除操作
  473. Storage::disk('public')->delete($filePath);
  474. }
  475. }
  476. }
  477. }
  478. public function showTimeAgo($time, $time_big){
  479. // 计算时间差(秒)
  480. $diffInSeconds = $time_big - $time;
  481. // 将时间差转换为更易处理的单位
  482. $diffInMinutes = floor($diffInSeconds / 60);
  483. $diffInHours = floor($diffInSeconds / 3600);
  484. $diffInDays = floor($diffInSeconds / (3600 * 24));
  485. // 根据时间差生成描述性文本
  486. if ($diffInSeconds < 60) {
  487. $timeAgo = '刚刚';
  488. } elseif ($diffInMinutes < 60) {
  489. $timeAgo = $diffInMinutes . '分钟前';
  490. } elseif ($diffInHours < 24) {
  491. $timeAgo = $diffInHours . '小时前';
  492. } elseif ($diffInDays < 2) {
  493. $timeAgo = '昨天';
  494. } elseif ($diffInDays < 7) {
  495. $timeAgo = $diffInDays . '天前';
  496. } elseif ($diffInDays < 15) {
  497. $timeAgo = '一周前';
  498. } elseif ($diffInDays < 30) {
  499. $timeAgo = '半个月内';
  500. } else {
  501. // 如果超过半个月,可以使用具体的日期格式
  502. $crtTimeDate = date('Y-m-d', $time);
  503. $timeAgo = '在 ' . $crtTimeDate;
  504. }
  505. return $timeAgo;
  506. }
  507. // 递归函数,用于在数据结构中查找值
  508. function findLabelsByValue($data, $valuesToFind, &$foundLabels) {
  509. foreach ($data as $item) {
  510. if (isset($item['value']) && in_array($item['value'], $valuesToFind)) {
  511. // 如果找到值,则添加其label到结果数组中
  512. $foundLabels[] = $item['label'];
  513. // 移除已找到的值,避免重复查找
  514. $key = array_search($item['value'], $valuesToFind);
  515. if ($key !== false) {
  516. unset($valuesToFind[$key]);
  517. }
  518. }
  519. if (isset($item['children']) && !empty($item['children'])) {
  520. // 递归调用自身来查找子节点
  521. $this->findLabelsByValue($item['children'], $valuesToFind, $foundLabels);
  522. }
  523. // 如果所有值都已找到,则停止递归
  524. if (empty($valuesToFind)) {
  525. break;
  526. }
  527. }
  528. }
  529. public function changeAndReturnDate($date_int){
  530. $int = intval($date_int);
  531. $bool = (string)$int === $date_int;
  532. if(! $bool || $date_int < 0) return [false, '日期不正确'];
  533. $epoch = strtotime("1900-01-01 00:00:00");
  534. $days = $date_int - 1;
  535. $seconds = $days * 86400;
  536. return [true,strtotime(date('Y-m-d 00:00:00', $epoch + $seconds))];
  537. }
  538. function findTopLevelId($data, $id) {
  539. // 遍历数据,查找给定ID的节点
  540. foreach ($data as $item) {
  541. if ($item['id'] == $id) {
  542. // 如果找到了给定ID的节点,并且它的parent_id为null,则它就是最顶层节点
  543. if ($item['parent_id'] === 0) {
  544. return $item['id'];
  545. } else {
  546. // 否则,继续寻找其父节点的最顶层节点
  547. return $this->findTopLevelId($data, $item['parent_id']);
  548. }
  549. }
  550. }
  551. // 如果没有找到给定ID的节点,返回null或抛出异常
  552. return 0;
  553. }
  554. function returnDays($time = [], $is_mirco_time = false){
  555. // 示例时间戳
  556. $timestamp1 = $time[0];
  557. $timestamp2 = $time[1];
  558. // 计算时间差
  559. $difference = abs($timestamp2 - $timestamp1);
  560. // 将时间差转换为天数
  561. $days = floor($difference / (60 * 60 * 24));
  562. if($is_mirco_time) $days = $days / 1000;
  563. return $days;
  564. }
  565. public function post_helper($url, $data, $header = [], $timeout = 30){
  566. $ch = curl_init();
  567. curl_setopt($ch, CURLOPT_URL, $url);
  568. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  569. curl_setopt($ch, CURLOPT_ENCODING, '');
  570. curl_setopt($ch, CURLOPT_POST, 1);
  571. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  572. curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
  573. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  574. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  575. if(!is_null($data)) curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  576. $r = curl_exec($ch);
  577. if ($r === false) {
  578. // 获取错误号
  579. $errorNumber = curl_errno($ch);
  580. // 获取错误信息
  581. $errorMessage = curl_error($ch);
  582. $message = "cURL Error #{$errorNumber}: {$errorMessage}";
  583. return [false, $message];
  584. }
  585. curl_close($ch);
  586. return [true, json_decode($r, true)];
  587. }
  588. function isOverThreeMonths($timestamp1, $timestamp2, $default_month = 3) {
  589. $date1 = new \DateTime();
  590. $date1->setTimestamp($timestamp1);
  591. $date2 = new \DateTime();
  592. $date2->setTimestamp($timestamp2);
  593. // 计算两个日期的间隔
  594. $interval = $date1->diff($date2);
  595. // 总月数 = 年差 * 12 + 月差
  596. $months = $interval->y * 12 + $interval->m;
  597. if ($months >= $default_month) {
  598. return [false, "时间区间须在" . $default_month . "个月内"];
  599. }elseif ($months == 3 && ($interval->d > 0 || $interval->h > 0 || $interval->i > 0 || $interval->s > 0)) {
  600. return [false, "时间区间须在" . $default_month . "个月内"];
  601. }
  602. return [true, ''];
  603. }
  604. public function countTotal($rows, $config = [])
  605. {
  606. if (empty($rows)) return [];
  607. $total = [];
  608. foreach ($config as $col) {
  609. $key = $col['key'] ?? null;
  610. if (!$key) continue;
  611. $decimals = $col['decimals'] ?? 2; // 默认保留 2 位
  612. // 1. 基础字段累加
  613. if (!empty($col['sum']) && $col['sum'] == 1) {
  614. $sum = '0';
  615. foreach ($rows as $row) {
  616. $sum = bcadd($sum, (string)($row[$key] ?? 0), $decimals);
  617. }
  618. $total[$key] = $sum;
  619. }
  620. // 2. 公式字段
  621. if (!empty($col['sum']) && $col['sum'] == 2 && !empty($col['formula'])) {
  622. $total[$key] = $this->calcFormula($col['formula'], $total, $decimals);
  623. }
  624. }
  625. return $total;
  626. }
  627. /**
  628. * 解析并计算公式(基于 bcmath)
  629. * 例: profit / income * 100
  630. */
  631. public function calcFormula($formula, $values, $decimals = 2)
  632. {
  633. $tokens = preg_split('/\s+/', trim($formula));
  634. $stack = [];
  635. foreach ($tokens as $token) {
  636. if ($token === '') continue;
  637. if (isset($values[$token])) {
  638. $stack[] = $values[$token];
  639. } elseif (is_numeric($token)) {
  640. $stack[] = (string)$token;
  641. } else {
  642. $stack[] = $token;
  643. }
  644. }
  645. $expr = implode(' ', $stack);
  646. return $this->evaluateWithBCMath($expr, $decimals);
  647. }
  648. /**
  649. * 用 bcmath 安全执行表达式 (支持 + - * /)
  650. */
  651. public function evaluateWithBCMath($expr, $decimals = 2)
  652. {
  653. preg_match_all('/(\d+(?:\.\d+)?|[+\/*-])/', $expr, $matches);
  654. $tokens = $matches[0] ?? [];
  655. if (empty($tokens)) return 0;
  656. $output = [];
  657. $ops = [];
  658. foreach ($tokens as $token) {
  659. if (is_numeric($token)) {
  660. $output[] = (string)$token;
  661. } elseif (in_array($token, ['+', '-', '*', '/'])) {
  662. $ops[] = $token;
  663. }
  664. }
  665. $result = array_shift($output);
  666. foreach ($ops as $i => $op) {
  667. $next = $output[$i] ?? '0';
  668. switch ($op) {
  669. case '+':
  670. $result = bcadd($result, $next, $decimals);
  671. break;
  672. case '-':
  673. $result = bcsub($result, $next, $decimals);
  674. break;
  675. case '*':
  676. $result = bcmul($result, $next, $decimals);
  677. break;
  678. case '/':
  679. if (bccomp($next, '0', $decimals) === 0) {
  680. $result = '0'; // 避免除零
  681. } else {
  682. $result = bcdiv($result, $next, $decimals);
  683. }
  684. break;
  685. }
  686. }
  687. return $result;
  688. }
  689. }