UpgradeController.php 28.5 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
<?php

namespace app\ht\modules\upgrade\controllers;

use Yii;
use yii\data\Pagination;
use common\components\adminlog\AdminLogs;
use domain\manufacturer\ManufacturerRepository;
use domain\upgrade\Upgrade;
use domain\upgrade\UpgradeRepository;
use domain\upgrade\UpgradeStatus;
use domain\model\ModelRepository;
use domain\project\ProjectRepository;
use app\ht\controllers\BaseController;
use Resource\FileService;

use stdClass;

/**
 * 版本管理
 * Class UpgradeController
 * @package app\ht\modules\upgrade\controllers
 */
class UpgradeController extends BaseController
{
    /**
     * 版本管理
     */
    public function actionIndex()
    {
        $params = $this->dataList(1);
        /**
         * 渲染模板
         */
        return $this->render('index', $params);
    }

    /**
     * 查询数据列表
     */
    protected function dataList($type = '')
    {
        $request     = Yii::$app->request;
        $creatTime   = $request->get('creatTime');
        $endTime     = $request->get('endTime');
        $status      = $request->get('status');
        $version     = $request->get('version');
        $dataType    = !empty($request->get('type')) ? $request->get('type') : UpgradeStatus::TYPE_APP;

        $gets = [
            'creatTime'  => $creatTime,
            'endTime'    => $endTime,
            'status'     => $status,
            'version'    => $version,
            'type'       => $dataType,
        ];

        $where = ['and'];
        if ($creatTime) {
            $creatTime = strtotime($creatTime);
            $where[] = ['>=', 'u.pushed_at', $creatTime];
        }
        if ($endTime) {
            $endTime = strtotime($endTime) + 86400;
            $where[] = ['<=', 'u.pushed_at', $endTime];
        }
        if ($status) {
            $status = ($status == -1) ? 0 : $status;
            $where[] = ['=', 'u.status', $status];
        }
        if ($version) {
            $where[] = ['like', 'u.version', $version];
        }
        if ($dataType) {
            $where[] = ['=', 'u.type', $dataType];
        }
        $user = Yii::$app->user->identity;
        if (isset($user->is_manufacture) && $user->is_manufacture == 1) {
            $where[] = ['=', 'mf.sys_user_id', $user->id];// ???
        }
        if ($type == 0) {
            $pageList = UpgradeRepository::getPageList($where, 0 , 0);
            $pages = null;
        } else {
            $pageSize = 20;
            $pages = new Pagination(['totalCount' => UpgradeRepository::getPageCount($where), 'pageSize' => $pageSize]);
            $pageList = UpgradeRepository::getPageList($where, $pages->offset, $pages->limit);
        }

        /**
         * 数据整理
         */

        return [
            'listdata'   => $pageList,
            'pages'      => $pages,
            'gets'       => $gets
        ];
    }

    /**
     * 创建版本
     * @return string
     */
    public function actionCreate()
    {
        $gets = $this->request->get();
        $user = Yii::$app->user->identity;
        if (isset($user->is_manufacture) && $user->is_manufacture == 1) {
            $gets["is_manufacture"] = 1;
            $manufacturer = ManufacturerRepository::findOne(["sys_user_id" => $user->id]);
            if ($manufacturer) {
                $gets["manufacture_name"] = $manufacturer->name;
                $gets["manufacture_id"] = $manufacturer->id;
            }
        }
        return $this->render('create', ['gets' => $gets]);
    }

    /**
     * 创建版本
     * @return string
     */
    public function actionDoAdd()
    {
        $request = Yii::$app->request;
        $version = $request->post("version"); // 版本
        if (empty(trim($version))) {
            Yii::$app->session->setFlash('error', '版本不能为空');
            return $this->render('create');
        }
        $user = Yii::$app->user->identity;
        if (isset($user->is_manufacture) && $user->is_manufacture == 1) {
            $manufacturer = ManufacturerRepository::findOne(["sys_user_id" => $user->id]);
            if (empty($manufacturer) || $manufacturer->id != $request->post("manufacture_id")) {
                Yii::$app->session->setFlash('error', '添加失败');
                return $this->render('create');
            }
        }
        $result = Upgrade::create($request->post());
        if ($result === -1) {
            Yii::$app->session->setFlash('error', '添加失败,版本' . $version . '已存在');
            return $this->render('create');
        }
        if ($result) {
            Yii::$app->session->setFlash('success', '添加成功');
        } else {
            Yii::$app->session->setFlash('error', '添加失败');
        }

        return $this->redirect('index?type=' . (!empty($request->post("type")) ? $request->post("type") : UpgradeStatus::TYPE_APP));
    }

    /**
     * 取消发布
     * @return string
     */
    public function actionDoCancel()
    {
        $request = Yii::$app->request;
        $id = $request->post("id"); //
        $e = new stdClass();
        $e->success = false;
        $e->message = 'fail';
        if (empty($id)) {
            $e->message = 'ID为空';
            return $this->renderJson($e);
        }
        $upgradeModel = UpgradeRepository::findOne(['id' => $id]);
        if (empty($upgradeModel)) {
            $e->message = '未找到版本记录';
            return $this->renderJson($e);
        }
        $upgradeModel->status = UpgradeStatus::STATUS_WAIT;
        if ($upgradeModel->save()) {
            $e->success = true;
        } else {
            $e->message = '取消失败';
        }

        return $this->renderJson($e);

    }

    /**
     * 编辑版本
     * @return string
     */
    public function actionEdit()
    {
        $upgradeId = $this->request->get("uid");
        $isCreate = $this->request->get("isCreate");
        $info = UpgradeRepository::selectOne($upgradeId, true);
        if (isset($info["path"])) {
            $info["oldName"] = $info["path"];
            $manufacture = ManufacturerRepository::selectOne($info["manufacture_id"]);
            if (isset($manufacture["name"])) {
                $info["manufacture_name"] = $manufacture["name"];
            }
        }
        return $this->render('edit', ["info" => ($isCreate == 2 ? $this->request->get() : $info)]);
    }

    /**
     * 编辑版本
     * @return string
     */
    public function actionDoEdit()
    {
        $request = Yii::$app->request;
        $version = $request->post("version");
        $uid = $request->post("uid");
        if (empty($uid)) {
            Yii::$app->session->setFlash('error', '版本编号不能为空');
            $params = $this->dataList(1);
            return $this->render('index', $params);
        }
        $user = Yii::$app->user->identity;
        if (isset($user->is_manufacture) && $user->is_manufacture == 1) {
            $manufacturer = ManufacturerRepository::findOne(["sys_user_id" => $user->id]);
            if (empty($manufacturer) || $manufacturer->id != $request->post("manufacture_id")) {
                Yii::$app->session->setFlash('error', '编辑失败');
                $params = $this->dataList(1);
                return $this->render('index', $params);
            }
        }
        $upgrade = UpgradeRepository::selectOne($uid,true);
        if (isset($upgrade["path"])) {
            $upgrade["oldName"] = $upgrade["path"];
            $manufacture = ManufacturerRepository::selectOne($upgrade["manufacture_id"]);
            if (isset($manufacture["name"])) {
                $upgrade["manufacture_name"] = $manufacture["name"];
            }
        }
        if (empty($upgrade)) {
            Yii::$app->session->setFlash('error', '版本记录不存在');
            $params = $this->dataList(1);
            return $this->render('index', $params);
        }
        if (empty(trim($version))) {
            Yii::$app->session->setFlash('error', '版本不能为空');
            return $this->render('edit', ["info" => $upgrade]);
        }

        $result = Upgrade::update($uid, $request->post());

        if ($result === -1) {
            Yii::$app->session->setFlash('error', '修改的版本' . $version . '已存在');
            return $this->render('edit', ["info" => $upgrade]);
        }
        if ($result) {
            Yii::$app->session->setFlash('success', '编辑成功');
        } else {
            Yii::$app->session->setFlash('error', '编辑失败');
        }
        $upgrade = UpgradeRepository::selectOne($uid,true);
        if (isset($upgrade["path"])) {
            $upgrade["oldName"] = $upgrade["path"];
            $manufacture = ManufacturerRepository::selectOne($upgrade["manufacture_id"]);
            if (isset($manufacture["name"])) {
                $upgrade["manufacture_name"] = $manufacture["name"];
            }
        }
        return $this->render('edit', ["info" => $upgrade]);
    }

    /**
     * 删除版本
     * @return string
     * @throws \Exception
     */
    public function actionDoDel()
    {
        $request = Yii::$app->request;
        $itemId = $request->post("data_id");
        $msg = array();
        $user = Yii::$app->user->identity;
        if (isset($user->is_manufacture) && $user->is_manufacture == 1) {
            $manufacturer = ManufacturerRepository::findOne(["sys_user_id" => $user->id]);
            $upgrade = UpgradeRepository::selectOne($itemId, true);
            if (empty($upgrade) || empty($manufacturer) || $manufacturer->id != $upgrade['manufacture_id']) {
                $msg['status'] = 0;
                $msg['msg'] = "删除";
                return $this->renderJson($msg);
            }
        }

        // 删除对应的版本
        if (Upgrade::delete($itemId)) {
            $msg['status'] = 1;
            $msg['msg'] = "操作成功";
        } else {
            $msg['status'] = 0;
            $msg['msg'] = "操作失败";
        }

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

    /**
     * 导出厂商数据
     * @return string
     */
    public function actionExport()
    {
        $params = $this->dataList(0);
        return $this->renderPartial('export', $params);
    }

    /**
     * 厂商管理
     */
    public function actionSelectManufacture()
    {
        $params = $this->dataListManufacture(1);
        /**
         * 渲染模板
         */
        return $this->render('select-manufacture', $params);
    }

    /**
     * 查询数据列表
     */
    protected function dataListManufacture($type = '')
    {
        $request     = Yii::$app->request;
        $creatTime   = $request->get('creatTime');
        $endTime     = $request->get('endTime');
        $name =  $request->get('name');
        $phone =  $request->get('phone');
        $loginName =  $request->get('loginName');

        $version =  $request->get('version');
        $uid =  $request->get('uid');
        $package_name =  $request->get('package_name');
        $manufacture_id =  $request->get('manufacture_id');
        $path =  $request->get('path');
        $size =  $request->get('size');
        $file_md5 =  $request->get('file_md5');
        $oldName =  $request->get('oldName');
        $type =  $request->get('type');
        $isCreate =  $request->get('isCreate');

        $gets = [
            'creatTime'  => $creatTime,
            'endTime'    => $endTime,
            'name'       => $name,
            'phone'      => $phone,
            'loginName'  => $loginName,
            'version'    => $version,
            'package_name' => $package_name,
            'path' => $path,
            'size' => $size,
            'file_md5' => $file_md5,
            'manufacture_id' => $manufacture_id,
            'oldName' => $oldName,
            'type' => $type,
            'uid' => $uid,
            'isCreate' => $isCreate,
        ];

        $where = ['and'];
        if ($name) {
            $where[] = ['like', 'name', $name];
        }
        if ($phone) {
            $where[] = ['like', 'phone', $phone];
        }
        if ($loginName) {
            $where[] = ['like', 'username', $loginName];
        }
        if ($creatTime) {
            $creatTime = strtotime($creatTime);
            $where[] = ['>=', 'm.created_at', $creatTime];
        }
        if ($endTime) {
            $endTime = strtotime($endTime) + 86400;
            $where[] = ['<=', 'm.created_at', $endTime];
        }
        if ($type == 0) {
            $pageList = ManufacturerRepository::getPageList($where, 0 , 0);
            $pages = null;
        } else {
            $pageSize = 8;
            $pages = new Pagination(['totalCount' => ManufacturerRepository::getPageCount($where), 'pageSize' => $pageSize]);
            $pageList = ManufacturerRepository::getPageList($where, $pages->offset, $pages->limit);
        }

        /**
         * 数据整理
         */
        return [
            'listdata'   => $pageList,
            'pages'      => $pages,
            'gets'       => $gets
        ];
    }

    /**
     * 上传文件函数,如过上传不成功打印$_FILES数组,查看error报错信息
     * 值:0; 没有错误发生,文件上传成功。
     * 值:1; 上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值。
     * 值:2; 上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值。
     * 值:3; 文件只有部分被上传。
     * 值:4; 没有文件被上传。
     * date:2018.4.18    from:zhix.net
     */
    public function actionUploadFile()
    {
        header("Expires: Mon, 26 Jul 2020 05:00:00 GMT");
        header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
        header("Content-type: text/html; charset=utf-8");
        header("Cache-Control: no-store, no-cache, must-revalidate");
        header("Cache-Control: post-check=0, pre-check=0", false);
        header("Pragma: no-cache");

        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
            exit; // finish preflight CORS requests here
        }
        if ( !empty($_REQUEST[ 'debug' ]) ) {
            $random = rand(0, intval($_REQUEST[ 'debug' ]) );
            if ( $random === 0 ) {
                header("HTTP/1.0 500 Internal Server Error");
                exit;
            }
        }
        // header("HTTP/1.0 500 Internal Server Error");
        // exit;
        // 5 minutes execution time
        set_time_limit(60 * 60);
        // Uncomment this one to fake upload time
        usleep(5000);
        // Settings
        $upload = dirname(dirname(dirname(__DIR__))) . "/web/upload";
        $savePath = 'web/upload/packages/package_' . date("Ymd");
        $assetsUrl = Yii::$app->params['assetsUrl'];
        $targetDir = $upload . '/packages/file_material_tmp/' . Yii::$app->user->id;            //存放分片临时目录
        $uploadDir = $upload . '/packages/package_' . date("Ymd");

        $cleanupTargetDir = true; // Remove old files
        $maxFileAge = 5 * 3600; // Temp file age in seconds

        // Create target dir
        if (!file_exists($targetDir)) {
            mkdir($targetDir,0777,true);
        }
        // Create target dir
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir,0777,true);
        }
        // Get a file name
        if (isset($_REQUEST["name"])) {
            $fileName = $_REQUEST["name"];
        } elseif (!empty($_FILES)) {
            $fileName = $_FILES["file"]["name"];
        } else {
            $fileName = uniqid("file_");
        }
        $oldName = $fileName;

        //$fileName = iconv('gbk','UTF-8',$fileName);
        $filePath = $targetDir . "/" . $fileName;
        // $uploadPath = $uploadDir . "/" . $fileName;
        // Chunking might be enabled
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
        // Remove old temp files
        if ($cleanupTargetDir) {
            if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
            }
            while (($file = readdir($dir)) !== false) {
                $tmpfilePath = $targetDir . "/" . $file;
                // If temp file is current file proceed to the next
                if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                    continue;
                }
                // Remove temp file if it is older than the max age and is not the current file
                if (preg_match('/\.(part|parttmp)$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
                    unlink($tmpfilePath);
                }
            }
            closedir($dir);
        }
        // Open temp file
        if (!$out = fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
            die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
        }
        if (!empty($_FILES)) {
            if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
            }
            // Read binary input stream and append it to temp file
            if (!$in = fopen($_FILES["file"]["tmp_name"], "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 104, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        } else {
            if (!$in = fopen("php://input", "rb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 105, "message": "Failed to open input stream."}, "id" : "id"}');
            }
        }
        while ($buff = fread($in, 4096)) {
            fwrite($out, $buff);
        }
        fclose($out);
        fclose($in);
        rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");
        $index = 0;
        $done = true;
        for( $index = 0; $index < $chunks; $index++ ) {
            if ( !file_exists("{$filePath}_{$index}.part") ) {
                $done = false;
                break;
            }
        }

        if ($done) {
            $pathInfo = pathinfo($fileName);
            $hashStr = substr(md5($pathInfo['basename']),8,16);
            $hashName = time() . $hashStr . '.' .$pathInfo['extension'];
            $uploadPath = $uploadDir . "/" .$hashName;
            $saveUploadPath = $savePath . "/" . $hashName;
            if (!$out = fopen($uploadPath, "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 106, "message": "Failed to open output stream."}, "id" : "id"}');
            }
            //flock($hander,LOCK_EX)文件锁
            if ( flock($out, LOCK_EX) ) {
                for( $index = 0; $index < $chunks; $index++ ) {
                    if (!$in = fopen("{$filePath}_{$index}.part", "rb")) {
                        break;
                    }
                    while ($buff = fread($in, 4096)) {
                        fwrite($out, $buff);
                    }
                    fclose($in);
                    unlink("{$filePath}_{$index}.part");
                }
                flock($out, LOCK_UN);
            }
            fclose($out);

            $savePath = self::getFilePath(Yii::$app->user->id, $hashName);

            $response = [
                'success'       => true,
                'oldName'       => $oldName,
                'filePath'      => $savePath,
                'uploadPath'    => $saveUploadPath,
                'fileSize'      => filesize($uploadPath),
                'fileSuffixes'  => $pathInfo['extension'],          //文件后缀名
                'file_md5'      => md5_file($uploadPath),
            ];

            // 上传OSS

           /* 分两步上传
           $fileService = new FileService();
            $fileService->add($uploadPath, $savePath);*/

            // 删除服务器传成功的文件
            //@unlink($uploadPath);

            /**
             * 后台操作日志
             */
            AdminLogs::doImport('上传APP版本', 1);
            return json_encode($response);
        }

        // Return Success JSON-RPC response
        die('{"jsonrpc" : "2.0", "result" : null, "id" : "id"}');
    }

    /**
     * 同步文件到OSS
     * @return array
     */
    public function actionPushOss()
    {
        $e = new stdClass();
        try {
            $request     = Yii::$app->request;
            $upgradeId   = $request->post('upgrade_id');
            $e->success = false;
            $e->message = "";
            if (empty($upgradeId)) {
                $e->message = "缺少版本编号";
                return $this->renderJson($e);
            }
            $upgradeModel = UpgradeRepository::findOne($upgradeId);
            if (empty($upgradeModel)) {
                $e->message = "该版本不存在";
                return $this->renderJson($e);
            }
            $uploadPath = dirname(dirname(dirname(__DIR__))) . "/" . $upgradeModel->upload_path;
            if (!file_exists($uploadPath)) {
                $e->message = "该版本ECS文件不存在";
                return $this->renderJson($e);
            }
            $savePath = $upgradeModel->path;
            $fileService = new FileService();
            $fileService->add($uploadPath, $savePath);
            $upgradeModel->oss_upload_status = UpgradeStatus::OSS_UPLOAD_SUCCESS;
            $upgradeModel->save();
            $e->success = true;
            $e->message = "同步OSS成功";
            return $this->renderJson($e);
        } catch (\Exception $ex) {
            $e->message = "同步OSS异常:" . $ex->getMessage();
            return $this->renderJson($e);
        }
    }

    /**
     * 发布APP版本
     * @return string
     */
    public function actionPushApp()
    {
        $upgradeId = $this->request->get("uid");
        $info = UpgradeRepository::selectOne($upgradeId, true);
        if (isset($info["path"])) {
            $info["oldName"] = $info["path"];
            $manufacture = ManufacturerRepository::selectOne($info["manufacture_id"]);
            if (isset($manufacture["name"])) {
                $info["manufacture_name"] = $manufacture["name"];
            }
            $project = ProjectRepository::selectOne($info["project_id"]);
            if (isset($project["name"])) {
                $info["project_name"] = $project["name"];
            }
            $model = ModelRepository::selectOne($info["model_id"]);
            if (isset($model["name"])) {
                $info["model_name"] = $model["name"];
            }
        }
        return $this->render('push-app', ["info" => $info]);
    }

    /**
     * 发布OTA版本
     * @return string
     */
    public function actionPushOta()
    {
        $upgradeId = $this->request->get("uid");
        $info = UpgradeRepository::selectOne($upgradeId, true);
        if (isset($info["path"])) {
            $info["oldName"] = $info["path"];
            $manufacture = ManufacturerRepository::selectOne($info["manufacture_id"]);
            if (isset($manufacture["name"])) {
                $info["manufacture_name"] = $manufacture["name"];
            }
            $project = ProjectRepository::selectOne($info["project_id"]);
            if (isset($project["name"])) {
                $info["project_name"] = $project["name"];
            }
            $model = ModelRepository::selectOne($info["model_id"]);
            if (isset($model["name"])) {
                $info["model_name"] = $model["name"];
            }
        }
        return $this->render('push-ota', ["info" => $info]);
    }

    /**
     * 发布版本
     * @return string
     */
    public function actionDoPushApp()
    {
        $request = Yii::$app->request;
        $selFocuse = $request->post("focuse");
        $uid = $request->post("uid");
        $type = $request->post("type");

        if (empty($uid)) {
            Yii::$app->session->setFlash('error', '版本编号不能为空');
            $params = $this->dataList(1);
            return $this->render('index', $params);
        }
        $upgradeModel = UpgradeRepository::findOne(['id' => $uid, 'is_delete' => 0]);
        if (!$upgradeModel) {
            Yii::$app->session->setFlash('error', '未找到升级记录');
            $params = $this->dataList(1);
            return $this->render('index', $params);
        }
        if (UpgradeStatus::TYPE_OTA == $upgradeModel->type) {
            $upgradeURL = 'push-ota?uid='.$uid;
        } else {
            $upgradeURL = 'push-app?uid='.$uid;
        }
        if (empty($selFocuse)) {
            Yii::$app->session->setFlash('error', '请选择是否强制升级');
            return $this->redirect($upgradeURL);
        }

        if (empty($upgradeModel->manufacture_id)) {
            Yii::$app->session->setFlash('error', '请先配置好厂商');
            return $this->redirect($upgradeURL);
        }
        if (empty($upgradeModel->project_id)) {
            Yii::$app->session->setFlash('error', '请先配置版本项目');
            return $this->redirect($upgradeURL);
        }
        if (empty($upgradeModel->model_id)) {
            Yii::$app->session->setFlash('error', '请先配置版本型号');
            return $this->redirect($upgradeURL);
        }
        $exitUpgradeModel = UpgradeRepository::findOne([
            'manufacture_id' => $upgradeModel->manufacture_id,
            'project_id'    => $upgradeModel->project_id,
            'model_id'      => $upgradeModel->model_id,
            'is_delete'     => 0,
            'type'          => $upgradeModel->type,
            'version'       => $upgradeModel->version,
            'package_name'  => $upgradeModel->package_name,
            'status'        => UpgradeStatus::STATUS_ON
        ]);

        if ($exitUpgradeModel && $upgradeModel->id != $exitUpgradeModel->id) {
            Yii::$app->session->setFlash('error', '该厂商该批次已经存在一个版本号为:'.$exitUpgradeModel->version.'的发布版本,请先取消它再发布');
            return $this->redirect($upgradeURL);
        }

        $result = Upgrade::update($uid, $request->post());

        if ($result === -1) {
            Yii::$app->session->setFlash('error', '发布失败');
        }
        if ($result) {
            Yii::$app->session->setFlash('success', '发布成功');
        } else {
            Yii::$app->session->setFlash('error', '发布失败');
        }

        return $this->redirect('index?type=' . (!empty($request->post("type")) ? $request->post("type") : UpgradeStatus::TYPE_APP));
    }

    /**
     * 获取文件存储路径: bind_apply/20170509/[userId]/文件名
     * @param $userId
     * @param $suffix 文件后缀
     * @return string
     */
    public static function getFilePath($userId, $filename)
    {
        $basePath = "upgrade_packages/" . date("Ymd") . '/' . $userId;
        $savePath = $basePath . '/' . $filename;
        return $savePath;
    }

    /**
     * @return string
     */
    public function actionCheckUpgrade()
    {
        $e = new stdClass();
        $e->success = false;
        $request = Yii::$app->request;
        $manufactureId = $request->post("manufacture");
        $projectId = $request->post("project");
        $modelId = $request->post("model");
        $type = $request->post("type");
        $id = $request->post('id');
        $version = $request->post('version');
        $package_name = $request->post('package_name');
        if (empty($package_name)) {
            $e->message = '请先录入一个包名';
            return $this->renderJson($e);
        }
        if (empty($manufactureId)) {
            $e->message = '请先选择厂商';
            return $this->renderJson($e);
        }

        if (empty($projectId)) {
            $e->message = '请先选择项目';
            return $this->renderJson($e);
        }

        if (empty($modelId)) {
            $e->message = '请先选择型号';
            return $this->renderJson($e);
        }

        $upgradeModel = UpgradeRepository::findOne(['manufacture_id' => $manufactureId, 'project_id' => $projectId, 'model_id' => $modelId, 'is_delete' => 0, 'package_name' => $package_name, 'type' => $type]);
        if ($upgradeModel && empty($id) ) {
                $e->message = '该厂商该批次已经存在一个版本号为:'.$upgradeModel->version.' 包名为'.$package_name.'的版本,请先确认再上传';
                return $this->renderJson($e);

        }

        if ($upgradeModel && !empty($id) && $id != $upgradeModel->id ) {
            $e->message = '该厂商该批次已经存在一个版本号为:'.$upgradeModel->version.' 包名为'.$package_name.'的版本,请先确认再上传!';
            return $this->renderJson($e);
        }
        $e->success = true;
        $e->message = 'ok';

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