UserOrderHelper.php 38.1 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
<?php

namespace app\api\modules\user\helpers;

use Yii;
use yii\base\Object;
use common\business\CouponUseRules;
use common\business\RepairOrderPriceRule;
use common\business\SuspendOrder;
use common\business\WarrantyLevelRule;
use common\helpers\ImageManager;
use common\helpers\Log as AppLog;
use common\helpers\Utils;
use common\models\RepairOrder                   as RepairOrderModel;
use common\models\Address                       as AddressModel;
use common\models\DeductionActivity             as DeductionActivityModel;
use common\models\Engineer                      as EngineerModel;
use common\models\EngineerProfile               as EngineerProfileModel;
use common\models\GuestDevice                   as GuestDeviceModel;
use common\models\RepairOrderAppeal             as RepairOrderAppealModel;
use common\models\RepairOrderDeduction          as RepairOrderDeductionModel;
use common\models\RepairOrderDetail             as RepairOrderDetailModel;
use common\models\RepairOrderImg                as RepairOrderImgModel;
use common\models\RepairOrderRate               as RepairOrderRateModel;
use common\models\RepairOrderRepairPlans        as RepairOrderRepairPlansModel;
use common\models\RepairOrderUserCoupon         as RepairOrderUserCouponModel;
use common\models\RepairOrderUserSelectFaults   as RepairOrderUserSelectFaultsModel;
use common\models\UserCoupon                    as UserCouponModel;
use common\models\UserDevice                    as UserDeviceModel;
use domain\trade\models\RepairOrderRemoteRepairPlans as RepairOrderRemoteRepairPlansModel;
use domain\trade\RepairOrderRemoteRepairPlansStatus;
use common\services\redis\RedisConfig;
use domain\marketing\thankfee\ThankFee;
use domain\trade\RepairOrderStatus;
use domain\trade\RepairOrderRepository;
use stdClass;
use function implode;
use function in_array;
use function mb_substr;
use function json_decode;
use function json_encode;
use function sprintf;
use function date;
use function count;

/**
 * 用户订单助手类
 * Class UserOrderHelper
 * @package app\api\helpers
 */
class UserOrderHelper extends Object
{
    /**
     * @param $orderId
     */
    public static function buildRowResult($orderUUId)
    {
        $orderModel = RepairOrderModel::findOne(['uuid' => $orderUUId]);

        $orderResult = [];
        $orderResult['order_id'] = $orderModel->uuid;
        $orderResult['order_no'] = $orderModel->order_no;
        $orderResult['repair_price'] = (float)$orderModel->repair_price;
        $orderResult['pay_price'] = (float)$orderModel->pay_price;
        $orderResult['pay_no'] = $orderModel->pay_no;
        $orderResult['status'] = (int)$orderModel->status;
        $orderResult['status_label'] = RepairOrderStatus::statusLabel($orderModel->status);
        $orderResult['created_time'] = date('Y-m-d H:i', $orderModel->created_at);
        $orderResult['device_img'] = '/i/ic_device_small.jpg';
        $orderResult['repair_device_name'] = $orderModel->repair_device_name;

        // 订单是否关闭(上门后工程师或用户取消订单)
        $is_user_close = (int)$orderModel->is_user_close;
        $is_engineer_close = (int)$orderModel->is_engineer_close;
        $orderResult['is_close'] = ($is_user_close == 1 || $is_engineer_close == 1) ? true : false;

        /**
         * 工程师信息
         */
        if ($orderModel->engineer_id) {
            $engineerProfile = EngineerProfileModel::findOne(['engineer_id' => $orderModel->engineer_id]);
            $orderResult['engineer_name'] = $engineerProfile->firstname . '工';
        }

        return $orderResult;
    }

    /**
     * @param $orderId
     * @return stdClass
     */
    public static function buildDetailResult($userId, $orderUUId)
    {
        $rd = 'repair_order_detail';
        $orderQuery = RepairOrderModel::find()
            ->select(RepairOrderDetailModel::selectedFields(['repair_order.*', 'address_profile.city']))
            ->leftJoin($rd, "`repair_order`.`id` = {$rd}.repair_order_id")
            ->leftJoin('address_profile', 'address_profile.address_id = repair_order.address_id')
            ->where(['repair_order.uuid' => $orderUUId])
            ->asArray();

        $orderArray = $orderQuery->one();

        if (empty($orderArray)) {
            return false;
        }

        $orderId = $orderArray['id'];
        $order = new stdClass();
        $order->id = $orderId;
        $order->client_id = $orderArray['client_id'];
        $order->order_no = $orderArray['order_no'];
        $order->user_id = $orderArray['user_id'];
        $order->repair_price = sprintf('%0.2f', $orderArray['repair_price']);
        $order->labor_discount_price = sprintf('%0.2f', $orderArray['labor_discount_price']); // 折扣价格
        $order->discount_price = sprintf('%0.2f', $orderArray['discount_price']);
        $order->pay_price = sprintf('%0.2f', $orderArray['pay_price']);
//        $order->is_can_apply_refund = (time() - $orderArray['finish_at']) > OrderRefund::FINISH_ORDER_REFUND_EXPIRE_IN ? 0 : 1;
        $order->door_fee = sprintf('%0.2f', $orderArray['door_fee']);
        $order->city = $orderArray['city'];
        $order->is_modify_price = $orderArray['is_modify_price'];

        // 判断是否订单拥有者
        $order->is_order_owner = true;
        if ($orderArray['user_id'] != $userId) {
            $order->is_order_owner = false;
        }

        // 读取订单联系人姓名 和 联系电话
        $order->contact_name = $orderArray['contact_name'];
        $order->contact_phone = Utils::hidePhoneNumber($orderArray['contact_phone']);

        /**
         * 工程师信息
         */
        $order = self::getEngineerInfoAssignToOrder($orderArray, $order);
        /**
         * 设备及故障信息
         */
        $order->repair_device_name = $orderArray['repair_device_name'];//'惠普-激光打印机';

        // 联合查询 repair_order_user_select_faults 和 device_fault
        $user_faults = self::getFaultsAssignToOrder($order);
        $user_faults_content = '';
        if (!empty($user_faults)) {
            $user_faults_content = implode("、", $user_faults);
        }
        // 追加用户输入的其他故障问题
        if (!empty($orderArray['other_fault'])) {
            if (!empty($user_faults_content)) {
                $order->user_faults = $user_faults_content . "、" . $orderArray['other_fault'];
            } else {
                $order->user_faults = $orderArray['other_fault'];
            }
        } else {
            $order->user_faults = $user_faults_content;
        }

        // 获取维修方案
        $remotePrice = RepairOrderRemoteRepairPlansModel::findOne(["repair_order_id" => $orderId, 'status' => [RepairOrderRemoteRepairPlansStatus::STATUS_WAIT]]);
        if (!empty($remotePrice) && $orderArray["is_suspend"] == 2) {
           $order = self::getRemotePriceToOrder($order);
        } else {
            $order = self::getPlansAssignToOrder($order);
        }

        /**
         * 用户报修图片
         */
        $order->repair_order_imgs = array();
        $orderImgs = RepairOrderImgModel::find()->where(['repair_order_id' => $orderArray['id']])->orderBy('sort_order ASC')->all();
        foreach ($orderImgs as $item) {
            $orderImg = new stdClass();
            $orderImg->img_path = ImageManager::getUrl($item->img_path);
            $order->repair_order_imgs[] = $orderImg;
        }

        /**
         * 报修地址信息
         */
        $addressModel = AddressModel::findOne(['id' => $orderArray['address_id']]);
        if ($addressModel) {
            $addressD = (isset($addressModel->detail) && !empty($addressModel->detail) ? $addressModel->detail : "");
            $addressTitle = empty($addressModel->title)? $addressModel->address: $addressModel->title;
            $order->address = $addressTitle. $addressD;
            $order->longitude = sprintf('%0.6f', $addressModel->longitude);
            $order->latitude = sprintf('%0.6f', $addressModel->latitude);
        }

        /**
         * 用户评价数据
         */
        $orderRateModel = RepairOrderRateModel::findOne(['repair_order_id' => $orderId/*, 'type' => RepairOrderRate::TYPE_USER*/]); // 用户评价和系统评价都要显示
        if ($orderRateModel) {
            $order->user_speed_star = $orderRateModel->user_speed_star;
            $order->user_attitude_star = $orderRateModel->user_attitude_star;
            $order->user_skill_star = $orderRateModel->user_skill_star;
            $order->user_comment = $orderRateModel->user_comment;

            $order->has_rate = true; // 有评价数据
        } else {
            $order->has_rate = false;
        }

        $order->can_consult = false;
        /**
         * 是否存在质保申请
         */
        $orderAppealModelFind = RepairOrderAppealModel::find();
        $orderAppealModelFind->where(['repair_order_id' => $orderId, 'is_main' => 1]);
        $orderAppealModelFind->orderBy("created_at desc");
        $orderAppealModel = $orderAppealModelFind->one();
        $orderModel = RepairOrderModel::findOne($orderId);
        if ($orderAppealModel) {
            $order->appeal_id = $orderAppealModel->id;
            $order->can_appeal = true;
        } else {
            $order->appeal_id = 0; // 无质保申请
            // 能否申请质保
            $order->can_appeal = RepairOrderStatus::canAppeal($orderModel);
        }
        $order->can_consult = RepairOrderStatus::canConsult($orderModel);
        $order->can_show_appeal = RepairOrderStatus::canShowAppeal($orderModel);

        // 订单是否取消状态
        $order->is_cancel = RepairOrderStatus::isCancel($orderArray['status']);

        // 订单是否关闭(上门后工程师或用户取消订单)
        $is_user_close = (int)$orderArray['is_user_close'];
        $is_engineer_close = (int)$orderArray['is_engineer_close'];
        $order->is_close = ($is_user_close == 1 || $is_engineer_close == 1) ? true : false;
        $order->is_admin_close = (int)$orderArray['is_admin_close'];

        /**
         * 其他信息
         */
        $order->remark = $orderArray['remark'];
        //$order->pay_no = $orderArray['pay_no'];
        $order->uuid = $orderArray['uuid'];

        $order->status = (int)$orderArray['status'];
        $order->status_label = RepairOrderStatus::statusLabel($orderArray['status']);

        // 订单挂起状态
        if (RepairOrderStatus::STATUS_WAIT_ACCEPT == $order->status) {
            if ($orderArray['is_suspend'] == SuspendOrder::SUSPEND_STATUS_APPLYING) {
                $order->status_label = '挂起申请中';
            } elseif ($orderArray['is_suspend'] == SuspendOrder::SUSPEND_STATUS_SUCCESS) {
                $order->status_label = '等待再次上门';
            }
        }
        // 感谢费列表
        $order->thank_fee_list = [];
        $order->thank_fee = $orderArray['thank_fee'];
        $order->cancel_reason_label = $orderArray['cancel_reason'];
        $order->schedule_door_min = $orderArray['schedule_door_min'];
        $order->is_suspend = $orderArray['is_suspend'];
        $datetimeFormat = 'Y-m-d H:i';
        $order->pay_datetime = $orderArray['pay_at'] ? date($datetimeFormat, $orderArray['pay_at']) : '';
        $order->pick_datetime = $orderArray['pick_at'] ? date($datetimeFormat, $orderArray['pick_at']) : '';
        $order->door_datetime = $orderArray['door_at'] ? date($datetimeFormat, $orderArray['door_at']) : '';
        $order->price_datetime = $orderArray['price_at'] ? date($datetimeFormat, $orderArray['price_at']) : '';
        $order->confirm_price_datetime = $orderArray['confirm_price_at'] ? date($datetimeFormat, $orderArray['confirm_price_at']) : '';
        $order->accept_datetime = $orderArray['accept_at'] ? date($datetimeFormat, $orderArray['accept_at']) : '';
        $order->cancel_datetime = $orderArray['cancel_at'] ? date($datetimeFormat, $orderArray['cancel_at']) : '';
        //$order->close_datetime = $orderArray['close_at'] ? date($datetimeFormat, $orderArray['close_at']) : '';
        $order->rate_datetime = $orderArray['rate_at'] ? date($datetimeFormat, $orderArray['rate_at']) : '';
        $order->finish_datetime = $orderArray['finish_at'] ? date($datetimeFormat, $orderArray['finish_at']) : '';
        $order->created_datetime = $orderArray['created_at'] ? date($datetimeFormat, $orderArray['created_at']) : '';
        $order->updated_datetime = $orderArray['updated_at'] ? date($datetimeFormat, $orderArray['updated_at']) : '';
        $order->suspend_datetime = $orderArray['suspend_at'] ? date($datetimeFormat, $orderArray['suspend_at']) : '';
        $order->two_door_datetime = $orderArray['two_door_at'] ? date($datetimeFormat, $orderArray['two_door_at']) : '';

        // 是否还在最长质保周期内
        if (!RepairOrderAppealModel::checkInWarrantyCycle($orderArray['accept_at'], $orderArray['warranty_days'])) {
            $order->in_appeal_cycle = false;
        } else {
            $order->in_appeal_cycle = true;
        }

        // 超过7提前的已完成的订单不可以申请退款
        // $order->is_can_apply_refund = (time() - $order->finish_at) > OrderRefund::FINISH_ORDER_REFUND_EXPIRE_IN ? 0 : 1;

        // 合并为一个字段: conpon_show_mode:  1-隐藏 COUPON_SHOW_MODE_NONE;2-仅显示 COUPON_SHOW_MODE_DISPLAY;3-选择COUPON_SHOW_MODE_SELECT
        $order->conpon_show_mode = UserCouponModel::getUserCouponShowMode($orderArray['status']);

        // 是否显示最后维修价格
        $order->show_repair_price = (in_array($orderArray['status'], array(6, 10, 103, 104))) ? true : false;

        /**
         * 当前可用的优惠券
         */
        $order = self::getCouponsAssignToOrder($orderArray, $userId, $order);

        // 订单选择的优惠券
        $order->select_coupon_id = $orderArray["select_user_coupon_id"];
        $order->select_coupon_amount = 0;
        $order->select_coupon_name = "";
        $order->select_coupon_index = 0;
        if ($orderArray["select_user_coupon_id"]) {
            $selectCoupon = UserCouponModel::findOne($orderArray["select_user_coupon_id"]);
            if ($selectCoupon) {
                if (isset($order->coupons) && $order->coupons) {
                    foreach ($order->coupons as $key => $couponItem) {
                        if ($couponItem->id == $orderArray["select_user_coupon_id"]) {
                            $order->select_coupon_index = $key;
                        }
                    }
                }
                $order->select_coupon_amount = $selectCoupon->amount;
                $order->select_coupon_name = $selectCoupon->coupon_name;
            }
        }
        // 订单进度数据
 	    $order->progressData = RepairOrderRepository::getProgressData($order);
        // 获取抵扣金活动相关信息
        self::getDeductionActivityInfo($order, $orderArray["id"], $orderModel->status);

        return $order;
    }

    /**
     * @return array|null
     */
    private static function getThankFee($repairOrderModel)
    {
        if (false == ThankFee::OPEN) {
            return [false, [], 0];
        }
        $repairOrderStatus = $repairOrderModel->status;
        if (RepairOrderStatus::STATUS_WAIT_PICK != $repairOrderStatus){
            return [true, [], 0];
        }
        $thankFeeList = ThankFee::thankFeeSteps();
        $selectedThankFee = $repairOrderModel->thank_fee;
        $returnArr = [];
        foreach($thankFeeList as $k => $v) {
            $canSelected = false;
            if ($v['amount'] > $selectedThankFee) {
                $canSelected = true;
            }
            $item = ['id' => $v['id'], 'title' => $v['title'], 'canSelected' => $canSelected, 'amount' => $v['amount']];
            $returnArr[] = $item;
        }
        return [true, $returnArr, ThankFee::TIME_OUT_SHOW];
    }

    /**
     * 获取抵扣金活动信息
     * @param $order
     * @param $orderId
     * @param $orderStatus
     */
    private static function getDeductionActivityInfo(&$order, $orderId, $orderStatus)
    {
        // 获取订单处理进度数据
        $order->hasOrderRepairDeduction = false;
        $order->repairOrderDeduction = null;
        $order->deductionActivityFinished = true;
        $repairDeductionCheck = RepairOrderDeductionModel::findOne(['repair_order_id' => $orderId]);
        if (empty($repairDeductionCheck)) {
            return false;
        }

        $deductionActivity = DeductionActivityModel::findOne(['id' => $repairDeductionCheck->activity_id]);
        if (empty($deductionActivity)) {
            return false;
        }

        $order->top_amount = 0;
        if (isset($deductionActivity->top_amount)) {
            $order->top_amount = intval($deductionActivity->top_amount);
        }
        $order->deductionActivityFinished = (isset($deductionActivity->expired_time) && $repairDeductionCheck->status == RepairOrderDeductionModel::STATUS_NOT_USE && ($repairDeductionCheck->created_at + $deductionActivity->expired_time) >= time()) ? false : true;
        $repairDeduction = RepairOrderDeductionModel::findOne(['repair_order_id' => $orderId, 'status' => RepairOrderDeductionModel::STATUS_NOT_USE]);
        if ($repairDeduction && (in_array($orderStatus,[RepairOrderStatus::STATUS_CONFIRM_PRICE, RepairOrderStatus::STATUS_WAIT_PICK, RepairOrderStatus::STATUS_WAIT_DOOR, RepairOrderStatus::STATUS_WAIT_PRICE]))) {
            // 获取订单是否有抵扣金
            $order->hasOrderRepairDeduction = true;
            $order->repairOrderDeduction = $repairDeduction;
        }
        $selectRepairDeduction = RepairOrderDeductionModel::findOne(['repair_order_id' => $orderId, 'status' => RepairOrderDeductionModel::STATUS_IS_USING]);
        $order->selectOrderRepairDeduction = false;
        $order->selectRepairOrderDeduction = null;
        if ($selectRepairDeduction) {
            // 获取订单是否有抵扣金
            $order->selectOrderRepairDeduction = true;
            $order->selectRepairOrderDeduction = $selectRepairDeduction;
        }
        $usedRepairDeduction = RepairOrderDeductionModel::findOne(['repair_order_id' => $orderId, 'status' => RepairOrderDeductionModel::STATUS_IS_USED]);
        $order->usedOrderRepairDeduction = false;
        $order->usedRepairOrderDeduction = null;
        if ($usedRepairDeduction) {
            // 获取订单是否有抵扣金
            $order->usedOrderRepairDeduction = true;
            $order->usedRepairOrderDeduction = $usedRepairDeduction;
        }

        return true;
    }

    /**
     * 地图订单信息判断是否有砍价活动
     * @param $orderId
     * @param $orderStatus
     * @return boot
     */
    public static function mapCheckDeductionActivity($orderId, $orderStatus)
    {
        $hasOrderRepairDeduction = false;
        $repairDeductionCheck = RepairOrderDeductionModel::findOne(['repair_order_id' => $orderId]);
        if (empty($repairDeductionCheck)) {
            return $hasOrderRepairDeduction;
        }

        $deductionActivity = DeductionActivityModel::findOne(['id' => $repairDeductionCheck->activity_id]);
        if (empty($deductionActivity)) {
            return $hasOrderRepairDeduction;
        }

        $repairDeduction = RepairOrderDeductionModel::findOne(['repair_order_id' => $orderId, 'status' => RepairOrderDeductionModel::STATUS_NOT_USE]);
        if ($repairDeduction && (in_array($orderStatus,[RepairOrderStatus::STATUS_CONFIRM_PRICE, RepairOrderStatus::STATUS_WAIT_PICK, RepairOrderStatus::STATUS_WAIT_DOOR, RepairOrderStatus::STATUS_WAIT_PRICE]))) {
            // 获取订单是否有抵扣金
            $hasOrderRepairDeduction = true;
        }

        return $hasOrderRepairDeduction;
    }

    /** 把订单里面工程师的信息组装到 $order
     * @param $orderArray
     * @param $order
     * @return mixed
     */
    public static function getEngineerInfoAssignToOrder($orderArray, $order)
    {
        if ($orderArray['engineer_id']) {
            $engineerModel = EngineerModel::findOne(['id' => $orderArray['engineer_id']]);
            $engineerProfile = $engineerModel->engineerProfile;
            $order->engineer_name = $engineerProfile->firstname . '工';
            $order->engineer_avatar = $engineerProfile->head_photo ? ImageManager::getUrl($engineerProfile->head_photo, ImageManager::$STYLE_90) : $engineerProfile->headimgurl; // 优先使用认证头像

            $order->engineer_id = $engineerModel->uuid;

            /**
             * 工程师已接单数量
             */
            $order->engineer_order_count = EngineerModel::getEngineerDoneOrderCount($orderArray['engineer_id']);
        }

        return $order;
    }

    /** 组转故障到 $order 里面
     * @param $order
     * @return mixed
     */
    static function getFaultsAssignToOrder($order)
    {
        $orderId = $order->id;
        $userFaultQuery = RepairOrderUserSelectFaultsModel::find()
            ->select(['repair_order_user_select_faults.device_fault_id', 'device_fault.name AS device_fault_name'])
            ->leftJoin('device_fault', "`repair_order_user_select_faults`.`device_fault_id` = `device_fault`.`id`")
            ->where(['repair_order_user_select_faults.repair_order_id' => $orderId])
            ->asArray();

        $user_faults = array();
        if ($userFaultArray = $userFaultQuery->all()) {
            foreach ($userFaultArray as $item) {
                $user_faults[] = $item['device_fault_name'];
            }
        }

        return $user_faults;
    }

    /**
     * @param $order
     * @return mixed
     */
    static function getPlansAssignToOrder($order)
    {
        $orderId = $order->id;
        $repairPlansQuery = RepairOrderRepairPlansModel::find()
            ->where(['repair_order_id' => $orderId])
            ->asArray();
        $repairPlansArray = $repairPlansQuery->all();

        $order->is_priced = false; // 是否已报过价(备注: 报价过的订单, 详情页才显示费用明细栏)
        $order->repair_plans = array();
        if ($repairPlansArray) {
            $order->is_priced = true;
            $index = 0;
            foreach ($repairPlansArray as $item) {
                $plan = new stdClass();
                $plan->id = ++$index;
                $plan->name = $item['plan_name'];
                $plan->reason = $item['plan_reason'];
                $plan->parts_price = $item['parts_price'];
                $plan->repair_hours = $item['repair_hours'];
                $plan->difficulty_degree = $item['difficulty_degree'];
                $plan->labor_price = $item['labor_price'];
                $plan->price = $item['price'];
                $plan->quantity = $item['quantity'];
                $plan->warranty_days = (int)$item['warranty_days'];
                $plan->warranty_pages = ceil($item['warranty_pages']/10000);
                $plan->warranty       = WarrantyLevelRule::getHistoryWarrantyLevelDesc($item['warranty_days'], $item['warranty_pages']);
                $order->repair_plans[] = $plan;
            }
        }

        return $order;
    }

    /**
     * @param $order
     * @return mixed
     */
    static function getRemotePriceToOrder($order)
    {
        $orderId = $order->id;
        $repairPlansQuery = RepairOrderRemoteRepairPlansModel::find()
            ->select(['repair_plan.id AS repair_plan_id', 'repair_plan.name AS name', 'repair_plan.reason AS reason', 'repair_order_remote_repair_plans.warranty_level as warranty_level',
                'repair_order_remote_repair_plans.warranty_days as warranty_days', 'repair_order_remote_repair_plans.warranty_pages as warranty_pages',
                'repair_order_remote_repair_plans.parts_price AS parts_price', 'repair_order_remote_repair_plans.repair_hours AS repair_hours', 'repair_order_remote_repair_plans.difficulty_degree AS difficulty_degree',
                'repair_order_remote_repair_plans.labor_price AS labor_price', 'repair_order_remote_repair_plans.price AS price', 'repair_order_remote_repair_plans.quantity AS quantity'])
            ->leftJoin('repair_plan', "`repair_plan`.`id` = `repair_order_remote_repair_plans`.`repair_plan_id`")
            ->where(['repair_order_remote_repair_plans.repair_order_id' => $orderId])
            ->asArray();

        $order->is_priced = true; // 是否已报过价(备注: 报价过的订单, 详情页才显示费用明细栏)
        $order->repair_plans = array();
        $calRepairPrice = 0;
        if ($repairPlansArray = $repairPlansQuery->all()) {
            $order->is_priced = true;
            $index = 0;
            foreach ($repairPlansArray as $item) {
                // $warrantyDaysPlan = WarrantyLevelRule::getComputerWarrantyByLevel($item['warranty_level']);
                $plan = new stdClass();
                $plan->id = ++$index;
                $plan->name = $item['name'];
                $plan->reason = $item['reason'];
                $plan->parts_price = $item['parts_price'];
                $plan->repair_hours = $item['repair_hours'];
                $plan->difficulty_degree = $item['difficulty_degree'];
                $plan->labor_price = $item['labor_price'];
                $plan->price = $item['price'];
                $plan->quantity = $item['quantity'];
                $plan->warranty_days = (int)$item['warranty_days'];
                $plan->warranty_pages = ceil($item['warranty_pages']/10000);
                $plan->warranty       = WarrantyLevelRule::getHistoryWarrantyLevelDesc($item['warranty_days'], $item['warranty_pages']);
                $order->repair_plans[] = $plan;
                $calRepairPrice += sprintf('%0.2f', (float)$item['price'] * $item['quantity']);
            }
        }
        $order->repair_price = $calRepairPrice;
        $order->labor_discount_price = 0; // 折扣价格
        $order->discount_price = 0;
        /* 总维修价格 */
        $repairOrderModel = RepairOrderModel::findOne($orderId);
        $calPayPrice = RepairOrderPriceRule::orderTotalPriceDurationPricing($calRepairPrice, $repairOrderModel);
        $order->pay_price = sprintf('%0.2f', $calPayPrice);
        return $order;
    }

    /** 获取可用优惠券
     * @param $orderArray
     * @param $userId
     * @param $order
     * @return mixed
     */
    static function getCouponsAssignToOrder($orderArray, $userId, $order)
    {
        $is_user_close = (int)$orderArray['is_user_close'];
        $is_engineer_close = (int)$orderArray['is_engineer_close'];
        $orderId = $order->id;
        $orderCoupon = RepairOrderUserCouponModel::findOne(['repair_order_id' => $orderId]);

        if ($orderCoupon) {  // 已经使用过优惠券
            $order->can_use_coupon = false;
            $order->can_use_pay_door_fee_coupon = false;
        } elseif ($orderArray['prepay_ok']) { // 已经预支付过, 不能使用优惠券
            $order->can_use_coupon = false;
            $order->can_use_pay_door_fee_coupon = false;
        }/* elseif (1 == $is_user_close || 1 == $is_engineer_close) { // 已关闭订单不允许使用优惠券
            $order->can_use_coupon = false;
        }*/ elseif ($order->discount_price > 0) { // 该订单已使用了其他优惠折扣
            $order->can_use_coupon = false;
            $order->can_use_pay_door_fee_coupon = false;
        } elseif ($order->pay_price == 0) { // 该订单已免费
            $order->can_use_coupon = false;
            $order->can_use_pay_door_fee_coupon = false;
        }/*elseif (!$order->is_order_owner) { // 访问别人的订单(代付款), 禁用优惠券
            $order->can_use_coupon = false;
        }*/ else {
            $effectCoupons = UserCouponModel::getEffectCoupons($userId);
            $coupons = [];

            // 第一个默认选项不使用优惠券
            $c = new stdClass();
            $c->id = 0;
            $c->coupon_name = '不使用优惠券';
            $c->amount = 0;
            $c->min_consume_amount = 0;
            $coupons[] = $c;

            // 当前订单关联的用户设备是否使用过首单有礼优惠券
            $useBindPhoneCoupons = UserCouponModel::getUseCoupons($orderArray['repair_device_id'], UserCouponModel::TYPE_BIND_PHONE);
            $hasUseBindPhoneCoupon = false;
            if ($useBindPhoneCoupons && $useBindPhoneCoupons->count() > 0) {
                $hasUseBindPhoneCoupon = true;
            }

            // 找出优惠金额最大的优惠券
            $maxAmount = 0;
            $maxCouponId = 0;
            $maxCouponIndex = 0;
            // 添加容错处理
            if (isset($effectCoupons) && $effectCoupons) {
                foreach ($effectCoupons->each() as $model) {
                    // 过滤订单中已经选择的优惠券
                    $is_select_coupon = RepairOrderDetailModel::findOne(['select_user_coupon_id' => $model->id]);
                    if ($is_select_coupon) {
                        AppLog::DEBUG('--------------过滤一张已选择的优惠券: coupon_id=' . $model->id);
                        continue;
                    }
                    // 过滤不可用的优惠券(低于最小消费金额)
                    if ($order->pay_price < $model->min_consume_amount) {
                        continue;
                    }

                    // 首单有礼优惠券每台设备仅用1次
                    if ($hasUseBindPhoneCoupon && $model->type == UserCouponModel::TYPE_BIND_PHONE) {
                        AppLog::DEBUG('--------------过滤一张首单有礼优惠券-------------');
                        continue;
                    }
                    // 判断领取优惠券是否可用
                    if ($model->type == UserCouponModel::TYPE_COUPON_ACTIVITY) {
                        if (!CouponUseRules::checkActivityCouponEnable($model, $orderArray)) {
                            continue;
                        }
                    }
                    // 如果是用户关闭或者工程师关闭的情况下只拿能够支付上门费的优惠券
                    if ( (1 == $is_user_close || 1 == $is_engineer_close) && 0 == $model->can_pay_door_fee) {
                        continue ;
                    }

                    $c = new stdClass();
                    $c->id = $model->id;
                    //$c->coupon_name = mb_substr($model->coupon_name, 0, 10, 'utf-8') . '(' . $model->amount . '元)'; // 名称只显示10个字符, 保证优惠券金额能显示完整
                    $c->coupon_name = '省' . $model->amount . '元:' . mb_substr($model->coupon_name, 0, 10, 'utf-8'); // 名称只显示10个字符, 保证优惠券金额能显示完整
                    $c->amount = (float)$model->amount;
                    $c->min_consume_amount = (float)$model->min_consume_amount;

                    // 找出优惠金额最大的优惠券
                    if ($model->amount > $maxAmount) {
                        $maxAmount = $model->amount;
                        $maxCouponId = $model->id;
                        $maxCouponIndex = count($coupons);
                    }

                    $coupons[] = $c;
                }
            }

            if (count($coupons) > 1) { // 默认第一项不使用优惠券
                $order->coupons = $coupons;
                $order->can_use_coupon = true;
                $order->can_use_pay_door_fee_coupon = (1 == $is_user_close || 1 == $is_engineer_close) ? true : false;
                $order->max_amount = $maxAmount;
                $order->max_coupon_id = $maxCouponId;
                $order->max_coupon_index = $maxCouponIndex;
            } else {
                $order->can_use_coupon = false;
                $order->can_use_pay_door_fee_coupon = false;
            }
        }

        return $order;
    }

    /**
     * 地图模式下订单处理中的信息读取
     * @param $orderId
     * @return stdClass
     */
    public static function buildMapDetailResult($userId, $orderUUId)
    {
        $orderQuery = RepairOrderModel::find()->where(['repair_order.uuid' => $orderUUId]);
        $orderObj = $orderQuery->one();
        if (empty($orderObj)) {
            return false;
        }

        $orderDetail = $orderObj->detail;

        $order = new stdClass();
        $order->id = $orderObj->id;
        $order->order_no =  $orderObj->order_no;
        $order->repair_device_type =  $orderObj->repair_device_type;
        //$order->repair_device_id =  $orderObj->repair_device_id;
        $order->created_at =  $orderObj->created_at;

        // 判断是否订单拥有者
        $order->is_order_owner = true;
        if ( $orderObj->user_id != $userId) {
            $order->is_order_owner = false;
        }

        if (RepairOrderModel::REPAIR_DEVICE_USER_TYPE ==  $orderObj->repair_device_type) {
            $deviceInfo = UserDeviceModel::findOne([
                'id' =>  $orderObj->repair_device_id
            ]);
        } else {
            $deviceInfo = GuestDeviceModel::findOne([
                'id' =>  $orderObj->repair_device_id
            ]);
        }
        if ($deviceInfo) {
            $order->repair_device_id = $deviceInfo->id;
            $order->repair_device_uuid  = $deviceInfo->uuid;
        } else {
            $order->repair_device_id = 0;
            $order->repair_device_uuid  = 0;
        }

        // 用户报修地址
        $addressModel = AddressModel::findOne(['id' =>  $orderObj->address_id]);
        if ($addressModel) {
            $order->address = $addressModel->address;
            $order->longitude = sprintf('%0.6f', $addressModel->longitude);
            $order->latitude = sprintf('%0.6f', $addressModel->latitude);
        } else {
            $order->address = '测试地址';
            $order->longitude = 113.324520;
            $order->latitude = 23.199994;
        }

        $order->status =  $orderObj->status;
        $order->status_label = RepairOrderStatus::statusLabel( $orderObj->status);

        // 订单挂起状态
        if ( $orderObj->is_suspend == SuspendOrder::SUSPEND_STATUS_SUCCESS) {
            $order->is_suspend = true;
            $order->status_label = '等待再次上门';
            $order->two_door_time = date('Y-m-d H:i', $orderDetail->two_door_at);
        } elseif ($orderObj->is_suspend == SuspendOrder::SUSPEND_STATUS_APPLYING) {
            $order->is_suspend = true;
            $order->status_label = '挂起申请中';
            $order->two_door_time = date('Y-m-d H:i', $orderDetail->two_door_at);
        } else {
            $order->is_suspend = false;
        }

        /**
         * 工程师信息
         */
        if ($orderObj->engineer_id) {
            $engineerInfo = EngineerModel::findOne($orderObj->engineer_id);
            $engineerProfile = EngineerProfileModel::findOne(['engineer_id' => $orderObj->engineer_id]);
            $engineer = new stdClass();
            $engineer->id = $engineerInfo->uuid;
            $engineer->engineer_name = $engineerProfile->firstname . '工';
            //$engineer->engineer_avatar = $engineerProfile->headimgurl;
            $engineer->engineer_avatar = $engineerProfile->head_photo ? ImageManager::getUrl($engineerProfile->head_photo, ImageManager::$STYLE_90) : $engineerProfile->headimgurl; // 优先使用认证头像

            /**
             * 工程师地址
             */
            $engineerModel = EngineerModel::findOne(['id' => $orderObj->engineer_id]);
            //$engineer->engineer_phone = $engineerModel->phone;

            $addressModel = AddressModel::findOne(['id' => $engineerModel->address_id]);
            if ($addressModel) {
                $engineer->address = $addressModel->address;
                $engineer->longitude = sprintf('%0.6f', $addressModel->longitude);
                $engineer->latitude = sprintf('%0.6f', $addressModel->latitude);
            } else {
                $engineer->address = '测试地址';
                $engineer->longitude = 113.324520;
                $engineer->latitude = 23.099994;
            }

            /**
             * 工程师已接单数量
             */
            $engineer->order_count = EngineerModel::getEngineerDoneOrderCount($orderObj->engineer_id);

            // 设置工程师对象参数
            $order->engineer = $engineer;
        }

        //
        $thankFeeSetting = self::getThankFee($orderObj);
        $order->show_thank_fee = $thankFeeSetting[0];
        $order->thank_fee_list = $thankFeeSetting[1];
        $order->timeout_show_thank_fee = $thankFeeSetting[2];
        $order->thank_fee = $orderObj->thank_fee;
        $order->thank_fee_max_add_times = ThankFee::MAX_ADD_TIMES;
        $order->add_thank_fee_count = $orderDetail->add_thank_fee_count;
        $order->max_thank_fee = ThankFee::MAX_AMOUNT;

        // 获取符合派单规则的工程师数量
        //$order->dispatch_engineer_num = 30; // 获取符合派单条件的工程师数量

        // 查看订单是否正在进行的抵扣金活动
        $order->has_deduction_activity = false;
        $order->repair_deduction = null;
        $redis = Yii::$app->redis;
        $key = RedisConfig::DEDUCTION_ACTIVITY_SHOW;
        $hasShow = true;
        $order->tip_text = "";
        $order->deduction_activity_start_amount = 0;
        $order->deduction_activity_top_amount = 0;
        $repairDeduction = RepairOrderDeductionModel::findOne(['repair_order_id' => $orderObj->id]);
        if ($repairDeduction) {
            $deductionActivity = DeductionActivityModel::findOne($repairDeduction->activity_id);
            $order->deduction_share_title   = $deductionActivity->share_title;
            $order->deduction_share_img     = ImageManager::getUrl($deductionActivity->share_img);
            $order->deduction_activity_start_amount = sprintf('%d', $deductionActivity->start_amount);
            $order->deduction_activity_top_amount = sprintf('%d', $deductionActivity->top_amount);
            $order->has_deduction_activity = true;
            $order->repair_deduction = $repairDeduction;
            if ($redis->hexists($key, $orderObj->id)) {
                $data = json_decode($redis->hget($key, $orderObj->id), true);
            } else {
                $hasShow = false;
                $order->tip_text = "";
                $redis->HSETNX($key, $orderObj->id, json_encode(array("times" => 1)));
            }

            if ($hasShow == false) {
                $order->tip_text = "邀请朋友,帮你攒人品,\n可将{$deductionActivity->start_amount}元基础维修抵扣金升值,\n邀请朋友越多,累计抵扣金越高,\n最高累计{$deductionActivity->top_amount}元。";
            }
        }
        $order->has_show = $hasShow;

        return $order;
    }
}