common.php 74.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
<?php

// 公共助手函数

use Symfony\Component\VarExporter\VarExporter;
use think\exception\HttpResponseException;
use think\Response;
use think\Db;

error_reporting(E_ERROR | E_WARNING | E_PARSE);

if (!function_exists('__')) {

    /**
     * 获取语言变量值
     * @param string $name 语言变量名
     * @param array $vars 动态变量值
     * @param string $lang 语言
     * @return mixed
     */
    function __($name, $vars = [], $lang = '')
    {
        if (is_numeric($name) || !$name) {
            return $name;
        }
        if (!is_array($vars)) {
            $vars = func_get_args();
            array_shift($vars);
            $lang = '';
        }
        return \think\Lang::get($name, $vars, $lang);
    }
}

if (!function_exists('format_bytes')) {

    /**
     * 将字节转换为可读文本
     * @param int $size 大小
     * @param string $delimiter 分隔符
     * @param int $precision 小数位数
     * @return string
     */
    function format_bytes($size, $delimiter = '', $precision = 2)
    {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 6; $i++) {
            $size /= 1024;
        }
        return round($size, $precision) . $delimiter . $units[$i];
    }
}

if (!function_exists('datetime')) {

    /**
     * 将时间戳转换为日期时间
     * @param int $time 时间戳
     * @param string $format 日期时间格式
     * @return string
     */
    function datetime($time, $format = 'Y-m-d H:i:s')
    {
        $time = is_numeric($time) ? $time : strtotime($time);
        return date($format, $time);
    }
}

if (!function_exists('human_date')) {

    /**
     * 获取语义化时间
     * @param int $time 时间
     * @param int $local 本地时间
     * @return string
     */
    function human_date($time, $local = null)
    {
        return \fast\Date::human($time, $local);
    }
}

if (!function_exists('cdnurl')) {

    /**
     * 获取上传资源的CDN的地址
     * @param string $url 资源相对地址
     * @param boolean $domain 是否显示域名 或者直接传入域名
     * @return string
     */
    function cdnurl($url, $domain = false)
    {
        $regex = "/^((?:[a-z]+:)?\/\/|data:image\/)(.*)/i";
        $cdnurl = \think\Config::get('upload.cdnurl');
        $url = preg_match($regex, $url) || ($cdnurl && stripos($url, $cdnurl) === 0) ? $url : $cdnurl . $url;
        if ($domain && !preg_match($regex, $url)) {
            $domain = is_bool($domain) ? request()->domain() : $domain;
            $url = $domain . $url;
        }
        return $url;
    }
}


if (!function_exists('is_really_writable')) {

    /**
     * 判断文件或文件夹是否可写
     * @param string $file 文件或目录
     * @return    bool
     */
    function is_really_writable($file)
    {
        if (DIRECTORY_SEPARATOR === '/') {
            return is_writable($file);
        }
        if (is_dir($file)) {
            $file = rtrim($file, '/') . '/' . md5(mt_rand());
            if (($fp = @fopen($file, 'ab')) === false) {
                return false;
            }
            fclose($fp);
            @chmod($file, 0777);
            @unlink($file);
            return true;
        } elseif (!is_file($file) or ($fp = @fopen($file, 'ab')) === false) {
            return false;
        }
        fclose($fp);
        return true;
    }
}

if (!function_exists('rmdirs')) {

    /**
     * 删除文件夹
     * @param string $dirname 目录
     * @param bool $withself 是否删除自身
     * @return boolean
     */
    function rmdirs($dirname, $withself = true)
    {
        if (!is_dir($dirname)) {
            return false;
        }
        $files = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($dirname, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::CHILD_FIRST
        );

        foreach ($files as $fileinfo) {
            $todo = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
            $todo($fileinfo->getRealPath());
        }
        if ($withself) {
            @rmdir($dirname);
        }
        return true;
    }
}

if (!function_exists('copydirs')) {

    /**
     * 复制文件夹
     * @param string $source 源文件夹
     * @param string $dest 目标文件夹
     */
    function copydirs($source, $dest)
    {
        if (!is_dir($dest)) {
            mkdir($dest, 0755, true);
        }
        foreach (
            $iterator = new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS),
                RecursiveIteratorIterator::SELF_FIRST
            ) as $item
        ) {
            if ($item->isDir()) {
                $sontDir = $dest . DS . $iterator->getSubPathName();
                if (!is_dir($sontDir)) {
                    mkdir($sontDir, 0755, true);
                }
            } else {
                copy($item, $dest . DS . $iterator->getSubPathName());
            }
        }
    }
}

if (!function_exists('mb_ucfirst')) {
    function mb_ucfirst($string)
    {
        return mb_strtoupper(mb_substr($string, 0, 1)) . mb_strtolower(mb_substr($string, 1));
    }
}

if (!function_exists('addtion')) {

    /**
     * 附加关联字段数据
     * @param array $items 数据列表
     * @param mixed $fields 渲染的来源字段
     * @return array
     */
    function addtion($items, $fields)
    {
        if (!$items || !$fields) {
            return $items;
        }
        $fieldsArr = [];
        if (!is_array($fields)) {
            $arr = explode(',', $fields);
            foreach ($arr as $k => $v) {
                $fieldsArr[$v] = ['field' => $v];
            }
        } else {
            foreach ($fields as $k => $v) {
                if (is_array($v)) {
                    $v['field'] = isset($v['field']) ? $v['field'] : $k;
                } else {
                    $v = ['field' => $v];
                }
                $fieldsArr[$v['field']] = $v;
            }
        }
        foreach ($fieldsArr as $k => &$v) {
            $v = is_array($v) ? $v : ['field' => $v];
            $v['display'] = isset($v['display']) ? $v['display'] : str_replace(['_ids', '_id'], ['_names', '_name'], $v['field']);
            $v['primary'] = isset($v['primary']) ? $v['primary'] : '';
            $v['column'] = isset($v['column']) ? $v['column'] : 'name';
            $v['model'] = isset($v['model']) ? $v['model'] : '';
            $v['table'] = isset($v['table']) ? $v['table'] : '';
            $v['name'] = isset($v['name']) ? $v['name'] : str_replace(['_ids', '_id'], '', $v['field']);
        }
        unset($v);
        $ids = [];
        $fields = array_keys($fieldsArr);
        foreach ($items as $k => $v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $ids[$n] = array_merge(isset($ids[$n]) && is_array($ids[$n]) ? $ids[$n] : [], explode(',', $v[$n]));
                }
            }
        }
        $result = [];
        foreach ($fieldsArr as $k => $v) {
            if ($v['model']) {
                $model = new $v['model'];
            } else {
                $model = $v['name'] ? \think\Db::name($v['name']) : \think\Db::table($v['table']);
            }
            $primary = $v['primary'] ? $v['primary'] : $model->getPk();
            $result[$v['field']] = isset($ids[$v['field']]) ? $model->where($primary, 'in', $ids[$v['field']])->column($v['column'], $primary) : [];
        }

        foreach ($items as $k => &$v) {
            foreach ($fields as $m => $n) {
                if (isset($v[$n])) {
                    $curr = array_flip(explode(',', $v[$n]));

                    $linedata = array_intersect_key($result[$n], $curr);
                    $v[$fieldsArr[$n]['display']] = $fieldsArr[$n]['column'] == '*' ? $linedata : implode(',', $linedata);
                }
            }
        }
        return $items;
    }
}

if (!function_exists('var_export_short')) {

    /**
     * 使用短标签打印或返回数组结构
     * @param mixed $data
     * @param boolean $return 是否返回数据
     * @return string
     */
    function var_export_short($data, $return = true)
    {
        return var_export($data, $return);
        $replaced = [];
        $count = 0;

        //判断是否是对象
        if (is_resource($data) || is_object($data)) {
            return var_export($data, $return);
        }

        //判断是否有特殊的键名
        $specialKey = false;
        array_walk_recursive($data, function (&$value, &$key) use (&$specialKey) {
            if (is_string($key) && (stripos($key, "\n") !== false || stripos($key, "array (") !== false)) {
                $specialKey = true;
            }
        });
        if ($specialKey) {
            return var_export($data, $return);
        }
        array_walk_recursive($data, function (&$value, &$key) use (&$replaced, &$count, &$stringcheck) {
            if (is_object($value) || is_resource($value)) {
                $replaced[$count] = var_export($value, true);
                $value = "##<{$count}>##";
            } else {
                if (is_string($value) && (stripos($value, "\n") !== false || stripos($value, "array (") !== false)) {
                    $index = array_search($value, $replaced);
                    if ($index === false) {
                        $replaced[$count] = var_export($value, true);
                        $value = "##<{$count}>##";
                    } else {
                        $value = "##<{$index}>##";
                    }
                }
            }
            $count++;
        });

        $dump = var_export($data, true);

        $dump = preg_replace('#(?:\A|\n)([ ]*)array \(#i', '[', $dump); // Starts
        $dump = preg_replace('#\n([ ]*)\),#', "\n$1],", $dump); // Ends
        $dump = preg_replace('#=> \[\n\s+\],\n#', "=> [],\n", $dump); // Empties
        $dump = preg_replace('#\)$#', "]", $dump); //End

        if ($replaced) {
            $dump = preg_replace_callback("/'##<(\d+)>##'/", function ($matches) use ($replaced) {
                return isset($replaced[$matches[1]]) ? $replaced[$matches[1]] : "''";
            }, $dump);
        }

        if ($return === true) {
            return $dump;
        } else {
            echo $dump;
        }
    }
}

if (!function_exists('letter_avatar')) {
    /**
     * 首字母头像
     * @param $text
     * @return string
     */
    function letter_avatar($text)
    {
        $total = unpack('L', hash('adler32', $text, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $bg = "rgb({$r},{$g},{$b})";
        $color = "#ffffff";
        $first = mb_strtoupper(mb_substr($text, 0, 1));
        $src = base64_encode('<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="100" width="100"><rect fill="' . $bg . '" x="0" y="0" width="100" height="100"></rect><text x="50" y="50" font-size="50" text-copy="fast" fill="' . $color . '" text-anchor="middle" text-rights="admin" dominant-baseline="central">' . $first . '</text></svg>');
        $value = 'data:image/svg+xml;base64,' . $src;
        return $value;
    }
}

if (!function_exists('hsv2rgb')) {
    function hsv2rgb($h, $s, $v)
    {
        $r = $g = $b = 0;

        $i = floor($h * 6);
        $f = $h * 6 - $i;
        $p = $v * (1 - $s);
        $q = $v * (1 - $f * $s);
        $t = $v * (1 - (1 - $f) * $s);

        switch ($i % 6) {
            case 0:
                $r = $v;
                $g = $t;
                $b = $p;
                break;
            case 1:
                $r = $q;
                $g = $v;
                $b = $p;
                break;
            case 2:
                $r = $p;
                $g = $v;
                $b = $t;
                break;
            case 3:
                $r = $p;
                $g = $q;
                $b = $v;
                break;
            case 4:
                $r = $t;
                $g = $p;
                $b = $v;
                break;
            case 5:
                $r = $v;
                $g = $p;
                $b = $q;
                break;
        }

        return [
            floor($r * 255),
            floor($g * 255),
            floor($b * 255)
        ];
    }
}

if (!function_exists('check_nav_active')) {
    /**
     * 检测会员中心导航是否高亮
     */
    function check_nav_active($url, $classname = 'active')
    {
        $auth = \app\common\library\Auth::instance();
        $requestUrl = $auth->getRequestUri();
        $url = ltrim($url, '/');
        return $requestUrl === str_replace(".", "/", $url) ? $classname : '';
    }
}

if (!function_exists('check_cors_request')) {
    /**
     * 跨域检测
     */
    function check_cors_request()
    {
        if (isset($_SERVER['HTTP_ORIGIN']) && $_SERVER['HTTP_ORIGIN']) {
            $info = parse_url($_SERVER['HTTP_ORIGIN']);
            $domainArr = explode(',', config('fastadmin.cors_request_domain'));
            $domainArr[] = request()->host(true);
            if (in_array("*", $domainArr) || in_array($_SERVER['HTTP_ORIGIN'], $domainArr) || (isset($info['host']) && in_array($info['host'], $domainArr))) {
                header("Access-Control-Allow-Origin: " . $_SERVER['HTTP_ORIGIN']);
            } else {
                $response = Response::create('跨域检测无效', 'html', 403);
                throw new HttpResponseException($response);
            }

            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');

            if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
                    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
                }
                if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
                    header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
                }
                $response = Response::create('', 'html');
                throw new HttpResponseException($response);
            }
        }
    }
}

if (!function_exists('xss_clean')) {
    /**
     * 清理XSS
     */
    function xss_clean($content, $is_image = false)
    {
        return \app\common\library\Security::instance()->xss_clean($content, $is_image);
    }
}

if (!function_exists('check_ip_allowed')) {
    /**
     * 检测IP是否允许
     * @param string $ip IP地址
     */
    function check_ip_allowed($ip = null)
    {
        $ip = is_null($ip) ? request()->ip() : $ip;
        $forbiddenipArr = config('site.forbiddenip');
        $forbiddenipArr = !$forbiddenipArr ? [] : $forbiddenipArr;
        $forbiddenipArr = is_array($forbiddenipArr) ? $forbiddenipArr : array_filter(explode("\n", str_replace("\r\n", "\n", $forbiddenipArr)));
        if ($forbiddenipArr && \Symfony\Component\HttpFoundation\IpUtils::checkIp($ip, $forbiddenipArr)) {
            $response = Response::create('请求无权访问', 'html', 403);
            throw new HttpResponseException($response);
        }
    }
}

if (!function_exists('build_suffix_image')) {
    /**
     * 生成文件后缀图片
     * @param string $suffix 后缀
     * @param null $background
     * @return string
     */
    function build_suffix_image($suffix, $background = null)
    {
        $suffix = mb_substr(strtoupper($suffix), 0, 4);
        $total = unpack('L', hash('adler32', $suffix, true))[1];
        $hue = $total % 360;
        list($r, $g, $b) = hsv2rgb($hue / 360, 0.3, 0.9);

        $background = $background ? $background : "rgb({$r},{$g},{$b})";

        $icon = <<<EOT
        <svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 512 512" style="enable-background:new 0 0 512 512;" xml:space="preserve">
            <path style="fill:#E2E5E7;" d="M128,0c-17.6,0-32,14.4-32,32v448c0,17.6,14.4,32,32,32h320c17.6,0,32-14.4,32-32V128L352,0H128z"/>
            <path style="fill:#B0B7BD;" d="M384,128h96L352,0v96C352,113.6,366.4,128,384,128z"/>
            <polygon style="fill:#CAD1D8;" points="480,224 384,128 480,128 "/>
            <path style="fill:{$background};" d="M416,416c0,8.8-7.2,16-16,16H48c-8.8,0-16-7.2-16-16V256c0-8.8,7.2-16,16-16h352c8.8,0,16,7.2,16,16 V416z"/>
            <path style="fill:#CAD1D8;" d="M400,432H96v16h304c8.8,0,16-7.2,16-16v-16C416,424.8,408.8,432,400,432z"/>
            <g><text><tspan x="220" y="380" font-size="124" font-family="Verdana, Helvetica, Arial, sans-serif" fill="white" text-anchor="middle">{$suffix}</tspan></text></g>
        </svg>
EOT;
        return $icon;
    }
}


if (!function_exists('array_callback')) {
    /**
     * 20190729 kevin
     * 规范数据返回函数
     * @param unknown $state
     * @param unknown $msg
     * @param unknown $data
     * @return multitype:unknown
     */
    function array_callback($state = true, $msg = '', $data = array())
    {
        return array('state' => $state, 'msg' => $msg, 'data' => $data);
    }
}

if (!function_exists('send_post')) {
//请求函数
    function send_post($url, $post_data = [], $method = 'POST')
    {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => $method, //or GET
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间(单位:s)
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }
}

if (!function_exists('corp_admin_id')) {
    /**
     * 获取企业所属admin_id
     */
    function corp_admin_id($corp_id = null)
    {
        $admin_id = 1;
        if (!empty($corp_id)) {
            $admin_id = \think\Db::name("corp")->where("id", $corp_id)->value("admin_id");
        }
        $admin_id = $admin_id > 0 ? $admin_id : 1;
        return $admin_id;
    }
}

if (!function_exists('group_id_exchange_admin_id')) {
    /**
     * 根据角色组获取某个管理员id
     */
    function group_id_exchange_admin_id($group_id = null)
    {
        $admin_id = 1;
        if (!empty($group_id)) {
            $admin_id = \think\Db::name("auth_group_access")->where("group_id", $group_id)->value("uid");
        }
        $admin_id = $admin_id > 0 ? $admin_id : 1;
        return $admin_id;
    }
}

if (!function_exists('get_groupinfo_by_admin_id')) {
    /**
     * 根据admin_id获取角色组信息
     */
    function get_groupinfo_by_admin_id($admin_id = null)
    {
        $group_info = [
            "id" => null,
            "name" => ""
        ];
        if (!empty($admin_id)) {
            $group_info = \think\Db::name("auth_group_access")->alias("a")
                ->join("auth_group g", "g.id=a.group_id")
                ->field("g.id,g.name")
                ->where("a.uid", $admin_id)->find();
        }
        return $group_info;

    }
}

if (!function_exists('verify_corp_admin_id')) {
    /**
     * 验证是否绑定过角色组(常规管理员)
     */
    function verify_corp_admin_id($corp_id = null)
    {
        $check = false;
        if (!empty($corp_id)) {
            $admin_id = \think\Db::name("corp")->where("id", $corp_id)->value("admin_id");
            if ($admin_id > 1) {
                //绑定过其他管理员
                $exsit = \think\Db::name("admin")->where("id", $admin_id)->find();
                if ($exsit) {
                    $check = true;
                }
            }
        }
        return $check;
    }
}

if (!function_exists('insert_openid_info')) {
    /**
     * 将授权用户信息保存起来
     */
    function insert_openid_info($data)
    {
        $data['upt_time'] = time();
        $res = \think\Db::name("openid_info")->where("openid", $data['openid'])->find();
//        file_put_contents("ccc.txt", date("Y-m-d H:i:s") . json_encode($data) . PHP_EOL, FILE_APPEND);
        if (!empty($res)) {
            \think\Db::name("openid_info")->where("openid", $data['openid'])->update($data);
        } else {
            \think\Db::name("openid_info")->insertGetId($data);
        }
        return true;
    }
}

if (!function_exists('http_request')) {
// curl请求
    function http_request($url, $timeout = 30, $header = array())
    {
        if (!function_exists('curl_init')) {
            throw new Exception('server not install curl');
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, true);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        if (!empty($header)) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        }
        $data = curl_exec($ch);
        list($header, $data) = explode("\r\n\r\n", $data);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_code == 301 || $http_code == 302) {
            $matches = array();
            preg_match('/Location:(.*?)\n/', $header, $matches);
            $url = trim(array_pop($matches));
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            $data = curl_exec($ch);
        }

        if ($data == false) {
            curl_close($ch);
        }
        @curl_close($ch);

        return $data;
    }
}
//加密解密函数
if (!function_exists('tyssl_decode')) {
    /**
     * 解密函数
     * @param string $secretdata
     * @return string
     */
    function tyssl_decode($secretdata)
    {
        $cryptkey = hash('sha256', 'e09dor37csce2', true);
        $password = "h78c4ea56z0sgw9e";
        return openssl_decrypt($secretdata, 'aes-256-cbc', $cryptkey, false, $password);
    }
}
if (!function_exists('tyssl_encode')) {
    /**
     * 加密函数
     * @param string $secretdata
     * @return string
     */
    function tyssl_encode($secretdata)
    {
        $cryptkey = hash('sha256', 'e09dor37csce2', true);
        $password = "h78c4ea56z0sgw9e";
        return openssl_encrypt($secretdata, 'aes-256-cbc', $cryptkey, false, $password);
    }
}

if (!function_exists('grid_level_pid_zero')) {
    /**
     * 无限级分类 获取顶级分类ID
     */
    function grid_level_pid_zero($id)
    {
        $arr = \think\Db::name("grid_level")->order("pid asc,id asc")->column("id,pid");
        while ($arr[$id]) {
            $id = $arr[$id];
        }
        return $id;
    }
}

if (!function_exists('uuid')) {
    function uuid($num = 32)
    {
        if ($num == 16) {
            return strtoupper(substr(md5(uniqid(mt_rand(), 1)), 10, 16));
        }
        if (function_exists('com_create_guid')) {
            return com_create_guid();
        } else {
            mt_srand(( double )microtime() * 10000); //optional for php 4.2.0 and up.随便数播种,4.2.0以后不需要了。
            $charid = strtoupper(md5(uniqid(rand(), true))); //根据当前时间(微秒计)生成唯一id.
            $uuid = substr($charid, 0, 8) . substr($charid, 8, 4) . substr($charid, 12, 4) . substr($charid, 16, 4) . substr($charid, 20, 12);
            return $uuid;
        }
    }
}

if (!function_exists('suiji_num')) {
    /**
     * 生成一个16位随机数(可以自定义前缀)
     */
    function suiji_num($before)
    {
        return $before . substr(uuid(16), 0, 16 - strlen($before));
    }
}

if (!function_exists('grid_level_has_child')) {
    /**
     * 查看当前网格层级是否还有子层级
     */
    function grid_level_has_child($grid_leve_id)
    {
        $count = \think\Db::name("grid_level")->where("pid", $grid_leve_id)->count();
        if ($count) {
            return true;
        }
        return false;
    }
}

if (!function_exists('grid_level_bottom_id')) {
    /**
     * 查看城市/农村的最底层分类id
     */
    function grid_level_bottom_id($id)
    {
        $sid = \think\Db::name("grid_level")->where("pid", $id)->order("weigh desc,id desc")->value("id");
        if (!empty($sid)) {
            $id = grid_level_bottom_id($sid);
        }
        return $id;
    }
}

if (!function_exists('grid_level_bottom_id_list')) {
    /**
     * 查看城市和农村的最底层id返回数组
     */
    function grid_level_bottom_id_list()
    {
        $arr = [];
        $c_id = grid_level_bottom_id(1);//1城市
        $n_id = grid_level_bottom_id(2);//2农村
        if ($c_id) {
            $arr[] = $c_id;
        }
        if ($n_id) {
            $arr[] = $n_id;
        }
        return $arr;
    }
}

if (!function_exists('grid_level_last_two_id_list')) {
    /**
     * 查看城市和农村的最底层id返回数组
     */
    function grid_level_last_two_id_list()
    {
        $arr = [];
        $c_id = grid_level_bottom_id(1);//1城市
        $n_id = grid_level_bottom_id(2);//2农村
        if ($c_id) {
            $arr[] = $c_id;
        }
        if ($n_id) {
            $arr[] = $n_id;
        }
        $arr2 = [];
        if (!empty($arr)) {
            foreach ($arr as $k => $v) {
                $arr2[] = $v;
                $pid = \think\Db::name("grid_level")->where("id", $v)->value("pid");
                if ($pid) {
                    $arr2[] = $pid;
                }
            }
        }
        return $arr2;
    }
}

if (!function_exists('get_groupchat_ids_by_grid_infomation_id')) {
    /**
     * 查询某个网格及其子网格的客户群ids的一维数组
     */
    function get_groupchat_ids_by_grid_infomation_id($grid_infomation_id)
    {
        $data = [];
        $where = [];
        if (!empty($grid_infomation_id)) {
            if ($grid_infomation_id == -1) {
                //返回全部客户群
            } else {
                //获取下级所有子网格ID
                $tree = \fast\Tree::instance();
                $gridInfomationModel = new \app\admin\model\GridInfomation();
                $tree->init(collection($gridInfomationModel->order('pid asc,id asc')->select())->toArray(), 'pid');
                $grid_ids = $tree->getChildrenIds($grid_infomation_id, true);
                if (!empty($grid_ids)) {
                    //查询网格点对应客户群ids
                    if (!empty($grid_ids)) {
                        $where["id"] = ["IN", $grid_ids];
                    }
                }
            }
            $gird_infomation_list = \think\Db::name("grid_infomation")->where($where)->field("corp_groupchat_ids,corp_user_ids")->select();
            if (!empty($gird_infomation_list)) {
                foreach ($gird_infomation_list as $k => $v) {
                    if (!empty($v['corp_groupchat_ids'])) {
                        $corp_groupchat_ids_arr = explode(",", $v['corp_groupchat_ids']);
                        $data = array_merge($data, $corp_groupchat_ids_arr);
                    }
                }
            }
        }
        if (!empty($data)) {
            //过滤掉相同客户群id
            $data = array_unique($data);
        }
        return $data;
    }
}
if (!function_exists('get_all_next_grid_infomation_ids')) {
    /***
     * 获得下级所有网格点id
     */
    function get_all_next_grid_infomation_ids($grid_infomation_id)
    {
        $grid_infomation = \think\Db::name("grid_infomation")->where("id", $grid_infomation_id)->find();
        if (!empty($grid_infomation)) {
            //获取下级所有子网格ID
            $tree = \fast\Tree::instance();
            $gridInfomationModel = new \app\admin\model\GridInfomation();
            $tree->init(collection($gridInfomationModel->order('pid asc,id asc')->select())->toArray(), 'pid');
            //$grid_ids包含网格所有等级的网格ids
            $grid_ids = $tree->getChildrenIds($grid_infomation_id, true);
            //获得网格点ids ,house_building_ids绑定了楼栋的
            $where['id'] = ['in', $grid_ids];
            $where['house_building_ids'] = ['>', '0'];
            $list = \think\Db::name("grid_infomation")
                ->where($where)
                ->column('id');
            return $list;
        }
    }
}
if (!function_exists('grid_infomation_relation')) {
    /**
     * 获取1.本网格、2.同级网格、3.本网格以及下级所有网格、4.同级网格以及下级所有网格 (多个用,隔开)
     */
    function grid_infomation_relation($grid_infomation_id, $type = 1)
    {
        // 新版本根据网格点找人(user_grid)  2022.05.27 kevin更新
        $ids = "";
        $where = [];
        if ($type == 1) {
            //本网格
            $where["a.id"] = ["=", $grid_infomation_id];
//            $where["a.corp_groupchat_ids"] = ["neq", ""];//客户群不能为空
            $id_arr = \think\Db::name("grid_infomation")
                ->alias("a")
                ->join("user_grid b", "a.id=b.grid_id")
                ->where($where)
                ->group("a.id")
                ->column("a.id");
            if (!empty($id_arr)) {
                $ids = implode($id_arr, ",");
            }
        } elseif ($type == 2) {
            //同级网格
            $grid_infomation = \think\Db::name("grid_infomation")->where("id", $grid_infomation_id)->find();
            if (!empty($grid_infomation)) {
                $where["a.pid"] = ["=", $grid_infomation['pid']];
                $where["a.corp_id"] = ["=", $grid_infomation['corp_id']];
                $where["a.grid_level_id"] = ["=", $grid_infomation['grid_level_id']];
//                $where["a.corp_groupchat_ids"] = ["neq", ""];//客户群不能为空
                $id_arr = \think\Db::name("grid_infomation")
                    ->alias("a")
                    ->join("user_grid b", "a.id=b.grid_id")
                    ->where($where)
                    ->group("a.id")
                    ->column("a.id");
                if (!empty($id_arr)) {
                    $ids = implode($id_arr, ",");
                }
            }
        } elseif ($type == 3) {
            //本网格以及下级所有网格
            $grid_infomation = \think\Db::name("grid_infomation")->where("id", $grid_infomation_id)->find();
            if (!empty($grid_infomation)) {
                //获取下级所有子网格ID
                $tree = \fast\Tree::instance();
                $gridInfomationModel = new \app\admin\model\GridInfomation();
                $tree->init(collection($gridInfomationModel->order('pid asc,id asc')->select())->toArray(), 'pid');
                $grid_ids = $tree->getChildrenIds($grid_infomation_id, true);
                if (!empty($grid_ids)) {
                    $where["a.id"] = ["in", $grid_ids];
//                    $where["a.corp_groupchat_ids"] = ["neq", ""];//客户群不能为空
                    $id_arr = \think\Db::name("grid_infomation")
                        ->alias("a")
                        ->join("user_grid b", "a.id=b.grid_id")
                        ->where($where)
                        ->group("a.id")
                        ->column("a.id");
                    if (!empty($id_arr)) {
                        $ids = implode($id_arr, ",");
                    }
                }
            }
        } elseif ($type == 4) {
            //同级网格以及下级所有网格
            $grid_infomation = \think\Db::name("grid_infomation")->where("id", $grid_infomation_id)->find();
            if (!empty($grid_infomation)) {
                //第一步:先找到同级网格id
                $where["pid"] = ["=", $grid_infomation['pid']];
                $where["corp_id"] = ["=", $grid_infomation['corp_id']];
                $where["grid_level_id"] = ["=", $grid_infomation['grid_level_id']];
                $id_arr = \think\Db::name("grid_infomation")->where($where)->column("id");
                if (!empty($id_arr)) {
                    $tree = \fast\Tree::instance();
                    $gridInfomationModel = new \app\admin\model\GridInfomation();
                    $tree->init(collection($gridInfomationModel->order('pid asc,id asc')->select())->toArray(), 'pid');
                    $grid_ids_arr = [];
                    foreach ($id_arr as $k => $v) {
                        $grid_ids = $tree->getChildrenIds($v, true);
                        $grid_ids_arr = array_merge($grid_ids_arr, $grid_ids);
                        $grid_ids_arr = array_unique($grid_ids_arr);
                    }
                    if (!empty($grid_ids_arr)) {
                        $where2 = [];
                        $where2["a.id"] = ["in", $grid_ids_arr];
//                        $where2["corp_groupchat_ids"] = ["neq", ""];//客户群不能为空
                        $id_arr = \think\Db::name("grid_infomation")
                            ->alias("a")
                            ->join("user_grid b", "a.id=b.grid_id")
                            ->where($where2)
                            ->group("a.id")
                            ->column("a.id");
                        if (!empty($id_arr)) {
                            $ids = implode($id_arr, ",");
                        }
                    }
                }
            }
        }
        return $ids;

        // // 老版本根据客户群找人
//        $ids = "";
//        $where = [];
//        if ($type == 1) {
//            //本网格
//            $where["id"] = ["=", $grid_infomation_id];
//            $where["corp_groupchat_ids"] = ["neq", ""];//客户群不能为空
//            $id_arr = \think\Db::name("grid_infomation")->where($where)->column("id");
//            if (!empty($id_arr)) {
//                $ids = implode($id_arr, ",");
//            }
//        } elseif ($type == 2) {
//            //同级网格
//            $grid_infomation = \think\Db::name("grid_infomation")->where("id", $grid_infomation_id)->find();
//            if (!empty($grid_infomation)) {
//                $where["pid"] = ["=", $grid_infomation['pid']];
//                $where["corp_id"] = ["=", $grid_infomation['corp_id']];
//                $where["grid_level_id"] = ["=", $grid_infomation['grid_level_id']];
//                $where["corp_groupchat_ids"] = ["neq", ""];//客户群不能为空
//                $id_arr = \think\Db::name("grid_infomation")->where($where)->column("id");
//                if (!empty($id_arr)) {
//                    $ids = implode($id_arr, ",");
//                }
//            }
//        } elseif ($type == 3) {
//            //本网格以及下级所有网格
//            $grid_infomation = \think\Db::name("grid_infomation")->where("id", $grid_infomation_id)->find();
//            if (!empty($grid_infomation)) {
//                //获取下级所有子网格ID
//                $tree = \fast\Tree::instance();
//                $gridInfomationModel = new \app\admin\model\GridInfomation();
//                $tree->init(collection($gridInfomationModel->order('pid asc,id asc')->select())->toArray(), 'pid');
//                $grid_ids = $tree->getChildrenIds($grid_infomation_id, true);
//                if (!empty($grid_ids)) {
//                    $where["id"] = ["in", $grid_ids];
//                    $where["corp_groupchat_ids"] = ["neq", ""];//客户群不能为空
//                    $id_arr = \think\Db::name("grid_infomation")->where($where)->column("id");
//                    if (!empty($id_arr)) {
//                        $ids = implode($id_arr, ",");
//                    }
//                }
//            }
//        } elseif ($type == 4) {
//            //同级网格以及下级所有网格
//            $grid_infomation = \think\Db::name("grid_infomation")->where("id", $grid_infomation_id)->find();
//            if (!empty($grid_infomation)) {
//                //第一步:先找到同级网格id
//                $where["pid"] = ["=", $grid_infomation['pid']];
//                $where["corp_id"] = ["=", $grid_infomation['corp_id']];
//                $where["grid_level_id"] = ["=", $grid_infomation['grid_level_id']];
//                $id_arr = \think\Db::name("grid_infomation")->where($where)->column("id");
//                if (!empty($id_arr)) {
//                    $tree = \fast\Tree::instance();
//                    $gridInfomationModel = new \app\admin\model\GridInfomation();
//                    $tree->init(collection($gridInfomationModel->order('pid asc,id asc')->select())->toArray(), 'pid');
//                    $grid_ids_arr = [];
//                    foreach ($id_arr as $k => $v) {
//                        $grid_ids = $tree->getChildrenIds($v, true);
//                        $grid_ids_arr = array_merge($grid_ids_arr, $grid_ids);
//                        $grid_ids_arr = array_unique($grid_ids_arr);
//                    }
//                    if (!empty($grid_ids_arr)) {
//                        $where2 = [];
//                        $where2["id"] = ["in", $grid_ids_arr];
//                        $where2["corp_groupchat_ids"] = ["neq", ""];//客户群不能为空
//                        $id_arr = \think\Db::name("grid_infomation")->where($where2)->column("id");
//                        if (!empty($id_arr)) {
//                            $ids = implode($id_arr, ",");
//                        }
//                    }
//                }
//            }
//        }
//        return $ids;
    }
}
if (!function_exists('user_day_count')) {
    /***
     * 根据网格id更新当日网格中群众总数
     * type =1 添加人员 type=2 删除人员
     */
    function user_day_count($grid_id, $type = 1)
    {
        $nowday = date('Ymd', time());
        //网格点信息
        $info = \think\Db::name('grid_infomation')
            ->where(['id' => $grid_id])
            ->find();
        //判断今日数据是否存在
        $kcs = \think\Db::name('user_user_ctall')
            ->where(['nowday' => $nowday, 'grid_id' => $grid_id])
            ->find();
        if ($type == 1) {
            //添加人员
            if (empty($kcs)) {
                //保存数据
                $gduall['admin_id'] = corp_admin_id($info['corp_id']);
                $gduall['grid_id'] = $grid_id;
                $gduall['nowday'] = $nowday;
                $gduall['nums'] = 1;
                $gduall['createtime'] = time();
                $rs = \think\Db::name('user_user_ctall')->insertGetId($gduall);
            } else {
                //更新总数
                $gdupd['nums'] = $kcs['nums'] + 1;
                $gdupd['updatetime'] = time();
                $rs = \think\Db::name('user_user_ctall')
                    ->where(['grid_id' => $grid_id, 'nowday' => $nowday])
                    ->update($gdupd);
            }
        }
        if ($type == 2 && !empty($kcs)) {
            //删除人员更新数据
            //更新总数
            $userAll = $kcs['nums'] - 1;
            $gdupd['nums'] = $userAll > 0 ? $userAll : 0;
            $gdupd['updatetime'] = time();
            $rs = \think\Db::name('user_user_ctall')
                ->where(['grid_id' => $grid_id, 'nowday' => $nowday])
                ->update($gdupd);
        }
    }
}
if (!function_exists('sub_str')) {
    /**
     * 字符串截取
     *
     */
    function sub_str($str, $length = 0, $append = true)
    {
        $str = trim($str);
        $strlength = strlen($str);

        if ($length == 0 || $length >= $strlength) {
            return $str;  //截取长度等于0或大于等于本字符串的长度,返回字符串本身
        } elseif ($length < 0)  //如果截取长度为负数
        {
            $length = $strlength + $length;//那么截取长度就等于字符串长度减去截取长度
            if ($length < 0) {
                $length = $strlength;//如果截取长度的绝对值大于字符串本身长度,则截取长度取字符串本身的长度
            }
        }

        if (function_exists('mb_substr')) {
            $newstr = mb_substr($str, 0, $length, "utf-8");
        } elseif (function_exists('iconv_substr')) {
            $newstr = iconv_substr($str, 0, $length, "utf-8");
        } else {
            //$newstr = trim_right(substr($str, 0, $length));
            $newstr = substr($str, 0, $length);
        }

        if ($append && $str != $newstr) {
            $newstr .= '...';
        }

        return $newstr;
    }
}

if (!function_exists('beingPushed')) {
    /**
     * 小程序模板推送选择类型
     * @param $type @模板类型
     * @param $openid @接收人ID
     * @param $page @跳转页面
     * @param $temp @具体提醒参数
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    function beingPushed($type, $openid, $page, $temp)
    {
        $data = [];
        $data['touser'] = $openid;
        //$data['page'] = $page;
        //模板内容,格式形如 { "key1": { "value": any }, "key2": { "value": any } }
        //预约结果通知
        $data['template_id'] = "XKfTFd23w3dzzoRHPQajIq8MxQ2usw6n9W4FuDBZvh4";
        $data['data'] = [
            "first" => [
                'value' => $temp['value1'],//消费代金券
            ],
            "keyword1" => [
                'value' =>$temp['value2'],//券状态
            ],
            "keyword2" => [
                'value' => $temp['value3'],//有效期
            ],
            "keyword3" => [
                'value' => $temp['value4'],//优惠券号

            ],
            "keyword4" => [
                'value' => $temp['value4'],//优惠券号

            ],
            "keyword5" => [
                'value' => $temp['value5'],//优惠券号

            ]
        ];

        return sendSubscribeMessage($data);
    }
}

if (!function_exists('sendSubscribeMessage')) {
    /**
     * 小程序订阅消息推送
     * @param $data
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    function sendSubscribeMessage($data)
    {
        //access_token
        $access_token = getAccessToken();

        //请求url
        $url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;//模板消息请求URL

        //file_put_contents('notify.txt',$data.PHP_EOL,FILE_APPEND);
        //跳转小程序类型:developer为开发版;trial为体验版;formal为正式版;默认为正式版
        //$data['miniprogram_state'] = 'formal';

        return curlPost($url, json_encode($data));
    }
}

if (!function_exists('getAccessToken')) {
    /**
     * 获取access_token
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    function getAccessToken()
    {
        $wx_xcx_token = \think\Db::name("wechat_token")->where("type", "wx_xcx")->find();
        if (empty($wx_xcx_token) || empty($wx_xcx_token['access_token']) || $wx_xcx_token['over_time'] <= time()) {
            //微信小程序失效
            //当前时间戳
            $now_time = strtotime(date('Y-m-d H:i:s', time()));

            //获取新的access_token
            $appid = "wx1c3cc5b4e2006be2";
            $secret = "643f1b6fdba08a773a7761a1a194a1ad";
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret;
            $res = json_decode(file_get_contents($url), true);

            $access_token = $res['access_token'];
            if (!empty($access_token)) {
                $time = time();
                $update_data = [
                    "access_token" => $access_token,
                    "over_time" => $time + 3600,
                    "type" => "wx_xcx",
                    "updatetime" => $time
                ];
                if (!empty($wx_xcx_token)) {
                    //更新
                    \think\Db::name("wechat_token")->where("id", $wx_xcx_token['id'])->update($update_data);
                } else {
                    //新增
                    \think\Db::name("wechat_token")->insertGetId($update_data);
                }
            }
        } else {
            $access_token = $wx_xcx_token['access_token'];
        }
        return $access_token;
    }
}

if (!function_exists('curlPost')) {
    /**
     * 发送post请求
     */
    function curlPost($url, $data)
    {
        $ch = curl_init();
        $params[CURLOPT_URL] = $url;    //请求url地址
        $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
        $params[CURLOPT_SSL_VERIFYPEER] = false;
        $params[CURLOPT_SSL_VERIFYHOST] = false;
        $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
        $params[CURLOPT_POST] = true;
        $params[CURLOPT_POSTFIELDS] = $data;
        curl_setopt_array($ch, $params); //传入curl参数
        $content = curl_exec($ch); //执行
//    file_put_contents('notify.txt', $content . date('Y-m-d H:i:s', time()) . PHP_EOL, FILE_APPEND);
        curl_close($ch); //关闭连接
        return $content;
    }
}

if (!function_exists('get_groupchat_member_list_by_groupchat_ids')) {
    /**
     * 根据客户群id找到外部联系人群成员unionid一维数组
     */
    function get_groupchat_member_list_by_groupchat_ids($ids)
    {
        $return_data = [];
        if (!empty($ids)) {
            $where = [];
            $where["g.id"] = ["in", $ids];
            $where["m.type"] = ["=", "2"];//成员类型 1企业成员 2外部联系人
            $where['m.unionid'] = ["neq", ""];//unionid不能为空

            $return_data = \think\Db::name("corp_groupchat")->alias("g")
                ->join("corp_groupchat_member m", "m.corp_groupchat_id=g.id")
                ->where($where)
                ->group("m.unionid")
                ->column("unionid");
        }

        return $return_data;
    }
}

if (!function_exists('has_bind_grid_infomation_user_ids')) {
    /**
     * 查询哪些人员已经绑定过网格点了
     */
    function has_bind_grid_infomation_user_ids()
    {
        $return_data = [];

        //网格管理员
        $where = [];
        $where["corp_user_mng_ids"] = ["neq", ""];
        $user_mng_ids = \think\Db::name("grid_infomation")->where($where)->where("corp_user_mng_ids", 'not null')->group("corp_user_mng_ids")->column("corp_user_mng_ids");
        if (!empty($user_mng_ids)) {
            foreach ($user_mng_ids as $k => $v) {
                //由于网格点可能有多个网格管理员,这里需要implode,然后去重后返回
                if (!empty($v)) {
                    $id_arr = explode(",", $v);
                    $return_data = array_merge($return_data, $id_arr);
                }
            }
            if (!empty($return_data)) {
                $return_data = array_unique($return_data);
            }
        }

        //网格长
        $where2 = [];
        $where2["corp_user_ids"] = ["neq", ""];
        $user_ids = \think\Db::name("grid_infomation")->where($where2)->where("corp_user_ids", 'not null')->group("corp_user_ids")->column("corp_user_ids");

        $return_data = array_merge($return_data, $user_ids);

        $return_data = array_unique($return_data);


//        $where = [];
//        $where["corp_user_ids"] = ["neq", ""];
//        $user_ids = \think\Db::name("grid_infomation")->where($where)->where("corp_user_ids", 'not null')->group("corp_user_ids")->column("corp_user_ids");
//        if (!empty($user_ids)) {
//            foreach ($user_ids as $k => $v) {
//                //由于网格点可能有多个网格管理员,这里需要implode,然后去重后返回
//                if (!empty($v)) {
//                    $id_arr = explode(",", $v);
//                    $return_data = array_merge($return_data, $id_arr);
//                }
//            }
//            if (!empty($return_data)) {
//                $return_data = array_unique($return_data);
//            }
//        }
        return $return_data;
    }
}

if (!function_exists('has_bind_grid_infomation_groupchat_ids')) {
    /**
     * 查询哪些客户群已经绑定过网格点了
     */
    function has_bind_grid_infomation_groupchat_ids()
    {
        $return_data = [];

        //楼栋
        $where = [];
        $where["corp_groupchat_ids"] = ["neq", ""];
        $corp_groupchat_ids = \think\Db::name("grid_infomation")->where($where)->where("corp_groupchat_ids", 'not null')->group("corp_groupchat_ids")->column("corp_groupchat_ids");
        if (!empty($corp_groupchat_ids)) {
            foreach ($corp_groupchat_ids as $k => $v) {
                //由于网格点可能有多个客户群,这里需要implode,然后去重后返回
                if (!empty($v)) {
                    $id_arr = explode(",", $v);
                    $return_data = array_merge($return_data, $id_arr);
                }
            }
            if (!empty($return_data)) {
                $return_data = array_unique($return_data);
            }
        }
        return $return_data;
    }
}

if (!function_exists('has_bind_grid_infomation_building_ids')) {
    /**
     * 查询哪些楼栋已经绑定过网格点了
     */
    function has_bind_grid_infomation_building_ids()
    {
        $return_data = [];

        //楼栋
        $where = [];
        $where["house_building_ids"] = ["neq", ""];
        $house_building_ids = \think\Db::name("grid_infomation")->where($where)->where("house_building_ids", 'not null')->group("house_building_ids")->column("house_building_ids");
        if (!empty($house_building_ids)) {
            foreach ($house_building_ids as $k => $v) {
                //由于网格点可能有多个楼栋,这里需要implode,然后去重后返回
                if (!empty($v)) {
                    $id_arr = explode(",", $v);
                    $return_data = array_merge($return_data, $id_arr);
                }
            }
            if (!empty($return_data)) {
                $return_data = array_unique($return_data);
            }
        }
        return $return_data;
    }
}

if (!function_exists('getLatelyTime')) {
    /**
     * 获取最近一周,一个月,一年
     * */
    function getLatelyTime($type = '')
    {
        $now = time();
        $result = [];

        if ($type == 'week5') {
            //最近一周
            for ($i = 0; $i < 5; $i++) {
                $result[] = date('Y-m-d ', strtotime('-' . $i . ' day', $now));
            }
        } elseif ($type == 'week') {
            //最近一周
            for ($i = 0; $i < 7; $i++) {
                $result[] = date('Ymd', strtotime('-' . $i . ' day', $now));
            }
        } elseif ($type == 'month') {
            //最近一个月
            for ($i = 0; $i < 30; $i++) {
                $result[] = date('Y-m-d', strtotime('-' . $i . ' day', $now));
            }
        } elseif ($type == 'year') {
            //最近一年
            for ($i = 0; $i < 12; $i++) {
                $result[] = date('Y-m', strtotime('-' . $i . ' month', $now));
            }
        }
        return $result;
    }
}

if (!function_exists('grid_name_relation_by_id')) {
    /**
     * 根据某个网格点id返回所有上级的id(不含本身)
     */
    function grid_name_relation_by_id($id, $arr = [])
    {

        $pid = \think\Db::name("grid_infomation")->where("id", $id)->value("pid");
        if ($pid > 0) {
            $arr = array_merge($arr, [$pid]);
        }
        return $pid > 0 ? grid_name_relation_by_id($pid, $arr) : $arr;
    }
}

if (!function_exists('grid_name_relation_names')) {
    /**
     * 根据某个网格点id返回所有上级的名称 用"$str"拼接(不含本身)
     */
    function grid_name_relation_names($id, $str = "/")
    {
        $pid_arr = grid_name_relation_by_id($id);
        $grid_name_str = "";
        $pid_arr = array_reverse($pid_arr);//数组倒序
        if (!empty($pid_arr)) {
            $w1 = [];
            $w1["id"] = ["IN", $pid_arr];
            $grid_name_arr = \think\Db::name("grid_infomation")->where($w1)->order("grid_level_id asc")->column("name");
            $grid_name_str = implode($grid_name_arr, $str);
        }
        return $grid_name_str;

    }
}

if (!function_exists('building_relation_names')) {
    /**
     * 根据某个楼栋id返回所有上级的名称 用"$str"拼接(不含本身)
     */
    function building_relation_names($id, $str = "/")
    {
        $grid_name_str = "";
        $house_building = \think\Db::name("house_building")->where("id", $id)->find();
        $house_community = \think\Db::name("house_community")->where("id", $house_building['house_community_id'])->find();
        $grid_name_str = $house_community['community_name'] . $str . $house_building['building_name'];
        return $grid_name_str;

    }
}

if (!function_exists('create_unit_to_chinese')) {
    /**
     * 批量创建单元转换中文拼接
     * $start_num 起始单元
     * $end_num 结束单元
     */
    function create_unit_to_chinese($start_num, $end_num)
    {
        $arr = [];
        for ($i = $start_num; $i <= $end_num; $i++) {
            $arr[] = $i . "单元";
        }
        return $arr;
    }

}

if (!function_exists('create_floor_to_chinese')) {
    /**
     * 批量创建楼层转换中文拼接
     * $start_num 起始楼层号
     * $end_num 结束楼层号
     */
    function create_floor_to_chinese($start_num, $end_num)
    {
        $arr = [];
        for ($i = $start_num; $i <= $end_num; $i++) {
            $arr[] = $i;
        }
        return $arr;
    }

}

if (!function_exists('create_room_to_chinese')) {
    /**
     * 批量创建房号转换中文拼接
     * $start_num 起始房号
     * $end_num 结束房号
     */
    function create_room_to_chinese($start_num, $end_num)
    {
        $arr = [];
        for ($i = $start_num; $i <= $end_num; $i++) {
            $arr[] = str_pad($i, 2, "0", STR_PAD_LEFT);//两位数 左边补0
        }
        return $arr;
    }

}

if (!function_exists('show_online_message_by_grid_id_arr')) {
    /**
     * 根据可查看的网格点数组去找进行中的敲门通知ids 一维数组
     * $grid_ids 网格id一维数组
     */
    function show_online_message_by_grid_id_arr($grid_ids)
    {
        $arr = [];
        if (!empty($grid_ids)) {
            $now_date = date("Y-m-d");
            foreach ($grid_ids as $k => $v) {
                $wh = [];
                $wh["type"] = ["=", 3];//只显示网上敲门的数据
                $wh["status"] = ["=", "1"];
                $list = \think\Db::name("message")
                    ->where($wh)
                    ->where('FIND_IN_SET(:id,grid_infomation_ids)', ['id' => $v])
                    ->field("id,start_time,end_time")
                    ->group("id")
                    ->select();
                if (!empty($list)) {
                    foreach ($list as $lk => $lv) {
                        if (!empty($lv['start_time'])) {
                            if (strtotime($lv['start_time']) > strtotime($now_date)) {
                                unset($list[$lk]);
                                continue;//跳出本层循环
                            }
                        }
                        if (!empty($lv['end_time'])) {
                            if (strtotime($lv['end_time']) < strtotime($now_date)) {
                                unset($list[$lk]);
                                continue;//跳出本层循环
                            }
                        }

                    }
                    $ids_arr = array_column($list, "id");
                    $arr = array_merge($arr, $ids_arr);
                }

            }
        }
        $arr = array_unique($arr);

        return $arr;
    }
}

if (!function_exists('show_outdate_online_message_by_grid_id_arr')) {
    /**
     * 根据可查看的网格点数组去找已过期的敲门通知ids 一维数组
     * $grid_ids 网格id一维数组
     */
    function show_outdate_online_message_by_grid_id_arr($grid_ids)
    {
        $arr = [];
        if (!empty($grid_ids)) {
            $now_date = date("Y-m-d");
            foreach ($grid_ids as $k => $v) {
                $wh = [];
                $wh["type"] = ["=", 3];//只显示网上敲门的数据
                $wh["status"] = ["=", "1"];
                $list = \think\Db::name("message")
                    ->where($wh)
                    ->where('FIND_IN_SET(:id,grid_infomation_ids)', ['id' => $v])
                    ->field("id,start_time,end_time")
                    ->group("id")
                    ->select();
                if (!empty($list)) {
                    foreach ($list as $lk => $lv) {
                        if (!empty($lv['end_time'])) {
                            if (strtotime($lv['end_time']) < strtotime($now_date)) {
                                $arr = array_merge($arr, [$lv['id']]);
                            }
                        }
                    }
                }

            }
        }
        $arr = array_unique($arr);
        return $arr;
    }
}

if (!function_exists('judge_bind_wx_xcx')) {
    /**
     * 判断是否绑定了小程序
     * true已绑定 false未绑定
     */
    function judge_bind_wx_xcx($unionid)
    {
        $flag = 0;
        if (!empty($unionid)) {
            //若授权小程序过小程序那么wx_xcx_openid肯定是有值的
            $wx_xcx_openid = Db::name("user")->where("unionid", $unionid)->value("wx_xcx_openid");
            if (!empty($wx_xcx_openid)) {
                $flag = 1;
            }
        }
        return $flag;
    }
}

if (!function_exists('judge_bind_wgz_relation')) {
    /**
     * 判断是否与网格的网格长加了好友的
     * true已加好友 false未加好友
     */
    function judge_bind_wgz_relation($unionid, $grid_id)
    {
        $flag = 0;
        if (!empty($unionid) && !empty($grid_id)) {
            $grid_infomation = Db::name("grid_infomation")->where("id", $grid_id)->find();
            if (!empty($grid_infomation['corp_user_ids'])) {
                //网格长信息
                $corp_user = Db::name("corp_user")->where("id", $grid_infomation['corp_user_ids'])->field("corp_id,userid")->find();
                //找到外部联系人的userid
                $userid = Db::name("corp_groupchat_member")->where("unionid", $unionid)->value("userid");
                if (!empty($userid)) {
                    //先查询外部联系人详细信息【follow_user中包含已加的内部成员列表】
                    $externalcontact_Api = new \app\api\controller\wework\Externalcontact();
                    $rr = $externalcontact_Api->externalcontactInfo($corp_user['corp_id'], $userid, "");
                    //判断下网格长的userid是否在客户的资料详情的客户好友中
                    if ($rr['state'] == true) {
                        $follow_user = $rr['data']['follow_user'];
                        if (!empty($follow_user)) {
                            //找到了外部联系人加过的企业内部员工列表
                            $userid_arr = array_column($follow_user, "userid");
                            if (in_array($corp_user['userid'], $userid_arr)) {
                                $flag = 1;
                            }
                        }
                    }
                }
            }
        }
        return $flag;
    }
}

if (!function_exists('judge_bind_groupchat_relation')) {
    /**
     * 判断是否加入过网格的客户群
     * true已加客户群 false未加客户群
     */
    function judge_bind_groupchat_relation($unionid, $grid_id)
    {
        $flag = 0;
        if (!empty($unionid) && !empty($grid_id)) {
            $grid_infomation = Db::name("grid_infomation")->where("id", $grid_id)->find();
            //客户群id
            if (!empty($grid_infomation['corp_groupchat_ids'])) {
                $w = [];
                $w["corp_groupchat_id"] = ["in", $grid_infomation['corp_groupchat_ids']];
                $w['type'] = ["=", "2"];//外部联系人
                $w['unionid'] = ["=", $unionid];
                $count = Db::name("corp_groupchat_member")->where($w)->count();
                if ($count > 0) {
                    $flag = 1;
                }
            }
        }
        return $flag;
    }
}

if (!function_exists('user_id_get_admin_id')) {
    /**
     * 根据用户id获取归属admin_id
     */
    function user_id_get_admin_id($id)
    {
        $admin_id = 1;
        if (!empty($id)) {
            $ad_id = Db::name("user")->alias("a")
                ->join("user_grid b", "a.unionid=b.unionid")
                ->where("a.id", $id)
                ->value("b.admin_id");
            if (!empty($ad_id)) {
                $admin_id = $ad_id;
            }
        }
        return $admin_id;
    }
}

if (!function_exists('str_add_xing')) {
    /**
     * 字符串中间加“*”号
     * @param $str
     * @return string
     */
    function str_add_xing($str)
    {
        //判断是否包含中文字符
        if (preg_match("/[\x{4e00}-\x{9fa5}]+/u", $str)) {
            //按照中文字符计算长度
            $len = mb_strlen($str, 'UTF-8');
            //echo '中文';
            if ($len >= 3) {
                //三个字符或三个字符以上掐头取尾,中间用*代替
                $str = mb_substr($str, 0, 1, 'UTF-8') . '*' . mb_substr($str, -1, 1, 'UTF-8');
            } elseif ($len == 2) {
                //两个字符
                $str = mb_substr($str, 0, 1, 'UTF-8') . '*';
            }
        } else {
            //按照英文字串计算长度
            $len = strlen($str);
            //echo 'English';
            if ($len >= 3) {
                //三个字符或三个字符以上掐头取尾,中间用*代替
                $str = substr($str, 0, 1) . '*' . substr($str, -1);
            } elseif ($len == 2) {
                //两个字符
                $str = substr($str, 0, 1) . '*';
            }
        }
        return $str;
    }

}

if (!function_exists('mobile_hide')) {
    /**
     * 手机号中间星号代替
     */
    function mobile_hide($mobile)
    {
        if (strlen($mobile) == 11) {
            $mobile = substr_replace($mobile, "****", 3, 4);
        }
        return $mobile;
    }
}

if (!function_exists('idcard_hide')) {
    /**
     * 身份证中间星号代替
     */
    function idcard_hide($idcard)
    {
        if (strlen($idcard) == 15) {
            $idcard = substr_replace($idcard, "****", 8, 4);
        } elseif (strlen($idcard) == 18) {
            $idcard = substr_replace($idcard, "********", 6, 8);
        }
        return $idcard;
    }
}

if (!function_exists('get_root_url')) {
    /**
     * 获取网站的根Url
     * @return string
     */
    function get_root_url()
    {
        $request = request();
        $base = $request->root();
        $root = strpos($base, '.') ? ltrim(dirname($base), DS) : $base;
        if ('' != $root) {
            $root = '/' . ltrim($root, '/');
        }

        return ($request->isSsl() ? 'https' : 'http') . '://' . $request->host() . "{$root}";
    }
}

if (!function_exists('del_place_qrcode')) {
    /**
     * 删除场所二维码文件(地址存在的是带域名的全路径 )
     * @param  [type] $pic [description]
     * @return [type]      [description]
     */
    function del_place_qrcode($pic)
    {
        $pic_path_arr = parse_url($pic);//parse_url函数将URL转换为关联数组
        $real_pic_path = $pic_path_arr['path'];
        $path = __FILE__;
        $paths = substr($path, 0, strpos($path, 'application'));
        $pic1 = $paths . "public" . $real_pic_path;

        if (file_exists($pic1)) {

            @unlink($pic1);

            return true;
        }
        return false;
    }
}


if (!function_exists('is_idcard')) {
    /**
     * 验证身份证
     * @param $id
     * @return bool
     * 公民身份证号码按照 GB11643—1999《公民身份证号码》国家标准编制,由18位数字组成。18位数字按照一定规则进行编写的:
     * 前1-6位:行政区划代码,即归属地
     * 第7-14位:出生年月日
     * 第15-17位:顺序码,表示在同一地址码所标识的区域范围内,对同年、同月、同日出生的人编定的顺序号
     * 第17位:顺序码之一,代表性别,奇数表示男性,偶数表示女性
     * 第18位:校验码,用于校验身份证号码是否合法。校检码可以是0~9的数字,有时也用x表示。
     * 例如: ·510525197902217660
     * 510525 四川省 泸州市 古蔺县
     * 19790221 1979年02月21日出生
     * 76 顺序码
     * 6 顺序码,男
     * 0 验证码
     */
    function is_idcard($id)
    {
        $id = strtoupper($id);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
        $arr_split = array();
        if (!preg_match($regx, $id)) {
            return false;
        }
        if (15 == strlen($id)) //检查15位
        {
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

            @preg_match($regx, $id, $arr_split);
            //检查生日日期是否正确
            $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
            if (!strtotime($dtm_birth)) {
                return false;
            } else {
                return true;
            }
        } else      //检查18位
        {
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);
            $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
            if (!strtotime($dtm_birth)) //检查生日日期是否正确
            {
                return false;
            } else {
                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成,X可以认为是数字10。
                $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
                $arr_ch = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
                $sign = 0;
                for ($i = 0; $i < 17; $i++) {
                    $b = (int)$id{$i};
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];
                if ($val_num != substr($id, 17, 1)) {
                    return false;
                } else {
                    return true;
                }
            }
        }

    }
}

if (!function_exists('area_code_get_groupid_and_adminid')) {
    /**
     * 根据行政区域编码获取角色组和管理员id
     */
    function area_code_get_groupid_and_adminid($area_code = null)
    {
        $group_id = 1;
        $admin_id = 1;
        if (!empty($area_code)) {
            $group_id = Db::name("auth_group")->where("mng_area_code", $area_code)->value("id");
            if ($group_id > 0) {
                $admin_id = Db::name("auth_group_access")->where("group_id", $group_id)->value("uid");
            }
        }

        $group_id = $group_id > 0 ? $group_id : 1;
        $admin_id = $admin_id > 0 ? $admin_id : 1;

        return ["group_id" => $group_id, "admin_id" => $admin_id];
    }
}

if (!function_exists('full_image')) {
    /**
     * 获取图片全地址
     */
    function full_image($img)
    {

        //七牛云插件(标识:qiniu)
        $qiniu_config = get_addon_config("qiniu");

        if (!empty($img)) {
            //判断是不是数组
            if (is_array($img)) {
                foreach ($img as $k => $v) {
                    if (!empty($v)) {
                        if ('http' != substr($v, 0, 4)) {
                            $img[$k] = $qiniu_config['cdnurl'] . $v;
                        }
                    }
                }
            } else {
                //判断是不是http开头的(若是就是就代表是本地上传。不是就是七牛上传的=>"/uploads")
                if ('http' != substr($img, 0, 4)) {
                    $img = $qiniu_config['cdnurl'] . $img;
                }
            }
        }
        return $img;
    }
}

if (!function_exists('get_tree_list')) {
    /**
     * 父子级树状结构 传入的参数为二维数组 parent是父级id
     */
    function get_tree_list($list)
    {
        //将每条数据中的id值作为其下标
        $temp = [];
        foreach ($list as $v) {
            $v['children'] = [];
            $temp[$v['id']] = $v;
        }
        //获取分类树
        foreach ($temp as $k => $v) {
            $temp[$v['parent']]['children'][] = &$temp[$v['id']];
        }
        return isset($temp[0]['children']) ? $temp[0]['children'] : [];
    }
}

if (!function_exists('monthlater')) {
    /**
     * @return array获取近12个月(月份从远到近)
     */
    function monthlater()
    {
        $str = array();
        for ($i = 0; $i <= 11; $i++) {
            $str[] = date("Y-m", strtotime(date('Y-m-01') . " -$i months"));
        }
        return array_reverse($str);
    }
}

if (!function_exists('apply_bind_admin_id')) {
    /**
     * 绑定管理员信息
     */
    function apply_bind_admin_id($cun_code)
    {
        $admin_id = 4;
        if ($cun_code) {
            $admin_id = Db::name("hc_area_code")->where("code", $cun_code)->value("admin_id");
        }
        return $admin_id;
    }
}

if (!function_exists('area_code_relation_names')) {
    /**
     * 根据某个区域code返回所有上级的名称 用"$str"拼接(不含本身)
     */
    function area_code_relation_names($code, $str = "/")
    {
        $pid_arr = area_name_relation_by_id($code);
        $grid_name_str = "";
        $pid_arr = array_reverse($pid_arr);//数组倒序
        if (!empty($pid_arr)) {
            $w1 = [];
            $w1["code"] = ["IN", $pid_arr];
            $grid_name_arr = Db::name("hc_area_code")->where($w1)->order("level asc")->column("name");
            $grid_name_str = implode($grid_name_arr, $str);
        }
        return $grid_name_str;

    }
}

if (!function_exists('area_name_relation_by_id')) {
    /**
     * 根据某个区域code返回所有上级的id(不含本身)
     */
    function area_name_relation_by_id($code, $arr = [])
    {

        $pcode = Db::name("hc_area_code")->where("code", $code)->value("pcode");
        if ($pcode > 0) {
            $arr = array_merge($arr, [$pcode]);
        }
        return $pcode > 0 ? area_name_relation_by_id($pcode, $arr) : $arr;
    }
}

if (!function_exists('get_child_ids')) {
    /**
     * @Description: 获取当前分类下所有子类ID(包含自己)
     * @pid:父类ID
     */
    function get_child_ids($pid)
    {
        return get_ids($pid, '', 'code');
    }
}

if (!function_exists('get_ids')) {
    /**
     * @Description: 获取类下所有父/子类ID
     * @pid:多个父/子类ID集以,分隔
     * @childids:找到的子/父分类列表
     * @find_column:where查找的字段[id|pid:default]
     */
    function get_ids($pid, $childids, $find_column = 'code')
    {
        if (!$pid || $pid <= 0 || strlen($pid) <= 0 || !in_array($find_column, array('code', 'pcode'))) return 0;
        if (!$childids || strlen($childids) <= 0) $childids = $pid;
        $column = ($find_column == 'code' ? "pcode" : "code");//id跟pid为互斥
        $ids = Db::name("hc_area_code")->where("$column in ($pid)")->column("$find_column");
        $ids = implode(",", $ids);

        //未找到,返回已经找到的
        if ($ids <= 0) return $childids;
        //添加到集合中
        $childids .= ',' . $ids;
        //递归查找
        return get_ids($ids, $childids, $find_column);
    }
}

/**
 * 发送curl请求获得数据
 * @param $url string
 * @param return array|mixed
 */
function https_request($url)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $AjaxReturn = curl_exec($curl);
    //获取转换为数组
    $data = json_decode($AjaxReturn, true);
    curl_close($curl);
    return $data;
}

function mb_substr_replace($string, $replacement, $start, $length = null, $encoding = null)
{
    if (extension_loaded('mbstring') === true) {
        $string_length = (is_null($encoding) === true) ? mb_strlen($string) : mb_strlen($string, $encoding);

        if ($start < 0) {
            $start = max(0, $string_length + $start);
        } else if ($start > $string_length) {
            $start = $string_length;
        }

        if ($length < 0) {
            $length = max(0, $string_length - $start + $length);
        } else if ((is_null($length) === true) || ($length > $string_length)) {
            $length = $string_length;
        }

        if (($start + $length) > $string_length) {
            $length = $string_length - $start;
        }

        if (is_null($encoding) === true) {
            return mb_substr($string, 0, $start) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length);
        }

        return mb_substr($string, 0, $start, $encoding) . $replacement . mb_substr($string, $start + $length, $string_length - $start - $length, $encoding);
    }

    return (is_null($length) === true) ? substr_replace($string, $replacement, $start) : substr_replace($string, $replacement, $start, $length);
}

function send_post($url, $post_data, $method = 'POST')
{
    $postdata = http_build_query($post_data);
    $options = array(
        'http' => array(
            'method' => $method, //or GET
            'header' => 'Content-type:application/x-www-form-urlencoded',
            'content' => $postdata,
            'timeout' => 15 * 60 // 超时时间(单位:s)
        )
    );
    $context = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return $result;
}

function api_notice_increment($url, $data = '', $method = 'GET')
{
    $curl = curl_init();
    $header = array("application/x-www-form-urlencoded; charset=utf-8");
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    if ($method == 'POST') {
        curl_setopt($curl, CURLOPT_POST, 1);
        if ($data != '') {
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
    }
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);
    curl_setopt($curl, CURLOPT_HEADER, 0);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($curl);
    curl_close($curl);
    return $result;
}

/**
 *求两个已知经纬度之间的距离,单位为千米
 * @param lng1,lng2 经度
 * @param lat1,lat2 纬度
 * @return float 距离,单位千米
 **/
//根据经纬度计算距离
function distance($lng1, $lat1, $lng2, $lat2)
{
    //将角度转为弧度
    $radLat1 = deg2rad($lat1);
    $radLat2 = deg2rad($lat2);
    $radLng1 = deg2rad($lng1);
    $radLng2 = deg2rad($lng2);
    $a = $radLat1 - $radLat2;//两纬度之差,纬度<90
    $b = $radLng1 - $radLng2;//两经度之差纬度<180
    $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137;
    return $s;
}