<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2020/2/4
 * Time: 12:47
 */

namespace app\common\command;

use app\admin\model\Admin;
use app\admin\model\AdminCate;
use app\admin\model\AdminMenu;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

class ResetPassWord extends Command
{
    /**
     * 重置管理员账号密码
     * php think ResetPassWord
     */
    protected function configure()
    {
        $this->setName('ResetPassWord')
            ->addArgument('new_pass', Argument::OPTIONAL, "input new pass", "123456")//重置密码
            ->addOption('new_permission', 'p', Option::VALUE_NONE, 'reset permission')//是否重置admin权限
            ->setDescription('reset admin password');
    }

    protected function execute(Input $input, Output $output)
    {
        $newpass = $input->getArgument("new_pass");
        $data = ['name' => 'admin', 'admin_cate_id' => 1, 'password' => password($newpass)];

        $admin = Admin::get(1);
        if (!$admin) {
            $data['nickname'] = systemName();
            $admin = new Admin();
        }
        $res = $admin->save($data);
        if ($res) {
            $output->writeln("<info>reset password success (admin new password : " . $newpass . ")</info>");
        } else {
            $output->writeln("<error>reset password fail</error>");
        }

        if ($input->getOption("new_permission")) {
            $cate = AdminCate::get(1);
            if (!$cate) {
                $cate = new AdminCate();
            }
            $res = $cate->save(['name' => '超级管理员', 'permissions' => implode(',', (new AdminMenu())->column('id'))]);
            if ($res) {
                $output->writeln("<info>reset permissions success</info>");
            } else {
                $output->writeln("<error>reset permissions fail</error>");
            }
        }
    }
}