Workorder.php 41.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 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
<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use think\Db;
use think\Exception;
use addons\workorder\model\Orders;
use addons\workorder\model\Engineer;
use addons\workorder\model\Records;
use addons\workorder\library\General;

class Workorder extends Frontend
{
    protected $noNeedLogin     = [];
    protected $noNeedRight     = ['*'];
    protected $layout          = 'default';
    protected $fileField       = ['image', 'images', 'file', 'files'];
    protected $userEngineerId  = null;
    protected $workorderConfig = [];

    public function _initialize()
    {
        parent::_initialize();
        // 当前用户是否是工程师
        if ($this->auth) {
            $this->userEngineerId = Engineer::where('user_id', $this->auth->id)->where('status', '1')->value('id');
        }

        $this->workorderConfig = get_addon_config('workorder');

        $this->autoClose();
    }

    public function autoClose()
    {
        if ($this->workorderConfig['auto_close'] == 0) {
            return true;
        }

        $nowTime = time();

        $orders = Orders::all(['status' => '3']);
        foreach ($orders as $index => $order) {
            $userLastRecordTime = Records::where('order_id', $order->id)
                ->where('user_id', '>', 0)
                ->order('createtime desc')
                ->value('createtime');
            $autoCloseTime      = $userLastRecordTime + (int)($this->workorderConfig['auto_close'] * 3600);
            if ($autoCloseTime <= time()) {
                $order->status = '4';
                $order->save();
                $record = [
                    'order_id'     => $order->id,
                    'engineer_id'  => $order->engineer_id,
                    'message_type' => 3,
                    'message'      => __('The job has been closed automatically!')
                ];
                Records::create($record);

                // 记录结单耗时
                $timeStatistics = Db::name('workorder_time_statistics')
                    ->where('order_id', $order->id)
                    ->where('type', 0)
                    ->where('time_consum', null)
                    ->find();
                if ($timeStatistics) {
                    Db::name('workorder_time_statistics')->where('id', $timeStatistics['id'])->update([
                        'endtime'     => $nowTime,
                        'time_consum' => $nowTime - $timeStatistics['starttime'],
                        'engineer_id' => $order->engineer_id,// 防转移,冲正为当前工程师
                    ]);
                }
            }
        }
    }

    public function my()
    {
        $page = $this->request->param('page');
        if ($this->request->isDelete()) {
            $order_id = (int)$this->request->param('order_id');
            $order    = Orders::get($order_id);
            if ($order->status != 5) {
                $this->error(__('You can delete a work order after closing it!'));
            }
            if (Orders::destroy(['id' => $order_id, 'user_id' => $this->auth->id])) {
                $this->success(__('Delete Success~'));
            } else {
                $this->error(__('Delete Fail!'));
            }
        }

        $orders = Orders::where('user_id', $this->auth->id)
            ->order('createtime desc')
            ->paginate(10, null, [])
            ->each(function ($item, $key) {
                $item->status = $this->handleStatus($item->status, false);
            });

        // 防止删除后当页显示空白
        if (count($orders) == 0 && $page > 1) {
            $this->redirect('workorder/my');
        }

        $this->view->assign('title', __('My work order'));
        $this->view->assign('orders', $orders);
        return $this->view->fetch();
    }

    public function manage()
    {
        if (!$this->userEngineerId) {
            $this->error(__('You have no permission to operate!'));
        }
        $page = $this->request->param('page');
        $type = $this->request->param('type') ?? 'all';

        $where['engineer_id'] = $this->userEngineerId;
        switch ($type) {
            case 'noreply':
                $where['status'] = ['in', '1,2'];
                break;
            case 'replied' :
                $where['status'] = 3;
                break;
            case 'closed':
                $where['status'] = ['in', '4,5'];
                break;
        }

        $orders = Orders::where($where)->order('createtime desc')->paginate(10, null, [])->each(function ($item, $key) {
            $item->status = $this->handleStatus($item->status, true);
        });

        if (count($orders) == 0 && $page > 1) {
            $this->redirect('workorder/manage');
        }

        $this->view->assign('title', __('work order manage'));
        $this->view->assign('orders', $orders);
        $this->view->assign('type', $type);
        return $this->view->fetch();
    }

    public function show_confidential($confidential_id)
    {
        // 直接读取数据库中的数据
        $row = Db::name('workorder_records')->where('id', $confidential_id)->find();
        if (!$row) {
            $this->error(__('Record order not found!'));
        }

        $order             = Orders::get($row['order_id']);
        $isUser            = ($order->user_id == $this->auth->id) ? true : false;
        $isCurrentEngineer = ($order->engineer_id === $this->userEngineerId) ? true : false;
        if (!$isUser && !$isCurrentEngineer) {
            $this->error(__('You have no permission to operate!'));
        }

        $this->success('ok', '', $row);
    }

    public function reply($id)
    {
        $token = $this->request->post('__token__');
        if (session('__token__') != $token) {
            $this->error(__('Token incorrect!'), null, ['token' => $this->request->token()]);
        }

        $order = Orders::get($id);
        if (!$order) {
            $this->error(__('Work order not found~'));
        }

        $isUser            = ($order->user_id == $this->auth->id) ? true : false;
        $isCurrentEngineer = false;
        if ($order->engineer_id === $this->userEngineerId) {
            $isCurrentEngineer = true;
            $engineerInfo      = Engineer::get($this->userEngineerId);
        }
        if (!$isUser && !$isCurrentEngineer) {
            $this->error(__('You have no permission to operate!'));
        }

        $replyField = $order->getFields(null, $isUser ? 1 : 2);
        $row        = $this->request->post('row/a');
        $origin     = $this->request->post('row/a', [], 'trim');
        // 要入沟通记录的字段-所有文件自动入沟通记录
        $recordField = [
            'reply_describe'     => '0',// 描述-富文本
            'reply_confidential' => '4',// 机密信息-机密信息
        ];
        $records     = [];

        foreach ($replyField as $index => $field) {
            if ($field['isrequire'] && (!isset($row[$field['name']]) || $row[$field['name']] == '')) {
                $this->error(__('%s can not be empty!', $field['title']), null, ['token' => $this->request->token()]);
            }

            if ($field['type_list'] == 'editor') {
                if (function_exists('xss_clean')) {
                    $row[$field['name']] = isset($origin[$field['name']]) ? xss_clean($origin[$field['name']]) : '';
                } else {
                    $row[$field['name']] = isset($origin[$field['name']]) ? General::removeXss($origin[$field['name']]) : '';
                }
            }

            if (array_key_exists($field['name'], $recordField) && isset($row[$field['name']]) && $row[$field['name']]) {
                $records[] = [
                    'message_type' => $recordField[$field['name']],
                    'message'      => $row[$field['name']]
                ];
            }

            if (in_array($field['type_list'], $this->fileField) && isset($row[$field['name']]) && $row[$field['name']]) {
                $attachment = explode(',', $row[$field['name']]);
                if ($field['type_list'] == 'image' || $field['type_list'] == 'images') {
                    $message_type = 1;
                } else {
                    $message_type = 2;
                }
                foreach ($attachment as $index => $item) {
                    $records[] = [
                        'message_type' => $message_type,
                        'message'      => $item
                    ];
                }
            }
        }

        $batch = Records::where('order_id', $id)->max('batch');

        foreach ($records as $index => $record) {
            $records[$index]['order_id'] = $id;
            $records[$index]['batch']    = $batch + 1;
            if ($isUser) {
                $records[$index]['sender']   = 'user';
                $records[$index]['user_id']  = $this->auth->id;
                $records[$index]['nickname'] = $this->auth->nickname;
                $records[$index]['avatar']   = $this->auth->avatar;
            } elseif ($isCurrentEngineer) {
                $records[$index]['sender']      = 'engineer';
                $records[$index]['engineer_id'] = $this->userEngineerId;
                $records[$index]['title']       = $engineerInfo->title;
                $records[$index]['avatar']      = ($engineerInfo->user && $engineerInfo->user->avatar) ? $engineerInfo->user->avatar : (function_exists('letter_avatar') ? letter_avatar($engineerInfo->title) : '/assets/img/avatar.png');
            }
        }

        $this->assignconfig('editor_name', $this->getEditorName());

        $recordsModel = new Records;
        $records      = $recordsModel->allowField(true)->saveAll($records);
        if ($records) {

            $this->view->engine->layout(false);
            foreach ($records as $index => $record) {
                $recordsHtml[$index] = $this->view->fetch('workorder/common/message_item', [
                    'record' => $record,
                    'isUser' => $isUser
                ]);
            }

            $General = General::instance($this->workorderConfig);

            $timeStatistics = Db::name('workorder_time_statistics')
                ->where('order_id', $id)
                ->where('type', 'in', '1,2')
                ->where('time_consum', null)
                ->find();

            if ($isCurrentEngineer) {
                if ($order->status == 2) {
                    $order->status = 3;

                    $General->mailNotice($order, 'user_got_reply', '【工单收到新的回复】' . $order->title, '工单:' . $order->title . ' 工程师已回复您的问题,请及时查看/反馈。');
                    $General->smsNotice($order, 'user_got_reply');
                }
                if ($order->lasturgingtime) {
                    $order->lasturgingtime = null;
                }

                // 计算回复时间
                $nowTime = time();
                if ($timeStatistics) {
                    Db::name('workorder_time_statistics')->where('id', $timeStatistics['id'])->update([
                        'endtime'     => $nowTime,
                        'time_consum' => $nowTime - $timeStatistics['starttime'],
                        'engineer_id' => $order->engineer_id,// 防转移,冲正为当前工程师
                    ]);
                    General::calcEngineerAvgResTime($order->engineer_id);
                }

            } else {
                if ($order->status == 3) {
                    $order->status = 2;

                    $General->mailNotice($order, 'engineer_got_reply', '【工单收到新的反馈】' . $order->title, '工单:' . $order->title . ' 用户反馈了新的信息,请及时查看/回复。');
                    $General->smsNotice($order, 'engineer_got_reply');
                }

                // 准备记录回复时间
                if (!$timeStatistics) {
                    $timeStatistics = [
                        'type'        => 1,
                        'order_id'    => $id,
                        'engineer_id' => $order->engineer_id,
                        'starttime'   => time()
                    ];
                    Db::name('workorder_time_statistics')->insert($timeStatistics);
                }

            }
            $order->save();
            $this->success(__('Reply Success~'), '', ['recordsHtml' => $recordsHtml]);
        }

        $this->error(__('Nothing happened~'));
    }

    public function transfer($id)
    {
        $row = Orders::get($id);
        if (!$row) {
            $this->error(__('Work order not found~'));
        }
        $isCurrentEngineer = ($row->engineer_id === $this->userEngineerId) ? true : false;
        if (!$isCurrentEngineer) {
            $this->error(__('You have no permission to operate!'));
        }

        if ($this->request->request('keyField')) {
            $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);
            $word = (array)$this->request->request("q_word/a");

            $engineers = Engineer::all(function ($query) use ($word) {
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where('title', "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item) {
                                $query->where('title', "like", "%{$item}%");
                            });
                        }
                    });
                }
                $query->where('status', '1');
                $query->where('user_id', '<>', $this->auth->id);
            });
            return json(['list' => $engineers, 'total' => count($engineers)]);
        }

        if ($this->request->isPost()) {
            $token = $this->request->post('__token__');
            if (session('__token__') != $token) {
                $this->error(__('Token incorrect!'), null, ['token' => $this->request->token()]);
            }
            $transfer_engineer = $this->request->post('transfer_engineer');
            $engineer          = Engineer::get($transfer_engineer);

            if (!$engineer->user_id) {
                $this->error(__('The engineer has not bound users!'), null, ['token' => $this->request->token()]);
            }

            if ($engineer->user_id == $row->user_id) {
                $this->error(__('Engineer and issuer cannot be the same person!'), null, ['token' => $this->request->token()]);
            }

            if ($engineer && $engineer->status == '1') {
                $row->engineer_id = $transfer_engineer;
                $row->save();

                $engineer->lastreceivetime = time();
                $engineer->work_order_quantity++;
                $engineer->save();

                $record = [
                    'order_id'     => $id,
                    'engineer_id'  => $this->userEngineerId,
                    'message_type' => 3,
                    'message'      => __('The work order has been transferred to:%s', $engineer->title)
                ];
                Records::create($record);
                $this->success(__('Work order transferred~'), url('index/workorder/manage'));
            }
        }

        $this->error(__('Nothing happened~'));
    }

    public function detail($id)
    {
        $nowTime = time();
        $row     = Orders::get($id);
        if (!$row) {
            $this->error(__('Work order not found~'), url('index/workorder/my'));
        }

        $isUser            = ($row->user_id == $this->auth->id) ? true : false;
        $isCurrentEngineer = ($row->engineer_id === $this->userEngineerId) ? true : false;
        if (!$isUser && !$isCurrentEngineer) {
            $this->error(__('You have no permission to operate!'));
        }
        $General = General::instance($this->workorderConfig);

        if ($row->status == 1 && $isCurrentEngineer) {
            $row->status = 2;
            $row->save();
            $record = [
                'order_id'     => $id,
                'engineer_id'  => $this->userEngineerId,
                'message_type' => 3,
                'message'      => __('The engineer has viewed your submitted questions')
            ];
            Records::create($record);

            // 发送通知
            $General->mailNotice($row, 'user_order_handle', '【工单已在处理】' . $row->title, '工单:' . $row->title . ' 工程师已查看您提交的问题,正在处理中');
            $General->smsNotice($row, 'user_order_handle');
        }

        // 下次可催办时间
        $urging_rate    = (int)($this->workorderConfig['urging_rate'] * 60);
        $nextUrgingTime = (int)$row->lasturgingtime + $urging_rate;

        if ($this->request->isPost()) {
            $type = $this->request->param('type');
            if ($type == 'close') {
                if ($row->status == 4 || $row->status == 5) {
                    $this->error(__('The work order has been closed!'));
                }

                if ($isCurrentEngineer && ($this->workorderConfig['engineer_close'] == 0)) {
                    $this->error(__('The engineer was not allowed to close the work order~'));
                }

                $row->status = 4;
                $row->save();

                $timeStatistics = Db::name('workorder_time_statistics')
                    ->where('order_id', $row->id)
                    ->where('type', 0)
                    ->where('time_consum', null)
                    ->find();
                if ($timeStatistics) {
                    // 记录结单耗时
                    Db::name('workorder_time_statistics')->where('id', $timeStatistics['id'])->update([
                        'endtime'     => $nowTime,
                        'time_consum' => $nowTime - $timeStatistics['starttime'],
                        'engineer_id' => $row->engineer_id,// 防转移,冲正为当前工程师
                    ]);
                }

                $this->success(__('Work order closed successfully~'));
            } elseif ($type == 'urging' && $isUser) {
                if (!$this->workorderConfig['user_urging']) {
                    $this->error(__('Reminder function not enabled~'));
                }

                if ($nextUrgingTime <= time()) {
                    $row->lasturgingtime = time();
                    $row->save();

                    $General->mailNotice($row, 'engineer_urging', '【工单催办】' . $row->title, '工单:' . $row->title . ' 用户希望您能尽快回复。');
                    $General->smsNotice($row, 'engineer_urging');

                    $this->success(__('Reminder message sent successfully~'));
                } else {
                    $this->error(__('Urge message sent frequently!'));
                }

            }

            $this->error(__('Nothing happened~'));
        }

        $replyField = $row->getFields(null, $isUser ? 1 : 2);
        $allField   = $row->getFields($row, 0);
        $basicField = [];// 工单基本信息字段
        $listField  = ['select', 'selects', 'checkbox', 'radio'];
        foreach ($allField as $index => $field) {
            if ($field['isbasicinfo'] == 1) {
                if (in_array($field['type_list'], $listField)) {
                    if (is_array($field['values_list'])) {
                        $field['value'] = isset($field['values_list'][$field['value']]) ? $field['values_list'][$field['value']] : '';
                    }
                }
                $basicField[] = $field;
            }
        }

        $row->urging = false;
        $row->close  = false;
        if ($isUser && $row->status <= 2 && $nextUrgingTime <= time() && $row->engineer_id && $this->workorderConfig['user_urging']) {
            $row->urging = true;
        }

        if ($row->status <= 3) {
            $row->close = true;
        }

        if ($isCurrentEngineer) {
            $basicField[] = [
                'title' => __('Submit user'),
                'value' => $row->user->nickname
            ];

            if (!$this->workorderConfig['engineer_close']) {
                $row->close = false;
            }
        }

        $row->status = $this->handleStatus($row->status, $isCurrentEngineer);

        // 沟通记录
        $records = Records::where('order_id', $id)->order('createtime asc')->select();

        // 共有哪些工程师
        $engineers = [];
        if ($row->engineer_id) {
            $engineers[$row->engineer_id] = $row->engineer_id;
        }
        foreach ($records as $index => $record) {
            if ($record->engineer_id) {
                $engineers[$record->engineer_id] = $record->engineer_id;
            }
            if ($record->engineer && $record->engineer->user) {
                $record->engineer->user->avatar = $record->engineer->user->avatar ? $record->engineer->user->avatar : (function_exists('letter_avatar') ? letter_avatar($record->engineer->title) : '/assets/img/avatar.png');
            }
        }
        $engineers          = Engineer::select($engineers);
        $engineerInfoConfig = Engineer::getEngineerInfoConfig();
        foreach ($engineers as $index => $engineer) {
            if (!$engineer->introduce) {
                $engineer->introduce = ($engineer->user && $engineer->user->bio) ? $engineer->user->bio : '';
            }
            $engineer->all_order_number = in_array('all_order_number', $engineerInfoConfig) ? $engineer->all_order_number : false;
            $engineer->wx               = in_array('wx', $engineerInfoConfig) ? $engineer->wx : false;
            $engineer->qq               = in_array('qq', $engineerInfoConfig) ? $engineer->qq : false;
            if ($engineer->user) {
                $engineer->user->mobile = in_array('mobile', $engineerInfoConfig) ? $engineer->user->mobile : false;
                $engineer->user->email  = in_array('email', $engineerInfoConfig) ? $engineer->user->email : false;
                $engineer->user->avatar = $engineer->user->avatar ? $engineer->user->avatar : (function_exists('letter_avatar') ? letter_avatar($engineer->title) : '/assets/img/avatar.png');
            }
        }

        // 处理用户头像
        if ($row->user) {
            $row->user->avatar = $row->user->avatar ? $row->user->avatar : (function_exists('letter_avatar') ? letter_avatar($row->user->nickname) : '/assets/img/avatar.png');
        }

        $editorName = $this->getEditorName();
        $this->view->assign('row', $row);
        $this->view->assign('isUser', $isUser);
        $this->view->assign('fields', $replyField);
        $this->view->assign('records', $records);
        $this->view->assign('engineers', $engineers);
        $this->view->assign('title', $row->title . ' – ' . __('Work order details'));
        $this->view->assign('basicField', $basicField);
        $this->view->assign('editor_name', $editorName);
        $this->assignconfig('editor_name', $editorName);
        return $this->view->fetch();
    }

    protected function getEditorName()
    {
        $editor     = ['nkeditor', 'umeditor', 'markdown', 'tinymce', 'simditor', 'ueditor', 'summernote'];
        $editorList = get_addon_list();
        foreach ($editor as $index => $item) {
            if (array_key_exists($item, $editorList) && $editorList[$item]['state'] == 1) {
                return $item;
            }
        }
        return 'none';
    }

    public function evaluate($id)
    {
        $order = Orders::get($id);
        if (!$order) {
            $this->error(__('Work order not found~'));
        }
        if ($order->status == 5) {
            $this->error(__('The work order has been evaluated~'));
        }

        if ($this->request->isPost()) {
            $nowTime = time();
            $token   = $this->request->post('__token__');
            if (session('__token__') != $token) {
                $this->error(__('Token incorrect!'), null, ['token' => $this->request->token()]);
            }

            $row = $this->request->post('row/a');

            if (!$row['stars']) {
                $this->error(__('Please select the overall evaluation~'));
            } elseif (!isset($row['solved'])) {
                $this->error(__('Please select whether the problem has been solved~'));
            }

            $row['order_id']    = $order->id;
            $row['category_id'] = $order->category_id;
            $row['user_id']     = $this->auth->id;
            $row['createtime']  = time();

            if (Db::name('workorder_evaluate')->insert($row)) {
                $order->status = 5;
                $order->save();

                // 记录结单耗时
                $timeStatistics = Db::name('workorder_time_statistics')
                    ->where('order_id', $order->id)
                    ->where('type', 0)
                    ->where('time_consum', null)
                    ->find();
                if ($timeStatistics) {
                    Db::name('workorder_time_statistics')->where('id', $timeStatistics['id'])->update([
                        'endtime'     => $nowTime,
                        'time_consum' => $nowTime - $timeStatistics['starttime'],
                        'engineer_id' => $order->engineer_id,// 防转移,冲正为当前工程师
                    ]);
                }

                $this->success(__('Evaluation submitted successfully~'), url('index/workorder/my'));
            } else {
                $this->error(__('Evaluation failed, please try again!'));
            }
        }

        $this->view->assign('title', __('Evaluation Work Order'));
        $this->view->assign('row', $order);
        return $this->view->fetch();
    }

    public function create()
    {
        $keywords = $this->request->param('keywords');
        $category = $this->request->param('category');
        $steps    = $this->request->param('steps');

        // 第一步-选择产品/服务
        if (!$category) {
            $where['status']     = '1';
            $where['deletetime'] = null;
            if ($keywords) {
                $where['pid']  = ['>', 0];
                $where['name'] = ['like', '%' . $keywords . '%'];
            }
            $category_temp = Db::name('workorder_category')->where($where)->order('weigh desc')->select();

            if ($keywords) {
                $category_list[] = [
                    'name'  => __('Query results'),
                    'child' => $category_temp
                ];
            } else {
                foreach ($category_temp as $index => $item) {
                    $pid = $item['pid'];
                    if ($pid == 0) {
                        $category_list[] = $item;
                    } else {
                        $category_child_temp[$pid][] = $item;
                    }
                }
                foreach ($category_list as $index => $item) {
                    $category_list[$index]['child'] = isset($category_child_temp[$item['id']]) ? $category_child_temp[$item['id']] : [];
                }
            }

            $steps = 1;
            $this->view->assign('title', __('Submit work order'));
            $this->view->assign('category_list', $category_list);
        }

        // 第二步-推荐解决方案
        if ($category && ($steps != 3 || $keywords)) {
            $kbs_ids = Db::name('workorder_category')
                ->where('id', $category)
                ->where('status', '1')
                ->where('deletetime', null)
                ->value('kbs_ids');

            $kbs = [];
            if ($kbs_ids) {
                $where['id']         = ['in', $kbs_ids];
                $where['status']     = '1';
                $where['deletetime'] = null;
                if ($keywords) {
                    $where['title'] = ['like', '%' . $keywords . '%'];
                }

                $kbs = Db::name('workorder_kbs')
                    ->field('id,title,views,likes,url')
                    ->where($where)
                    ->order('weigh desc')
                    ->limit(20)
                    ->select();
            }

            $submit_channel = Db::name('workorder_submit_channel')->where('status', 1)->order('weigh desc')->select();
            foreach ($submit_channel as $index => $item) {
                $submit_channel[$index]['url'] = $this->handleUrl($item['url'], $category);
            }

            $steps = 2;
            $this->view->assign('kbs', $kbs);
            $this->view->assign('kbs_count', count($kbs));
            $this->view->assign('title', __('Recommended solutions'));
            $this->view->assign('submit_channel', $submit_channel);
            $this->view->assign('search_kbs', $keywords ? true : false);
        }

        // 第三步-创建工单
        if ($category && $steps == 3) {
            $fields        = Orders::getFields(null, 0);
            $category_name = Db::name('workorder_category')
                ->where('id', $category)
                ->where('status', '1')
                ->where('deletetime', null)
                ->value('name');

            if (!$category_name) {
                $this->error(__('Product / service classification not found~'));
            }

            if ($this->request->isPost()) {
                $token = $this->request->post('__token__');
                if (session('__token__') != $token) {
                    $this->error(__('Token incorrect!'), null, ['token' => $this->request->token()]);
                }

                $row    = $this->request->post('row/a');
                $origin = $this->request->post('row/a', [], 'trim');

                // 要入沟通记录的字段-所有文件自动入沟通记录
                $recordField = [
                    'describe'     => '0',// 描述-富文本
                    'confidential' => '4',// 机密信息-机密信息
                ];
                $records     = [];

                foreach ($fields as $index => $field) {
                    if ($field['isrequire'] && (!isset($row[$field['name']]) || $row[$field['name']] == '')) {
                        $this->error(__('%s can not be empty!', $field['title']), null, ['token' => $this->request->token()]);
                    }

                    if ($field['type_list'] == 'editor') {
                        if (function_exists('xss_clean')) {
                            $row[$field['name']] = isset($origin[$field['name']]) ? xss_clean($origin[$field['name']]) : '';
                        } else {
                            $row[$field['name']] = isset($origin[$field['name']]) ? General::removeXss($origin[$field['name']]) : '';
                        }
                    }

                    if (array_key_exists($field['name'], $recordField) && isset($row[$field['name']]) && $row[$field['name']]) {
                        $records[] = [
                            'user_id'      => $this->auth->id,
                            'message_type' => $recordField[$field['name']],
                            'message'      => $row[$field['name']]
                        ];
                    }

                    if (in_array($field['type_list'], $this->fileField) && isset($row[$field['name']]) && $row[$field['name']]) {
                        $attachment = explode(',', $row[$field['name']]);
                        if ($field['type_list'] == 'image' || $field['type_list'] == 'images') {
                            $message_type = 1;
                        } else {
                            $message_type = 2;
                        }
                        foreach ($attachment as $index => $item) {
                            $records[] = [
                                'user_id'      => $this->auth->id,
                                'message_type' => $message_type,
                                'message'      => $item
                            ];
                        }
                    }
                }
                $row['user_id']     = $this->auth->id;
                $row['category_id'] = $category;
                $row['status']      = 0;
                $row['createtime']  = time();
                $row['updatetime']  = time();

                try {
                    $order = Orders::create($row);
                    if ($records) {
                        foreach ($records as $index => $record) {
                            $records[$index]['batch']    = 1;
                            $records[$index]['order_id'] = $order->id;
                        }
                        $recordsModel = new Records;
                        $recordsModel->saveAll($records);
                    }

                    // 分派工单
                    $engineerId = $this->distribution($order);

                    // 准备记录结单和首回耗时
                    $timeStatistics[0]         = [
                        'type'        => 0,
                        'order_id'    => $order->id,
                        'engineer_id' => $engineerId,
                        'starttime'   => time()
                    ];
                    $timeStatistics[1]         = $timeStatistics[0];
                    $timeStatistics[1]['type'] = 2;
                    Db::name('workorder_time_statistics')->insertAll($timeStatistics);

                } catch (Exception $e) {
                    $this->error("error:" . $e->getMessage());
                }

                $this->success(__('Submitted successfully~'), url('index/workorder/detail', ['id' => $order->id]));
            }

            $urgentrank = Db::name('workorder_urgentrank')
                ->where('status', '1')
                ->where('deletetime', null)
                ->order('weigh desc')
                ->select();
            if (!$urgentrank) {
                $this->error(__('Emergency level of no work order available!'));
            }

            $this->view->assign('fields', $fields);
            $this->view->assign('urgentrank', $urgentrank);
            $this->view->assign('title', __('Create work order'));
            $this->view->assign('category_name', $category_name);
        }

        $this->view->assign('category', $category);
        $this->view->assign('steps', isset($steps) ? $steps : 1);
        return $this->view->fetch();
    }

    protected function distribution($order)
    {
        if (isset($order->engineer_id) && $order->engineer_id) {
            return false;
        } elseif (!$order->category_id) {
            return false;
        }

        $distribution_engineer = null;
        $where['status']       = '1';
        $where['user_id']      = ['<>', $this->auth->id];

        if ($this->workorderConfig['distribution_type'] == 2) {
            // 技能分派-循环
            $category_engineer = Db::name('workorder_category')->where('id', $order->category_id)->value('we_ids');
            if (!$category_engineer) {
                return false;
            }
            $where['id']                                = ['in', $category_engineer];
            $this->workorderConfig['distribution_type'] = 0;
        } elseif ($this->workorderConfig['distribution_type'] == 3) {
            // 技能分派-负载
            $category_engineer = Db::name('workorder_category')->where('id', $order->category_id)->value('we_ids');
            if (!$category_engineer) {
                return false;
            }
            $where['id']                                = ['in', $category_engineer];
            $this->workorderConfig['distribution_type'] = 1;
        }

        if ($this->workorderConfig['distribution_type'] == 0) {
            $distribution_engineer = Engineer::where($where)->order('lastreceivetime asc')->find();
        } elseif ($this->workorderConfig['distribution_type'] == 1) {

            $engineer = Engineer::where($where)->select();
            foreach ($engineer as $index => $item) {
                $orderNumber = Orders::where('engineer_id', $item->id)->count();
                if ($orderNumber == 0) {
                    $distribution_engineer = $item;
                    break;
                } else {
                    if (isset($minOrder)) {
                        if ($orderNumber < $minOrder) {
                            $minOrder = $orderNumber;
                        }
                    } else {
                        $distribution_engineer = $item;
                        $minOrder              = $orderNumber;
                    }
                }
            }
        }

        if (!$distribution_engineer) {
            return false;
        }

        $distribution_engineer->lastreceivetime = time();
        $distribution_engineer->work_order_quantity++;
        $distribution_engineer->save();
        $order->engineer_id = $distribution_engineer->id;
        $order->status      = 1;
        $order->save();

        // 发送通知
        $General = General::instance($this->workorderConfig);
        $General->mailNotice($order, 'engineer_new_order', '【新的工单】' . $order->title, '用户提交了新的工单:' . $order->title . ' 请尽快处理。');
        $General->smsNotice($order, 'engineer_new_order');
        return $distribution_engineer->id;
    }

    public function kbs()
    {
        $id       = $this->request->param('id');
        $category = $this->request->param('category');
        $kbs      = Db::name('workorder_kbs')
            ->where('id', $id)
            ->where('status', '1')
            ->where('deletetime', null)
            ->find();
        if (!$kbs) {
            $this->error(__('I cant find the knowledge~'), url('index/workorder/create'));
        }

        if ($this->request->isPost()) {
            $type = $this->request->param('type');
            if ($type == 'likes' || $type == 'dislikes') {
                $cookieName         = 'workorder_kbs_' . $type . '_cookie';
                $workorderKbsCookie = \think\Cookie::get($cookieName);
                if ($workorderKbsCookie) {
                    $workorderKbsCookieArr = explode('|', $workorderKbsCookie);
                    if (in_array($id, $workorderKbsCookieArr)) {
                        $this->error('您已经点' . ($type == 'likes' ? '赞' : '踩') . '过了!');
                    }
                }
                Db::name('workorder_kbs')->where('id', $id)->setInc($type);
                $workorderKbsCookie .= $id . '|';
                \think\Cookie::set($cookieName, $workorderKbsCookie, 315360000);
                $this->success();
            }
        }

        $kbs['createtime'] = date('Y-m-d H:i:s', $kbs['createtime']);

        // 推荐知识点
        $rec_kbs = [];
        if ($category) {
            $kbs_ids = Db::name('workorder_category')
                ->where('id', $category)
                ->where('status', '1')
                ->where('deletetime', null)
                ->value('kbs_ids');
            if ($kbs_ids) {
                $rec_kbs = Db::name('workorder_kbs')
                    ->field('id,title,url')
                    ->where('id', 'in', $kbs_ids)
                    ->where('status', '1')
                    ->where('deletetime', null)
                    ->where('id', '<>', $id)
                    ->order('weigh desc')
                    ->limit(20)
                    ->select();
            }
        }
        if (!$rec_kbs) {
            $rec_kbs = Db::name('workorder_kbs')
                ->field('id,title')
                ->where('status', '1')
                ->where('deletetime', null)
                ->where('id', '<>', $id)
                ->order('weigh desc,views desc')
                ->limit(20)
                ->select();
        }

        Db::name('workorder_kbs')->where('id', $id)->setInc("views", 1);

        $this->view->assign('kbs', $kbs);
        $this->view->assign('rec_kbs', $rec_kbs);
        $this->view->assign('title', $kbs['title']);
        $this->view->assign('category', $category);
        return $this->view->fetch();
    }

    public function icon()
    {
        $suffix = $this->request->param("suffix");
        header('Content-type: image/svg+xml');
        $suffix = $suffix ? $suffix : "FILE";
        echo General::build_suffix_image($suffix);
        exit;
    }

    private function handleStatus($status, $isEngineer = false)
    {
        $colors = [
            'info',
            'info',
            'warning',
            'danger',
            'danger',
            'success'
        ];

        $statusLang = __('Status ' . $status);
        if ($isEngineer) {
            switch ($statusLang) {
                case '待您反馈':
                    $statusLang = __('Waiting for user feedback');
                    break;
                case '待评价':
                    $statusLang = __('To be evaluated by users');
                    break;
                case '待工程师回复':
                    $statusLang = __('Waiting for your reply');
                    break;
            }
        }

        return [
            'pc'     => '<span class="text-' . $colors[$status] . '">' . $statusLang . '</span>',
            'h5'     => '<span class="text-' . $colors[$status] . '">[' . $statusLang . ']</span>',
            'number' => $status
        ];
    }

    private function handleUrl($url, $category)
    {
        if (preg_match('/^https?:\/\//i', $url)) {
            if (strpos($url, '?') === false) {
                $url .= '?category=' . $category;
            } else {
                $url .= '&category=' . $category;
            }
            return $url;
        } else {
            return url($url, ['category' => $category]);
        }
    }
}