FaultController.php 33.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
<?php

namespace app\ht\modules\device\controllers;

use Yii;
use yii\base\Exception;
use yii\log\Logger;
use yii\data\Pagination;
use app\ht\controllers\BaseController;
use app\ht\helpers\Sort;
use common\business\WarrantyLevelRule;
use common\models\DeviceFault                   as DeviceFaultModel;
use common\models\ModelsRepairPlanPrices        as ModelsRepairPlanPricesModel;
use common\models\RegionFeeSetting              as RegionFeeSettingModel;
use common\models\RepairOrderUserSelectFaults   as RepairOrderUserSelectFaultsModel;
use common\models\RepairPlan                    as RepairPlanModel;
use domain\device\models\Device                 as DeviceModel;
use domain\device\models\ModelsDeviceFaults     as ModelsDeviceFaultsModel;
use domain\device\DeviceCatRepository;
use stdClass;
use function intval;
use function time;
use function in_array;
use function array_key_exists;
use function explode;
use function bccomp;
use function print_r;

/**
 * 故障管理控制器
 * Class FaultController
 * @package app\ht\modules\device\controllers
 */
class FaultController extends BaseController
{
    public function actionIndex()
    {
        $params = $this->dataList();
        #$params['brandList'] = Brand::find(["is_available"=>1])->select("id,english_name,chinese_name")->asArray()->all();
        /**
         * 渲染模板
         */
        return $this->render('index', $params);
    }

    public function actionCreate()
    {
        $params = array();
        #$params['brandList'] = Brand::find(["is_available"=>1])->select("id,english_name,chinese_name")->asArray()->all();
        return $this->render('create',$params);
    }

    /**
     * 执行添加
     */
    public function actionDoAdd()
    {
        $post = Yii::$app->request->post();
        $parentId = $post['parentId'];    // 上级ID
        $childId = $post['childId'];      // 下级ID
        $faultName = $post['faultName'];  // 故障名称
        $isCommon = $post['isCommon'];    // 是否常见故障
        $sortOrder = $post['sortOrder'];  // 故障排序

        $deviceFault = new DeviceFaultModel();
        $deviceFault->name = $faultName;
        // 如果没有二级类型,就使用一级类型??? 可能需要限制必须二级分类
        if (empty($childId)) {
            $deviceFault->device_cat_id = $parentId;
        } else {
            $deviceFault->device_cat_id = $childId;
        }
        $deviceFault->is_common = empty($isCommon) ? 0:1;
        $deviceFault->sort_order = empty($sortOrder) ? 1:$sortOrder;
        $deviceFault->version = Yii::$app->params['DATA_VERSION'];

        $result = $deviceFault->insert();

        $msg = array();
        if ($result) {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

        return $this->renderJson($msg);
    }

    /**
     * 更新故障
     * @return string
     */
    public function actionUpdate()
    {
        $req = Yii::$app->request->get();
        $faultId = $req['id'];

        // 获取故障
        $fault = DeviceFaultModel::findOne(["id"=>$faultId])->toArray();

        // 获取故障对应的分类信息
        $deviceCat = DeviceCatRepository::selectOne(intval($fault['device_cat_id']));
        $catPid = $deviceCat->parent_id;
        $catId  = $deviceCat->id;

        // 获取父级分类
        $deviceCatParentList = DeviceCatRepository::getTopParentCats();
        // 获取子级分类
        $deviceCatChildList = DeviceCatRepository::getSubCatsByParentId($catPid);

        $params = array();
        //$params['brandList'] = Brand::find(["is_available"=>1])->select("id,english_name,chinese_name")->asArray()->all();
        $params['fault']    = $fault;
        $params['catPid']   = $catPid;
        $params['catId']    = $catId;
        $params['deviceCatParentList']  = $deviceCatParentList;
        $params['deviceCatChildList']   = $deviceCatChildList;

        return $this->render('update',$params);
    }

    /**
     * 执行更新
     * @return string
     */
    public function actionDoUpdate()
    {
        $post = Yii::$app->request->post();

        $faultId = $post['faultId'];        //要修改故障ID
        $childId = $post['childId'];        //下级ID
        $faultName = $post['faultName'];   //故障名称
        $isCommon = $post['isCommon'];     //是否常见故障
        $sortOrder = $post['sortOrder'];  //故障排序

        $deviceFaultModel = DeviceFaultModel::findOne(["id"=>$faultId]);
        $deviceFaultModel->device_cat_id = intval($childId);
        $deviceFaultModel->name = $faultName;
        $deviceFaultModel->updated_at = time();
        $deviceFaultModel->is_common = empty($isCommon) ? 0:1;
        $deviceFaultModel->sort_order = empty($sortOrder) ? 1:$sortOrder;
        $result = $deviceFaultModel->save();

        $msg = array();
        if ($result) {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

        return $this->renderJson($msg);
    }

    /**
     * @return
     * 删除故障, 需要检查关联表是否有数据
     */
    public function actionDelete()
    {
        // 1	11	打印空白	0	1492854426	1492936510
        //repair_order_user_select_faults
        //repair_plan
        //models_device_faults
        $req = Yii::$app->request;
        $id = $req->get('id');

        $result = 1;
        $repair = RepairOrderUserSelectFaultsModel::find()->where(['device_fault_id'=>intval($id)])->asArray()->one();
        if (!empty($repair)) {
            $result = 0;
        } else {
            $repair_plan = RepairPlanModel::find()->where(['device_fault_id'=>intval($id)])->asArray()->one();
            if (!empty($repair_plan)) {
                $result = 0;
            } else {
                $deviceFaults = ModelsDeviceFaultsModel::find()->where(['device_fault_id'=>intval($id)])->asArray()->one();
                if (!empty($deviceFaults)) {
                    $result = 0;
                }
            }
        }

        if ($result) {
            # 删除有数据风险
            $result = DeviceFaultModel::findOne(["id"=>intval($id)])->delete();
            Yii::$app->session->setFlash('success', '删除成功');
        } else {
            Yii::$app->session->setFlash('danger', '此设备已经关联了其他资料,无法删除');
        }

        return $this->redirect(['index']);

    }


    /**
     * 故障设置
     */
    public function actionFaultset()
    {
        $req        = Yii::$app->request;
        $type       = empty($req->get('type')) ? 1:2; #type:1 已经添加, 2 未添加
        $model_id   = $req->get('mid');
        $title      = $req->get('title');

        $map        = array();
        $map[]      = array("=","f.model_id",$model_id,"I");

        $params     = array();
        $deviceFault = new DeviceFaultModel();

        // 已经添加的
        if ($type == 1) {
            $pageSize = $req->get("pageSize") ? (int) $req->get("pageSize") : 20;
            $pages = new Pagination(['totalCount' => $deviceFault->getSetedDeviceFaultListCount($map), 'pageSize' => $pageSize]);
            $deviceFaultlList = $deviceFault->getSetedDeviceFaultList($pages->offset,$pages->limit,$map);
        } else {
            // 此处参数不是数组,是具体的模型id
            $pageSize = $req->get("pageSize") ? (int) $req->get("pageSize") : 20;
            $pages = new Pagination(['totalCount' => $deviceFault->getNotSetedDeviceFaultListCount($model_id), 'pageSize' => $pageSize]);
            $deviceFaultlList = $deviceFault->getNotSetedDeviceFaultList($pages->offset,$pages->limit,$model_id);
        }

        /*
         * 页面id
         * 当显示的额是已经添加的故障的时候,id为已经添加故障的id
         * 当显示的为未添加故障的时候,id为设备故障列表id
         */

        $params['deviceFaultlList'] = $deviceFaultlList;
        //var_dump($deviceFaultlList);
        $params['pages'] = $pages;
        $params['gets'] = array(
            'info'=>$title,
            'type'=>$type,
            'model_id'=>$model_id
        );

        return $this->render("faultset",$params);
    }

    /**
     * @return array 故障管理查询方法
     */
    protected function dataList()
    {
        $req = Yii::$app->request;
        $cat_pid    = $req->get('deviceParentCat');//设备一级分类
        $cat_id    = $req->get('deviceChildCat');//设备二级分类
        $faultName = $req->get('faultName');        //故障名称
        $selsiscommon = $req->get('selsiscommon');  //是否常见

        $params = array();
        $get = array();

        $get['cat_pid'] = empty($cat_pid) ? 0 : $cat_pid;
        $get['cat_id'] = empty($cat_id) ? 0 : $cat_id;

        #可以构建一个解析器。。
        $map = array();

        // 过滤设备分类
        if ($cat_pid > 0) {
            if ($cat_id > 0) { // 选择了二级分类则精准查找
                $map[] = array("=", "f.device_cat_id", $cat_id, "I");
            } else { // 仅选择了一级分类, 则查询一级分类下所有子分类的数据
                $deviceCatIdArray = array();
                $children = DeviceCatRepository::getSubCatsByParentId($cat_pid, 'sort_order ASC', false);
                foreach ($children as $child) {
                    if (isset($child->id)) {
                         $deviceCatIdArray[] = $child->id;
                    }
                }

                // 父节点
                $deviceCatIdArray[] = $cat_pid;

                $deviceCatIds = '(' . implode(",", $deviceCatIdArray) . ')';
                $map[] = array("in", "f.device_cat_id", $deviceCatIds, "I"); // 转换为sql:   id IN (1,2,3)
            }
        }

        $get['faultName'] = $faultName;       //故障名称
        $get['selsiscommon'] = $selsiscommon; //是否常见

        // 判断故障名称
        if ($faultName) {
            $map[] = array("like", "f.name", "%{$faultName}%", "S");
        }

        // 判断是否常见
        if ($selsiscommon) {
            $iscom = $selsiscommon==2?0:1;
            $map[] = array("=", "f.is_common", intval($iscom), "I");
        }

        $deviceFaultModel = new DeviceFaultModel();
        /**
         * 排序
         */
        $sortHelper =  Yii::createObject(Sort::className());
        $sortHelper->setAttributes($deviceFaultModel,array("sort_order"=>"排序","id"=>"ID"));
        $sort['sort_order'] = $sortHelper->link('sort_order');
        $sort['id'] = $sortHelper->link('id');
        $getsort = $req->get("sort");
        $orderBy = '';
        if ($getsort) {
            $getorder = $sortHelper->getOrders();
            if (array_key_exists("id",$getorder)) {
                $orderBy = ($getorder['id'] == 4)? "f.id asc":"f.id desc";
            }
            if (array_key_exists("sort_order",$getorder)) {
                $orderBy = ($getorder['sort_order'] == 4)? "f.sort_order asc":"f.sort_order desc";
            }
        }
        if (empty($orderBy)) {
            $orderBy="f.id desc";
        }

        /**
         * 分页处理
         */
        $pageSize = $req->get("pageSize") ? (int) $req->get("pageSize") : 20;
        $pages = new Pagination(['totalCount' => $deviceFaultModel->getDeviceFaultListCount($map), 'pageSize' => $pageSize]);
        $deviceFaultlList = $deviceFaultModel->getDeviceFaultList($pages->offset,$pages->limit,$map,$orderBy);

        $deviceCatParentList = DeviceCatRepository::getTopParentCats();

        $params['deviceFaultlList'] = $deviceFaultlList;
        $params['deviceCatParentList'] =  $deviceCatParentList;
        $params['pages'] = $pages;
        $params['gets'] = $get;
        $params['sort'] = $sort;

        return $params;
    }

    /**
     * 显示批量添加故障页面
     * @return string
     */
    public function actionBatchCreate()
    {
        return $this->render("batch_create");
    }

    /**
     * 执行批量添加故障
     */
    public function actionDoBatchCreate()
    {
        $post = Yii::$app->request->post();
        $parentId = $post['parentId'];
        $childId = $post['childId'];
        $faultList = $post['faultList'];

        foreach ($faultList as $key => $val) {
            $fault = explode("_",$val);
            $deviceFault = new DeviceFaultModel();
            $deviceFault->name = $fault[0];
            $deviceFault->device_cat_id = $childId;
            $deviceFault->is_common = $fault[1];
            $deviceFault->created_at = time();
            $deviceFault->updated_at = time();
            $deviceFault->version = Yii::$app->params['DATA_VERSION'];

            $deviceFault->insert();
        }

        $msg = array();
        if (true) {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";

        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

        return $this->renderJson($msg);
    }


    //-------------------------故障设置

    /**
     * 故障设置添加
     * @return string
     */
    public function actionModelFaultAdd()
    {
        $req = Yii::$app->request;
        $model_id = $req->post('mid');
        $fault_id = $req->post('fault_id');

        $models_device_faults = new ModelsDeviceFaultsModel();
        $models_device_faults->device_fault_id  = $fault_id;
        $models_device_faults->model_id         = $model_id;
        $models_device_faults->version          = Yii::$app->params['DATA_VERSION'];
        $models_device_faults->created_at       = time();
        $models_device_faults->updated_at       = time();
        $result = $models_device_faults->insert();

        $msg = array();
        if ($result) {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

        return $this->renderJson($msg);
    }

    /**
     * 故障设置删除
     * @return string
     */
    public function actionModelFaultDel()
    {
        $req = Yii::$app->request;
        $model_device_fault_id = $req->post('id');
        #$model_id = $req->post('model_id');

        $msg = array();
        if (!empty($model_device_fault_id)) {
            $result = ModelsDeviceFaultsModel::findOne(["id" => intval($model_device_fault_id)])->delete();
            if ($result) {
                $msg['status'] = 1;
                $msg['msg'] = "操作成功";
            } else {
                $msg['status'] = 0;
                $msg['msg'] = "操作失败";
            }
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

        return $this->renderJson($msg);
    }

    /**
     * 执行故障设置的 批量添加
     */
    public function actionBatchModelDeviceFaultAdd()
    {
        $req = Yii::$app->request;
        $fault_ids = $req->post('ids');
        $model_id = $req->post('model_id');

        $fault_id_arr = explode(",",$fault_ids);
        $dataVersion = Yii::$app->params['DATA_VERSION'];
        $nowTime = time();
        foreach ($fault_id_arr as $key => $val) {
            $models_device_faults = new ModelsDeviceFaultsModel();
            $models_device_faults->device_fault_id  = $val;
            $models_device_faults->model_id         = $model_id;
            $models_device_faults->version          = $dataVersion;
            $models_device_faults->created_at       = $nowTime;
            $models_device_faults->updated_at       = $nowTime;

            $models_device_faults->insert();
        }

        if (true) {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

        return $this->renderJson($msg);
    }

    /** 批量删除故障
     * @return string
     * @throws \Exception
     */
    public function actionBatchModelDeviceFaultDel()
    {
        $req = Yii::$app->request;
        $fault_ids = $req->post('ids');

        $fault_id_arr = explode(",",$fault_ids);

        foreach ($fault_id_arr as $key => $val) {
            ModelsDeviceFaultsModel::findOne(["id"=> intval($val)])->delete();
        }

        if (true) {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

        return $this->renderJson($msg);
    }

    public function actionCheck()
    {
        $model = new ModelsRepairPlanPricesModel();
        $list = $model->getModelsRepairPlanPriceCheckList();

        $params = array();
        $params['list'] = $list;

        return $this->render('check', $params);
    }

    /**
     * 单个数据修复
     * @return \yii\web\Response
     */
    public function actionCheckRepair()
    {
        $req = Yii::$app->request;
        $id = $req->get("id");

        if (!empty($id)) {
            # 删除有数据风险
            //$result = DeviceFault::findOne(["id"=>intval($id)])->delete();
            $plan = ModelsRepairPlanPricesModel::findOne(["id"=>intval($id)])->toArray();
            if (!empty($plan)) {
                $manHoursFee = RegionFeeSettingModel::getManHourFeeByCity();
                $mRepairPlanPrices = ModelsRepairPlanPricesModel::findOne(["id"=>intval($id)]);
                $mRepairPlanPrices->labor_price = $manHoursFee * $plan['repair_hours'] *  $plan['difficulty_degree'];
                $mRepairPlanPrices->price = $mRepairPlanPrices->labor_price + $plan['parts_price'];
                $mRepairPlanPrices->updated_at = time();
                $result = $mRepairPlanPrices->save();
                if ($result > 0) {
                    Yii::$app->session->setFlash('success', '修复成功');
                } else {
                    Yii::$app->session->setFlash('danger', '修复失败');
                }
            } else {
                Yii::$app->session->setFlash('danger', '修复失败');
            }
        } else {
            Yii::$app->session->setFlash('danger', '缺失参数,修复失败');
        }

        return $this->redirect(['check']);
    }

    /**
     * 修复所有
     * @return \yii\web\Response
     */
    public function actionCheckRepairAll()
    {
        $plan = new ModelsRepairPlanPricesModel();
        $result = $plan->setAllCheckUpdate();
        if ($result > 0) {
            Yii::$app->session->setFlash('success', '修复成功');
        } else {
            Yii::$app->session->setFlash('danger', '修复失败');
        }

        return $this->redirect(['check']);
    }

    /**
     * 检测错误报价并修复-需整理开发一个专门的功能页面
     * @return string
     */
    public function actionCheck_bak()
    {
        $req = Yii::$app->request;
        $offset = empty($req->get('offset')) ? 0 : $req->get('offset');
        $limit = empty($req->get('limit')) ? 10000 : $req->get('limit');
        $fix = $req->get('fix');

        $errorRecords = array();
        $manHoursFee = RegionFeeSettingModel::getManHourFeeByCity();
        $children = ModelsRepairPlanPricesModel::find()->select("id, parts_price, repair_hours, difficulty_degree, labor_price, price")->offset($offset)->limit($limit)->all();
        foreach ($children as $child) {
            $parts_price = (float)$child->parts_price;
            $repair_hours = (float)$child->repair_hours;
            $difficulty_degree = (float)$child->difficulty_degree;
            $labor_price = (float)$child->labor_price;
            $price = (float)$child->price;

            $cal_labor_price = (float)($manHoursFee * $repair_hours * $difficulty_degree);
            $cal_price = (float)($parts_price + $cal_labor_price);
            if (bccomp($labor_price, $cal_labor_price, 2) != 0  || bccomp($price, $cal_price, 2) != 0 ) {
                $errorRecord = new stdClass();
                $errorRecord->id = $child->id;
                $errorRecord->parts_price = $parts_price;
                $errorRecord->repair_hours = $repair_hours;
                $errorRecord->difficulty_degree = $difficulty_degree;
                $errorRecord->labor_price = $labor_price;
                $errorRecord->price = $price;
                $errorRecord->cal_labor_price = $cal_labor_price;
                $errorRecord->cal_price = $cal_price;
                $errorRecords[] = $errorRecord;

                // 直接修复数据
                if ($fix == 1) {
                    $child->labor_price = $cal_labor_price;
                    $child->price = $cal_price;
                    $child->save();
                }
            }
        }

        print_r($errorRecords);
    }


    //------------------------根据故障设置维修方案 begin------------------------------------
    /**
     * 维修方案添加
     * @return string
     */
    public function actionRepairPlanSet()
    {
        $req = Yii::$app->request;
        $type = empty($req->get('type')) ? 1:intval($req->get('type')); //区分 已经添加和未添加
        $modelDeviceFaultId = $req->get('modelDeviceFaultId');
        $fault_id = 0;
        $model_id = 0;

        if (!empty($modelDeviceFaultId)) {
            $modelsDeviceFaults = ModelsDeviceFaultsModel::findOne(['id' => $modelDeviceFaultId]);
            if ($modelsDeviceFaults) {
                $fault_id = $modelsDeviceFaults->device_fault_id;
                $model_id = $modelsDeviceFaults->model_id;
            }
        }
        //根据型号id 获取设备信息
        $deviceModel = new DeviceModel();
        $device = $deviceModel->getDeviceInfoByModelId($model_id);
        //根据故障id 获取故障名称
        $deviceFault = DeviceFaultModel::findOne(["id"=>$fault_id])->toArray();

        //根据型号id 获取
        //type=1 已经添加的维修方案,type=2 未添加的维修方案
        $modelsRepairPlanPrices = new ModelsRepairPlanPricesModel();
        $list = array();
        if ($type == 1) {
            $list = $modelsRepairPlanPrices->getAllSetRepairPlanByFaultId($fault_id, $model_id);
        } else {
            $list = $modelsRepairPlanPrices->getAllNotSetRepairPlanByFaultId($fault_id, $model_id);
        }

        $params = array();
        $params['fault'] = $deviceFault;
        $params['list'] = $list;
        $params['gets'] = array(
            'info'      => $device['device_name'],
            'type'      => $type,
            'model_id'  => $model_id,
            'fault_id'  => $fault_id,
            'modelDeviceFaultId' => $modelDeviceFaultId
        );

        return $this->render("repair_plan_set", $params);
    }

    /**
     * 根据故障维修方案报价id 删除 维修方案报价数据
     * 支持单个,及批次删除
     * @return string
     */
    public function actionFaultRepairPlanDel()
    {
        $req = Yii::$app->request;
        $model_repair_plan_price_id = $req->post('ids');
        $model_id = $req->post('model_id'); #因为有了主键id ,其实不需要 型号id

        $model_repair_plan_price_id_arr = explode(",",$model_repair_plan_price_id);

        foreach ($model_repair_plan_price_id_arr as $key=>$val) {
            ModelsRepairPlanPricesModel::findOne(["id"=>intval($val)])->delete();
        }

        if (true) {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

        return $this->renderJson($msg);
    }

    /**
     * 根据 维修方案id 及 型号id 构建一个新的故障维修方案报价
     * @return string
     */
    public function actionFaultRepairPlanAdd()
    {
        $req = Yii::$app->request;
        $repair_plan_ids = $req->post('ids');
        $model_id = $req->post('model_id');

        $repair_plan_ids_arr = explode(",", $repair_plan_ids);

        foreach ($repair_plan_ids_arr as $key=>$val) {
            $modelsRepairPlanPrices = new ModelsRepairPlanPricesModel();
            $modelsRepairPlanPrices->repair_plan_id  = $val;
            $modelsRepairPlanPrices->model_id         = $model_id;
            $modelsRepairPlanPrices->parts_price      = 0;
            $modelsRepairPlanPrices->repair_hours     = 0;
            $modelsRepairPlanPrices->difficulty_degree = 0;
            $modelsRepairPlanPrices->labor_price      = 0;
            $modelsRepairPlanPrices->version          = Yii::$app->params['DATA_VERSION'];
            $modelsRepairPlanPrices->price            = 0;
            $modelsRepairPlanPrices->created_at       = time();
            $modelsRepairPlanPrices->updated_at       = time();

            $modelsRepairPlanPrices->insert();
        }

        if (true) {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

        return $this->renderJson($msg);
    }

    //------------------------根据故障设置维修方案 end------------------------------------


    //-----------------------------设置价格 begin-----------------------------
    //定价设置
    public function actionRepairPlanPriceSet()
    {
        $req = Yii::$app->request;

        $modelsRepairPlanPricesId = $req->get('modelsRepairPlanPricesId');
        $model_id = 0; //设备型号id
        $fault_id = 0; //设备型号id
        $modelDeviceFaultId = 0;

        // 根据方案报价id 和 型号id 设备故障id 获取 关于此设备的详细数据
        $modelsRepairPlanPrices = ModelsRepairPlanPricesModel::getFaultRepairPlanInfoByModelPlanPriceId($modelsRepairPlanPricesId);
        if ($modelsRepairPlanPrices) {
            $model_id = $modelsRepairPlanPrices['model_id']; //设备型号id
            $fault_id = $modelsRepairPlanPrices['device_fault_id']; //设备型号id
            $modelDeviceFaultId = $modelsRepairPlanPrices['models_device_faults_id'];

        }

        // 根据型号id 获取设备信息
        $deviceModel = new DeviceModel();
        $device = $deviceModel->getDeviceInfoByModelId($model_id);
        // 根据故障id 获取故障名称
        $deviceFault = DeviceFaultModel::findOne(["id" => $fault_id])->toArray();
        $modelDeviceCat = DeviceCatRepository::selectOne($device['device_cat_id']);
        $isComputer = WarrantyLevelRule::isComputer($modelDeviceCat);

        $params = array();
        $params['fault'] = $deviceFault;
        $params['plan'] = $modelsRepairPlanPrices;
        $params['isComputer'] = $isComputer;
        $params['warrantyLevel'] = WarrantyLevelRule::getAllWarrantyLevels($isComputer);

        $params['gets'] = array(
            'info'                      => $device['device_name'],
            'model'                     => $device['model'],
            'modelDeviceFaultId'        => $modelDeviceFaultId,
            'modelsRepairPlanPricesId'  => $modelsRepairPlanPricesId,
        );
        $params['man_hour_fee'] = RegionFeeSettingModel::getManHourFeeByCity();

        return $this->render("repair_price_set", $params);
    }

    /** 更新报价的信息
     * @return string
     */
    public function actionUpdateModelsRepairPlanPrice()
    {
        $req = Yii::$app->request;
        $modelRepairPlanPriceId = $req->post('modelsRepairPlanPricesId');
        $parts_price            = $req->post('parts_price');
        $repair_hours           = $req->post('repair_hours');
        $difficulty_degree      = $req->post('difficulty_degree');
        $warranty_level         = $req->post('warranty_level');
        $msg = array();

        if (empty($modelRepairPlanPriceId)) {
            $msg['status']  = 0;
            $msg['msg']     = "修复失败,缺少必要参数";
            return $this->renderJson($msg);
        }

        if (!in_array($warranty_level, WarrantyLevelRule::getWarrantyLevelKeys())) {
            $msg['status']  = 0;
            $msg['msg']     = "保修等级有误,当前是旧版的保修等级,请修改为新版的保修等级再保存!";
            return $this->renderJson($msg);
        }

        $mRepairPlanPrices = ModelsRepairPlanPricesModel::findOne(["id"=> $modelRepairPlanPriceId]);
        if (empty($mRepairPlanPrices)) {
            $msg['status']  = 0;
            $msg['msg']     = "未找到报价!";
            return $this->renderJson($msg);
        }

        $manHoursFee = RegionFeeSettingModel::getManHourFeeByCity();
        $labor_price = $manHoursFee * $repair_hours * $difficulty_degree;
        $price       = $labor_price + $parts_price;

        $mRepairPlanPrices->parts_price         = $parts_price;
        $mRepairPlanPrices->repair_hours        = $repair_hours;
        $mRepairPlanPrices->difficulty_degree   = $difficulty_degree;
        $mRepairPlanPrices->labor_price         = $labor_price;
        $mRepairPlanPrices->price               = $price;
        $mRepairPlanPrices->warranty_level      = $warranty_level;
        $result = $mRepairPlanPrices->save();
        if ($result > 0) {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        } else {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        }

        return $this->renderJson($msg);
    }


    //-----------------------------设置价格 end-----------------------------

    /**
     * 更新故障信息
     */
    public function actionUpdateInfo()
    {
        $post = Yii::$app->request->post();
        if (empty($post["pk"])) {
            return $this->renderJson(array("status"=>-1, "msg"=>"缺少必要参数,不能更新"));exit;
        }
        $flag= $post['name'];
        if (empty($flag)) {
            return $this->renderJson(array("status"=>-1, "msg"=>"参数有误,不能更新"));exit;
        }
        $order = DeviceFaultModel::findOne($post['pk']);
        if ($flag=="name") {
            $order->name = $post['value'];
        } elseif ($flag=="iscommon") {
            $order->is_common = $post['value'];
        }
        $result = $order->save();

        if ($result) {
            return $this->renderJson(array("status"=>1, "msg"=>"修改成功"));exit;
        } else {
            return $this->renderJson(array("status"=>-1, "msg"=>"修改失败"));exit;
        }
    }

    /**
     * 批量更新故障排序
     */
    public function actionUpdateOrder()
    {
        $post = Yii::$app->request->post();
        if (empty($post["updatestr"])) {
            return $this->renderJson(array("status"=>-1, "msg"=>"缺少必要参数,不能保存"));exit;
        }
        $updatedata = explode('|',$post["updatestr"]);


        $transaction = Yii::$app->db->beginTransaction();
        try {
            if ($updatedata) {
                foreach ($updatedata as $k => $v) {
                    $updatekeyandvalue = explode(',',$v);
                    if ($updatekeyandvalue) {
                        $order = DeviceFaultModel::findOne($updatekeyandvalue[0]);
                        if ($order) {
                            $order->sort_order = empty($updatekeyandvalue[1]) ? 1 : $updatekeyandvalue[1];
                            $result = $order->save();
                        }
                    }
                }
                $transaction->commit();
                return $this->renderJson(array("status"=>1, "msg"=>"排序保存成功"));exit;
            }
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->renderJson(array("status"=>-1, "msg"=>"排序保存异常,更新失败"));exit;
        }
    }

    /**
     * 暴力删除故障和关联的维修报价数据
    1、删除:device_fault、repair_plan、models_device_faults、models_repair_plan_prices
    2、修复订单数据: repair_order_user_select_faults、repair_order_repair_plans
     */
    public function forceDeleteFaultData($device_fault_id)
    {
        $defaultFault = DeviceFaultModel::findOne($device_fault_id);
        if (!$defaultFault) {
            return false;
        }

        // 删除[型号-故障记录] models_device_faults
        ModelsDeviceFaultsModel::deleteAll(["device_fault_id" => $device_fault_id]);
        // 删除[型号-维修方案价格记录] models_repair_plan_prices
        $repairPlanArray = RepairPlanModel::findAll(["device_fault_id" => $device_fault_id]);
        foreach ($repairPlanArray as $plan) {
            ModelsRepairPlanPricesModel::deleteAll(["repair_plan_id" => $plan->id]);
        }
        // 删除[维修方案记录] repair_plan
        RepairPlanModel::deleteAll(["device_fault_id" => $device_fault_id]);

        // 删除故障
        $defaultFault->delete();

        return true;
    }

    /**
     * 清理电脑故障数据[临时接口]
     */
    public function actionClearComputerData()
    {
        $transaction = Yii::$app->getDb()->beginTransaction();
        try {
            $faultArray = DeviceFaultModel::findAll(["device_cat_id" => [7, 8, 9]]);
            foreach ($faultArray as $fault) {
                $this->forceDeleteFaultData($fault->id);
            }
            $transaction->commit();
        } catch (Exception $exception) {
            $transaction->rollBack();
            Yii::getLogger()->log($exception->getTraceAsString(), Logger::LEVEL_ERROR);
            Yii::$app->session->setFlash('success', '清理电脑故障数据异常');
        }

        Yii::$app->session->setFlash('success', '清理电脑故障数据成功');

        return $this->redirect(['index']);
    }
}