User.php 88.4 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 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411
<?php
namespace app\mobile\controller;

use think\Validate;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use app\common\controller\Api;
use app\common\library\Sms as Smslib;
use app\mobile\controller\Sms;
use app\mobile\model\Company;
use app\mobile\model\CompanyUser;
use app\mobile\model\Exam;
use app\mobile\model\CourseOrder;
use app\mobile\model\CourseAppraise;
use app\mobile\model\SecretOrder;
use app\mobile\model\ScoreSpec;
use app\mobile\model\ScoreOrder;
use app\mobile\model\Recharge;
use app\mobile\model\RechargeOrder;
use app\mobile\model\QuestionCollect;
use app\mobile\model\CourseCollect;
use app\mobile\model\QuestionNote;
use app\mobile\model\Message;
use app\mobile\model\Feedback;
use app\mobile\model\Problem;
use app\mobile\model\Topic;
use app\mobile\model\TopicAppraise;
use app\mobile\model\TopicAppraiseGood;
use app\mobile\model\UserJob;
use app\mobile\model\CompanyJob;
use app\mobile\model\Statistic;
use app\mobile\model\UserThird;
use addons\epay\library\Service;
use Endroid\QrCode\QrCode;

/**
 * 我的接口
 * @ApiWeigh (66)
 */
class User extends Api
{
	protected $noNeedLogin = ['registerUser','agreementUser','registerCompany','agreementCompany','agreementPrivacy','login','thirdLogin','thirdBindMobile','resetpwd','exam','noLogin','problemList','problemInfo'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiWeigh (99)
     * @ApiTitle    (注册-个人)
     * @ApiSummary  (注册-个人)
     * @ApiMethod   (POST)
     * @param string $mobile   手机号
     * @param string $code   验证码
     * @param string $password 密码
     */
    public function registerUser()
    {
        $mobile = $this->request->param('mobile');
        $code = $this->request->param('code');
        $password = $this->request->param('password');

        empty($mobile) && $this->error('请输入手机号');
        empty($code) && $this->error('请输入验证码');
        empty($password) && $this->error('请输入密码');
        !Validate::regex($mobile, "^1\d{10}$") && $this->error('手机号格式不正确');
        $ret = Sms::check($mobile, $code, 'register');
        !$ret && $this->error('验证码不正确');

        Db::startTrans();
        try {
            $extend = ['phone' => $mobile]; //与pc端统一
            $ret = $this->auth->register($mobile, $password, $email='', $mobile, $extend);
            // 记录每日注册数量
            $statistic = Statistic::where('today',date('Y-m-d'))->find();
            if($statistic){
                $statistic->save(['register_times' => $statistic->register_times+1]);
            }else{
                (new Statistic)->save([
                    'register_times' => 1,
                    'today' => date('Y-m-d')
                ]);
            }
            // 密码设置为明文,与pc端统一
            $this->auth->getUser()->save(['password'=>$password]);
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->auth->logout();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->auth->logout();
            $this->error($e->getMessage());
        }
        if ($ret) {
            $this->auth->setAllowFields(['id', 'mobile', 'group_id']);
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success('注册成功', $data);
        } else {
            Db::rollback();
            $this->error($this->auth->getError());
        }
    }

    /**
     * @ApiWeigh (97)
     * @ApiTitle    (注册协议-个人)
     * @ApiSummary  (注册协议-个人)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1599017563",
		"data": "用户协议内容" //协议内容
	})
     */
    public function agreementUser()
    {
        $content = Db::name('mobile_config')->where('id',1)->value('user_agreement');
        $this->success('成功', $content);
    }

    /**
     * @ApiWeigh (95)
     * @ApiTitle    (注册-公司)
     * @ApiSummary  (注册-公司)
     * @ApiMethod   (POST)
     * @param string $name   公司名称
     * @param string $address   公司地址
     * @param string $license   公司执照
     * @param string $legal_person   法人名称
     * @param string $mobile   手机号
     * @param string $code   验证码
     * @param string $password 密码
     */
    public function registerCompany()
    {
    	$name = $this->request->param('name');
        $address = $this->request->param('address');
        $license = $this->request->param('license');
        $legal_person = $this->request->param('legal_person');
        $mobile = $this->request->param('mobile');
        $code = $this->request->param('code');
        $password = $this->request->param('password');

        empty($name) && $this->error('请输入公司名称');
        empty($address) && $this->error('请输入地址');
        empty($license) && $this->error('请上传执照');
        empty($legal_person) && $this->error('请输入法人名称');
        empty($mobile) && $this->error('请输入手机号');
        empty($code) && $this->error('请输入验证码');
        empty($password) && $this->error('请输入密码');
        !Validate::regex($mobile, "^1\d{10}$") && $this->error('手机号格式不正确');
        $ret = Sms::check($mobile, $code, 'register');
        !$ret && $this->error('验证码不正确');

        Db::startTrans();
        try {
            $extend = ['phone' => $mobile]; //与pc端统一
            $ret = $this->auth->register($mobile, $password, $email='', $mobile, $extend);
            $company = Company::create([
                'user_id' => $this->auth->id,
                'name' => $name,
                'address' => $address,
                'license' => $license,
                'legal_person' => $legal_person
            ]);
            // 添加企业邀请码
            $this->setInviteCode($company['id']);
            // 记录每日注册数量
            $statistic = Statistic::where('today',date('Y-m-d'))->find();
            if($statistic){
                $statistic->save(['register_times' => $statistic->register_times+1]);
            }else{
                (new Statistic)->save([
                    'register_times' => 1,
                    'today' => date('Y-m-d')
                ]);
            }
            // 密码设置为明文,与pc端统一
            $this->auth->getUser()->save(['password'=>$password]);
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->auth->logout();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->auth->logout();
            $this->error($e->getMessage());
        }
        if($ret){
            $this->auth->setAllowFields(['id', 'mobile', 'group_id']);
            $data = ['userinfo' => $this->auth->getUserInfo()];
        }else{
            Db::rollback();
            $this->error($this->auth->getError());
        }
        $this->success('注册成功', $data);
    }

    /**
     * @ApiWeigh (93)
     * @ApiTitle    (注册协议-公司)
     * @ApiSummary  (注册协议-公司)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1599017563",
		"data": "用户协议内容" //协议内容
	})
     */
    public function agreementCompany()
    {
        $content = Db::name('mobile_config')->where('id',1)->value('company_agreement');
        $this->success('成功', $content);
    }

    /**
     * @ApiWeigh (93)
     * @ApiTitle    (隐私协议)
     * @ApiSummary  (隐私协议)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599017563",
        "data": "隐私协议内容" //协议内容
    })
     */
    public function agreementPrivacy()
    {
        $content = Db::name('mobile_config')->where('id',1)->value('privacy_agreement');
        $this->success('成功', $content);
    }

    /**
     * @ApiWeigh (91)
     * @ApiTitle    (登录)
     * @ApiSummary  (登录)
     * @ApiMethod   (POST)
     *
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     *
     * @ApiReturn({
        "code": 1, 
        "msg": "登录成功", 
        "time": "1600498819", 
        "data": {
            "userinfo": {
                "id": 15, //用户ID
                "group_id": 1, //角色:0=普通用户,1=企业管理员
                "mobile": "15133120361", //用户登录手机号
                "token": "339d3a6c-c611-4961-a8e6-56a432b02a49", //token
                "user_id": 15, //用户ID
                "createtime": 1600498819, 
                "expiretime": 1603090819, 
                "expires_in": 2592000
            }
        }
    })
     */
    public function login()
    {
        $mobile = $this->request->param('mobile');
        $password = $this->request->param('password');

        empty($mobile) && $this->error('请输入账号或手机号');
        empty($password) && $this->error('请输入密码');
        $field = Validate::regex($mobile, '/^1\d{10}$/') ? 'mobile' : 'username';
        $user = \app\common\model\User::get([$field => $mobile]);
        !$user && $this->error(__('Account is incorrect'));
        $user->password != $password && $this->error(__('Password is incorrect'));
        //直接登录会员
        $this->auth->direct($user->id);
        // 记录日活
        $statistic = Statistic::where('today',date('Y-m-d'))->find();
        if($statistic){
            $statistic->save(['active_times' => $statistic->active_times+1]);
        }else{
            (new Statistic)->save([
                'active_times' => 1,
                'today' => date('Y-m-d')
            ]);
        }
        $this->auth->setAllowFields(['id', 'mobile', 'group_id']);
        $data = ['userinfo' => $this->auth->getUserInfo()];
        $this->success('登录成功', $data);
    }

    /**
     * 第三方登录
     * @ApiWeigh    (91)
     *
     * @ApiTitle    (第三方登录)
     * @ApiSummary  (第三方登录)
     * @ApiMethod   (POST)
     *
     * @ApiParams   (name="nickname", type="integer", required=true, description="第三方账号昵称")
     * @ApiParams   (name="avatar", type="integer", required=false, description="第三方账号头像")
     * @ApiParams   (name="gender", type="integer", required=false, description="第三方性别")
     * @ApiParams   (name="openid", type="string", required=true, description="第三方登录返回的唯一识别数据")
     * @ApiParams   (name="unionid", type="string", required=false, description="第三方用户多个产品中的唯一id,如:微信开放平台")
     *
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": {
            "bind_mobile": 是否已绑定手机号码0=否1=是,
            "token": 用户token
        }
    })
     */
    public function thirdLogin() {
        $param = $this->request->param();
        $validate = new Validate([
            'nickname'              => 'require',
            'openid'                => 'require',
        ]);
        $validate->message([
            'nickname.require'      => '缺少参数nickname!',
            'openid.require'        => '缺少参数openid!',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        // 判断用户是否已绑定该openid
        $bind_mobile = 0;
        $time = time();
        $ip = request()->ip();
        $third = UserThird::where('openid',$param['openid'])->find();
        if($third) {
            $user = \app\common\model\User::get($third['user_id']);
            if($user){
                Db::startTrans();
                // 修改第三方信息
                $result = $third->save([
                    'openname' => $param['nickname'],
                    'logintime'=>$time
                ]);
                // 修改用户信息
                if(empty($user['nickname'])){
                    $user->nickname = $param['nickname'];
                }
                if(!empty($param['avatar']) && (empty($user['image']) || stripos($user['image'], 'http') !== false)){
                    $user->image = $param['avatar'];
                }
                if(!empty($param['gender']) && !isset($user['sex'])){
                    $user->sex = $param['gender'] == 2 ? 0 : $param['gender'];
                }
                $user->loginip = $ip;
                $user->logintime = $time;
                $user->updatetime = $time;
                $results = $user->save();
                // 登录
                $login = $this->auth->direct($third['user_id']);
                if(!$result || !$results || !$login) {
                    Db::rollback();
                    $this->error('授权登录失败');
                }
                Db::commit();
                $bind_mobile = 1;
                $token = $this->auth->getToken();
            }
        } else {
            // 添加第三方信息
            $result = UserThird::create([
                'openname' => $param['nickname'],
                'platform' => 'wechat',
                'openid' => $param['openid'],
                'createtime' => $time,
                'updatetime' => $time,
                'logintime' => $time,
                'unionid' => $param['unionid'],
            ]);
            if(!$result) {
                Db::rollback();
                $this->error('授权登录失败');
            }
        }
        Db::commit();
        $this->success('成功',['bind_mobile'=>$bind_mobile,'token'=>empty($token)?'':$token]);
    }

    /**
     * 绑定手机号
     * @ApiWeigh    (91)
     *
     * @ApiTitle    (第三方登录-绑定手机号)
     * @ApiSummary  (第三方登录-绑定手机号)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="mobile", type="integer", required=true, description="手机号码")
     * @ApiParams   (name="code", type="integer", required=true, description="验证码")
     * @ApiParams   (name="openid", type="integer", required=true, description="第三方登录返回的唯一识别数据")
     * @ApiParams   (name="nickname", type="integer", required=true, description="第三方账号昵称")
     * @ApiParams   (name="avatar", type="integer", required=false, description="第三方账号头像")
     * @ApiParams   (name="gender", type="integer", required=false, description="第三方性别")
     *
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": {
            "token": 用户token,
            "is_password": 是否设置密码(0,否;1,是)
        }
    })
     */
    public function thirdBindMobile() {
        if($this->request->isPost()) {
            $param = $this->request->param();
            $validate = new Validate([
                'mobile'                    => 'require',
                'code'                      => 'require|number|length:4',
                'openid'                    => 'require',
            ]);
            $validate->message([
                'mobile.require'            => '请输入您的手机号!',
                'code.require'              => '请输入数字验证码!',
                'code.number'               => '请输入正确的数字验证码!',
                'code.length'               => '数字验证码长度错误!',
                'openid.require'            => '缺少参数openid!',
            ]);
            if (!$validate->check($param)) {
                $this->error($validate->getError());
            }
            if (!Sms::check($param['mobile'], $param['code'], 'bind')) {
                $this->error(__('Captcha is incorrect'));
            }
            // 判断用户是否已绑定该openid
            $third = UserThird::where('openid',$param['openid'])->find();
            if($third) {
                $user_model = new \app\common\model\User();
                $user = $user_model->get($third['user_id']);
                Db::startTrans();
                if($user) {
                    $this->error('已绑定手机号');
                }
                // 判断是否存在该手机号
                $user = $user_model->where('mobile',$param['mobile'])->find();
                $ip = request()->ip();
                $time = time();
                if(!$user) {
                    $user_insert = [
                        'username'          => $param['mobile'],
                        'nickname'          => $param['nickname'],
                        'image'             => empty($param['avatar']) ? '/assets/img/avatar.png' : $param['avatar'],
                        'sex'               => isset($param['gender']) && $param['gender'] == 0 ? 2 : 1,
                        'mobile'            => $param['mobile'],
                        'jointime'          => $time,
                        'joinip'            => $ip,
                        'logintime'         => $time,
                        'loginip'           => $ip,
                        'prevtime'          => $time,
                        'status'            => 'normal',
                    ];
                    $results = $user_model->isUpdate(false)->save($user_insert);
                    $this->auth->direct($user_model['id']);
                    $is_password = 0;
                } else {
                    // 判断手机号是否已经绑定第三方
                    $third_user_data = UserThird::where('user_id',$user['id'])
                        ->where('platform','wechat')
                        ->find();
                    if($third_user_data) {
                        Db::rollback();
                        $this->error('该手机号已绑定微信');
                    }
                    // 修改用户信息
                    if(empty($user['nickname'])){
                        $user->nickname = $param['nickname'];
                    }
                    if(!empty($param['avatar']) && (empty($user['image']) || stripos($user['image'], 'http') !== false)){
                        $user->image = $param['avatar'];
                    }
                    if(!empty($param['gender']) && !isset($user['sex'])){
                        $user->sex = $param['gender'] == 2 ? 0 : $param['gender'];
                    }
                    $user->loginip = $ip;
                    $user->logintime = $time;
                    $user->updatetime = $time;
                    $results = $user->save();
                    $this->auth->direct($user['id']);
                    $is_password = $user['password'] ? 1 : 0;
                }
                $result = $third->save([
                    'logintime'     => $time,
                    'user_id'       => $user['id'],
                ]);
                if(!$result || !$results) {
                    Db::rollback();
                    $this->error('第三方绑定失败');
                }
                Db::commit();
                // 生成token
                $token = $this->auth->getToken();
                $this->success('绑定成功',['token'=>$token,'is_password'=>$is_password]);
            }
        }
    }

    /**
     * 第三方登录-设置密码
     * @ApiWeigh    (91)
     *
     * @param string $password 密码
     * @param string $confirm_password 确认密码
     */
    public function thirdPassword()
    {
        $password = $this->request->request('password');
        $confirm_password = $this->request->request('confirm_password');
        if ($confirm_password != $password) {
            $this->error(__('密码与确认密码不一致'));
        }
        if ($this->auth->password) {
            $this->error('已设置过密码');
        }
        $user_model = new \app\common\model\User();
        $result = $user_model->update(['id' => $this->auth->id, 'password' => $password]);
        if (!$result) {
            $this->error('密码设置失败');
        }
        $this->success('密码设置成功');
    }

    /**
     * @ApiWeigh (89)
     * @ApiTitle    (忘记密码)
     * @ApiSummary  (忘记密码)
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $code     验证码
     */
    public function resetpwd()
    {
        $mobile = $this->request->request("mobile");
        $code = $this->request->request("code");
        $newpassword = $this->request->request("newpassword");

        empty($mobile) && $this->error('请输入手机号');
        empty($newpassword) && $this->error('请输入密码');
        !Validate::regex($mobile, "^1\d{10}$") && $this->error('手机号格式不正确');
        $user = \app\common\model\User::getByMobile($mobile);
        !$user && $this->error('用户不存在');
        $ret = Sms::check($mobile, $code, 'resetpwd');
        !$ret && $this->error('验证码不正确');

        Smslib::flush($mobile, 'resetpwd');
        //模拟一次登录
        $this->auth->direct($user->id);
        // $ret = $this->auth->changepwd($newpassword, '', true);
        // 密码设置为明文,与pc端统一
        $ret = $this->auth->getUser()->save(['password'=>$newpassword]);
        if ($ret) {
            $this->success('重置密码成功');
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * @ApiWeigh (85)
     * @ApiTitle    (暂不登录提示)
     * @ApiSummary  (暂不登录提示)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1599017563",
		"data": "暂不登录提示内容" //暂不登录提示内容
	})
     */
    public function noLogin()
    {
        $content = Db::name('mobile_config')->where('id',1)->value('no_login');
        $this->success('成功', $content);
    }

    /**
     * @ApiWeigh (83)
     * @ApiTitle    (我的-首页)
     * @ApiSummary  (我的-首页)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602813642",
        "data": {
            "id": 15,
            "group_id": 1, //身份:0=个人用户,1=企业用户
            "username": "",
            "nickname": "", //真实姓名
            "password": "743fee718194570689974bad08666a56",
            "salt": "UDnPtj",
            "email": "",
            "mobile": "15133120361",
            "avatar": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZlcnNpb249IjEuMSIgaGVpZ2h0PSIxMDAiIHdpZHRoPSIxMDAiPjxyZWN0IGZpbGw9InJnYigxNjAsMjI5LDE3OSkiIHg9IjAiIHk9IjAiIHdpZHRoPSIxMDAiIGhlaWdodD0iMTAwIj48L3JlY3Q+PHRleHQgeD0iNTAiIHk9IjUwIiBmb250LXNpemU9IjUwIiB0ZXh0LWNvcHk9ImZhc3QiIGZpbGw9IiNmZmZmZmYiIHRleHQtYW5jaG9yPSJtaWRkbGUiIHRleHQtcmlnaHRzPSJhZG1pbiIgYWxpZ25tZW50LWJhc2VsaW5lPSJjZW50cmFsIj48L3RleHQ+PC9zdmc+",
            "level": 1,
            "gender": 0,
            "birthday": null,
            "bio": "",
            "money": "0.00",
            "score": 0,
            "successions": 1,
            "maxsuccessions": 3,
            "prevtime": 1601340700,
            "logintime": 1602242130,
            "loginip": "127.0.0.1",
            "loginfailure": 0,
            "joinip": "127.0.0.1",
            "jointime": 1599914736,
            "createtime": 1599914736,
            "updatetime": 1602242130,
            "token": "",
            "status": "normal",
            "verification": {
                "email": 0,
                "mobile": 0
            },
            "pwd": null,
            "card": null,
            "sex": null,
            "phone": null,
            "work_address": null,
            "image": "", //头像
            "expirationtime": null,
            "studynum": null,
            "message_count": 1, //未读消息数量
            "url": "/u/15"
        }
    })
     */
    public function index()
    {
        $user = $this->auth->getUser();
        $user->image = !empty($user->image) ? cdnurl($user->image,true) : '';
        $user->message_count = Message::where('user_id',$user->id)->where('is_read','0')->count();
        $this->success('成功', $user);
    }

    /**
     * @ApiWeigh (81)
     * @ApiTitle    (我的-修改会员个人信息)
     * @ApiSummary  (我的-修改会员个人信息)
     *
     * @param string $image   头像地址
     * @param string $username 用户名
     * @param string $nickname 真实姓名
     * @param int $sex 性别1男0女
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->param('username');
        $nickname = $this->request->param('nickname');
        $image = $this->request->param('image', '', 'trim,strip_tags,htmlspecialchars');
        $sex = $this->request->param('sex');
        if($username || $nickname || $image || in_array($sex,[0,1])) {
            if ($username) {
                $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
                if ($exists) {
                    $this->error('用户名已存在');
                }
                $user->username = $username;
            }
            if ($nickname) {
                $user->nickname = $nickname;
            }
            if ($image) {
                $user->image = $image;
            }
            if (in_array($sex,[0,1])) {
                $user->sex = $sex;
            }
            $user->save();
        }
        $this->success();
    }

    /**
     * @ApiWeigh (79)
     * @ApiTitle    (修改手机号-第一步)
     * @ApiSummary  (修改手机号-第一步)
     * @param string $code 验证码
     */
    public function changemobile1()
    {
        $user = $this->auth->getUser();
        $code = $this->request->param('code');
        !$code && $this->error(__('请输入验证码'));
        $ret = Sms::check($user['mobile'], $code, 'changemobile1');
        !$ret && $this->error('验证码不正确');
        Smslib::flush($user['mobile'], 'changemobile1');
        $this->success();
    }

    /**
     * @ApiWeigh (77)
     * @ApiTitle    (修改手机号-第二步)
     * @ApiSummary  (修改手机号-第二步)
     *
     * @param string $mobile 新手机号
     * @param string $code 验证码
     */
    public function changemobile2()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->param('mobile');
        $code = $this->request->param('code');
        if (!$mobile || !$code) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $code, 'changemobile2');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Smslib::flush($mobile, 'changemobile2');
        $this->success();
    }

    /**
     * @ApiWeigh    (77)
     * @ApiTitle    (绑定微信)
     * @ApiSummary  (绑定微信)
     * @ApiMethod   (POST)
     *
     * @ApiParams   (name="nickname", type="integer", required=true, description="第三方账号昵称")
     * @ApiParams   (name="avatar", type="integer", required=false, description="第三方账号头像")
     * @ApiParams   (name="gender", type="integer", required=false, description="第三方性别")
     * @ApiParams   (name="openid", type="string", required=true, description="第三方登录返回的唯一识别数据")
     * @ApiParams   (name="unionid", type="string", required=false, description="第三方用户多个产品中的唯一id,如:微信开放平台")
     *
     * @ApiReturn   ({
        'code':'1',
        'msg':'返回成功',
        "data": {
            "token": 用户token
        }
    })
     */
    public function bindThird() {
        $param = $this->request->param();
        $validate = new Validate([
            'nickname'              => 'require',
            'openid'                => 'require',
        ]);
        $validate->message([
            'nickname.require'      => '缺少参数nickname!',
            'openid.require'        => '缺少参数openid!',
        ]);
        if (!$validate->check($param)) {
            $this->error($validate->getError());
        }
        // 判断用户是否已绑定该openid
        $time = time();
        $third = UserThird::where('openid',$param['openid'])->find();
        Db::startTrans();
        if($third) {
            $user = \app\common\model\User::get($third['user_id']);
            if($user['id'] != $this->auth->id){
                $this->error('该微信已绑定其他账号');
            }
            // 修改第三方账号
            $result = UserThird::where('id',$third['id'])->update([
                'openname' => $param['nickname'],
            ]);
        } else {
            // 删除原来的第三方账号
            UserThird::where('user_id',$this->auth->id)->delete();
            $user = \app\common\model\User::get($this->auth->id);
            // 添加新的第三方账号
            $result = UserThird::create([
                'user_id' => $this->auth->id,
                'openname' => $param['nickname'],
                'platform' => 'wechat',
                'openid' => $param['openid'],
                'createtime' => $time,
                'updatetime' => $time,
                'logintime' => $time,
                'unionid' => $param['unionid'],
            ]);
        }
        // 修改用户信息
        if(!empty($param['nickname']) && empty($user['nickname'])){
            $user->nickname = $param['nickname'];
        }
        if(!empty($param['avatar']) && (empty($user['image']) || stripos($user['image'], 'http') !== false)){
            $user->image = $param['avatar'];
        }
        if(!empty($param['gender']) && !isset($user['sex'])){
            $user->sex = $param['gender'] == 2 ? 0 : $param['gender'];
        }
        $user->updatetime = $time;
        $results = $user->save();
        if(!$result || !$results) {
            Db::rollback();
            $this->error('绑定微信失败');
        }
        Db::commit();
        $this->success('成功');
    }

    /**
     * @ApiWeigh (76)
     * @ApiTitle    (加入企业-查询企业)
     * @ApiSummary  (加入企业-查询企业)
     * @ApiMethod   (POST)
     *
     * @ApiParams (name="keyword", type="string", required=true, description="关键字")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602310974",
        "data": [{
            "id": 7, //企业ID
            "name": "测试公司" //企业名称
        }]
    })
     */
    public function companyList()
    {
        $keyword = $this->request->param('keyword');
        empty($keyword) && $this->error('请输入关键字');
        $list = Company::where('status','1')
            ->where('name','like','%'.$keyword.'%')
            ->field('id,name')
            ->select();
        count($list) <= 0 && $this->error('未查找到该企业');
        $this->success('成功',$list);
    }

    /**
     * @ApiWeigh (75)
     * @ApiTitle    (加入企业)
     * @ApiSummary  (加入企业)
     *
     * @param string $company_id 企业ID
     * @param string $name 姓名
     * @param string $mobile 手机号
     * @param string $invite_code 验证码
     */
    public function joinCompany()
    {
        $company_id = $this->request->param('company_id');
        $name = $this->request->param('name');
        $mobile = $this->request->param('mobile');
        $invite_code = $this->request->param('invite_code');
        // 验证传参
        empty($company_id) && $this->error('缺少必需参数');
        empty($name) && $this->error('请填写姓名');
        empty($mobile) && $this->error('请填写联系方式');
        empty($invite_code) && $this->error('请填写邀请码');
        !Validate::regex($mobile, "^1\d{10}$") && $this->error(__('Mobile is incorrect'));
        // 验证邀请码
        $company = Company::where('invite_code',$invite_code)
            ->where('id',$company_id)
            ->field('id')
            ->find();
        empty($company) && $this->error('邀请码错误,请输入正确的邀请码');
        // 验证申请状态
        $company_user = CompanyUser::where('company_id',$company['id'])
            ->where('user_id',$this->auth->id)
            ->field('status')
            ->find();
        if($company_user){
            if($company_user['status'] == '0'){
                $this->error('正在申请中,请勿重复提交申请');
            }
            if($company_user['status'] == '1'){
                $this->error('加入企业成功,请勿重复提交申请');
            }
        }
        CompanyUser::create([
            'user_id' => $this->auth->id,
            'company_id' => $company_id,
            'name' => $name,
            'mobile' => $mobile
        ]);
        $this->success('已成功提交,请提醒企业管理员及时审核');
    }

    /**
     * 更新企业邀请码
     * @ApiInternal
     * @param string $company_id 企业ID
     */
    public function setInviteCode($company_id){
        $code = mt_rand(100000,999999);
        $find = Company::where('invite_code',$code)->field('id')->find();
        if(!$find){
            Company::where('id',$company_id)->setField('invite_code',$code);
            return $code;
        }else{
            $this->setInviteCode($company_id);
        }
    }

    /**
     * @ApiWeigh (73)
     * @ApiTitle    (我的课程)
     * @ApiSummary  (我的课程)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600081718",
        "data": {
			"total": 1, // 数据总数
			"list": [{
	            "id": 9, //课程订单ID
	            "pay_price": "50.00", //实际支付金额
	            "course": { //课程信息
	                "id": 1, //课程ID
	                "title": "测试课程", //课程标题
	                "cover": "" //课程封面图
	            },
	            "is_have_qi": 0 //是否有企字:0=否,1=是
	            "is_have_appraise": 0 //是否已评价:0=否,1=是
	        }]
        }
    })
     */
    public function myCourse(){
    	$page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        // 我加入的企业购买的课程
        $company_course_list = CourseOrder::alias('co')
            ->join('mobile_company_user cu','cu.company_id = co.company_id')
            ->where('cu.user_id',$this->auth->id)
            ->where('cu.status','1')
            ->field('co.id,co.company_id,co.people_num,co.is_top')
            ->select();
        // 查询我是否可以享受企业课程(按企业审核时间排队,没在队伍里就无法享受企业课程)
        $course_id_arr = [];
        foreach ($company_course_list as $v) {
            if($v['is_top'] == '1'){
                $course_id_arr[] = $v['id'];
                continue;
            }
            $user_id_arr = CompanyUser::where('company_id',$v['company_id'])
                ->where('status','1')
                ->order('updatetime asc')
                ->limit($v['people_num'])
                ->column('user_id');
            if(in_array($this->auth->id,$user_id_arr)){
                $course_id_arr[] = $v['id'];
            }
        }
        // 查找所有课程
        $data = CourseOrder::with(['course'])
            ->where(function($query)use($course_id_arr){
                $query->where('user_id', $this->auth->id)->whereor('id', 'in', $course_id_arr);
            })
            ->where('pay_status','1')
            ->order('createtime desc')
            ->paginate($page_num,false,['page'=>$page])
            ->each(function($v)use($course_id_arr){
                // 是否有企字
	            $v['is_have_qi'] = in_array($v['id'], $course_id_arr) ? 1 : 0;
	            // 是否已评价
	            $have_appraise = CourseAppraise::where('user_id',$this->auth->id)
	                ->where('course_id',$v['course_id'])
	                ->where('course_order_id',$v['id'])
	                ->field('id')
	                ->find();
	            $v['is_have_appraise'] = !empty($have_appraise) ? 1 : 0;
	            $v->visible(['id','pay_price','course'])->append(['is_have_qi','is_have_appraise']);
	            $v->getRelation('course')->visible(['id','cover','title']);
            })->toArray();
        $this->success('成功',['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiWeigh (71)
     * @ApiTitle    (我的课程-评价页面)
     * @ApiSummary  (我的课程-评价页面)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="course_order_id", type="int", required=true, description="课程订单ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600084253",
        "data": {
            "id": 10, //课程订单ID
            "pay_price": "50.00", //实际支付金额
            "course": { //课程信息
                "title": "测试课程", //课程标题
                "cover": "" //课程封面图
            },
            "is_have_qi": 0 //是否有企字:0=否,1=是
        }
    })
     */
    public function appraiseView(){
        $course_order_id = $this->request->param('course_order_id');
        empty($course_order_id) && $this->error('缺少必需参数');
        $info = CourseOrder::get($course_order_id,['course']);
        empty($info) && $this->error('课程订单不存在');
        $user_id_arr = CompanyUser::where('company_id',$info['company_id'])
            ->where('status','1')
            ->order('updatetime asc')
            ->limit($info['people_num'])
            ->column('user_id');
        $info['is_have_qi'] = in_array($this->auth->id,$user_id_arr) ? 1 : 0;
        $info->visible(['id','pay_price','course'])->append(['is_have_qi']);
        $info->getRelation('course')->visible(['cover','title']);
        $this->success('成功',$info);
    }

    /**
     * @ApiWeigh (69)
     * @ApiTitle    (我的课程-评价)
     * @ApiSummary  (我的课程-评价)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="course_order_id", type="int", required=true, description="课程订单ID")
     * @ApiParams (name="star", type="int", required=true, description="评价星数")
     * @ApiParams (name="content", type="int", required=true, description="评价内容")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600084253",
        "data": null
    })
     */
    public function appraise(){
        $course_order_id = $this->request->param('course_order_id');
        $star = $this->request->param('star');
        $content = $this->request->param('content');
        empty($course_order_id) && $this->error('缺少必需参数');
        empty($star) && $this->error('请选择星数');
        empty($content) && $this->error('请填写评价内容');
        $info = CourseOrder::get($course_order_id,['course']);
        empty($info) && $this->error('课程订单不存在');
        CourseAppraise::create([
            'user_id' => $this->auth->id,
            'course_id' => $info['course_id'],
            'course_order_id' => $info['id'],
            'star' => $star,
            'content' => $content
        ]);
        $this->success('评价成功');
    }

    /**
     * @ApiWeigh (67)
     * @ApiTitle    (我的密卷)
     * @ApiSummary  (我的密卷)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600081718",
        "data": {
			"total": 1, // 数据总数
			"list": [{
	            "id": 9, //密卷订单ID
	            "pay_price": "50.00", //实际支付金额
	            "secret": { //密卷信息
	                "id": 1, //密卷ID
	                "title": "测试密卷", //密卷标题
	                "do_num": "" //做过人数
	            },
	            "is_have_qi": 0 //是否有企字:0=否,1=是
	        }]
        }
    })
     */
    public function mySecret(){
    	$page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        // 我加入的企业购买的密卷
        $company_secret_list = SecretOrder::alias('a')
            ->join('mobile_company_user b','b.company_id = a.company_id')
            ->where('b.user_id',$this->auth->id)
            ->where('b.status','1')
            ->field('a.id,a.company_id,a.people_num,a.is_top')
            ->select();
        // 查询我是否可以享受企业密卷(按企业审核时间排队,没在队伍里就无法享受企业密卷)
        $secret_id_arr = [];
        foreach ($company_secret_list as $v) {
            if($v['is_top'] == '1'){
                $secret_id_arr[] = $v['id'];
                continue;
            }
            $user_id_arr = CompanyUser::where('company_id',$v['company_id'])
                ->where('status','1')
                ->order('updatetime asc')
                ->limit($v['people_num'])
                ->column('user_id');
            if(in_array($this->auth->id,$user_id_arr)){
                $secret_id_arr[] = $v['id'];
            }
        }
        // 查找所有密卷
        $data = SecretOrder::with(['secret'])
            ->where(function($query)use($secret_id_arr){
                $query->where('user_id', $this->auth->id)->whereor('id', 'in', $secret_id_arr);
            })
            ->where('pay_status','1')
            ->order('createtime desc')
            ->paginate($page_num,false,['page'=>$page])
            ->each(function($v)use($secret_id_arr){
                // 是否有企字
	            $v['is_have_qi'] = in_array($v['id'], $secret_id_arr) ? 1 : 0;
	            $v->visible(['id','pay_price','secret'])->append(['is_have_qi']);
	            $v->getRelation('secret')->visible(['id','title']);
            })->toArray();
        $this->success('成功',['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiWeigh (65)
     * @ApiTitle    (我的积分)
     * @ApiSummary  (我的积分)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1600135095",
		"data": {
			"id": 16, //用户ID
			"score": 0, //当前积分
			"url": "/u/16",
			"max_score": 0 //累计积分
		}
	})
     */
    public function myScore(){
        $user = $this->auth->getUser();
        $user['max_score'] = db('user_score_log')->where('user_id',$user['id'])->max('after');
        $user = $user->visible(['id','score'])->append(['max_score'])->toArray();
        $this->success('成功',$user);
    }

    /**
     * @ApiWeigh (63)
     * @ApiTitle    (积分说明)
     * @ApiSummary  (积分说明)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599017563",
        "data": "积分说明" //积分说明内容
    })
     */
    public function scoreIntro()
    {
        $content = Db::name('mobile_config')->where('id',1)->value('user_score_intro');
        $this->success('成功', $content);
    }

    /**
     * @ApiWeigh (61)
     * @ApiTitle    (积分记录)
     * @ApiSummary  (积分记录)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599017563",
        "data": "积分说明" //积分说明内容
    })
     */
    public function scoreLog()
    {
    	$page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $data = \app\common\model\ScoreLog::where('user_id',$this->auth->id)
        	->order('createtime desc')
        	->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                $v['createtime'] = date('Y.m.d H:i',$v['createtime']);
            })->toArray();
        $this->success('成功', ['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiWeigh (59)
     * @ApiTitle    (海报分享)
     * @ApiSummary  (海报分享)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599017563",
        "data": {
            "url": "http://www.enterprise.top/qrcode/20201017/52b77af2efe121e124c1b26d4d0d7f43.png", //海报地址
        }
    })
     */
    public function share()
    {
        $user = \app\mobile\model\User::get($this->auth->id);
        empty($user['image']) && $this->error('请先上传用户头像');
        empty($user['exam']) && $this->error('请先选择考试');
        //将用户的头像保存到本地
        $user_dir = 'uploads/user';
        if (!file_exists($user_dir)){
           mkdir($user_dir,0777,true);
        }
        $user_image = $user_dir.'/'.$user['id'].'.png';
        file_put_contents($user_image,file_get_contents($user['image']));
        createRoundImg($user_image);
        \think\Image::open($user_image)->thumb(73,73,\think\Image::THUMB_CENTER)->save($user_image);

        $image = \think\Image::open(ROOT_PATH.'public/assets/img/poster_qr_bg1.png');
        $path_ttf = ROOT_PATH.'public/assets/fonts/PingFang.ttf';
        // 我的二维码
        $qrCode = new QrCode();
        $qrCode
           ->setText($user['id'])
           ->setSize(210)
           ->setPadding(10)
           ->setErrorCorrection('high')
           ->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
           ->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0])
           ->setLabelFontSize(16)
           ->setImageType(QrCode::IMAGE_TYPE_PNG);
        $user_code = $user_dir.'/qrcode_'.$user['id'].'.png';
        // save it to a file
        $qrCode->save($user_code);
        $user_poster = $user_dir.'/poster_'.$user['id'].'.png';
        $exam_name = $user['exam'][0]['name'];
        $desc = "我正在“精工筑匠”\n学习“{$exam_name}\n来和我一起学习吧!";
        $image->text('我的海报',$path_ttf,14,'#ffffff',[150,54])
           ->water(ROOT_PATH.'public/assets/img/poster_qr_bg2.png',[11,158])
           ->water(ROOT_PATH.'public/'.$user_code,[73,242])
           ->text('扫描二维码下载APP',$path_ttf,12,'#06121F',[120,486])
           ->text($desc,$path_ttf,12,'#ffffff',[45,594])
           ->water($user_image,[260,590])
           ->save($user_poster);
        // 删除头像
        is_file($user_image) && @unlink($user_image);
        // 删除二维码
        is_file($user_code) && @unlink($user_code);
        $url = request()->domain().'/'.$user_poster;
        $this->success('成功',compact('url'));
    }

    /**
     * @ApiWeigh (57)
     * @ApiTitle    (充值积分-套餐)
     * @ApiSummary  (充值积分-套餐)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599017563",
        "data": "积分说明" //积分说明内容
    })
     */
    public function scoreSpec()
    {
        $list = ScoreSpec::select();
        $score_recharge_price = Db::name('mobile_config')->where('id',1)->value('score_recharge_price');
        $this->success('成功', compact('list','score_recharge_price'));
    }

    /**
     * @ApiWeigh (55)
     * @ApiTitle    (积分充值预览)
     * @ApiSummary  (积分充值预览)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="score_spec_id", type="int", required=false, description="套餐ID")
     * @ApiParams (name="score", type="int", required=false, description="自定义积分")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599046220",
        "data": {
            "id": 1, //试卷ID
            "title": "测试试卷", //试卷标题
            "year": 2015, //年费(单位:年)
            "time": 100, //答题时间(单位:分)
            "pass_score": 80, //合格分数
            "description": "这个还行", //试卷描述
            "do_num": 10, //回答人数
            "full_score": 100 //试卷分数(单位:分)
        }
    })
     */
    public function scoreRechargeView()
    {
        $param = $this->request->param();
        $model = new ScoreOrder;
        if(!$order = $model->payView($this->auth->getUser(),$param)){
            $this->error($model->getError(),null,$model->getCode());
        }
        $this->success(__('成功'),$order);
    }

    /**
     * @ApiWeigh (53)
     * @ApiTitle    (充值积分)
     * @ApiSummary  (充值积分)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="score_spec_id", type="int", required=false, description="积分套餐ID")
     * @ApiParams (name="score", type="int", required=false, description="自定义积分")
     * @ApiParams (name="pay_type", type="string", required=true, description="支付方式:wechat=微信,alipay=支付宝")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599017563",
        "data": "积分说明" //积分说明内容
    })
     */
    public function scoreRecharge()
    {
    	$param = $this->request->param();
    	$model = new ScoreOrder;
        if(!$order = $model->payView($this->auth->getUser(),$param)){
            $this->error($model->getError(),null,$model->getCode());
        }
        if (!$param['pay_type'] || !in_array($param['pay_type'], ['alipay', 'wechat'])) {
            $this->error("请选择支付方式");
        }
        // 创建订单
        $model->add($this->auth->getUser(), $order, $param['pay_type']);
        // 零元直接支付成功
        if($model['pay_price'] <= 0){
            (new Notify)->notifyScoreZero($model['order_sn'],$model['pay_price'],$param['pay_type']);
            $this->success('成功',[]);
        }
        //回调链接
        $notifyurl = $this->request->root(true) . '/mobile/notify/notifyScore/paytype/' . $param['pay_type'];
        // $model['pay_price'] = 0.01; //测试金额
        $payment = Service::submitOrder($model['pay_price'], $model['order_sn'], $param['pay_type'], '积分', $notifyurl, null, 'app');
        $this->success('成功',$payment);
    }

    /**
     * @ApiWeigh (51)
     * @ApiTitle    (我的收藏-题目)
     * @ApiSummary  (我的收藏-题目)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600162242",
        "data": {
            "total": 1, // 题目总数
            "list": [{
                "id": 1,
                "user_id": 16, //用户ID
                "question_id": 1, //题目ID
                "createtime": "2020.09.03 19:25", //收藏时间
                "is_answer": 1, //是否已作答:0=否,1=是
                "question": { //题目信息
                    "title": "测定混凝土立方体抗压强度时,标准试件的尺寸是(      )㎜。", //题目
                    "type": "1", //题目类型:1=单选题,2=多选题,3=判断题,4=简答题
                    "target_type": "1" //题目归属类型:1=全能题库,2=模拟试题,3=历年真题,4=每日一练,5=通关密卷
                }
            }]
        }
    })
     */
    public function collectQuestionList()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $data = QuestionCollect::with(['question'])
            ->alias('a')
            ->join('mobile_question b','a.question_id = b.id')
            ->join('mobile_question_answer c','c.question_id = b.id and c.user_id = '.$this->auth->id,'left')
        	->where('a.user_id',$this->auth->id)
        	->order('a.createtime desc')
            ->field('a.*,if(c.id > 0,1,0) is_answer')
        	->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                $v['createtime'] = date('Y.m.d H:i',$v['createtime']);
                if($v->getRelation('question')){
                    $v->getRelation('question')->visible(['title','type','target_type']);
                }
            })->toArray();
        $this->success('成功', ['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiWeigh (49)
     * @ApiTitle    (我的收藏-课程)
     * @ApiSummary  (我的收藏-课程)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1600164731",
		"data": {
			"total": 1, //数据总数
			"list": [{
				"id": 1,
				"user_id": 16, //用户ID
				"course_id": 1, //课程ID
				"createtime": "2020.09.03 19:25", //收藏时间
				"course": { //课程信息
					"title": "测试课程", //课程标题
					"cover": "", //课程封面图
					"current_price": "50.00", //现价
					"original_price": "100.00" //原价
				}
			}]
		}
	})
     */
    public function collectCourseList()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $data = CourseCollect::with(['course'])
        	->where('user_id',$this->auth->id)
        	->order('createtime desc')
        	->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                $v['createtime'] = date('Y.m.d H:i',$v['createtime']);
                $v->getRelation('course')->visible(['cover','title','current_price','original_price','study_num']);
            })->toArray();
        $this->success('成功', ['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiWeigh (47)
     * @ApiTitle    (我的收藏-笔记)
     * @ApiSummary  (我的收藏-笔记)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1600165190",
		"data": {
			"total": 1, //数据总数
			"list": [{
				"id": 3, //笔记ID
				"user_id": 16, //用户ID
				"question_id": 5, //题目ID
				"content": "这就是街舞", //笔记内容
				"createtime": "2020.09.10 19:15", //收藏时间
				"updatetime": 1599736531,
				"question": { //题目信息
					"title": "测试多选", //题目标题
					"type": "2" //题目类型:1=单选题,2=多选题,3=判断题,4=简答题
				}
			}]
		}
	})
     */
    public function collectNoteList()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $data = QuestionNote::with(['question'])
        	->where('user_id',$this->auth->id)
        	->order('createtime desc')
        	->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                $v['createtime'] = date('Y.m.d H:i',$v['createtime']);
                $v->getRelation('question')->visible(['title','type']);
            })->toArray();
        $this->success('成功', ['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiWeigh (45)
     * @ApiTitle    (我的收藏-笔记-删除)
     * @ApiSummary  (我的收藏-笔记-删除)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="question_note_id", type="inter", required=false, description="当前页(默认1)")
     *
     * @ApiReturn({
		"code": 1,
		"msg": "删除成功",
		"time": "1600165190",
		"data": null
	})
     */
    public function noteDelete()
    {
        $question_note_id = $this->request->param('question_note_id');
        empty($question_note_id) && $this->error('缺少必需参数');
        $info = QuestionNote::get($question_note_id);
        empty($info) && $this->error('笔记信息不存在');
        $info->delete();
        $this->success('删除成功');
    }

    /**
     * @ApiWeigh (44)
     * @ApiTitle    (消息)
     * @ApiSummary  (消息)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602813893",
        "data": {
            "total": 1, //数据总数
            "list": [{
                "id": 7, //消息ID
                "title": "这是个消息", //消息标题
                "is_read": "1", //是否已读:0=否,1=是
                "createtime": "2020.09.12 20:45" //发送时间
            }]
        }
    })
     */
    public function messageList()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $data = Message::where('user_id',$this->auth->id)
        	->order('createtime desc')
        	->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                $v['createtime'] = date('Y.m.d H:i',$v['createtime']);
                $v->visible(['id','title','is_read','createtime']);
            })->toArray();
        $this->success('成功', ['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiWeigh (43)
     * @ApiTitle    (消息-一键已读)
     * @ApiSummary  (消息-一键已读)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600167138",
        "data": {
            "total": 1, //数据总数
            "list": [{
                "id": 7, //消息ID
                "title": "这是个消息", //消息标题
                "createtime": "2020.09.12 20:45" //发送时间
            }]
        }
    })
     */
    public function allRead()
    {
        Message::where('user_id',$this->auth->id)->update(['is_read'=>'1']);
        $this->success('成功');
    }

    /**
     * @ApiWeigh (43)
     * @ApiTitle    (消息-详情)
     * @ApiSummary  (消息-详情)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="message_id", type="inter", required=true, description="消息ID")
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1600167441",
		"data": {
			"id": 7, //消息ID
			"user_id": 16, //用户ID
			"title": "这是个消息", //消息标题
			"content": "这个消息还不错Q", //消息内容
			"is_read": "1", //是否已读:0=否,1=是
			"createtime": 1599914736,
			"updatetime": 1600167441
		}
	})
     */
    public function messageInfo()
    {
        $message_id = $this->request->param('message_id');
        empty($message_id) && $this->error('缺少必需参数');
        $info = Message::get($message_id);
        empty($info) && $this->error('消息不存在');
        $info->save(['is_read'=>'1']);
        $this->success('成功', $info);
    }

    /**
     * @ApiWeigh (41)
     * @ApiTitle    (意见反馈-错误类型)
     * @ApiSummary  (意见反馈-错误类型)
     * @ApiMethod   (POST)
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1600167441",
		"data": {
			"id": 7, //消息ID
			"user_id": 16, //用户ID
			"title": "这是个消息", //消息标题
			"content": "这个消息还不错Q", //消息内容
			"is_read": "1", //是否已读:0=否,1=是
			"createtime": 1599914736,
			"updatetime": 1600167441
		}
	})
     */
    public function feedbackWrong()
    {
        $list = Db::name('mobile_feedback_wrong')->field('id,name')->select();
        $this->success('成功', $list);
    }

    /**
     * @ApiWeigh (39)
     * @ApiTitle    (意见反馈)
     * @ApiSummary  (意见反馈)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="feedback_wrong_id", type="inter", required=true, description="错误类型ID")
     * @ApiParams   (name="content", type="string", required=true, description="反馈内容")
     *
     * @ApiReturn({
		"code": 1,
		"msg": "成功",
		"time": "1600167441",
		"data": {
			"id": 7, //消息ID
			"user_id": 16, //用户ID
			"title": "这是个消息", //消息标题
			"content": "这个消息还不错Q", //消息内容
			"is_read": "1", //是否已读:0=否,1=是
			"createtime": 1599914736,
			"updatetime": 1600167441
		}
	})
     */
    public function feedback()
    {
        $feedback_wrong_id = $this->request->param('feedback_wrong_id');
        $content = $this->request->param('content');
        empty($feedback_wrong_id) && $this->error('请选择错误类型');
        empty($content) && $this->error('请填写反馈内容');
        Feedback::create([
        	'user_id' => $this->auth->id,
        	'feedback_wrong_id' => $feedback_wrong_id,
        	'content' => $content
        ]);
        $this->success('反馈成功');
    }

    /**
     * @ApiWeigh (37)
     * @ApiTitle    (我的帖子)
     * @ApiSummary  (我的帖子)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602300901",
        "data": {
            "total": 1, //数据总数
            "list": [{
                "id": 1, //话题ID
                "title": "公司即将上市", //话题标题
                "cover": "http://qizhibang.brotop.cn/uploads/20201009/9bc002db9517fe79f93478550a979768.jpg", //封面图
                "content": "他咯土佐玉木桶浴", //话题内容
                "good_num": 3, //点赞量
                "appraise_num": 3, //评价量
                "download_num": 0, //下载量
                "createtime": "2020.09.29 09:11", //发布时间
                "user": { //发布者信息
                    "id": 15, //用户ID
                    "nickname": "", //昵称
                    "image": "" //头像
                },
                "imgs": [ //发布内容图片
                    "http://qizhibang.brotop.cn/uploads/20201010/dd2b86d8186f0e89735798d6f9a8f56c.jpg"
                ]
            }]
        }
    })
     */
    public function topicList()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $data = Topic::with(['user'])
            ->withCount(['good'=>'good_num'])
            ->withCount(['appraise'=>'appraise_num'])
            ->where('status','1')
        	->where('user_id',$this->auth->id)
        	->order('createtime desc')
        	->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                // 发布时间格式化
                $v->createtime = date('Y.m.d H:i',$v->createtime);
                // 过滤标签
                $content1 = htmlspecialchars_decode($v->content);
                $content2 = str_replace(['&nbsp;','&emsp;'],['',''],$content1);
                $v->content = strip_tags($content2);
                // 拼装图片
                $imgs = str_replace('\\','',strip_tags($content2, '<img>'));
                //$matches[1] 为图片路径数组
                preg_match_all('/\<img\s+src\=\"([\w:\/\.]+)\"/', $imgs, $matches);
                // 不小于3张就显示3张,小于3张就显示1张图片
                $v->imgs = count($matches[1]) >=3 ? array_slice($matches[1],0,3) : (count($matches[1]) >=1 ? array_slice($matches[1],0,1) : []);
                // 显示数据
                $v->visible(['id','title','cover','content','createtime','download_num','user','good_num','appraise_num'])->append(['imgs']);
                $v->getRelation('user')->visible(['id','image','nickname']);
            })->toArray();
        $this->success('成功', ['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiWeigh (36)
     * @ApiTitle    (我的帖子-删除)
     * @ApiSummary  (我的帖子-删除)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="topic_id", type="inter", required=false, description="话题ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602300901",
        "data": null
    })
     */
    public function topicDel()
    {
        $topic_id = $this->request->param('topic_id');
        empty($topic_id) && $this->error('缺少必需参数');
        $info = Topic::get(['id'=>$topic_id,'user_id'=>$this->auth->id]);
        empty($info) && $this->error('话题信息不存在');
        Db::startTrans();
        try {
            // 删除点赞
            $info->good()->delete();
            // 删除评论点赞
            TopicAppraiseGood::where('topic_appraise_id','in',array_column($info->appraise,'id'))->delete();
            // 删除评论
            $info->appraise()->delete();
            // 删除附件
            $info->attachment()->delete();
            // 删除话题信息
            $info->delete();
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('删除帖子成功');
    }

    /**
     * @ApiWeigh (35)
     * @ApiTitle    (我的帖子-@我的)
     * @ApiSummary  (我的帖子-@我的)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602334544",
        "data": {
            "total": 3, //数据总数
            "list": [{
                "id": 4, //评论ID
                "content": "这就是街舞,say hei", //评论内容
                "createtime": "2020.10.10 20:55", //评论时间
                "user": { //评论者信息
                    "id": 15, //用户ID
                    "nickname": "" //真实姓名
                },
                "topic": { //话题信息
                    "id": 1, //话题ID
                    "title": "公司即将上市" //话题标题
                }
            }]
        }
    })
     */
    public function topicCueMe()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        // 评论我的文章的评论
        $id_arr1 = TopicAppraise::alias('ta')
            ->join('mobile_topic t','t.id = ta.topic_id')
            ->where('ta.pid',0)
            ->where('ta.is_replied','0')
            ->column('ta.id');
        // @我的评论
        $id_arr2 = TopicAppraise::alias('ta')
            ->join('mobile_topic_appraise ta1','ta1.id = ta.cue_appraise_id')
            ->where('ta1.user_id',$this->auth->id)
            ->where('ta.is_replied','0')
            ->column('ta.id');
        $id_arr = array_unique(array_merge($id_arr1, $id_arr2));
        $data = TopicAppraise::with(['user','topic'])
        	->where('id','in',$id_arr)
        	->order('createtime desc')
        	->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                // 评论时间
                $v->createtime = date('Y.m.d H:i',$v->createtime);
                $v->visible(['id','content','createtime','user','topic']);
                $v->getRelation('user')->visible(['id','nickname']);
                $v->getRelation('topic')->visible(['id','title']);
            })->toArray();
        $this->success('成功', ['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiWeigh (33)
     * @ApiTitle    (我的帖子-@我的-回复)
     * @ApiSummary  (我的帖子-@我的-回复)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="cue_appraise_id", type="int", required=true, description="被@评论ID")
     * @ApiParams (name="content", type="int", required=true, description="评论内容")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1600084253",
        "data": null
    })
     */
    public function appraiseReply(){
        $cue_appraise_id = $this->request->param('cue_appraise_id');
        $content = $this->request->param('content');
        empty($cue_appraise_id) && $this->error('缺少必需参数');
        empty($content) && $this->error('请填写评论内容');
        $info = TopicAppraise::get($cue_appraise_id);
        empty($info) && $this->error('评论不存在');
        $pid = $info['pid'] > 0 ? $info['pid'] : $info['id'];
        Db::startTrans();
        try {
            // 添加回复
            TopicAppraise::create([
                'topic_id' => $info['topic_id'],
                'pid' => $pid,
                'user_id' => $this->auth->id,
                'cue_appraise_id' => $cue_appraise_id,
                'content' => $content
            ]);
            // 状态变为已被回复
            $info->is_replied = '1';
            $info->save();
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('回复成功');
    }

    /**
     * @ApiWeigh (31)
     * @ApiTitle    (我的求职-我发布的)
     * @ApiSummary  (我的求职-我发布的)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     * @ApiParams   (name="flag", type="inter", required=true, description="0=全部,1=尚无意向,2=已被下载")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602412497",
        "data": {
            "total": 1, //总条数
            "per_page": 15,
            "current_page": 1,
            "last_page": 1,
            "data": [{
                "id": 2, //职位ID
                "name": "怎么说", //职位名称
                "type": "1", //职位类型
                "salary": "9753.20", //工资
                "start_time": "2020.10.11", //开始工作时间
                "end_time": "2020.10.11", //结束工作时间
                "address": "测试地址", //地址
                "mobile": "15133120361", //电话
                "resume": "", //简历文件路径
                "resume_name": "", //简历原始名称
                "type_text": "全职", //职位类型说明
                "qualification_arr": [] //资质证明
            }]
        }
    })
     */
    public function userJob()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $flag = $this->request->param('flag');
        $where['user_id'] = $this->auth->id;
        $where['status'] = '1';
        switch ($flag) {
            case '1':
                $where['is_download'] = '0';
                break;
            case '2':
                $where['is_download'] = '1';
                break;
            default:
                break;
        }
        $data = UserJob::where($where)
            ->field('id,name,type,salary,start_time,end_time,address,phone mobile,resume,resume_name,qualification')
            ->order('createtime desc')
            ->paginate($page_num,false,['page'=>$page])
            ->toArray();
        $this->success('成功', $data);
    }

    /**
     * @ApiWeigh (30)
     * @ApiTitle    (我的求职-我发布的-详情)
     * @ApiSummary  (我的求职-我发布的-详情)
     * @ApiMethod   (POST)
     *
     * @ApiParams   (name="user_job_id", type="inter", required=false, description="求职ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602835489",
        "data": {
            "id": 2, //求职ID
            "user_id": 15,
            "name": "怎么说", //职位
            "type": "1",
            "mobile": "15133120361",
            "start_time": "2020.10.11",
            "end_time": "2020.10.11",
            "salary": "9753.20",
            "address": "测试地址",
            "user_job_ability_ids": "3,4",
            "qualification": "",
            "resume": "http://qizhibang.brotop.cn456", //简历地址
            "resume_name": "", //简历名称
            "status": "1",
            "is_download": "0",
            "createtime": 1602408183,
            "updatetime": 1602480359,
            "weigh": 0,
            "type_text": "全职",
            "qualification_arr": []
        }
    })
     */
    public function userJobInfo()
    {
        $user_job_id = $this->request->param('user_job_id');
        empty($user_job_id) && $this->error('缺少必需参数');
        $info = UserJob::get($user_job_id);
        empty($info) && $this->error('求职信息不存在');
        $this->success('成功', $info);
    }

    /**
     * @ApiWeigh (29)
     * @ApiTitle    (我的求职-我发布的-编辑)
     * @ApiSummary  (我的求职-我发布的-编辑)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="user_job_id", type="string", required=true, description="求职ID")
     * @ApiParams (name="name", type="string", required=true, description="岗位名称")
     * @ApiParams (name="type", type="string", required=true, description="岗位类型:1=全职,2=兼职,3=其他")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="start_time", type="string", required=true, description="开始工作日期")
     * @ApiParams (name="end_time", type="string", required=true, description="结束工作日期")
     * @ApiParams (name="salary", type="string", required=true, description="薪资待遇")
     * @ApiParams (name="address", type="string", required=true, description="期望工作地点")
     * @ApiParams (name="user_job_ability_ids", type="string", required=true, description="资质能力")
     * @ApiParams (name="qualification", type="string", required=true, description="资质证明(多文件用英文逗号隔开)")
     * @ApiParams (name="resume", type="string", required=true, description="简历文件路径")
     *
     * @ApiReturn({
        "code": 1, 
        "msg": "登录成功", 
        "time": "1600498819", 
        "data": null
    })
     */
    public function userJobEdit()
    {
        $post = $this->request->param();
        empty($post['user_job_id']) && $this->error('缺少必需参数');
        empty($post['name']) && $this->error('请输入岗位名称');
        empty($post['type']) && $this->error('请选择岗位类型');
        empty($post['mobile']) && $this->error('请输入手机号');
        empty($post['start_time']) && $this->error('请选择开始工作日期');
        empty($post['end_time']) && $this->error('请选择结束工作日期');
        empty($post['salary']) && $this->error('请输入薪资待遇');
        empty($post['address']) && $this->error('请输入期望工作地点');
        empty($post['user_job_ability_ids']) && $this->error('请选择资质能力');
        empty($post['resume']) && $this->error('请选择简历');
        $info = UserJob::get($post['user_job_id']);
        empty($info) && $this->error('职位信息不存在');
        // 编辑后,需要重新审核
        $info->allowField(true)->save(array_merge([
            'status' => '0'
        ],$post));
        $this->success('编辑求职成功');
    }

    /**
     * @ApiWeigh (27)
     * @ApiTitle    (我的求职-我发布的-删除)
     * @ApiSummary  (我的求职-我发布的-删除)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="user_job_id", type="inter", required=false, description="求职ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602234925",
        "data": null
    })
     */
    public function userJobDel()
    {
        $user_job_id = $this->request->param('user_job_id');
        empty($user_job_id) && $this->error('缺少必需参数');
        $info = UserJob::get(['user_id'=>$this->auth->id,'id'=>$user_job_id]);
        empty($info) && $this->error('求职信息不存在');
        Db::startTrans();
        try {
            // 删除简历下载记录
            $info->download()->delete();
            // 删除求职信息
            $info->delete();
            Db::commit();
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('删除成功');
    }

    /**
     * @ApiWeigh (25)
     * @ApiTitle    (我的求职-我投递的)
     * @ApiSummary  (我的求职-我投递的)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     * @ApiParams   (name="flag", type="inter", required=true, description="0=全部,1=尚无意向,2=已被下载")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602406820",
        "data": {
            "total": 1, //总条数
            "per_page": 15,
            "current_page": 1,
            "last_page": 1,
            "data": [{
                "id": 1, //职位ID
                "name": "123", //职位名称
                "type": "1", //职位类型
                "salary": "9753.20", //工资
                "start_time": "2020.10.11", //开始工作时间
                "end_time": "2020.10.11", //结束工作时间
                "address": "测试地址", //地址
                "is_view": "0", //是否已被下载:0=否,1=是
                "type_text": "全职" //职位类型说明
            }]
        }
    })
     */
    public function companyJob()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $flag = $this->request->param('flag');
        $where['cj.status'] = '1';
        switch ($flag) {
            case '1':
                $where['cjr.is_view'] = '0';
                break;
            case '2':
                $where['cjr.is_view'] = '1';
                break;
            default:
                break;
        }
        $data = CompanyJob::alias('cj')
            ->join('mobile_company_job_resume cjr','cjr.company_job_id = cj.id and cjr.user_id = '.$this->auth->id)
            ->where($where)
            ->field('cj.id,cj.name,cj.type,cj.salary,cj.start_time,cj.end_time,cj.address,cjr.is_view')
            ->order('cjr.createtime desc')
            ->paginate($page_num,false,['page'=>$page])
            ->toArray();
        $this->success('成功', $data);
    }

    /**
     * @ApiWeigh (10)
     * @ApiTitle    (常见问题)
     * @ApiSummary  (常见问题)
     * @ApiMethod   (POST)
     *
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="page_num", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602814874",
        "data": {
            "total": 1, //数据总数
            "list": [{
                "id": 7, //问题ID
                "title": "常见问题测试", //标题
                "createtime": "2020.09.12 20:45" //发布时间
            }]
        }
    })
     */
    public function problemList()
    {
        $page = $this->request->param('page', 1, 'intval');
        $page_num = $this->request->param('page_num', 10, 'intval');
        $data = Problem::order('createtime desc')
        	->paginate($page_num,false,['page'=>$page])
            ->each(function($v){
                $v['createtime'] = date('Y.m.d H:i',$v['createtime']);
                $v->visible(['id','title','createtime']);
            })->toArray();
        $this->success('成功', ['total'=>$data['total'],'list'=>$data['data']]);
    }

    /**
     * @ApiWeigh (9)
     * @ApiTitle    (常见问题-详情)
     * @ApiSummary  (常见问题-详情)
     * @ApiMethod   (POST)
     *
     * @ApiParams   (name="problem_id", type="inter", required=true, description="问题ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1602815306",
        "data": {
            "id": 7, //问题ID
            "title": "常见问题测试", //问题标题
            "content": "<p>常见问题测试内容</p>", //问题内容
            "createtime": 1599914736,
            "updatetime": 1599914736
        }
    })
     */
    public function problemInfo()
    {
        $problem_id = $this->request->param('problem_id');
        empty($problem_id) && $this->error('缺少必需参数');
        $info = Problem::get($problem_id);
        empty($info) && $this->error('问题不存在');
        $this->success('成功', $info);
    }

    /**
     * @ApiWeigh (8)
     * @ApiTitle    (我自己的学习列表)
     * @ApiSummary  (我自己的学习列表)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="page", type="inter", required=false, description="当前页(默认1)")
     * @ApiParams   (name="pageNum", type="inter", required=false, description="每页显示数据个数(默认10)")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1571492001",
        "data": {
            "total_num"://总条数
            "info":[
                "id"://ID
                "examname"://考试名称
                "class_hour"://所需课时
                "finish_hour"://完成课时
                "image"://图片
                "expirationtime"://截止日期
            ]
        }
    })
     */
    public function study_list()
    {
        $erzi = Db::name('type')->field('id,pid')->select();
        if(!empty($erzi)){
            $erzi_id = array_column($erzi,"id");
            $sunzi = Db::name('type')->where(['pid'=>['in',$erzi_id]])->field("id")->select();
            $sunzi_id = array_column($sunzi,"id");
            $son = array_merge($sunzi_id,$erzi_id);
            $where['type_id'] = ['in',$son];
        }
        $page = $this->request->param('page', 1, 'intval');
        $pageNum = $this->request->param('pageNum', 10, 'intval');
        $qiniu = get_addon_config('qiniu')['cdnurl'];
        $user_id = $this->auth->id;
        $where['expirationtime'] = ['>',time()];
        $data['total_num'] = Db::name('study')
            ->where($where)
            ->count();
        $data['info'] = Db::name('study')
            ->field('updatetime,createtime',true)
            ->where($where)
            ->order('id desc')
            ->page($page,$pageNum)
            ->select();
        foreach ($data['info'] as &$v){
            if(empty($user_id)){
                $v['finish_hour'] = 0;
            }else{
                $finish_hour = Db::name('study_class')
                    ->alias('a')
                    ->join('classes b','a.class_id = b.id')
                    ->where('a.third_id',$user_id)
                    ->where('a.study_id',$v['id'])
                    ->where('a.status',2)
                    ->field('sum(b.class_hour) as finsh_hour')
                    ->find();
                if(empty($finish_hour['finsh_hour'])){
                    $v['finish_hour'] = 0;
                }else{
                    $v['finish_hour'] = $finish_hour['finsh_hour'];
                }

            }
            $v['image'] = $qiniu.$v['image'];
            $v['expirationtime'] = date('Y-m-d H:i:s',$v['expirationtime']);
        }
        $this->success('success',$data);
    }

    /**
     * @ApiWeigh (7)
     * @ApiTitle    (内购充值列表)
     * @ApiSummary  (内购充值列表)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1614425430",
        "data": {
            "money": "0.00", //当前余额
            "list": [{
                "id": 6, //充值产品ID
                "name": "308元", //充值名称
                "price": "308.00", //充值金额
                "product_id": "123", //苹果内购产品ID
                "createtime": 1614423262,
                "updatetime": 1614423262
        }]
    }
    })
     */
    public function rechargeList()
    {
        $money = $this->auth->money;
        $list = Recharge::all();
        $this->success('成功', compact('money','list'));
    }

    /**
     * @ApiWeigh (6)
     * @ApiTitle    (充值)
     * @ApiSummary  (充值)
     * @ApiMethod   (POST)
     *
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams (name="recharge_id", type="int", required=false, description="充值产品ID")
     *
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1599017563",
        "data": "积分说明" //积分说明内容
    })
     */
    public function recharge()
    {
        $param = $this->request->param();
        $model = new RechargeOrder;
        if(!$order = $model->payView($param)){
            $this->error($model->getError(),null,$model->getCode());
        }
        // 创建订单
        $model->add($this->auth->getUser(), $order, 'ios');
        $this->success('成功',['order_sn'=>$model['order_sn']]);
    }
}