<?php

namespace console\controllers;

use Yii;
use yii\console\Controller;
use yii\helpers\Console;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use common\models\User;
use common\models\Category;

/**
 * Description of RbacsetController
 *
 * @author blobt
 */
class InitController extends Controller {

    public function actionIndex() {
        echo "index\n";
        Category::deleteAll();
        for ($i = 0; $i < 1000000; $i++) {
            $model = new Category();
            $model->attributes = [
                "cat_name" => "这是一个测试分类{$i}",
                "icon" => 'fa',
                "icon_type" => 1,
                "sort_order" => $i,
                "created_at" => time() - rand(10000, 1000000)
            ];
            $model->save();
        }
    }

    public function actionCreateAdmin($password = NULL) {
        $auth = Yii::$app->authManager;
        while ($password == NULL) {
            $password = $this->prompt("\n\n请输入admin用户密码(最少6位任意字符):");

            if (strlen($password) < 6) {
                $password = NULL;
                continue;
            }
            break;
        }

        $this->createAdmin($password);
    }

    /**
     * 数据迁移
     * @param sring $migrationPath 数据迁移代码目录
     */
    private function migrate($migrationPath = "@app/migrations") {
        $migrate = Yii::createObject("yii\console\controllers\MigrateController", ["action", $this]);
        $migrate->interactive = false;
        $migrate->migrationPath = $migrationPath;
        $migrate->runAction("up", []);
    }

    /**
     * TODO没有完善
     * 清空数据库
     */
    public function actionClearDb() {
        Yii::$app->db->createCommand("SET FOREIGN_KEY_CHECKS = 0;")->execute();
        $dbname = explode('=', explode(';', Yii::$app->db->dsn)[1])[1];
        $sql = "SELECT CONCAT('drop table ',table_name,';') FROM information_schema.`TABLES` WHERE table_schema='{$dbname}';";
        $sqls = Yii::$app->db->createCommand($sql)->queryColumn();
        foreach ($sqls as $dropSql) {
            Yii::$app->db->createCommand($dropSql)->execute();
        }
    }

    /**
     * 创建管理员
     * @param string $password 管理员密码
     */
    private function createAdmin($password) {
        $auth = Yii::$app->authManager;

        $model = User::findOne("username = 'admin");

        if (empty($model)) {
            $model = new User();
        }

        $model->username = "admin";
        $model->email = "admin@kcshop.store";
        $model->setPassword($password);
        $model->generateAuthKey();
        $model->status = User::STATUS_ACTIVE;
        $model->created_at = $model->updated_at = time();
        if ($model->save()) {
            //$oRole = $auth->getRole("超级管理员");
            //if ($auth->assign($oRole, $model->id)) {
            $this->stdout("Create admin success!\n", Console::FG_GREEN);
            //}
        }
    }

}