ModelController.php 18.8 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
<?php

namespace app\ht\modules\device\controllers;

use Yii;
use yii\base\Exception;
use yii\data\Pagination;
use yii\web\NotFoundHttpException;
use app\ht\controllers\BaseController;
use common\models\DeviceImg                 as DeviceImgModel;
use common\models\GuestDevice               as GuestDeviceModel;
use common\models\Model                     as ModelModel;
use common\models\ModelsRepairPlanPrices    as ModelsRepairPlanPricesModel;
use common\models\UserDevice                as UserDeviceModel;
use common\models\Brand                     as BrandModel;
use domain\device\models\Device             as DeviceModel;
use domain\device\models\ModelsDeviceFaults as ModelsDeviceFaultsModel;
use domain\device\BrandRepository;
use domain\device\DeviceCatRepository;
use stdClass;
use function sizeof;
use function intval;
use function count;
use function strtoupper;
use function time;
use function explode;
use function array_filter;

/**
 * 型号管理控制器
 * Class BrandController
 * @package app\ht\modules\catalog\controllers
 */
class ModelController extends BaseController
{
    /**
     * 启用的型号列表
     */
    public function actionIndex()
    {
        $params = $this->dataList();

        $params['brandList'] = BrandRepository::getAllAvailableBrands();
        /**
         * 渲染模板
         */
        return $this->render('index', $params);
    }

    public function actionGetModelList()
    {
        $request  = Yii::$app->request;
        $cat_id   = $request->post("cat_id");
        $brand_id = $request->post("brand_id");
        //$sort = empty($request->post("sort")) ? "asc":"desc";

        $modelList = ModelModel::find()->where(["device_cat_id"=>$cat_id,"brand_id"=>$brand_id])->orderBy("model ASC")->asArray()->all();

        if (sizeof($modelList) > 0) {
            $data = array(
                "status"    => 1,
                "msg"       => "success",
                "modelList" => $modelList
            );
        } else {
            $data = array(
                "status"    => 0,
                "msg"       => "success",
                "modelList" => $modelList
            );
        }

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

    /**
     * 获取类型
     * pid = 0 为父级
     * 否则为 子级
     */
    public function actionGetDeviceCatList()
    {
        $request  = Yii::$app->request;
        $parentId = $request->post("parentId");

        $deviceCatList = DeviceCatRepository::getSubCatsByParentId($parentId);//find()->select("id,name,parent_id")->where(["parent_id"=>intval($parentId)])->asArray()->all();

        if (sizeof($deviceCatList) > 0) {
            $data = array(
                "status"    => 1,
                "msg"       => "success",
                "modelList" => $deviceCatList
            );
        } else {
            $data = array(
                "status"    => 0,
                "msg"       => "success",
                "modelList" => $deviceCatList
            );
        }

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

    /**
     * 获取单个分类信息
     * @return string
     */
    public function actionGetDeviceCat()
    {
        $request = Yii::$app->request;
        $id = $request->post("id");

        $catModel = DeviceCatRepository::selectOne(intval($id));
        $cat = $catModel->toArray();
        if (sizeof($cat) > 0) {
            $data = array(
                "status"    => 1,
                "msg"       => "success",
                "modelList" => $cat
            );
        } else {
            $data = array(
                "status"    => 0,
                "msg"       => "success",
                "modelList" => $cat
            );
        }

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

    protected function dataList()
    {
        $request = Yii::$app->request;

        $brandId = $request->get("brand");
        $deviceParentCat = $request->get("deviceParentCat");
        $deviceChildCat = $request->get("deviceChildCat");
        $deviceTitle = $request->get("title");
        /**
         * 查询过滤处理
         */
        $get = array();
        $map = array();
        if (!empty($brandId)) {
            $map[] = array("=", "m.brand_id", intval($brandId), "I");
            $get['brandId'] = intval($brandId);
        } else {
            $get['brandId'] = 0;
        }

        if (!empty($deviceChildCat)) {
            $map[] = array("=", "m.device_cat_id", intval($deviceChildCat), "I");
            $get['cateId'] = intval($deviceChildCat);
        } else {
            $get['cateId'] = 0;
        }

        if (!empty($deviceParentCat)) {
            $get['catePid'] = intval($deviceParentCat);
        } else {
            $get['catePid'] = 0;
        }
        if (isset($_GET['title'])) {
            $map[] = array("like", "m.model", "%" . $deviceTitle . "%", "S");
            $get['title'] = $deviceTitle;
        } else {
            $get['title'] = '';
        }
        /**
         * 分页处理
         */
        $modelModel = new ModelModel();
        $pageSize = $request->get("pageSize") ? (int) $request->get("pageSize") : 20;
        $pages = new Pagination(['totalCount' => $modelModel->getModelListCount($map), 'pageSize' => $pageSize]);
        $modelList = $modelModel->getModelList($pages->offset,$pages->limit,$map);

        return [
            'gets'      => $get,
            'modelList' => $modelList,
            'pages'     => $pages,
        ];
    }

    /**
     * 新增界面
     */
    public function actionCreate()
    {
        $req = Yii::$app->request;
        $brand_id = $req->get('brand_id');
        $params = array();
        $params['brandList'] = BrandRepository::getAllAvailableBrands();
        $params['brand_id'] = empty($brand_id) ? "": intval($brand_id);

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

    /**
     * 新增执行动作
     */
    public function actionDoAdd()
    {
        $post = Yii::$app->request->post();
        if (empty($post)) {
            return;
        }

        $brand_id = $post['brand_id'];
        $cat_id = $post['cat_id'];
        $modelName = strtoupper($post['model']);

        $resultModel = ModelModel::find()->where(["brand_id"=>$brand_id,"device_cat_id"=>$cat_id,"model"=>$modelName])->one();
        $msg = array();

        if (empty($resultModel)) {
            $model = new ModelModel();
            $model->brand_id = $brand_id;
            $model->device_cat_id = $cat_id;
            $model->model = $modelName;
            $result = $model->insert();
            if ($result) {
                $msg['status'] = 1;
                $msg['msg'] = "操作成功";
            } else {
                $msg['status'] = 0;
                $msg['msg'] = "操作失败";
            }
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "型号已存在";
        }

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

    /**
     * 显示批量增加
     * @return string
     */
    public function actionBatchCreate()
    {
        $params = array();
        $params['brandList'] = BrandModel::find()->where(["is_available"=>1])->select("id,english_name,chinese_name")->asArray()->all();

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

    /**
     * 新增批量增加动作
     */
    public function actionDoAddBatch()
    {
        $post = Yii::$app->request->post();
        if (empty($post)) {
            return;
        }

        $cat_id = $post['cat_id'];
        $brand_id = $post['brand_id'];
        $modelList = strtoupper($post['model']);

        //事务  已经存在的类型不会添加进去
        $tr = Yii::$app->db->beginTransaction();
        $result = true;
        try {
            foreach ($modelList as $val) {
                $resultModel = ModelModel::find()->where(["brand_id"=>$brand_id,"device_cat_id"=>$cat_id,"model"=>$val])->one();
                if (!$resultModel) {
                    $model = new ModelModel();
                    $model->brand_id = $brand_id;
                    $model->device_cat_id = $cat_id;
                    $model->model = $val;
                    $model->insert();
                }
            }
            $tr->commit();
        } catch (Exception $e) {
            $tr->rollBack();
            $result = false;
        }

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

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

    /**
     * 更新界面
     */
    public function actionUpdate($id,$info)
    {
        $model = $this->findModel($id);
        return $this->render('update', [
            'model' => $model,
            'info'=>$info
        ]);
    }

    /**
     * 更新执行动作
     */
    public function actionDoUpdate()
    {
        $request = Yii::$app->request;
        $modelId = $request->post("modelId");
        $modelName = $request->post("modelName");
        $brandId = $request->post("brandId");
        $deviceCatId = $request->post("deviceCatId");
        // 判断型号数据是否存在,避免修改造成重复数据
        $resultModel = ModelModel::find()->where(["brand_id"=>$brandId,"device_cat_id"=>$deviceCatId,"model"=>$modelName])->one();
        $msg = array();

        if (empty($resultModel)) {
            $fModel = ModelModel::findOne(["id"=>$modelId]);
            $fModel->model = strtoupper($modelName);
            $result = $fModel->save();
            if ($result) {
                $msg['status'] = 1;
                $msg['msg'] = "操作成功";
            } else {
                $msg['status'] = 0;
                $msg['msg'] = "操作失败";
            }
        } else {
            $resultModel->model = strtoupper($modelName);
            $resultModel->save();
            $msg['status'] = 1;
            $msg['msg'] = "操作成功(未变化)";
        }

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

    /** 删除型号
     *  删除执行动作
     */
    public function actionDelete()
    {
        $req= Yii::$app->request;
        $modelId = $req->get('id');

        // 判断型号是否有被使用,如果有不允许删除
        $count = DeviceModel::find()->where(["model_id"=>$modelId])->count();
        $msg = array();
        if ($count > 0) {
            $msg['status'] = 0;
            $msg['msg'] = "型号已经关联设备,无法删除!";
            Yii::$app->session->setFlash('danger', '型号已经关联设备,无法删除!');
        } else {
            $sysUserId = Yii::$app->user->id;
            $modelM = ModelModel::findOne([ "id"=> $modelId ]);
            if (!$modelM) {
                $msg['status'] = 0;
                $msg['msg'] = "型号删除失败, 型号为空";
                Yii::$app->session->setFlash('danger', '型号删除失败, 型号为空');
                return $this->redirect(['index']);
            }
            $modelDeviceFaultsFind = ModelsDeviceFaultsModel::find();
            $modelDeviceFaultsFind->where(['model_id' => $modelId]);
            $modelDeviceFaults = $modelDeviceFaultsFind->count();
            if ($modelDeviceFaults > 0 ) {
                $msg['status'] = 0;
                $msg['msg'] = "型号下面有故障,请删除故障再操作";
                Yii::$app->session->setFlash('danger', '型号下面有故障,请删除故障再操作');
                return $this->redirect(['index']);
            }

            $models = $modelM->toArray();
            $result = $modelM->delete();
            $modelRepairPlanPrices =  ModelsRepairPlanPricesModel::find();
            $modelRepairPlanPrices->where(['model_id' => $modelId]);
            $modelRepairPlanPrices->asArray();
            $modelRepairPlanPricesList = $modelRepairPlanPrices->all();
            if (count($modelRepairPlanPricesList) > 0) {
                ModelsRepairPlanPricesModel::deleteAll(['model_id' => $modelId]);
            }

            if ($result) {
                $msg['status'] = 1;
                $msg['msg'] = "操作成功";
                Yii::$app->session->setFlash('success', '型号删除完成');
            } else {
                $msg['status'] = 0;
                $msg['msg'] = "操作失败";
                Yii::$app->session->setFlash('danger', '型号删除失败');
            }
        }

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

    /**
     * 根据主键查找模型
     */
    protected function findModel($id)
    {
        $modelModel = Yii::createObject(ModelModel::className());
        if (($model = $modelModel::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('访问页面不存在');
        }
    }

    /**
     * 启用或禁用
     */
    public function actionEnable($id)
    {
        $model = $this->findModel($id);
        $model->is_available = ($model->is_available == 1) ? 0 : 1;
        $model->save();
        return $this->redirect(['index']);
    }

    /**
     * 批量启用
     */
    public function actionBatchEnable($ids)
    {
        $_ids = explode(',', $ids);
        $_ids = array_filter($_ids);

        foreach ($_ids as $id) {
            $model = $this->findModel($id);
            $model->is_available = 1;
            $model->save();
        }

        Yii::$app->getSession()->setFlash('success', '批量启用成功');
        return $this->redirect(['index']);
    }

    /**
     * 批量禁用
     */
    public function actionBatchDisable($ids)
    {
        $_ids = explode(',', $ids);
        $_ids = array_filter($_ids);

        foreach ($_ids as $id) {
            $model = $this->findModel($id);
            $model->is_available = 0;
            $model->save();
        }

        Yii::$app->getSession()->setFlash('success', '批量禁用成功');

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

    /**
     * 合并设备型号
     */
    public function actionCombine()
    {
        return $this->render('combine',array());
    }

    /**
     * 搜索型号返回型号信息
     */
    public function actionSearchModel()
    {
        $e = new stdClass();
        $e->success = false;
        $e->list = [];
        $req = Yii::$app->request;
        $keyword = $req->post('query');
        $deviceModel = ModelModel::find();
        $deviceModel->select(['id', 'device_cat_id', 'model']);
        $deviceModel->where(['like', 'model', $keyword]);
        $deviceModel->asArray();
        $deviceModel->limit(10);
        $deviceList = $deviceModel->all();
        if ($deviceList) {
            $e->list = $deviceList;
        }

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

    /**
     * 合并设备型号数据
     */
    public function actionDoCombine()
    {
        $req= Yii::$app->request;
        $needbindmodel = $req->post('needbindmodel');
        $bindtomodel = $req->post('bindtomodel');
        if ($needbindmodel=="" || $bindtomodel=="") {
            return $this->renderJson(array("status"=>-1, "msg"=>"缺少必要参数,不能更新!"));
        }

        if ($needbindmodel == $bindtomodel) {
            return $this->renderJson(array("status"=>-2, "msg"=>"需要合并的设备型号和要合并到的设备型号一样!"));
        }

        // 查找需要合并的设备型号信息
        $needbindmodelfind = ModelModel::findOne(["model"=>$needbindmodel]);
        $bindtomodelfind = ModelModel::findOne(["model"=>$bindtomodel]);

        // 判断需要合并的设备型号对应的数据及要合并到的数据为空时不让更新
        if (empty($needbindmodelfind) || empty($bindtomodelfind)) {
            return $this->renderJson(array("status"=>-3, "msg"=>"型号数据不存在,不能更新!"));
        }

        // 获取型号编号
        $needbindmodelid = $needbindmodelfind["id"]; //需要合并的设备型号对应的数据编号
        $bindtomodelid = $bindtomodelfind["id"]; //要合并到的设备型号对应的数据编号

        // 开启事务防止合并过程中失败造成数据处理不全的情况
        $transaction = Yii::$app->db->beginTransaction();
        try {
            // 设置更新数据
            $udData = array();
            $udData['model_id'] = $bindtomodelid;
            $udData['updated_at'] = time();
            // 获取型号对应的设备信息
            $needbinddeviceidfind = DeviceModel::findOne(["model_id"=>$needbindmodelid]);
            $bindtodeviceidfind = DeviceModel::findOne(["model_id"=>$bindtomodelid]);
            $needbinddeviceid =  $needbinddeviceidfind["id"];
            $bindtodeviceid = $bindtodeviceidfind["id"];

            // 判断合并型号下如果没有对应设备不给更新
            if (empty($needbinddeviceid) || empty($bindtodeviceid)) {
                $transaction->rollBack();
                return $this->renderJson(array("status"=>-1, "msg"=>"需要合并或者合并到的型号下没有对应设备,不能更新!"));
            }

            // 更新user_device guest_device 中的model_id  需要合并的设备型号统一替换成要合并到的设备型号 $guestresult =
            GuestDeviceModel::updateAll($udData,"model_id=:model_id", [":model_id"=>$needbindmodelid]);

            // 删除设备故障,维修方案数据,删除设备表中信息,删除型号标中数据 $devicefaultresult =  $deviceplanresult =
            ModelsDeviceFaultsModel::deleteAll("model_id=:model_id", [":model_id"=>$needbindmodelid]);
            ModelsRepairPlanPricesModel::deleteAll("model_id=:model_id", [":model_id"=>$needbindmodelid]);

            // 更新userdevice 表中数据,删除冗余设备信息
            if ($needbinddeviceid) {
                // 查找userdevice表是否有对应的设备信息
                $userdevicelist = UserDeviceModel::findOne(["device_id" => $needbinddeviceid]);
                if ($userdevicelist && $bindtodeviceid) {
                    UserDeviceModel::updateAll(array("device_id"=>$bindtodeviceid, "updated_at" => time()), "device_id in (:ids)", [":ids" => $needbinddeviceid]); //$userresult =
                }
                DeviceModel::deleteAll("model_id in (:ids)", [":ids"=>$needbindmodelid]); //$deviceresult =
                DeviceImgModel::deleteAll("device_id in (:ids)", [":ids"=>$needbinddeviceid]);
            }
            // 删除冗余的型号数据
            unset($udData);
            $modelresult = ModelModel::deleteAll("id=:model_id", [":model_id"=>$needbindmodelid]);
            if ($modelresult) {
                $transaction->commit();
                return $this->renderJson(array("status"=>1, "msg"=>"合并处理成功"));
            } else {
                $transaction->rollBack();
                return $this->renderJson(array("status"=>-4, "msg"=>"合并处理失败"));
            }
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->renderJson(array("status"=>-5, "msg"=>"合并处理异常"));
        }
    }
}