Mission.php 42.0 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
<?php

namespace app\api\controller\v7\inspection;

use app\admin\model\Admin;
use app\admin\model\inspection\Areaitem;
use app\admin\model\inspection\Plan;
use app\admin\model\inspection\Project;
use app\admin\model\inspection\Projectitem;
use app\admin\model\inspection\Staff;
use app\admin\model\inspection\Warning;
use app\admin\model\inspection\Warningcategory;
use app\admin\model\inspection\Warningreply;
use app\admin\model\inspection\Workorder;
use app\admin\model\inspection\Workorderdeal;
use app\admin\model\notices\Noticesnormal;
use app\admin\model\User;
use app\common\controller\Api;
use think\Db;
use think\Exception;
use think\exception\PDOException;

/**
 * 巡检任务相关接口
 * Class Mission
 * @package app\api\controller\v7\inspection
 */
class Mission extends Api
{
//    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $statusList = [
        '-1' => '漏检',
        '0' => '进行中',
        '1' => '已巡检',
        '2' => '跳捡'
    ];

    protected $stateList = [
        '0' => '进行中',
        '1' => '正常',
        '2' => '异常'
    ];

    protected $circleTypeList = [
        '1' => '日计划',
        '2' => '周计划',
        '3' => '月计划'
    ];

    protected $itemTypeList = [
        '1' => '正常/异常',
        '2' => '数据',
    ];

    protected $warningStatusList = [
        '-1' => '审核失败',
        '0' => '待审核',
        '1' => '审核通过',
        '2' => '处理完成',
    ];

    protected $workorderStatusList = [
        '0' => '待处理',
        '1' => '待审核',
        '2' => '已处理',
        '3' => '审核未通过',
        '4' => '无法处理',
    ];
    protected $staffInfo;

    public function _initialize()
    {
        parent::_initialize();
        $staffModel = new \app\admin\model\inspection\Staff();
        $staffInfo = $staffModel->where(['user_id' => $this->auth->id])->find();
        $this->staffInfo = $staffInfo;
    }

    //首页统计工单数量和任务数量
    public function index(){
        //获取工单数量
        $where = [
            'status' => 0,
            'staff_id' => $this->staffInfo->id,
        ];
        $workorderModel = new Workorder();
        $workorder_num = $workorderModel
            ->where($where)
            ->count();
        //获取当天任务数量
        $datetime = strtotime(date('Y-m-d'));
        $projectModel = new Project();
        $project_num = $projectModel
            ->where([
                'status' => 0,
                'state' => 0,
                'staff_id' => $this->staffInfo->id,
                'begintime' => ['egt', $datetime],
            ])
            ->count();
        $result = [
            'workorder_num' => $workorder_num,
            'project_num' => $project_num,
        ];
        $this->success('成功', $result);
    }

    //计划任务列表
    public function lists(){
        $params = $this->request->get();
        if (empty($params['datetime'])){
            //默认取当天0点的时间戳
            $datetime = strtotime(date('Y-m-d'));
        }else{
            $datetime = strtotime(date('Y-m-d', $params['datetime']));
        }
        //查询当前登录人员的员工staff_id
        $staffModel = new Staff();
        $staff = $staffModel
            ->field([
                'staff.*',
                'u.nickname',
                'u.avatar'
            ])
            ->alias('staff')
            ->join('user u','u.id=staff.user_id', 'LEFT')
            ->where(['user_id' => $this->auth->id])->find();//todo
        $where = [
            'p.staff_id' => $staff['id'],
            'p.begintime' => ['elt', $datetime + 24*3600 - 1],
            'p.endtime' => ['egt', $datetime],
        ];

        $whereOr = [
            'p.staff_id' => $staff['id'],
            'p.begintime' => ['elt', $datetime + 24*3600 - 1],
            'p.endtime' => null
        ];

        $plan = new Plan();
        $list = $plan
            ->field([
                'p.*',
                'r.route_name',
            ])
            ->alias('p')
            ->join('inspection_route r', 'r.id=p.route_id', 'LEFT')
            ->where(function ($query) use ($where) {
                $query->where($where);
            })
            ->whereOr(function ($query) use ($whereOr) {
                $query->where($whereOr);
            })
            ->select();

        $status1List = [];
        $status2List = [];
        $status3List = [];
        foreach ($list as $item){
            $item['circle_type_text'] = $this->circleTypeList[$item['circle_type']];
            //巡检人员信息
            $item['plan_staff_info'] = $staff;
            //查询当前计划下的所有任务,当前日期的任务
            $projects = (new Project())
                ->where([
                    'plan_id' => $item['id'],
                    'begintime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
                ])
                ->select();
            $totalProjectNum = count($projects);
            $finishProjectNum = 0;
            foreach ($projects as $project){
                if ($project['status'] != 0){
                    $finishProjectNum++;
                }
            }
            $item['total_project_num'] = $totalProjectNum;
            $item['finish_project_num'] = $finishProjectNum;
            if ($finishProjectNum == 0){
                //未开始
                $status1List[] = $item;
            } elseif ($finishProjectNum == $totalProjectNum){
                //已完成
                //完成率统计
                $completionRate = 0;
                foreach ($projects as $pro){
                    if ($pro['status'] == 1){
                        $completionRate++;
                    }
                }
                if ($totalProjectNum == 0){
                    $item['completion_rate'] = '0.00%';
                }else{
                    $item['completion_rate'] = round(($completionRate / $totalProjectNum) * 100, 2) . '%';
                }
                //总里程统计
                $totalDistance = Db::name('inspection_position')
                    ->where([
                        'plan_id' => $item['id'],
                        'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
                    ])
                    ->sum('distance');
                $item['total_distance'] = bcdiv($totalDistance, 1000, 3) . 'km';
                //总时长统计
                $totalTime = Db::name('inspection_position')
                    ->where([
                        'plan_id' => $item['id'],
                        'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
                    ])
                    ->sum('times');
                $item['total_time'] = $this->convertSecondsToHMS($totalTime);
                $status3List[] = $item;
            } else {
                //进行中
                $status2List[] = $item;
            }
        }

        $result = [
            'status1' => $status1List,
            'status2' => $status2List,
            'status3' => $status3List,
        ];

        $this->success('成功', $result);
    }

    //获取计划任务详情
    public function planDetail(){
        $params = $this->request->get();
        if (empty($params['datetime'])){
            //默认取当天0点的时间戳
            $datetime = strtotime(date('Y-m-d'));
        }else{
            $datetime = strtotime(date('Y-m-d', $params['datetime']));
        }
        if (empty($params['plan_id'])){
            $this->error('计划ID必须');
        }
        $planModel = new Plan();
        $plan = $planModel->where(['id' => $params['plan_id']])->field('id,plan_name,staff_id')->find();
        if (!$plan){
            $this->error('计划不存在');
        }
        //查询当前登录人员的员工staff_id
        $staffModel = new Staff();
        $staff = $staffModel
            ->field([
                'staff.*',
                'u.nickname',
                'u.avatar'
            ])
            ->alias('staff')
            ->join('user u','u.id=staff.user_id', 'LEFT')
            ->where(['user_id' => $this->auth->id])->find();//todo

        $plan['staff_info'] = $staff;

        //总里程统计
        $totalDistance = Db::name('inspection_position')
            ->where([
                'plan_id' => $plan['id'],
                'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
            ])
            ->sum('distance');
        $plan['total_distance'] = bcdiv($totalDistance, 1000, 3) . 'km';
        //开始位置
        $startPosition = Db::name('inspection_position')
            ->field('lng,lat')
            ->where([
                'plan_id' => $plan['id'],
                'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
            ])
            ->order(['createtime' => 'asc'])
            ->find();
        if ($startPosition){
            $plan['start_lng'] = $startPosition['lng'];
            $plan['start_lat'] = $startPosition['lat'];
        }else{
            $plan['start_lng'] = 0;
            $plan['start_lat'] = 0;
        }

        //结束位置
        $endPosition = Db::name('inspection_position')
            ->field('lng,lat')
            ->where([
                'plan_id' => $plan['id'],
                'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
            ])
            ->order(['createtime' => 'desc'])
            ->find();
        if ($endPosition){
            $plan['end_lng'] = $endPosition['lng'];
            $plan['end_lat'] = $endPosition['lat'];
        }else{
            $plan['end_lng'] = 0;
            $plan['end_lat'] = 0;
        }
        //总时长统计
        $minTime = Db::name('inspection_position')
            ->where([
                'plan_id' => $plan['id'],
                'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
            ])
            ->min('createtime');
        $maxTime = Db::name('inspection_position')
            ->where([
                'plan_id' => $plan['id'],
                'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
            ])
            ->max('createtime');
        $totalTime = Db::name('inspection_position')
            ->where([
                'plan_id' => $plan['id'],
                'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
            ])
            ->sum('times');
        if ($minTime) {
            $plan['min_time'] = date('Y-m-d H:i:s', $minTime);
        }else{
            $plan['min_time'] = '--';
        }
        if ($maxTime) {
            $plan['max_time'] = date('Y-m-d H:i:s', $maxTime);
        }else{
            $plan['max_time'] = '--';
        }
        $plan['total_time'] = $this->convertSecondsToHMS($totalTime);
        //查询当前计划下的所有任务,当前日期的任务
        $projectIds = (new Project())
            ->where([
                'plan_id' => $plan['id'],
                'begintime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
            ])
            ->column('id');
        $warningNum = 0;
        $dealWarningNum = 0;
        if (!empty($projectIds)){
            $warningModel = new Warning();
            $workorderModel = new Workorder();
            //查询相关连的异常上报数量
            $warningIds = $warningModel->where(['project_id' => ['in', $projectIds]])->column('id');
            $warningNum = count($warningIds);
            if (!empty($warningIds)){
                $dealWarningNum = $workorderModel->where(['warning_id' => ['in', $warningIds], 'status' => '2'])->count();
            }
        }
        $notDealWarningNum = $warningNum - $dealWarningNum;
        $plan['warning_num'] = $warningNum;
        $plan['deal_warning_num'] = $dealWarningNum;
        $plan['not_deal_warning_num'] = $notDealWarningNum;
        $this->success('成功', $plan);
    }

    /**
     * 巡检轨迹
     */
    public function planDetailGuiji(){
        $params = $this->request->get();
        if (empty($params['datetime'])){
            //默认取当天0点的时间戳
            $datetime = strtotime(date('Y-m-d'));
        }else{
            $datetime = strtotime(date('Y-m-d', $params['datetime']));
        }
        if (empty($params['plan_id'])){
            $this->error('计划ID不能为空');
        }
        $planModel = new Plan();
        $plan = $planModel->where(['id' => $params['plan_id']])->field('id,plan_name,staff_id')->find();
        if (!$plan){
            $this->error('计划不存在');
        }

        //总里程统计
        $data = Db::name('inspection_position')
            ->where([
                'plan_id' => $plan['id'],
                'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
            ])
            ->field("lat,lng")->select();
        $this->success('成功', $data);
    }



    //任务点路线列表
    public function siteList(){
        $params = $this->request->get();

        if (empty($params['plan_id'])){
            $this->error('计划ID参数必须');
        }
        $plan_id = $params['plan_id'];

        if (empty($params['datetime'])){
            //默认取当天0点的时间戳
            $datetime = strtotime(date('Y-m-d'));
        }else{
            $datetime = strtotime(date('Y-m-d', $params['datetime']));
        }

        $where = [
            'p.plan_id' => $plan_id,
            'p.begintime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
        ];

        $project = new Project();
        $list = $project
            ->field([
                'p.*',
                'a.area_name',
                'pl.plan_name',
                'r.route_name',
                'asi.site_name',
                'asi.verify',
                'asi.lnglat',
                'asi.distance',
                'asi.qrcode_src',
            ])
            ->alias('p')
            ->join('inspection_route_site rs','rs.route_id=p.route_id and rs.area_site_id=p.area_site_id', 'LEFT')
            ->join('inspection_area a','a.id=p.area_id', 'LEFT')
            ->join('inspection_plan pl','pl.id=p.plan_id', 'LEFT')
            ->join('inspection_route r','r.id=p.route_id', 'LEFT')
            ->join('inspection_area_site asi','asi.id=p.area_site_id', 'LEFT')
            ->where($where)
            ->order(['rs.weigh' => 'asc', 'rs.createtime' => 'asc'])
            ->select();
        $projectItemModel = new Projectitem();
        $areaItemModel = new Areaitem();

        $timeDotArr = [];
        foreach ($list as $item){
            //统计任务对应检查项提交数量以及检查点数量
            $checkedNum = $projectItemModel->where(['project_id' => $item['id']])->count();
            $totalNum = $areaItemModel->where(['areasite_id' => $item['area_site_id']])->count();
            $item['checked_num'] = $checkedNum;
            $item['need_check_num'] = $totalNum;
            //查询当前任务的异常个数
            if ($item['state'] == 2){
                $warningModel = new Warning();
                $item['warning_num'] = $warningModel->where(['project_id' => $item['id']])->count();
            }else{
                $item['warning_num'] = 0;
            }
            $itemArr = $item->toArray();
            if (isset($timeDotArr[$item['begintime']])){
                $timeDotArr[$item['begintime']][] = $itemArr;
            }else{
                $timeDotArr[$item['begintime']] = [$itemArr];
            }
        }

        $this->success('成功', $timeDotArr);
    }

    //根据巡检点id获取任务检查项信息
    public function getItemByAreasite()
    {
        $area_site_id = $this->request->param("id");
        if (empty($area_site_id)){
            $this->error('参数错误');
        }

        $itemModel = new Areaitem();
        $items = $itemModel
            ->where([
                'areasite_id' => $area_site_id
            ])
            ->order(['weigh' => 'asc', 'id' => 'asc'])
            ->select();
        if (empty($items)){
            $this->error('该巡检点暂无检查项目', []);
        }else{
            foreach ($items as $item){
                $item['type_text'] = $this->itemTypeList[$item['type']];
            }
        }

        //查询当前登录人员的员工staff_id
        $staffModel = new Staff();
        $staff = $staffModel
            ->field([
                'staff.*',
                'u.nickname',
                'u.avatar'
            ])
            ->alias('staff')
            ->join('user u','u.id=staff.user_id', 'LEFT')
            ->where(['user_id' => $this->auth->id])->find();//todo

        $datetime = strtotime(date('Y-m-d'));
        $projectModel = new Project();
        $projects = $projectModel
            ->field('id,begintime')
            ->where([
                'staff_id' => $staff['id'],
                'area_site_id' => $area_site_id,
                'begintime' => ['between',[$datetime, $datetime + 24*3600 -1]]
            ])
            ->select();
        $timeDotArr = [];
        $warningModel = new Warning();
        foreach ($projects as $project){
            $itemsData = [];
            foreach ($items as $ite){
                $iteArr = $ite->toArray();
                $iteArr['value'] = null;//前端需要,后端无用
                //查询是否提交过异常
                $has = $warningModel->where(['project_id' => $project['id'], 'areasite_id' => $area_site_id, 'areaitem_id' => $ite['id']])->find();
                if ($has){
                    $iteArr['has_warning'] = 1;
                }else{
                    $iteArr['has_warning'] = 0;
                }
                $itemsData[] = $iteArr;
            }
            $newData = [
                $project['id'] => $itemsData
            ];
            if (isset($timeDotArr[$project['begintime']])){
                $timeDotArr[$project['begintime']][] = $newData;
            }else{
                $timeDotArr[$project['begintime']] = [$newData];
            }
        }
        if (empty($timeDotArr)){
            $this->error('该巡检点暂无巡检任务', []);
        }
        $this->success('获取检查项成功', $timeDotArr);
    }

    //保存巡检结果
    public function saveProjectItem(){

        $params = $this->request->post();

        if (empty($params['id'])){
            $this->error('任务id必须');
        }

        $projectModel = Project::get($params['id']);
        if (!$projectModel){
            $this->error('任务不存在');
        }

        if ($projectModel['status'] > 0){
            $this->error('该巡检任务已完成,请勿重复提交');
        }
        if (empty($params['state'])){
            $this->error('任务状态state必须');
        }
        if (!in_array($params['state'], [1,2])){
            $this->error('任务状态state参数错误');
        }

        //检查项数据
        if (!empty($params['item_jsons'])){
            $items = $params['item_jsons'];
            if (!is_array($items)){
                $this->error('item_jsons数据格式不正确');
            }
            //验证
            foreach ($items as $it){
                if (empty($it['item_name'])){
                    $this->error('检查项名称不能为空');
                }
                if (empty($it['type']) || !in_array($it['type'], [1,2])){
                    $this->error('检查项类型参数错误');
                }
                if (empty($it['value'])){
                    $this->error('检查项的值必须');
                }
                if($it['type'] == 1){
                    if (!in_array($it['value'], [1,2])){
                        $this->error('检查项的值必须为1或2');
                    }
                }
            }
        }

        $data = [
            'checktime' => time(),
            'status' => 1,
            'state' => $params['state'],
        ];
        if (!empty($params['images'])){
            $data['images'] = $params['images'];
        }
        if (!empty($params['content'])){
            $data['content'] = $params['content'];
        }

        Db::startTrans();
        try {
            $projectModel->allowField(true)->save($data);
            //保存检查项
            $projectItemModel = new Projectitem();
            foreach ($items as $item){
                $item['project_id'] = $projectModel['id'];
                //判断是否提交过该项数据
                $find = $projectItemModel->where(['project_id' => $projectModel['id'], 'item_name' => $item['$item']])->find();
                if ($find){
                    continue;
                }
                $projectItemModel->allowField(true)->insert($item);
            }
            Db::commit();
        }catch (PDOException|Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功');
    }

    //记录行走路线点
    public function recordLngLat(){

        $params = $this->request->post();

        if (empty($params['plan_id'])){
            $this->error('计划ID必须');
        }

        if (!in_array($params['status'], [0,1])){
            $this->error('巡检状态status必须');
        }

        if (empty($params['lng'])){
            $this->error('经度必须');
        }

        if (empty($params['lat'])){
            $this->error('纬度必须');
        }
        //当前时间戳
        $ctime = time();
        //计算距离
        $distance = 0;
        //计算时间
        $times = 0;
        //获取当天0点的时间戳
        $datetime = strtotime(date('Y-m-d'));
        $preDot = Db::name('inspection_position')
            ->where([
                'plan_id' => $params['plan_id'],
                'createtime' => ['egt', $datetime]
            ])
            ->order(['createtime' => 'desc'])
            ->find();
        if ($preDot){
            if ($preDot['status'] == 1){
                $from = [$preDot['lng'],$preDot['lat']];
                $to = [$params['lng'],$params['lat']];
                $distance = $this->getDistance($from,$to,false,2);
                $times = bcsub($ctime, $preDot['createtime']);
            }
        }
        $data = [
            'plan_id' => $params['plan_id'],
            'lng' => $params['lng'],
            'lat' => $params['lat'],
            'distance' => $distance,
            'times' => $times,
            'createtime' => $ctime,
            'status' => $params['status'],
        ];
        $res = Db::name('inspection_position')->insert($data);
        if ($res){
            $this->success();
        }else{
            $this->error('定位记录失败');
        }
    }

    //根据计划ID和时间获取行走记录点
    public function getLngLat(){
        $params = $this->request->get();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 50;
        if (empty($params['datetime'])){
            //默认取当天0点的时间戳
            $datetime = strtotime(date('Y-m-d'));
        }else{
            $datetime = strtotime(date('Y-m-d', $params['datetime']));
        }
        if (empty($params['plan_id'])){
            $this->error('计划ID必须');
        }
        $plan = Plan::get($params['plan_id']);
        if (!$plan){
            $this->error('计划不存在');
        }

        $list = [];
        $total = Db::name('inspection_position')
            ->where([
                'plan_id' => $params['plan_id'],
                'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
            ])
            ->count();
        if ($total > 0){
            $list = Db::name('inspection_position')
                ->where([
                    'plan_id' => $params['plan_id'],
                    'createtime' => ['between', [$datetime, $datetime + 24*3600 - 1]]
                ])
                ->order(['createtime' => 'asc'])
                ->page($page, $limit)
                ->select();
        }

        $result = [
            'page' => $page,
            'limit' => $limit,
            'total' => $total,
            'rows' => $list,
        ];
        $this->success('成功', $result);
    }

    //隐患上报
    public function warningReport(){
        $params = $this->request->post();
        if (empty($params['title'])){
            $this->error('隐患标题必须');
        }
        if (empty($params['message'])){
            $this->error('预警信息必须');
        }
//        if (empty($params['project_id'])){
//            $this->error('任务ID必须');
//        }
//        if (empty($params['area_id'])){
//            $this->error('巡检区域ID必须');
//        }
//        if (empty($params['areasite_id'])){
//            $this->error('巡检点ID必须');
//        }
//        if (empty($params['areaitem_id'])){
//            $this->error('检查项ID必须');
//        }
        if (empty($params['category_id'])){
            $this->error('隐患分类ID必须');
        }
        if (empty($params['lng']) || empty($params['lat'])){
            $this->error('经纬度信息必须');
        }
        //查询当前登录人员的员工staff_id
        $staffModel = new Staff();
        $staff = $staffModel
            ->where(['user_id' => $this->auth->id])//todo
            ->find();
        if (!$staff){
            $this->error('没有找到您的员工信息');
        }
        $data = [
            'title' => $params['title'],
            'message' => $params['message'],
            'staff_id' => $staff['id'],
            'status' => '0',
            'createtime' => time(),
            'lng' => $params['lng'],
            'lat' => $params['lat'],
            'category_id' => $params['category_id'],
        ];
        if (!empty($params['area_id'])){
            $data['area_id'] = $params['area_id'];
        }
        if (!empty($params['areasite_id'])){
            $data['areasite_id'] = $params['areasite_id'];
        }
        if (!empty($params['areaitem_id'])){
            $data['areaitem_id'] = $params['areaitem_id'];
        }
        if (!empty($params['project_id'])){
            $data['project_id'] = $params['project_id'];
        }
        if (!empty($params['cover_images'])){
            $data['cover_images'] = $params['cover_images'];
        }
        $warningModel = new Warning();
        $result = $warningModel->allowField(true)->save($data);
        if ($result) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    //隐患再次上报
    public function warningReplay(){
        $params = $this->request->post();
        if (empty($params['wid'])){
            $this->error('隐患ID必须');
        }
        if (empty($params['reply'])){
            $this->error('回复内容必须');
        }
        $warning = Warning::get($params['wid']);
        if (!$warning){
            $this->error('隐患不存在');
        }
        //查询当前登录人员的员工staff_id
        $staffModel = new Staff();
        $staff = $staffModel
            ->where(['user_id' => $this->auth->id])//todo
            ->find();
        if (!$staff){
            $this->error('没有找到您的员工信息');
        }
        $data = [
            'wid' => $params['wid'],
            'reply' => $params['reply'],
            'staffid' => $staff['id'],
            'status' => '0',
            'createtime' => time(),
        ];
        $warningModel = new Warningreply();
        $result = $warningModel->allowField(true)->save($data);
        if ($result) {
            $this->success('提交成功');
        }
        $this->error('提交失败');
    }

    //获取隐患类型列表
    public function getWarningCategory(){
        $categoryModel = new Warningcategory();
        $pList = $categoryModel->field('id,name')->where(['show_switch' => 1, 'level' => 1])->select();
        if (!empty($pList)){
            foreach ($pList as $p){
                $children = $categoryModel->field('id,name')->where(['show_switch' => 1, 'level' => 2, 'pid' => $p['id']])->select();
                if ($children){
                    $p['children'] = $children;
                }else{
                    $p['children'] = [];
                }
            }
        }else{
            $pList = [];
        }
        $this->success('成功', $pList);
    }

    //获取隐患上报情况列表
    public function getWarningList(){
        $params = $this->request->get();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        if (!in_array($params['status'], [0,1,2])){
            $this->error('status参数错误');
        }
        //查询当前登录人员的员工staff_id
        $staffModel = new Staff();
        $staff = $staffModel
            ->where(['user_id' => $this->auth->id])//todo
            ->find();
        if (!$staff){
            $this->error('没有找到您的员工信息');
        }
        $where = [
            'w.staff_id' => $staff['id']
        ];
        if ($params['status'] != '0'){
            $where['w.status'] = $params['status'].'';
        }
        $warningModel = new Warning();

        $total = $warningModel
            ->alias('w')
            ->field([
                'w.*',
                'a.area_name',
                's.site_name',
                'i.item_name',
                'c.name as category_name',
                'c_p.name as category_pname',
            ])
            ->join('inspection_area a', 'a.id=w.area_id', 'LEFT')
            ->join('inspection_area_site s', 's.id=w.areasite_id', 'LEFT')
            ->join('inspection_area_item i', 'i.id=w.areaitem_id', 'LEFT')
            ->join('inspection_warning_category c', 'c.id=w.category_id', 'LEFT')
            ->join('inspection_warning_category c_p', 'c_p.id=c.pid', 'LEFT')
            ->where($where)
            ->count();
        $list = [];
        if ($total > 0){
            $list = $warningModel
                ->alias('w')
                ->field([
                    'w.*',
                    'a.area_name',
                    's.site_name',
                    'i.item_name',
                    'c.name as category_name',
                    'c_p.name as category_pname',
                ])
                ->join('inspection_area a', 'a.id=w.area_id', 'LEFT')
                ->join('inspection_area_site s', 's.id=w.areasite_id', 'LEFT')
                ->join('inspection_area_item i', 'i.id=w.areaitem_id', 'LEFT')
                ->join('inspection_warning_category c', 'c.id=w.category_id', 'LEFT')
                ->join('inspection_warning_category c_p', 'c_p.id=c.pid', 'LEFT')
                ->where($where)
                ->order(['createtime' => 'desc'])
                ->page($page,$limit)
                ->select();
            foreach ($list as $item){
                $item['staff_info'] = $staff;
                $item['status_value'] = $this->warningStatusList[$item['status']];
            }
        }
        $result = [
            'page' => $page,
            'limit' => $limit,
            'total' => $total,
            'rows' => $list,
        ];
        $this->success('成功', $result);
    }

    //根据隐患ID获取隐患上报详情
    public function getWarningDetail(){
        $params = $this->request->get();
        if (empty($params['id'])){
            $this->error('id参数必须');
        }
        $warningModel = new Warning();
        $warning = $warningModel
            ->alias('w')
            ->field([
                'w.*',
                'a.area_name',
                's.site_name',
                'i.item_name',
                'c.name as category_name',
                'c_p.name as category_pname',
            ])
            ->join('inspection_area a', 'a.id=w.area_id', 'LEFT')
            ->join('inspection_area_site s', 's.id=w.areasite_id', 'LEFT')
            ->join('inspection_area_item i', 'i.id=w.areaitem_id', 'LEFT')
            ->join('inspection_warning_category c', 'c.id=w.category_id', 'LEFT')
            ->join('inspection_warning_category c_p', 'c_p.id=c.pid', 'LEFT')
            ->where([
                'w.id' => $params['id']
            ])
            ->find();
        if ($warning){
            //查询员工staff_id
            $staffModel = new Staff();
            $warning['staff_info'] = $staffModel
                ->where(['id' => $warning['staff_id']])
                ->find();
            $warning['status_value'] = $this->warningStatusList[$warning['status']];
            //查询回复数据
            $warningReplyModel = new Warningreply();
            $warning['reply_record'] = $warningReplyModel->where(['wid' => $warning['id']])->order(['createtime' => 'desc'])->select();
            $this->success('成功', $warning);
        }else{
            $this->error('隐患不存在');
        }
    }

    // 根据状态获取工单列表
    public function getWorkorder(){
        $params = $this->request->get();
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;
        if (empty($params['status']) || !in_array($params['status'], [1,2,3,4])){
            $this->error('status参数错误');
        }

        $where = [];
        if (!empty($params['datetime'])){
            $datetime = strtotime(date('Y-m-d', $params['datetime']));
            $where = [
                'start_time' => ['elt', $datetime + 24*3600 -1],
                'end_time' => ['egt', $datetime],
            ];
        }

        if ($params['status'] == 3){
            $where['status'] = ['in', ['0','3']];
        }else{
            $where['status'] = $params['status'].'';
        }

        //查询处理人员信息
        $staffModel = new Staff();
        $staff = $staffModel
            ->alias('s')
            ->field([
                's.*',
                'u.nickname',
                'u.avatar'
            ])
            ->join('user u','u.id=s.user_id', 'LEFT')
            ->where([
                's.user_id' => $this->auth->id
            ])
            ->find();
        $where['staff_id'] = $staff['id'];

        $workorderModel = new Workorder();
        $total = $workorderModel
            ->where($where)
            ->count();
        $list = [];
        if ($total > 0){
            $list = $workorderModel
                ->where($where)
                ->order(['id' => 'desc'])
                ->page($page, $limit)
                ->select();
            foreach ($list as $item){
                $item['status_value'] = $this->workorderStatusList[$item['status']];
                //查询异常报告信息
                $warningModel = new Warning();
                $warning = $warningModel
                    ->alias('w')
                    ->field([
                        'w.*',
                        'a.area_name',
                        's.site_name',
                        'i.item_name',
                        'wc.name as category_name',
                    ])
                    ->join('inspection_area a','a.id=w.area_id', 'LEFT')
                    ->join('inspection_area_site s','s.id=w.areasite_id', 'LEFT')
                    ->join('inspection_area_item i','i.id=w.areaitem_id', 'LEFT')
                    ->join('inspection_warning_category wc','wc.id=w.category_id', 'LEFT')
                    ->where([
                        'w.id' => $item['warning_id']
                    ])
                    ->find();
                $item['warning_info'] = $warning;
                $item['staff_info'] = $staff;
                //如果状态为无法处理,则获取无法处理的内容
                if ($item['status'] == 4){
                    $dealModel = new Workorderdeal();
                    $deal = $dealModel
                        ->where(['workorder_id' => $item['id']])
                        ->order(['id' => 'desc'])
                        ->select();
                    $item['deal_info'] = $deal;
                }
            }
        }

        $result = [
            'page' => $page,
            'limit' => $limit,
            'total' => $total,
            'rows' => $list,
        ];

        $this->success('成功', $result);
    }

    // 根据工单ID获取详情
    public function getWorkorderDetail(){
        $id = $this->request->get('id');
        if (empty($id)){
            $this->error('工单id必须');
        }
        
        $workorder = Workorder::get($id);
        if (!$workorder){
            $this->error('工单不存在');
        }

        $workorder['status_value'] = $this->workorderStatusList[$workorder['status']];
        //查询异常报告信息
        $warningModel = new Warning();
        $warning = $warningModel
            ->alias('w')
            ->field([
                'w.*',
                'a.area_name',
                's.site_name',
                'i.item_name',
                'wc.name as category_name',
            ])
            ->join('inspection_area a','a.id=w.area_id', 'LEFT')
            ->join('inspection_area_site s','s.id=w.areasite_id', 'LEFT')
            ->join('inspection_area_item i','i.id=w.areaitem_id', 'LEFT')
            ->join('inspection_warning_category wc','wc.id=w.category_id', 'LEFT')
            ->where([
                'w.id' => $workorder['warning_id']
            ])
            ->find();
        $workorder['warning_info'] = $warning;
        //查询处理人员信息
        $staffModel = new Staff();
        $staff = $staffModel
            ->alias('s')
            ->field([
                's.*',
                'u.nickname',
                'u.avatar'
            ])
            ->join('user u','u.id=s.user_id', 'LEFT')
            ->where([
                's.id' => $workorder['staff_id']
            ])
            ->find();
        $workorder['staff_info'] = $staff;
        //获取工单处理结果
        $workorderdealModel = new Workorderdeal();
        $workorderdeal = $workorderdealModel
            ->where([
                'workorder_id' => $workorder['id']
            ])
            ->order([
                'id' => 'desc'
            ])
            ->select();
        $workorder['deal_info'] = $workorderdeal;
        $this->success('成功', $workorder);
    }

    //处理工单结果
    public function dealWorkorder(){
        $params = $this->request->post();
        if (empty($params['workorder_id'])){
            $this->error('工单id必须');
        }
        $workorder = Workorder::get($params['workorder_id']);
        if (!$workorder){
            $this->error('工单不存在');
        }

        if (!in_array($workorder['status'], ['0','3'])){
            $this->error('工单已处理,无需重复操作');
        }

        if (empty($params['status']) || !in_array($params['status'], [1,4])){
            $this->error('status参数错误');
        }

        if (empty($params['message'])){
            $this->error('处理问题描述信息必须');
        }

        $data = [
            'workorder_id' => $workorder['id'],
            'message' => $params['message'],
            'images' => $params['images'],
            'files' => $params['files'],
            'staff_id' => $workorder['staff_id'],
        ];

        if (!empty($params['start_time'])){
            $data['start_time'] = $params['start_time'];
        }else{
            $data['start_time'] = $workorder['start_time'];
        }
        if (!empty($params['end_time'])){
            $data['end_time'] = $params['end_time'];
        }else{
            $data['end_time'] = $workorder['end_time'];
        }

        Db::startTrans();
        try {
            $workorderdeal = new Workorderdeal();
            $result = $workorderdeal->allowField(true)->save($data);
            if ($result){
                $workorder->allowField(true)->save(['status' => $params['status'].'']);
            }
            Db::commit();
        }catch (PDOException|Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('提交成功');
    }

    /**
     * 判断经纬度是否在范围之内
     */
    public function checkLnglat()
    {
        $id = $this->request->param("id");
        $lng = $this->request->param("lng");
        $lat = $this->request->param("lat");

        $project = new \addons\inspection\service\Project();

//        , "project.begintime" => ['elt', time()], "project.endtime" => ['egt', time()]
        $where = ['plan.staff_id' => $this->staffInfo['id'], 'project.id' => $id];
        $projectInfo = $project->getProjectInfo($where);
        if (empty($projectInfo)) {
            $this->error("当前巡检任务不存在");
        }
        if ($projectInfo['verify'] == 1) {
            $lnglat = $projectInfo['lnglat'];
            $lnglat_arr = explode(",", $lnglat);
            $distance = $project->checkDistance($lng, $lat, empty($lnglat_arr[0]) ? '' : $lnglat_arr[0], empty($lnglat_arr[1]) ? '' : $lnglat_arr[1]);
            if ($distance > $projectInfo['distance']) {
                $this->error("当前定位不在允许范围之内");
            } else {
                $this->success("请求成功");
            }
        } else {
            $this->error("当前巡检任务不需要验证定位");
        }

    }

    /**
     * 根据起点坐标和终点坐标测距离
     * @param  [array]   $from  [起点坐标(经纬度),例如:array(118.012951,36.810024)]
     * @param  [array]   $to    [终点坐标(经纬度)]
     * @param  [bool]    $km        是否以公里为单位 false:米 true:公里(千米)
     * @param  [int]     $decimal   精度 保留小数位数
     * @return [string]  距离数值
     */
    public function getDistance($from,$to,$km=true,$decimal=2){
        sort($from);
        sort($to);
        $EARTH_RADIUS = 6370.996; // 地球半径系数

        $distance = $EARTH_RADIUS*2*asin(sqrt(pow(sin( ($from[0]*pi()/180-$to[0]*pi()/180)/2),2)+cos($from[0]*pi()/180)*cos($to[0]*pi()/180)* pow(sin( ($from[1]*pi()/180-$to[1]*pi()/180)/2),2)))*1000;

        if($km){
            $distance = $distance / 1000;
        }

        return round($distance, $decimal);
    }

    /**
     * 把秒时长转换成格式化H:i:s格式返回
     * @param int $seconds 秒时长
     * @return string 返回格式化时长H:i:s
     */
    public function convertSecondsToHMS(int $seconds) {
        $hours = floor($seconds / 3600);
        $minutes = floor(($seconds / 60) % 60);
        $seconds = $seconds % 60;

        return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
    }
}