BaseService.php 37.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
<?php
/**
 +----------------------------------------------------------------------------------------------------------------------
 * 逻辑层:逻辑处理基类
 +----------------------------------------------------------------------------------------------------------------------
 *
 * PHP version 7
 *
 * @category  App\Services
 * @package   App\Services
 * @author    Richer <yangzi1028@163.com>
 * @date      2019年10月10日,18:31:22
 * @copyright 2021-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
namespace App\Services;

use App\Factories\OrderFactory;
use App\Models\Traits\AdminUserTrait;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Closure;
use Exception;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use App\Models\Traits\AdministrativeDivisionTrait;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;

/**
 * Class BaseService
 *
 * @category  App\Services
 * @package   App\Services
 * @author    Richer <yangzi1028@163.com>
 * @date      2020年12月25日11:01:11
 * @copyright 2021-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
class BaseService
{
     use AdministrativeDivisionTrait, AdminUserTrait;


    /**
     * Model 实例
     *
     * @var model
     */
    protected $model;

    /**
     * Validator 层实例
     *
     * @var \Validator
     */
    protected $validator;

    const NO_DATA = '暂无相关数据!';

    /**
     * 模型操作返回的提示信息
     *
     * @var \String
     */
    public $message  = '';

    /**
     * 操作的用户ID
     *
     * @var \Int
     */
    protected $loginUserId;

    /**
     * 操作的用户手机号
     *
     * @var \String
     */
    protected $loginUserMobile;

    /**
     * 操作的用户用户名
     *
     * @var \String
     */
    protected $loginUserName;

    /**
     * 操作的用户信息
     *
     * @var \Arr
     */
    protected $loginUserInfo;

    /**
     * 列表需要查询的用户字段
     *
     * @var \String
     */
    const AUTHOR_LIST_COLUMNS = ['id','mobile','username','nickname','avatar'];

    /**
     * BaseService constructor.
     *
     * @param Model     $model     model
     * @param \Validator $validator validator
     */
    public function __construct($model = null, $validator = null)
    {
        $this->model        = $model;
        $this->validator    = $validator;
    }

    /**
     * 获取返回的提示信息
     *
     * @return String
     */
    public function getMessage()
    {
        return $this->message ? : __('operate_failed');
    }

    /**
     * 获取登录用户信息
     *
     * @return \Illuminate\Contracts\Auth\Authenticatable|mixed
     */
    public function getLoginUser()
    {
        return $this->loginUserInfo = auth('user')->user() ?? request()->user;

        if (is_admin()) {
            return $this->loginUserInfo = \Auth::guard('api_admin')->authenticate() ?? request()->user;
        } else {
            return $this->loginUserInfo = auth('user')->user() ?? request()->user;
        }
    }
    /**
     * 获取登录用户id
     *
     * @return int
     */
    public function getLoginUserId()
    {
        $user = self::getLoginUser();
        if ($user) {
            return $this->loginUserId   = $user->id;
        }

        return 0;
    }

    /**
     * 获取登录用户手机号
     *
     * @return string
     */
    public function getLoginUserMobile()
    {
        return $this ->loginUserMobile = self::getLoginUser()->mobile;
    }

    /**
     * 获取登录用户用户名
     *
     * @return string
     */
    public function getLoginUserName()
    {
        return $this ->loginUserName = self::getLoginUser()->username;
    }

    /**
     * Retrieve data array for populate field select
     *
     * @param string $column $column
     * @param string $key    $key
     *
     * @return \Illuminate\Support\Collection|array
     */
    public function lists($column, $key = null)
    {
        return $this->model->lists($column, $key);
    }

    /**
     * Retrieve data array for populate field select
     * Compatible with Laravel 5.3
     *
     * @param string $column $column
     * @param string $key    $key
     *
     * @return \Illuminate\Support\Collection|array
     */
    public function pluck($column, $key = null)
    {
        return $this->model->pluck($column, $key);
    }

    /**
     * Sync relations
     *
     * @param integer  $id         主键id
     * @param Relation $relation   关联模型
     * @param array    $attributes 参数
     * @param bool     $detaching  $detaching
     *
     * @return mixed
     */
    public function sync($id, $relation, $attributes, $detaching = true)
    {
        return $this->find($id)->{$relation}()->sync($attributes, $detaching);
    }

    /**
     * Display a listing of the resource.
     *
     * @param array   $columns 查询字段
     * @param array   $where   查询条件
     * @param string  $orders  排序
     * @param integer $limit   每页数量
     * @param string  $method  分页方法
     *
     * @return \Illuminate\Support\Collection|array
     */
    public function index($columns = ['*'], $where = [], $orders = '', $limit = 0, $method = "paginate")
    {

        // 设置默认的查询字段
        if ($columns == ['*']) {
            $columns = $this->model::LIST_QUERY_COLUMNS;
        }

        // 设置查询条件
        $this->applyConditions($where);
        // 设置默认分页参数
        $limit = !$limit ? request('per_page') : $limit;
        // 设置排序字段
        $this->setOrderBy($orders);
        $results = $this->model->{$method}($limit, $columns);
        //$results->appends(app('request')->query());
        // 未获取到数据不进行转换
        if ($results->total() == 0) {
            return $results;
        }
        return $this->parserResult($results);
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Support\Collection|array
     */
    public function list()
    {
        return $this->index();
    }

    /**
     * Retrieve all data of repository
     *
     * @param array  $columns 查询字段
     * @param array  $where   查询条件
     * @param string $orders  排序
     *
     * @return \Illuminate\Support\Collection|array
     */
    public function all($columns = ['*'], $where = [], $orders = '')
    {
        // 设置查询条件
        $this->applyConditions($where);
        // 设置排序字段
        $this->setOrderBy($orders);
        $results = null;
        if ($this->model instanceof Builder) {
            $results = $this->model->get($columns);
        } else {
            $results = $this->model->all($columns);
        }
        return $this->parserResult($results);
    }

    /**
     * Retrieve top N data of repository
     * 获取repository存储库的前N个数据
     *
     * @param Request $request $request
     * @param array   $columns 查询字段
     * @param string  $orders  排序
     *
     * @return \Illuminate\Support\Collection|array
     */
    public function top($request, $columns = ['*'], $orders = '')
    {
        $latest = $request->latest;
        $take = $request->take ? : 10;
        $this->setOrderBy($orders);// 设置排序
        if ($latest == 'true') {
            $this->model->latest();
        }
        $results = $this->model->take($take)->get($columns);
        return $this->parserResult($results);
    }

    /**
     * 获取 options
     *
     *
     * @param string $field_value
     * @param string $field_caption
     * @return \Illuminate\Support\Collection|array
     */
    public function options($field_value = 'id', $field_caption = 'name')
    {
        $collection = $this->model->when($q = \request('q'), function ($query) use ($field_caption, $q) {
            $query->where("$field_caption", 'like', "%$q%");
        })->latest()->get([$field_value, $field_caption])->map(function ($item) use ($field_caption, $field_value)  {
            return [$item->$field_value => $item->$field_caption];
        });

        return  $collection;
    }

    /**
     * Retrieve first data of repository
     *
     * @param array  $columns 字段
     * @param array  $where   查询条件
     * @param string $orders  排序
     *
     * @return \Illuminate\Support\Collection|array
     */
    public function first($columns = ['*'], $where = [], $orders = '')
    {
        // 设置查询条件
        $this->applyConditions($where);
        // 设置排序字段
        $this->setOrderBy($orders);
        $results = $this->model->first($columns);
        return $this->parserResult($results);
    }

    /**
     * Retrieve first data of repository, or return new Entity
     *
     * @param array $attributes $attributes
     *
     * @return mixed
     */
    public function firstOrNew(array $attributes = [])
    {
        $model = $this->model->firstOrNew($attributes);
        return $this->parserResult($model);
    }

    /**
     * Retrieve first data of repository, or create new Entity
     *
     * @param array $attributes $attributes
     *
     * @return mixed
     */
    public function firstOrCreate(array $attributes = [])
    {
        $model = $this->model->firstOrCreate($attributes);
        return $this->parserResult($model);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param Request $request $request
     *
     * @return Response
     *
     * @throws ModelNotFoundException
     */
    public function create($request)
    {
        $model = $this->model->newInstance($request->all());
        // 数据进行清理和处理
        $model = $this->prepareStore($model);
        $model->save();
        return $this->parserResult($model);
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  Request $request
     *
     * @return bool|\Illuminate\Http\Response
     */
    public function store($request)
    {
        $result =  $this->create($request);

        if ($result == false) {
            return false;
        }

        return $result;
    }

    /**
     * Store the relation resource in storage.
     *
     * @param Request $request $request
     *
     * @return Response
     */
    public function storeRelation($request)
    {
        $data = $this->model->storeRelation($request);
        return $data;
    }

    /**
     * Display the specified resource.
     *
     * @param int   $id      主键id
     * @param array $columns 列
     *
     * @return array|bool|\Illuminate\Support\Collection
     */
    public function show($id, $columns = ['*'])
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id, $columns);

            // add by Richer 于 2020年9月27日16:49:40 增加标识判断是 详情 的操作
//            $model->function = 'show';
            // add by Richer 于2022年5月11日17:22:21 增加标识判断是 详情 的操作
            request()->offsetSet('function', 'show');

            // 执行资源点击事件,将资源的点击量增加一
            event(new \App\Events\IncreaseViews($id, $model));

            return $this->parserResult($model);
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * Display the specified resource.
     *
     * @param int   $id       主键id
     * @param array $columns  列
     * @param array $relation 关联
     *
     * @return Response
     */
    public function showRelation($id, $columns = ['*'], $relation = [])
    {
        $data = $this->model->findRelation($id, $columns, $relation);
        return $data;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id 主键id
     *
     * @return bool
     */
    public function edit($id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);

            // 通过 Policy 策略来判断是否有修改的权限
            $can = $this->getLoginUser()->can('update', $model);
            if ($can === false) {
                $this->message = __('cannot_edit_data');
                return false;
            }

            return $this->parserResult($model);
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request $request
     * @param string  $id      主键id
     *
     * @return Response|bool
     *
     * @throws ModelNotFoundException
     */
    public function update($request, $id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);

            // 当前的审核状态
            $old_status = $model->audited_status;

            // 通过 Policy 策略来判断是否有修改的权限
            // TODO add by Richer 于 2022-3-4 17:07:142 去掉 验证
//            $can = $this->getLoginUser()->can('update', $model);
//            if ($can === false) {
//                $this->message = __('cannot_edit_data');
//                return false;
//            }

            // 审核状态为不通过,编辑后变更为待审核
            if ($old_status == config('constants.AUDIT_NOT_PASSED')) {
                // 编辑后变为待审核
                $request['audited_status'] = config('constants.UNAUDITED');
            }

            // 设置可以批量赋值的字段
            $model->fill($request->all());

            // 数据进行清理和处理
            $model = $this->prepareStore($model);

            // 直接返回操作结果
            $model->save();

            if ($old_status == config('constants.AUDIT_NOT_PASSED')) {
                // 判断当前的状态是否是由不通过到待审核,如果是则说明该审核退回后,用户再次进行提交
                // 执行事件给对象发送消息
//                event(new \App\Events\ResubmitAudit($model));
            }

            return $model;
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param Request $request request
     * @param string  $id
     *
     * @return Response
     *
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */

    // public function updateRelation($request, $id = null)
    // {
    //     $data = $this->model->updateRelation($request->all(), $id);

    //     return $data;
    // }

    /**
     * 根据Id批量更新数据,可以放在model里面,使得每个model都是调用这个方法
     *
     * @param array $multipleData 数据
     *
     * @return bool
     * @throws \Illuminate\Validation\ValidationException
     * @author Richer
     */
    public function updateBatch($multipleData = array())
    {
        $tableName = $this->model->getTable();
        if (!is_array($multipleData)) {
            throw new \Illuminate\Validation\ValidationException('must be an array', null, '6001');
        }

        foreach ($multipleData as &$row) {
            if (!array_key_exists('id', $row)) {
                throw new \Illuminate\Validation\ValidationException('参数错误,缺少主键', null, '6001');
            }
            //$row[Model::FIELD_UPDATED_AT] = Carbon::now();
        }

        if ($tableName && !empty($multipleData)) {
            $updateColumn  = array_keys(\Arr::first($multipleData));
            $referenceColumn = \Arr::first($updateColumn);
            unset($updateColumn[0]);
            $whereIn = "";
            $q = "UPDATE " . $tableName . " SET ";
            foreach ($updateColumn as $uColumn) {
                $q .= $uColumn . " = CASE ";
                foreach ($multipleData as $data) {
                    $q .= "WHEN " . $referenceColumn . " = " . $data[$referenceColumn] . " THEN '" . $data[$uColumn] . "' ";
                }
                $q .= "ELSE " . $uColumn . " END, ";
            }
            foreach ($multipleData as $data) {
                $whereIn .= "'" . $data[$referenceColumn] . "', ";
            }

            $q = rtrim($q, ", ") . " WHERE " . $referenceColumn . " IN (" . rtrim($whereIn, ', ') . ")";

            return \DB::update(\DB::raw($q));
        } else {
            return false;
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param integer $id          主键
     * @param boolean $forceDelete 是否强制物理删除
     *
     * @return bool|Response
     */
    public function destroy($id, $forceDelete = false)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);

            // 通过 Policy 策略来判断是否有删除的权限
            $can = $this->getLoginUser()->can('delete', $model);
            if ($can === false) {
                $this->message = '您无法删除当前数据!';
                return false;
            }

            //$originalModel = clone $model;

            $deleted = false;
            if ($forceDelete === true) {
                $deleted = $model->forceDelete();
            } else {
                $deleted = $model->delete();
            }
            return $deleted;
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * Delete multiple entities by given criteria.
     *
     * @param array $where 查询条件
     *
     * @return int
     * @throws Exception
     */
    public function deleteWhere(array $where)
    {
        $this->applyConditions($where);
        $deleted = $this->model->delete();
        return $deleted;
    }

    /**
     * Check if entity has relation
     *
     * @param string $relation 关联
     *
     * @return $this
     */
    public function has($relation)
    {
        $this->model = $this->model->has($relation);
        return $this;
    }

    /**
     * Load relations
     *
     * @param array|string $relations 关联
     *
     * @return $this
     */
    public function with($relations)
    {
        $this->model = $this->model->with($relations);
        return $this;
    }

    /**
     * Add subselect queries to count the relations.
     *
     * @param mixed $relations 关联
     *
     * @return $this
     */
    public function withCount($relations)
    {
        $this->model = $this->model->withCount($relations);
        return $this;
    }

    /**
     * Load relation with closure
     *
     * @param string  $relation $relation
     * @param closure $closure  $closure
     *
     * @return $this
     */
    public function whereHas($relation, $closure)
    {
        $this->model = $this->model->whereHas($relation, $closure);
        return $this;
    }

    /**
     * Set hidden fields
     *
     * @param array $fields $fields
     *
     * @return $this
     */
    public function hidden(array $fields)
    {
        $this->model->setHidden($fields);
        return $this;
    }

    /**
     * Wrapper result data
     *
     * @param mixed $result $result
     *
     * @return mixed
     */
    public function parserResult($result)
    {
        // 数据转换
        /*if ($this->transformer instanceof TransformerAbstract) {

            if ($result instanceof Collection) {

                $list =[];
                foreach ($result as $value) {
                    if ($value instanceof Model) {
                        $list[] = $this->transformer->transform($value);
                    }
                }
                return $list;

            } elseif ($result instanceof LengthAwarePaginator) {

                // $result->each(function ($model) {

                //     if ($model instanceof Model) {
                //         $list[] = $this->transformer->transform($model);
                //     }

                //     return $list;
                // });
                $list =[];
                foreach ($result as $value) {
                    if ($value instanceof Model) {
                        $list[] = $this->transformer->transform($value);
                    }
                }

                $result->data = $list;
                return $result;
            } elseif ($result instanceof Model) {
                $result = $this->transformer->transform($result);
            }
        }*/
        return $result;
    }

    /**
     * 搜索功能:基类方法只组合关键字查询条件。如果需要组合其他条件,请在子类中重写
     *
     * @param array  $where   自定义查询条件
     * @param array  $columns 自定义查询字段
     * @param string $orders  自定义排序字段,逗号分隔:id desc,created_at
     * @param int    $limit   自定义分页参数
     *
     * @return array             结果集
     */
    public function search($where = [], $columns = ['*'], $orders = '', $limit = 0)
    {
        $where[] = ['id','>','0'];
        // 获取搜索关键字
        request('kw') &&  $where[] = ['title','like','%' . request('kw') . '%'];
        $list = $this->model->paginate($where, $columns, $orders, $limit);
        return $list;
    }

    /**
     * Get the configs.
     *
     * @param Request $request request
     *
     * @return array
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function configs($request)
    {
        $options = \App\Models\System\Config::getConfigByKey($this->model->getConfigOpions());
        return $options;
    }

    /**
     * 评论:根据目标对象的评论一个对象,并进行系统消息提醒
     *
     * @param Request $request $request
     * @param integer $id      目标对象的主键
     *
     * @return mix|bool
     */
    public function comment($request, $id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);
            // 评论对象
            $comment = $model->comment($request->comment);

            // 判断结果,评论成功,进行系统消息通知和消息推送
            if ($comment) {
                // To approve a single comment
                $comment->approve();

                // 获取全部的评论。并更新表中字段
                $this->model->where('id', $id)->increment("comments_count");// 自增1

                // 通知用户评论:根据不同的对象实例不同的通知类
//                \App\Models\User\User::find($model->user_id)->notify(\App\Notifications\CommentNotification::getInstance($model));
            }
            return $comment ;
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * 获取评论的列表,按照特地的排序规则
     *
     * @param integer $id 目标对象的主键
     *
     * @return mix|bool
     */
    public function comments($id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);
            return $comments = $model->comments()
                ->with('commentator')
                ->orderByRaw('votes_count desc, favorites_count desc')
                ->latest()
                ->paginate(request('per_page', config('constants.PER_PAGE')));
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * 点赞投票:根据目标对象的点赞投票一个对象
     *
     * @param integer $id 目标对象的主键
     *
     * @return mix|bool
     */
    public function vote($id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model  = $this->model->findOrFail($id);
            $user   = $this->getLoginUser();

            // 点赞
            $result = $user->vote($model);
            // 验证结果
            if ($result) {
                // 获取全部的收藏量。并更新表中字段
                $model->votes_count = $model->voters()->get()->count();
                $model->save();
            }
            return $result ;
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * 取消点赞投票:根据目标对象的取消点赞一个对象
     *
     * @param integer $id 目标对象的主键
     *
     * @return mix|bool
     */
    public function unvote($id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);
            $user = $this->getLoginUser();

            // 判断用户是否点赞,如果点赞了才
            $hasUpvoted = $user->hasUpvoted($model);
            if (!$hasUpvoted) {
                $this->message = __('do_not_repeat_the_operation');//$e->getMessage();
                return false;
            }

            // 取消点赞
            $result = $user->cancelVote($model);
            // 验证结果
            if ($result) {
                // 获取全部的收藏量。并更新表中字段
                $model->votes_count = $model->voters()->get()->count();
                $model->save();
            }
            return $result ;
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * 收藏:根据目标对象的主键收藏一个对象
     *
     * @param integer $id 目标对象的主键
     *
     * @return mix|bool
     */
    public function favorite($id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);
            $user   = $this->getLoginUser();

            // 是否已经收藏了
            if ($model->isFavoritedBy($user)) {
                $this->message = '您已经收藏了,请勿重复操作!';
                return false;
            }

            // 收藏对象
            $result = $user->favorite($model);

            // 验证结果
            if ($result) {
                $model->favorites_count = $model->favoriters()->count();
                $model->save();
            }

            return $result;
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * 取消点赞投票:根据目标对象的取消点赞一个对象
     *
     * @param integer $id 目标对象的主键
     *
     * @return mix|bool
     */
    public function unfavorite($id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);
            $user = $this->getLoginUser();

            // 判断用户是否收藏,如果收藏了才继续
            $hasFavorited = $user->hasFavorited($model);
            if (!$hasFavorited) {
                $this->message = __('您还未收藏,无法取消!');//$e->getMessage();
                return false;
            }
            // 取消收藏
            $result = $user->unfavorite($model);
            // 验证结果
            if ($result) {
                // 获取全部的收藏量。并更新表中字段
                $model->favorites_count = $model->favoriters()->count();
                $model->save();
            }
            return $result ;
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * 喜欢:根据目标对象的主键喜欢一个对象
     *
     * @param integer $id 目标对象的主键
     *
     * @return bool
     */
    public function like($id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);

            $user = $this->getLoginUser();

            return $result = $user->like($model); // Vote with 'upvote' for default;
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * 取消点赞投票:根据目标对象的取消点赞一个对象
     *
     * @param integer $id 目标对象的主键
     *
     * @return bool
     */
    public function unlike($id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);

            $user = $this->getLoginUser();

            // 判断用户是否收藏,如果收藏了才继续
            $hasLiked = $user->hasLiked($model);

            if (!$hasLiked) {
                $this->message = __('do_not_repeat_the_operation');//$e->getMessage();
                return false;
            }
            return $result = $user->unlike($model);
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * 举报:根据目标对象的report一个对象,并进行系统消息提醒
     *
     * @param Request $request $request
     * @param integer $id      目标对象的主键
     *
     * @return bool
     */
    public function report($request, $id)
    {
        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);

            $func = 'reports';
            // 判断是否存在方法,不存在退出
            if (!method_exists($model, $func)) {
                $this->message = '该数据暂时无法举报!';
                return false;
            }

            // 判断用户是否可以举报
            // 当前操作用户
            $user = $this->getLoginUser();
            if (!method_exists($user, 'report')) {
                $this->message = '您无法举报!';
                return false;
            }

            // 举报对象
            return $result = $user->report($model);
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * 订购:根据目标对象订购 一个对象,生成订单
     *
     * @param Request $request $request
     * @param integer $id      目标对象的主键
     *
     * @return bool
     */
    public function order($request, $id)
    {
        DB::beginTransaction();
        try {
            // 获取数据,如果没有获取到抛出异常 mysql 悲观锁
            $model = $this->model->lockForUpdate()->findOrFail($id);

            $factory = app(OrderFactory::class);
            $result =  $factory->generateOrder($model, $this->getLoginUser());
            if (!$result) {
                $this->message = $factory->getMessage();
                return false;
            }
            //提交事务
            DB::commit();

            return $result;
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            DB::rollBack();
            return false;
        }

        try {
            // 获取数据,如果没有获取到抛出异常
            $model = $this->model->findOrFail($id);
            // 对应方法
            $func = 'orders';
            // 判断是否存在方法,不存在退出
            if (!method_exists($model, $func)) {
                $this->message = '该数据暂时无法订购!';
                return false;
            }

            // 当前操作用户
            $user = $this->getLoginUser();

            if (!method_exists($user, 'placeOrder')) {
                $this->message = '您无法订购!';
                return false;
            }

            $factory = app(OrderFactory::class);
            $result =  $factory->generateOrder($model, $user);
            if (!$result) {
                $this->message = $factory->getMessage();
                return false;
            }
            return $result;
        } catch (ModelNotFoundException $e) {
            $this->message = __('no_data');//$e->getMessage();
            return false;
        }
    }

    /**
     * 赠送:根据目标对象订购 一个对象,生成订单
     *
     * @param Request $request $request
     * @param integer $id      目标对象的主键
     *
     * @return bool
     */
    public function give($request, $id)
    {
        DB::beginTransaction();
        try {
            // 验证数量是否可以进行赠送
            $given_number   = $request->given_number;
            $given_quantity = $request->given_quantity;
            $quantity = $request->quantity;
            if ($quantity % ($given_number * $given_quantity) !== 0) {
                $this->message = '赠送好友人数和赠送数量 与 商品数量不匹配!';
                return false;
            }
            // 获取数据,如果没有获取到抛出异常 mysql 悲观锁
            $model = $this->model->lockForUpdate()->findOrFail($id);

            $factory = app(OrderFactory::class);
            $order =  $factory->generateOrder($model, $this->getLoginUser());
            if (!$order) {
                $this->message = $factory->getMessage();
                return false;
            }

            //提交事务
            DB::commit();

            return $order;
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            DB::rollBack();
            return false;
        }
    }

    /**
     * 设置排序
     *
     * @param string $orderBys 排序字段组合
     *
     * @return BaseService
     */
    public function setOrderBy($orderBys = '')
    {
        // 默认排序
        $orderBys = !$orderBys ? request('order') : $orderBys;
        if (!$orderBys) {
            $orderBys = 'created_at desc,id desc';
        }

        $this->model = $this->model->orderByRaw($orderBys);

        return $this;

        // 另一种方法
        $order_arr = explode(',', $orderBys);
        foreach ($order_arr as $key => $value) {
            // 再通过空格进行分割
            $temp       = explode(' ', $value);
            $column     = Arr::get($temp, 0);
            $direction  = Arr::get($temp, 1) ?? 'asc';
            $this->model = $this->model->orderBy($column, $direction);
        }

        return $this;
    }

    /**
     * 设置排序
     *
     * @param array  $column    column
     * @param string $direction $direction
     *
     * @return BaseService
     */
    public function orderBy($column, $direction = 'asc')
    {
        $this->model = $this->model->orderBy($column, $direction);
        return $this;
    }

    /**
     * Set visible fields
     *
     * @param array $fields 字段
     *
     * @return $this
     */
    public function visible(array $fields)
    {
        $this->model->setVisible($fields);
        return $this;
    }

    /**
     * Applies the given where conditions to the model.
     * 将给定的条件应用于模型。
     *
     * @param array $where 条件
     *
     * @return Model|null
     */
    protected function applyConditions(array $where)
    {
        // 设置关键词查询
        $this->model = $this->model->when($q = request('q'), function ($query) use ($q) {
            $query->where('name', 'like', '%'.$q.'%');
        });

        if (empty($where)) {
            return $this->model;
        }

        foreach ($where as $field => $value) {
            // 数组
            if (is_array($value)) {
                // add By Richer 于2019年5月28日16:50:12 增加or and 等逻辑判断
                $_logic = Arr::get($value, '_logic');
                if ($_logic && $_logic == 'or') {
                    $query      = Arr::get($value, 'query');
                    $query_1    = Arr::get($query, 0);
                    list($condition, $val) = $query_1;
                    $this->model = $this->model->where($field, $condition, $val);
                    unset($query[0]);
                    if (!empty($query)) {
                        foreach ($query as $vo) {
                            list($condition, $val) = $vo;
                            $this->model = $this->model->orWhere($field, $condition, $val);
                        }
                    }
                } else {
                    // add by Richer 于 2019年6月25日11:56:56 增加wherein
                    if (Arr::get($value, 0) == 'in') {
                        $this->model = $this->model->whereIn($field, Arr::get($value, 1));
                    } else {
                        list($field, $condition, $val) = $value;

                        $this->model = $this->model->where($field, $condition, $val);
                    }
                }
            } else {
                $this->model = $this->model->where($field, '=', $value);
            }
        }
    }

    /**
     * 对象信息新增扩展函数,便于子类继承
     *
     * @param Model $model 模型
     *
     * @return mixed 数据处理结果
     */
    public function prepareStore($model = null)
    {
        //$model->user_id    = self::getLoginUserId()?: 0;
        return $model;
    }

    /**
     * 对象信息新增扩展函数,便于子类继承,准备插入或更新的输入数据。:将数据进行清理,只获取当前模型对应的表中存在的字段
     *
     * @param Model $model 模型
     *
     * @return mixed 数据处理结果
     */
    public function prepareUpdate($model = null)
    {
        //$model->setAttribute('updated_by', self::getLoginUserId());
        //$model->updated_by    = self::getLoginUserId()?: 0;
        return $model;
    }
}