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

namespace app\api\controllers;

use Yii;
use yii\base\Exception;
use yii\log\Logger;
use yii\helpers\HtmlPurifier;
use yii\db\Query;

use common\business\MarketingCoupon;
use common\business\RepairOrderPriceRule;
use common\business\WarrantyLevelRule;
use common\helpers\AppErrorLog;
use common\helpers\Log                      as AppLog;
use common\helpers\ImageManager;
use common\helpers\Utils;

use common\models\Address                   as AddressModel;
use common\models\BindDeviceApply           as BindDeviceApplyModel;
use common\models\ClientUser                as ClientUserModel;
use common\models\CouponActivity            as CouponActivityModel;
use common\models\DeviceFault               as DeviceFaultModel;
use common\models\GuestDevice               as GuestDeviceModel;
use common\models\Owner                     as OwnerModel;
use common\models\Qrcode                    as QrcodeModel;
use common\models\RegionFeeSetting          as RegionFeeSettingModel;
use common\models\RepairOrder               as RepairOrderModel;
use common\models\RepairOrderRepairPlans    as RepairOrderRepairPlansModel;
use common\models\SysSetting                as SysSettingModel;
use common\models\UserDevice                as UserDeviceModel;
use common\models\UserDeviceFav             as UserDeviceFavModel;
use common\models\UserDeviceLog             as UserDeviceLogModel;
use common\models\RedpackActivity           as RedpackActivityModel;
use common\models\UserRedpacks              as UserRedpacksModel;
use common\models\User                      as UserModel;
use common\models\RedpackAmount             as RedpackAmountModel;
use common\models\RepairPlan                as RepairPlanModel;
use common\helpers\MinaHelper;

use common\exts\wxpay\Log as WxpayLog;
use domain\device\DeviceCatRepository;
use domain\device\DeviceCat;
use domain\device\models\ModelsDeviceFaults as ModelsDeviceFaultsModel;
use domain\trade\RepairOrderUserOp;
use domain\trade\RepairOrderStatus;
use domain\trade\RepairOrderChannel;
use domain\trade\RepairOrderClaimRepository;
use domain\marketing\userads\UserAdsRepository;

use stdClass;
use function sizeof;
use function date;
use function count;
use function time;

/**
 * 设备-控制器
 * Class DeviceController
 * @package app\api\controllers
 */
class DeviceController extends ScopeUserController
{
    const PAGE_SIZE = 20; // 列表数据默认分页大小

    /**
     * 极速报修首页
     * @return string
     */
    public function actionRepairHome()
    {
        $e = new stdClass();
        $e->success = true;

        // 获取顶级分类信息
        $cats = DeviceCatRepository::getRootCatsWithImg();

        // 首页广告
        $ads = [];
        $adsArray = UserAdsRepository::search(['is_enable' => 1], ['orderBy' => ['sort_order' => SORT_ASC]])->fetchAll();
        foreach ($adsArray as $adItem) {
            $ad = new stdClass();
            $ad->id = $adItem['id'];
            $ad->title = $adItem['title'];
            $ad->cover_img_path = !empty($adItem['cover_img_path']) ? ImageManager::getUrl($adItem['cover_img_path']) : '';
            $ad->link_mode = $adItem['link_mode'];
            $ad->link_mode_label = $adItem['link_mode_label'];
            $ad->url = $adItem['url'];
            $ad->appid = $adItem['appid'];
            $ad->path = $adItem['path'];
            $ads[] = $ad;
        }

        // 后台读取配置
        $e->service_phone = SysSettingModel::getServicePhone();
        $e->enable_more = (SysSettingModel::getIsMoreDeviceEnable() == 1) ? true : false; // 是否启用更多分类: 未启用提示"敬请期待..."
        //$e->is_notice_enable = (SysSetting::getIsNoticeEnable() == 1) ? true : false; // 是否启用通知栏
        //$e->can_close_notice = (SysSetting::getCanCloseNotice() == 1) ? true : false; // 是否允许关闭通知栏
        $e->ads = $ads;
        $e->cats = $cats;

        return $e;
    }

    /**
     * 极速报修首页获取用户相关信息
     * @return string
     */
    public function actionRepairHomeUser()
    {
        $e = new stdClass();
        $e->device_fav_num = 0;
        $e->hasBindPhone = false;
        $e->hasCouponActivity = false;

        $clientUserId = $this->getClientUserId();
        $clientUser = ClientUserModel::findOne($clientUserId);
        if (false == $clientUser) {
            return $e;
        }

        $userModel = $this->getUserModel();
        if (false == $userModel) {
            return $e;
        }

        // 检测是否有符合的优惠券活动
        $coupon_activity = MarketingCoupon::checkCouponActivity($userModel->id, $clientUserId, CouponActivityModel::CHANNEL_USER_MINA, CouponActivityModel::ACTION_HOME_PAGE);
        if ($coupon_activity) {
            $e->hasCouponActivity = true;
            $e->couponActivity = $coupon_activity;
        }

        // 设备收藏夹数量
        $e->device_fav_num  = UserDeviceFavModel::getFavNum($userModel->id);

        // 是否手机号绑定认证
        if (!empty($userModel->phone)) {
            $e->hasBindPhone = true;
            // 手机认证用户才需要显示
            $e->agreement_version = MinaHelper::getAgreementVersion(); // 极办公用户协议版本号
            $e->agreement_udpate_desc = MinaHelper::getAgreementUpdateDesc(); // 极办公用户协议更新描述
        }

        return $e;
    }


    /**
     * 读取维修设备的二级分类数据
     * @return stdClass
     */
    public function actionDeviceCats()
    {
        $e = new stdClass();
        $e->success = false;

        if (false == $this->request->isPost) {
            $e->success = false;
            return $e;
        }

        $deviceCatId = $this->request->post('id');
        if (empty($deviceCatId)) {
            $e->success = false;
            return $e;
        }

        $cats = DeviceCatRepository::getCatByParentIdWithImg($deviceCatId);

        $e->success = true;
        $e->cats = $cats;

        return $e;
    }

    /**
     * 获取指定设备分类ID下的所有品牌
     * @return stdClass
     */
    public function actionGetBrands()
    {
        $e = new stdClass();
        $e->success = false;

        if (false == $this->request->isPost) {
            $e->success = false;
            return $e;
        }

        // 从设备型号表找出属于$deviceCatId的所有不同品牌
        $deviceCatId = $this->request->post('device_cat_id');
        if (empty($deviceCatId)) {
            $e->success = false;
            return $e;
        }

        $deviceCatModel = DeviceCatRepository::selectOne($deviceCatId);
        if (!$deviceCatModel) {
            $e->success = false;
            return $e;
        }

        $query = new Query();
        $query->select(['brand.id AS brand_id', 'brand.chinese_name AS chinese_name', 'brand.english_name AS english_name', 'brand.img_url AS img_url']);
        $query->from('model');
        $query->leftJoin('brand', 'brand.id = model.brand_id');
        $query->groupBy('brand.id');
        $query->where([
            'brand.is_available'  => 1,
            'model.device_cat_id' => $deviceCatId
        ]);
        $brandArray = $query->all();

        // 格式化返回匹配的品牌数组
        $brands = [];

        foreach ($brandArray as $item) {
            if (empty($item['brand_id'])) {
                continue ;
            }
            if ($item['english_name'] == 'JIWORK') {
                continue ; // 过滤[极办公]品牌
            }
            $brand = new stdClass();
            $brand->id = $item['brand_id'];
            $brand->name = $item['chinese_name'];
            $brand->english_name = $item['english_name'];
	        $brand->full_name = $item['chinese_name'] . '( ' . $item['english_name'] . ' )';
            $brand->icon = $item['img_url'] ? ImageManager::getUrl($item['img_url'], ImageManager::$STYLE_180) : '';

            // 电脑通用品牌图标区分: 台式机/笔记本/一体机
            if ($item['english_name'] == 'COMPUTER') {
                if ($deviceCatModel->name == "一体机") {
                    $brand->icon = '/i/ic_computer_yiti.png';
                } elseif ($deviceCatModel->name == "笔记本") {
                    $brand->icon = '/i/ic_computer_notebook.png';
                }
            }

            $brands[] = $brand;
        }

        $rootCatModel = DeviceCatRepository::selectOne($deviceCatId);
        if (isset($rootCatModel->parent_id) && $rootCatModel->parent_id != DeviceCat::COMPUTER_CAT_ID) {
            $brand = new stdClass();
            $brand->id = 0;
            $brand->name = "其它品牌";
            $brand->english_name = "OTHER";
            $brand->full_name = "其它品牌";
            $brand->icon = '/i/ic_brand_other.png';
            $brands[] = $brand;
        }
        $e->success = true;
        $e->brands = $brands;

        return $e;
    }

    /**
     * 读取系统对应二级分类的所有常见故障列表
     * @return stdClass
     */
    public function actionGetFaultsByCatId()
    {
        $e = new stdClass();
        $e->success = false;

        if (false == $this->request->isPost) {
            $e->success = false;
            return $e;
        }

        $deviceCatId = $this->request->post('device_cat_id');
        if (empty($deviceCatId)) {
            $e->success = false;
            return $e;
        }

        $faults = [];
        //$faultArray = DeviceFault::findAll(['device_cat_id' => $deviceCatId, 'is_common' => 1]);
        //$faultArray = DeviceFault::find()->where(['device_cat_id' => $deviceCatId, 'is_common' => 1])->orderBy('sort_order ASC')->all();
        $faultArray = DeviceFaultModel::find()->where(['device_cat_id' => $deviceCatId, 'version' => Yii::$app->params['DATA_VERSION']])->orderBy('sort_order ASC')->all();
        foreach ($faultArray as $faultItem) {
            $fault = new stdClass();
            $fault->id = $faultItem->id;
            $fault->name = $faultItem->name;
            $faults[] = $fault;
        }

        $e->success = true;
        $e->faults = $faults;

        return $e;
    }


    /**
     * 根据二维码编号获取设备信息
     * @return stdClass
     */
    public function actionGetDeviceByNumber()
    {
        $e = new stdClass();
        $e->success = false;

        if (false == $this->request->isPost) {
            $e->success = false;
            return $e;
        }

        $qrcode_number = $this->request->post('qrcode_number');
        AppLog::DEBUG('根据二维码编号获取设备信息: qrcode_number=' . $qrcode_number);
        if (empty($qrcode_number)) {
            $e->error = '无效设备二维码';
            $e->success = false;
            return $e;
        }

        $deviceQuery = QrcodeModel::find();
        $deviceQuery->select(['qrcode.*',
            'user_device.id AS device_id',
            'user_device.uuid AS device_uuid',
            'brand.id AS brand_id',
            'device_cat.id AS device_cat_id',
            'device.device_name AS device_name']);
        $deviceQuery->leftJoin('user_device', "qrcode.id = user_device.device_qrcode_id");
        $deviceQuery->leftJoin('device', "user_device.device_id = device.id");
        $deviceQuery->leftJoin('device_cat', "device.device_cat_id = device_cat.id");
        $deviceQuery->leftJoin('model', "device.model_id = model.id");
        $deviceQuery->leftJoin('brand', "model.brand_id = brand.id");
        $deviceQuery->where(['qrcode.number'=> $qrcode_number]);
        $deviceQuery->asArray();
        $deviceArray = $deviceQuery->one();
        if (empty($deviceArray)) {
            $e->error = '无效设备二维码';
            return $e;
        }

        if ($deviceArray['device_id'] == 0) {
            $e->error = '该二维码未绑定设备';
            return $e;
        }

        $device = new stdClass();
        $device->device_id = $deviceArray['device_uuid'];
        $device->brand_id = (int)$deviceArray['brand_id'];
        $device->device_cat_id = (int)$deviceArray['device_cat_id'];
        $device->device_name = $deviceArray['device_name'];

        $e->success = true;
        $e->device = $device;

        return $e;
    }


    /**
     * 获取设备信息
     * @return stdClass
     */
    public function actionGetDeviceDetail()
    {
        $e = new stdClass();
        $e->success = false;
        $e->needClaim = false;
        $e->orderId = '';

        if (false == $this->request->isPost) {
            $e->success = false;
            return $e;
        }

        $channel = $this->request->post('channel');
        $qrcodeNumber = $this->request->post('qrcodeNumber');
        $deviceUUId = $this->request->post('deviceId');
        $deviceType = $this->request->post('deviceType');

        AppLog::DEBUG('获取设备信息[参数]: ' . 'channel=' . $channel . ' | qrcodeNumber=' . $qrcodeNumber . ' | deviceUUId=' . $deviceUUId . ' | deviceType=' . $deviceType);

        // 根据设备二维码读取
        if ($channel == RepairOrderChannel::REPAIR_CHANNEL_SCAN || $channel == RepairOrderChannel::REPAIR_CHANNEL_HOME_SCAN) {
            $deviceResult = QrcodeModel::getDeviceInfoByScan($qrcodeNumber);
            if (false == $deviceResult->success) {
                return $deviceResult;
            }
            $deviceArray = $deviceResult->device;
            $device = new stdClass();
            $device->device_id = $deviceArray['device_uuid'];
            $device->model_id = $deviceArray['model_uuid'];
            $device->device_name = !empty($deviceArray['device_name']) ? $deviceArray['device_name'] : '';
            $device->model_name = !empty($deviceArray['model_name']) ? $deviceArray['model_name'] : '';
            $device->serial_no = !empty($deviceArray['serial_no']) ? $deviceArray['serial_no'] : '';
            $device->device_img = DeviceCatRepository::getParentCatImg($deviceArray['cat_parent_id'], $deviceArray['device_img']); ;

            // 设备位置
            if ($deviceArray['address_id']) {
                $addressModel = AddressModel::findOne($deviceArray['address_id']);
                if ($addressModel) {
                    $addressTitle = empty($addressModel->title)?$addressModel->address:$addressModel->title;
                    $addressDetailNote =  empty($addressModel->detail)?'':$addressModel->detail;
                    $device->address = $addressTitle.$addressDetailNote;
                } else {
                    $device->address = false;
                }
            }

            // 设备拥有者
            if ($deviceArray['owner_id']) {
                $ownerModel = OwnerModel::findOne($deviceArray['owner_id']);
                if ($ownerModel) {
                    $device->owner = $ownerModel->name;
                } else {
                    $device->owner = false;
                }
            }
            $user_id = $this->getUserId();
            $clientUserId = $this->getClientUserId();
            $claimResult = new stdClass();
            if (!empty($device->model_id) && !empty($user_id)) {
                $claimResult = RepairOrderClaimRepository::canClaimDeviceOrder($deviceArray['user_device_id'], UserDeviceFavModel::DeviceTypeUser, $user_id);
            } else {
                $claimResult->success = false;
            }

            if (true == $claimResult->success) {
                $orders = [];
                $device->busy_order = false;
                $device->can_submit_order = false;
                $e->needClaim = true;
                $e->orderId = $claimResult->orderId;
            } else {
                // 维修订单记录
                $orders = $this->getDeviceOrders(0, self::PAGE_SIZE, $deviceArray['user_device_id'], UserDeviceFavModel::DeviceTypeUser);

                // 查找该设备是否有亟需处理订单
                $device->busy_order = $this->getBusyOrder($deviceArray['user_device_id'], UserDeviceFavModel::DeviceTypeUser);
                $device->can_submit_order = UserDeviceModel::canSubmitOrder($deviceArray['user_device_id']);
            }

            MarketingCoupon::checkCouponActivity($user_id, $clientUserId,  CouponActivityModel::CHANNEL_USER_MINA,  CouponActivityModel::ACTION_SCAN_ORDER_DETAIL);
        } elseif ($channel == RepairOrderChannel::REPAIR_CHANNEL_FAV) { // 根据设备ID读取详情
            $dResult = UserDeviceModel::getFavDeviceInfoById($deviceUUId);
            if (false == $dResult->success) {
                return $dResult;
            }
            $deviceArray = $dResult->device;

            $device = new stdClass();
            $device->device_id = $deviceArray['device_uuid'];
            $device->model_id = $deviceArray['model_uuid'];

            $brandName = isset($deviceArray['brand_name'])?$deviceArray['brand_name']:'';
            $deviceName = isset($deviceArray['device_name'])?$deviceArray['device_name']:'';
            $deviceCatName = isset($deviceArray['device_cat_name'])?$deviceArray['device_cat_name']:'';

            // 设备名称
            $device->device_name = !empty($deviceName) ? $deviceName : $brandName.'-'.$deviceCatName;

            // 未审核用户设备空值处理
            if (empty($device->device_name)) {
                $device->device_name = '';
            }
            // 设备型号名称
            $device->model_name = !empty($deviceArray['model_name']) ? $deviceArray['model_name'] : $deviceArray['input_model'];
            if (empty($device->model_name)) {
                $device->model_name = '';
            }

            // 设备序列号
            if ($deviceType == UserDeviceFavModel::DeviceTypeUser) {
                $device->serial_no = $deviceArray['serial_no'];
            } else {
                $device->serial_no = '';
            }

            // 未审核用户设备空值处理
            if (empty($device->serial_no)) {
                $device->serial_no = '';
            }

            $device->device_img = DeviceCatRepository::getParentCatImg($deviceArray['cat_parent_id'], $deviceArray['device_img']) ;//$deviceArray['device_img'] ? ImageManager::getUrl($deviceArray['device_img']) : '/i/ic_device.jpg';

            // 设备位置
            if ($deviceType == UserDeviceFavModel::DeviceTypeUser && $deviceArray['address_id']) {
                $addressModel = AddressModel::findOne($deviceArray['address_id']);
                if ($addressModel) {
                    $device->address = $addressModel->address;
                } else {
                    $device->address = false;
                }
            } else {
                $device->address = false;
            }

            // 设备拥有者
            if ($deviceType == UserDeviceFavModel::DeviceTypeUser && $deviceArray['owner_id']) {
                $ownerModel = OwnerModel::findOne($deviceArray['owner_id']);
                if ($ownerModel) {
                    $device->owner = $ownerModel->name;
                } else {
                    $device->owner = false;
                }
            } else {
                $device->owner = false;
            }
            $user_id = $this->getUserId();
            $claimResult = new stdClass();
            if (!empty($deviceArray['model_uuid']) && !empty($user_id)) {
                $claimResult = RepairOrderClaimRepository::canClaimDeviceOrder($deviceArray['device_id'], UserDeviceFavModel::DeviceTypeUser, $user_id);
            } else {
                $claimResult->success = false;
            }
            if (true == $claimResult->success) {
                $orders = [];
                $device->busy_order = false;
                $device->can_submit_order = false;
                $e->needClaim = true;
                $e->orderId = $claimResult->orderId;
            } else {
                // 历史维修订单记录
                $orders = $this->getDeviceOrders(0, self::PAGE_SIZE, $deviceArray['device_id'], $deviceType);

                // 查找该设备是否有亟需处理订单
                $device->busy_order = $this->getBusyOrder($deviceArray['device_id'], UserDeviceFavModel::DeviceTypeUser);
                $device->can_submit_order = UserDeviceModel::canSubmitOrder($deviceArray['device_id']);
            }

        } else {
            $e->error = '非法访问设备详情页';
            return $e;
        }

        $bindStatus = $deviceArray['bindStatus'];
        if (BindDeviceApplyModel::STATUS_APPLY_PASS == $bindStatus) {
            $device->showSerial = true; 
        } else {
            $device->showSerial = false;
        }

        $e->success = true;
        $e->device = $device;
        $e->orders = $orders;

        // 是否手机号绑定认证
        $userModel = $this->getUserModel();
        if ($userModel && !empty($userModel->phone)) {
            $e->hasBindPhone = true;
        } else {
            $e->hasBindPhone = false;
        }

        return $e;
    }

    /** 获取订设备维修订单
     * @param $offset
     * @param $limit
     * @param $deviceId
     * @param $deviceType
     * @return array
     */
    private function getDeviceOrders($offset, $limit, $deviceId, $deviceType)
    {
        $userId = $this->getUserId();
        $orders = [];

//        $orderQuery = RepairOrder::find();
        $orderQuery = new Query();
        $orderQuery->select(['repair_order.*', 'repair_order_detail.contact_name', 'engineer_profile.firstname AS firstname', 'engineer_profile.lastname AS lastname']);
        $orderQuery->from('repair_order');
        $orderQuery->leftJoin('engineer_profile', "`repair_order`.`engineer_id` = `engineer_profile`.`engineer_id`");
        $orderQuery->leftJoin('repair_order_detail', "`repair_order_detail`.`repair_order_id` = `repair_order`.`id`");
        $orderQuery->where(['repair_order.repair_device_id' => $deviceId]);
        $orderQuery->andWhere(['repair_order.repair_device_type' => $deviceType]);

        // 只读取已完成订单-[修改为: 全部展示]
        //$statusValues = [RepairOrderStatus::STATUS_WAIT_RATE, RepairOrderStatus::STATUS_FINISH];
        //$orderQuery->andFilterWhere(['repair_order.status' => $statusValues]);
        // 过滤系统删除订单
        $orderQuery->andWhere(['repair_order.is_system_delete' => 0]);
        $orderQuery->orderBy('repair_order.id DESC');
        $orderQuery->offset($offset);
        $orderQuery->limit($limit);
        $rows = $orderQuery->all();

        // 获取最终结果
        foreach ($rows as $row) {
            $order = [];
            $orderId =  $row['id'];
            $order['order_id'] = $row['uuid'];
            $order['repair_price'] = RepairOrderPriceRule::orderTotalPrice($row, true); // 订单总金额, 这个reprice_price 不是订单里面的repair_price
            $order['status'] = (int)$row['status'];
            $order['processing'] = RepairOrderStatus::isProcessing($row['status']);
            $order['status_label'] = RepairOrderStatus::statusLabel($row['status']);
            $order['created_time'] = $row['created_at'] ? date('Y-m-d', $row['created_at']) : '';

            // 维修工程师名字
            if ($row['engineer_id'] != 0) {
                $order['engineer_name'] = $row['firstname'] . '工'; // $row['firstname'] . $row['lastname'];
            }else {
                $order['engineer_name'] = false;
            }

            /**
             * 报修用户信息
             */
            //if ($row['user_id']) {
            $order['repair_user_name'] = empty($row['contact_name']) ? UserModel::getUserNickName($row['user_id'], $row['client_id']) : $row['contact_name'];
            $avatar = UserModel::getUseAvatar($row['user_id'], $row['client_id']);

            $order['repair_user_avatar'] = Utils::getUserAvatar($avatar);
            //}

            // 权限检查: 订单本人和授权用户才有权限
            $order['has_permission'] = RepairOrderUserOp::hasPermission($userId, $orderId);

            /**
             * 维修方案
             */
            $repairPlansQuery = RepairOrderRepairPlansModel::find()
                ->select(['repair_plan_id', 'plan_name AS name', 'price'])
                ->where(['repair_order_id' => $orderId])
                ->asArray();
            // 拼接维修方案描述
            $repair_plans_desc = '';
            if ($repairPlansArray = $repairPlansQuery->all()) {
                foreach ($repairPlansArray as $k => $item) {
                    if ( 0 == $k ) {
                        $repair_plans_desc = $repair_plans_desc . $item['name'];
                    } else {
                        $repair_plans_desc = $repair_plans_desc . ' | '. $item['name'];
                    }
                }
            }
            $order['repair_plans_desc'] = $repair_plans_desc;

            // 填充数组
            $orders[] = $order;
        }

        return $orders;
    }

    /**
     * 获取指定设备的历史维修订单
     * @return string
     */
    public function actionGetDeviceOrders()
    {
        $e = new stdClass();
        $e->success = false;
        $e->orders = [];

        $deviceUUId = $this->request->post('deviceId');
        $deviceType = (int)$this->request->post('deviceType');
        $offset = (int)$this->request->post('offset');
        $limit = (int)$this->request->post('limit');

        $deviceId = '';
        if (RepairOrderModel::REPAIR_DEVICE_USER_TYPE == $deviceType) {
            $deviceInfo = UserDeviceModel::findOne(['uuid' => $deviceUUId]);
        } else {
            $deviceInfo = GuestDeviceModel::findOne(['uuid' => $deviceUUId]);
        }
        if ($deviceInfo) {
            $deviceId = $deviceInfo->id;
        }

        $orders = $this->getDeviceOrders($offset, $limit, $deviceId, $deviceType);
        if (sizeof($orders)) {
            $e->hasMore = true;
            $e->orders = $orders;
        } else {
            $e->hasMore = false;
        }

        $e->success = true;
        return $e;
    }

    /**
     * 查找指定设备是否存在亟需处理的订单
     * @param $deviceId
     * @param $deviceType
     * @return int
     */
    private function getBusyOrder($deviceId, $deviceType)
    {
        $orderQuery = new Query();
        $orderQuery->select(['repair_order.*']);
        $orderQuery->from('repair_order');
        $orderQuery->where(['repair_order.repair_device_id' => $deviceId]);
        $orderQuery->andWhere(['repair_order.repair_device_type' => $deviceType]);

        // 3-确认报价;4-等待验收;5-等待支付;
        $statusValues = [
            RepairOrderStatus::STATUS_CONFIRM_PRICE,
            RepairOrderStatus::STATUS_WAIT_ACCEPT,
            RepairOrderStatus::STATUS_WAIT_PAY
        ];
        $orderQuery->andWhere(['repair_order.status' => $statusValues]);

        $orderArray = $orderQuery->one();
        if (empty($orderArray)) {
            return false;
        }

        // 权限检查: 订单本人和授权用户才有权限
        $userId = $this->getUserId();
        $hasPermission = RepairOrderUserOp::hasPermission($userId, $orderArray['id']);
        if (false == $hasPermission) {
            return false;
        }

        $busyOrder = new stdClass();
        $busyOrder->id = $orderArray['uuid'];
        $busyOrder->status = (int)$orderArray['status'];

        //AppLog::DEBUG('getBusyOrder: 该设备有待处理订单=>' . json_encode($busyOrder));

        return $busyOrder;
    }

    /**
     * 扫码领红包结果回调
     * @return stdClass
     */
    public function actionScanRedpackResult()
    {
        $e = new stdClass();
        $e->success = false;
        $e->errMsg = false;

        $clientUserId = $this->getClientUserId();
        $clientUser = ClientUserModel::findOne($clientUserId);
        if (false == $clientUser) {
            $e->errMsg = '用户不存在';
            return $e;
        }

        // 读取传参
        $success = $this->request->post('success');
        $user_redpacks_id = $this->request->post('user_redpacks_id');
        $func = $this->request->post('func');
        $jsRes = $this->request->post('jsRes');
        WxpayLog::init();
        WxpayLog::DEBUG('扫码领红包js返回结果(' . $func .  '):=>' . json_encode($jsRes) . ' | success=' . $success);

        $userRedpacksModel = UserRedpacksModel::findOne(['client_user_id' => $clientUserId, 'id' => $user_redpacks_id]);
        // 更新红包领取记录的状态
        if (false == $userRedpacksModel) {
            $e->errMsg = '红包领取记录不存在';
            return $e;
        }

        $userRedpacksModel->status = $success ? UserRedpacksModel::STATUS_OPEN_SUCCESS : UserRedpacksModel::STATUS_OPEN_FAIL;
        $userRedpacksModel->received_at = time();
        if (!$userRedpacksModel->save()) {
            $e->errMsg = '红包领取记录保存失败';
            return $e;
        }

        $e->success = true;
        return $e;
    }

    /**
     * 扫码领红包接口
     * @return stdClass
     */
    public function actionScanRedpack()
    {
        $e = new stdClass();
        $e->success = false;
        $e->errMsg = false;
        $e->subcribeHint = RedpackActivityModel::SUBCRIBE_HINT;
        $e->has_no_act = false;

        $qrcodeNumber = $this->request->post('qrcodeNumber');
        if (empty($qrcodeNumber)) {
            // 邮件通知告警
            //AppErrorLog::error("[设备二维码扫码红包] 无效二维码编号");
            $e->errMsg = '无效二维码编号';
            return $e;
        }

        // 检测是否demo二维码
        if ($qrcodeNumber == RedpackActivityModel::DEMO_QRCODE_NUMBER) {
            // 邮件通知告警
            //AppErrorLog::error("[设备二维码扫码红包] 检测demo二维码");
            return $this->scanDemoRedpack();
        }

        // 扫码收藏用户设备
        $deviceResult = QrcodeModel::getDeviceInfoByScan($qrcodeNumber);
        if ($deviceResult->success) {
            $deviceArray = $deviceResult->device;
            $user_id = $this->getUserId();
            if ($deviceArray['device_id'] > 0) { // 仅收藏已审核通过的设备
                UserDeviceFavModel::scanFavDevice($user_id, $deviceArray['user_device_id']);
            }
        }

        $user_device_id = $this->getUserDeviceIdByQrcodeNumber($qrcodeNumber);
        if (false == $user_device_id) {
            // 邮件通知告警
            //AppErrorLog::error("[设备二维码扫码红包] 设备不存在=>[qrcodeNumber=" . $qrcodeNumber . ']');
            $e->errMsg = '设备不存在';
            return $e;
        }

        $clientUserId = $this->getClientUserId();
        $clientUser = ClientUserModel::findOne($clientUserId);
        if (false == $clientUser || false == $clientUser->profileMina) {
            // 邮件通知告警
            //AppErrorLog::error("[设备二维码扫码红包] 用户不存在");
            $e->errMsg = '用户不存在';
            return $e;
        }

        $clientId = $clientUser->client_id;
        $openId = $clientUser->profileMina->openid;

        // 该手机号在工程师端注册的角色是否允许领红包
//        $engineerModel = Engineer::findOne(['phone' => $clientUser->user->phone]);
//        if ($engineerModel && !Engineer::canRedpack($engineerModel->role)) {
//            $e->errMsg = '不允许领红包';
//            $e->has_no_act = true;
//            return $e;
//        }

        /**
         * 读取红包活动表,判断当前设备、当前用户是否符合【场景红包】领取条件,如符合则调用JS接口(回调函数中必须调用API更新红包领取记录表);如不符合则弹窗提示“该设备红包已被领取,更多红包正在来袭~”
         * 约定: 用户U1     设备D1     活动A1
         * 1. 查找一个可参加的活动: 启用/未过期(多个活动循环判断一个有红包的)
         * 2. D1的A1红包未被领取完 < redpack_num_per_device
         * 3. U1领取A1红包数量 < redpack_num_per_user
         */
        $findActivity = new stdClass();
        $resultCode = RedpackActivityModel::RESULT_NO_ACT;

        $currentTime = time();
        $weekDay = date('w'); // 0-周日; 1~6-周一~周六
        $actQuery = RedpackActivityModel::find()
            ->select(['redpack_activity.*'])
            ->where(['redpack_activity.is_enable' => 1])
            ->andWhere(['redpack_activity.scene' => RedpackActivityModel::SCENE_SCAN])
            ->andFilterWhere(['<=', 'redpack_activity.start_at', $currentTime])
            ->andFilterWhere(['>=', 'redpack_activity.end_at', $currentTime])
            ->andWhere("find_in_set('{$weekDay}', redpack_activity.weekdays)") // 固定星期几有效
            ->asArray();
        $actArray = $actQuery->all();
        if ($actQuery && $actArray) {
            foreach ($actArray as $act) {
                // 判断该红包活动已发放金额是否超过预算 或 超过发放总数
                $sendAmountQuery = UserRedpacksModel::find()
                    ->select(['SUM(user_redpacks.amount) as sent_amount', 'COUNT(*) as sent_num'])
                    ->where(['user_redpacks.redpack_activity_id' => $act['id']])
                    ->asArray();
                $sendAmount = $sendAmountQuery->one();
                $sent_amount = $sendAmount['sent_amount'] ? $sendAmount['sent_amount'] : 0;
                $sent_num = $sendAmount['sent_num'] ? $sendAmount['sent_num'] : 0;
                if ($sent_amount >= $act['total_amount']) {
                    // 邮件通知告警
                    //AppErrorLog::error("[设备二维码扫码红包]活动ID:{$act['id']}、端用户编号(client_user_id):{$clientUserId}、扫描二维码编号:{$qrcodeNumber}; 该活动已经超预算了");
                    continue ; // 该活动已超预算, 直接跳过
                }
                if ($sent_num >= $act['total_num']) {
                    // 邮件通知告警
                    //AppErrorLog::error("[设备二维码扫码红包]活动ID:{$act['id']}、端用户编号(client_user_id):{$clientUserId}、扫描二维码编号:{$qrcodeNumber}; 该活动红包已发完");
                    continue ; // 该活动红包已发完, 直接跳过
                }

                // 遍历查找一个该设备的红包尚未领取完的活动
                $deviceRedpackQuery = UserRedpacksModel::find()
                    ->select('COUNT(*)')
                    ->where(['user_redpacks.redpack_activity_id' => $act['id']])
                    ->andWhere(['user_redpacks.user_device_id' => $user_device_id])
                    ->asArray();

                // 该设备还有该活动红包可以领取
                $sendCount = $deviceRedpackQuery->count();
                if ($sendCount < $act['redpack_num_per_device']) {
                    // 用户领取该活动红包数量是否超过限制
                    $userRedpackQuery = UserRedpacksModel::find()
                        ->select('COUNT(*)')
                        ->where(['user_redpacks.redpack_activity_id' => $act['id']])
                        ->andWhere(['user_redpacks.client_user_id' => $clientUserId])
                        ->asArray();

                    $userRecvCount = $userRedpackQuery->count();
                    if ($userRecvCount < $act['redpack_num_per_user']) {
                        // 用户领取该活动单个设备的红包数量是否超过限制
                        $userDeviceRedpackQuery = UserRedpacksModel::find()
                            ->select('COUNT(*)')
                            ->where(['user_redpacks.redpack_activity_id' => $act['id']])
                            ->andWhere(['user_redpacks.user_device_id' => $user_device_id])
                            ->andWhere(['user_redpacks.client_user_id' => $clientUserId])
                            ->asArray();

                        $userDeviceRecvCount = $userDeviceRedpackQuery->count();
                        if ($userDeviceRecvCount < $act['user_redpack_num_per_device']) {
                            $findActivity->id = $act['id'];
                            $findActivity->name = $act['name'];
                            $findActivity->send_name = $act['send_name'];
                            $findActivity->remark = $act['remark'];

                            // 找到一个可领取的红包, 直接跳出, 走红包领取流程
                            $resultCode = RedpackActivityModel::RESULT_OK;
                            break;
                        } else {
                            // 邮件通知告警
                            //AppErrorLog::error("[设备二维码扫码红包]活动ID:{$act['id']}、端用户编号(client_user_id):{$clientUserId}、扫描二维码编号:{$qrcodeNumber}; 用户领取该活动单个设备的红包数量超过限制(用户领取数:{$userDeviceRecvCount},设置数:{$act['user_redpack_num_per_device']})");
                            $resultCode = RedpackActivityModel::RESULT_OVER_DEVICE_LIMIT;
                        }
                    } else {
                        // 邮件通知告警
                        //AppErrorLog::error("[设备二维码扫码红包]活动ID:{$act['id']}、端用户编号(client_user_id):{$clientUserId}、扫描二维码编号:{$qrcodeNumber}; 该活动红包每个用户可领取红包个数超限(用户领取数:{$userRecvCount},设置数:{$act['redpack_num_per_user']})");
                        $resultCode = RedpackActivityModel::RESULT_OVER_ACT_LIMIT;
                    }
                } else {
                    // 邮件通知告警
                    //AppErrorLog::error("[设备二维码扫码红包]活动ID:{$act['id']}、端用户编号(client_user_id):{$clientUserId}、扫描二维码编号:{$qrcodeNumber}; 该活动红包每台设备可领取红包个数超限(当前领取数:{$sendCount},设置数:{$act['redpack_num_per_device']})");
                    $resultCode = RedpackActivityModel::RESULT_DEVICE_NO_REDPACK;
                }
            }
        } else {
            // 邮件通知告警
            // AppErrorLog::error("[设备二维码扫码红包]端用户编号(client_user_id):{$clientUserId}、扫描二维码编号:{$qrcodeNumber}; 暂无可参加的红包活动");
        }

        // 领取红包失败
        if (RedpackActivityModel::RESULT_OK != $resultCode ) {
            $e->errMsg = RedpackActivityModel::resultLabels($resultCode);
            $e->has_no_act = true; // 不提示用户, 太烦了
            return $e;
        }

        // 红包领取流程
        try {
            AppLog::DEBUG(json_encode($findActivity));
            $redpackAmount = RedpackAmountModel::getRandomAmountRecord($findActivity->id);
            $amount = $redpackAmount ? $redpackAmount->amount : RedpackAmountModel::DEFAULT_AMOUNT;
            $wishing = $redpackAmount ? $redpackAmount->wishing : RedpackAmountModel::DEFAULT_WISHING;
            $result = MinaHelper::sendMinaRedPack($openId, $amount, $wishing, $findActivity->name, $findActivity->remark, $findActivity->send_name);

            // 添加红包领取记录
            $userRedpacksModel = new UserRedpacksModel([
                'client_id'             => $clientId,
                'client_user_id'        => $clientUserId,
                'redpack_activity_id'   => $findActivity->id,
                'user_device_id'        => $user_device_id,
                'amount'                => $amount,
                'status'                => UserRedpacksModel::STATUS_WAIT,
                'jsApiParameters'       => $result['jsApiParameters'], // 保存小程序红包发放接口返回结果,用于红包领取失败后重新领取
                'send_result'           => $result['result'], // 保存小程序红包发放接口返回结果
            ]);
            $userRedpacksModel->save();
            $userRedpackId = $userRedpacksModel->id;
        } catch (Exception $exception) {
            Yii::getLogger()->log($exception->getTraceAsString(), Logger::LEVEL_ERROR);
            //$e->errMsg = '接口异常: ' . $exception->getMessage();
            $e->errMsg = RedpackActivityModel::resultLabels(RedpackActivityModel::RESULT_API_ERROR);
            return $e;
        }

        $e->success = true;
        $e->jsApiParameters = json_decode($result['jsApiParameters']);
        $e->user_redpacks_id = $userRedpackId;
        return $e;
    }

    /**
     * 根据二维码编号判断对一个的用户设备是否存在
     * @param $qrcodeNumber
     * @return bool
     */
    private function getUserDeviceIdByQrcodeNumber($qrcodeNumber)
    {
        $deviceQuery = QrcodeModel::find();
        $deviceQuery->select(['qrcode.*',
            'user_device.id AS user_device_id',
        ]);
        $deviceQuery->leftJoin('user_device', "qrcode.id = user_device.device_qrcode_id");
        $deviceQuery->leftJoin('device', "user_device.device_id = device.id");
        $deviceQuery->where(['qrcode.number' => $qrcodeNumber]);
        $deviceQuery->asArray();
        $deviceArray = $deviceQuery->one();
        if (empty($deviceArray) || $deviceArray['user_device_id'] == 0) {
            return false;
        }

        return $deviceArray['user_device_id'];
    }

    /**
     * 扫描demo二维码, 100%发红包(仅供演示)
     * @return stdClass
     */
    public function scanDemoRedpack()
    {
        $e = new stdClass();
        $e->success = false;
        $e->errMsg = false;
        $e->subcribeHint = RedpackActivityModel::SUBCRIBE_HINT;
        $e->has_no_act = false;

        $qrcodeNumber = RedpackActivityModel::DEMO_QRCODE_NUMBER;
        $user_device_id = $this->getUserDeviceIdByQrcodeNumber($qrcodeNumber);
        if (false == $user_device_id) {
            $e->errMsg = '用户设备不存在';
            return $e;
        }

        $clientUserId = $this->getClientUserId();
        $clientUser = ClientUserModel::findOne($clientUserId);
        if (false == $clientUser || false == $clientUser->profileMina) {
            $e->errMsg = '用户不存在';
            return $e;
        }

        $clientId = $clientUser->client_id;
        $openId = $clientUser->profileMina->openid;

        $findActivity = RedpackActivityModel::findOne(['scene' => RedpackActivityModel::SCENE_DEMO]);
        if (false == $findActivity) {
            $e->errMsg = '未设置demo红包活动';
            return $e;
        }

        // 判断该红包活动已发放金额是否超过预算 或 超过发放总数
        $sendAmountQuery = UserRedpacksModel::find()
            ->select(['SUM(user_redpacks.amount) as sent_amount', 'COUNT(*) as sent_num'])
            ->where(['user_redpacks.redpack_activity_id' => $findActivity->id])
            ->asArray();
        $sendAmount = $sendAmountQuery->one();
        $sent_amount = $sendAmount['sent_amount'] ? $sendAmount['sent_amount'] : 0;
        $sent_num = $sendAmount['sent_num'] ? $sendAmount['sent_num'] : 0;
        if ($sent_amount >= $findActivity->total_amount) {
            // 该活动已超预算, 直接跳过
            $e->has_no_act = true;
            return $e;
        }
        if ($sent_num >= $findActivity->total_num) {
            // 该活动红包已发完, 直接跳过
            $e->has_no_act = true;
            return $e;
        }

        // 遍历查找一个该设备的红包尚未领取完的活动
        $deviceRedpackQuery = UserRedpacksModel::find()
            ->select('COUNT(*)')
            ->where(['user_redpacks.redpack_activity_id' => $findActivity->id])
            ->andWhere(['user_redpacks.user_device_id' => $user_device_id])
            ->asArray();

        // 该设备还有该活动红包可以领取
        $sendCount = $deviceRedpackQuery->count();
        if ($sendCount < $findActivity->redpack_num_per_device) {
            // 用户领取该活动红包数量是否超过限制
            $userRedpackQuery = UserRedpacksModel::find()
                ->select('COUNT(*)')
                ->where(['user_redpacks.redpack_activity_id' => $findActivity->id])
                ->andWhere(['user_redpacks.client_user_id' => $clientUserId])
                ->asArray();

            $userRecvCount = $userRedpackQuery->count();
            if ($userRecvCount < $findActivity->redpack_num_per_user) {
                // 用户领取该活动单个设备的红包数量是否超过限制
                $userDeviceRedpackQuery = UserRedpacksModel::find()
                    ->select('COUNT(*)')
                    ->where(['user_redpacks.redpack_activity_id' => $findActivity->id])
                    ->andWhere(['user_redpacks.user_device_id' => $user_device_id])
                    ->andWhere(['user_redpacks.client_user_id' => $clientUserId])
                    ->asArray();

                $userDeviceRecvCount = $userDeviceRedpackQuery->count();
                if ($userDeviceRecvCount < $findActivity->user_redpack_num_per_device) {
                    // 找到一个可领取的红包, 直接跳出, 走红包领取流程
                    $resultCode = RedpackActivityModel::RESULT_OK;
                } else {
                    $resultCode = RedpackActivityModel::RESULT_OVER_DEVICE_LIMIT;
                }
            } else {
                $resultCode = RedpackActivityModel::RESULT_OVER_ACT_LIMIT;
            }
        } else {
            $resultCode = RedpackActivityModel::RESULT_DEVICE_NO_REDPACK;
        }

        // 领取红包失败
        if (RedpackActivityModel::RESULT_OK != $resultCode ) {
            $e->errMsg = RedpackActivityModel::resultLabels($resultCode);
            return $e;
        }

        // 红包领取流程
        try {
            //AppLog::DEBUG(json_encode($findActivity));
            $redpackAmount = RedpackAmountModel::getRandomAmountRecord($findActivity->id);
            $amount = $redpackAmount ? $redpackAmount->amount : RedpackAmountModel::DEFAULT_AMOUNT;
            $wishing = $redpackAmount ? $redpackAmount->wishing : RedpackAmountModel::DEFAULT_WISHING;
            $result = MinaHelper::sendMinaRedPack($openId, $amount, $wishing, $findActivity->name, $findActivity->remark, $findActivity->send_name);

            // 添加红包领取记录
            $userRedpacksModel = new UserRedpacksModel([
                'client_id'           => $clientId,
                'client_user_id'      => $clientUserId,
                'redpack_activity_id' => $findActivity->id,
                'user_device_id'      => $user_device_id,
                'amount'              => $amount,
                'status'              => UserRedpacksModel::STATUS_WAIT,
                'jsApiParameters'     => $result['jsApiParameters'], // 保存小程序红包发放接口返回结果,用于红包领取失败后重新领取
                'send_result'         => $result['result'], // 保存小程序红包发放接口返回结果
            ]);
            if (!$userRedpacksModel->save()) {
                $e->errMsg = '添加红包领取记录失败';
                return $e;
            }

            $userRedpackId = $userRedpacksModel->id;
        } catch (Exception $exception) {
            Yii::getLogger()->log($exception->getTraceAsString(), Logger::LEVEL_ERROR);
            //$e->errMsg = '接口异常: ' . $exception->getMessage();
            $e->errMsg = RedpackActivityModel::resultLabels(RedpackActivityModel::RESULT_API_ERROR);
            return $e;
        }

        $e->success = true;
        $e->jsApiParameters = json_decode($result['jsApiParameters']);
        $e->user_redpacks_id = $userRedpackId;

        return $e;
    }

    /**
     * 获取指定型号的所有故障
     * @return stdClass
     */
    public function actionGetFaultsByModelId()
    {
        $e = new stdClass();
        $e->success = false;

        if (false == $this->request->isPost) {
            $e->success = false;
            return $e;
        }
        $deviceFaultName = $this->request->post("device_fault_name");

        $modelUUId = $this->request->post('model_id');
        $faultQuery = ModelsDeviceFaultsModel::find()
            ->select(['models_device_faults.device_fault_id', 'models_device_faults.version', 'device_fault.name AS device_fault_name', 'device_fault.sort_order AS sort_order'])
            ->leftJoin('device_fault', "`models_device_faults`.`device_fault_id` = `device_fault`.`id`")
            ->innerJoin('model', "model.id = models_device_faults.model_id")
            ->where(['model.uuid' => $modelUUId])
            ->andWhere(['models_device_faults.version' => Yii::$app->params['DATA_VERSION']])
            ->orderBy('sort_order ASC')
            ->asArray();
        if ($deviceFaultName) {
            $faultQuery->andWhere(['like', 'device_fault.name', $deviceFaultName]);
        }
        // 格式化获取该报修设备的故障列表
        $index = 0;
        $faults = array();
        if ( $faultArray = $faultQuery->all()) {
            foreach ($faultArray as $item) {
                $fault = new stdClass();
                $fault->index = ++$index;
                $fault->id = $item['device_fault_id'];
                $fault->name = $item['device_fault_name'];
                $faults[] = $fault;
            }
        }

        $e->success = true;
        $e->faults = $faults;
        $e->hasData = count($faults) > 0 ? true : false;

        return $e;
    }

    /**
     * 搜索所有维修方案
     * @return stdClass
     */
    public function actionSearchRepairPlans()
    {
        $e = new stdClass();
        $e->success = false;

        if (false == $this->request->isPost) {
            return $e;
        }
        $repairPlanName = $this->request->post("repair_plan_name");

        //$faultId = $this->request->post('fault_id');
        $modelUUId = $this->request->post('model_id');
        $deviceUUId = $this->request->post('device_id');
        if (empty($modelUUId) || empty($deviceUUId)) {
            return $e;
        }

        $city = '';
        $repairOrderUUId = $this->request->post('order_id');
        $repairOrderModel = RepairOrderModel::findOne(['uuid' => $repairOrderUUId ]);
        if ($repairOrderModel) { // 按订单所在城市查询上门费
            if (isset($repairOrderModel->addressProfile->city)) {
                $city = $repairOrderModel->addressProfile->city;
            }
        } else { // 按设备所在城市查询上门费
            $userDeviceModel = UserDeviceModel::find();
            $userDeviceModel->leftJoin("address_profile", "user_device.address_id = address_profile.address_id");
            $userDeviceModel->select(['address_profile.city']);
            $userDeviceModel->where(['user_device.uuid' => $deviceUUId]);
            $userDeviceModel->asArray();
            $deviceInfo = $userDeviceModel->one();
            if ($deviceInfo) {
                $city = $deviceInfo['city'];
            }
        }
        $regionSetting = RegionFeeSettingModel::getSettingByCity($city);
        $version = Yii::$app->params['DATA_VERSION'];
        $repairPlansQuery = RepairPlanModel::find()
            ->select(['repair_plan.id AS repair_plan_id', 'repair_plan.name AS name', 'repair_plan.reason AS reason',
                'models_repair_plan_prices.parts_price AS parts_price', 'models_repair_plan_prices.repair_hours AS repair_hours',
                'models_repair_plan_prices.difficulty_degree AS difficulty_degree', 'models_repair_plan_prices.price AS price',
                'models_repair_plan_prices.warranty_level AS warranty_level', 'model.device_cat_id'])
            ->innerJoin('models_repair_plan_prices', "`models_repair_plan_prices`.`repair_plan_id` = `repair_plan`.`id`")
            ->leftJoin('model', "model.id = models_repair_plan_prices.model_id")
            ->where(['model.uuid' => $modelUUId])
            ->andWhere(['repair_plan.version' => $version])
            ->andWhere(['models_repair_plan_prices.version' => $version])
            ->andWhere(['>','models_repair_plan_prices.price', 0])
            //->andWhere(['repair_plan.device_fault_id' => $faultId])
            ->orderBy('price ASC')
            ->asArray();

        if ($repairPlanName) {
            $repairPlansQuery->andWhere(['like', 'repair_plan.name', $repairPlanName]);
        }
        $repairPlansArray = $repairPlansQuery->all();
        $index = 0;
        $repair_plans = array();
        if ($repairPlansArray) {
            foreach ($repairPlansArray as $item) {
                $warrantyDays = SysSettingModel::getGuranteeTime() . '天';
                if (isset($item['device_cat_id']) && !empty($item['device_cat_id'])) {
                    $modelDeviceCat = DeviceCatRepository::selectOne($item['device_cat_id']);
                    $warrantyDaysPlan = WarrantyLevelRule::getWarrantyLevelsByDeviceCatId($modelDeviceCat->parent_id, $modelDeviceCat->id, $item['warranty_level']);
                    if ($warrantyDaysPlan) {
                        $warrantyDays = $warrantyDaysPlan['desc'];
                    }
                }
                $plan = new stdClass();
                $plan->id = ++$index;
                $plan->name = $item['name'];
                $plan->reason = $item['reason'];
                $price = $item['parts_price'] + ($regionSetting['man_hour_fee'] * $item['repair_hours'] * $item['difficulty_degree']);
                $plan->price = round($price, 2);
                $plan->warranty_days = $warrantyDays;
                $repair_plans[] = $plan;
            }
        }

        $e->success = true;
        $e->repair_plans = $repair_plans;
        $e->door_fee = $regionSetting['door_fee'];
        $e->hasData = count($repair_plans) > 0 ? true : false;

        return $e;
    }

    /**
     * 获取指定故障的所有维修方案
     * @return stdClass
     */
    public function actionGetRepairPlansByFaultId()
    {
        $e = new stdClass();
        $e->success = false;

        if (false == $this->request->isPost) {
            return $e;
        }
        $repairPlanName = $this->request->post("repair_plan_name");

        $faultId = $this->request->post('fault_id');
        $modelUUId = $this->request->post('model_id');
        $deviceUUId = $this->request->post('device_id');
        if (empty($faultId) || empty($modelUUId) || empty($deviceUUId)) {
            return $e;
        }

        $city = '';
        $repairOrderUUId = $this->request->post('order_id');
        $repairOrderModel = RepairOrderModel::findOne(['uuid' => $repairOrderUUId ]);
        if ($repairOrderModel) { // 按订单所在城市查询上门费
            if (isset($repairOrderModel->addressProfile->city)) {
                $city = $repairOrderModel->addressProfile->city;
            }
        } else { // 按设备所在城市查询上门费
            $userDeviceModel = UserDeviceModel::find();
            $userDeviceModel->leftJoin("address_profile", "user_device.address_id = address_profile.address_id");
            $userDeviceModel->select(['address_profile.city']);
            $userDeviceModel->where(['user_device.uuid' => $deviceUUId]);
            $userDeviceModel->asArray();
            $deviceInfo = $userDeviceModel->one();
            if ($deviceInfo) {
                $city = $deviceInfo['city'];
            }
        }
        $regionSetting = RegionFeeSettingModel::getSettingByCity($city);

        $version = Yii::$app->params['DATA_VERSION'];
        $repairPlansQuery = RepairPlanModel::find()
            ->select(['repair_plan.id AS repair_plan_id', 'repair_plan.name AS name', 'repair_plan.reason AS reason', 'repair_plan.version AS version',
                'models_repair_plan_prices.parts_price AS parts_price', 'models_repair_plan_prices.repair_hours AS repair_hours',
                'models_repair_plan_prices.difficulty_degree AS difficulty_degree', 'models_repair_plan_prices.price AS price', 'models_repair_plan_prices.warranty_level AS warranty_level', 'model.device_cat_id'])
            ->innerJoin('models_repair_plan_prices', "`models_repair_plan_prices`.`repair_plan_id` = `repair_plan`.`id`")
            ->leftJoin('model', "model.id = models_repair_plan_prices.model_id")
            ->where(['model.uuid' => $modelUUId])
            ->andWhere(['repair_plan.device_fault_id' => $faultId])
            ->andWhere(['repair_plan.version' => $version])
            ->andWhere(['models_repair_plan_prices.version' => $version])
            ->andWhere(['>', 'models_repair_plan_prices.price', 0])
            ->orderBy('price ASC')
            ->asArray();

        if ($repairPlanName) {
            $repairPlansQuery->andWhere(['like', 'repair_plan.name', $repairPlanName]);
        }
        $repairPlansArray = $repairPlansQuery->all();
        $index = 0;
        $repair_plans = array();
        if ($repairPlansArray) {
            foreach ($repairPlansArray as $item) {
                $warrantyDays =  SysSettingModel::getGuranteeTime().'天';
                if (isset($item['device_cat_id']) && !empty($item['device_cat_id'])) {
                    $modelDeviceCat = DeviceCatRepository::selectOne($item['device_cat_id']);
                    $warrantyDaysPlan = WarrantyLevelRule::getWarrantyLevelsByDeviceCatId($modelDeviceCat->parent_id, $modelDeviceCat->id, $item['warranty_level']);
                    if ($warrantyDaysPlan) {
                        $warrantyDays = $warrantyDaysPlan['desc'];
                    }
                }
                $plan = new stdClass();
                $plan->id = ++$index;
                $plan->name = $item['name'];
                $plan->reason = $item['reason'];
                $price = $item['parts_price'] + ($regionSetting['man_hour_fee'] * $item['repair_hours'] * $item['difficulty_degree']);
                $plan->price = round($price, 2);
                $plan->warranty_days = $warrantyDays;
                $repair_plans[] = $plan;
            }
        }

        $e->success = true;
        $e->repair_plans = $repair_plans;
        $e->door_fee = $regionSetting['door_fee'];
        $e->hasData = count($repair_plans) > 0 ? true : false;

        return $e;
    }

    /**
     * 获取用户设备信息
     */
    public  function actionGetUserDeviceInfoById()
    {
        $e = new stdClass();
        $e->success = false;

        if (false == $this->request->isPost) {
            return $e;
        }

        $deviceUUId = $this->request->post('deviceId');
        if (empty($deviceUUId)) {
            return $e;
        }

        $deviceQuery = UserDeviceModel::find();
        $deviceQuery->select([
            'user_device.uuid AS device_uuid',
            'user_device.address_id AS address_id',
            'user_device.owner_id AS owner_id',
            'address.longitude as longitude',
            'address.latitude as latitude',
            'address.address as address',
            'owner.type AS owner_type',
            'owner.name AS owner',
        ]);
        $deviceQuery->leftJoin('owner', "user_device.owner_id = owner.id");
        $deviceQuery->leftJoin('address', "user_device.address_id = address.id");
        $deviceQuery->where(['user_device.uuid' => $deviceUUId]);
        $deviceQuery->asArray();
        $deviceArray = $deviceQuery->one();
        if (empty($deviceArray)) {
            $e->error = '用户设备不存在';
            return $e;
        }

        $e->success = true;
        $e->device = $deviceArray;

        return $e;
    }

    /**
     * 编辑用户设备
     * @return \Exception|stdClass|Exception
     * @throws \yii\base\ErrorException
     * @throws \yii\db\Exception
     */
     public function actionEditUserDeviceInfoById()
     {
        $e = new stdClass();
        $e->success = false;
        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (false == $this->request->isPost) {
                $e->success = false;
                return $e;
            }
            $deviceUUId = $this->request->post('deviceId');
            $address = $this->request->post('address');
            $address = HtmlPurifier::process($address,['HTML.Allowed'=> '']);

            $longitude = $this->request->post('longitude');
            $latitude = $this->request->post('latitude');
            $companyName = $this->request->post('companyname');
            $companyName = HtmlPurifier::process($companyName,['HTML.Allowed'=> '']);


            $ownerType = $this->request->post('ownertype');
            if (empty($address) || empty($longitude) || empty($latitude) || empty($companyName) || !isset($ownerType)) {
                $e->error='缺少必要参数(deviceUUId|address|longitude|latitude|companyname|ownerType)';
                return $e;
            }

            if (empty($deviceUUId)) {
                $e->error='该用户设备不存在';
                return $e;
            }

            $deviceQuery = UserDeviceModel::find();
            $deviceQuery->select([
                'user_device.id AS user_device_id',
                'user_device.address_id AS address_id',
                'user_device.owner_id AS owner_id',
            ]);
            $deviceQuery->leftJoin('device', "user_device.device_id = device.id");
            $deviceQuery->leftJoin('device_img', "`user_device`.`device_id` = `device_img`.`device_id` and  `device_img`.`is_cover` = 1");
            $deviceQuery->leftJoin('model', "device.model_id = model.id");
            $deviceQuery->leftJoin('owner', "user_device.owner_id = owner.id");
            $deviceQuery->where(['user_device.uuid' => $deviceUUId]);
            $deviceQuery->asArray();
            $deviceArray = $deviceQuery->one();
            if (empty($deviceArray)) {
                $e->error = '用户设备不存在';
                return $e;
            }

            if (empty($deviceArray["address_id"])) {
                $e->error='用户设备地址不存在';
                return $e;
            }

            if (empty($deviceArray["owner_id"])) {
                $e->error='用户设备地址无设备拥有者';
                return $e;
            }

            $addressModel = AddressModel::findOne($deviceArray["address_id"]);
            if (empty($addressModel)) {
                $e->error='用户设备地址编号无效';
                return $e;
            }

            $deviceId = $deviceArray['user_device_id'];
            $clientUserId = $this->getClientUserId();
            $clientUser = ClientUserModel::findOne($clientUserId);
            if (false == $clientUser || false == $clientUser->profileMina) {
                $e->errMsg = '用户不存在';
                return $e;
            }

            UserDeviceLogModel::addLog([
                'user_device_id'     => $deviceId,
                'operator_id'        => $clientUser->user_id,
                'operator_type'      => UserDeviceLogModel::OPERATOR_TYPE_USER,
                'old_user_device_id' => 0,
                'content'            => "编辑设备地址 :address_id: {$deviceArray["address_id"]} ==> address(old:{$addressModel->address}, new:{$address}), longitude(old:{$addressModel->longitude}, new:{$longitude}), latitude(old:{$addressModel->latitude}, new:{$latitude})",
                'type'               => UserDeviceLogModel::TYPE_EDIT_ADDRESS
            ]);
            //AppLog::DEBUG("actionEditUserDeviceInfoById(编辑设备信息):address_id:{$deviceArray["address_id"]} ==> address(old:{$addressModel->address},new:{$address}), longitude(old:{$addressModel->longitude},new:{$longitude}), latitude(old:{$addressModel->latitude},new:{$latitude})");
            $addressModel->address = $address;
            $addressModel->longitude = $longitude;
            $addressModel->latitude = $latitude;
            $addressModel->updated_at = time();
            $resEditAddress = $addressModel->save();
            $ownerModel = OwnerModel::findOne($deviceArray["owner_id"]);
            if (empty($ownerModel)) {
                $e->error='用户设备拥有者编号不存在';
                return $e;
            }

            UserDeviceLogModel::addLog([
                'user_device_id'     => $deviceId,
                'operator_id'        => $clientUser->user_id,
                'operator_type'      => UserDeviceLogModel::OPERATOR_TYPE_USER,
                'old_user_device_id' => 0,
                'content'            => "编辑设备拥有者:owner_id: {$deviceArray["owner_id"]} ==> name(old:{$ownerModel->name}, new:{$companyName}), type(old:{$ownerModel->type}, new:{$ownerType})",
                'type'               => UserDeviceLogModel::TYPE_EDIT_OWNER
            ]);
            //AppLog::DEBUG("actionEditUserDeviceInfoById(编辑设备信息):owner_id:{$deviceArray["owner_id"]} ==> name(old:{$ownerModel->name},new:{$companyName}), type(old:{$ownerModel->type},new:{$ownerType})");
            $ownerModel->name = $companyName;
            $ownerModel->type = $ownerType;
            $ownerModel->updated_at = time();
            $resEditOwner = $ownerModel->save();
            if ($resEditAddress && $resEditOwner) {
                $transaction->commit();
                $e->success = true;
                $e->error='用户设备更新成功';
                return $e;
            } else {
                $transaction->rollBack();
                $e->error='用户设备更新失败';
                return $e;
            }
        } catch (Exception $e) {
            $transaction->rollBack();
            Yii::getLogger()->log($e->getTraceAsString(), Logger::LEVEL_ERROR);
            //$e->errMsg = '接口异常: ' . $exception->getMessage();
            $e->error = RedpackActivityModel::resultLabels(RedpackActivityModel::RESULT_API_ERROR);
            return $e;
        }
    }
}