刘远航 4 lat temu
rodzic
commit
811c0b8a14
96 zmienionych plików z 8951 dodań i 0 usunięć
  1. 10 0
      app/Admin/Controllers/AuthController.php
  2. 67 0
      app/Admin/Controllers/ExampleController.php
  3. 34 0
      app/Admin/Controllers/HomeController.php
  4. 20 0
      app/Admin/bootstrap.php
  5. 16 0
      app/Admin/routes.php
  6. 42 0
      app/Console/Kernel.php
  7. 14 0
      app/Exceptions/ExitOutException.php
  8. 66 0
      app/Exceptions/Handler.php
  9. 325 0
      app/Helpers/functions.php
  10. 44 0
      app/Http/Controllers/Api/V1/ArticleController.php
  11. 22 0
      app/Http/Controllers/Api/V1/AuthController.php
  12. 53 0
      app/Http/Controllers/Api/V1/CollectionController.php
  13. 114 0
      app/Http/Controllers/Api/V1/CommonController.php
  14. 131 0
      app/Http/Controllers/Api/V1/DocterController.php
  15. 32 0
      app/Http/Controllers/Api/V1/EvaluateController.php
  16. 49 0
      app/Http/Controllers/Api/V1/NurseController.php
  17. 524 0
      app/Http/Controllers/Api/V1/OrderController.php
  18. 60 0
      app/Http/Controllers/Api/V1/PatientController.php
  19. 93 0
      app/Http/Controllers/Api/V1/PayCallbackController.php
  20. 33 0
      app/Http/Controllers/Api/V1/ServicePackController.php
  21. 35 0
      app/Http/Controllers/Api/V1/SuggestController.php
  22. 82 0
      app/Http/Controllers/Api/V1/UserController.php
  23. 44 0
      app/Http/Controllers/Api/V1/VaccineController.php
  24. 33 0
      app/Http/Controllers/Api/V2/ArticleController.php
  25. 22 0
      app/Http/Controllers/Api/V2/AuthController.php
  26. 45 0
      app/Http/Controllers/Api/V2/CallPhoneController.php
  27. 1124 0
      app/Http/Controllers/Api/V2/CommonController.php
  28. 118 0
      app/Http/Controllers/Api/V2/DocterMessageController.php
  29. 3158 0
      app/Http/Controllers/Api/V2/DoctorController.php
  30. 49 0
      app/Http/Controllers/Api/V2/NurseController.php
  31. 679 0
      app/Http/Controllers/Api/V2/PatientController.php
  32. 49 0
      app/Http/Controllers/Api/V2/PhoneCallController.php
  33. 45 0
      app/Http/Controllers/Api/V2/ServiceApplyController.php
  34. 159 0
      app/Http/Controllers/Api/V2/SuggestController.php
  35. 59 0
      app/Http/Controllers/Api/V2/UserController.php
  36. 42 0
      app/Http/Controllers/Controller.php
  37. 81 0
      app/Http/Kernel.php
  38. 21 0
      app/Http/Middleware/Authenticate.php
  39. 17 0
      app/Http/Middleware/CheckForMaintenanceMode.php
  40. 17 0
      app/Http/Middleware/EncryptCookies.php
  41. 26 0
      app/Http/Middleware/RedirectIfAuthenticated.php
  42. 18 0
      app/Http/Middleware/TrimStrings.php
  43. 23 0
      app/Http/Middleware/TrustProxies.php
  44. 24 0
      app/Http/Middleware/VerifyCsrfToken.php
  45. 18 0
      app/Models/Areas.php
  46. 26 0
      app/Models/Article.php
  47. 16 0
      app/Models/Axb.php
  48. 18 0
      app/Models/BaseModel.php
  49. 21 0
      app/Models/CallLog.php
  50. 15 0
      app/Models/CallPhone.php
  51. 26 0
      app/Models/Collection.php
  52. 14 0
      app/Models/CouponType.php
  53. 36 0
      app/Models/Docter.php
  54. 15 0
      app/Models/DocterLable.php
  55. 15 0
      app/Models/DocterMessage.php
  56. 28 0
      app/Models/DocterOrganization.php
  57. 14 0
      app/Models/DocterServiceTimes.php
  58. 19 0
      app/Models/DocterSetting.php
  59. 14 0
      app/Models/DocterTimes.php
  60. 39 0
      app/Models/DocterUser.php
  61. 22 0
      app/Models/Evaluate.php
  62. 15 0
      app/Models/ImMessage.php
  63. 14 0
      app/Models/Nurse.php
  64. 14 0
      app/Models/Office.php
  65. 54 0
      app/Models/Order.php
  66. 14 0
      app/Models/OrderNurse.php
  67. 14 0
      app/Models/OrderPack.php
  68. 21 0
      app/Models/OrderPatient.php
  69. 14 0
      app/Models/OrderVaccine.php
  70. 21 0
      app/Models/Organization.php
  71. 15 0
      app/Models/Patient.php
  72. 14 0
      app/Models/Payment.php
  73. 14 0
      app/Models/Qualification.php
  74. 17 0
      app/Models/Schedule.php
  75. 23 0
      app/Models/SchedulePeriod.php
  76. 15 0
      app/Models/SelfSchedule.php
  77. 15 0
      app/Models/ServiceApply.php
  78. 17 0
      app/Models/ServicePack.php
  79. 46 0
      app/Models/Suggest.php
  80. 16 0
      app/Models/SuggestDetail.php
  81. 16 0
      app/Models/SystemConfig.php
  82. 17 0
      app/Models/Team.php
  83. 14 0
      app/Models/TimePeriod.php
  84. 100 0
      app/Models/User.php
  85. 14 0
      app/Models/UserBalanceLog.php
  86. 56 0
      app/Models/UserCoupon.php
  87. 15 0
      app/Models/UserDocter.php
  88. 14 0
      app/Models/UserMessages.php
  89. 14 0
      app/Models/Vaccine.php
  90. 18 0
      app/Models/WeekSchedule.php
  91. 28 0
      app/Providers/AppServiceProvider.php
  92. 30 0
      app/Providers/AuthServiceProvider.php
  93. 21 0
      app/Providers/BroadcastServiceProvider.php
  94. 34 0
      app/Providers/EventServiceProvider.php
  95. 73 0
      app/Providers/RouteServiceProvider.php
  96. 39 0
      app/User.php

+ 10 - 0
app/Admin/Controllers/AuthController.php

xqd
@@ -0,0 +1,10 @@
+<?php
+
+namespace App\Admin\Controllers;
+
+use Encore\Admin\Http\Controllers\AuthController as BaseAuthController;
+
+class AuthController extends BaseAuthController
+{
+
+}

+ 67 - 0
app/Admin/Controllers/ExampleController.php

xqd
@@ -0,0 +1,67 @@
+<?php
+
+namespace App\Admin\Controllers;
+
+use Encore\Admin\Http\Controllers\AdminController;
+use Encore\Admin\Form;
+use Encore\Admin\Table;
+use Encore\Admin\Show;
+
+class ExampleController extends AdminController
+{
+    /**
+     * Title for current resource.
+     *
+     * @var string
+     */
+    protected $title = 'Example controller';
+
+    /**
+     * Make a table builder.
+     *
+     * @return Table
+     */
+    protected function table()
+    {
+        $table = new Table(new ExampleModel);
+
+        $table->column('id', __('ID'))->sortable();
+        $table->column('created_at', __('Created at'));
+        $table->column('updated_at', __('Updated at'));
+
+        return $table;
+    }
+
+    /**
+     * Make a show builder.
+     *
+     * @param mixed   $id
+     * @return Show
+     */
+    protected function detail($id)
+    {
+        $show = new Show(ExampleModel::findOrFail($id));
+
+        $show->field('id', __('ID'));
+        $show->field('created_at', __('Created at'));
+        $show->field('updated_at', __('Updated at'));
+
+        return $show;
+    }
+
+    /**
+     * Make a form builder.
+     *
+     * @return Form
+     */
+    protected function form()
+    {
+        $form = new Form(new ExampleModel);
+
+        $form->display('id', __('ID'));
+        $form->display('created_at', __('Created At'));
+        $form->display('updated_at', __('Updated At'));
+
+        return $form;
+    }
+}

+ 34 - 0
app/Admin/Controllers/HomeController.php

xqd
@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Admin\Controllers;
+
+use App\Http\Controllers\Controller;
+use Encore\Admin\Http\Controllers\Dashboard;
+use Encore\Admin\Layout\Column;
+use Encore\Admin\Layout\Content;
+use Encore\Admin\Layout\Row;
+
+class HomeController extends Controller
+{
+    public function index(Content $content)
+    {
+        return $content
+            ->title('Dashboard')
+            ->description('Description...')
+            ->row(Dashboard::title())
+            ->row(function (Row $row) {
+
+                $row->column(4, function (Column $column) {
+                    $column->append(Dashboard::environment());
+                });
+
+                $row->column(4, function (Column $column) {
+                    $column->append(Dashboard::extensions());
+                });
+
+                $row->column(4, function (Column $column) {
+                    $column->append(Dashboard::dependencies());
+                });
+            });
+    }
+}

+ 20 - 0
app/Admin/bootstrap.php

xqd
@@ -0,0 +1,20 @@
+<?php
+
+/**
+ * Laravel-admin - admin builder based on Laravel.
+ * @author z-song <https://github.com/z-song>
+ *
+ * Bootstraper for Admin.
+ *
+ * Here you can remove builtin form field:
+ * Encore\Admin\Form::forget(['map', 'editor']);
+ *
+ * Or extend custom form field:
+ * Encore\Admin\Form::extend('php', PHPEditor::class);
+ *
+ * Or require js and css assets:
+ * Admin::css('/packages/prettydocs/css/styles.css');
+ * Admin::js('/packages/prettydocs/js/main.js');
+ *
+ */
+

+ 16 - 0
app/Admin/routes.php

xqd
@@ -0,0 +1,16 @@
+<?php
+
+use Illuminate\Routing\Router;
+
+Admin::routes();
+
+Route::group([
+    'prefix'        => config('admin.route.prefix'),
+    'namespace'     => config('admin.route.namespace'),
+    'middleware'    => config('admin.route.middleware'),
+    'as'            => config('admin.route.prefix') . '.',
+], function (Router $router) {
+
+    $router->get('/', 'HomeController@index')->name('home');
+
+});

+ 42 - 0
app/Console/Kernel.php

xqd
@@ -0,0 +1,42 @@
+<?php
+
+namespace App\Console;
+
+use Illuminate\Console\Scheduling\Schedule;
+use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
+
+class Kernel extends ConsoleKernel
+{
+    /**
+     * The Artisan commands provided by your application.
+     *
+     * @var array
+     */
+    protected $commands = [
+        //
+    ];
+
+    /**
+     * Define the application's command schedule.
+     *
+     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
+     * @return void
+     */
+    protected function schedule(Schedule $schedule)
+    {
+        // $schedule->command('inspire')
+        //          ->hourly();
+    }
+
+    /**
+     * Register the commands for the application.
+     *
+     * @return void
+     */
+    protected function commands()
+    {
+        $this->load(__DIR__.'/Commands');
+
+        require base_path('routes/console.php');
+    }
+}

+ 14 - 0
app/Exceptions/ExitOutException.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-23
+ * Time: 上午10:59
+ */
+
+namespace App\Exceptions;
+
+class ExitOutException extends \Exception
+{
+
+}

+ 66 - 0
app/Exceptions/Handler.php

xqd
@@ -0,0 +1,66 @@
+<?php
+
+namespace App\Exceptions;
+
+use Exception;
+use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
+use Illuminate\Validation\ValidationException;
+
+class Handler extends ExceptionHandler
+{
+    /**
+     * A list of the exception types that are not reported.
+     *
+     * @var array
+     */
+    protected $dontReport = [
+        ExitOutException::class,
+    ];
+
+    /**
+     * A list of the inputs that are never flashed for validation exceptions.
+     *
+     * @var array
+     */
+    protected $dontFlash = [
+        'password',
+        'password_confirmation',
+    ];
+
+    /**
+     * Report or log an exception.
+     *
+     * @param  \Exception  $exception
+     * @return void
+     */
+    public function report(Exception $exception)
+    {
+        parent::report($exception);
+    }
+
+    /**
+     * Render an exception into an HTTP response.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  \Exception  $exception
+     * @return \Illuminate\Http\Response
+     */
+    public function render($request, Exception $exception)
+    {
+        //如果路由中含有“api/”,则说明是一个 api 的接口请求
+        if ($request->is("api/*")) {
+            //如果错误是 ValidationException的一个实例,说明是一个验证的错误
+            if ($exception instanceof ValidationException) {
+                return out(null, 10000, array_values($exception->errors())[0][0]);
+            }
+
+            if ($exception instanceof ExitOutException){
+                $msg = $exception->getMessage();
+                $out = json_decode($msg, true);
+                return out($out['data'], $out['status'], $out['message']);
+            }
+        }
+
+        return out(null, 500, $exception->getMessage());
+    }
+}

+ 325 - 0
app/Helpers/functions.php

xqd
@@ -0,0 +1,325 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-23
+ * Time: 上午10:56
+ */
+
+use Illuminate\Support\Facades\Log;
+use App\Exceptions\ExitOutException;
+
+//统一输出格式话的json数据
+if (!function_exists('out')) {
+    function out($data = null, $status = 0, $message = 'success', $exceptionData = false)
+    {
+        $out = ['status' => $status, 'message' => $message, 'data' => $data];
+
+        if ($exceptionData !== false) {
+            trace([$message => $exceptionData], 'error');
+        }
+
+        return response()->json($out);
+    }
+}
+
+//统一异常输出格式话的json数据
+if (!function_exists('exit_out')) {
+    function exit_out($data = null, $status = 0, $message = 'success', $exceptionData = false)
+    {
+        $out = ['status' => $status, 'message' => $message, 'data' => $data];
+
+        if ($exceptionData !== false) {
+            trace([$message => $exceptionData], 'error');
+        }
+
+        $json = json_encode($out, JSON_UNESCAPED_UNICODE);
+
+        throw new ExitOutException($json);
+    }
+}
+
+//日志记录
+if (!function_exists('trace')) {
+    function trace($log = '', $level = 'info')
+    {
+        Log::log($level, $log);
+    }
+}
+
+
+if (!function_exists('upDecimal')) {
+
+    /**
+     * 对价格进行向上取整
+     * @param $price    价格
+     * @param $decimal  保留小数位数
+     */
+    function upDecimal($price, $decimal = 2){
+        $data1 = pow(10, $decimal);
+        $data2 = ceil(bcmul($price, $data1,10));
+        $data3 = bcdiv($data2, $data1, $decimal);
+        return $data3;
+    }
+}
+
+//AES加密
+if (!function_exists('aes_encrypt')) {
+    function aes_encrypt($data)
+    {
+        if (is_array($data)) {
+            $data = json_encode($data, JSON_UNESCAPED_UNICODE);
+        }
+        $key = config('config.aes_key');
+        $iv  = config('config.aes_iv');
+
+        $cipher_text = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
+        $cipher_text = base64_encode($cipher_text);
+
+        return urlencode($cipher_text);
+    }
+}
+
+//AES解密
+if (!function_exists('aes_decrypt')) {
+    function aes_decrypt($encryptData)
+    {
+        $encryptData = urldecode($encryptData);
+        $encryptData = base64_decode($encryptData);
+
+        $key = config('config.aes_key');
+        $iv  = config('config.aes_iv');
+
+        $original_plaintext = openssl_decrypt($encryptData, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
+
+        return json_decode($original_plaintext, true);
+    }
+}
+
+//获取distance的sql字段
+if (!function_exists('get_distance_field')) {
+    function get_distance_field($latitude, $longitude)
+    {
+        if (empty($latitude) || empty($longitude)) {
+            return '999999999 distance';
+        }
+
+        return 'if(longitude=0 and latitude=0,999999999,round(6378.138*2*asin(sqrt(pow(sin( (' . $latitude . '*pi()/180-latitude*pi()/180)/2),2)+cos(' . $latitude . '*pi()/180)*cos(latitude*pi()/180)* pow(sin((' . $longitude . '*pi()/180-longitude*pi()/180)/2),2)))*1000)) distance';
+    }
+}
+
+//构建单号
+if (!function_exists('build_sn')) {
+    function build_sn($id, $len = 2, $prefix = '')
+    {
+        $idx = 0 - $len;
+        $suffix = substr($id, $idx);
+        $suffix = str_pad($suffix, $len, '0', STR_PAD_LEFT);
+
+        $sn = $prefix.substr(date('YmdHis'), 2).$suffix;
+
+        return $sn;
+    }
+}
+
+
+if (!function_exists('numBirthday')){
+    /**
+     * 生日转年龄
+     * @author Yuanhang Liu & Xiaoyun Liu
+     * @param $birthday 2020-10-14 00:48
+     * @return string
+     */
+    function numBirthday($birthday){
+
+        if ($birthday){
+            try {
+                list($year,$month,$day) = explode("-",$birthday);
+                $year_diff = (date("Y") - $year)>0?date("Y") - $year.'岁':'';
+                $month_diff = (date("m") - $month)>0?date("m") - $month.'个月':'';
+                $day_diff  = (date("d") - $day)>0?date("d") - $day.'天':'';
+                if ($day_diff < 0 || $month_diff < 0)
+                    $year_diff--;
+                return $year_diff.$month_diff.$day_diff ;
+            }catch (Exception $e){
+
+                return '';
+            }
+
+        }else{
+            return '';
+        }
+
+    }
+}
+if (!function_exists('getWeek')){
+    /**
+     * 获取当日周几
+     * @author Yuanhang Liu & Xiaoyun Liu
+     * @param $birthday 2020-10-14 00:48
+     * @return string
+     */
+    function getWeek($date){
+
+        $weekday= "今天是星期" . mb_substr( "日一二三四五六",$date,1,"utf-8" );
+        return $weekday ;
+    }
+}
+
+//发送短信
+if (!function_exists('send_sms')) {
+    function send_sms($phone, $templateKey, $templateParam = [])
+    {
+        $sms_config = config('config.aly_sms');
+        //是否启用https
+        $security = false;
+        $params = [];
+        $params["PhoneNumbers"] = $phone;
+        $params["SignName"] = $sms_config['sign_name'];
+        $params["TemplateCode"] = $sms_config[$templateKey];
+        $params['TemplateParam'] = $templateParam;
+
+        if (is_array($params["TemplateParam"])) {
+            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
+        }
+
+        $content = aly_sm_request(
+            $sms_config['access_key'],
+            $sms_config['access_secret'],
+            "dysmsapi.aliyuncs.com",
+            array_merge($params, array(
+                "RegionId" => "cn-hangzhou",
+                "Action" => "SendSms",
+                "Version" => "2017-05-25",
+            )),
+            $security
+        );
+
+        return $content;
+    }
+}
+
+if (!function_exists('aly_sm_request')) {
+    function aly_sm_request($accessKeyId, $accessKeySecret, $domain, $params, $security = false, $method = 'POST')
+    {
+        $apiParams = array_merge(array(
+            "SignatureMethod" => "HMAC-SHA1",
+            "SignatureNonce" => uniqid(mt_rand(0, 0xffff), true),
+            "SignatureVersion" => "1.0",
+            "AccessKeyId" => $accessKeyId,
+            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
+            "Format" => "JSON",
+        ), $params);
+        ksort($apiParams);
+
+        $sortedQueryStringTmp = "";
+        foreach ($apiParams as $key => $value) {
+            $sortedQueryStringTmp .= "&" . aly_sms_encode($key) . "=" . aly_sms_encode($value);
+        }
+
+        $stringToSign = "${method}&%2F&" . aly_sms_encode(substr($sortedQueryStringTmp, 1));
+
+        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&", true));
+
+        $signature = aly_sms_encode($sign);
+
+        $url = ($security ? 'https' : 'http') . "://{$domain}/";
+
+        try {
+            $content = aly_sms_fetch_content($url, $method, "Signature={$signature}{$sortedQueryStringTmp}");
+            return json_decode($content);
+        } catch (\Exception $e) {
+            return false;
+        }
+    }
+}
+
+if (!function_exists('aly_sms_encode')) {
+    function aly_sms_encode($str)
+    {
+        $res = urlencode($str);
+        $res = preg_replace("/\+/", "%20", $res);
+        $res = preg_replace("/\*/", "%2A", $res);
+        $res = preg_replace("/%7E/", "~", $res);
+        return $res;
+    }
+}
+
+if (!function_exists('aly_sms_fetch_content')) {
+    function aly_sms_fetch_content($url, $method, $body)
+    {
+        $ch = curl_init();
+
+        if ($method == 'POST') {
+            curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
+            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
+        } else {
+            $url .= '?' . $body;
+        }
+
+        curl_setopt($ch, CURLOPT_URL, $url);
+        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
+        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
+            "x-sdk-client" => "php/2.0.0"
+        ));
+
+        if (substr($url, 0, 5) == 'https') {
+            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
+            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
+        }
+
+        $rtn = curl_exec($ch);
+
+        if ($rtn === false) {
+            // 大多由设置等原因引起,一般无法保障后续逻辑正常执行,
+            // 所以这里触发的是E_USER_ERROR,会终止脚本执行,无法被try...catch捕获,需要用户排查环境、网络等故障
+            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
+        }
+        curl_close($ch);
+        return $rtn;
+    }
+
+    if (!function_exists('getDateFromList')) {
+        /**
+         * 获取指定日期段内每一天的日期
+         * @param  Date  $startdate 开始日期
+         * @param  Date  $enddate   结束日期
+         * @return Array
+         */
+        function getDateFromList($start,$end){
+            $stimestamp = strtotime($start);
+            $etimestamp = strtotime($end);
+            // 计算日期段内有多少天
+            $days = ($etimestamp-$stimestamp)/86400+1;
+            // 保存每天日期
+            $arr = [];
+            for($i=0;$i<$days;$i++){
+                $arr[] = date('Y-m-d',$stimestamp+(86400*$i));
+            }
+            return $arr;
+
+
+        }
+
+    }
+
+    if (!function_exists('numDays')){
+        /**
+         * 计算日期到现在多天天
+         * @param $date
+         * @return float
+         */
+        function numDays($date){
+            $Date_List_a1=explode("-",date('Y-m-d',time()));
+            $Date_List_a2=explode("-",$date);
+            $d1=mktime(0,0,0,$Date_List_a1[1],$Date_List_a1[2],$Date_List_a1[0]);
+            $d2=mktime(0,0,0,$Date_List_a2[1],$Date_List_a2[2],$Date_List_a2[0]);
+            $Days=round(($d1-$d2)/3600/24);
+            return $Days;
+        }
+    }
+
+
+
+}

+ 44 - 0
app/Http/Controllers/Api/V1/ArticleController.php

xqd
@@ -0,0 +1,44 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:40
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Article;
+
+class ArticleController extends AuthController
+{
+    /**
+     * 不验证路由
+     * ArticleController constructor.
+     */
+    public function __construct()
+    {
+//        parent::__construct();
+        $this->middleware('auth:api', ['except' => ['articleList']]);
+
+    }
+    public function articleList()
+    {
+
+        $data = Article::orderBy('id', 'desc')->paginate();
+
+        return out($data);
+    }
+
+    public function articleDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'article_id' => 'required|integer',
+        ]);
+
+        $data = Article::where('id', $req['article_id'])->first();
+
+        return out($data);
+    }
+}

+ 22 - 0
app/Http/Controllers/Api/V1/AuthController.php

xqd
@@ -0,0 +1,22 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-23
+ * Time: 上午11:34
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Http\Controllers\Controller;
+use App\Models\User;
+
+class AuthController extends Controller
+{
+    protected $user = null;
+
+    public function __construct()
+    {
+        $this->user = User::getUserByToken();
+    }
+}

+ 53 - 0
app/Http/Controllers/Api/V1/CollectionController.php

xqd
@@ -0,0 +1,53 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:18
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Collection;
+
+class CollectionController extends AuthController
+{
+    public function submitCollect()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'type' => 'required|in:1,2',
+            'relation_id' => 'required|integer',
+        ]);
+        $user = $this->user;
+
+        $map = [1 => 'docter_id', 2 => 'article_id'];
+        if (Collection::where('user_id', $user['id'])->where($map[$req['type']], $req['relation_id'])->count()) {
+            Collection::where('user_id', $user['id'])->where($map[$req['type']], $req['relation_id'])->delete();
+            $is_collect = 0;
+        }
+        else {
+            Collection::create([
+                'user_id' => $user['id'],
+                $map[$req['type']] => $req['relation_id']
+            ]);
+            $is_collect = 1;
+        }
+
+        return out(['is_collect' => $is_collect]);
+    }
+
+    public function collectList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'type' => 'required|in:1,2',
+        ]);
+        $user = $this->user;
+
+        $map = [1 => 'docter_id', 2 => 'article_id'];
+        $data = Collection::with(['docter', 'article'])->where('user_id', $user['id'])->where($map[$req['type']], '>', 0)->paginate();
+
+        return out($data);
+    }
+}

+ 114 - 0
app/Http/Controllers/Api/V1/CommonController.php

xqd
@@ -0,0 +1,114 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-23
+ * Time: 上午11:26
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Http\Controllers\Controller;
+use App\Models\User;
+use EasyWeChat\Factory;
+
+class CommonController extends Controller
+{
+    public function wxLogin()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'wechat_code' => 'required',
+            'nickname|昵称' => 'max:50',
+            'avatar|头像' => 'url',
+            'latitude|纬度' => 'numeric',
+            'longitude|纬度' => 'numeric',
+        ]);
+
+        $app = Factory::miniProgram(config('config.wechat_small_program'));
+        $data = $app->auth->session($req['wechat_code']);
+        if (empty($data['openid'])){
+            return out(null, 10001, '微信登录code错误');
+        }
+
+        $session_key = !empty($data['session_key']) ? $data['session_key'] : '';
+        $user = User::select(['id', 'status', 'phone', 'nickname', 'avatar'])->where('openid', $data['openid'])->first();
+        if (empty($user)){
+            $user = User::create([
+                'openid' => $data['openid'],
+                'nickname' => $req['nickname'] ?? '',
+                'avatar' => $req['avatar'] ?? '',
+                'latitude' => $req['latitude'] ?? 0,
+                'longitude' => $req['longitude'] ?? 0,
+                'session_key' => $session_key
+            ]);
+        }
+        else {
+            if ($user['status'] == 0) {
+                return out(null, 10002, '该账号已被冻结');
+            }
+
+            User::where('id', $user['id'])->update([
+                'nickname' => $req['nickname'] ?? '',
+                'avatar' => $req['avatar'] ?? '',
+                'latitude' => $req['latitude'] ?? 0,
+                'longitude' => $req['longitude'] ?? 0,
+                'session_key' => $session_key
+            ]);
+        }
+
+        $token = aes_encrypt(['id' => $user['id'], 'time' => time()]);
+
+        return out(['token' => $token]);
+    }
+
+    public function uploadFile()
+    {
+        $file = request()->file('file');
+        if (empty($file)) {
+            return out(null, 10001, '文件不能为空');
+        }
+
+        $path = $file->store('uploads/'.date('Ymd'));
+        $url = request()->getScheme().'://'.request()->getHost().'/'.$path;
+
+        return out(['url' => $url]);
+    }
+
+    public function doc()
+    {
+        $database = env('DB_DATABASE');
+        $prefix = env('DB_PREFIX');
+        $exclude_tables = "'bm_password_resets','bm_admin_menu','bm_admin_users','bm_failed_jobs','bm_migrations'";
+
+        $sql = "select TABLE_NAME name,TABLE_COMMENT comment from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='".$database."' and TABLE_NAME not in (".$exclude_tables.")";
+        $tables = \DB::select($sql);
+        $map1 = $map2 = [];
+        $i = round(count($tables)/2);
+        foreach ($tables as $k => $v) {
+            $name = str_replace($prefix, '', $v->name);
+            if ($k >= $i) {
+                $map1[$v->name] = $name.'('.$v->comment.')';
+            }
+            else {
+                $map2[$v->name] = $name.'('.$v->comment.')';
+            }
+        }
+
+        $data1 = [];
+        foreach ($map1 as $k => $v){
+            $sql = "select COLUMN_NAME name, DATA_TYPE type, COLUMN_COMMENT comment from INFORMATION_SCHEMA.COLUMNS where table_schema = '".$database."' AND table_name = '".$k."'";
+            $comment = \DB::select($sql);
+            $data1[$v] = $comment;
+        }
+
+        $data2 = [];
+        foreach ($map2 as $k => $v){
+            $sql = "select COLUMN_NAME name, DATA_TYPE type, COLUMN_COMMENT comment from INFORMATION_SCHEMA.COLUMNS where table_schema = '".$database."' AND table_name = '".$k."'";
+            $comment = \DB::select($sql);
+            $data2[$v] = $comment;
+        }
+
+        return view('doc', ['data1' => $data1, 'data2' => $data2]);
+    }
+}

+ 131 - 0
app/Http/Controllers/Api/V1/DocterController.php

xqd
@@ -0,0 +1,131 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-29
+ * Time: 上午11:09
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Docter;
+use App\Models\Organization;
+use App\Models\Schedule;
+use App\Models\SchedulePeriod;
+use App\Models\TimePeriod;
+use DB;
+
+class DocterController extends AuthController
+{
+    public function docterList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'list_type' => 'in:0,1,2,3',
+            'city_id' => 'integer',
+            'name' => 'max:255',
+            'latitude' => 'numeric',
+            'longitude' => 'numeric',
+            'sort_type' => 'in:0,1,2,3',
+            'schedule_date' => 'required_if:list_type,3|date',
+            'time_period_id' => 'required_if:list_type,3|integer',
+        ]);
+        $user = $this->user;
+
+        $latitude = !empty($req['latitude']) ? $req['latitude'] : $user['latitude'];
+        $longitude = !empty($req['longitude']) ? $req['longitude'] : $user['longitude'];
+        $distance_field = get_distance_field($latitude, $longitude);
+
+        $builder = Docter::with('office', 'qualification')->select(['id', 'type', 'name', 'phone', 'sex', 'birthday', 'avatar', 'status', 'label', 'sign', 'intro', 'office_id', 'qualification_id', 'score', 'service_persons', 'eva_num', 'service_days', 'phone_minutes', 'chat_price', 'phone_price', 'appoint_price', 'is_chat', 'is_phone', 'is_appoint', 'latitude', 'longitude', DB::raw($distance_field)])->where('status', 1);
+        $list_type = !empty($req['list_type']) ? $req['list_type'] : 0;
+        if ($list_type == 1) {
+            $builder->where('is_phone', 1);
+        }
+        if ($list_type == 2) {
+            $builder->where('is_chat', 1);
+        }
+        if ($list_type == 3) {
+            $builder->where('is_appoint', 1);
+        }
+        if (!empty($req['name'])) {
+            $name = $req['name'];
+            $organizations = Organization::with('docter')->select(['id'])->where('name', 'like', '%'.$name.'%')->get()->toArray();
+            $docterIds = [];
+            foreach ($organizations as $k => $v) {
+                $tmpDocterIds = array_column($v['docter'], 'id');
+                $docterIds = array_merge($docterIds, $tmpDocterIds);
+            }
+            $docterIds = array_values(array_unique($docterIds));
+            $builder->where(function ($query) use($name, $docterIds) {
+                $query->where('name', 'like', '%'.$name.'%')->orWhereIn('id', $docterIds);
+            });
+        }
+
+        if ($list_type == 3) {
+            $docterIds2 = SchedulePeriod::where('time_period_id', $req['time_period_id'])->where('schedule_date', $req['schedule_date'])->pluck('docter_id')->toArray();
+            $builder->whereIn('id', $docterIds2);
+        }
+
+        if (!empty($req['sort_type'])) {
+            if ($req['sort_type'] == 1) {
+                $builder->orderBy('distance', 'asc');
+            }
+            elseif ($req['sort_type'] == 2) {
+                $builder->orderBy('eva_num', 'desc');
+            }
+            elseif ($req['sort_type'] == 3) {
+                $builder->orderBy('service_persons', 'desc');
+            }
+        }
+        $data = $builder->paginate();
+
+        return out($data);
+    }
+
+    public function docterDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'docter_id' => 'required|integer',
+            'list_type' => 'in:0,1,2,3',
+            'schedule_date' => 'required_if:list_type,3|date',
+            'time_period_id' => 'required_if:list_type,3|integer',
+            'latitude' => 'numeric',
+            'longitude' => 'numeric',
+        ]);
+        $user = $this->user;
+
+        $latitude = !empty($req['latitude']) ? $req['latitude'] : $user['latitude'];
+        $longitude = !empty($req['longitude']) ? $req['longitude'] : $user['longitude'];
+        $distance_field = get_distance_field($latitude, $longitude);
+
+        $data = Docter::with('office', 'qualification', 'evaluate.user')->select(['id', 'type', 'name', 'phone', 'sex', 'birthday', 'avatar', 'status', 'label', 'sign', 'intro', 'office_id', 'qualification_id', 'score', 'service_persons', 'eva_num', 'service_days', 'phone_minutes', 'chat_price', 'phone_price', 'appoint_price', 'is_chat', 'is_phone', 'is_appoint', 'latitude', 'longitude', DB::raw($distance_field)])->where('id', $req['docter_id'])->where('status', 1)->first()->toArray();
+
+        $data['organization'] = null;
+        if (!empty($req['list_type']) && $req['list_type'] == 3) {
+            $schedulePeriod = SchedulePeriod::with('organization')->select(['organization_id'])->where('docter_id', $req['docter_id'])->where('time_period_id', $req['time_period_id'])->where('schedule_date', $req['schedule_date'])->first()->toArray();
+            $data['organization'] = $schedulePeriod['organization'];
+        }
+
+        return ($data);
+    }
+
+    public function schedulePeriodList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'docter_id' => 'required|integer',
+            'per_page' => 'integer',
+        ]);
+
+        $data = Schedule::with('schedulePeriod.timePeriod')->where('docter_id', $req['docter_id'])->where('schedule_day', '>=', date('Ymd'))->paginate($req['per_page']??15);
+
+        return out($data);
+    }
+
+    public function timePeriodList()
+    {
+        $data = TimePeriod::select(['id', 'start_time_period', 'end_time_period'])->get();
+        return out($data);
+    }
+}

+ 32 - 0
app/Http/Controllers/Api/V1/EvaluateController.php

xqd
@@ -0,0 +1,32 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 上午11:44
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Evaluate;
+
+class EvaluateController extends AuthController
+{
+    public function evaluateList()
+    {
+        $user = $this->user;
+        $data = Evaluate::with('order.docter')->where('user_id', $user['id'])->orderBy('id', 'desc')->paginate();
+        return out($data);
+    }
+
+    public function evaluateDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'evaluate_id' => 'required|integer',
+        ]);
+
+        $data = Evaluate::with('order.docter')->where('id', $req['evaluate_id'])->first();
+        return out($data);
+    }
+}

+ 49 - 0
app/Http/Controllers/Api/V1/NurseController.php

xqd
@@ -0,0 +1,49 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-4
+ * Time: 下午8:43
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Nurse;
+
+class NurseController extends AuthController
+{
+    public function nurseList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'name' => 'max:255',
+            'free_type' => 'in:0,1,2',
+            'sort_type' => 'in:1,2'
+        ]);
+
+        $builder = Nurse::select(['id', 'price', 'name', 'remark']);
+        if (!empty($req['free_type'])) {
+            if ($req['free_type'] == 1) {
+                $builder->where('price', 0);
+            }
+            elseif ($req['free_type'] == 2) {
+                $builder->where('price', '>', 0);
+            }
+        }
+        if (!empty($req['name'])) {
+            $builder->where('name', 'like', '%'.$req['name'].'%');
+        }
+        if (!empty($req['sort_type'])) {
+            if ($req['sort_type'] == 1) {
+                $builder->orderBy('price', 'asc');
+            }
+            elseif ($req['sort_type'] == 2) {
+                $builder->orderBy('price', 'desc');
+            }
+        }
+
+        $data = $builder->paginate();
+
+        return out($data);
+    }
+}

+ 524 - 0
app/Http/Controllers/Api/V1/OrderController.php

xqd
@@ -0,0 +1,524 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午10:58
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Nurse;
+use App\Models\Order;
+use App\Models\OrderNurse;
+use App\Models\OrderPack;
+use App\Models\OrderPatient;
+use App\Models\OrderVaccine;
+use App\Models\Patient;
+use App\Models\Payment;
+use App\Models\ServicePack;
+use App\Models\TimePeriod;
+use App\Models\User;
+use App\Models\UserCoupon;
+use App\Models\Vaccine;
+use EasyWeChat\Factory;
+use DB;
+
+class OrderController extends AuthController
+{
+    public function consultPlaceOrder()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'payment_type' => 'required|in:1,2',
+            'product_type' => 'required|in:1,2',
+            'docter_id' => 'required|integer',
+            'patient_id' => 'required|integer',
+            'total_amount' => 'required|integer',
+            'user_coupon_id' => 'integer',
+            'phone' => 'required_if:product_type,1',
+            'phone_minutes' => 'required_if:product_type,1|integer',
+            'symptoms' => 'required_if:product_type,2|max:2000',
+            'medical_imgs' => 'required_if:product_type,2|json|max:3000',
+        ]);
+        $user = $this->user;
+
+        $discount_amount = 0;
+        if (!empty($req['user_coupon_id'])) {
+            //计算优惠金额
+            $discount_amount = UserCoupon::getDiscountAmount($req['user_coupon_id'], $user['id'], $req['total_amount'], $req['product_type']);
+        }
+        $payment_amount = $req['total_amount'] - $discount_amount;
+        $payment_amount = $payment_amount < 0 ? 0 : $payment_amount;
+
+        if ($req['payment_type'] == 2) {
+            if ($user['balance'] < $payment_amount) {
+                return out(null, 601, '余额不足');
+            }
+        }
+
+        $order_status = $payment_status = 1;
+        $payment_time = 0;
+        if ($payment_amount == 0 || $req['payment_type'] == 2) {
+            $order_status = $payment_status = 2;
+            $payment_time = time();
+        }
+
+        $config = null;
+        DB::beginTransaction();
+        try {
+            //保存订单数据
+            $order = Order::create([
+                'user_id' => $user['id'],
+                'payment_type' => $req['payment_type'],
+                'product_type' => $req['product_type'],
+                'docter_id' => $req['docter_id'],
+                'total_amount' => $req['total_amount'],
+                'payment_amount' => $payment_amount,
+                'discount_amount' => $discount_amount,
+                'patient_id' => $req['patient_id'],
+                'order_status' => $order_status,
+                'payment_status' => $payment_status,
+                'payment_time' => $payment_time,
+            ]);
+            $order_sn = build_sn($order['id']);
+            Order::where('id', $order['id'])->update(['order_sn' => $order_sn]);
+            //保存订单患者信息
+            $addPatient = Patient::select(['name', 'sex', 'avatar', 'birthday', 'relationship', 'info', 'card_type', 'card_number'])->where('id', $req['patient_id'])->first()->toArray();
+            $addPatient['order_id'] = $order['id'];
+            $addPatient['patient_id'] = $req['patient_id'];
+            if ($req['product_type'] == 1) {
+                $addPatient['phone'] = $req['phone'];
+                $addPatient['phone_minutes'] = $req['phone_minutes'];
+            }
+            elseif ($req['product_type'] == 2) {
+                $addPatient['symptoms'] = $req['symptoms'];
+                $addPatient['medical_imgs'] = $req['medical_imgs'];
+            }
+            OrderPatient::create($addPatient);
+
+            //判断是微信支付
+            if ($req['payment_type'] == 1) {
+                //生成支付交易单
+                if ($payment_amount > 0) {
+                    $trade_sn = build_sn($order['id'], 3, 'T');
+                    $payBody = '超级宝妈-'.config('config.product_type_map')[$req['product_type']];
+                    Payment::create([
+                        'user_id' => $user['id'],
+                        'order_id' => $order['id'],
+                        'trade_sn' => $trade_sn,
+                        'amount' => $payment_amount,
+                        'remark' => $payBody,
+                    ]);
+                    //请求支付
+                    $payment = Factory::payment(config('config.wechat_pay'));
+                    $result = $payment->order->unify([
+                        'body' => $payBody,
+                        'out_trade_no' => $trade_sn,
+                        'total_fee' => $payment_amount,
+                        'trade_type' => 'JSAPI',
+                        'openid' => $user['openid'],
+                    ]);
+
+                    if (empty($result['prepay_id'])) {
+                        $errorMsg = !empty($result['err_code_des']) ? $result['err_code_des'] : $result['return_msg'];
+                        return out(null, 702, $errorMsg);
+                    }
+
+                    $config = $payment->jssdk->bridgeConfig($result['prepay_id'], false);
+                }
+            }
+            //判断是余额支付
+            elseif ($req['payment_type'] == 2) {
+                if ($payment_amount > 0) {
+                    //改变用户余额
+                    $change_amount = 0 - $payment_amount;
+                    User::changeBalance($user['id'], $change_amount, 1, $order['id'], '咨询订单消费');
+                }
+            }
+
+            DB::commit();
+        } catch (\Exception $e) {
+            DB::rollBack();
+            return out(null, 500, '下单失败,请稍后重试', $e->getMessage());
+        }
+
+        return out($config);
+    }
+
+    public function appointPlaceOrder()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'payment_type' => 'required|in:1,2',
+            'product_type' => 'required|in:3,4,5',
+            'patient_id' => 'required|integer',
+            'organization_id' => 'required|integer',
+            'schedule_date' => 'required|date',
+            'time_period_id' => 'required|integer',
+            'total_amount' => 'required|integer',
+            'user_coupon_id' => 'integer',
+            'docter_id' => 'required_if:product_type,3|integer',
+            'vaccine_id' => 'required_if:product_type,4|integer',
+            'nurse_ids' => 'required_if:product_type,5|json',
+        ]);
+        $user = $this->user;
+
+        $product_type = $req['product_type'];
+
+        if ($req['product_type'] == 4) {
+            $vaccine = Vaccine::select(['type'])->where('id', $req['vaccine_id'])->first();
+            if ($vaccine['type'] == 2) {
+                if (empty($req['total_amount'])) {
+                    return out(null, 10001, '总价不能为0');
+                }
+            }
+        }
+
+        $discount_amount = 0;
+        if (!empty($req['user_coupon_id'])) {
+            //计算优惠金额
+            $discount_amount = UserCoupon::getDiscountAmount($req['user_coupon_id'], $user['id'], $req['total_amount'], $product_type);
+        }
+        $payment_amount = $req['total_amount'] - $discount_amount;
+        $payment_amount = $payment_amount < 0 ? 0 : $payment_amount;
+
+        if ($req['payment_type'] == 2) {
+            if ($user['balance'] < $payment_amount) {
+                return out(null, 601, '余额不足');
+            }
+        }
+
+        $order_status = $payment_status = 1;
+        $payment_time = 0;
+        if ($payment_amount == 0 || $req['payment_type'] == 2) {
+            $order_status = $payment_status = 2;
+            $payment_time = time();
+        }
+
+        $config = null;
+        DB::beginTransaction();
+        try {
+            //保存订单数据
+            $order = Order::create([
+                'user_id' => $user['id'],
+                'docter_id' => $req['docter_id'] ?? 0,
+                'patient_id' => $req['patient_id'],
+                'organization_id' => $req['organization_id'],
+                'payment_type' => $req['payment_type'],
+                'product_type' => $product_type,
+                'order_status' => $order_status,
+                'payment_status' => $payment_status,
+                'total_amount' => $req['total_amount'],
+                'payment_amount' => $payment_amount,
+                'discount_amount' => $discount_amount,
+                'payment_time' => $payment_time,
+            ]);
+            $order_sn = build_sn($order['id']);
+            Order::where('id', $order['id'])->update(['order_sn' => $order_sn]);
+            //保存订单患者信息
+            $addPatient = Patient::select(['name', 'sex', 'avatar', 'birthday', 'relationship', 'info', 'card_type', 'card_number'])->where('id', $req['patient_id'])->first()->toArray();
+            $addPatient['order_id'] = $order['id'];
+            $addPatient['patient_id'] = $req['patient_id'];
+            $addPatient['organization_id'] = $req['organization_id'];
+            $addPatient['time_period_id'] = $req['time_period_id'];
+            $timePeriod = TimePeriod::where('id', $req['time_period_id'])->first();
+            $addPatient['appoint_start_time'] = strtotime($req['schedule_date'].' '.$timePeriod['start_time_period'].':00');
+            $addPatient['appoint_end_time'] = strtotime($req['schedule_date'].' '.$timePeriod['end_time_period'].':00');
+            $orderPatient = OrderPatient::create($addPatient);
+            //保存订单疫苗信息
+            if ($req['product_type'] == 4) {
+                $addVaccine = Vaccine::select(['id vaccine_id', 'type vaccine_type', 'price vaccine_price', 'name vaccine_name', 'remark vaccine_remark', 'supplier vaccine_supplier'])->where('id', $req['vaccine_id'])->first()->toArray();
+                $addVaccine['order_id'] = $order['id'];
+                $addVaccine['order_patient_id'] = $orderPatient['id'];
+                OrderVaccine::create($addVaccine);
+            }
+            //保存儿保订单信息
+            if ($req['product_type'] == 5) {
+                $nurse_ids = json_decode($req['nurse_ids'], true);
+                foreach ($nurse_ids as $k => $v) {
+                    $addNurse = Nurse::select(['id nurse_id', 'price nurse_price', 'name nurse_name', 'remark nurse_remark'])->where('id', $v)->first()->toArray();
+                    $addNurse['order_id'] = $order['id'];
+                    $addNurse['order_patient_id'] = $orderPatient['id'];
+                    OrderNurse::create($addNurse);
+                }
+            }
+
+            //判断是微信支付
+            if ($req['payment_type'] == 1) {
+                //生成支付交易单
+                if ($payment_amount > 0) {
+                    $trade_sn = build_sn($order['id'], 3, 'T');
+                    $payBody = '超级宝妈-'.config('config.product_type_map')[$product_type];
+                    Payment::create([
+                        'user_id' => $user['id'],
+                        'order_id' => $order['id'],
+                        'trade_sn' => $trade_sn,
+                        'amount' => $payment_amount,
+                        'remark' => $payBody,
+                    ]);
+                    //请求支付
+                    $payment = Factory::payment(config('config.wechat_pay'));
+                    $result = $payment->order->unify([
+                        'body' => $payBody,
+                        'out_trade_no' => $trade_sn,
+                        'total_fee' => $payment_amount,
+                        'trade_type' => 'JSAPI',
+                        'openid' => $user['openid'],
+                    ]);
+
+                    if (empty($result['prepay_id'])) {
+                        $errorMsg = !empty($result['err_code_des']) ? $result['err_code_des'] : $result['return_msg'];
+                        return out(null, 702, $errorMsg);
+                    }
+
+                    $config = $payment->jssdk->bridgeConfig($result['prepay_id'], false);
+                }
+            }
+            //判断是余额支付
+            elseif ($req['payment_type'] == 2) {
+                if ($payment_amount > 0) {
+                    //改变用户余额
+                    $change_amount = 0 - $payment_amount;
+                    User::changeBalance($user['id'], $change_amount, 1, $order['id'], '预约订单消费');
+                }
+            }
+
+            DB::commit();
+        } catch (\Exception $e) {
+            DB::rollBack();
+            return out(null, 500, '下单失败,请稍后重试', $e->getMessage());
+        }
+
+        return out($config);
+    }
+
+    public function packPlaceOrder()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'payment_type' => 'required|in:1,2',
+            'patient_id' => 'required|integer',
+            'total_amount' => 'required|integer',
+            'user_coupon_id' => 'integer',
+            'service_pack_id' => 'required|integer',
+            'is_security' => 'required|in:0,1',
+            'guardian_name' => 'required|max:50',
+            'relationship_type' => 'required|integer',
+        ]);
+        $user = $this->user;
+
+        $discount_amount = 0;
+        if (!empty($req['user_coupon_id'])) {
+            //计算优惠金额
+            $discount_amount = UserCoupon::getDiscountAmount($req['user_coupon_id'], $user['id'], $req['total_amount'], 6);
+        }
+        $payment_amount = $req['total_amount'] - $discount_amount;
+        $payment_amount = $payment_amount < 0 ? 0 : $payment_amount;
+
+        if ($req['payment_type'] == 2) {
+            if ($user['balance'] < $payment_amount) {
+                return out(null, 601, '余额不足');
+            }
+        }
+
+        $order_status = $payment_status = 1;
+        $payment_time = 0;
+        if ($payment_amount == 0 || $req['payment_type'] == 2) {
+            $order_status = $payment_status = 2;
+            $payment_time = time();
+        }
+
+        $config = null;
+        DB::beginTransaction();
+        try {
+            //保存订单数据
+            $order = Order::create([
+                'user_id' => $user['id'],
+                'patient_id' => $req['patient_id'],
+                'payment_type' => $req['payment_type'],
+                'product_type' => 6,
+                'docter_id' => $req['docter_id'],
+                'total_amount' => $req['total_amount'],
+                'payment_amount' => $payment_amount,
+                'discount_amount' => $discount_amount,
+                'order_status' => $order_status,
+                'payment_status' => $payment_status,
+                'payment_time' => $payment_time,
+            ]);
+            $order_sn = build_sn($order['id']);
+            Order::where('id', $order['id'])->update(['order_sn' => $order_sn]);
+            //保存订单患者信息
+            $addPatient = Patient::select(['name', 'sex', 'avatar', 'birthday', 'relationship', 'info', 'card_type', 'card_number'])->where('id', $req['patient_id'])->first()->toArray();
+            $addPatient['order_id'] = $order['id'];
+            $addPatient['patient_id'] = $req['patient_id'];
+            OrderPatient::create($addPatient);
+            //保存订单服务包表
+            $addPack = ServicePack::select(['id service_pack_id', 'name pack_name', 'intro pack_intro', 'price pack_price', 'team_id', 'phone_minutes', 'chat_num', 'appoint_num', 'vaccine_limit_amount', 'nurses_limit_amount', 'effective_days'])->where('id', $req['service_pack_id'])->first()->toArray();
+            $addPack['order_id'] = $order['id'];
+            $addPack['is_security'] = $req['is_security'];
+            $addPack['guardian_name'] = $req['guardian_name'];
+            $addPack['relationship_type'] = $req['relationship_type'];
+            $addPack['start_time'] = time();
+            $addPack['end_time'] = time() + $addPack['effective_days']*24*3600;
+            OrderPack::create($addPack);
+
+            //判断是微信支付
+            if ($req['payment_type'] == 1) {
+                //生成支付交易单
+                if ($payment_amount > 0) {
+                    $trade_sn = build_sn($order['id'], 3, 'T');
+                    $payBody = '超级宝妈-'.config('config.product_type_map')[6];
+                    Payment::create([
+                        'user_id' => $user['id'],
+                        'order_id' => $order['id'],
+                        'trade_sn' => $trade_sn,
+                        'amount' => $payment_amount,
+                        'remark' => $payBody,
+                    ]);
+                    //请求支付
+                    $payment = Factory::payment(config('config.wechat_pay'));
+                    $result = $payment->order->unify([
+                        'body' => $payBody,
+                        'out_trade_no' => $trade_sn,
+                        'total_fee' => $payment_amount,
+                        'trade_type' => 'JSAPI',
+                        'openid' => $user['openid'],
+                    ]);
+
+                    if (empty($result['prepay_id'])) {
+                        $errorMsg = !empty($result['err_code_des']) ? $result['err_code_des'] : $result['return_msg'];
+                        return out(null, 702, $errorMsg);
+                    }
+
+                    $config = $payment->jssdk->bridgeConfig($result['prepay_id'], false);
+                }
+            }
+            //判断是余额支付
+            elseif ($req['payment_type'] == 2) {
+                if ($payment_amount > 0) {
+                    //改变用户余额
+                    $change_amount = 0 - $payment_amount;
+                    User::changeBalance($user['id'], $change_amount, 1, $order['id'], '购买服务包');
+                }
+            }
+
+            DB::commit();
+        } catch (\Exception $e) {
+            DB::rollBack();
+            return out(null, 500, '下单失败,请稍后重试', $e->getMessage());
+        }
+
+        return out($config);
+    }
+
+    public function orderList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'list_type' => 'required|in:1,2,3',
+            'product_type' => 'integer',
+            'order_status' => 'integer',
+            'time_sort' => 'in:0,1'
+        ]);
+        $user = $this->user;
+
+        $builder = Order::with(['docter.office', 'docter.qualification', 'orderPatient', 'orderPack', 'orderNurse', 'orderVaccine'])->where('user_id', $user['id']);
+        if (!empty($req['product_type'])) {
+            $builder->where('product_type', $req['product_type']);
+        }
+        else {
+            if ($req['list_type'] == 1) {
+                $builder->whereIn('product_type', [1,2]);
+            }
+            elseif ($req['list_type'] == 2) {
+                $builder->whereIn('product_type', [3,4,5]);
+            }
+            elseif ($req['list_type'] == 3) {
+                $builder->where('product_type', 6);
+            }
+        }
+        if (!empty($req['order_status'])) {
+            $builder->where('order_status', $req['order_status']);
+        }
+        if (!empty($req['time_sort'])) {
+            $builder->orderBy('id', 'desc');
+        }
+        else {
+            $builder->orderBy('id', 'asc');
+        }
+
+        $data = $builder->paginate();
+
+        return out($data);
+    }
+
+    public function orderDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'order_id' => 'required|integer'
+        ]);
+        $user = $this->user;
+
+        $data = Order::with(['docter.office', 'docter.qualification', 'orderPatient', 'orderPack', 'orderNurse', 'orderVaccine'])->where('id', $req['order_id'])->where('user_id', $user['id'])->first();
+
+        return out($data);
+    }
+
+    public function topup()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'amount' => 'required|integer',
+        ]);
+        $user = $this->user;
+
+        DB::beginTransaction();
+        try {
+            //保存订单数据
+            $order = Order::create([
+                'user_id' => $user['id'],
+                'product_type' => 7,
+                'total_amount' => $req['amount'],
+                'payment_amount' => $req['amount'],
+            ]);
+            $order_sn = build_sn($order['id']);
+            Order::where('id', $order['id'])->update(['order_sn' => $order_sn]);
+
+            //生成支付交易单
+            $trade_sn = build_sn($order['id'], 3, 'T');
+            $payBody = '超级宝妈-'.config('config.product_type_map')[7];
+            Payment::create([
+                'user_id' => $user['id'],
+                'order_id' => $order['id'],
+                'trade_sn' => $trade_sn,
+                'amount' => $req['amount'],
+                'remark' => $payBody,
+            ]);
+            //请求支付
+            $payment = Factory::payment(config('config.wechat_pay'));
+            $result = $payment->order->unify([
+                'body' => $payBody,
+                'out_trade_no' => $trade_sn,
+                'total_fee' => $req['amount'],
+                'trade_type' => 'JSAPI',
+                'openid' => $user['openid'],
+            ]);
+
+            if (empty($result['prepay_id'])) {
+                $errorMsg = !empty($result['err_code_des']) ? $result['err_code_des'] : $result['return_msg'];
+                return out(null, 702, $errorMsg);
+            }
+
+            $config = $payment->jssdk->bridgeConfig($result['prepay_id'], false);
+
+            DB::commit();
+        } catch (\Exception $e) {
+            DB::rollBack();
+            return out(null, 500, '下单失败,请稍后重试', $e->getMessage());
+        }
+
+        return out($config);
+    }
+}

+ 60 - 0
app/Http/Controllers/Api/V1/PatientController.php

xqd
@@ -0,0 +1,60 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-2
+ * Time: 下午8:46
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Order;
+use App\Models\Patient;
+
+class PatientController extends AuthController
+{
+    public function createPatient()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'name' => 'required|max:50',
+            'sex' => 'required|in:1,2',
+            'avatar' => 'required|url',
+            'birthday' => 'required|date',
+            'relationship_type' => 'required|integer',
+            'info' => 'max:1000',
+            'card_type' => 'required|in:1,2',
+            'card_number' => 'required|max:50',
+        ]);
+        $user = $this->user;
+
+        $req['user_id'] = $user['id'];
+        Patient::create($req);
+
+        return out();
+    }
+
+    public function patientList()
+    {
+        $user = $this->user;
+        $data = Patient::where('user_id', $user['id'])->orderBy('id', 'desc')->paginate();
+        return out($data);
+    }
+
+    public function patientDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'patient_id' => 'required|integer',
+        ]);
+        $user = $this->user;
+
+        $data = [];
+        $data['patient'] = Patient::where('id', $req['patient_id'])->where('user_id', $user['id'])->first();
+
+        $data['orders']['cases'] = Order::with(['docter' => ['office', 'qualification']])->where('user_id', $user['id'])->where('patient_id', $req['patient_id'])->whereIn('order_status', [2,3])->where('product_type', '<', 6)->orderBy('id', 'desc')->get();
+        $data['orders']['service_packs'] = Order::with('orderPack')->where('user_id', $user['id'])->where('patient_id', $req['patient_id'])->whereIn('order_status', [2,3])->where('product_type', 6)->orderBy('id', 'desc')->get();
+
+        return out($data);
+    }
+}

+ 93 - 0
app/Http/Controllers/Api/V1/PayCallbackController.php

xqd
@@ -0,0 +1,93 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-2
+ * Time: 下午8:27
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Http\Controllers\Controller;
+use App\Models\Docter;
+use App\Models\Order;
+use App\Models\Payment;
+use App\Models\User;
+use App\Models\UserBalanceLog;
+use DB;
+use EasyWeChat\Factory;
+
+class PayCallbackController extends Controller
+{
+    public function wechatPayNotify()
+    {
+        $app = Factory::payment(config('config.wechat_pay'));
+        $response = $app->handlePaidNotify(function($message, $fail){
+            // 使用通知里的 "交易单号" 去自己的数据库找到订单
+            $payment = Payment::where('trade_sn', $message['out_trade_no'])->first();
+            // 如果订单不存在 或者 订单已经支付过了
+            if (empty($payment) || $payment['status'] != 1) {
+                return true; // 告诉微信,我已经处理完了或者订单没找到,别再通知我了
+            }
+            //使用通知里的 "微信支付订单号" 去自己的数据库找是否已经存在
+            if(Payment::where('online_sn', $message['transaction_id'])->exists()){
+                return true; // 告诉微信,我已经处理过这单了,别再通知我了
+            }
+
+            //建议在这里调用微信的【订单查询】接口查一下该笔订单的情况,确认是已经支付
+
+            // return_code 表示通信状态,不代表支付状态
+            if ($message['return_code'] === 'SUCCESS') {
+                // 用户是否支付成功
+                if ($message['result_code'] === 'SUCCESS') {
+                    // 启动事务
+                    DB::beginTransaction();
+                    try {
+                        //更新payment
+                        Payment::where('id', $payment['id'])->update(['online_sn' => $message['transaction_id'], 'status' => 2, 'payment_time' => time()]);
+                        $order = Order::select(['id', 'user_id', 'docter_id', 'product_type', 'payment_amount'])->where('id', $payment['order_id'])->first();
+                        $order_status = 2;
+                        if ($order['product_type'] == 7) {
+                            $order_status = 3;
+                            //改变用户余额
+                            User::changeBalance($order['user_id'], $order['payment_amount'], 2, $order['id'], '充值');
+                        }
+                        //更新订单
+                        Order::where('id', $payment['order_id'])->update([
+                            'order_status' => $order_status,
+                            'payment_status' => 2,
+                            'payment_time' => time(),
+                        ]);
+
+                        if (!empty($order['docter_id'])) {
+                            //更新医生的服务人数
+                            Docter::where('id', $order['docter_id'])->increment('service_persons');
+                        }
+
+                        // 提交事务
+                        DB::commit();
+                    } catch (\Exception $e) {
+                        // 回滚事务
+                        DB::rollback();
+                        trace(['微信支付回调错误' => $e->getMessage(), '错误数据' => $payment], 'error');
+                        return $fail('内部服务失败,请稍后再通知我');
+                    }
+                }
+                elseif ($message['result_code'] === 'FAIL') {
+                    $err_code = $message['err_code'] ?? '';
+                    $err_code_des = $message['err_code_des'] ?? '';
+                    $remark = $err_code.':'.$err_code_des;
+                    Payment::where('id', $payment['id'])->update(['remark' => $remark, 'status' => 3, 'payment_time' => time()]);
+                }
+            }
+            else {
+                trace(['微信支付回调通知数据错误,返回码return_code:' => $message['return_code'], '错误数据' => $payment], 'error');
+                return $fail('通信失败,请稍后再通知我');
+            }
+
+            return true; // 返回处理完成
+        });
+
+        return $response;
+    }
+}

+ 33 - 0
app/Http/Controllers/Api/V1/ServicePackController.php

xqd
@@ -0,0 +1,33 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-4
+ * Time: 下午9:57
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\ServicePack;
+
+class ServicePackController extends AuthController
+{
+    public function servicePackList()
+    {
+        $data = ServicePack::orderBy('id', 'desc')->paginate();
+
+        return out($data);
+    }
+
+    public function servicePackDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'service_pack_id' => 'required|integer'
+        ]);
+
+        $data = ServicePack::with('team.docter')->where('id', $req['service_pack_id'])->first();
+
+        return out($data);
+    }
+}

+ 35 - 0
app/Http/Controllers/Api/V1/SuggestController.php

xqd
@@ -0,0 +1,35 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 上午11:28
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Suggest;
+
+class SuggestController extends AuthController
+{
+    public function suggestList()
+    {
+        $user = $this->user;
+
+        $data = Suggest::with('order.docter')->where('user_id', $user['id'])->orderBy('id', 'desc')->paginate();
+
+        return out($data);
+    }
+
+    public function suggestDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'suggest_id' => 'required|integer',
+        ]);
+
+        $data = Suggest::with('order.docter')->where('id', $req['suggest_id'])->first();
+
+        return out($data);
+    }
+}

+ 82 - 0
app/Http/Controllers/Api/V1/UserController.php

xqd
@@ -0,0 +1,82 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-23
+ * Time: 上午11:36
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Order;
+use App\Models\User;
+use App\Models\UserBalanceLog;
+use EasyWeChat\Factory;
+
+class UserController extends AuthController
+{
+    public function userInfo()
+    {
+        $user = $this->user;
+
+        unset($user['session_key']);
+
+        return out($user);
+    }
+
+    public function getPhoneNumber()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'iv' => 'required',
+            'encryptData' => 'required',
+        ]);
+        $user = $this->user;
+
+        $app = Factory::miniProgram(config('config.wechat_small_program'));
+
+        try {
+            $decryptedData = $app->encryptor->decryptData($user['session_key'], $req['iv'], $req['encryptData']);
+        } catch (\Exception $e) {
+            return out(null, 10001, '获取手机号失败', $e->getMessage());
+        }
+
+        return out($decryptedData);
+    }
+
+    public function updateUser()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'nickname' => 'max:100',
+            'avatar' => 'url',
+            'sex' => 'in:1,2',
+            'birthday' => 'date',
+            'latitude' => 'numeric',
+            'longitude' => 'numeric',
+        ]);
+        $user = $this->user;
+
+        User::where('id', $user['id'])->update($req);
+
+        return out();
+    }
+
+    public function userBalanceLog()
+    {
+        $user = $this->user;
+        $data = UserBalanceLog::where('user_id', $user['id'])->orderBy('id', 'desc')->paginate();
+        return out($data);
+    }
+
+    public function familyDocterList()
+    {
+        $user = $this->user;
+
+        $order_ids = Order::where('user_id', $user['id'])->whereIn('order_status', [2, 3])->where('docter_id', '>', 0)->pluck('docter_id')->toArray();
+
+        $data = Order::with(['docter.office', 'docter.qualification', 'orderPatient'])->select(['id', 'docter_id'])->whereIn('docter_id', $order_ids)->paginate();
+
+        return out($data);
+    }
+}

+ 44 - 0
app/Http/Controllers/Api/V1/VaccineController.php

xqd
@@ -0,0 +1,44 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-4
+ * Time: 下午8:32
+ */
+
+namespace App\Http\Controllers\Api\V1;
+
+use App\Models\Vaccine;
+
+class VaccineController extends AuthController
+{
+    public function vaccineList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'name' => 'max:50',
+            'type' => 'in:1,2',
+            'sort_type' => 'in:1,2',
+        ]);
+
+        $builder = Vaccine::select(['id', 'type', 'price', 'name', 'remark', 'supplier']);
+        if (!empty($req['type'])) {
+            $builder->where('type', $req['type']);
+        }
+        if (!empty($req['name'])) {
+            $builder->where('name', 'like', '%'.$req['name'].'%');
+        }
+        if (!empty($req['sort_type'])) {
+            if ($req['sort_type'] == 1) {
+                $builder->orderBy('price', 'asc');
+            }
+            elseif ($req['sort_type'] == 2) {
+                $builder->orderBy('price', 'desc');
+            }
+        }
+
+        $data = $builder->paginate();
+
+        return out($data);
+    }
+}

+ 33 - 0
app/Http/Controllers/Api/V2/ArticleController.php

xqd
@@ -0,0 +1,33 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:40
+ */
+
+namespace App\Http\Controllers\Api\V2;
+
+use App\Models\Article;
+
+class ArticleController extends AuthController
+{
+    public function articleList()
+    {
+        $data = Article::orderBy('id', 'desc')->paginate();
+
+        return out($data);
+    }
+
+    public function articleDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'article_id' => 'required|integer',
+        ]);
+
+        $data = Article::where('id', $req['article_id'])->first();
+
+        return out($data);
+    }
+}

+ 22 - 0
app/Http/Controllers/Api/V2/AuthController.php

xqd
@@ -0,0 +1,22 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-23
+ * Time: 上午11:34
+ */
+
+namespace App\Http\Controllers\Api\V2;
+
+use App\Http\Controllers\Controller;
+use App\Models\User;
+
+class AuthController extends Controller
+{
+    protected $user = null;
+
+    public function __construct()
+    {
+        $this->user = User::getUserByToken();
+    }
+}

+ 45 - 0
app/Http/Controllers/Api/V2/CallPhoneController.php

xqd
@@ -0,0 +1,45 @@
+<?php
+namespace App\Http\Controllers\Api\V2;
+use AlibabaCloud\Client\AlibabaCloud;
+use AlibabaCloud\Client\Exception\ClientException;
+use AlibabaCloud\Client\Exception\ServerException;
+
+/**
+ * 通话记录类(一期废弃)
+ * Class CallPhoneController
+ * @package App\Http\Controllers\Api\V2
+ */
+class CallPhoneController extends Controller
+{
+
+    public function BindAxb($phone1='',$phone2='',$data=[]){
+        var_dump('到我了!');die();
+        $config = config('config.axb');
+        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
+            ->regionId('cn-kunming')
+            ->asDefaultClient();
+        try {
+            $result = AlibabaCloud::rpc()
+                ->product('Dyplsapi')
+                ->version('2017-05-25')
+                ->action('BindAxb')
+                ->method('POST')
+                ->host('dyplsapi.aliyuncs.com')
+                ->options([
+                    'query' => [
+                        "Expiration" => "2020-11-25 12:00:00",
+                        'RegionId' => "cn-kunming",
+                        'PhoneNoA' => "18831125321",
+                        'PhoneNoB' => "18830277213",
+                    ],
+                ])
+                ->request();
+            print_r($result->toArray());
+        } catch (ClientException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        } catch (ServerException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        }
+    }
+
+}

+ 1124 - 0
app/Http/Controllers/Api/V2/CommonController.php

xqd
@@ -0,0 +1,1124 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-23
+ * Time: 上午11:26
+ */
+
+namespace App\Http\Controllers\Api\V2;
+
+use App\Http\Controllers\Controller;
+use App\Models\Article;
+use App\Models\Order;
+use App\Models\User;
+use App\Models\Docter;
+use EasyWeChat\Factory;
+use http\Env\Request;
+use Illuminate\Support\Facades\DB;
+use AlibabaCloud\Client\Exception\ClientException;
+use Alibabaloud\Client\Exception\ServerException;
+use AlibabaCloud\Client\AlibabaCloud;
+use AlibabaCloud\Dybaseapi\MNS\Requests\BatchReceiveMessage;
+use AlibabaCloud\Dybaseapi\MNS\Requests\BatchDeleteMessage;
+use App\Models\CallLog;
+use App\Models\Axb;
+use App\Models\ImMessage;
+
+/**
+ * 公共方法类
+ * Class CommonController
+ * @package App\Http\Controllers\Api\V2
+ */
+class CommonController extends Controller
+{
+    public function wxLogin()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'wechat_code' => 'required',
+            'nickname|昵称' => 'max:50',
+            'avatar|头像' => 'url',
+            'latitude|纬度' => 'numeric',
+            'longitude|纬度' => 'numeric',
+        ]);
+        $app = Factory::miniProgram(config('config.wechat_small_program'));
+
+        $data = $app->auth->session($req['wechat_code']);
+
+        if (empty($data['openid'])){
+            return out(null, 10001, '微信登录code错误');
+        }
+
+        $session_key = !empty($data['session_key']) ? $data['session_key'] : '';
+
+        $user = User::select(['id', 'status', 'phone', 'nickname', 'avatar'])->where('openid', $data['openid'])->first();
+        if (empty($user)){
+            $user = User::create([
+                'openid' => $data['openid'],
+                'nickname' => $req['nickname'] ?? '',
+                'avatar' => $req['avatar'] ?? '',
+                'latitude' => $req['latitude'] ?? 0,
+                'longitude' => $req['longitude'] ?? 0,
+                'session_key' => $session_key
+            ]);
+        }
+        else {
+            if ($user['status'] == 0) {
+                return out(null, 10002, '该账号已被冻结');
+            }
+
+            User::where('id', $user['id'])->update([
+                'nickname' => $req['nickname'] ?? '',
+                'avatar' => $req['avatar'] ?? '',
+                'latitude' => $req['latitude'] ?? 0,
+                'longitude' => $req['longitude'] ?? 0,
+                'session_key' => $session_key
+            ]);
+        }
+        // 查询医生表有没有记录
+        $doct = User::where('openid',$data['openid'])->orderBy('id','desc')->first();
+
+        if ($doct['phone']!=''){
+            $list = Docter::where('phone',$doct['phone'])->orderBy('id','desc')->first();
+            if ($list){
+                if ($list['status'] == 0) {
+                    return out(null, 10002, '该账号已被冻结');
+                }
+                $datas = [
+                    'avatar' => $list['avatar'],
+                    'name' => $list['name'],
+                    'flag' => 'doctor_'.$list['id'],
+                ];
+                $token = aes_encrypt(['doctor_id' => $list['id'], 'time' => time()]);
+                return out(['token' => $token,'data'=>$datas]);
+            }else{
+                return out(['session_key'=>$session_key,'openid'=>$data['openid']]);
+            }
+        }else{
+            return out(['session_key'=>$session_key,'openid'=>$data['openid']]);
+        }
+    }
+
+    /**
+     * 获取手机号!
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/18 17:17 *
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function getPhoneNumber(){
+        $req = request()->post();
+        $this->validate(request(), [
+            'iv' => 'required',
+            'encryptedData' => 'required',
+            'session_key' => 'required',
+            'openid' => 'required',
+        ]);
+
+        $app = Factory::miniProgram(config('config.wechat_small_program'));
+//        $data = $app->auth->session($req['code']);
+//        if (empty($data['openid'])){
+//            return out(null, 10001, '微信登录code错误');
+//        }
+        $session_key = !empty($req['session_key']) ? $req['session_key'] : '';
+        $user = User::select(['id','sex', 'status', 'phone', 'birthday','nickname', 'avatar','status'])->where('openid', $req['openid'])->first();
+        if (!$user){
+            return out(['status'=>false,'msg' => '用户不存在!']);
+        }
+
+
+        $decryptedData = $app->encryptor->decryptData($session_key, $req['iv'], $req['encryptedData']);
+        if (!isset($decryptedData['phoneNumber']) || empty($decryptedData['phoneNumber'])){
+            return out(['status'=>false,'msg' => '手机号解密失败!']);
+        }
+
+
+        $docter_list = [
+            'type' => 1,
+            'name' => $user['nickname'],
+            'phone' => $decryptedData['phoneNumber'],
+            'sex' => $user['sex'],
+            'birthday' => $user['birthday'],
+            'avatar' => $user['avatar'],
+            'status' => 1,
+            'label' => '无',
+            'sign' => '无',
+            'intro' => 0,
+            'office_id' => 0,
+            'qualification_id' => 0,
+            'score' => 0,
+            'service_persons' => 0,
+            'eva_num' => 0,
+            'service_days' => 0,
+            'phone_minutes' => 0,
+            'chat_price' => 0,
+            'phone_price' => 0,
+            'appoint_price' => 0,
+            'is_chat' => 0,
+            'is_phone' => 0,
+            'is_appoint' => 0,
+            'latitude' => 0,
+            'longitude' => 0,
+            'is_then' => 0,
+            'practice' => 0,
+            'card_photo' => 0,
+            'is_quail' => 0,
+            'card_id' => 0,
+        ];
+        // 查询医生表有没有记录
+        $doct = Docter::where('phone',$decryptedData['phoneNumber'])->orderBy('id','desc')->first();
+
+        if ($doct){
+            if ($doct['status'] == 0) {
+                return out(null, 10002, '该账号已被冻结');
+            }
+            $datas = [
+                'avatar' => $doct['avatar'],
+                'name' => $doct['name'],
+                'flag' => 'doctor_'.$doct['id'],
+            ];
+            $token = aes_encrypt(['doctor_id' => $doct['id'], 'time' => time()]);
+            return out(['token' => $token,'data'=>$datas]);
+        }
+        $list=[];
+        if ($user){
+            DB::beginTransaction();
+            try {
+                User::where('openid', $req['openid'])->update([
+                    'phone' => $decryptedData['phoneNumber'] ?? '','is_docter'=>1,
+                ]);
+                // 注册医生
+                $list = Docter::create($docter_list);
+                DB::commit();
+            }catch (\Exception $e){
+                DB::rollback();
+                return out(null, 500, $e->getMessage());
+            }catch (\PDOException $e){
+                DB::rollback();
+                return out(null, 500, $e->getMessage());
+            }
+        }
+
+        $datas = [
+            'avatar' => $list['avatar'],
+            'name' => $list['name'],
+            'flag' => 'doctor_'.$list['id'],
+        ];
+        $token = aes_encrypt(['doctor_id' => $list['id'], 'time' => time()]);
+        return out(['token' => $token,'data'=>$datas]);
+
+    }
+
+    /**
+     * 手机号登陆
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/18 19:17 *
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function phoneLogin(){
+        $req = request()->post();
+        $this->validate(request(), [
+            'phone|手机号' => 'required|integer',
+        ]);
+        $req['verify'] = 0;
+        $find = Docter::where('phone','=',$req['phone'])->first();
+
+        if (empty($find)){
+            $docter_list = [
+                'type' => 1,
+                'name' => '用户名',
+                'phone' => $req['phone'],
+                'sex' => 0,
+                'birthday' => 0,
+                'avatar' => '../../static/login/moren.png',
+                'status' => 1,
+                'label' => '无',
+                'sign' => '无',
+                'intro' => 0,
+                'office_id' => 0,
+                'qualification_id' => 0,
+                'score' => 0,
+                'service_persons' => 0,
+                'eva_num' => 0,
+                'service_days' => 0,
+                'phone_minutes' => 0,
+                'chat_price' => 0,
+                'phone_price' => 0,
+                'appoint_price' => 0,
+                'is_chat' => 0,
+                'is_phone' => 0,
+                'is_appoint' => 0,
+                'latitude' => 0,
+                'longitude' => 0,
+                'is_then' => 0,
+                'practice' => 0,
+                'card_photo' => 0,
+                'is_quail' => 0,
+                'card_id' => 0,
+            ];
+            $list = Docter::create($docter_list)->toArray();
+            if (!empty($list)){
+                $datas = [
+                    'avatar' => $list['avatar'],
+                    'name' => $list['name'],
+                    'flag' => 'doctor_'.$list['id'],
+                ];
+                $token = aes_encrypt(['doctor_id' => $list['id'], 'time' => time()]);
+                return out(['token' => $token,'data'=>$datas]);
+            }else{
+                return out('',401,'用户不存在,注册失败!');
+            }
+        }
+
+        $find = $find->toArray();
+        if ($find['status'] == 0) {
+            return out(null, 10002, '该账号已被冻结');
+        }
+        if ($req['verify']==0){
+            $datas = [
+                'avatar' => $find['avatar'],
+                'name' => $find['name'],
+                'flag' => 'doctor_'.$find['id'],
+            ];
+            // 验证是否正确
+            $token = aes_encrypt(['doctor_id' => $find['id'], 'time' => time()]);
+            return out(['token' => $token,'data'=>$datas]);
+        }else{
+            return out(null, 401, '验证码错误');
+
+        }
+
+    }
+
+    /**
+     * 账号密码登陆
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/18 19:17 *
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function passLogin(){
+        $req = request()->post();
+        $this->validate(request(), [
+            'phone|手机号' => 'required|integer',
+            'password|密码' => 'required',
+        ]);
+        $find = Docter::where('phone','=',$req['phone'])->first();
+        if (empty($find)){
+            return out(null, 401, '账号不存在');
+        }
+        if ($find['status'] == 0) {
+            return out(null, 10002, '该账号已被冻结');
+        }
+        $find = $find->toArray();
+        // 验证密码
+        $password = md5(md5(md5($req['password'])));
+        if ($password==$find['password']){
+
+            $datas = [
+                'avatar' => $find['avatar'],
+                'name' => $find['name'],
+                'flag' => 'doctor_'.$find['id'],
+            ];
+            $token = aes_encrypt(['doctor_id' => $find['id'], 'time' => time()]);
+
+            return out(['token' => $token,'data'=>$datas]);
+        }else{
+                return out(null, 401, '密码错误');
+        }
+    }
+
+    /**
+     * 获取验证码
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/11/6 10:45
+     */
+    public function putverfiy(){
+        $req = request()->post();
+        $this->validate(request(), [
+            'phone|手机号' => 'required|integer',
+        ]);
+        $mobile =$req['phone']; //获取传入的手机号
+        $num = rand(1000,9999);   //随机产生四位数字的验证码
+        $verify_code = $num;
+        $texts = send_sms($mobile,'verify_template_code',['code'=>$verify_code]);
+        if ($texts->Message=='OK'){
+            return out($num);
+        }else{
+            return out('',500,'发送验证码错误');
+        }
+    }
+
+    /**
+     * 手机号注册
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/18 20:17 *
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function phoneRegister(){
+        $req = request()->post();
+        $this->validate(request(), [
+            'phone|手机号' => 'required|integer',
+            'password|密码' => 'required',
+        ]);
+
+        // 查询是否注册过!
+        $docters = Docter::where('phone','=',$req['phone'])->first();
+
+        if (!empty($docters)){
+            return out('',500,'此手机号已被注册!');
+        }
+
+        $password = md5(md5(md5($req['password'])));
+        $docter_list = [
+            'type' => 1,
+            'name' => '用户名',
+            'phone' => $req['phone'],
+            'sex' => 0,
+            'birthday' => 0,
+            'avatar' => '无',
+            'status' => 1,
+            'label' => '无',
+            'sign' => '',
+            'intro' => '',
+            'office_id' => 0,
+            'qualification_id' => 0,
+            'score' => 0,
+            'service_persons' => 0,
+            'eva_num' => 0,
+            'service_days' => 0,
+            'phone_minutes' => 0,
+            'chat_price' => 0,
+            'phone_price' => 0,
+            'appoint_price' => 0,
+            'is_chat' => 0,
+            'is_phone' => 0,
+            'is_appoint' => 0,
+            'latitude' => 0,
+            'longitude' => 0,
+            'password' => $password,
+            'is_then' => 0,
+            'practice' => 0,
+            'card_photo' => 0,
+            'is_quail' => 0,
+            'card_id' => 0,
+        ];
+        $list = Docter::create($docter_list)->toArray();
+        if (!empty($list)){
+
+            $datas = [
+                'avatar' => $list['avatar'],
+                'name' => $list['name'],
+                'flag' => 'doctor_'.$list['id'],
+            ];
+            $token = aes_encrypt(['doctor_id' => $list['id'], 'time' => time()]);
+            return out(['token' => $token,'data'=>$datas]);
+        }else{
+            return out('',500,'注册失败!');
+        }
+
+//        return out();
+    }
+
+    public function articleList()
+    {
+        $data = Article::orderBy('id', 'desc')->paginate();
+
+        return out($data);
+    }
+
+    public function getUserIdByDoctorId($phone=null){
+        $list = Docter::where('phone', $phone)->first();
+        if ($list){
+            return $list->id;
+        }else{
+            return false;
+        }
+    }
+
+    public function uploadFile()
+    {
+        $file = request()->file('file');
+        if (empty($file)) {
+            return out(null, 10001, '文件不能为空');
+        }
+
+        $path = $file->store('uploads/'.date('Ymd'));
+//        $url = request()->getScheme().'://'.request()->getHost().'/'.$path;
+
+        return out(['url' => $path]);
+    }
+
+    public function doc()
+    {
+        $database = env('DB_DATABASE');
+        $prefix = env('DB_PREFIX');
+        $exclude_tables = "'bm_password_resets','bm_admin_menu','bm_admin_users','bm_failed_jobs','bm_migrations'";
+
+        $sql = "select TABLE_NAME name,TABLE_COMMENT comment from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='".$database."' and TABLE_NAME not in (".$exclude_tables.")";
+        $tables = \DB::select($sql);
+        $map1 = $map2 = [];
+        $i = round(count($tables)/2);
+        foreach ($tables as $k => $v) {
+            $name = str_replace($prefix, '', $v->name);
+            if ($k >= $i) {
+                $map1[$v->name] = $name.'('.$v->comment.')';
+            }
+            else {
+                $map2[$v->name] = $name.'('.$v->comment.')';
+            }
+        }
+
+        $data1 = [];
+        foreach ($map1 as $k => $v){
+            $sql = "select COLUMN_NAME name, DATA_TYPE type, COLUMN_COMMENT comment from INFORMATION_SCHEMA.COLUMNS where table_schema = '".$database."' AND table_name = '".$k."'";
+            $comment = \DB::select($sql);
+            $data1[$v] = $comment;
+        }
+
+        $data2 = [];
+        foreach ($map2 as $k => $v){
+            $sql = "select COLUMN_NAME name, DATA_TYPE type, COLUMN_COMMENT comment from INFORMATION_SCHEMA.COLUMNS where table_schema = '".$database."' AND table_name = '".$k."'";
+            $comment = \DB::select($sql);
+            $data2[$v] = $comment;
+        }
+
+        return view('doc', ['data1' => $data1, 'data2' => $data2]);
+    }
+
+
+    /**
+     * 绑定号码池子
+     * @param string $phone1 医生id
+     * @param string $phone2 用户id
+     * @param array $data 参数
+     * @return mixed
+     */
+    public function BindAxb($phone1,$phone2,$data=[]){
+        $config = config('config.axb');
+        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
+            ->regionId('cn-kunming')
+            ->asDefaultClient();
+        try {
+            $result = AlibabaCloud::rpc()
+                ->product('Dyplsapi')
+                ->version('2017-05-25')
+                ->action('BindAxb')
+                ->method('POST')
+                ->host('dyplsapi.aliyuncs.com')
+                ->options([
+                    'query' => [
+                        "Expiration" => date("Y-m-d H:i:s",strtotime("+1 day")),
+                        'RegionId' => "cn-kunming",
+                        'PhoneNoA' => $phone1,
+                        'PhoneNoB' => $phone2,
+                    ],
+                ])
+                ->request();
+            return $result->toArray();
+        } catch (ClientException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        } catch (ServerException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        }
+    }
+
+    /**
+     * 释放虚拟号码
+     * @param int $phone
+     */
+    public function ReleaseSecretNo($phone){
+        $config = config('config.axb');
+        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
+            ->regionId('cn-kunming')
+            ->asDefaultClient();
+
+        try {
+            $result = AlibabaCloud::rpc()
+                ->product('Dyplsapi')
+                // ->scheme('https') // https | http
+                ->version('2017-05-25')
+                ->action('ReleaseSecretNo')
+                ->method('POST')
+                ->host('dyplsapi.aliyuncs.com')
+                ->options([
+                    'query' => [
+                        'RegionId' => "cn-kunming",
+                        "SecretNo" => $phone,
+                        "PoolKey" => $config['PoolKey'],
+                    ],
+                ])
+                ->request();
+            $res = $result->toArray();
+           return $res;
+
+        } catch (ClientException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        } catch (ServerException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        }
+    }
+
+
+    /**
+     * 查询号码关系
+     * @param $phone
+     * @return mixed
+     */
+    public function QuerySubscriptionDetail($phone,$SubsId){
+        $config = config('config.axb');
+        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
+            ->regionId('cn-kunming')
+            ->asDefaultClient();
+
+        try {
+
+            $result = AlibabaCloud::rpc()
+                ->product('Dyplsapi')
+                // ->scheme('https') // https | http
+                ->version('2017-05-25')
+                ->action('QuerySubscriptionDetail')
+                ->method('POST')
+                ->host('dyplsapi.aliyuncs.com')
+                ->options([
+                    'query' => [
+                        'RegionId' => "cn-hangzhou",
+                        "PoolKey" => $config['PoolKey'],
+                        "SubsId" => $SubsId,
+                        "PhoneNoX" => $phone,
+
+                    ],
+                ])
+                ->request();
+
+            $res = $result->toArray();
+           return $res;
+
+        } catch (ClientException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        } catch (ServerException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        }
+    }
+
+
+    /**
+     * 解除绑定关系
+     * @param $phone
+     * @return mixed
+     */
+    public function UnbindSubscription($phone,$subId){
+        $config = config('config.axb');
+        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
+            ->regionId('cn-kunming')
+            ->asDefaultClient();
+        try {
+            $result = AlibabaCloud::rpc()
+                ->product('Dyplsapi')
+                // ->scheme('https') // https | http
+                ->version('2017-05-25')
+                ->action('UnbindSubscription')
+                ->method('POST')
+                ->host('dyplsapi.aliyuncs.com')
+                ->options([
+                    'query' => [
+                        'RegionId' => "cn-kunming",
+                        'SubsId' => $subId,
+                        "SecretNo" => $phone,
+                        "PoolKey" => $config['PoolKey'],
+                    ],
+                ])
+                ->request();
+            $res = $result->toArray();
+            return $res;
+        } catch (ClientException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        } catch (ServerException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        }
+    }
+
+
+    /**
+     * 调用接口QuerySubsId查询绑定唯一标识SubsId
+     * @param $phone X号码
+     * @return mixed
+     */
+    public function QuerySubsId($phone){
+        $config = config('config.axb');
+        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
+            ->regionId('cn-kunming')
+            ->asDefaultClient();
+        try {
+            $result = AlibabaCloud::rpc()
+                ->product('Dyplsapi')
+                // ->scheme('https') // https | http
+                ->version('2017-05-25')
+                ->action('QuerySubsId')
+                ->method('POST')
+                ->host('dyplsapi.aliyuncs.com')
+                ->options([
+                    'query' => [
+                        'RegionId' => "cn-hangzhou",
+                        'Action' => "QuerySubsId",
+                        "PhoneNoX" => $phone,
+                        "PoolKey" => $config['PoolKey'],
+                    ],
+                ])
+                ->request();
+            $res = $result->toArray();
+            return $res;
+        } catch (ClientException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        } catch (ServerException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        }
+    }
+
+
+    /**
+     * 解锁号码
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/11/25 18:36
+     */
+    public function unLokPhone($phone,$SubsId){
+        $unlok = $this->UnbindSubscription($phone,$SubsId);
+        if ($unlok['Code']!='OK'){
+            return out($unlok);
+        }else{
+            return 1;
+        }
+    }
+
+    /**
+     * 测试解除绑定电话的方法
+     */
+    public function testunlockphone(){
+        $phone = 17052201940;
+        $sub_id = 1000027059330181;
+        var_dump($this->unLokPhone($phone,$sub_id));
+
+    }
+
+    /**
+     * 调用接口QueryCallStatus查询呼叫状态。
+     * @param $phone
+     * @author Liu-Yh
+     * Create By 2020/11/26 10:51
+     */
+    public function QueryCallStatus($phone,$SubsId){
+        $config = config('config.axb');
+        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
+            ->regionId('cn-kunming')
+            ->asDefaultClient();
+        try {
+            $result = AlibabaCloud::rpc()
+                ->product('Dyplsapi')
+                // ->scheme('https') // https | http
+                ->version('2017-05-25')
+                ->action('QueryCallStatus')
+                ->method('POST')
+                ->host('dyplsapi.aliyuncs.com')
+                ->options([
+                    'query' => [
+                        'RegionId' => "cn-hangzhou",
+                        "PoolKey" => $config['PoolKey'],
+                        "SubsId" => $SubsId,
+                    ],
+                ])
+                ->request();
+            $res = $result->toArray();
+            return $res;
+        } catch (ClientException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        } catch (ServerException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        }
+
+    }
+
+
+    /**
+     * 接收通话发起时的通话记录报告内容,可以在呼叫发起时立即获取到通话记录信息,包括通话开始时间、主被叫号码等,便于平台进行预判处理
+     * @author Liu-Yh
+     * Create By 2020/11/25 14:44
+     */
+    public function StartSecretReport(){
+        $config = config('config.axb');
+        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
+            ->regionId('cn-kunming')
+            ->asDefaultClient();
+        $queueName = $config['StartReport']; // 队列名称
+        $messageType = "SecretStartReport"; // 需要接收的消息类型
+        $response = null;
+        $token = null;
+        $i = 0;
+        do {
+            try {
+                if (null == $token || strtotime($token['ExpireTime']) - time() > 2 * 60) {
+                    $response = AlibabaCloud::rpcRequest()
+                        ->product('Dybaseapi')
+                        ->version('2017-05-25')
+                        ->action('QueryTokenForMnsQueue')
+                        ->method('POST')
+                        ->host("dybaseapi.aliyuncs.com")
+                        ->options([
+                            'query' => [
+                                'MessageType' => $messageType,
+                                'QueueName' => $queueName,
+                            ],
+                        ])
+                        ->request()
+                        ->toArray();
+                }
+                $token = $response['MessageTokenDTO'];
+                $mnsClient = new \AlibabaCloud\Dybaseapi\MNS\MnsClient(
+                    "http://1943695596114318.mns.cn-hangzhou.aliyuncs.com",
+                    $token['AccessKeyId'],
+                    $token['AccessKeySecret'],
+                    $token['SecurityToken']
+                );
+                $mnsRequest = new BatchReceiveMessage(10, 5);
+                $mnsRequest->setQueueName($queueName);
+                $mnsResponse = $mnsClient->sendRequest($mnsRequest);
+                $receiptHandles = Array();
+                foreach ($mnsResponse->Message as $message) {
+                    // 用户逻辑:
+                    // 入库
+//                    var_dump(base64_decode($message->MessageBody));
+//                    var_dump(json_decode(base64_decode($message->MessageBody),true));
+
+//                    $receiptHandles[] = $message->ReceiptHandle; // 加入$receiptHandles数组中的记录将会被删除
+                    $messageBody = json_decode(base64_decode($message->MessageBody),true); // base64解码后的JSON字符串
+                    echo "进来了";
+
+                    var_dump($messageBody);
+                }
+
+                if (count($receiptHandles) > 0) {
+                    $deleteRequest = new BatchDeleteMessage($queueName, $receiptHandles);
+                    $mnsClient->sendRequest($deleteRequest);
+                }
+            } catch (ClientException $e) {
+                echo $e->getErrorMessage() . PHP_EOL;
+            } catch (ServerException $e) {
+                if ($e->getCode() == 404) {
+                    $i++;
+                }
+                echo $e->getErrorMessage() . PHP_EOL;
+            }
+        } while ($i < 3);
+    }
+
+
+
+    /**
+     * 接收通话结束时的通话记录报告内容,可以在呼叫结束后获取通话记录信息,包括通话开始时间、通话结束时间、主被叫号码等,
+     * @author Liu-Yh
+     * Create By 2020/11/25 12:29
+     */
+    public function SecretPullReport(){
+        $config = config('config.axb');
+        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
+            ->regionId('cn-kunming')
+            ->asDefaultClient();
+        $queueName = $config['Report']; // 队列名称
+        $messageType = "SecretReport"; // 需要接收的消息类型
+        $response = null;
+        $token = null;
+        $i = 0;
+        do {
+            try {
+                if (null == $token || strtotime($token['ExpireTime']) - time() > 2 * 60) {
+                    $response = AlibabaCloud::rpcRequest()
+                        ->product('Dybaseapi')
+                        ->version('2017-05-25')
+                        ->action('QueryTokenForMnsQueue')
+                        ->method('POST')
+                        ->host("dybaseapi.aliyuncs.com")
+                        ->options([
+                            'query' => [
+                                'MessageType' => $messageType,
+                                'QueueName' => $queueName,
+                            ],
+                        ])
+                        ->request()
+                        ->toArray();
+                }
+                $token = $response['MessageTokenDTO'];
+                $mnsClient = new \AlibabaCloud\Dybaseapi\MNS\MnsClient(
+                    "http://1943695596114318.mns.cn-hangzhou.aliyuncs.com",
+                    $token['AccessKeyId'],
+                    $token['AccessKeySecret'],
+                    $token['SecurityToken']
+                );
+                $mnsRequest = new BatchReceiveMessage(10, 5);
+                $mnsRequest->setQueueName($queueName);
+                $mnsResponse = $mnsClient->sendRequest($mnsRequest);
+                $receiptHandles = Array();
+                $getList = CallLog::get();
+                if ($getList){
+                    $getList = $getList->toArray();
+                }
+                $msgs = $mnsResponse->Message;
+                if (!is_array($msgs)){
+                    $messageBody = json_decode(base64_decode($msgs->MessageBody),true); // base64解码后的JSON字符
+                    if (count($getList)==0){
+                        CallLog::create([
+                            'call_time'=>$messageBody['call_time'],
+                            'ring_time'=>$messageBody['release_time'],
+                            'release_dir'=>$messageBody['release_dir'],
+                            'call_type'=>$messageBody['call_type'],
+                            'aphone'=>$messageBody['phone_no'],
+                            'bphone'=>$messageBody['peer_no'],
+                            'call_id'=>$messageBody['call_id'],
+                            'secret_no'=>$messageBody['secret_no'],
+                            'sub_id'=>$messageBody['sub_id'],
+                            'talk_time'=> strtotime($messageBody['release_time'])-strtotime($messageBody['start_time']),
+                        ]);
+                    }else{
+                        foreach ($getList as $k=>$v){
+                            if ($v['call_id']==$messageBody['call_id']){
+                                unset($messageBody);
+                            }else{
+                                CallLog::create([
+                                    'call_time'=>$messageBody['call_time'],
+                                    'ring_time'=>$messageBody['release_time'],
+                                    'release_dir'=>$messageBody['release_dir'],
+                                    'call_type'=>$messageBody['call_type'],
+                                    'aphone'=>$messageBody['phone_no'],
+                                    'bphone'=>$messageBody['peer_no'],
+                                    'call_id'=>$messageBody['call_id'],
+                                    'secret_no'=>$messageBody['secret_no'],
+                                    'sub_id'=>$messageBody['sub_id'],
+                                    'talk_time'=> strtotime($messageBody['release_time'])-strtotime($messageBody['start_time']),
+                                ]);
+                            }
+                        }
+                    }
+                }else{
+                    foreach ($msgs as $message) {
+                        // 用户逻辑:
+                        $messageBody = json_decode(base64_decode($message->MessageBody),true); // base64解码后的JSON字符串
+                        if (count($getList)==0) {
+                            CallLog::create([
+                                'call_time'=>$messageBody['call_time'],
+                                'ring_time'=>$messageBody['release_time'],
+                                'release_dir'=>$messageBody['release_dir'],
+                                'call_type'=>$messageBody['call_type'],
+                                'aphone'=>$messageBody['phone_no'],
+                                'bphone'=>$messageBody['peer_no'],
+                                'call_id'=>$messageBody['call_id'],
+                                'secret_no'=>$messageBody['secret_no'],
+                                'sub_id'=>$messageBody['sub_id'],
+                                'talk_time'=> strtotime($messageBody['release_time'])-strtotime($messageBody['start_time']),
+                            ]);
+                        }else{
+                            foreach ($getList as $k=>$v){
+                                if ($v['call_id']==$messageBody['call_id']){
+                                    unset($messageBody);
+                                }else{
+                                    CallLog::create([
+                                        'call_time'=>$messageBody['call_time'],
+                                        'ring_time'=>$messageBody['release_time'],
+                                        'release_dir'=>$messageBody['release_dir'],
+                                        'call_type'=>$messageBody['call_type'],
+                                        'aphone'=>$messageBody['phone_no'],
+                                        'bphone'=>$messageBody['peer_no'],
+                                        'call_id'=>$messageBody['call_id'],
+                                        'secret_no'=>$messageBody['secret_no'],
+                                        'sub_id'=>$messageBody['sub_id'],
+                                        'talk_time'=> strtotime($messageBody['release_time'])-strtotime($messageBody['start_time']),
+                                    ]);
+                                }
+                            }
+                        }
+                     $receiptHandles[] = $message->ReceiptHandle; // 加入$receiptHandles数组中的记录将会被删除
+                    }
+                }
+                if (count($receiptHandles) > 0) {
+                    $deleteRequest = new BatchDeleteMessage($queueName, $receiptHandles);
+                    $mnsClient->sendRequest($deleteRequest);
+                }
+            } catch (ClientException $e) {
+                echo $e->getErrorMessage() . PHP_EOL;
+            } catch (ServerException $e) {
+                if ($e->getCode() == 404) {
+                    $i++;
+                }
+                echo $e->getErrorMessage() . PHP_EOL;
+            }
+        } while ($i < 3);
+
+    }
+
+
+
+
+    /**
+     * 通话开始时候回调数据
+     * @return false|string
+     * 返回参数
+     * [{
+        "phone_no": "18831138292",
+        "pool_key": "FC100000115024469", 对应的号池Key。
+        "city": "昆明",
+        "sub_id": 1000027052283144,  	通话对应的三元组的绑定关系ID。
+        "unconnected_cause": 0,
+        "call_time": "2020-12-21 17:23:56",  主叫拨打时间。
+        "peer_no": "15222021008",             AXB中的B号码或者N号码。
+        "called_display_no": "17052201941",   被叫显号X号码
+        "call_id": "31343639616333323735",  	唯一标识一通通话记录的ID。
+        "partner_key": "FC100000115024469",
+        "control_msg": "OK",
+        "id": 1007221453890,
+        "secret_no": "17052201941",
+        "call_type": 0,0:主叫(phone_no打给peer_no);1:被叫(peer_no打给phone_no);2:短信发送;3:短信接收;4:呼叫拦截;5:短信收发拦截;
+        "control_type": "CONTINUE"
+      }]
+     */
+    public function SecretStartReport(){
+        // 开始json
+        $req = request()->post();
+        // 首先创建记录
+        try {
+            $data = [];
+            $data['call_time'] = $req[0]['call_time'];
+            $data['call_type'] = $req[0]['call_type'];
+            $data['aphone'] = $req[0]['phone_no'];
+            $data['bphone'] = $req[0]['peer_no'];
+            $data['call_id'] = $req[0]['call_id'];
+            $data['secret_no'] = $req[0]['called_display_no'];
+            $data['sub_id'] = $req[0]['sub_id'];
+            CallLog::create($data);
+        }catch (\Exception $e){
+            var_dump($e->getFile().$e->getLine().$e->getMessage());
+
+        }catch (\PDOException $e){
+            var_dump($e->getFile().$e->getLine().$e->getMessage());
+        }
+
+        return json_encode(['code'=>0,'msg'=>"成功"],JSON_UNESCAPED_UNICODE);
+    }
+
+
+    /**
+     * 电话挂断时候回调数据!
+     * @return false|string
+     * 回调数据
+     * [{
+        "phone_no": "18831138292",              主叫号码
+        "pool_key": "FC100000115024469",        对应的号池Key。
+        "city": "昆明",
+        "sub_id": 1000027052283144, 	        通话对应的三元组的绑定关系ID。
+        "unconnected_cause": 0,                 0表示正常通话,1表示黑名单拦截,2表示无绑定关系,3表示呼叫限制,4表示其他
+        "call_time": "2020-12-21 17:23:56",     主叫拨打时间
+        "call_out_time": "2020-12-21 17:23:56", 呼叫由X送给B端局的时间
+        "peer_no": "15222021008",               AXB中的B号码或者N号码
+        "called_display_no": "17052201941",     被叫显号
+        "release_dir": 2,                       通话释放方向。0表示平台释放,1表示主叫挂断,2表示被叫挂断
+        "ring_time": "2020-12-21 17:23:56",     呼叫送被叫端局时,被叫端局响应的时间。
+        "call_id": "31343639616333323735",  	唯一标识一通通话记录的ID。
+        "start_time": "2020-12-21 17:24:05",    被叫接听时间
+        "free_ring_time": "2020-12-21 17:24:03",被叫手机真实的振铃时间。free_ring_time 大于call_out_time表示被叫真实发生了振铃事件。free_ring_time 和call_out_time相等表示未振铃。
+        "partner_key": "FC100000115024469",
+        "control_msg": "OK",
+        "id": 1007221453890,
+        "secret_no": "17052201941",             AXB中的X号码
+        "call_type": 0,                         呼叫类型,包括:0:主叫,即phone_no打给peer_no。1:被叫,即peer_no打给phone_no。2:短信发送。3:短信接收。4:呼叫拦截5:短信收发拦截
+        "release_cause": 16,                    释放原因。请根据编号在释放原因中查看。
+        "control_type": "CONTINUE",
+        "release_time": "2020-12-21 17:24:09"   被叫挂断时间。release_time和start_time之差表示通话时长, 如果结果为0,说明呼叫未接通
+        }]
+     *
+     */
+    public function SecretReport(){
+        $req = request()->post();
+        $callids = CallLog::where('call_id',$req[0]['call_id'])->first();
+        try {
+            if ($callids){
+                if($req[0]['release_dir']==0||(strtotime($req[0]['release_time'])-strtotime($req[0]['start_time']))==0||$req[0]['unconnected_cause']!=0){
+                    CallLog::where('call_id',$req[0]['call_id'])->delete();
+                }else{
+                    // 修改信息
+                    $axbId = Axb::where(['xphone'=>$req[0]['called_display_no'],'subs_id'=>$req[0]['sub_id']])->first();
+                    if($axbId){
+                        $where['docter_id'] = $axbId['docter_id'];
+                        $where['user_id'] = $axbId['user_id'];
+                        $where['product_type'] =1;
+                        $where['order_status'] =3;
+                        $where['payment_status'] =2;
+                        $order_id = Order::where($where)->first();
+                        if ($order_id){
+                            $order_id = $order_id->id;
+                            $save_data = [];
+                            $save_data['order_id'] = $order_id;
+                            $save_data['ring_time'] = $req[0]['release_time'];
+                            $save_data['docter_id'] = $axbId['docter_id'];
+                            $save_data['release_dir'] = $req[0]['release_dir'];
+                            $save_data['talk_time'] = strtotime($req[0]['release_time'])-strtotime($req[0]['start_time']);
+                            $save_data['text'] = json_encode($req,JSON_UNESCAPED_UNICODE);
+                            // 解除号码绑定,并且删除数据库绑定信息
+                            $this->unLokPhone($req[0]['called_display_no'],$req[0]['sub_id']);
+                            Axb::where(['subs_id'=>$req[0]['sub_id']])->delete();
+                            CallLog::where('call_id',$req[0]['call_id'])->update($save_data);
+                            return json_encode(['code'=>0,'msg'=>"成功"],JSON_UNESCAPED_UNICODE);
+                        }
+                    }
+                }
+            }
+
+        }catch (\Exception $e){
+            CallLog::create(['text'=>json_encode($e->getFile().$e->getCode().$e->getMessage(),JSON_UNESCAPED_UNICODE)]);
+        }catch (\PDOException $e){
+            CallLog::create(['text'=>json_encode($e->getFile().$e->getCode().$e->getMessage(),JSON_UNESCAPED_UNICODE)]);
+        }
+
+    }
+
+
+    /**
+     * goEasy聊天记录存入数据库
+     * * @return false|string
+     */
+    public function easyMessage(){
+        $req = request()->post();
+        try {
+            $data = json_decode($req['content'],true);
+            $ImList = ImMessage::get();
+            $newList=[];
+            if ($ImList){
+                foreach ($ImList as $k=>$v){
+                    $newList[$k] = $v['messageId'];
+                }
+            }
+            $list = [];
+            if($data){
+                foreach ($data as $k=>$v){
+                    if(!in_array($v['messageId'],$newList)){
+                        $list[$k]['messageId'] = $v['messageId'];
+                        $list[$k]['type'] = $v['type'];
+                        $list[$k]['senderId'] = $v['senderId'];
+                        $list[$k]['receiverId'] = $v['receiverId'];
+                        $list[$k]['timestamp'] = $v['timestamp'];
+                        $list[$k]['payload'] = $v['payload'];
+                        $list[$k]['text'] = $req['content'];
+                        $list[$k]['create_time'] = time();
+                    }
+                }
+                ImMessage::insert($list);
+            }else{
+                $list['text'] = $req['content'];
+                ImMessage::create($list);
+
+            }
+            return json_encode(['code'=>200,'content'=>'success']);
+        }catch (\Exception $e){
+            ImMessage::create(['text'=>json_encode($e->getFile().'的第 '.$e->getLine().'行报错:'.$e->getMessage(),true)]);
+        }catch (\PDOException $e){
+            ImMessage::create(['text'=>json_encode($e->getFile().'的第 '.$e->getLine().'行报错:'.$e->getMessage(),true)]);
+        }
+
+    }
+}

+ 118 - 0
app/Http/Controllers/Api/V2/DocterMessageController.php

xqd
@@ -0,0 +1,118 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Yuanhang Liu
+ * Date: 20-10-15
+ * Time: 下午8:46
+ */
+
+namespace App\Http\Controllers\Api\V2;
+
+use App\Models\Order;
+use App\Models\Patient;
+use App\Models\CallLog;
+use App\Models\OrderPatient;
+use App\Models\DocterOrganization;
+use App\Models\Organization;
+use App\Models\DocterMessage;
+use App\Http\Controllers\Api\V2\CommonController as Commons;
+
+/**
+ * 医生通知类
+ * Class DocterMessageController
+ * @package App\Http\Controllers\Api\V2
+ */
+class DocterMessageController extends AuthController
+{
+    /**
+     * @return mixed
+     * 医生通知列表
+     * @author Yuanhang Liu & Xiaoyun Liu
+     */
+    public function docterMessageList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'curPage' => 'required|integer',
+            'pageSize' => 'required|integer',
+        ]);
+        $pageSize = ($req['curPage']-1)*$req['pageSize'];
+        $user = $this->user;
+        $doctor_id = $user['id'];
+
+        $where['docter_id'] = $doctor_id;
+        $data = DocterMessage::where($where)->orderBy('id', 'desc')->skip($pageSize)->take($req['pageSize'])->get();
+
+        if ($data){
+            $data = $data->toArray();
+
+        }else{
+            return out([]);
+        }
+        return out($data);
+    }
+
+    /**
+     * @return mixed
+     * 删除医生通知
+     * @author Yuanhang Liu & Xiaoyun Liu
+     */
+    public function delDocterMessage()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'id' => 'required|integer',
+        ]);
+
+        $del = DocterMessage::where('id','=',$req['id'])->delete();
+        if ($del){
+            return out();
+        }else{
+            return out('',500,'删除错误!');
+        }
+
+    }
+
+    /**
+     * @return mixed
+     * 全部标为已读医生通知
+     * @author Yuanhang Liu & Xiaoyun Liu
+     */
+    public function okDocterMessage()
+    {
+        $req = request()->post();
+//        $this->validate(request(), [
+//            'id' => 'required|integer',
+//        ]);
+        $user = $this->user;
+        $del = DocterMessage::where('docter_id','=',$user['id'])->update(['status'=>2]);
+        if ($del){
+            return out();
+        }else{
+            return out('',500,'操作失败!');
+        }
+
+    }
+
+    /**
+     * 标记已读
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/12/9 10:46
+     */
+    public function readOk()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'id' => 'required|integer',
+        ]);
+        $user = $this->user;
+        $del = DocterMessage::where('id','=',$req['id'])->update(['status'=>2]);
+        if ($del){
+            return out();
+        }else{
+            return out('',500,'操作失败!');
+        }
+
+    }
+}

+ 3158 - 0
app/Http/Controllers/Api/V2/DoctorController.php

xqd
@@ -0,0 +1,3158 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Yuanhang Liu & Xiaoyun Liu
+ * Date: 20-10-14
+ * Time: 下午2:50
+ */
+
+namespace App\Http\Controllers\Api\V2;
+
+use App\Http\Controllers\Api\V1\AuthController;
+use App\Models\Docter;
+use App\Models\Office;
+use App\Models\Order;
+use App\Models\OrderPack;
+use App\Models\OrderPatient;
+use App\Models\Patient;
+use App\Models\Qualification;
+use App\Models\Suggest;
+use App\Models\Areas;
+use App\Models\Collection as Collections;
+use App\Models\Organization;
+use App\Models\DocterTimes;
+use App\Models\DocterOrganization;
+use App\Http\Controllers\Api\V2\CommonController as Commons;
+use App\Models\Team;
+use App\Models\User;
+use Illuminate\Support\Facades\DB;
+use MongoDB\BSON\ObjectId;
+use PhpParser\Comment\Doc;
+use App\Models\DocterUser;
+use App\Models\Schedule;
+use App\Models\TimePeriod;
+use App\Models\SchedulePeriod;
+use App\Models\DocterMessage;
+use App\Models\Evaluate;
+use App\Models\UserDocter;
+use App\Models\ServiceApply;
+use App\Models\SystemConfig;
+use App\Models\WeekSchedule;
+use App\Models\SelfSchedule;
+use App\Models\DocterSetting;
+use App\Models\DocterServiceTimes;
+use App\Models\CallLog;
+use App\Models\ImMessage;
+use App\Models\DocterLable;
+
+/**
+ * 医生相关类
+ * Auth Yuanhang Liu
+ * Date 2020/10/14 15:06
+ * Class DoctorController
+ * @package App\Http\Controllers\Api\V2
+ */
+class DoctorController extends AuthController
+{
+
+    /**service_schedule
+     * @return \Illuminate\Http\JsonResponse
+     * 首页医生个人信息接口
+     */
+    public function doctorInfor()
+    {
+        $req = $this->user;
+        $data = Docter::where('phone', $req['phone'])->first(['id', 'name', 'avatar', 'label', 'sign', 'intro', 'service_days', 'service_persons','password', 'eva_num', 'score', 'is_then', 'created_at']);
+
+        if (!empty($data)) {
+
+            // 获取标签
+            $LabFind = [];
+            if ($data['label']!='无'){
+                if(count($data['label'])!=0){
+                    $labstr = $data['label'];
+                    $LabFind = DocterLable::whereIn('id',$labstr)->where('status',1)->select('label_name')->get();
+                }
+            }
+
+
+
+            $data['label'] = $LabFind;
+//            $counts = Evaluate::where('docter_id', '=', $req['id'])->count();
+            $evalList = Evaluate::where('docter_id', '=', $req['id'])->get();
+            $counts = count($evalList);
+
+
+            $data['eva_num'] = $counts;
+            $soc = 0;
+            if ($counts != 0) {
+                $evalList = $evalList->toArray();
+                foreach ($evalList as $k => $v) {
+                    $soc += $v['score'];
+                }
+                $data['score'] = upDecimal($soc / $counts, 1);
+            }
+
+            $data['service_days'] = numDays(date('Y-m-d', strtotime($data['created_at'])));
+            return out($data);
+        } else {
+            return exit_out($data, 1, '参数错误,数据不存在');
+        }
+
+    }
+
+    /**
+     * 医生端个人信息修改
+     * @return mixed
+     */
+    public function doctorInfoEdit()
+    {
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        if (request()->isMethod('post')) {
+            $req = request()->post();
+            $this->validate(request(), [
+                'avatar' => 'string',
+                'sign' => 'max:255',
+//            'phone|手机号不正确' => 'regex:/^1[3456789][0-9]{9}$/',
+                'intro' => 'max:2555'
+            ]);
+            $data = [];
+            if (isset($req['avatar']) && !empty($req['avatar'])) {
+                $data['avatar'] = $req['avatar'];
+            }
+            if (isset($req['sign']) && !empty($req['sign'])) {
+                $data['sign'] = $req['sign'];
+            }
+            if (isset($req['intro']) && !empty($req['intro'])) {
+                $data['intro'] = $req['intro'];
+            }
+
+            if (empty($data)) {
+                return out();
+            }
+            if ($doctor_id) {
+                $save = Docter::where('id', $doctor_id)->update($data);
+                return out();
+            }
+        } else {
+            // get提交哈
+            $list = Docter::where('id', '=', $doctor_id)->first()->toArray();
+            // 头像,个人标签,服务简介展示
+            $data = [
+                'avatar' => !empty($list['avatar'])?$list['avatar']:'',
+                'sign' => !empty($list['sign'])?$list['sign']:'',
+                'intro' => !empty($list['intro'])?$list['intro']:'',
+            ];
+            return out($data);
+        }
+    }
+
+
+    /**
+     * 修改密码
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/11/4 18:19
+     */
+    public function passwordEdit()
+    {
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $req = request()->post();
+        $this->validate(request(), [
+            'lis:原密码' => 'string',
+            'newpassword:新密码' => 'string',
+        ]);
+        $data = [];
+        $data = Docter::where('id', '=', $doctor_id)->first()->toArray();
+        $password = md5(md5(md5($req['newpassword'])));
+        if ($data['password'] == '' || !$data['password']) {
+            // 说明第一次直接跳过
+            $save = Docter::where('id', $doctor_id)->update(['password' => $password]);
+            return out();
+        } else {
+            if(isset($req['lis'])&&!empty($req['lis'])){
+                $oldpassword = md5(md5(md5($req['lis'])));
+                if ($oldpassword != $data['password']) {
+                    return out('', '401', '旧密码错误');
+                } else {
+                    $save = Docter::where('id', $doctor_id)->update(['password' => $password]);
+                    return out();
+                }
+            }else{
+                return out('', '401', '请输入旧密码');
+
+            }
+
+        }
+    }
+
+
+    /**
+     * 基本/更多设置读取(废弃)
+     * @return \Illuminate\Http\JsonResponse
+     * @author Yuanhang Liu
+     */
+    public function getSettingList()
+    {
+        $req = request()->post();
+
+        $this->validate(request(), [
+            'type' => 'required|integer|in:1,2',
+            'service_type' => 'integer'
+        ]);
+        $user = $this->user;
+        $doctor_id = (new Commons)->getUserIdByDoctorId($user['phone']);
+        $finds = Docter::select(['is_chat', 'is_phone', 'is_appoint'])->where('id', $doctor_id)->first()->toArray();
+
+        $finds['is_chat'] = $finds['is_chat'] == 0 ? false : true;
+        $finds['is_phone'] = $finds['is_phone'] == 0 ? false : true;
+        $finds['is_appoint'] = $finds['is_appoint'] == 0 ? false : true;
+        $finds['is_chat_status'] = $this->getStyStatus(1);
+        $finds['is_phone_status'] = $this->getStyStatus(2);
+        $finds['is_appoint_status'] = $this->getStyStatus(3);
+
+        if ($req['type'] == 2) {
+            (array)$list = [];
+            // 获取显示状态:
+            $list['show'] = $finds;
+
+            // 获取电话咨询时间
+            $phone_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 1])->first();
+            if ($phone_fins) {
+                $phone_fins = $phone_fins->toArray();
+            } else {
+                $phone_fins = [];
+            }
+            $list['list']['phone'] = $phone_fins;
+            // 图文咨询时间
+            $pic_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 2])->first();
+            if ($pic_fins) {
+                $pic_fins = $pic_fins->toArray();
+            } else {
+                $pic_fins = [];
+            }
+            $list['list']['chat'] = $pic_fins;
+            // 门诊咨询时间
+
+            $men_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 3])->get();
+            if ($men_fins) {
+                $men_fins = $men_fins->toArray();
+            } else {
+                $men_fins = [];
+            }
+            $list['list']['men'] = $men_fins;
+
+            // 获取医院
+            $org = DocterOrganization::with('organization')->where('docter_id', $doctor_id)->get();
+            $org_pre = [];
+            $org_pres = [];
+            if ($org) {
+                $org = $org->toArray();
+                foreach ($org as $k => $v) {
+                    $org_pres[$k]['id'] = $v['organization']['id'];
+                    $org_pres[$k]['name'] = $v['organization']['name'];
+                    $org_pre[$k]['name'] = $v['organization']['name'];
+                }
+            }
+            $list['org'] = $org_pre;
+            $list['orgs'] = $org_pres;
+            $times = TimePeriod::get();
+            if ($times) {
+                $times = $times->toArray();
+                $newTimes = [];
+                foreach ($times as $k => $v) {
+                    $newTimes[$k]['id'] = $v['id'];
+                    $newTimes[$k]['name'] = $v['start_time_period'] . ' - ' . $v['end_time_period'];
+                    $newTimes[$k]['checked'] = false;
+                }
+                $times1 = [];
+                $times2 = [];
+                $times3 = [];
+                foreach ($newTimes as $k => $v) {
+                    if ($k >= 0 && $k < 16) {
+                        array_push($times1, $v);
+                    } else if ($k >= 16 && $k < 32) {
+                        array_push($times2, $v);
+                    } else {
+                        array_push($times3, $v);
+                    }
+                }
+                $list['times']['list1'] = $times1;
+                $list['times']['list2'] = $times2;
+                $list['times']['list3'] = $times3;
+            } else {
+                $times = [];
+            }
+            return out($list);
+        }
+        return out($finds);
+    }
+
+
+    /**
+     * 更多设置读取,新的
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/12/16 11:10
+     */
+    public function getSettingListnew()
+    {
+        $req = request()->post();
+
+        $this->validate(request(), [
+            'type' => 'required|integer|in:1,2',
+            'service_type' => 'integer'
+        ]);
+        $user = $this->user;
+        $doctor_id = (new Commons)->getUserIdByDoctorId($user['phone']);
+        $finds = Docter::select(['is_chat', 'is_phone', 'is_appoint'])->where('id', $doctor_id)->first()->toArray();
+
+        $finds['is_chat'] = $finds['is_chat'] == 0 ? false : true;
+        $finds['is_phone'] = $finds['is_phone'] == 0 ? false : true;
+        $finds['is_appoint'] = $finds['is_appoint'] == 0 ? false : true;
+        $finds['is_chat_status'] = $this->getStyStatus(1);
+        $finds['is_phone_status'] = $this->getStyStatus(2);
+        $finds['is_appoint_status'] = $this->getStyStatus(3);
+
+
+        if ($req['type'] == 2) {
+            (array)$list = [];
+            // 获取显示状态:
+            $list['show'] = $finds;
+            // 获取电话咨询时间
+            $phone_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 1])->first();
+            if ($phone_fins) {
+                $phone_fins = $phone_fins->toArray();
+                $phone_fins['service_time'] = json_decode($phone_fins['service_time']);
+            } else {
+                $phone_fins = [];
+            }
+            $list['list']['phone'] = $phone_fins;
+            // 图文咨询时间
+            $pic_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 2])->first();
+            if ($pic_fins) {
+                $pic_fins = $pic_fins->toArray();
+                $pic_fins['service_time'] = json_decode($pic_fins['service_time']);
+
+            } else {
+                $pic_fins = [];
+            }
+            $list['list']['chat'] = $pic_fins;
+            // 门诊咨询时间
+            $newLists=[];
+            $men_fins = DocterSetting::where(['docter_id' => $doctor_id, 'type' => 1])->orderBy('org_id','asc')->get();
+            $org = DocterOrganization::with('organization')->where(['docter_id'=>$doctor_id,'state'=>1])->orderBy('organization_id','asc')->get();
+            if ($org) {
+                $org = $org->toArray();
+                foreach ($org as $k => $v) {
+                    $org_pre[$k]['id'] = $v['organization']['id'];
+                    $org_pre[$k]['name'] = $v['organization']['name'];
+                }
+            }
+
+            if ($men_fins) {
+                $men_fins = $men_fins->toArray();
+
+                foreach ($men_fins as $k => $v) {
+                    $men_fins[$k]['service_time'] = json_decode($v['service_time'],true);
+                }
+
+                $org_list=[];
+
+                foreach ($org as $k=>$v){
+                    $org_list[$k]['docter_id'] = $doctor_id;
+                    $org_list[$k]['type'] = 1;
+                    $org_list[$k]['status'] = 2;
+                    $org_list[$k]['show_days'] = '';
+                    $org_list[$k]['service_times'] = '';
+                    $org_list[$k]['service_num'] = '';
+                    $org_list[$k]['org_id'] = $v['organization']['id'];
+                    $org_list[$k]['org_name'] = $v['organization']['name'];
+                    $org_list[$k]['appoint_price'] = '';
+                    $org_list[$k]['service_time'] = [
+                        1=>['amStartTime'=>'','amEndTime'=>'','amPerson'=>''],
+                        2=>['pmStartTime'=>'','pmEndTime'=>'','pmPerson'=>''],
+                        3=>['nightStartTime'=>'','nightEndTime'=>'','nightPerson'=>''],
+                    ];
+                }
+                foreach ($org_list as $k=>$v){
+                    foreach ($men_fins as $kk=>$vv){
+                        if ($v['org_id']==$vv['org_id']){
+                            $org_list[$k]['docter_id'] = $doctor_id;
+                            $org_list[$k]['type'] = 1;
+                            $org_list[$k]['status'] = 2;
+                            $org_list[$k]['show_days'] = $vv['show_days'];
+                            $org_list[$k]['service_times'] = $vv['service_times'];
+                            $org_list[$k]['service_num'] = $vv['service_num'];
+                            $org_list[$k]['org_id'] = $vv['org_id'];
+                            $org_list[$k]['org_name'] = $v['org_name'];
+                            $org_list[$k]['appoint_price'] = $vv['appoint_price'];
+                            $org_list[$k]['service_time'] = [
+                                1=>['amStartTime'=>$vv['service_time'][1]['amStartTime'],'amEndTime'=>$vv['service_time'][1]['amEndTime'],'amPerson'=>$vv['service_time'][1]['amPerson']],
+                                2=>['pmStartTime'=>$vv['service_time'][2]['pmStartTime'],'pmEndTime'=>$vv['service_time'][2]['pmEndTime'],'pmPerson'=>$vv['service_time'][2]['pmPerson']],
+                                3=>['nightStartTime'=>$vv['service_time'][3]['nightStartTime'],'nightEndTime'=>$vv['service_time'][3]['nightEndTime'],'nightPerson'=>$vv['service_time'][3]['nightPerson']],
+                            ];
+                        }
+                    }
+
+                }
+                $newLists = $org_list;
+            } else {
+                $men_fins = [];
+                foreach ($org as $k=>$v){
+                    $newLists[$k]['docter_id'] = $doctor_id;
+                    $newLists[$k]['type'] = 1;
+                    $newLists[$k]['status'] = 2;
+                    $newLists[$k]['show_days'] = '';
+                    $newLists[$k]['service_times'] = '';
+                    $newLists[$k]['service_num'] = '';
+                    $newLists[$k]['org_id'] = $v['organization']['id'];
+                    $newLists[$k]['org_name'] = $v['organization']['name'];
+                    $newLists[$k]['appoint_price'] = '';
+                    $newLists[$k]['service_time'] = [
+                        1=>['amStartTime'=>'','amEndTime'=>'','amPerson'=>''],
+                        2=>['pmStartTime'=>'','pmEndTime'=>'','pmPerson'=>''],
+                        3=>['nightStartTime'=>'','nightEndTime'=>'','nightPerson'=>''],
+                    ];
+                }
+            }
+
+            // 获取医院
+//            $org_pre = [];
+
+            $list['list']['men'] = $newLists;
+
+//            $list['org'] = $org_pre;
+            return out($list);
+        }
+        return out($finds);
+    }
+
+
+
+
+
+
+    /**
+     * 获取审核状态
+     * @param $type
+     * @return bool
+     */
+    public function getStyStatus($type)
+    {
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $where['docter_id'] = $doctor_id;
+        $where['service_type'] = $type;
+        $statusD = ServiceApply::where($where)->first();
+        if ($statusD) {
+            return $statusD;
+        } else {
+            return false;
+        }
+    }
+
+
+    /**
+     * 基本/更多设置修改
+     * @return \Illuminate\Http\JsonResponse
+     * @author Yuanhang Liu
+     */
+    public function saveSettingList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'type' => 'required|integer|in:1,2',
+        ]);
+        $data = json_decode($req['data'], true);
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $finds = Docter::select(['is_chat', 'is_phone', 'is_appoint'])->where('id', $doctor_id)->first();
+
+        $flag = false;
+        if ($req['type'] == 1) {
+            // 修改基本信息
+            $list = [];
+            isset($data['is_chat']) ? $data['is_chat'] == true ? $list['is_chat'] = 1 : $list['is_chat'] = 0 : '';
+            isset($data['is_phone']) ? $data['is_phone'] == true ? $list['is_phone'] = 1 : $list['is_phone'] = 0 : '';
+            isset($data['is_appoint']) ? $data['is_appoint'] == true ? $list['is_appoint'] = 1 : $list['is_appoint'] = 0 : '';
+            Docter::where('id', $doctor_id)->update($list);
+            return out();
+        } else if ($req['type'] == 2) {
+            Db::beginTransaction();
+            try {
+                // 修改更多信息
+                if ($finds['is_chat'] == 0) {
+                    if (isset($data['is_chat']) && !empty($data['is_chat'])) {
+                        unset($data['is_chat']);
+
+                    }
+                } else {
+                    if (isset($data['is_chat']) && !empty($data['is_chat'])) {
+                        DocterServiceTimes::where(['docter_id'=>$doctor_id,'type'=>2])->delete();
+                        $save_data = $data['is_chat'];
+                        $newData = [];
+                        $serviceData = [];
+                        $newData['base_price'] = $save_data['base_price'];
+                        $newData['step_price'] = $save_data['step_price'];
+                        $serviceData[0]['docter_id']=$doctor_id;
+                        $serviceData[0]['type']=2;
+                        $serviceData[0]['start_time_period']=$save_data['amStartTime'];
+                        $serviceData[0]['end_time_period']=$save_data['amEndTime'];
+                        $serviceData[0]['start_time_line']=str_replace(':','',$save_data['amStartTime']);
+                        $serviceData[0]['end_time_line']=str_replace(':','',$save_data['amEndTime']);
+
+                        $serviceData[1]['docter_id']=$doctor_id;
+                        $serviceData[1]['type']=2;
+                        $serviceData[1]['start_time_period']=$save_data['pmStartTime'];
+                        $serviceData[1]['end_time_period']=$save_data['pmEndTime'];
+                        $serviceData[1]['start_time_line']=str_replace(':','',$save_data['pmStartTime']);
+                        $serviceData[1]['end_time_line']=str_replace(':','',$save_data['pmEndTime']);
+
+                        $serviceData[2]['docter_id']=$doctor_id;
+                        $serviceData[2]['type']=2;
+                        $serviceData[2]['start_time_period']=$save_data['nightStartTime'];
+                        $serviceData[2]['end_time_period']=$save_data['nightEndTime'];
+                        $serviceData[2]['start_time_line']=str_replace(':','',$save_data['nightStartTime']);
+                        $serviceData[2]['end_time_line']=str_replace(':','',$save_data['nightEndTime']);
+
+
+
+
+                        $service_times = [
+                            1 => ['amStartTime' => $save_data['amStartTime'], 'amEndTime' => $save_data['amEndTime']],
+                            2 => ['pmStartTime' => $save_data['pmStartTime'], 'pmEndTime' => $save_data['pmEndTime']],
+                            3 => ['nightStartTime' => $save_data['nightStartTime'], 'nightEndTime' => $save_data['nightEndTime']],
+                        ];
+                        $newData['service_time'] = json_encode($service_times, JSON_UNESCAPED_UNICODE);
+                        $newData['person'] = $save_data['person'];
+                        $newData['type'] = $save_data['type'];
+                        $pic_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 2])->first();
+
+                        DocterServiceTimes::insert($serviceData);
+                        if (empty($pic_fins)) {
+                            $newData['docter_id'] = $doctor_id;
+                            DocterTimes::create($newData);
+                        } else {
+                            $pic_fins = $pic_fins->toArray();
+                            DocterTimes::where(['id' => $pic_fins['id']])->update($newData);
+                        }
+                    }
+                }
+                if ($finds['is_phone'] == 0) {
+                    if (isset($data['is_phone']) && !empty($data['is_phone'])) {
+                        unset($data['is_phone']);
+                    }
+                } else {
+                    if (isset($data['is_phone']) && !empty($data['is_phone'])) {
+                        // 存入状态为1的操作
+                        DocterServiceTimes::where(['docter_id'=>$doctor_id,'type'=>1])->delete();
+
+                        $save_data = $data['is_phone'];
+                        $newData = [];
+                        $serviceData = [];
+
+                        $newData['base_price'] = $save_data['base_price'];
+                        $newData['step_price'] = $save_data['step_price'];
+
+                        $serviceData[0]['docter_id']=$doctor_id;
+                        $serviceData[0]['type']=1;
+                        $serviceData[0]['start_time_period']=$save_data['amStartTime'];
+                        $serviceData[0]['end_time_period']=$save_data['amEndTime'];
+                        $serviceData[0]['start_time_line']=str_replace(':','',$save_data['amStartTime']);
+                        $serviceData[0]['end_time_line']=str_replace(':','',$save_data['amEndTime']);
+
+                        $serviceData[1]['docter_id']=$doctor_id;
+                        $serviceData[1]['type']=1;
+                        $serviceData[1]['start_time_period']=$save_data['pmStartTime'];
+                        $serviceData[1]['end_time_period']=$save_data['pmEndTime'];
+                        $serviceData[1]['start_time_line']=str_replace(':','',$save_data['pmStartTime']);
+                        $serviceData[1]['end_time_line']=str_replace(':','',$save_data['pmEndTime']);
+
+                        $serviceData[2]['docter_id']=$doctor_id;
+                        $serviceData[2]['type']=1;
+                        $serviceData[2]['start_time_period']=$save_data['nightStartTime'];
+                        $serviceData[2]['end_time_period']=$save_data['nightEndTime'];
+                        $serviceData[2]['start_time_line']=str_replace(':','',$save_data['nightStartTime']);
+                        $serviceData[2]['end_time_line']=str_replace(':','',$save_data['nightEndTime']);
+
+                        $service_times = [
+                            1 => ['amStartTime' => $save_data['amStartTime'], 'amEndTime' => $save_data['amEndTime']],
+                            2 => ['pmStartTime' => $save_data['pmStartTime'], 'pmEndTime' => $save_data['pmEndTime']],
+                            3 => ['nightStartTime' => $save_data['nightStartTime'], 'nightEndTime' => $save_data['nightEndTime']],
+                        ];
+                        $newData['service_time'] = json_encode($service_times, JSON_UNESCAPED_UNICODE);
+                        $newData['person'] = $save_data['person'];
+                        $newData['type'] = $save_data['type'];
+                        // 图文咨询时间
+                        $phone_fins = DocterTimes::where(['docter_id' => $doctor_id, 'type' => 1])->first();
+                        DocterServiceTimes::insert($serviceData);
+                        if (empty($phone_fins)) {
+                            $newData['docter_id'] = $doctor_id;
+                            DocterTimes::create($newData);
+                        } else {
+                            $phone_fins = $phone_fins->toArray();
+                            DocterTimes::where(['id' => $phone_fins['id']])->update($newData);
+                        }
+                    }
+                }
+                if ($finds['is_appoint'] == 0) {
+                    if (isset($data['is_appoint']) && !empty($data['is_appoint'])) {
+                        unset($data['is_appoint']);
+                    }
+                } else {
+                    // 此时可能有两个医院,为一个数组,一个一个入库
+                    if (isset($data['is_appoint']) && !empty($data['is_appoint'])) {
+                        $save_data = $data['is_appoint'];
+                        $setting_data = [];
+                        $times_data = [];
+                        // 查询除本地来
+                        $edutime = DocterSetting::where(['docter_id' => $doctor_id, 'type' => 1])->get();
+                        if ($edutime) {
+                            $newedu = [];
+                            foreach ($edutime as $k => $v) {
+                                $newedu[$k]['org_id'] = $v['org_id'];
+                                $newedu[$k]['service_times'] = $v['service_times'];
+                            }
+                            $flag_arr = [];
+                            foreach ($newedu as $k => $v) {
+                                foreach ($save_data as $kk => $vv) {
+                                    if ($v['org_id'] == $vv['org_id']) {
+                                        if ($v['service_times'] != $vv['service_times']) {
+                                            $flag_arr[] = $vv['org_id'];
+                                        }
+                                    }
+                                }
+                            }
+                            $flag = !empty($flag_arr) ? $flag_arr : false;
+                        }
+                        foreach ($save_data as $k => $v) {
+                            if (!isset($v['service_times'])||empty($v['service_times'])){
+                                unset($save_data[$k]);
+                            }else{
+                                DocterSetting::where('docter_id', '=', $doctor_id)->where('org_id', $v['org_id'])->delete();
+                                TimePeriod::where('docter_id', '=', $doctor_id)->where('org_id', $v['org_id'])->delete();
+                                $setting_data[$k]['docter_id'] = $doctor_id;
+                                $setting_data[$k]['type'] = 1;
+                                $setting_data[$k]['status'] = 2;
+                                $setting_data[$k]['appoint_price'] = $v['base_price'];
+                                $setting_data[$k]['show_days'] = $v['show_days'];
+                                $setting_data[$k]['service_times'] = $v['service_times'];
+                                $setting_data[$k]['service_num'] = $v['service_num'];
+                                $setting_data[$k]['org_id'] = $v['org_id'];
+                                $service_times = [
+                                    1 => ['amStartTime' => $v['amStartTime'], 'amEndTime' => $v['amEndTime'], 'amPerson' => $v['amPerson']],
+                                    2 => ['pmStartTime' => $v['pmStartTime'], 'pmEndTime' => $v['pmEndTime'], 'pmPerson' => $v['pmPerson']],
+                                    3 => ['nightStartTime' => $v['nightStartTime'], 'nightEndTime' => $v['nightEndTime'], 'nightPerson' => $v['nightPerson']],
+                                ];
+                                $setting_data[$k]['service_time'] = json_encode($service_times, JSON_UNESCAPED_UNICODE);
+                                $setting_data[$k]['created_at'] = date('Y-m-d H:i:s', time());
+                                $setting_data[$k]['updated_at'] = date('Y-m-d H:i:s', time());
+                                // 第二步, 根据时长去生成24小时的时间段,也要存id
+
+                                $timeList = $this->getTimeHoures($v['service_times']);
+                                foreach ($timeList as $kk => $vv) {
+                                    $times_data[$k][$kk]['type'] = 2;
+                                    $times_data[$k][$kk]['docter_id'] = $doctor_id;
+                                    $times_data[$k][$kk]['start_time_period'] = $vv[0];
+                                    $times_data[$k][$kk]['end_time_period'] = $vv[1];
+                                    $times_data[$k][$kk]['org_id'] = $v['org_id'];
+                                }
+                            }
+
+                        }
+                        if($times_data&&$setting_data){
+                            foreach ($times_data as $k => $v) {
+                                TimePeriod::insert($v);
+                            }
+                            DocterSetting::insert($setting_data);
+                        }
+                    }
+                }
+                DB::commit();
+            } catch (\Exception $e) {
+                DB::rollBack();
+                return out('', 500, $e->getMessage());
+            } catch (\PDOException $e) {
+                DB::rollBack();
+                return out('', 500, $e->getMessage());
+            }
+
+            if ($finds['is_appoint'] != 0 && isset($data['is_appoint']) && !empty($data['is_appoint'])) {
+                /*去重新更新,自定义排班表,和排班详情表,因为时间段id发生了变化!*/
+
+                if ($flag != false) {
+                    $weekList = WeekSchedule::where('docter_id', $doctor_id)->get();
+                    $moth_date = $this->date_bool();
+                    $counts = Schedule::where('schedule_date', '>=', $moth_date[0]['date'])->where('schedule_date', '<=', end($moth_date)['date'])->get();
+                    if ($weekList && $counts) {
+                        $weekList = $weekList->toArray();
+                        $selfScheduleList = SelfSchedule::where('docter_id', $doctor_id)->whereIn('organization_id', $flag)->get();
+                        // 修改自定义表 不存在则不管就好
+                        SchedulePeriod::where('docter_id', '=', $doctor_id)->delete();
+                        if ($selfScheduleList) {
+                            $selfScheduleList = $selfScheduleList->toArray();
+                            $selfList = [];
+                            foreach ($selfScheduleList as $k => $v) {
+                                if (!isset($selfList[$v['schedule_date']])) {
+                                    $selfList[$v['schedule_date']] = $v;
+                                    if ($v['type'] == 1) {
+                                        $selfList[$v['schedule_date']]['ident']['zao_id'] = $v['organization_id'];
+                                        $selfList[$v['schedule_date']]['ident']['xia_id'] = 0;
+                                        $selfList[$v['schedule_date']]['ident']['wan_id'] = 0;
+                                    } else if ($v['type'] == 2) {
+                                        $selfList[$v['schedule_date']]['ident']['zao_id'] = 0;
+                                        $selfList[$v['schedule_date']]['ident']['xia_id'] = $v['organization_id'];
+                                        $selfList[$v['schedule_date']]['ident']['wan_id'] = 0;
+                                    } else {
+                                        $selfList[$v['schedule_date']]['ident']['zao_id'] = 0;
+                                        $selfList[$v['schedule_date']]['ident']['xia_id'] = 0;
+                                        $selfList[$v['schedule_date']]['ident']['wan_id'] = $v['organization_id'];
+                                    }
+                                } else {
+                                    if ($v['type'] == 1) {
+                                        $selfList[$v['schedule_date']]['ident']['zao_id'] = $v['organization_id'];
+                                    } else if ($v['type'] == 2) {
+                                        $selfList[$v['schedule_date']]['ident']['xia_id'] = $v['organization_id'];
+                                    } else {
+                                        $selfList[$v['schedule_date']]['ident']['wan_id'] = $v['organization_id'];
+                                    }
+                                }
+                            }
+
+                            // 拼接数据交给saveDay来操作
+                            $saveDatas = [];
+                            SelfSchedule::where('docter_id', $doctor_id)->delete();
+                            foreach ($selfList as $k => $v) {
+                                $saveDatas[$k]['schedule_date'] = $v['schedule_date'];
+                                $saveDatas[$k]['week'] = $v['week'];
+                                if ($v['ident']['zao_id']) {
+                                    $saveDatas[$k]['type'] = 1;
+                                    $saveDatas[$k]['organization_id'] = $v['ident']['zao_id'];
+                                    $saveSelf = $this->saveDay($saveDatas[$k]);
+                                    if (!$saveSelf) {
+                                        return out('', 500, '修改排班失败!');
+                                    }
+                                }
+                                if ($v['ident']['xia_id']) {
+                                    $saveDatas[$k]['type'] = 2;
+                                    $saveDatas[$k]['organization_id'] = $v['ident']['xia_id'];
+                                    $saveSelf = $this->saveDay($saveDatas[$k]);
+                                    if (!$saveSelf) {
+                                        return out('', 500, '修改排班失败!');
+                                    }
+                                }
+                                if ($v['ident']['wan_id']) {
+                                    $saveDatas[$k]['type'] = 3;
+                                    $saveDatas[$k]['organization_id'] = $v['ident']['wan_id'];
+                                    $saveSelf = $this->saveDay($saveDatas[$k]);
+                                    if (!$saveSelf) {
+                                        return out('', 500, '修改排班失败!');
+                                    }
+
+                                }
+                            }
+                        }
+                        Db::beginTransaction();
+                        try {
+                            $selfScheduleList = SelfSchedule::where('docter_id', $doctor_id)->whereIn('organization_id', $flag)->get();
+
+                            foreach ($counts as $kk => $vv) {
+                                $schedule[$kk]['schedule_date'] = $vv['schedule_date'];
+                                $schedule[$kk]['week'] = $vv['week'];
+                                $sid[$kk] = $vv['id'];
+                            }
+                            // 占用效率
+                            $scheduleLists = [];
+                            foreach ($sid as $kk => $vv) {
+                                foreach ($weekList as $k => $v) {
+                                    if ($schedule[$kk]['week'] == $v['week']) {
+                                        if ($v['type'] == 1) {
+                                            $times = $this->num_time($v['organization_id'], 1);
+                                            if (!$times) {
+                                                return out('', 500, "请先在排班设置中填写本机构的时间段");
+                                            }
+                                            $maf = $this->getMaf($vv, $times, ['organization_id' => $v['organization_id'], 'schedule_date' => $schedule[$kk]['schedule_date'], 'type' => 1], $doctor_id);
+                                            if ($maf) {
+                                                foreach ($maf as $os) {
+                                                    $scheduleLists[] = $os;
+                                                }
+                                            }
+                                        }
+                                        if ($v['type'] == 2) {
+                                            $times = $this->num_time($v['organization_id'], 2);
+                                            if (!$times) {
+                                                return out('', 500, "请先在排班设置中填写本机构的时间段");
+                                            }
+                                            $maf = $this->getMaf($vv, $times, ['organization_id' => $v['organization_id'], 'schedule_date' => $schedule[$kk]['schedule_date'], 'type' => 2], $doctor_id);
+                                            if ($maf) {
+                                                foreach ($maf as $os) {
+                                                    $scheduleLists[] = $os;
+                                                }
+                                            }
+                                        }
+                                        if ($v['type'] == 3) {
+                                            $times = $this->num_time($v['organization_id'], 3);
+                                            if (!$times) {
+                                                return out('', 500, "请先在排班设置中填写本机构的时间段");
+                                            }
+                                            $maf = $this->getMaf($vv, $times, ['organization_id' => $v['organization_id'], 'schedule_date' => $schedule[$kk]['schedule_date'], 'type' => 3], $doctor_id);
+                                            if ($maf) {
+                                                foreach ($maf as $os) {
+                                                    $scheduleLists[] = $os;
+                                                }
+                                            }
+                                        }
+                                    }
+                                }
+                            }
+
+                            // 查询重复替换
+                            $chong = [];
+                            if ($selfScheduleList && $scheduleLists) {
+                                foreach ($scheduleLists as $k => $v) {
+                                    foreach ($selfScheduleList as $kk => $vv) {
+                                        if ($v['schedule_date'] == $vv['schedule_date']) {
+                                            $chong[$kk]['schedule_id'] = $v['schedule_id'];
+                                            $chong[$kk]['docter_id'] = $v['docter_id'];
+                                            $chong[$kk]['order_num'] = $v['order_num'];
+                                            $chong[$kk]['organization_id'] = $vv['organization_id'];
+                                            $chong[$kk]['time_period_id'] = $vv['time_period_id'];
+                                            $chong[$kk]['type'] = $vv['type'];
+                                            $chong[$kk]['schedule_date'] = $vv['schedule_date'];
+                                            unset($scheduleLists[$k]);
+                                        }
+                                    }
+                                }
+                            }
+
+                            $listPeriod = array_merge($chong, $scheduleLists);
+                            SchedulePeriod::insert($listPeriod);
+                            DB::commit();
+                        } catch (\Exception $e) {
+                            DB::rollBack();
+                            return out('', 500, '2' . $$e->getMessage());
+                        } catch (\PDOException $e) {
+                            DB::rollBack();
+                            return out('', 500, '2' . $e->getMessage());
+                        }
+                    }
+                }
+
+            }
+
+        }
+
+        return out();
+    }
+
+
+    /**
+     * 计算24小时的时间区间段
+     * @param $minute 分钟比如:15
+     * @return array
+     */
+    public function getTimeHoures($minute)
+    {
+        // 可选10分钟,15分钟,20分钟,30分钟,1个小时
+        $start = strtotime(date("Y-m-d 00:00:00"));
+        $end = strtotime(date("Y-m-d 23:59:59"));
+        $returnArr = [];
+        for ($time = $start; $time <= $end; $time = $time + $minute * 60) {
+            array_push($returnArr, date("H:i", $time));
+        }
+        $newList = [];
+//        for($i=0;$i<count($returnArr)-1;$i++){
+//            $newList[$i]['start']=$returnArr[$i];
+//            $newList[$i]['end']=$returnArr[$i+1];
+//        }
+        $k = 0;
+        for ($i = 0; $i < (count($returnArr) * 2) - 1; $i++) {
+            if ($i % 2 != 0) {
+                if ($i != 0) {
+                    $k++;
+                    $newList[$k][0] = $returnArr[$k];
+                }
+            } else {
+                if ($i != 0) {
+                    $newList[$k - 1][1] = $returnArr[$k];
+                } else {
+                    $newList[$k][0] = $returnArr[$k];
+                }
+            }
+        }
+        $newList[count($newList) - 1][1] = $returnArr[0];
+        return $newList;
+    }
+
+    /**
+     * 新修改医生排班设置(废弃)
+     * @return mixed
+     * @throws \Exception
+     */
+    public function service_schedule()
+    {
+        $req = request()->post();
+        $data = json_decode($req['data'], true);
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        Db::beginTransaction();
+        try {
+            if (isset($data) && !empty($data)) {
+                $setting_data = [];
+                $times_data = [];
+                foreach ($data as $k => $v) {
+                    DocterSetting::where('docter_id', '=', $doctor_id)->where('org_id', $v['org_id'])->delete();
+                    TimePeriod::where('docter_id', '=', $doctor_id)->where('org_id', $v['org_id'])->delete();
+                    $setting_data[$k]['docter_id'] = $doctor_id;
+                    $setting_data[$k]['type'] = 1;
+                    $setting_data[$k]['status'] = 2;
+                    $setting_data[$k]['show_days'] = $v['show_days'];
+                    $setting_data[$k]['service_times'] = $v['service_times'];
+                    $setting_data[$k]['service_num'] = $v['service_num'];
+                    $setting_data[$k]['org_id'] = $v['org_id'];
+                    $service_times = [
+                        1 => ['amStartTime' => $v['amStartTime'], 'amEndTime' => $v['amEndTime'], 'amPerson' => $v['amPerson']],
+                        2 => ['pmStartTime' => $v['pmStartTime'], 'pmEndTime' => $v['pmEndTime'], 'pmPerson' => $v['pmPerson']],
+                        3 => ['nightStartTime' => $v['nightStartTime'], 'nightEndTime' => $v['nightEndTime'], 'nightPerson' => $v['nightPerson']],
+                    ];
+                    $setting_data[$k]['service_time'] = json_encode($service_times, JSON_UNESCAPED_UNICODE);
+                    $setting_data[$k]['created_at'] = date('Y-m-d H:i:s', time());
+                    $setting_data[$k]['updated_at'] = date('Y-m-d H:i:s', time());
+                    // 第二步, 根据时长去生成24小时的时间段,也要存id
+                    $timeList = $this->getTimeHoures($v['service_times']);
+                    foreach ($timeList as $kk => $vv) {
+                        $times_data[$k][$kk]['type'] = 2;
+                        $times_data[$k][$kk]['docter_id'] = $doctor_id;
+                        $times_data[$k][$kk]['start_time_period'] = $vv[0];
+                        $times_data[$k][$kk]['end_time_period'] = $vv[1];
+                        $times_data[$k][$kk]['org_id'] = $v['org_id'];
+                    }
+                }
+                foreach ($times_data as $k => $v) {
+                    TimePeriod::insert($v);
+                }
+                DocterSetting::insert($setting_data);
+            }
+            DB::commit();
+            return out('');
+        } catch (\Exception $e) {
+            DB::rollBack();
+            return out('', 500, $e->getMessage());
+        } catch (\PDOException $e) {
+            DB::rollBack();
+            return out('', 500, $e->getMessage());
+        }
+    }
+
+    /**
+     * 提交认证
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/14 15:08 *
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function addthen()
+    {
+        $req = request()->post();
+
+        $this->validate(request(), [
+            'name|医生姓名' => 'required|max:50',
+            'sex|性别' => 'required|in:男,女',
+            'ID|身份证号' => 'required|min:16|max:18',
+            'works|医院信息' => 'required',
+            'certificate|医生照片和执业证书' => 'required|string',
+            'idPhoto|身份证正反面' => 'required|string',
+            'doctorQualification|照片和资格证书' => 'required|string',
+        ]);
+        if ($req['sex'] == '男') {
+            $req['sex'] = 1;
+        } else {
+            $req['sex'] = 2;
+        }
+        // 首先获取医生姓名,性别,身份证号,照片,身份证,资格证去补全医生表
+        // 入库organization_ids这个数据是一条字符串,先分割成数组,如果只有一条则医生只选择了一个医院,机构id和医生id入库docter_organization(医生机构关联表)
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        if (!$doctor_id) {
+            return out(null, 500, '医生信息错误!');
+        }
+        $data = [];
+        $data['name'] = $req['name'];
+        $data['sex'] = $req['sex'];
+        $data['card_id'] = $req['ID'];
+        $data['practice'] = $req['certificate'];
+        $data['card_photo'] = $req['idPhoto'];
+        $data['is_quail'] = $req['doctorQualification'];
+        //处理医院机构id
+        $work = json_decode($req['works'], true);
+        if (!$work) {
+            return out('', '', '缺少医院');
+        }
+        $off_then = DocterOrganization::where('docter_id', '=', $doctor_id)->get('id')->toArray();
+        $is_del = false;
+        if ($off_then) {
+            $newids = [];
+            foreach ($off_then as $k => $v) {
+                $newids[$k] = $v['id'];
+            }
+            $is_del = true;
+        }
+        $org_list = [];
+        foreach ($work as $k => $v) {
+            if ($v['hospital']) {
+                $org_list[$k]['docter_id'] = $doctor_id;
+                $org_list[$k]['organization_id'] = $v['hospital'];
+                $org_list[$k]['offices_id'] = $v['department'];
+                $org_list[$k]['qualifications_id'] = $v['qualifications'];
+                $org_list[$k]['state'] = $v['state'];
+            }
+        }
+
+        DB::beginTransaction();//开启事务
+        try {
+            //补全医生表
+            Docter::where('id', $doctor_id)->update($data);
+            if ($is_del) {
+                foreach ($newids as $k => $v) {
+                    DocterOrganization::where('id', $v)->delete();
+                }
+            }
+            // 提交消息;
+            DocterMessage::create([
+                'docter_id' => $doctor_id,
+                'status' => 1,
+                'type' => 8,
+                'content' => '您已提交医生资质认证审核材料 '
+            ]);
+            DocterOrganization::insertOrIgnore($org_list);
+            DB::commit();//提交至数据库
+            return out();
+        } catch (\Exception $e) {
+            DB::rollback();
+            return out(null, 500, $e->getMessage());
+        }
+    }
+
+
+    /**
+     * 获取地区/联动医院
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/14 17:17 *
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function get_city_id()
+    {
+        // 查询机构!
+        $req = request()->post();
+
+        $this->validate(request(), [
+            'level_type' => 'required|in:4',
+            'province|省或直辖市id' => 'required_if:level_type,==,4',
+            'city|市' => 'required_if:level_type,==,4',
+            'area|区' => 'required_if:level_type,==,4',
+        ]);
+        // 查找下医院
+//            $ids_string = explode(',',$req['organizations_ids']);
+        $province = trim($req['province']);
+        $city = trim($req['city']);
+        $area = trim($req['area']);
+
+
+        $where['province_id'] = $province;
+        $where['city_id'] = $city;
+        $where['area_id'] = $area;
+        $where['type'] = 1;
+        $Organization = Organization::with('offices')->where($where)->get()->toArray();
+        $qulire = Qualification::where('status', 1)->get();
+        $newList = [];
+
+        if ($Organization) {
+
+            foreach ($Organization as $k => $v) {
+                $newList[$k]['value'] = $v['id'];
+                $newList[$k]['label'] = $v['name'];
+                if ($v['offices']) {
+                    foreach ($v['offices'] as $kk => $vv) {
+                        $newList[$k]['children'][$kk]['value'] = $vv['id'];
+                        $newList[$k]['children'][$kk]['label'] = $vv['name'];
+                        if ($qulire) {
+                            foreach ($qulire as $p => $c) {
+                                $newList[$k]['children'][$kk]['children'][$p]['value'] = $c['id'];
+                                $newList[$k]['children'][$kk]['children'][$p]['label'] = $c['name'];
+                            }
+                        } else {
+                            unset($Organization[$k], $newList[$k]);
+                        }
+                    }
+                } else {
+                    unset($Organization[$k], $newList[$k]);
+                }
+            }
+        }
+        return out($newList);
+    }
+
+    /**
+     * 获取城市联动
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/11/4 19:35
+     */
+    public function getCityList()
+    {
+        // 查询机构!
+        $req = request()->post();
+        $where['status'] = 1;
+        $data = Areas::where($where)->get(['id', 'name', 'level', 'parent_id'])->toArray();
+        $newData = [];
+        foreach ($data as $k => $v) {
+            $newData[$k]['value'] = $v['id'];
+            $newData[$k]['label'] = $v['name'];
+            $newData[$k]['pid'] = $v['parent_id'];
+        }
+        $list = $this->getTrees($newData);
+        $list = $this->getTree($list);
+        return out($list);
+    }
+
+    /**
+     * 获取城市树
+     * @param $data
+     * @return array
+     */
+    protected function getTrees($arr, $pid = 0)
+    {
+        static $list = [];
+
+        foreach ($arr as $key => $value) {
+            if ($value["pid"] == $pid) {
+                $list[] = $value;
+                unset($arr[$key]); //删除已经排好的数据为了减少遍历的次数,当然递归本身就很费神就是了
+                $this->getTrees($arr, $value["value"]);
+            }
+        }
+        return $list;
+    }
+
+    /**
+     * 整合树🌲
+     * @param $data
+     * @param $pId
+     * @return string
+     */
+    protected function getTree($data, $pId = 0)
+    {
+        $tree = [];
+        foreach ($data as $k => $v) {
+            if ($v['pid'] == $pId) {         //父亲找到儿子
+                $chid = $this->getTree($data, $v['value']);
+                if ($chid) {
+                    $v['children'] = $chid;
+                }
+                $tree[] = $v;
+                unset($data[$k]);
+            } else {
+                unset($data[$k]);
+
+            }
+        }
+        return $tree;
+    }
+
+
+    /*    public function getCityList(){
+            // 查询机构!
+            $req = request()->post();
+            $this->validate(request(), [
+                'type' => 'required|in:1,2,3',
+                'parent_id|父级id' => 'required_if:type,==,2|required_if:type,==,3|integer',
+            ]);//1=省,2=市,3=区
+            $where['level'] = $req['type'];
+            $where['status'] = 1;
+            if($req['type']==1){
+                $cityList = Areas::where($where)->get(['id','name'])->toArray();
+            }else if ($req['type']==2){
+                $where['parent_id']= $req['parent_id'];
+                $cityList = Areas::where($where)->get(['id','name'])->toArray();
+            }else if ($req['type']==3){
+                $where['parent_id']= $req['parent_id'];
+                $cityList = Areas::where($where)->get(['id','name'])->toArray();
+            }else{
+                return out('','','错误请求');
+            }
+            return out($cityList);
+        }*/
+
+    /**
+     * 获取科室和资质
+     * @return mixed
+     */
+    public function getOfferList()
+    {
+        // 查询机构!
+        $req = request()->post();
+        $this->validate(request(), [
+            'type' => 'required|in:1,2',
+        ]);//1=科室,2=资质
+        $type = $req['type'];
+        if ($type == 1) {
+            $List = Office::get(['id', 'name'])->toArray();
+        } else if ($type == 2) {
+            $List = Qualification::get(['id', 'name'])->toArray();
+        } else {
+            return out('', '', '错误请求');
+        }
+        return out($List);
+    }
+
+
+    /**
+     * 获取我的患者列表
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/17 13:21
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function userList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'userId' => 'integer',
+            'userType|用户类型' => 'integer|in:1,2,3,4,5,6,7',
+        ]);
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        if (!$doctor_id) {
+            return out(null, 500, '医生信息错误!');
+        }
+
+        $returnList = [];
+        $orderList = Order::with(['user'])->where('docter_id', '=', $doctor_id)->groupBy('id', 'product_type', 'user_id')->get()->toArray();
+        $collections = DocterUser::with('user')->where('docter_id', '=', $doctor_id)->groupBy('user_id')->get()->toArray();
+        $newList = [];
+        foreach ($orderList as $k => $v) {
+            $newList[$k]['order_id'] = $v['id'];
+            $newList[$k]['user_id'] = $v['user_id'];
+            $newList[$k]['order_sn'] = $v['order_sn'];
+            $newList[$k]['nickname'] = $v['user']['nickname'];
+            $save = UserDocter::where('user_id', '=', $v['user']['id'])->first();
+            if ($save) {
+                $newList[$k]['remark'] = $save['remark'];
+            } else {
+                $newList[$k]['remark'] = '';
+            }
+            $newList[$k]['avatar'] = $v['user']['avatar'];
+            $newList[$k]['product_type'] = $v['product_type'];
+        }
+        $newcoll = [];
+        foreach ($collections as $k => $v) {
+            $newcoll[$k]['id'] = $v['id'];
+            $newcoll[$k]['user_id'] = $v['user_id'];
+            $newcoll[$k]['nickname'] = $v['user']['nickname'];
+            $save = UserDocter::where('user_id', '=', $v['user_id'])->first();
+            if ($save) {
+                $newList[$k]['remark'] = $save['remark'];
+            } else {
+                $newList[$k]['remark'] = '';
+            }
+            $newcoll[$k]['avatar'] = $v['user']['avatar'];
+        }
+        $user_pic = [];
+        $user_relation = [];
+        $user_vaccines = [];
+        $user_guar = [];
+        $user_pack = [];
+
+
+        foreach ($newList as $k => $v) {
+            if ($v['product_type'] == 1 || $v['product_type'] == 2) {
+                // 咨询患者
+                if (!$this->putusers($user_pic, $v['user_id'])) {
+                    array_push($user_pic, $v);
+                }
+            }
+            if ($v['product_type'] == 3) {
+                // 门诊患者
+                if (!$this->putusers($user_relation, $v['user_id'])) {
+                    array_push($user_relation, $v);
+                }
+
+            }
+            if ($v['product_type'] == 4) {
+                // 疫苗患者
+                if (!$this->putusers($user_vaccines, $v['user_id'])) {
+                    array_push($user_vaccines, $v);
+                }
+
+
+            }
+            if ($v['product_type'] == 5) {
+                // 儿保预约
+                if (!$this->putusers($user_guar, $v['user_id'])) {
+                    array_push($user_guar, $v);
+                }
+            }
+            if ($v['product_type'] == 6) {
+                // 服务包
+                $OrderPacks = OrderPack::where('order_id', '=', $v['order_id'])->first();
+                if ($OrderPacks) {
+                    $teams = Team::with('docter')->where('id', '=', $OrderPacks['team_id'])->first();
+                    if ($teams) {
+                        $teams = $teams->toArray();
+                        if ($teams['docter']) {
+                            foreach ($teams['docter'] as $kk => $vv) {
+                                if ($vv['id'] == $doctor_id) {
+                                    array_push($user_pack, $v);
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+        }
+        $returnList['user_pic']['data'] = $user_pic;
+        $returnList['user_relation']['data'] = $user_relation;
+        $returnList['user_vaccines']['data'] = $user_vaccines;
+        $returnList['user_guar']['data'] = $user_guar;
+        $returnList['user_pack']['data'] = $user_pack;
+        if (empty($newcoll)) {
+            // 关注患者
+            $returnList['user_collection']['data'] = [];
+        } else {
+            $returnList['user_collection']['data'] = $newcoll;
+        }
+
+
+        $returnList['user_pic']['count'] = count($user_pic);
+        $returnList['user_relation']['count'] = count($user_relation);
+        $returnList['user_vaccines']['count'] = count($user_vaccines);
+        $returnList['user_guar']['count'] = count($user_guar);
+        $returnList['user_pack']['count'] = count($user_pack);
+        $returnList['user_collection']['count'] = count($returnList['user_collection']['data']);
+        return out($returnList);
+    }
+
+
+    /**
+     * 升级版 in_array
+     * @param $data1
+     * @param $data2
+     * @return bool
+     * @author Liu-Yh
+     * Create By 2020/11/27 16:18
+     */
+    protected function putusers($data1, $data2)
+    {
+        if (empty($data1)) {
+            return false;
+        }
+
+        $list = [];
+        foreach ($data1 as $k => $v) {
+            array_push($list, $v['user_id']);
+        }
+        if (in_array($data2, $list)) {
+            return true;
+        } else {
+            return false;
+        }
+
+    }
+
+
+    /**
+     * 上备注
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/11/27 16:16
+     */
+    public function remacks()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'remak|备注' => 'required',
+            'id|id' => 'required',
+        ]);
+        $user = $this->user;
+        $user_id = $user['id'];
+        $wheres['docter_id'] = $user_id;
+        $wheres['user_id'] = $req['id'];
+        $save = UserDocter::where($wheres)->first();
+
+        if ($save) {
+            UserDocter::where('id', '=', $save['id'])->update([
+                'remark' => $req['remak']
+            ]);
+        } else {
+            UserDocter::create([
+                'docter_id' => $user_id,
+                'user_id' => $req['id'],
+                'remark' => $req['remak']
+            ]);
+        }
+        return out([]);
+
+
+    }
+
+    /**
+     * 评价列表
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/11/17 17:41
+     */
+    public function evaluate()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'curPage' => 'required|integer',
+            'pageSize' => 'required|integer',
+        ]);
+        $pageSize = ($req['curPage'] - 1) * $req['pageSize'];
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $wheres['docter_id'] = $doctor_id;
+        $wheres['status'] = 2;
+        $data = Evaluate::with(['order', 'user'])->where($wheres)->skip($pageSize)->take($req['pageSize'])->groupBy('id')->get()->toArray();;
+        if ($data) {
+            $newList = [];
+            foreach ($data as $k => $v) {
+                $newList[$k]['order_id'] = $v['order']['order_sn'];
+                $newList[$k]['user'] = $v['user']['nickname'];
+                $newList[$k]['lv'] = $v['score'];
+                $newList[$k]['time'] = $v['created_at'];
+                $newList[$k]['evaluate'] = $v['content'];
+            }
+            return out($newList);
+        } else {
+            return out([]);
+        }
+    }
+
+
+    /**
+     * 我的列表进入详情
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/18 15:21
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function userListDetile()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'user_id|用户ID' => 'required|integer',
+            'userType|用户类型' => 'integer|in:1,2,3,4,5,6,7',
+        ]);
+        $user = $this->user;
+        // 查询详情;
+        $finds_patient = User::with('patients')->where('id', '=', $req['user_id'])->first();
+        $remarks = UserDocter::where('user_id', '=', $req['user_id'])->first();
+
+
+        $finds_order = Order::with('orderPatient')->where('user_id', '=', $req['user_id'])->orderBy('created_at', 'desc')->limit(3)->get();
+        if ($finds_order) {
+            $finds_order = $finds_order->toArray();
+        }
+        $userArr = $patientsArr = $orderArr = $fuwArr = [];
+        $patientsArr = [];
+        $ws['user_id'] = $req['user_id'];
+        $ws['product_type'] = 6;
+        $fuw_order = Order::with('orderPack')->where($ws)->orderBy('created_at', 'desc')->get();
+        if ($fuw_order) {
+            $fuw_order = $fuw_order->toArray();
+
+            foreach ($fuw_order as $kk => $vv) {
+                $fuwArr[$kk]['order_id'] = $vv['id'];
+                if ($vv['order_pack']) {
+                    foreach ($vv['order_pack'] as $k => $v) {
+                        $fuwArr[$kk]['id'] = $v['id'];
+                        $fuwArr[$kk]['pack_name'] = $v['pack_name'];
+                        $fuwArr[$kk]['pack_intro'] = $v['pack_intro'];
+                        $fuwArr[$kk]['pack_price'] = $v['pack_price'];
+                        $fuwArr[$kk]['effective_days'] = $v['effective_days'];
+                        $fuwArr[$kk]['start_time'] = date('Y-m-d,H:i', $v['start_time']);
+                        $fuwArr[$kk]['end_time'] = date('Y-m-d,H:i', $v['end_time']);
+                    }
+                }
+
+            }
+        }
+
+
+        if ($finds_patient) {
+            $finds_patient = $finds_patient->toArray();
+            $userArr['id'] = $finds_patient['id'];
+            if ($remarks) {
+                $userArr['remark'] = $remarks['remark']; //用户备注
+            } else {
+                $userArr['remark'] = ''; //用户备注
+            }
+            $userArr['nickname'] = $finds_patient['nickname'];
+            $userArr['avatar'] = $finds_patient['avatar'];
+            if ($finds_patient['patients']) {
+                foreach ($finds_patient['patients'] as $kk => $vv) {
+                    $patientsArr[$kk]['id'] = $vv['id'];
+                    $patientsArr[$kk]['avatar'] = $vv['avatar'];
+                    $patientsArr[$kk]['name'] = $vv['name'];
+                    if ($vv['sex'] == 0) {
+                        $patientsArr[$kk]['sex'] = '未知';
+                    } elseif ($vv['sex'] == 1) {
+                        $patientsArr[$kk]['sex'] = '男';
+                    } else {
+                        $patientsArr[$kk]['sex'] = '女';
+                    }
+                    $patientsArr[$kk]['age'] = numBirthday($vv['birthday']);
+                }
+            }
+        }
+
+
+        if ($finds_order) {
+            foreach ($finds_order as $k => $v) {
+                $orderArr[$k]['id'] = $v['id'];
+                $orderArr[$k]['order_sn'] = $v['order_sn'];
+                if ($v['order_status'] >= 4) {
+                    $orderArr[$k]['receiving_time'] = date('Y-m-d H:i', $v['receiving_time']);
+                    $orderArr[$k]['outtime'] = date('Y-m-d H:i', $v['end_time']);
+                } else {
+                    $orderArr[$k]['receiving_time'] = '';
+                    $orderArr[$k]['outtime'] = '';
+                }
+                $orderArr[$k]['order_status'] = $v['order_status'];
+                $orderArr[$k]['product_type'] = $v['product_type'];
+                $orderArr[$k]['created_at'] = $v['created_at'];
+                $orderArr[$k]['name'] = $v['order_patient']['name'];
+                $orderArr[$k]['birthday'] = numBirthday($v['order_patient']['birthday']);
+            }
+        }
+
+
+        // 拼接服务消息
+        $wh['user_id'] = $req['user_id'];
+        $wh['order_status'] = ['>', 3];
+        $wh['product_type'] = 6;
+        $fuwuList = [];
+        $fuwuInfo = Order::where($wh)->get();
+        $fuwuList['fuwu_num'] = count($fuwuInfo);
+        $whs['user_id'] = $req['user_id'];
+        $whs['order_status'] = ['>', 3];
+        $order_nums = Order::where($whs)->get();
+
+        $fuwuList['order_num'] = count($order_nums);
+        $pati_nums = Patient::where('user_id', '=', $req['user_id'])->get();
+        $fuwuList['pati_num'] = count($pati_nums);
+
+
+        $returnArr = [
+            'user_arr' => $userArr,
+            'patients_arr' => $patientsArr,//患者档案
+            'order_arr' => $orderArr, //历史问诊
+            'fuwu_arr' => $fuwArr, //已购服务
+            'nums' => $fuwuList,
+        ];
+        return out($returnArr);
+    }
+
+
+    /**
+     * 我的列表进入详情
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/20 23:21
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function patientsDetile()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'patient_id|患者ID' => 'required|integer',
+        ]);
+        $user = $this->user;
+        $finds = Patient::where('id', '=', $req['patient_id'])->first();
+        if ($finds) {
+            $finds = $finds->toArray();
+        }
+        if ($finds['sex'] == 0) {
+            $finds['sex'] = '中性';
+        } elseif ($finds['sex'] == 1) {
+            $finds['sex'] = '男';
+        } else {
+            $finds['sex'] = '女';
+        }
+
+        switch ($finds['relationship_type']) {
+            case 1:
+                $finds['relationship_type'] = '父亲';
+                break;
+            case 2:
+                $finds['relationship_type'] = '母亲';
+                break;
+            case 3:
+                $finds['relationship_type'] = '祖父';
+                break;
+            case 4:
+                $finds['relationship_type'] = '祖母';
+                break;
+            case 5:
+                $finds['relationship_type'] = '外祖父';
+                break;
+            case 6:
+                $finds['relationship_type'] = '外祖母';
+                break;
+            case 7:
+                $finds['relationship_type'] = '叔侄';
+                break;
+            default:
+                $finds['relationship_type'] = '其他';
+        }
+        $finds['age'] = numBirthday($finds['birthday']);
+        // 患者单子
+        $patient_list = OrderPatient::with('order')->where('patient_id', '=', $req['patient_id'])->groupBy('id', 'order_id')->get();
+        $patient_arr = [];
+        if ($patient_list) {
+            $patient_list = $patient_list->toArray();
+            foreach ($patient_list as $k => $v) {
+                switch ($v['order']['product_type']) {
+                    case 1:
+                        $patient_arr[$k]['product_type'] = '电话咨询';
+                        break;
+                    case 2:
+                        $patient_arr[$k]['product_type'] = '图文咨询';
+                        break;
+                    case 3:
+                        $patient_arr[$k]['product_type'] = '门诊';
+                        break;
+                    case 4:
+                        $patient_arr[$k]['product_type'] = '疫苗接种预约';
+                        break;
+                    case 5:
+                        $patient_arr[$k]['product_type'] = '儿保预约';
+                        break;
+                    case 6:
+                        $patient_arr[$k]['product_type'] = '服务包';
+                        break;
+                    case 7:
+                        $patient_arr[$k]['product_type'] = '充值';
+                        break;
+                    default:
+                        $patient_arr[$k]['product_type'] = '错误';
+                }
+                switch ($v['order']['order_status']) {
+                    case 1:
+                        $patient_arr[$k]['order_status'] = '未支付';
+                        break;
+                    case 2:
+                        $patient_arr[$k]['order_status'] = '待接单';
+                        break;
+                    case 3:
+                        $patient_arr[$k]['order_status'] = '进行中';
+                        break;
+                    case 4:
+                        $patient_arr[$k]['order_status'] = '已完成';
+                        break;
+                    case 5:
+                        $patient_arr[$k]['order_status'] = '已取消';
+                        break;
+                    default:
+                        $patient_arr[$k]['order_status'] = '未知';
+                }
+                $patient_arr[$k]['created_at'] = $v['created_at'];
+            }
+        }
+
+        $returnArr = [
+            'patient' => $finds,
+            'patientOrder' => $patient_arr,
+        ];
+        return out($returnArr);
+    }
+
+    /**
+     * 关注用户
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/21 00:21
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function userFollow()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'user_id|用户ID' => 'required|integer',
+            'is_ley' => 'required',
+        ]);
+        // 如果ley==false说明要取消关注,反之添加关注
+        $user = $this->user;
+        $docter_id = $user['id'];
+
+        if ($req['is_ley'] == 1) {
+            DocterUser::where('user_id', '=', $req['user_id'])->delete();
+        } else {
+            DocterUser::create([
+                'user_id' => $req['user_id'],
+                'docter_id' => $user['id'],
+            ]);
+        }
+        return out();
+    }
+
+    /**
+     * 是否关注用户
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/21 00:21
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function getFollows()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'user_id|用户ID' => 'required|integer',
+        ]);
+        $user = $this->user;
+        $docter_id = $user['id'];
+        $where['docter_id'] = $docter_id;
+        $where['user_id'] = $req['user_id'];
+        $find = DocterUser::where($where)->first();
+
+        if ($find) {
+            $find = $find->toArray();
+            return out(true);
+        } else {
+            return out(false);
+        }
+    }
+
+    /**
+     * 获取医生所在机构列表
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/21 00:21
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function organizationList()
+    {
+
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $where['docter_id'] = $doctor_id;
+        $where['state'] = 1;
+        $orgList = DocterOrganization::with('organization')->where($where)->get()->toArray();
+        $newList = [];
+        foreach ($orgList as $k => $v) {
+            $newList[$k]['value'] = $v['organization']['id'];
+            $newList[$k]['label'] = $v['organization']['name'];
+        }
+        return out($newList);
+    }
+
+
+    /**
+     * 获取医院的服务时间
+     * @return mixed
+     */
+    public function getOrgTimes()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'org_id|医院id' => 'required',
+        ]);
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $where['docter_id'] = $doctor_id;
+        $orgList = DocterSetting::where(['docter_id'=>$doctor_id,'type'=>1,'org_id'=>$req['org_id']])->first();
+        $newList = [];
+
+        if($orgList){
+            $time = json_decode($orgList['service_time'],true);
+            $newList['zao']['amStartTime'] = isset($time[1])?$time[1]['amStartTime']:'';
+            $newList['zao']['amEndTime'] = isset($time[1])?$time[1]['amEndTime']:'';
+            $newList['zao']['amPerson'] = isset($time[1])?$time[1]['amPerson']:'';
+
+            $newList['zhong']['pmStartTime'] = isset($time[2])?$time[2]['pmStartTime']:'';
+            $newList['zhong']['pmEndTime'] = isset($time[2])?$time[2]['pmEndTime']:'';
+            $newList['zhong']['pmPerson'] = isset($time[2])?$time[2]['pmPerson']:'';
+
+            $newList['wan']['nightStartTime'] = isset($time[3])?$time[3]['nightStartTime']:'';
+            $newList['wan']['nightEndTime'] = isset($time[3])?$time[3]['nightEndTime']:'';
+            $newList['wan']['nightPerson'] = isset($time[3])?$time[3]['nightPerson']:'';
+        }
+
+        return out($newList);
+    }
+
+    /**
+     * 获取历史排班时间列表
+     */
+    public function getLinsList()
+    {
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $newData = [];
+        $strim = date('Y-m-d', (time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600));
+        $wheres['docter_id'] = $doctor_id;
+        $data = Schedule::select(['id', 'schedule_date'])->where($wheres)->whereDate('schedule_date', '>', $strim)->orderBy('schedule_date', 'desc')->get();
+        if ($data) {
+            $data = $data->toArray();
+        } else {
+            return out($newData);
+        }
+
+//        $newDates = [];
+//        foreach ($data as $k=>$v){
+//            if((time() + (7 - (date('w') == 0 ? 7 : date('w'))) * 24 * 3600) > strtotime($v['schedule_date'])){
+//                array_push($newDates,$data[$k]);
+//            }
+//        }
+//        $data =$newDates;
+//        $k=1;
+//        foreach ($data as $v){
+//            $newData[$k]=$v;
+//            $k++;
+//        }
+        $newData = array_values($data);
+        $lab = [];
+        $p = 0;
+        for ($i = count($newData); $i > 0; $i--) {
+//            if ($i%7==0||$i==1){
+//
+//                if ($p>=1){
+//                    $lab[$p-1]['end_time'] = $arr[$i-1];
+//                    $lab[$p]['start_time'] = $arr[$i-1];
+//                    if(isset($arr[$i-7])){
+//                        $lab[$p]['end_time'] = isset($arr[$i-7])?$arr[$i-7]:'error';
+//
+//                    }else{
+//                        unset($lab[$p]);
+//                    }
+////                    $lab[$p]['end_time'] = isset($arr[$i-7])?$arr[$i-7]:'error';
+//                }else{
+//                    $lab[$p]['start_time'] = $arr[$i-1];
+//                }
+//                ++$p;
+//            }else{
+//                continue;
+//            }
+            if ($i % 7 == 0 || $i == 1) {
+                if ($p >= 1) {
+                    $lab[$p - 1]['end_time'] = $newData[$i - 1];
+                    if (isset($newData[$i - 7])) {
+                        $lab[$p]['start_time'] = $newData[$i - 1];
+                        $lab[$p]['end_time'] = $newData[$i - 7];
+                    } else {
+                        unset($lab[$p]);
+                    }
+                } else {
+                    $lab[$p]['start_time'] = $newData[$i - 1];
+                }
+                ++$p;
+            } else {
+                continue;
+            }
+        }
+        // 审核通过时间拿出来
+        $wh['docter_id'] = $doctor_id;
+        $wh['service_type'] = 3;
+        $wh['status'] = 2;
+        $service = ServiceApply::where($wh)->first();
+        if ($service) {
+            $service = $service;
+        } else {
+            $service = 0;
+        }
+        $rtuenList = [
+            'list' => $lab,
+            'service' => $service,
+        ];
+        return out($rtuenList);
+    }
+
+
+    /**
+     * 获取历史排班详情(废弃)
+     */
+    public function getLinsDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'start_date|开始时间' => 'required',
+            'end_date|结束时间' => 'required',
+        ]);
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $newData = [];
+        $req['start_date'] = date("Y-m-d", strtotime($req['start_date']));
+        $req['end_date'] = date("Y-m-d", strtotime($req['end_date']));
+//        $data = Schedule::with(['schedulePeriod'])->orderBy('id','desc')->get();
+        $data = SchedulePeriod::with('organization')->where('docter_id', '=', $doctor_id)->whereBetween('schedule_date', [$req['start_date'], $req['end_date']])->groupBy('schedule_id', 'type')->get();
+        if ($data) {
+            $data = $data->toArray();
+        } else {
+            return out($newData);
+        }
+
+        $lab = [];
+        $datesList = getDateFromList($req['start_date'], $req['end_date']);
+        foreach ($data as $k => $v) {
+            $lab[$k]['schedule_id'] = $v['schedule_id'];
+            $lab[$k]['type'] = $v['type']; // 1=早上,2=下午,3=晚上
+            switch (date('w', strtotime($v['schedule_date']))) {
+                case "0":
+                    $lab[$k]['week'] = '周日';
+                    break;
+                case "1":
+                    $lab[$k]['week'] = '周一';
+                    break;
+                case "2":
+                    $lab[$k]['week'] = '周二';
+                    break;
+                case "3":
+                    $lab[$k]['week'] = '周三';
+                    break;
+                case "4":
+                    $lab[$k]['week'] = '周四';
+                    break;
+                case "5":
+                    $lab[$k]['week'] = '周五';
+                    break;
+                default:
+                    $lab[$k]['week'] = '周六';
+            }
+            $lab[$k]['schedule_date'] = date('m-d', strtotime($v['schedule_date'])); // 日期
+            $lab[$k]['name'] = $v['organization']; // 所在医院
+            $lab[$k]['flag'] = $v['me_sure']; // 所在医院
+        }
+        $newLists = [];
+        $newReturn = [];
+        foreach ($lab as $k => $v) {
+            if (!isset($newLists[$v['schedule_id']])) {
+                $newLists[$v['schedule_id']] = $v;
+                $newReturn[$v['schedule_id']]['schedule_id'] = $v['schedule_id'];
+                if ($v['type'] == 1) {
+                    if ($v['flag'] != 0) {
+                        $newReturn[$v['schedule_id']]['type']['zao_flag'] = true;
+                        $newReturn[$v['schedule_id']]['type']['xia_flag'] = false;
+                        $newReturn[$v['schedule_id']]['type']['wan_flag'] = false;
+                    } else {
+                        $newReturn[$v['schedule_id']]['type']['zao_flag'] = false;
+                        $newReturn[$v['schedule_id']]['type']['xia_flag'] = false;
+                        $newReturn[$v['schedule_id']]['type']['wan_flag'] = false;
+                    }
+                    $newReturn[$v['schedule_id']]['type']['zao'] = $v['name']['name'];
+                    $newReturn[$v['schedule_id']]['type']['xia'] = false;
+                    $newReturn[$v['schedule_id']]['type']['wan'] = false;
+                    $newReturn[$v['schedule_id']]['type']['zao_id'] = $v['name']['id'];
+                    $newReturn[$v['schedule_id']]['type']['xia_id'] = 0;
+                    $newReturn[$v['schedule_id']]['type']['wan_id'] = 0;
+                } else if ($v['type'] == 2) {
+                    if ($v['flag'] != 0) {
+                        $newReturn[$v['schedule_id']]['type']['zao_flag'] = false;
+                        $newReturn[$v['schedule_id']]['type']['xia_flag'] = true;
+                        $newReturn[$v['schedule_id']]['type']['wan_flag'] = false;
+                    } else {
+                        $newReturn[$v['schedule_id']]['type']['zao_flag'] = false;
+                        $newReturn[$v['schedule_id']]['type']['xia_flag'] = false;
+                        $newReturn[$v['schedule_id']]['type']['wan_flag'] = false;
+                    }
+                    $newReturn[$v['schedule_id']]['type']['zao'] = false;
+                    $newReturn[$v['schedule_id']]['type']['xia'] = $v['name']['name'];
+                    $newReturn[$v['schedule_id']]['type']['wan'] = false;
+
+                    $newReturn[$v['schedule_id']]['type']['zao_id'] = 0;
+                    $newReturn[$v['schedule_id']]['type']['xia_id'] = $v['name']['id'];
+                    $newReturn[$v['schedule_id']]['type']['wan_id'] = 0;
+                } else {
+
+                    if ($v['flag'] != 0) {
+                        $newReturn[$v['schedule_id']]['type']['zao_flag'] = false;
+                        $newReturn[$v['schedule_id']]['type']['xia_flag'] = false;
+                        $newReturn[$v['schedule_id']]['type']['wan_flag'] = true;
+                    } else {
+                        $newReturn[$v['schedule_id']]['type']['zao_flag'] = false;
+                        $newReturn[$v['schedule_id']]['type']['xia_flag'] = false;
+                        $newReturn[$v['schedule_id']]['type']['wan_flag'] = false;
+                    }
+
+                    $newReturn[$v['schedule_id']]['type']['zao'] = false;
+                    $newReturn[$v['schedule_id']]['type']['xia'] = false;
+                    $newReturn[$v['schedule_id']]['type']['wan'] = $v['name']['name'];
+
+                    $newReturn[$v['schedule_id']]['type']['zao_id'] = 0;
+                    $newReturn[$v['schedule_id']]['type']['xia_id'] = 0;
+                    $newReturn[$v['schedule_id']]['type']['wan_id'] = $v['name']['id'];
+                }
+                $newReturn[$v['schedule_id']]['week'] = $v['week'];
+                $newReturn[$v['schedule_id']]['schedule_date'] = $v['schedule_date'];
+                $newReturn[$v['schedule_id']]['name'] = $v['name'];
+            } else {
+                if ($v['type'] == 1) {
+                    if ($v['flag'] != 0) {
+                        $newReturn[$v['schedule_id']]['type']['zao_flag'] = true;
+                    } else {
+                        $newReturn[$v['schedule_id']]['type']['zao_flag'] = false;
+                    }
+                    $newReturn[$v['schedule_id']]['type']['zao'] = $v['name']['name'];
+                    $newReturn[$v['schedule_id']]['type']['zao_id'] = $v['name']['id'];
+                } else if ($v['type'] == 2) {
+                    $newReturn[$v['schedule_id']]['type']['xia'] = $v['name']['name'];
+                    if ($v['flag'] != 0) {
+                        $newReturn[$v['schedule_id']]['type']['xia_flag'] = true;
+                    } else {
+                        $newReturn[$v['schedule_id']]['type']['xia_flag'] = false;
+                    }
+                    $newReturn[$v['schedule_id']]['type']['xia_id'] = $v['name']['id'];
+
+                } else {
+                    $newReturn[$v['schedule_id']]['type']['wan'] = $v['name']['name'];
+                    if ($v['flag'] != 0) {
+                        $newReturn[$v['schedule_id']]['type']['wan_flag'] = true;
+                    } else {
+                        $newReturn[$v['schedule_id']]['type']['wan_flag'] = false;
+                    }
+                    $newReturn[$v['schedule_id']]['type']['wan_id'] = $v['name']['id'];
+                }
+            }
+        }
+
+        $returnLists['list'] = array_values($newReturn);
+        $instartTimes = $req['start_date'];
+        // 判断数据库有没有这个时间段
+        $whr['docter_id'] = $doctor_id;
+        $whr['schedule_date'] = $instartTimes;
+        $finds = Schedule::where($whr)->first();
+        if ($finds) {
+            $returnLists['save_flag'] = false;
+        } else {
+            $returnLists['save_flag'] = true;
+        }
+        return out($returnLists);
+    }
+
+    /**
+     * 获取周模板详情
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/12/16 12:09
+     */
+    public function getLinsDetailnew()
+    {
+        $req = request()->post();
+
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $newData = [];
+
+//        $data = Schedule::with(['schedulePeriod'])->orderBy('id','desc')->get();
+        $data = WeekSchedule::with('organization')->where('docter_id', '=', $doctor_id)->groupBy('type', 'week')->orderBy('week', 'asc')->get();
+
+        if ($data) {
+            $data = $data->toArray();
+        } else {
+            return out($newData);
+        }
+
+        $lab = [];
+
+        foreach ($data as $k => $v) {
+            $lab[$k]['id'] = $v['id'];
+            $lab[$k]['type'] = $v['type']; // 1=早上,2=下午,3=晚上
+            $lab[$k]['organization_id'] = $v['organization_id']; // 1=早上,2=下午,3=晚上
+            $lab[$k]['flag'] = $v['week'];
+
+            switch ($v['week']) {
+                case "7":
+                    $lab[$k]['week'] = '周日';
+                    break;
+                case "1":
+                    $lab[$k]['week'] = '周一';
+                    break;
+                case "2":
+                    $lab[$k]['week'] = '周二';
+                    break;
+                case "3":
+                    $lab[$k]['week'] = '周三';
+                    break;
+                case "4":
+                    $lab[$k]['week'] = '周四';
+                    break;
+                case "5":
+                    $lab[$k]['week'] = '周五';
+                    break;
+                default:
+                    $lab[$k]['week'] = '周六';
+            }
+            $lab[$k]['name'] = $v['organization']; // 所在医院
+        }
+        $weekList = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
+
+        try {
+            $newReturn = [];
+
+            foreach ($lab as $k => $v) {
+                if (!isset($newReturn[$v['flag']])) {
+                    $newReturn[$v['flag']] = $v;
+                    if ($v['type'] == 1) {
+                        if ($v['flag'] != 0) {
+                            $newReturn[$v['flag']]['ident']['zao_flag'] = true;
+                            $newReturn[$v['flag']]['ident']['xia_flag'] = false;
+                            $newReturn[$v['flag']]['ident']['wan_flag'] = false;
+                        } else {
+                            $newReturn[$v['flag']]['ident']['zao_flag'] = false;
+                            $newReturn[$v['flag']]['ident']['xia_flag'] = false;
+                            $newReturn[$v['flag']]['ident']['wan_flag'] = false;
+                        }
+                        $newReturn[$v['flag']]['ident']['zao'] = $v['name']['name'];
+                        $newReturn[$v['flag']]['ident']['xia'] = false;
+                        $newReturn[$v['flag']]['ident']['wan'] = false;
+                        $newReturn[$v['flag']]['ident']['zao_id'] = $v['name']['id'];
+                        $newReturn[$v['flag']]['ident']['xia_id'] = 0;
+                        $newReturn[$v['flag']]['ident']['wan_id'] = 0;
+                    } else if ($v['type'] == 2) {
+                        if ($v['flag'] != 0) {
+                            $newReturn[$v['flag']]['ident']['zao_flag'] = false;
+                            $newReturn[$v['flag']]['ident']['xia_flag'] = true;
+                            $newReturn[$v['flag']]['ident']['wan_flag'] = false;
+                        } else {
+                            $newReturn[$v['flag']]['ident']['zao_flag'] = false;
+                            $newReturn[$v['flag']]['ident']['xia_flag'] = false;
+                            $newReturn[$v['flag']]['ident']['wan_flag'] = false;
+                        }
+                        $newReturn[$v['flag']]['ident']['zao'] = false;
+                        $newReturn[$v['flag']]['ident']['xia'] = $v['name']['name'];
+                        $newReturn[$v['flag']]['ident']['wan'] = false;
+
+                        $newReturn[$v['flag']]['ident']['zao_id'] = 0;
+                        $newReturn[$v['flag']]['ident']['xia_id'] = $v['name']['id'];
+                        $newReturn[$v['flag']]['ident']['wan_id'] = 0;
+                    } else {
+                        if ($v['flag'] != 0) {
+                            $newReturn[$v['flag']]['ident']['zao_flag'] = false;
+                            $newReturn[$v['flag']]['ident']['xia_flag'] = false;
+                            $newReturn[$v['flag']]['ident']['wan_flag'] = true;
+                        } else {
+                            $newReturn[$v['flag']]['ident']['zao_flag'] = false;
+                            $newReturn[$v['flag']]['ident']['xia_flag'] = false;
+                            $newReturn[$v['flag']]['ident']['wan_flag'] = false;
+                        }
+                        $newReturn[$v['flag']]['ident']['zao'] = false;
+                        $newReturn[$v['flag']]['ident']['xia'] = false;
+                        $newReturn[$v['flag']]['ident']['wan'] = $v['name']['name'];
+                        $newReturn[$v['flag']]['ident']['zao_id'] = 0;
+                        $newReturn[$v['flag']]['ident']['xia_id'] = 0;
+                        $newReturn[$v['flag']]['ident']['wan_id'] = $v['name']['id'];
+                    }
+                    $newReturn[$v['flag']]['week'] = $v['week'];
+                    $newReturn[$v['flag']]['name'] = $v['name'];
+                } else {
+                    if ($v['type'] == 1) {
+                        if ($v['flag'] != 0) {
+                            $newReturn[$v['flag']]['ident']['zao_flag'] = true;
+                        } else {
+                            $newReturn[$v['flag']]['ident']['zao_flag'] = false;
+                        }
+                        $newReturn[$v['flag']]['ident']['zao'] = $v['name']['name'];
+                        $newReturn[$v['flag']]['ident']['zao_id'] = $v['name']['id'];
+                    } else if ($v['type'] == 2) {
+                        $newReturn[$v['flag']]['ident']['xia'] = $v['name']['name'];
+                        if ($v['flag'] != 0) {
+                            $newReturn[$v['flag']]['ident']['xia_flag'] = true;
+                        } else {
+                            $newReturn[$v['flag']]['ident']['xia_flag'] = false;
+                        }
+                        $newReturn[$v['flag']]['ident']['xia_id'] = $v['name']['id'];
+
+                    } else {
+                        $newReturn[$v['flag']]['ident']['wan'] = $v['name']['name'];
+                        if ($v['flag'] != 0) {
+                            $newReturn[$v['flag']]['ident']['wan_flag'] = true;
+                        } else {
+                            $newReturn[$v['flag']]['ident']['wan_flag'] = false;
+                        }
+                        $newReturn[$v['flag']]['ident']['wan_id'] = $v['name']['id'];
+                    }
+                }
+                unset($newReturn[$v['flag']]['name']);
+
+            }
+        } catch (\Exception $e) {
+            var_dump($e->getMessage() . $e->getFile() . $e->getLine());
+        }
+
+
+        $returnLists['list'] = array_values($newReturn);
+
+        return out($returnLists);
+    }
+
+    /**
+     * 门诊排班(废弃)
+     * Auth:Yuanhang-Liu
+     * Date:2020/10/21 00:21
+     * @return \Illuminate\Http\JsonResponse
+     */
+    public function scheduling()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'data|数据' => 'required',
+        ]);
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $data = json_decode($req['data'], true);
+        $schedule = [];
+        $morning = [];//早上
+        $afternoon = [];//下午
+        $night = [];//晚上
+        $zaoTimes = [];
+        $zhongTimes = [];
+        $wanTimes = [];
+        $configs = SystemConfig::get()->toArray();
+        if (isset($configs[0]['value']) && !empty($configs[0]['value'])) {
+            $zaoTimes[0] = $configs[0]['value'];
+        } else {
+            $zaoTimes[0] = "09:00";
+        }
+        if (isset($configs[1]['value']) && !empty($configs[1]['value'])) {
+            $zaoTimes[1] = $configs[1]['value'];
+        } else {
+            $zaoTimes[1] = "12:00";
+        }
+        if (isset($configs[2]['value']) && !empty($configs[2]['value'])) {
+            $zhongTimes[0] = $configs[2]['value'];
+        } else {
+            $zhongTimes[0] = "13:00";
+        }
+        if (isset($configs[3]['value']) && !empty($configs[3]['value'])) {
+            $zhongTimes[1] = $configs[3]['value'];
+        } else {
+            $zhongTimes[1] = "18:00";
+        }
+        if (isset($configs[4]['value']) && !empty($configs[4]['value'])) {
+            $wanTimes[0] = $configs[4]['value'];
+        } else {
+            $wanTimes[0] = "19:00";
+        }
+        if (isset($configs[5]['value']) && !empty($configs[5]['value'])) {
+            $wanTimes[1] = $configs[5]['value'];
+        } else {
+            $wanTimes[1] = "21:00";
+        }
+
+        $morningd = TimePeriod::where('start_time_period', '>=', $zaoTimes[0])->where('end_time_period', '<=', $zaoTimes[1])->get()->toArray();
+        $morning = array_column($morningd, 'id');
+        $afternoond = TimePeriod::where('start_time_period', '>=', $zhongTimes[0])->where('end_time_period', '<=', $zhongTimes[1])->get()->toArray();
+        $afternoon = array_column($afternoond, 'id');
+        $nightd = TimePeriod::where('start_time_period', '>=', $wanTimes[0])->where('end_time_period', '<=', $wanTimes[1])->get()->toArray();
+        $night = array_column($nightd, 'id');
+        // 先进行删除
+        DB::beginTransaction();
+        try {
+            foreach ($data as $k => $v) {
+                // 删除
+                Schedule::where('schedule_date', '=', $v["schedule_date"])->delete();
+                SchedulePeriod::where('schedule_date', '=', $v['schedule_date'])->delete();
+                $schedule[$k]['schedule_date'] = $v['schedule_date'];
+                $schedule[$k]['schedule_day'] = str_replace('-', '', $v['schedule_date']);
+                $schedule[$k]['docter_id'] = $doctor_id;
+                $schedule[$k]['organization_id'] = 0;
+                $schedule[$k]['per_time_num'] = 10;
+                $sid = Schedule::insertGetId($schedule[$k]);
+                // 插入详情
+                if ($v['hospital'][0]['organization_id']) {
+                    $maf = $this->getMaf($sid, $morning, ['organization_id' => $v['hospital'][0]['organization_id'], 'schedule_date' => $v['schedule_date'], 'type' => 1], $doctor_id);
+                    SchedulePeriod::insert($maf);
+                }
+                if ($v['hospital'][1]['organization_id']) {
+                    $maf = $this->getMaf($sid, $afternoon, ['organization_id' => $v['hospital'][1]['organization_id'], 'schedule_date' => $v['schedule_date'], 'type' => 2], $doctor_id);
+                    SchedulePeriod::insert($maf);
+                }
+                if ($v['hospital'][2]['organization_id']) {
+                    $maf = $this->getMaf($sid, $night, ['organization_id' => $v['hospital'][2]['organization_id'], 'schedule_date' => $v['schedule_date'], 'type' => 3], $doctor_id);
+                    SchedulePeriod::insert($maf);
+                }
+            }
+            DB::commit();
+            return out('', '', '成功');
+        } catch (\Exception $e) {
+            DB::rollBack();
+            return out('', 500, $e->getFile() . '中的第:' . $e->getLine() . '行报错:' . $e->getCode(), $e->getMessage());
+        }
+
+    }
+
+
+    /**
+     * 生成时间段
+     * @param int $org_id 机构id
+     * @param int $type 时间段,1=早上,2=下午,3=晚上
+     * @return array|bool
+     * @author Liu-Yh
+     * Create By 2020/12/15 18:47
+     */
+    protected function num_time($org_id = 0, $type = 1)
+    {
+
+
+
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $zaoTimes = [];
+        $zhongTimes = [];
+        $wanTimes = [];
+        $where['docter_id'] = $doctor_id;
+        $where['type'] = 1;
+        $where['org_id'] = $org_id;
+        $configs = DocterSetting::where($where)->first();
+
+        if ($configs) {
+            $list = json_decode($configs['service_time'], true);
+            if (isset($list[1]['amStartTime']) && !empty($list[1]['amStartTime'])) {
+                $zaoTimes[0] = $list[1]['amStartTime'];
+            } else {
+                $zaoTimes[0] = "08:00";
+            }
+            if (isset($list[1]['amEndTime']) && !empty($list[1]['amEndTime'])) {
+                $zaoTimes[1] = $list[1]['amEndTime'];
+            } else {
+                $zaoTimes[1] = "12:00";
+            }
+            if (isset($list[2]['pmStartTime']) && !empty($list[2]['pmStartTime'])) {
+                $zhongTimes[0] = $list[2]['pmStartTime'];
+            } else {
+                $zhongTimes[0] = "13:00";
+            }
+            if (isset($list[2]['pmEndTime']) && !empty($list[2]['pmEndTime'])) {
+                $zhongTimes[1] = $list[2]['pmEndTime'];
+            } else {
+                $zhongTimes[1] = "18:00";
+            }
+            if (isset($list[3]['nightStartTime']) && !empty($list[3]['nightStartTime'])) {
+                $wanTimes[0] = $list[3]['nightStartTime'];
+            } else {
+                $wanTimes[0] = "19:00";
+            }
+            if (isset($list[3]['nightEndTime']) && !empty($list[3]['nightEndTime'])) {
+                $wanTimes[1] = $list[3]['nightEndTime'];
+            } else {
+                $wanTimes[1] = "21:00";
+            }
+        } else {
+            return false;
+        }
+        if ($type == 1) {
+            $morningWhere[] = ['start_time_period', '>=', $zaoTimes[0]];
+            $morningWhere[] = ['end_time_period', '<=', $zaoTimes[1]];
+            $morningWhere['docter_id'] = $doctor_id;
+            $morningWhere['org_id'] = $org_id;
+
+            $morningd = TimePeriod::where($morningWhere)->get()->toArray();
+
+            array_pop($morningd);
+            $morning = array_column($morningd, 'id');
+            return $morning;
+        } elseif ($type == 2) {
+            $afternoondWhere[] = ['start_time_period', '>=', $zhongTimes[0]];
+            $afternoondWhere[] = ['end_time_period', '<=', $zhongTimes[1]];
+            $afternoondWhere['docter_id'] = $doctor_id;
+            $afternoondWhere['org_id'] = $org_id;
+            $afternoond = TimePeriod::where($afternoondWhere)->get()->toArray();
+            array_pop($afternoond);
+            $afternoon = array_column($afternoond, 'id');
+            return $afternoon;
+
+        } elseif ($type == 3) {
+            $nightWhere[] = ['start_time_period', '>=', $wanTimes[0]];
+            $nightWhere[] = ['end_time_period', '<=', $wanTimes[1]];
+            $nightWhere['docter_id'] = $doctor_id;
+            $nightWhere['org_id'] = $org_id;
+            $nightd = TimePeriod::where($nightWhere)->get()->toArray();
+            array_pop($nightd);
+            $night = array_column($nightd, 'id');
+            return $night;
+
+        } else {
+            $morningWhere[] = ['start_time_period', '>=', $zaoTimes[0]];
+            $morningWhere[] = ['end_time_period', '<=', $zaoTimes[1]];
+            $morningWhere['docter_id'] = $doctor_id;
+            $morningWhere['org_id'] = $org_id;
+            $morningd = TimePeriod::where($morningWhere)->get()->toArray();
+            array_pop($morningd);
+            $morning = array_column($morningd, 'id');
+
+            $afternoondWhere[] = ['start_time_period', '>=', $zhongTimes[0]];
+            $afternoondWhere[] = ['end_time_period', '<=', $zhongTimes[1]];
+            $afternoondWhere['docter_id'] = $doctor_id;
+            $afternoondWhere['org_id'] = $org_id;
+            $afternoond = TimePeriod::where($afternoondWhere)->get()->toArray();
+            array_pop($afternoond);
+            $afternoon = array_column($afternoond, 'id');
+
+            $nightWhere[] = ['start_time_period', '>=', $wanTimes[0]];
+            $nightWhere[] = ['end_time_period', '<=', $wanTimes[1]];
+            $nightWhere['docter_id'] = $doctor_id;
+            $nightWhere['org_id'] = $org_id;
+            $nightd = TimePeriod::where($nightWhere)->get()->toArray();
+            array_pop($nightd);
+            $night = array_column($nightd, 'id');
+            return [$morning, $afternoon, $night];
+        }
+    }
+
+
+    /**
+     * 获取俩月日期
+     * @return array
+     */
+    protected function date_bool($start_time = false, $end_time = false)
+    {
+        $weekarray = array(7, 1, 2, 3, 4, 5, 6);
+        $monthDays = [];
+
+        if ($start_time && $end_time) {
+            $firstDay = $start_time;
+            $lastDay = $end_time;
+        } else {
+            $firstDay = date('Y-m-01', time());
+            $lastDay = date('Y-m-d', strtotime("$firstDay +2 month -1 day"));
+        }
+
+        $i = 0;
+        while (date('Y-m-d', strtotime("$firstDay +$i days")) <= $lastDay) {
+            $monthDays[$i]['date'] = date('Y-m-d', strtotime("$firstDay +$i days"));
+            $monthDays[$i]['week'] = $weekarray[date("w", strtotime("$firstDay +$i days"))];
+            $i++;
+        }
+        return $monthDays;
+    }
+
+
+    /**
+     * 新版门诊排班(排班周模板)
+     * @return mixed
+     * @throws \Exception
+     */
+    public function week_scheduling()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'data|数据' => 'required',
+        ]);
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $data = json_decode($req['data'], true);
+
+        $moth_date = $this->date_bool();
+        // 添加到周模板(不管时间)
+        $weekList = [];
+        $weekModel = new WeekSchedule();
+        // 先进行删除
+        $counts = Schedule::where('schedule_date', '>=', $moth_date[0]['date'])->where('docter_id',$doctor_id)->where('schedule_date', '<=', end($moth_date)['date'])->get();
+        // 12个月平均两个月最短是29天
+        $selfWhere['docter_id'] = $doctor_id;
+        $selfWhere[] = ['schedule_date','>=',date('Y-m-d',time())];
+        $selfScheduleList = SelfSchedule::where($selfWhere)->get();
+
+        $flag = false;
+        DB::beginTransaction();
+        try {
+            $weekModel->where('docter_id', '=', $doctor_id)->where('schedule_type', '=', 1)->delete();
+            $delWhere['docter_id'] = $doctor_id;
+            $delWhere[] = ['schedule_date','>=',date('Y-m-d',time())];
+            SchedulePeriod::where($delWhere)->delete();
+            $schedule = [];
+            if (count($counts) < 29) {
+                $flag = true;
+                Schedule::where('docter_id', '=', $doctor_id)->delete();
+                foreach ($moth_date as $kk => $vv) {
+                    $schedule[$kk]['schedule_date'] = $vv['date'];
+                    $schedule[$kk]['schedule_day'] = str_replace('-', '', $vv['date']);
+                    $schedule[$kk]['docter_id'] = $doctor_id;
+                    $schedule[$kk]['organization_id'] = 0;
+                    $schedule[$kk]['week'] = $vv['week'];
+                    $schedule[$kk]['per_time_num'] = 10;
+                    $sid[$kk] = Schedule::insertGetId($schedule[$kk]);
+                }
+            } else {
+                foreach ($counts as $kk => $vv) {
+                    if ($vv['schedule_date'] >= date('Y-m-d',time())){
+                        $schedule[$kk]['schedule_date'] = $vv['schedule_date'];
+                        $schedule[$kk]['week'] = $vv['week'];
+                        $sid[$kk] = $vv['id'];
+                    }
+                }
+            }
+
+
+            foreach ($data as $k => $v) {
+
+                // 插入详情
+                if ($v['identifi']['zao']!=0) {
+                    $maf[$k]['schedule_type'] = 1;
+                    $maf[$k]['docter_id'] = $doctor_id;
+                    $maf[$k]['week'] = $v['week'];
+                    $maf[$k]['type'] = 1;
+                    $maf[$k]['organization_id'] = $v['identifi']['zao'];
+                    $weekList[] = $maf[$k];
+//                        $times = $this->num_time($v['identifi']['zao'],1);
+//                        if (!$times){
+//                            return out('',500,"请先在排班设置中填写本机构的时间段");
+//                        }
+//                        $zao_maf=$this->week_getMaf($times,['organization_id'=>$v['identifi']['zao'],'week'=>$v['week'],'type'=>1],$doctor_id);
+//                        if ($zao_maf){
+//                            foreach ($zao_maf as $o){
+//                                $weekList[]=$o;
+//                            }
+//                        }
+                }
+                if ($v['identifi']['zhong']!=0) {
+                    $maf[$k]['schedule_type'] = 1;
+                    $maf[$k]['docter_id'] = $doctor_id;
+                    $maf[$k]['week'] = $v['week'];
+                    $maf[$k]['type'] = 2;
+                    $maf[$k]['organization_id'] = $v['identifi']['zhong'];
+                    $weekList[] = $maf[$k];
+                    /*       $times = $this->num_time($v['identifi']['zhong'],2);
+                           if (!$times){
+                               return out('',500,"请先在排班设置中填写本机构的时间段");
+                           }
+                           $zhong_maf=$this->week_getMaf($times,['organization_id'=>$v['identifi']['zhong'],'week'=>$v['week'],'type'=>2],$doctor_id);
+                           if ($zhong_maf){
+                               foreach ($zhong_maf as $o){
+                                   $weekList[]=$o;
+
+                               }
+                           }*/
+                }
+                if ($v['identifi']['wan']!=0) {
+                    $maf[$k]['schedule_type'] = 1;
+                    $maf[$k]['docter_id'] = $doctor_id;
+                    $maf[$k]['week'] = $v['week'];
+                    $maf[$k]['type'] = 3;
+                    $maf[$k]['organization_id'] = $v['identifi']['wan'];
+                    $weekList[] = $maf[$k];
+                    /*$times = $this->num_time($v['identifi']['wan'],3);
+                    if (!$times){
+                        return out('',500,"请先在排班设置中填写本机构的时间段");
+                    }
+                    $wan_maf=$this->week_getMaf($times,['organization_id'=>$v['identifi']['wan'],'week'=>$v['week'],'type'=>3],$doctor_id);
+                    if ($wan_maf){
+                        foreach ($wan_maf as $o){
+                            $weekList[]=$o;
+
+                        }
+                    }*/
+                }
+            }
+
+            // 占用效率
+
+            $scheduleLists = [];
+            foreach ($sid as $kk => $vv) {
+                foreach ($data as $k => $v) {
+                    if ($schedule[$kk]['week'] == $v['week']) {
+                        //检查有没有设置时间
+//                        if ($v['identifi']['zao']==0) {
+//                            $times = $this->num_time($v['identifi']['zao'], 1);
+//                            if (!$times) {
+//                                return out('', 500, "请先在排班设置中填写本机构的时间段1");
+//                            }
+//                        }
+
+                        if ($v['identifi']['zao']) {
+                            $times = $this->num_time($v['identifi']['zao'], 1);
+                            if (!$times) {
+                                return out('', 500, "请先在排班设置中填写本机构的时间段2");
+                            }
+                            $maf = $this->getMaf($vv, $times, ['organization_id' => $v['identifi']['zao'], 'schedule_date' => $schedule[$kk]['schedule_date'], 'type' => 1], $doctor_id);
+                            if ($maf) {
+                                foreach ($maf as $os) {
+//                                    array_push($scheduleLists, $os);
+                                    $scheduleLists[] = $os;
+                                }
+                            }
+                        }
+                        if ($v['identifi']['zhong']) {
+                            $times = $this->num_time($v['identifi']['zhong'], 2);
+                            if (!$times) {
+                                return out('', 500, "请先在排班设置中填写本机构的时间段3");
+                            }
+                            $maf = $this->getMaf($vv, $times, ['organization_id' => $v['identifi']['zhong'], 'schedule_date' => $schedule[$kk]['schedule_date'], 'type' => 2], $doctor_id);
+                            if ($maf) {
+                                foreach ($maf as $os) {
+                                    $scheduleLists[] = $os;
+
+                                }
+                            }
+                        }
+                        if ($v['identifi']['wan']) {
+                            $times = $this->num_time($v['identifi']['wan'], 3);
+                            if (!$times) {
+                                return out('', 500, "请先在排班设置中填写本机构的时间段4");
+                            }
+                            $maf = $this->getMaf($vv, $times, ['organization_id' => $v['identifi']['wan'], 'schedule_date' => $schedule[$kk]['schedule_date'], 'type' => 3], $doctor_id);
+                            if ($maf) {
+                                foreach ($maf as $os) {
+//                                    array_push($scheduleLists, $os);
+                                    $scheduleLists[] = $os;
+
+                                }
+                            }
+                        }
+                    }
+                }
+            }
+
+
+            // 查询重复替换
+            $chong = [];
+            if ($selfScheduleList && $scheduleLists) {
+                foreach ($scheduleLists as $k => $v) {
+                    foreach ($selfScheduleList as $kk => $vv) {
+                        if ($v['schedule_date'] == $vv['schedule_date']) {
+                            $chong[$kk]['schedule_id'] = $v['schedule_id'];
+                            $chong[$kk]['docter_id'] = $v['docter_id'];
+                            $chong[$kk]['order_num'] = $v['order_num'];
+                            $chong[$kk]['organization_id'] = $vv['organization_id'];
+                            $chong[$kk]['time_period_id'] = $vv['time_period_id'];
+                            $chong[$kk]['type'] = $vv['type'];
+                            $chong[$kk]['schedule_date'] = $vv['schedule_date'];
+                            unset($scheduleLists[$k]);
+                        }
+                    }
+                }
+            }
+            $listPeriod = array_merge($chong, $scheduleLists);
+            SchedulePeriod::insert($listPeriod);
+            WeekSchedule::insert($weekList);
+            DB::commit();
+            return out();
+        } catch (\Exception $e) {
+            DB::rollBack();
+            return out('', 500, $e->getFile() . '中的第:' . $e->getLine() . '行报错:' . $e->getCode(), $e->getMessage());
+        } catch (\PDOException $e) {
+            DB::rollBack();
+            return out('', 500, $e->getFile() . '中的第:' . $e->getLine() . '行报错:' . $e->getCode(), $e->getMessage());
+        }
+    }
+
+
+    /**
+     * 修改某一天的数据
+     * @author Liu-Yh
+     * Create By 2020/12/16 18:46
+     */
+    public function saveDay($data = [])
+    {
+        $flag = false;
+        if (empty($data)) {
+            $req = request()->post();
+            $this->validate(request(), [
+                'schedule_date|日期' => 'required',
+                'week|日期' => 'required',
+                'type|类型' => 'required',
+                'organization_id|日期' => 'required',
+            ]);
+        } else {
+            $flag = true;
+            $req = $data;
+        }
+
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $save_data = [];
+//        $type_data = explode(',', $req['type']);
+        DB::beginTransaction();
+        try {
+            $type_data = json_decode($req['type'],true);
+
+            $finds = SelfSchedule::where(['schedule_date' => $req['schedule_date'], 'docter_id' => $doctor_id, 'schedule_type' => 1])->delete();
+            $save_data=[];
+            if($type_data['mon']!=0) {
+                $mon_times = $this->num_time($type_data['mon'], 1);
+                $mf1 = $this->arrangeDay($mon_times, ['organization_id' => $type_data['mon'], 'week' => $req['week'], 'schedule_date' => $req['schedule_date'], 'type' => 1], $doctor_id);
+                if($mf1){
+                    foreach ($mf1 as $v){
+                        $save_data[] = $v;
+                    }
+                }
+            }
+            if($type_data['aft']!=0){
+                $aft_times = $this->num_time($type_data['aft'], 2);
+                $mf2 = $this->arrangeDay($aft_times, ['organization_id' => $type_data['aft'], 'week' => $req['week'], 'schedule_date' => $req['schedule_date'], 'type' => 2], $doctor_id);
+                if($mf2){
+                    foreach ($mf2 as $v){
+                        $save_data[] = $v;
+                    }
+                }
+            }
+            if($type_data['nig']!=0) {
+                $nig_times = $this->num_time($type_data['nig'], 3);
+                $mf3 = $this->arrangeDay($nig_times, ['organization_id' => $type_data['nig'], 'week' => $req['week'], 'schedule_date' => $req['schedule_date'], 'type' => 3], $doctor_id);
+                if($mf3){
+                    foreach ($mf3 as $v){
+                        $save_data[] = $v;
+                    }
+                }
+            }
+
+
+            if (!$flag){
+                $lists = Schedule::where(['docter_id'=>$doctor_id,'schedule_date'=>$req['schedule_date']])->first();
+
+
+                if($lists){
+                    SchedulePeriod::where(['docter_id'=>$doctor_id,'schedule_date'=>$req['schedule_date']])->delete();
+                    $chong = [];
+                    foreach ($save_data as $k => $v) {
+                        $chong[$k]['schedule_id'] = $lists['id'];
+                        $chong[$k]['docter_id'] = $v['docter_id'];
+                        $chong[$k]['order_num'] = 0;
+                        $chong[$k]['organization_id'] = $v['organization_id'];
+                        $chong[$k]['time_period_id'] = $v['time_period_id'];
+                        $chong[$k]['type'] = $v['type'];
+                        $chong[$k]['schedule_date'] = $v['schedule_date'];
+                    }
+                    SchedulePeriod::insert($chong);
+                }
+            }
+            SelfSchedule::insert($save_data);
+            DB::commit();
+            if ($flag) {
+                return true;
+            } else {
+                return out();
+            }
+        } catch (\Exception $e) {
+            DB::rollBack();
+            if ($flag) {
+                return false;
+            } else {
+                return out('', 500, $e->getFile() . '中的第:' . $e->getLine() . '行报错:' . $e->getCode(), $e->getMessage());
+            }
+        } catch (\PDOException $e) {
+            DB::rollBack();
+            if ($flag) {
+                return false;
+            } else {
+                return out('', 500, $e->getFile() . '中的第:' . $e->getLine() . '行报错:' . $e->getCode(), $e->getMessage());
+            }
+        }
+    }
+
+    /**
+     * 整理单个修改排班的数据
+     * @param $time
+     * @param $req
+     * @param $doctor_id
+     * @return array
+     * @author Liu-Yh
+     * Create By 2020/12/16 19:00
+     */
+    protected function arrangeDay($time, $req, $doctor_id)
+    {
+
+        $save_data = [];
+        foreach ($time as $k => $v) {
+            $save_data[$k]['schedule_date'] = $req['schedule_date'];
+            $save_data[$k]['week'] = $req['week'];
+            $save_data[$k]['schedule_type'] = 1;
+            $save_data[$k]['type'] = $req['type'];
+            $save_data[$k]['organization_id'] = $req['organization_id'];
+            $save_data[$k]['docter_id'] = $doctor_id;
+            $save_data[$k]['time_period_id'] = $v;
+        }
+
+        return $save_data;
+    }
+
+
+    /**
+     * 查看月视图
+     * @author Liu-Yh
+     * Create By 2020/12/16 19:20
+     */
+    public function monthDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'start_day|日期' => 'required',
+            'end_day|日期' => 'required',
+        ]);
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $selfScheduleList = SelfSchedule::where('docter_id', '=', $doctor_id)->get();
+        $weekSchduleList = WeekSchedule::with('organization')->where('docter_id', '=', $doctor_id)->groupBy('type', 'week')->orderBy('week', 'asc')->get()->toArray();
+
+        // 占用效率
+        $scheduleLists = [];
+        $moth_date = $this->date_bool($req['start_day'], $req['end_day']);
+        $lab=[];
+        foreach ($weekSchduleList as $k => $v) {
+            $lab[$k]['id'] = $v['id'];
+            $lab[$k]['type'] = $v['type']; // 1=早上,2=下午,3=晚上
+            $lab[$k]['organization_id'] = $v['organization_id']; // 1=早上,2=下午,3=晚上
+            $lab[$k]['flag'] = $v['week'];
+            switch ($v['week']) {
+                case "7":
+                    $lab[$k]['week'] = '周日';
+                    break;
+                case "1":
+                    $lab[$k]['week'] = '周一';
+                    break;
+                case "2":
+                    $lab[$k]['week'] = '周二';
+                    break;
+                case "3":
+                    $lab[$k]['week'] = '周三';
+                    break;
+                case "4":
+                    $lab[$k]['week'] = '周四';
+                    break;
+                case "5":
+                    $lab[$k]['week'] = '周五';
+                    break;
+                default:
+                    $lab[$k]['week'] = '周六';
+            }
+        }
+
+
+        $newReturn = [];
+        $weekList = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
+        foreach ($lab as $k => $v) {
+            if (!isset($newReturn[$v['flag']])) {
+                $newReturn[$v['flag']] = $v;
+                if ($v['type'] == 1) {
+                    $newReturn[$v['flag']]['ident']['zao_id'] = $v['organization_id'];
+                    $newReturn[$v['flag']]['ident']['xia_id'] = 0;
+                    $newReturn[$v['flag']]['ident']['wan_id'] = 0;
+                } else if ($v['type'] == 2) {
+                    $newReturn[$v['flag']]['ident']['zao_id'] = 0;
+                    $newReturn[$v['flag']]['ident']['xia_id'] = $v['organization_id'];
+                    $newReturn[$v['flag']]['ident']['wan_id'] = 0;
+                } else {
+                    $newReturn[$v['flag']]['ident']['zao_id'] = 0;
+                    $newReturn[$v['flag']]['ident']['xia_id'] = 0;
+                    $newReturn[$v['flag']]['ident']['wan_id'] = $v['organization_id'];
+                }
+            } else {
+                if ($v['type'] == 1) {
+                    $newReturn[$v['flag']]['ident']['zao_id'] = $v['organization_id'];
+                } else if ($v['type'] == 2) {
+                    $newReturn[$v['flag']]['ident']['xia_id'] = $v['organization_id'];
+                } else {
+
+                    $newReturn[$v['flag']]['ident']['wan_id'] = $v['organization_id'];
+                }
+            }
+        }
+        $newList = [];
+        foreach ($moth_date as $k => $v) {
+            $newList[$k]['date'] = $v['date'];
+            $newList[$k]['ident']['zao'] = 0;
+            $newList[$k]['ident']['xia'] = 0;
+            $newList[$k]['ident']['wan'] = 0;
+            foreach ($newReturn as $kk => $vv) {
+                if ($v['week'] == $vv['flag']) {
+                    $newList[$k]['date'] = $v['date'];
+                    $newList[$k]['ident']['zao'] = $vv['ident']['zao_id'];
+                    $newList[$k]['ident']['xia'] = $vv['ident']['xia_id'];
+                    $newList[$k]['ident']['wan'] = $vv['ident']['wan_id'];
+                }
+            }
+        }
+
+        $selfList = [];
+        if ($selfScheduleList) {
+            // 自定义排班数组
+            $selfScheduleList = $selfScheduleList->toArray();
+            foreach ($selfScheduleList as $k => $v) {
+                if (!isset($selfList[$v['schedule_date']])) {
+                    $selfList[$v['schedule_date']] = $v;
+                    if ($v['type'] == 1) {
+                        $selfList[$v['schedule_date']]['ident']['zao_id'] = $v['organization_id'];
+                        $selfList[$v['schedule_date']]['ident']['xia_id'] = 0;
+                        $selfList[$v['schedule_date']]['ident']['wan_id'] = 0;
+                    } else if ($v['type'] == 2) {
+                        $selfList[$v['schedule_date']]['ident']['zao_id'] = 0;
+                        $selfList[$v['schedule_date']]['ident']['xia_id'] = $v['organization_id'];
+                        $selfList[$v['schedule_date']]['ident']['wan_id'] = 0;
+                    } else {
+                        $selfList[$v['schedule_date']]['ident']['zao_id'] = 0;
+                        $selfList[$v['schedule_date']]['ident']['xia_id'] = 0;
+                        $selfList[$v['schedule_date']]['ident']['wan_id'] = $v['organization_id'];
+                    }
+                } else {
+                    if ($v['type'] == 1) {
+                        $selfList[$v['schedule_date']]['ident']['zao_id'] = $v['organization_id'];
+                    } else if ($v['type'] == 2) {
+                        $selfList[$v['schedule_date']]['ident']['xia_id'] = $v['organization_id'];
+                    } else {
+                        $selfList[$v['schedule_date']]['ident']['wan_id'] = $v['organization_id'];
+                    }
+                }
+            }
+
+            foreach ($selfList as $k => $v) {
+                foreach ($newList as $kk => $vv) {
+                    if ($v['schedule_date'] == $vv['date']) {
+                        $newList[$kk]['date'] = $vv['date'];
+                        $newList[$kk]['ident']['zao'] = $v['ident']['zao_id'];
+                        $newList[$kk]['ident']['xia'] = $v['ident']['xia_id'];
+                        $newList[$kk]['ident']['wan'] = $v['ident']['wan_id'];
+                    }
+                }
+            }
+
+
+        }
+        return out($newList);
+    }
+
+
+    /**
+     * 获取早中下午的id
+     * @param $sid
+     * @param $time
+     * @param $req
+     * @param $doctor_id
+     * @return array
+     * @author Liu-Yh
+     * Create By 2020/11/6 16:27
+     */
+    protected function getMaf($sid, $time, $req, $doctor_id)
+    {
+        $maf = [];
+        foreach ($time as $k => $v) {
+            $maf[$k]['schedule_id'] = $sid;
+            $maf[$k]['organization_id'] = $req['organization_id'];
+            $maf[$k]['time_period_id'] = $v;
+            $maf[$k]['schedule_date'] = $req['schedule_date'];
+            $maf[$k]['docter_id'] = $doctor_id;
+            $maf[$k]['type'] = $req['type'];
+            $maf[$k]['order_num'] = 0;
+        }
+
+        return $maf;
+    }
+
+
+    /**
+     * 周模板添加数据
+     * @param $time
+     * @param $req
+     * @param $doctor_id
+     * @return array
+     */
+    protected function week_getMaf($time, $req, $doctor_id)
+    {
+
+        $maf = [];
+        foreach ($time as $k => $v) {
+//            $maf[$k]['schedule_id']=$sid;
+//            $maf[$k]['schedule_date']=$req['schedule_date'];
+            $maf[$k]['type'] = $req['type'];
+            $maf[$k]['schedule_type'] = 1;
+            $maf[$k]['organization_id'] = $req['organization_id'];
+            $maf[$k]['docter_id'] = $doctor_id;
+            $maf[$k]['time_period_id'] = $v;
+            $maf[$k]['week'] = $req['week'];
+        }
+
+        return $maf;
+    }
+
+
+    /**
+     * 获取会话列表
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/11/6 17:11
+     */
+    public function getUserListMsg()
+    {
+        $req = request()->post();
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $where[] = ['product_type', 2];
+        $where[] = ['order_status', '>', 2];
+        $where[] = ['payment_status', 2];
+        $where[] = ['docter_id', $doctor_id];
+        $list = Order::with('user')->where($where)->orderBy('receiving_time', 'desc')->get();
+        $newList = [];
+        if ($list) {
+            $list = $list->toArray();
+            foreach ($list as $k => $v) {
+                $messages = ImMessage::where(['senderId'=>'doctor_'.$doctor_id,'receiverId'=>'member_'.$v['user_id']])->orWhere(function ($query) use ($req,$doctor_id,$v){
+                    $query->where(['senderId'=>'member_'.$v['user_id'],'receiverId'=>'doctor_'.$doctor_id]);
+                })->orderBy('id','desc')->first();
+                if($messages){
+                    if($messages['type']=='text'){
+                        $newList[$v['user_id']]['out_message'] = $messages['payload'];
+                    }else if ($messages['type'] == 'audio'){
+                        $newList[$v['user_id']]['out_message'] = "[语音消息]";
+                    }else{
+                        $newList[$v['user_id']]['out_message'] = "[图片消息]";
+                    }
+                    if (empty($messages['create_time'])){
+                        $newList[$v['user_id']]['out_time'] = "";
+
+                    }else{
+                        $newList[$v['user_id']]['out_time'] = date('m-d',$messages['create_time']);
+                    }
+                }else{
+                    $newList[$v['user_id']]['out_message'] = '';
+                    $newList[$v['user_id']]['out_time'] = '';
+                }
+
+                $newList[$v['user_id']]['flag'] = 'member_' . $v['user_id'];
+                $newList[$v['user_id']]['order_status'] = $v['order_status'];
+                $newList[$v['user_id']]['nickname'] = $v['user']['nickname'];
+                $newList[$v['user_id']]['avatar'] = $v['user']['avatar'];
+                $newList[$v['user_id']]['remark'] = !empty($v['user']['remark'])?$v['user']['remark']:'';
+            }
+            $newList = array_values($newList);
+        }
+        return out($newList);
+    }
+
+
+    /**
+     * 获取认证信息
+     * @return mixed
+     */
+    public function getRenInfo()
+    {
+        $req = request()->post();
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        // 获取本人认证信息
+        $returnRes = [];
+        $docter = Docter::where('id', '=', $doctor_id)->first();
+        if ($docter) {
+            $docter = $docter->toArray();
+        } else {
+            return $docter;
+        }
+        $returnRes['info'] = $docter;
+        // 获取申请的认证机构
+        $org = DocterOrganization::with(['organization'])->where('docter_id', '=', $doctor_id)->get();
+        $oqf = DocterOrganization::with(['office', 'qualification'])->where('docter_id', '=', $doctor_id)->get();
+        foreach ($org as $k => $v) {
+            $org[$k]['province'] = Areas::where('id', '=', $v['organization']['province_id'])->select('name')->first()['name'];
+            $org[$k]['city'] = Areas::where('id', '=', $v['organization']['city_id'])->select('name')->first()['name'];
+            $org[$k]['area'] = Areas::where('id', '=', $v['organization']['area_id'])->select('name')->first()['name'];
+            $org[$k]['name'] = $v['organization']['name'];
+        }
+        $returnRes['orgList'] = $org;
+        $returnRes['oqf'] = $oqf;
+        return out($returnRes);
+    }
+
+    /**
+     * 获取通话记录
+     * @return mixed
+     */
+    public function callLog(){
+        $req = request()->post();
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $where =[];
+        if(isset($req['order_id'])&&!empty($req['order_id'])){
+            $where['order_id'] = $req['order_id'];
+        }
+        $where['docter_id'] = $doctor_id;
+        $list = CallLog::where($where)->get();
+        return out($list);
+    }
+
+
+    /**
+     * 通话列表
+     * @return mixed
+     */
+    public function user_call(){
+        $req = request()->post();
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $list=[];
+//        var_dump($doctor_id);
+//die();
+        if(isset($req['user_id'])&&!empty($req['user_id'])){
+            $ids = [];
+            $orderList = Order::where(['user_id'=>$req['user_id'],'product_type'=>1,'payment_status'=>2])->select('id')->get();
+            if($orderList){
+                foreach ($orderList as $k=>$v){
+                    $ids[$k] = $v['id'];
+                }
+            }
+            $lists = CallLog::with('orders')->whereIn('order_id',$ids)->orderBy('call_time', 'desc')->get();
+            if ($lists){
+                foreach ($lists as $k=>$v){
+                    $list[$k]['time'] = $v['call_time'];
+                    $list[$k]['talk_time'] = $v['talk_time'];
+                    $list[$k]['order_sn'] = $v['orders']['order_sn'];
+                }
+            }
+        }else{
+            $orderList = Order::with(['user','calllog'])->where(['docter_id'=>$doctor_id,'product_type'=>1,'payment_status'=>2])->groupBy(['user_id'])->get();
+
+            if ($orderList){
+                foreach ($orderList as $k=>$v){
+                    $list[$k]['user'] = $v['user'];
+                    $calls = CallLog::where('docter_id',$doctor_id)->orderBy('id','desc')->first();
+                    if ($calls){
+
+                        $list[$k]['user']['dates'] = $calls['call_time'];
+                    }else{
+                        $list[$k]['user']['dates'] = '无';
+                    }
+
+                    $save = UserDocter::where(['user_id'=>$v['user']['id'],'docter_id'=>$doctor_id])->first();
+
+                    if ($save) {
+                        $list[$k]['user']['remark'] = $save['remark'];
+                    } else {
+                        $list[$k]['user']['remark'] = '';
+                    }
+
+                    $list[$k]['user']['log'] = $v['calllog'];
+//                    $list[$k]['log']['date'] = date('m/d',strtotime(end($v['calllog'])['call_time']));
+                }
+            }
+
+        }
+
+        return out($list);
+    }
+
+    /**
+     * 获取聊天记录
+     * @return mixed
+     */
+    public function getImList(){
+        $req = request()->post();
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $where =[];
+        if(!isset($req['flag'])||empty($req['flag'])){
+            return out("",500,'用户flag不能为空');
+        }
+        $list = ImMessage::where(['senderId'=>'doctor_'.$doctor_id,'receiverId'=>$req['flag']])->orWhere(function ($query) use ($req,$doctor_id){
+            $query->where(['senderId'=>$req['flag'],'receiverId'=>'doctor_'.$doctor_id]);
+        })->get();
+
+        $newList=[];
+        if ($list){
+            foreach ($list as $k=>$v){
+                $decode = json_decode($v['text'],true);
+//               $newList[$k]['id']=$decode['id'];
+                $newList[$k]['messageId']=$decode[0]['messageId'];
+                $newList[$k]['type']=$decode[0]['type'];
+                $newList[$k]['senderId']=$decode[0]['senderId'];
+                $newList[$k]['receiverId']=$decode[0]['receiverId'];
+                $newList[$k]['timestamp']=$decode[0]['timestamp'];
+                $newList[$k]['payload']= json_decode($decode[0]['payload'],true);
+            }
+
+        }
+        return out($newList);
+    }
+}

+ 49 - 0
app/Http/Controllers/Api/V2/NurseController.php

xqd
@@ -0,0 +1,49 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-4
+ * Time: 下午8:43
+ */
+
+namespace App\Http\Controllers\Api\V2;
+
+use App\Models\Nurse;
+
+class NurseController extends AuthController
+{
+    public function nurseList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'name' => 'max:255',
+            'free_type' => 'in:0,1,2',
+            'sort_type' => 'in:1,2'
+        ]);
+
+        $builder = Nurse::select(['id', 'price', 'name', 'remark']);
+        if (!empty($req['free_type'])) {
+            if ($req['free_type'] == 1) {
+                $builder->where('price', 0);
+            }
+            elseif ($req['free_type'] == 2) {
+                $builder->where('price', '>', 0);
+            }
+        }
+        if (!empty($req['name'])) {
+            $builder->where('name', 'like', '%'.$req['name'].'%');
+        }
+        if (!empty($req['sort_type'])) {
+            if ($req['sort_type'] == 1) {
+                $builder->orderBy('price', 'asc');
+            }
+            elseif ($req['sort_type'] == 2) {
+                $builder->orderBy('price', 'desc');
+            }
+        }
+
+        $data = $builder->paginate();
+
+        return out($data);
+    }
+}

+ 679 - 0
app/Http/Controllers/Api/V2/PatientController.php

xqd
@@ -0,0 +1,679 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Yuanhang Liu
+ * Date: 20-10-15
+ * Time: 下午8:46
+ */
+
+namespace App\Http\Controllers\Api\V2;
+
+use App\Models\Docter;
+use App\Models\Order;
+use App\Models\Patient;
+use App\Models\CallLog;
+use App\Models\OrderPatient;
+use App\Models\DocterOrganization;
+use App\Models\Suggest;
+use App\Models\User;
+use App\Models\UserMessages;
+use App\Models\Organization;
+use App\Http\Controllers\Api\V2\CommonController as Commons;
+use Illuminate\Support\Facades\DB;
+use App\Models\Axb;
+use App\Models\CallPhone;
+
+/**
+ * 咨询订单用户类
+ * Class PatientController
+ * @package App\Http\Controllers\Api\V2
+ */
+class PatientController extends AuthController
+{
+    protected $relationSearch = true;
+    /**
+     * @return mixed
+     * 患者咨询列表
+     * @author Yuanhang Liu & Xiaoyun Liu
+     */
+    public function orderPatientList()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'curPage' => 'required|integer',
+            'pageSize' => 'required|integer',
+        ]);
+        $pageSize = ($req['curPage']-1)*$req['pageSize'];
+        $user = $this->user;
+        $doctor_id = $user['id'];
+        $where = [];
+        $order=['created_at','desc'];
+
+        $where['docter_id'] = $doctor_id;
+        if (isset($req['appointment']) && $req['appointment']==1){
+            // 门诊预约
+            $where['product_type'] = 3;
+            if (isset($req['timeSort']) && $req['timeSort']=='0') {
+                $order = ['order_patients.appoint_start_time','asc']; //预约时间正序
+            }
+            if (isset($req['timeSort']) && $req['timeSort']=='1') {
+                $order= ['order_patients.appoint_start_time','desc']; //预约时间倒叙
+            }
+            if (isset($req['timeSort']) && $req['timeSort']=='2') {
+                $order = ['created_at','asc']; //下单时间正序
+            }
+            if (isset($req['timeSort']) && $req['timeSort']=='3') {
+                $order = ['created_at','desc']; //下单时间倒叙
+            }
+
+            if (isset($req['comStatus']) && $req['comStatus']=='0') {
+                $comstatus = [1,2,3];
+                $where[] = [function($query) use ($comstatus){
+                    $query->whereIn('order_status', $comstatus);//处理中
+                }];
+            }
+            if (isset($req['comStatus']) && $req['comStatus']=='1') {
+                $where['order_status'] = 4; //已完成
+
+            }
+        }else{
+            // 图文和电话的
+            $ids = [1,2];
+            $where[] = [function($query) use ($ids){
+                $query->whereIn('product_type', $ids);
+            }];
+            if(isset($req['typeAll']) && $req['typeAll']==1){
+                $where['product_type']=2;//图文咨询
+            }
+            if(isset($req['typeAll']) && $req['typeAll']==2){
+                $where['product_type']=1;//电话咨询
+            }
+            if(isset($req['processing']) && $req['processing']==0){
+                $status = [1,2,3];
+                $where[] = [function($query) use ($status){
+                    $query->whereIn('order_status', $status);//处理中
+                }];
+            }
+            if(isset($req['processing']) && $req['processing']==1){
+                $where['order_status'] = 4; //历史记录,已完成订单
+            }
+        }
+
+
+//        $data = Order::With(['orderPatient'=>function($query) use ($orders){
+//            $query->orderBy($orders[0],$orders[1]);
+//        }])->where($where)->orderBy($order[0],$order[1])->skip($pageSize)->take($req['pageSize'])->groupBy('id')->get()->toArray();
+        $data = DB::table('orders')
+                ->leftJoin('order_patients','order_patients.order_id','=','orders.id')
+                ->select(['orders.*','order_patients.birthday as obirthday','order_patients.appoint_start_time','order_patients.name as oanme'])
+                ->where($where)->orderBy($order[0],$order[1])
+                ->skip($pageSize)->take($req['pageSize'])
+                ->groupBy('id')
+                ->get()->toArray();
+
+//        $data = Order::with('orderPatient')->where($where)->skip($pageSize)->take($req['pageSize'])->groupBy('id')->toSql();
+//        $data = OrderPatient::with("order")->where('id', $user['id'])->orderBy('id', 'desc')->limit($pageSize,$req['pageSize'])->get()->toarray();
+        $list = [];
+        try {
+
+            foreach ($data as $k=>$v){
+                $v = get_object_vars($v);
+                if (!$v['obirthday']){
+                    unset($list[$k]);
+                }else{
+                    $list[$k]['id'] = $v['id'];
+                    $list[$k]['user_id'] = $v['user_id'];
+                    $list[$k]['order_sn'] = $v['order_sn'];
+                    $list[$k]['zl'] = $v['product_type'];
+                    $list[$k]['zt'] = $v['order_status'];
+                    unset($list[$k]['order_status'],$list[$k]['product_type']);
+                    $list[$k]['created_at'] = $v['created_at'];
+                    $list[$k]['appoint_time'] = empty($v['appoint_start_time'])?'---':date('Y-m-d H:i:s',$v['appoint_start_time']);
+                    $list[$k]['name'] = $v['oanme'];
+                    $list[$k]['birthday'] = numBirthday($v['obirthday']);
+                }
+
+            }
+
+            return out($list);
+        }catch (\Exception $e){
+            return out($e->getFile().'中第 '.$e->getLine().'行发生了 '.$e->getMessage().'错误');
+        }
+        return out($list);
+    }
+
+
+    public function mzPutOrder(){
+
+    }
+    /**
+     * @return mixed
+     * 完成订单
+     * @author Yuanhang Liu & Xiaoyun Liu
+     */
+    public function orderPatientok(){
+        $req = request()->post();
+        $this->validate(request(), [
+            'order_id|订单id' => 'required|integer',
+            'pathogen|病因' => 'required',
+            'suggest|建议' => 'required',
+            'patient_id|患者ID' => 'required',
+
+        ]);
+        $user = $this->user;
+        $find = Order::where('id','=',$req['order_id'])->first()->toArray();
+        if (!$find){
+            return out('',500,'订单错误!');
+        }
+        if ($find['order_status']>3){
+            return out('',500,'此订单不可操作!');
+
+        }
+        $lable = '';
+        switch ($find['product_type']){
+            case 1:
+                $lable = '电话咨询';
+                break;
+            case 2:
+                $lable = '图文咨询';
+                break;
+            case 3:
+                $lable = '门诊预约';
+                break;
+            case 4:
+                $lable = '疫苗接种预约';
+                break;
+            case 5:
+                $lable = '儿保预约';
+                break;
+            case 6:
+                $lable = '服务包';
+                break;
+            default:
+                $lable ='参数错误!';
+        }
+        $relation_id = '';
+        if ($find['product_type']==1 || $find['product_type']==2){
+            // 需要有意见单的
+            $suggests = Suggest::create([
+                'order_id'=> $find['id'],
+                'user_id'=> $find['user_id'],
+                'symptoms'=> $req['symptoms'],
+                'pathogen'=> $req['pathogen'],
+                'suggest'=> $req['suggest'],
+                'patient_id'=> $req['patient_id']
+            ]);
+            $suggests = $suggests->toArray();
+            $relation_id= $suggests['id'];
+        }else{
+            $relation_id= 0;
+        }
+
+
+        $status = $find['product_type'];
+        $lab='';
+        $mesid = $relation_id;
+        if ($status==1){
+            $lab = '电话咨询';
+        }else if ($status==2){
+            $lab = '图文咨询';
+        }else if($status==3){
+            $mesid = $find['id'];
+            $lab = '门诊预约';
+        }
+        $order_sn = $find['order_sn'];
+        $doctername = $user['name'];
+
+
+        DB::beginTransaction();
+        try {
+            Order::where('id','=',$req['order_id'])->update(['order_status'=>4,'updated_at'=>date('Y-m-d H:i:s',time()),'end_time'=>time()]);
+            Docter::where('id','=',$user['id'])->increment('service_persons');
+            // 添加到用户记录中!
+            UserMessages::create([
+                'user_id'=>$find['user_id'],
+                'docter_id'=>$user['id'],
+                'status'=>1,
+                'type'=>2,
+                'relation_id'=>$mesid,
+                'content'=>"您的 ".$lab." 订单,订单号".$order_sn.",医生".$doctername."已经确认完成(点击查看意见单)",
+            ]);
+            DB::commit();
+        }catch (\Exception $e){
+            DB::rollBack();
+            return out('',500,$e->getMessage());
+        }catch (\PDOException $e){
+            DB::rollBack();
+            return out('',500,$e->getMessage());
+        }
+
+        $axbwhere['docter_id'] = $user['id'];
+        $axbwhere['user_id'] = $req['user_id'];
+        $finds = Axb::where($axbwhere)->orderBy('id','desc')->first();
+
+        if ($status==1 && $finds){
+            $unlok = (new Commons())->unLokPhone($finds['xphone']);
+            Axb::where($axbwhere)->delete();
+        }
+
+        return out();
+
+    }
+
+
+    /**
+     * 门诊预约完成订单
+     * @return mixed
+     * @throws \Exception
+     */
+    public function mzPatientok(){
+        $req = request()->post();
+        $this->validate(request(), [
+            'order_id|订单id' => 'required|integer',
+        ]);
+        $user = $this->user;
+        $find = Order::where('id','=',$req['order_id'])->first()->toArray();
+        if (!$find){
+            return out('',500,'订单错误!');
+        }
+        if ($find['order_status']>3){
+            return out('',500,'此订单不可操作!');
+
+        }
+        $lable = '';
+        switch ($find['product_type']){
+            case 1:
+                $lable = '电话咨询';
+                break;
+            case 2:
+                $lable = '图文咨询';
+                break;
+            case 3:
+                $lable = '门诊预约';
+                break;
+            case 4:
+                $lable = '疫苗接种预约';
+                break;
+            case 5:
+                $lable = '儿保预约';
+                break;
+            case 6:
+                $lable = '服务包';
+                break;
+            default:
+                $lable ='参数错误!';
+        }
+        $relation_id= 0;
+        $status = $find['product_type'];
+        $lab='';
+        $mesid = $relation_id;
+        if ($status==1){
+            $lab = '电话咨询';
+        }else if ($status==2){
+            $lab = '图文咨询';
+        }else if($status==3){
+            $mesid = $find['id'];
+            $lab = '门诊预约';
+        }
+        $order_sn = $find['order_sn'];
+        $doctername = $user['name'];
+        DB::beginTransaction();
+        try {
+            Order::where('id','=',$req['order_id'])->update(['order_status'=>4,'updated_at'=>date('Y-m-d H:i:s',time()),'end_time'=>time()]);
+            Docter::where('id','=',$user['id'])->increment('service_persons');
+            // 添加到用户记录中!
+            UserMessages::create([
+                'user_id'=>$find['user_id'],
+                'docter_id'=>$user['id'],
+                'status'=>1,
+                'type'=>2,
+                'relation_id'=>$mesid,
+                'content'=>"您的 ".$lab." 订单,订单号".$order_sn.",医生".$doctername."已经确认完成(点击查看订单)",
+            ]);
+            DB::commit();
+        }catch (\Exception $e){
+            DB::rollBack();
+            return out('',500,$e->getMessage());
+        }catch (\PDOException $e){
+            DB::rollBack();
+            return out('',500,$e->getMessage());
+        }
+
+        return out();
+    }
+
+    /**
+     * @return mixed
+     * 接单
+     * @author Yuanhang Liu & Xiaoyun Liu
+     */
+    public function putOrderPatient(){
+        $req = request()->post();
+        $this->validate(request(), [
+            'order_id|订单id' => 'required|integer',
+        ]);
+        $user = $this->user;
+
+        $find = Order::where('id','=',$req['order_id'])->first()->toArray();
+        $status = $find['product_type'];
+        $lab='';
+        if ($status==1){
+            $lab = '电话咨询';
+        }else if ($status==2){
+            $lab = '图文咨询';
+        }else if($status==3){
+            $lab = '门诊预约';
+        }
+        $order_sn = $find['order_sn'];
+        $order_id = $find['id'];
+        $doctername = $user['name'];
+//        1.电话咨询 2.图文咨询 3.门诊预约 4.疫苗接种预约 5.儿保预约 6.服务包 7.充值
+
+        if (!$find){
+            return out('',500,'订单错误!');
+        }
+        if ($find['order_status']!=2){
+            return out('',500,'此订单已被接单或未付款!');
+        }
+        if ($find['payment_status']>=4){
+            return out('',500,'此订单可能已完成!');
+        }
+        DB::beginTransaction();
+        try {
+            Order::where('id','=',$req['order_id'])->update(['order_status'=>3,'updated_at'=>date('Y-m-d H:i:s',time()),'receiving_time'=>time()]);
+            // 添加到用户记录中!
+            UserMessages::create([
+                'user_id'=>$find['user_id'],
+                'docter_id'=>$user['id'],
+                'status'=>1,
+                'type'=>1,
+                'relation_id'=>$order_id,
+                'content'=> "您的 ".$lab." 订单,订单号".$order_sn.",医生".$doctername."已经确认接单(点击查看订单详情)",
+            ]);
+            DB::commit();
+            return out();
+        }catch (\Exception $e){
+
+            DB::rollBack();
+            return out('',500,$e->getMessage());
+        }catch (\PDOException $e){
+
+            DB::rollBack();
+            return out('',500,$e->getMessage());
+        }
+    }
+
+    /**
+     * @return mixed
+     * 患者咨询详情
+     * @author Yuanhang Liu & Xiaoyun Liu
+     */
+    public function orderPatientDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'patient_id' => 'required|integer',
+        ]);
+        $data = [];
+        // 订单查询
+        $data = Order::with(['orderPatient','user','calllog'])->where('id', $req['patient_id'])->first()->toArray();
+
+        // 通话记录查询
+        $datas = CallLog::where('order_id', $req['patient_id'])->get();
+
+        // 机构查询
+        $user = $this->user;
+        $doctor_id = (new Commons)->getUserIdByDoctorId($user['phone']);
+        // 返回数组
+        $res_patient = [];
+        //电话咨询
+
+        if($data['product_type']==1){
+
+            $res_patient['patient_id'] = $data['order_patient']['id'];
+            $res_patient['user_id'] = $data['user_id'];
+            $res_patient['order_sn'] = $data['order_sn'];
+            $res_patient['patient_id'] = $data['patient_id'];
+            $res_patient['product_type'] = $data['product_type'];
+            $res_patient['name']=$data['order_patient']['name'];//患者姓名
+            $res_patient['numbirthday']=numBirthday($data['order_patient']['birthday']);//年龄
+            $res_patient['card_number']=$data['order_patient']['card_number'];//身份证号
+            $res_patient['created_at']=$data['created_at'];//下单时间
+            $res_patient['nickname']=$data['user']['nickname'];//下单用户
+            $res_patient['receiving_time']=!empty($data['receiving_time'])?date('Y-m-d H:i:s',$data['receiving_time']):'---';//接单时间
+            $res_patient['order_status']=$data['order_status'];//订单状态
+            $res_patient['call_list']=[];//通话记录
+            $res_patient['one_call'] = '';
+            if ($data['calllog']){
+                $res_patient['one_call'] = $data['calllog'][0]['call_time'];
+                $res_patient['secret_no']=$data['calllog'][count($data['calllog'])-1]['secret_no'];//X号码
+                foreach ($data['calllog'] as $ks=>$vs){
+                    $res_patient['call_list'][$ks]['frequency']='通话'.($ks+=1);//拨打电话开始时间
+                    $res_patient['call_list'][$ks]['start']=$vs['call_time'];//拨打电话开始时间
+                    $res_patient['call_list'][$ks]['end']=$vs['ring_time'];//拨打电话结束时间
+                    $res_patient['call_list'][$ks]['duration']=gmdate('i:s',$vs['talk_time']);//拨打电话结束时间
+
+                }
+            }
+        }
+
+        //图文咨询
+        if($data['product_type']==2){
+            $res_patient['order_sn'] = $data['order_sn'];
+            $res_patient['patient_id'] = $data['patient_id'];
+            $res_patient['user_id'] = $data['user_id'];
+            $res_patient['user_name'] = $data['user']['nickname'];
+            $res_patient['user_avatar'] = $data['user']['avatar'];
+            $res_patient['product_type'] = $data['product_type'];
+            $res_patient['name']=$data['order_patient']['name'];
+            $res_patient['numbirthday']=numBirthday($data['order_patient']['birthday']);
+            $res_patient['card_number']=$data['order_patient']['card_number'];
+            $res_patient['symptoms']=$data['order_patient']['symptoms'];//病情描述
+            $res_patient['medical_imgs']=json_decode($data['order_patient']['medical_imgs'],true);//病情照片
+            $res_patient['created_at']=$data['created_at'];//下单时间
+            $res_patient['nickname']=$data['user']['nickname'];//下单用户
+            $res_patient['receiving_time']=!empty($data['receiving_time'])?date('Y-m-d H:i:s',$data['receiving_time']):'---'; //接单时间
+            $res_patient['order_status']=$data['order_status'];//接单时间
+        }
+
+        //门诊预约
+        if($data['product_type']==3){
+            $res_patient['order_sn'] = $data['order_sn'];
+            $res_patient['patient_id'] = $data['patient_id'];
+            $res_patient['product_type'] =$data['product_type'];
+            $res_patient['name']=$data['order_patient']['name']; // 患者
+            $res_patient['numbirthday']=numBirthday($data['order_patient']['birthday']); //年龄
+            $res_patient['card_number']=$data['order_patient']['card_number']; // 证件号
+            $res_patient['appoint_time'] = date('Y年m月d日 H:i',$data['order_patient']['appoint_start_time']);// 预约时间
+            $res_patient['order_status'] = $data['order_status'];// 订单状态
+            $organization = Organization::where('id','=',$data['organization_id'])->first();
+            if($organization){
+                $organization = $organization->toArray();
+                $res_patient['organization']= $organization['name']; // 门诊机构
+            }else{
+                $res_patient['organization']= ''; // 门诊机构
+
+            }
+            $res_patient['order_sn']=$data['order_sn'];//订单号
+            $res_patient['created_at']=$data['created_at'];//下单时间
+            $res_patient['nickname']=$data['user']['nickname'];//下单用户
+        }
+
+        return out($res_patient);
+    }
+
+
+    /**
+     * 拨打电话/绑定电话
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/11/24 19:19
+     */
+    public function callPhones(){
+        $req = request()->post();
+        $user = $this->user;
+        $this->validate(request(), [
+            'order_id' => 'required',
+            'user_id' => 'required|integer',
+        ]);
+        $docter_id = $user['id'];
+        $docter_phone = $user['phone'];
+        if(!$docter_phone){
+            return out('',500,'医生电话不存在!');
+        }
+        $find = Order::with('orderPatient')->where('order_sn',$req['order_id'])->first()->toArray();
+        if (empty($find['order_patient'])){
+            return out('',500,'患者电话不存在');
+        }
+        $phone = $find['order_patient']['phone'];
+
+        if($docter_phone==$phone){
+            return out('',500,'医生和患者电话号不能一样!');
+
+        }
+        $wheres['docter_id'] = $docter_id;
+        $wheres['user_id'] = $req['user_id'];
+        $commons = new Commons();
+        $finds = Axb::where($wheres)->orderBy('id','desc')->first();
+
+        if ($finds){
+            $querylok = $commons->QuerySubsId($finds['xphone']);
+            if ($querylok['Code']=='OK'){
+                // 可能是数组
+                $new_arr = explode(',',$querylok['SubsId']);
+                foreach ($new_arr as $v){
+                    $queryCallStatus = $commons->QuerySubscriptionDetail($finds['xphone'],$v);
+                    if ($queryCallStatus['Code']=='OK'){
+                        if ($queryCallStatus['Code']=="OK"){
+                            if ($queryCallStatus['SecretBindDetailDTO']['PhoneNoA']==$docter_phone&&$queryCallStatus['SecretBindDetailDTO']['PhoneNoB']==$phone){
+                                return out($finds['xphone']);
+                            }else{
+                                if ($phone){
+                                    $callModel = $commons->BindAxb($docter_phone,$phone);
+                                    if ($callModel['Code']=="OK"){
+                                        Axb::create([
+                                            'docter_id'=>$docter_id,
+                                            'user_id'=>$req['user_id'],
+                                            'xphone'=>$callModel['SecretBindDTO']['SecretNo'],
+                                            'subs_id'=>$callModel['SecretBindDTO']['SubsId'],
+                                            'createtime'=>time(),
+                                        ]);
+                                        return out($callModel['SecretBindDTO']['SecretNo']);
+                                    }
+                                }else{
+                                    return out('',500,'患者电话不存在');
+                                }
+                            }
+                        }else{
+                            if ($phone){
+                                $callModel = $commons->BindAxb($docter_phone,$phone);
+                                if ($callModel['Code']=="OK"){
+                                    Axb::create([
+                                        'docter_id'=>$docter_id,
+                                        'user_id'=>$req['user_id'],
+                                        'xphone'=>$callModel['SecretBindDTO']['SecretNo'],
+                                        'subs_id'=>$callModel['SecretBindDTO']['SubsId'],
+                                        'createtime'=>time(),
+                                    ]);
+                                    return out($callModel['SecretBindDTO']['SecretNo']);
+                                }
+                            }else{
+                                return out('',500,'患者电话不存在');
+                            }
+                        }
+                    }
+                }
+
+
+            }
+
+        }else{
+            if ($phone){
+                $callModel = $commons->BindAxb($docter_phone,$phone);
+
+                if ($callModel['Code']=="OK"){
+                    Axb::create([
+                        'docter_id'=>$docter_id,
+                        'user_id'=>$req['user_id'],
+                        'xphone'=>$callModel['SecretBindDTO']['SecretNo'],
+                        'subs_id'=>$callModel['SecretBindDTO']['SubsId'],
+                        'createtime'=>time(),
+                    ]);
+                    return out($callModel['SecretBindDTO']['SecretNo']);
+                }else{
+                    return out($callModel);
+                }
+            }else{
+                return out('',500,'患者电话不存在');
+            }
+        }
+
+    }
+
+
+    /**
+     * 电话随访
+     * @return \Illuminate\Http\JsonResponse
+     * @author Liu-Yh
+     * Create By 2020/11/24 19:19
+     */
+    public function callPhoneSure(){
+        $req = request()->post();
+        $user = $this->user;
+        $this->validate(request(), [
+            'user_id' => 'required|integer',
+        ]);
+        $docter_id = $user['id'];
+        $docter_phone = $user['phone'];
+        if(!$docter_phone){
+            return out('',500,'医生电话不存在!');
+        }
+        $find = User::where('id',$req['user_id'])->first()->toArray();
+        $phone = $find['phone'];
+        $wheres['docter_id'] = $docter_id;
+        $wheres['user_id'] = $find['id'];
+        $commons = new Commons();
+        $finds = Axb::where($wheres)->orderBy('id','desc')->first();
+        if ($finds){
+            $querylok = $commons->QuerySubsId($finds['xphone']);
+            if ($querylok['Code']=='OK'){
+                $queryCallStatus = $commons->QueryCallStatus($phone,$querylok['SubsId']);
+                if ($queryCallStatus['Code']=='OK'){
+                    if ($queryCallStatus['SecretCallStatusDTO']!=4){
+                        return out($finds['xphone']);
+                    }else{
+                        if ($phone){
+                            $callModel = $commons->BindAxb($docter_phone,$phone);
+                            if ($callModel['Code']=="OK"){
+                                return out($callModel['SecretBindDTO']['SecretNo']);
+                            }
+                        }else{
+                            return out('',500,'患者电话不存在');
+                        }
+                    }
+                }
+            }
+
+        }else{
+            if ($phone){
+                $callModel = $commons->BindAxb($docter_phone,$phone);
+                if ($callModel['Code']=="OK"){
+                    Axb::create([
+                        'docter_id'=>$docter_id,
+                        'user_id'=>$req['user_id'],
+                        'xphone'=>$callModel['SecretBindDTO']['SecretNo'],
+                        'createtime'=>time(),
+                    ]);
+                    return out($callModel['SecretBindDTO']['SecretNo']);
+                }else{
+                    return out($callModel);
+                }
+            }else{
+                return out('',500,'患者电话不存在');
+            }
+        }
+
+    }
+
+
+}

+ 49 - 0
app/Http/Controllers/Api/V2/PhoneCallController.php

xqd
@@ -0,0 +1,49 @@
+<?php
+namespace App\Http\Controllers\Api\V2;
+use AlibabaCloud\Client\AlibabaCloud;
+use AlibabaCloud\Client\Exception\ClientException;
+use Alibabaloud\Client\Exception\ServerException;
+
+/**
+ * 废弃!
+ * Class PhoneCallController
+ * @package App\Http\Controllers\Api\V2
+ */
+class PhoneCallController extends Controller
+{
+    public function BindAxb($phone1='',$phone2='',$data=[]){
+
+        $config = config('config.axb');
+        AlibabaCloud::accessKeyClient($config['appid'], $config['appscret'])
+            ->regionId('cn-kunming')
+            ->asDefaultClient();
+        try {
+            $result = AlibabaCloud::rpc()
+                ->product('Dyplsapi')
+                ->version('2017-05-25')
+                ->action('BindAxb')
+                ->method('POST')
+                ->host('dyplsapi.aliyuncs.com')
+                ->options([
+                    'query' => [
+                        "Expiration" => "2020-11-25 12:00:00",
+                        'RegionId' => "cn-kunming",
+                        'PhoneNoA' => "18831125321",
+                        'PhoneNoB' => "18830277213",
+                    ],
+                ])
+                ->request();
+            print_r($result->toArray());
+        } catch (ClientException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        } catch (ServerException $e) {
+            echo $e->getErrorMessage() . PHP_EOL;
+        }
+    }
+
+
+
+
+}
+
+?>

+ 45 - 0
app/Http/Controllers/Api/V2/ServiceApplyController.php

xqd
@@ -0,0 +1,45 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Yuanhang Liu
+ * Date: 20-10-14
+ * Time: 上午00:01
+ */
+
+namespace App\Http\Controllers\Api\V2;
+
+use App\Models\ServiceApply;
+
+/**
+ * 服务设置类
+ * Class ServiceApplyController
+ * @package App\Http\Controllers\Api\V2
+ */
+class ServiceApplyController extends AuthController
+{
+    /**
+     * 服务设置审核
+     */
+    public function serviceExamine(){
+        $req = request()->post();
+        $this->validate(request(), [
+            'service_type' => 'required|integer',
+        ]);
+        $user = $this->user;
+        $doctor_id = $user['id'];
+
+        $where['docter_id'] = $doctor_id;
+        $where['service_type'] = $req['service_type'];
+        $data = ServiceApply::where($where)->first();
+        if(empty($data)){
+            ServiceApply::create([
+                'docter_id' => $doctor_id,
+                'service_type' => $req['service_type'],
+                'status' => 1   //审核状态 1 审核 2 已通过 3 已拒绝
+            ]);
+            return out();
+        }else{
+            return out('','','您已提交');
+        }
+    }
+}

+ 159 - 0
app/Http/Controllers/Api/V2/SuggestController.php

xqd
@@ -0,0 +1,159 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: Yuanhang Liu
+ * Date: 20-10-14
+ * Time: 上午00:01
+ */
+
+namespace App\Http\Controllers\Api\V2;
+
+use App\Models\Evaluate;
+use App\Models\Order;
+use App\Models\Suggest;
+use App\Models\SuggestDetail;
+
+/**
+ * 意见管理类
+ * Class SuggestController
+ * @author Yuanhang Liu & Xiaoyun Liu
+ * @package App\Http\Controllers\Api\V2
+ */
+class SuggestController extends AuthController
+{
+    /**
+     * 意见单查看
+     * @author Yuanhang Liu & Xiaoyun Liu
+     * @date 2020/10/14 00:03
+     * @return mixedsuggestList
+     */
+    public function suggestList(){
+        $req = request()->post();
+        $this->validate(request(), [
+            'curPage' => 'required|integer',
+            'pageSize' => 'required|integer',
+            'orders' => 'required',
+        ]);
+        $pageSize = ($req['curPage']-1)*$req['pageSize'];
+        $user = $this->user;
+        $docter_id = $user['id'];
+        $order =[];
+        if($req['orders']==1){
+            // 正序
+            $order = ['created_at','ASC'];
+        }else if($req['orders']==2){
+            // 倒叙
+            $order = ['created_at','desc'];
+        }else{
+            $order =['id','desc'];
+        }
+
+        $order_ids = Order::where('docter_id',$docter_id)->select('id')->get();
+        $data = [];
+        $ids = [];
+        if ($order_ids){
+            foreach($order_ids as $k=>$v){
+                $ids[$k] = $v['id'];
+            }
+            $data = Suggest::with(['order','Patient'])->whereIn('order_id',$ids)->orderBy($order[0], $order[1])->skip($pageSize)->take($req['pageSize'])->get()->toArray();
+            foreach ($data as $k=>$v){
+                if (!$data[$k]['order']||$data[$k]['order']==null||!$data[$k]['patient']||$data[$k]['patient']==null){
+                    unset($data[$k]);
+                }
+                else{
+                    $data[$k]['numBirthday'] = numBirthday($v['patient']['birthday']);
+                    $data[$k]['patient_name'] = $v['patient']['name'];
+                    $data[$k]['order_sn'] = $v['order']['order_sn'];
+                    unset($data[$k]['patient'],$data[$k]['order']);
+                }
+
+            }
+        }
+
+        return out($data);
+    }
+
+    /**
+     * 获取意见单
+     * @author Yuanhang Liu & Xiaoyun Liu
+     * @date 2020/10/14 00:10
+     * @return mixed
+     */
+    public function getSuggestDetail($id=null)
+    {
+        if (empty($id)){
+            $req = request()->post();
+            $this->validate(request(), [
+                'suggest_id' => 'required|integer',
+                'type'  => 'integer',
+            ]);
+            if($req['type']==2){
+                $data = Suggest::where('order_id',$req['suggest_id'])->get()->first();
+                if($data){
+                    $data = $data->toArray();
+                    $id = $data['id'];
+                }else{
+                    return out('',500,'数据错误!');
+                }
+            }else{
+                $id = $req['suggest_id'];
+            }
+        }
+        $data = Suggest::with(['details','Patient','user','order'])->where('id',$id)->get()->toArray();
+//        var_dump($data);die();
+        if ($data){
+            $data[0]['patient_name'] = $data[0]['patient']['name'];
+            $data[0]['patient_card_number'] = $data[0]['patient']['card_number'];
+            $data[0]['birthday'] = numBirthday($data[0]['patient']['birthday']);
+            $data[0]['username'] = $data[0]['user']['nickname'];
+            $data[0]['order_sn'] = $data[0]['order']['order_sn'];
+            unset($data[0]['patient'],$data[0]['user'],$data[0]['order']);
+            return out($data[0]);
+        }else{
+            return out([]);
+        }
+    }
+
+
+
+
+    /**
+     * 补充意见单
+     * @author Yuanhang Liu & Xiaoyun Liu
+     * @date 2020/10/14 00:20
+     * @return mixed
+     */
+    public function addSuggestDetail()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'suggest_id' => 'required|integer',
+            'supplement_reason' => 'required|max:500',
+            'supplement_content' => 'required|max:500',
+        ]);
+
+        $num = 0;
+        // 查询补充过几次了!
+        $count_array = $this->getSuggestDetail($req['suggest_id']);
+        $count_array = json_decode($count_array->getContent(),true);
+        if ($count_array){
+            $count_array = $count_array['data']['details'];
+            $num = count($count_array);
+        }
+//        var_dump($num);die();
+        if ($num>=2){
+            return out(null, 500, '您已经补充过两次意见了!');
+        }
+        $data = SuggestDetail::create([
+            'suggest_id'=>$req['suggest_id'],
+            'supplement_reason'=>$req['supplement_reason'],
+            'supplement_content'=>$req['supplement_content'],
+        ]);
+        return out();
+    }
+
+    public function getWeek(){
+        $data=getWeek(date("w"));
+        return out($data);
+    }
+}

+ 59 - 0
app/Http/Controllers/Api/V2/UserController.php

xqd
@@ -0,0 +1,59 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-23
+ * Time: 上午11:36
+ */
+
+namespace App\Http\Controllers\Api\V2;
+
+use App\Models\Order;
+use App\Models\User;
+use App\Models\Docter;
+use App\Models\UserBalanceLog;
+use EasyWeChat\Factory;
+use Illuminate\Support\Facades\DB;
+
+/**
+ * 用户类
+ * Class UserController
+ * @package App\Http\Controllers\Api\V2
+ */
+class UserController extends AuthController
+{
+    public function userInfo()
+    {
+        $user = $this->user;
+
+        unset($user['session_key']);
+
+        return out($user);
+    }
+
+
+
+    public function updateUser()
+    {
+        $req = request()->post();
+        $this->validate(request(), [
+            'nickname' => 'max:100',
+            'avatar' => 'url',
+            'sex' => 'in:1,2',
+            'birthday' => 'date',
+            'latitude' => 'numeric',
+            'longitude' => 'numeric',
+        ]);
+        $user = $this->user;
+        User::where('id', $user['id'])->update($req);
+        return out();
+    }
+
+    public function userBalanceLog()
+    {
+        $user = $this->user;
+        $data = UserBalanceLog::where('user_id', $user['id'])->orderBy('id', 'desc')->paginate();
+        return out($data);
+    }
+
+}

+ 42 - 0
app/Http/Controllers/Controller.php

xqd
@@ -0,0 +1,42 @@
+<?php
+
+namespace App\Http\Controllers;
+
+use Illuminate\Foundation\Bus\DispatchesJobs;
+use Illuminate\Http\Request;
+use Illuminate\Routing\Controller as BaseController;
+use Illuminate\Foundation\Validation\ValidatesRequests;
+use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
+
+class Controller extends BaseController
+{
+    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
+
+    /**
+     * Validate the given request with the given rules.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  array  $rules
+     * @param  array  $messages
+     * @param  array  $customAttributes
+     * @return array
+     *
+     * @throws \Illuminate\Validation\ValidationException
+     */
+    public function validate(Request $request, array $rules,
+                             array $messages = [], array $customAttributes = [])
+    {
+        $validate = [];
+        foreach ($rules as $k => $v){
+            $tmp = explode('|', $k);
+            $validate[$tmp[0]] = $v;
+            if (!empty($tmp[1]) && empty($customAttributes[$tmp[0]])){
+                $customAttributes[$tmp[0]] = $tmp[1];
+            }
+        }
+
+        return $this->getValidationFactory()->make(
+            $request->all(), $validate, $messages, $customAttributes
+        )->validate();
+    }
+}

+ 81 - 0
app/Http/Kernel.php

xqd
@@ -0,0 +1,81 @@
+<?php
+
+namespace App\Http;
+
+use Illuminate\Foundation\Http\Kernel as HttpKernel;
+
+class Kernel extends HttpKernel
+{
+    /**
+     * The application's global HTTP middleware stack.
+     *
+     * These middleware are run during every request to your application.
+     *
+     * @var array
+     */
+    protected $middleware = [
+        \App\Http\Middleware\TrustProxies::class,
+        \App\Http\Middleware\CheckForMaintenanceMode::class,
+        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
+        \App\Http\Middleware\TrimStrings::class,
+        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
+    ];
+
+    /**
+     * The application's route middleware groups.
+     *
+     * @var array
+     */
+    protected $middlewareGroups = [
+        'web' => [
+            \App\Http\Middleware\EncryptCookies::class,
+            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
+            \Illuminate\Session\Middleware\StartSession::class,
+            // \Illuminate\Session\Middleware\AuthenticateSession::class,
+            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
+            \App\Http\Middleware\VerifyCsrfToken::class,
+            \Illuminate\Routing\Middleware\SubstituteBindings::class,
+        ],
+
+        'api' => [
+            'throttle:60,1',
+            'bindings',
+        ],
+    ];
+
+    /**
+     * The application's route middleware.
+     *
+     * These middleware may be assigned to groups or used individually.
+     *
+     * @var array
+     */
+    protected $routeMiddleware = [
+        'auth' => \App\Http\Middleware\Authenticate::class,
+        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
+        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
+        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
+        'can' => \Illuminate\Auth\Middleware\Authorize::class,
+        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
+        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
+        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
+        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
+    ];
+
+    /**
+     * The priority-sorted list of middleware.
+     *
+     * This forces non-global middleware to always be in the given order.
+     *
+     * @var array
+     */
+    protected $middlewarePriority = [
+        \Illuminate\Session\Middleware\StartSession::class,
+        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
+        \App\Http\Middleware\Authenticate::class,
+        \Illuminate\Routing\Middleware\ThrottleRequests::class,
+        \Illuminate\Session\Middleware\AuthenticateSession::class,
+        \Illuminate\Routing\Middleware\SubstituteBindings::class,
+        \Illuminate\Auth\Middleware\Authorize::class,
+    ];
+}

+ 21 - 0
app/Http/Middleware/Authenticate.php

xqd
@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Illuminate\Auth\Middleware\Authenticate as Middleware;
+
+class Authenticate extends Middleware
+{
+    /**
+     * Get the path the user should be redirected to when they are not authenticated.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @return string
+     */
+    protected function redirectTo($request)
+    {
+        if (! $request->expectsJson()) {
+            return route('login');
+        }
+    }
+}

+ 17 - 0
app/Http/Middleware/CheckForMaintenanceMode.php

xqd
@@ -0,0 +1,17 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode as Middleware;
+
+class CheckForMaintenanceMode extends Middleware
+{
+    /**
+     * The URIs that should be reachable while maintenance mode is enabled.
+     *
+     * @var array
+     */
+    protected $except = [
+        //
+    ];
+}

+ 17 - 0
app/Http/Middleware/EncryptCookies.php

xqd
@@ -0,0 +1,17 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Illuminate\Cookie\Middleware\EncryptCookies as Middleware;
+
+class EncryptCookies extends Middleware
+{
+    /**
+     * The names of the cookies that should not be encrypted.
+     *
+     * @var array
+     */
+    protected $except = [
+        //
+    ];
+}

+ 26 - 0
app/Http/Middleware/RedirectIfAuthenticated.php

xqd
@@ -0,0 +1,26 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Closure;
+use Illuminate\Support\Facades\Auth;
+
+class RedirectIfAuthenticated
+{
+    /**
+     * Handle an incoming request.
+     *
+     * @param  \Illuminate\Http\Request  $request
+     * @param  \Closure  $next
+     * @param  string|null  $guard
+     * @return mixed
+     */
+    public function handle($request, Closure $next, $guard = null)
+    {
+        if (Auth::guard($guard)->check()) {
+            return redirect('/home');
+        }
+
+        return $next($request);
+    }
+}

+ 18 - 0
app/Http/Middleware/TrimStrings.php

xqd
@@ -0,0 +1,18 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Illuminate\Foundation\Http\Middleware\TrimStrings as Middleware;
+
+class TrimStrings extends Middleware
+{
+    /**
+     * The names of the attributes that should not be trimmed.
+     *
+     * @var array
+     */
+    protected $except = [
+        'password',
+        'password_confirmation',
+    ];
+}

+ 23 - 0
app/Http/Middleware/TrustProxies.php

xqd
@@ -0,0 +1,23 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Illuminate\Http\Request;
+use Fideloper\Proxy\TrustProxies as Middleware;
+
+class TrustProxies extends Middleware
+{
+    /**
+     * The trusted proxies for this application.
+     *
+     * @var array|string
+     */
+    protected $proxies;
+
+    /**
+     * The headers that should be used to detect proxies.
+     *
+     * @var int
+     */
+    protected $headers = Request::HEADER_X_FORWARDED_ALL;
+}

+ 24 - 0
app/Http/Middleware/VerifyCsrfToken.php

xqd
@@ -0,0 +1,24 @@
+<?php
+
+namespace App\Http\Middleware;
+
+use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
+
+class VerifyCsrfToken extends Middleware
+{
+    /**
+     * Indicates whether the XSRF-TOKEN cookie should be set on the response.
+     *
+     * @var bool
+     */
+    protected $addHttpCookie = true;
+
+    /**
+     * The URIs that should be excluded from CSRF verification.
+     *
+     * @var array
+     */
+    protected $except = [
+        //
+    ];
+}

+ 18 - 0
app/Models/Areas.php

xqd
@@ -0,0 +1,18 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-29
+ * Time: 上午11:15
+ */
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Model;
+
+class Areas extends Model
+{
+    protected $guarded = [];
+
+    public $timestamps = false;
+}

+ 26 - 0
app/Models/Article.php

xqd
@@ -0,0 +1,26 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:37
+ */
+
+namespace App\Models;
+
+class Article extends BaseModel
+{
+    protected $appends = ['is_collect'];
+
+    public function getIsCollectAttribute()
+    {
+        if (!empty(request()->header('token'))) {
+            $user = User::getUserByToken();
+            if (Collection::where('user_id', $user['id'])->where('article_id', $this->id)->exists()) {
+                return 1;
+            }
+        }
+
+        return 0;
+    }
+}

+ 16 - 0
app/Models/Axb.php

xqd
@@ -0,0 +1,16 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:37
+ */
+
+namespace App\Models;
+
+class Axb extends BaseModel
+{
+    protected $table='axb';
+
+
+}

+ 18 - 0
app/Models/BaseModel.php

xqd
@@ -0,0 +1,18 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-29
+ * Time: 上午11:15
+ */
+
+namespace App\Models;
+
+use Illuminate\Database\Eloquent\Model;
+
+class BaseModel extends Model
+{
+    protected $guarded = [];
+
+    public $timestamps = false;
+}

+ 21 - 0
app/Models/CallLog.php

xqd
@@ -0,0 +1,21 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:37
+ */
+
+namespace App\Models;
+
+class CallLog extends BaseModel
+{
+    protected $table='call_logs';
+
+    public function orders()
+    {
+        
+//        return $this->belongsTo(Order::class);
+        return $this->hasOne(Order::class,'id','order_id');
+    }
+}

+ 15 - 0
app/Models/CallPhone.php

xqd
@@ -0,0 +1,15 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:37
+ */
+
+namespace App\Models;
+
+class CallPhone extends BaseModel
+{
+    protected $table='call_phone';
+
+}

+ 26 - 0
app/Models/Collection.php

xqd
@@ -0,0 +1,26 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:18
+ */
+
+namespace App\Models;
+
+class Collection extends BaseModel
+{
+    public function docter()
+    {
+        return $this->belongsTo(Docter::class);
+    }
+    public function user()
+    {
+        return $this->belongsTo(User::class);
+    }
+
+    public function article()
+    {
+        return $this->belongsTo(Article::class);
+    }
+}

+ 14 - 0
app/Models/CouponType.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午11:44
+ */
+
+namespace App\Models;
+
+class CouponType extends BaseModel
+{
+
+}

+ 36 - 0
app/Models/Docter.php

xqd
@@ -0,0 +1,36 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-29
+ * Time: 上午11:12
+ */
+
+namespace App\Models;
+
+class Docter extends BaseModel
+{
+    protected $casts = [
+        'label' => 'json',
+    ];
+
+    public function office()
+    {
+        return $this->belongsTo(Office::class)->select(['id', 'name']);
+    }
+
+    public function qualification()
+    {
+        return $this->belongsTo(Qualification::class)->select(['id', 'name']);
+    }
+
+    public function organization()
+    {
+        return $this->belongsToMany(Organization::class);
+    }
+
+    public function evaluate()
+    {
+        return $this->hasMany(Evaluate::class)->where('status', 2);
+    }
+}

+ 15 - 0
app/Models/DocterLable.php

xqd
@@ -0,0 +1,15 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:37
+ */
+
+namespace App\Models;
+
+class DocterLable extends BaseModel
+{
+    protected $table='docter_label';
+
+}

+ 15 - 0
app/Models/DocterMessage.php

xqd
@@ -0,0 +1,15 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:37
+ */
+
+namespace App\Models;
+
+class DocterMessage extends BaseModel
+{
+    protected $table='docter_messages';
+    public $timestamps = true;
+}

+ 28 - 0
app/Models/DocterOrganization.php

xqd
@@ -0,0 +1,28 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-29
+ * Time: 上午11:12
+ */
+
+namespace App\Models;
+
+class DocterOrganization extends BaseModel
+{
+    protected $table='docter_organization';
+    public $timestamps = true;
+    public function organization()
+    {
+        return $this->belongsTo(Organization::class);
+    }
+
+    public function office()
+    {
+        return $this->belongsTo(Office::class,'offices_id','id');
+    }
+    public function qualification()
+    {
+        return $this->belongsTo(Qualification::class,'qualifications_id','id');
+    }
+}

+ 14 - 0
app/Models/DocterServiceTimes.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-29
+ * Time: 上午11:12
+ */
+
+namespace App\Models;
+
+class DocterServiceTimes extends BaseModel
+{
+    protected $table='docter_service_times';
+}

+ 19 - 0
app/Models/DocterSetting.php

xqd
@@ -0,0 +1,19 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-29
+ * Time: 上午11:12
+ */
+
+namespace App\Models;
+
+class DocterSetting extends BaseModel
+{
+    protected $table="docter_settings";
+
+    public function organization()
+    {
+        return $this->belongsTo(Organization::class,'org_id','id');
+    }
+}

+ 14 - 0
app/Models/DocterTimes.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-29
+ * Time: 上午11:12
+ */
+
+namespace App\Models;
+
+class DocterTimes extends BaseModel
+{
+
+}

+ 39 - 0
app/Models/DocterUser.php

xqd
@@ -0,0 +1,39 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-29
+ * Time: 上午11:12
+ */
+
+namespace App\Models;
+
+class DocterUser extends BaseModel
+{
+    protected $table='docter_user';
+    public $timestamps = true;
+    public function user()
+    {
+        return $this->belongsTo(User::class);
+    }
+
+//    public function office()
+//    {
+//        return $this->belongsTo(Office::class)->select(['id', 'name']);
+//    }
+//
+//    public function qualification()
+//    {
+//        return $this->belongsTo(Qualification::class)->select(['id', 'name']);
+//    }
+//
+//    public function organization()
+//    {
+//        return $this->belongsToMany(Organization::class);
+//    }
+//
+//    public function evaluate()
+//    {
+//        return $this->hasMany(Evaluate::class)->where('status', 2);
+//    }
+}

+ 22 - 0
app/Models/Evaluate.php

xqd
@@ -0,0 +1,22 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午9:40
+ */
+
+namespace App\Models;
+
+class Evaluate extends BaseModel
+{
+    public function user()
+    {
+        return $this->belongsTo(User::class)->select(['id', 'nickname', 'avatar']);
+    }
+
+    public function order()
+    {
+        return $this->belongsTo(Order::class);
+    }
+}

+ 15 - 0
app/Models/ImMessage.php

xqd
@@ -0,0 +1,15 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午3:37
+ */
+
+namespace App\Models;
+
+class ImMessage extends BaseModel
+{
+    protected $table='im_message';
+
+}

+ 14 - 0
app/Models/Nurse.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-4
+ * Time: 下午4:35
+ */
+
+namespace App\Models;
+
+class Nurse extends BaseModel
+{
+
+}

+ 14 - 0
app/Models/Office.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午2:20
+ */
+
+namespace App\Models;
+
+class Office extends BaseModel
+{
+
+}

+ 54 - 0
app/Models/Order.php

xqd
@@ -0,0 +1,54 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午10:56
+ */
+
+namespace App\Models;
+
+class Order extends BaseModel
+{
+    public function docter()
+    {
+        return $this->belongsTo(Docter::class);
+    }
+    public function user()
+    {
+        return $this->belongsTo(User::class);
+    }
+    public function calllog()
+    {
+        return $this->hasMany(CallLog::class);
+    }
+    /**
+     * 用户医生关注表
+     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
+     * @author Liu-Yh
+     * Create By 2020/11/18 11:06
+     */
+    public function userDocter(){
+        return $this->hasOne(UserDocter::class,'user_id','user_id')->select(['id', 'remark']);;
+    }
+
+    public function orderPatient()
+    {
+        return $this->hasOne(OrderPatient::class);
+    }
+
+    public function orderPack()
+    {
+        return $this->hasMany(OrderPack::class);
+    }
+
+    public function orderNurse()
+    {
+        return $this->hasMany(OrderNurse::class);
+    }
+
+    public function orderVaccine()
+    {
+        return $this->hasOne(OrderVaccine::class);
+    }
+}

+ 14 - 0
app/Models/OrderNurse.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-2
+ * Time: 下午11:44
+ */
+
+namespace App\Models;
+
+class OrderNurse extends BaseModel
+{
+
+}

+ 14 - 0
app/Models/OrderPack.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-2
+ * Time: 下午10:57
+ */
+
+namespace App\Models;
+
+class OrderPack extends BaseModel
+{
+
+}

+ 21 - 0
app/Models/OrderPatient.php

xqd
@@ -0,0 +1,21 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-1
+ * Time: 上午12:09
+ */
+
+namespace App\Models;
+
+class OrderPatient extends BaseModel
+{
+    protected $casts = [
+        'medical_imgs' => 'json',
+    ];
+
+    public function order()
+    {
+        return $this->belongsTo(Order::class);
+    }
+}

+ 14 - 0
app/Models/OrderVaccine.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-2
+ * Time: 下午11:44
+ */
+
+namespace App\Models;
+
+class OrderVaccine extends BaseModel
+{
+
+}

+ 21 - 0
app/Models/Organization.php

xqd
@@ -0,0 +1,21 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-29
+ * Time: 下午2:35
+ */
+
+namespace App\Models;
+
+class Organization extends BaseModel
+{
+    public function docter()
+    {
+        return $this->belongsToMany(Docter::class);
+    }
+
+    public function offices(){
+        return $this->hasMany(Office::class,'org_id','id');
+    }
+}

+ 15 - 0
app/Models/Patient.php

xqd
@@ -0,0 +1,15 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-1
+ * Time: 上午12:10
+ */
+
+namespace App\Models;
+
+class Patient extends BaseModel
+{
+    protected $table="patients";
+
+}

+ 14 - 0
app/Models/Payment.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-1
+ * Time: 上午12:43
+ */
+
+namespace App\Models;
+
+class Payment extends BaseModel
+{
+
+}

+ 14 - 0
app/Models/Qualification.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午2:20
+ */
+
+namespace App\Models;
+
+class Qualification extends BaseModel
+{
+
+}

+ 17 - 0
app/Models/Schedule.php

xqd
@@ -0,0 +1,17 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午2:47
+ */
+
+namespace App\Models;
+
+class Schedule extends BaseModel
+{
+    public function schedulePeriod()
+    {
+        return $this->hasMany(SchedulePeriod::class);
+    }
+}

+ 23 - 0
app/Models/SchedulePeriod.php

xqd
@@ -0,0 +1,23 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午2:51
+ */
+
+namespace App\Models;
+
+class SchedulePeriod extends BaseModel
+{
+    public function organization()
+    {
+        return $this->belongsTo(Organization::class);
+    }
+
+    public function timePeriod()
+    {
+        return $this->belongsTo(TimePeriod::class)->select(['id', 'start_time_period', 'end_time_period']);
+    }
+
+}

+ 15 - 0
app/Models/SelfSchedule.php

xqd
@@ -0,0 +1,15 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-1
+ * Time: 上午12:10
+ */
+
+namespace App\Models;
+
+class SelfSchedule extends BaseModel
+{
+    protected $table="self_schedule";
+
+}

+ 15 - 0
app/Models/ServiceApply.php

xqd
@@ -0,0 +1,15 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: lyh
+ * Date: 20-10-4
+ * Time: 下午7:11
+ */
+
+namespace App\Models;
+
+class ServiceApply extends BaseModel
+{
+    protected $table='service_applys';
+    public $timestamps = true;
+}

+ 17 - 0
app/Models/ServicePack.php

xqd
@@ -0,0 +1,17 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-4
+ * Time: 下午7:11
+ */
+
+namespace App\Models;
+
+class ServicePack extends BaseModel
+{
+    public function team()
+    {
+        return $this->belongsTo(Team::class);
+    }
+}

+ 46 - 0
app/Models/Suggest.php

xqd
@@ -0,0 +1,46 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 上午11:31
+ */
+
+namespace App\Models;
+
+class Suggest extends BaseModel
+{
+
+
+    public function order()
+    {
+        return $this->belongsTo(Order::class);
+    }
+
+    /**
+     * 患者表联查
+     * @return mixed
+     */
+    public function Patient()
+    {
+        return $this->hasOne(Patient::class,'id','patient_id');
+    }
+
+    /**
+     * 意见详情表联查
+     * @return mixed
+     */
+    public function details()
+    {
+        return $this->hasMany(SuggestDetail::class,'suggest_id','id');
+    }
+
+    /**
+     * 获取用户信息
+     * @return mixed
+     */
+    public function user()
+    {
+        return $this->hasOne(User::class,'id','user_id');
+    }
+}

+ 16 - 0
app/Models/SuggestDetail.php

xqd
@@ -0,0 +1,16 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 上午11:31
+ */
+
+namespace App\Models;
+
+class SuggestDetail extends BaseModel
+{
+    protected $table='suggests_detail';
+    public $timestamps = true;
+
+}

+ 16 - 0
app/Models/SystemConfig.php

xqd
@@ -0,0 +1,16 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 上午11:31
+ */
+
+namespace App\Models;
+
+class SystemConfig extends BaseModel
+{
+    protected $table='system_config';
+
+
+}

+ 17 - 0
app/Models/Team.php

xqd
@@ -0,0 +1,17 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-4
+ * Time: 下午10:09
+ */
+
+namespace App\Models;
+
+class Team extends BaseModel
+{
+    public function docter()
+    {
+        return $this->belongsToMany(Docter::class, 'team_docters');
+    }
+}

+ 14 - 0
app/Models/TimePeriod.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午4:32
+ */
+
+namespace App\Models;
+
+class TimePeriod extends BaseModel
+{
+
+}

+ 100 - 0
app/Models/User.php

xqd
@@ -0,0 +1,100 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-23
+ * Time: 上午11:04
+ */
+
+namespace App\Models;
+
+class User extends BaseModel
+{
+    protected $table = 'users';
+
+    public function patients()
+    {
+        return $this->hasMany(Patient::class);
+    }
+
+    public function order()
+    {
+        return $this->hasMany(Order::class);
+    }
+    //通过token获取用户信息
+    public static function getUserByToken()
+    {
+        $auth = request()->header('token');
+        if (empty($auth)) {
+            exit_out(null, 401, '认证失效,请重新登录');
+        }
+
+        $arr = aes_decrypt($auth);
+        if (isset($arr['doctor_id'])){
+            // 说明是医生登陆!
+            if (empty($arr['doctor_id'])) {
+                exit_out(null, 401, '认证失效,请重新登录');
+            }
+
+            $user = Docter::where('id', $arr['doctor_id'])->first();
+            if (empty($user)){
+                exit_out(null, 601, '该账号已被删除');
+            }
+            $user = $user->toArray();
+//            if ($user['status'] == 0){
+//                exit_out(null, 602, '该账号已被冻结');
+//            }
+
+            return $user;
+
+        }else{
+            if (empty($arr['id'])) {
+                exit_out(null, 401, '认证失效,请重新登录');
+            }
+
+            $user = User::where('id', $arr['id'])->first();
+            if (empty($user)){
+                exit_out(null, 601, '该账号已被删除');
+            }
+            $user = $user->toArray();
+
+            if ($user['status'] == 0){
+                exit_out(null, 602, '该账号已被冻结');
+            }
+
+            return $user;
+        }
+
+    }
+
+    /**
+     * 用户医生关注表
+     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
+     * @author Liu-Yh
+     * Create By 2020/11/18 11:06
+     */
+    public function userDorter(){
+        return $this->hasOne(UserDocter::class,'user_id','id')->select(['id', 'remark']);;
+    }
+
+    //改变用户余额
+    public static function changeBalance($user_id, $change_balance, $type, $relation_id, $remark, $admin_user_id = 0)
+    {
+        $user = User::select(['balance'])->where('id', $user_id)->first();
+
+        User::where('id', $user_id)->increment('balance', $change_balance);
+
+        UserBalanceLog::create([
+            'user_id' => $user_id,
+            'admin_user_id' => $admin_user_id,
+            'type' => $type,
+            'relation_id' => $relation_id,
+            'before_balance' => $user['balance'],
+            'change_balance' => $change_balance,
+            'after_balance' => $user['balance'] + $change_balance,
+            'remark' => $remark,
+        ]);
+
+        return true;
+    }
+}

+ 14 - 0
app/Models/UserBalanceLog.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午12:04
+ */
+
+namespace App\Models;
+
+class UserBalanceLog extends BaseModel
+{
+
+}

+ 56 - 0
app/Models/UserCoupon.php

xqd
@@ -0,0 +1,56 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午11:25
+ */
+
+namespace App\Models;
+
+class UserCoupon extends BaseModel
+{
+    public static function getDiscountAmount($id, $user_id, $total_amount, $product_type)
+    {
+        $userCoupon = self::where('id', $id)->where('user_id', $user_id)->first();
+        if (empty($userCoupon)) {
+            exit_out(null, 10001, '用户优惠券不存在');
+        }
+        if ($userCoupon['status'] == 2) {
+            exit_out(null, 10002, '该优惠券已被使用,请勿重复使用');
+        }
+        if ($userCoupon['status'] == 3) {
+            exit_out(null, 10003, '该优惠券已过期');
+        }
+        if ($userCoupon['status'] == 1) {
+            if ($userCoupon['expire_type'] == 1) {
+                $expire_time = strtotime($userCoupon['created_at']) + $userCoupon['effective_days']*24*3600;
+            }
+            else {
+                $expire_time = $userCoupon['end_time'];
+            }
+            if ($expire_time < time()) {
+                self::where('id', $id)->update(['status' => 3]);
+                exit_out(null, 10004, '该优惠券已过期');
+            }
+
+            if ($userCoupon['min_consume_amount'] > $total_amount) {
+                exit_out(null, 10005, '未达到该优惠券的最低消费金额');
+            }
+
+            if ($userCoupon['usable_type'] == 2 && !CouponType::where('user_coupon_id', $id)->where('product_type', $product_type)->count()) {
+                exit_out(null, 10006, '该优惠券不支持该类型的订单');
+            }
+        }
+
+        if ($userCoupon['type'] == 1) {
+            $discountAmount = $userCoupon['money'];
+        }
+        else {
+            $discountAmount = floor((1 - $userCoupon['discount']/10)*$total_amount);
+            $discountAmount = $userCoupon['max_reduce_amount'] < $discountAmount ? $userCoupon['max_reduce_amount'] : $discountAmount;
+        }
+
+        return $discountAmount;
+    }
+}

+ 15 - 0
app/Models/UserDocter.php

xqd
@@ -0,0 +1,15 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-9-30
+ * Time: 下午11:25
+ */
+
+namespace App\Models;
+
+class UserDocter extends BaseModel
+{
+    protected $table='user_docter';
+    public $timestamps = true;
+}

+ 14 - 0
app/Models/UserMessages.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-5
+ * Time: 下午12:04
+ */
+
+namespace App\Models;
+
+class UserMessages extends BaseModel
+{
+
+}

+ 14 - 0
app/Models/Vaccine.php

xqd
@@ -0,0 +1,14 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-4
+ * Time: 下午3:24
+ */
+
+namespace App\Models;
+
+class Vaccine extends BaseModel
+{
+
+}

+ 18 - 0
app/Models/WeekSchedule.php

xqd
@@ -0,0 +1,18 @@
+<?php
+/**
+ * Created by PhpStorm.
+ * User: zilongs
+ * Date: 20-10-1
+ * Time: 上午12:10
+ */
+
+namespace App\Models;
+
+class WeekSchedule extends BaseModel
+{
+    protected $table="week_schedule";
+    public function organization()
+    {
+        return $this->belongsTo(Organization::class);
+    }
+}

+ 28 - 0
app/Providers/AppServiceProvider.php

xqd
@@ -0,0 +1,28 @@
+<?php
+
+namespace App\Providers;
+
+use Illuminate\Support\ServiceProvider;
+
+class AppServiceProvider extends ServiceProvider
+{
+    /**
+     * Register any application services.
+     *
+     * @return void
+     */
+    public function register()
+    {
+        //
+    }
+
+    /**
+     * Bootstrap any application services.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        //
+    }
+}

+ 30 - 0
app/Providers/AuthServiceProvider.php

xqd
@@ -0,0 +1,30 @@
+<?php
+
+namespace App\Providers;
+
+use Illuminate\Support\Facades\Gate;
+use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
+
+class AuthServiceProvider extends ServiceProvider
+{
+    /**
+     * The policy mappings for the application.
+     *
+     * @var array
+     */
+    protected $policies = [
+        // 'App\Model' => 'App\Policies\ModelPolicy',
+    ];
+
+    /**
+     * Register any authentication / authorization services.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        $this->registerPolicies();
+
+        //
+    }
+}

+ 21 - 0
app/Providers/BroadcastServiceProvider.php

xqd
@@ -0,0 +1,21 @@
+<?php
+
+namespace App\Providers;
+
+use Illuminate\Support\ServiceProvider;
+use Illuminate\Support\Facades\Broadcast;
+
+class BroadcastServiceProvider extends ServiceProvider
+{
+    /**
+     * Bootstrap any application services.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        Broadcast::routes();
+
+        require base_path('routes/channels.php');
+    }
+}

+ 34 - 0
app/Providers/EventServiceProvider.php

xqd
@@ -0,0 +1,34 @@
+<?php
+
+namespace App\Providers;
+
+use Illuminate\Support\Facades\Event;
+use Illuminate\Auth\Events\Registered;
+use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
+use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
+
+class EventServiceProvider extends ServiceProvider
+{
+    /**
+     * The event listener mappings for the application.
+     *
+     * @var array
+     */
+    protected $listen = [
+        Registered::class => [
+            SendEmailVerificationNotification::class,
+        ],
+    ];
+
+    /**
+     * Register any events for your application.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        parent::boot();
+
+        //
+    }
+}

+ 73 - 0
app/Providers/RouteServiceProvider.php

xqd
@@ -0,0 +1,73 @@
+<?php
+
+namespace App\Providers;
+
+use Illuminate\Support\Facades\Route;
+use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
+
+class RouteServiceProvider extends ServiceProvider
+{
+    /**
+     * This namespace is applied to your controller routes.
+     *
+     * In addition, it is set as the URL generator's root namespace.
+     *
+     * @var string
+     */
+    protected $namespace = 'App\Http\Controllers';
+
+    /**
+     * Define your route model bindings, pattern filters, etc.
+     *
+     * @return void
+     */
+    public function boot()
+    {
+        //
+
+        parent::boot();
+    }
+
+    /**
+     * Define the routes for the application.
+     *
+     * @return void
+     */
+    public function map()
+    {
+        $this->mapApiRoutes();
+
+        $this->mapWebRoutes();
+
+        //
+    }
+
+    /**
+     * Define the "web" routes for the application.
+     *
+     * These routes all receive session state, CSRF protection, etc.
+     *
+     * @return void
+     */
+    protected function mapWebRoutes()
+    {
+        Route::middleware('web')
+             ->namespace($this->namespace)
+             ->group(base_path('routes/web.php'));
+    }
+
+    /**
+     * Define the "api" routes for the application.
+     *
+     * These routes are typically stateless.
+     *
+     * @return void
+     */
+    protected function mapApiRoutes()
+    {
+        Route::prefix('api')
+             ->middleware('api')
+             ->namespace($this->namespace)
+             ->group(base_path('routes/api.php'));
+    }
+}

+ 39 - 0
app/User.php

xqd
@@ -0,0 +1,39 @@
+<?php
+
+namespace App;
+
+use Illuminate\Notifications\Notifiable;
+use Illuminate\Contracts\Auth\MustVerifyEmail;
+use Illuminate\Foundation\Auth\User as Authenticatable;
+
+class User extends Authenticatable
+{
+    use Notifiable;
+
+    /**
+     * The attributes that are mass assignable.
+     *
+     * @var array
+     */
+    protected $fillable = [
+        'name', 'email', 'password',
+    ];
+
+    /**
+     * The attributes that should be hidden for arrays.
+     *
+     * @var array
+     */
+    protected $hidden = [
+        'password', 'remember_token',
+    ];
+
+    /**
+     * The attributes that should be cast to native types.
+     *
+     * @var array
+     */
+    protected $casts = [
+        'email_verified_at' => 'datetime',
+    ];
+}