<?php
declare (strict_types=1);

namespace app\controller;

use app\model\Access;
use think\exception\ValidateException;
use think\facade\Db;
use think\facade\Validate;
use think\Request;
use app\validate\Admin as AdminValidate;
use app\model\Admin as AdminModel;

class Admin
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {

        $list = AdminModel:: paginate([
            'list_rows' => 5,
            'query' => request()->param()
        ]);
        return json($list);
    }

    public function admin_all()
    {

        $list = AdminModel::select();
        return json($list);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     * @return string|\think\Response
     */
    private function PasswordStrongEnough($password)
    {
        $error = "";
        if (strlen($password) < 10) {
            $error .= "密码至少为10位";
            return $error;
        }
        if (!preg_match("/[a-z]/", $password)) {
            $error .= "密码至少包含一个小写字母";
            return $error;
        }
        if (!preg_match("/[A-Z]/", $password)) {
            $error .= "密码至少包含一个大写字母";
            return $error;
        }
        if (!preg_match("/[0-9]/", $password)) {
            $error .= "密码至少包含一个数字";
            return $error;
        }
        if (!preg_match("/[.!@#$%]/", $password)) {
            $error .= "密码至少包含:(.!@#$%)其中一个符号";
            return $error;
        }
    }

    public function save(Request $request)
    {
        $data = $request->param();
        $username = $data['username'];
        $nickname = $data['nickname'];
        $password = $data['password'];
        $email = $data['email'];
        $phone = $data['phone'];
        $passwordStrengthErrors = $this->PasswordStrongEnough($password);
        if (!empty($passwordStrengthErrors)) {
            return json(['code' => 1, 'message' => '密码强度不足,' . $passwordStrengthErrors]);
        }
        $id = AdminModel::where('username', $username)->value('id');
        if (empty($id)) {
            AdminModel::create([
                'username' => $username,
                'password' => $password,
                'nickname' => $nickname,
                'email' => $email,
                'phone' => $phone
            ]);
            return json(['code' => 200, 'message' => '注册成功']);
        } else {
            return json(['code' => 1, 'message' => '用户名已存在']);
        }

    }

    /**
     * 显示指定的资源
     *
     * @return \think\Response
     */
    public function read(Request $request)
    {
        $data = $request->param();
        $message = "'%" . $data['message'] . "%'";
        $list = Db::table('admin')->whereRaw('(username like' . $message . ' or nickname like' . $message . ' or email like' . $message . ' or phone like' . $message . ' or roles like ' . $message . ')')->paginate(20);
        return json($list);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {

    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     *
     * @return \think\Response
     */
    public function update(Request $request): \think\Response
    {
        $data = $request->param();

        $validate = Validate::rule([
            'username' => 'require|min:2|max:10|chsDash|unique:admin',
            //'__token__'         =>  'require|token',
            'nickname' => 'require|min:2|max:10|chsDas',
            'password' => 'require|min:6',
            'email' => 'require|email|unique:admin',
            'phone' => 'require|number|length:11|unique:admin'
        ]);
        try {
            $validate->batch(true)->check($request->param());
        } catch (ValidateException $exception) {
            return json(['code' => 1, 'massage' => $exception->getError()]);
        }
        $id = AdminModel::where('username', $data['username'])->value('id');
        if (!empty($id)) {
            AdminModel::update([
                'nickname' => $data['nickname'],
                'password' => $data['password'],
                'email' => $data['email'],
                'phone' => $data['phone'],
                'roles' => $data['roles']
            ], ['id' => $id]);
            return json(['code' => 200, 'massage' => '修改成功']);
        } else {
            return json(['code' => 1, 'massage' => '用户不存在']);
        }
    }

    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete(Request $request)
    {
        $data = $request->param();
        $username = $data['username'];
        $id = AdminModel::where('username', $username)->value('id');
        if ($id != null) {
            $result = AdminModel::destroy($id);
            if ($result) {
                return json(['code' => 200, 'massage' => '删除成功']);
            } else {
                return json(['code' => 1, 'massage' => '删除失败']);
            }
        } else {
            return json(['code' => 1, 'massage' => '该管理员不存在']);
        }

    }

    public function update_password(Request $request)
    {
        $data = $request->param();
        $phone = $data['phone'];
        $id = AdminModel::where(['username' => $data['username'], 'phone' => $phone])->find()->getData('id');
        if (!empty($id)) {
            $password = $data['password'];
            $result = AdminModel::where('id', $id)->update(['password' => $password]);
            if ($result == 0) {
                return json(['code' => 1, 'message' => '手机号或用户名错误！']);
            } else {
                return json(['code' => 200, 'message' => '已成功修改密码']);
            }
        }
    }

    public function change_password(Request $request)
    {
        $data = $request->param();
        $username = $data['username'];
        $old_password = $data['old_password'];
        $id = AdminModel::where(['username' => $username, 'password' => $old_password])->value('id');
        if (!empty($id)) {
            $new_password = $data['new_password'];
            $result = AdminModel::where('id', $id)->update(['password' => $new_password]);
            if ($result == 1) {
                return json(['code' => 200, 'message' => '已成功修改密码']);
            }
        } else {
            return json(['code' => 1, 'message' => '原始密码不正确']);
        }
    }

    public function UpdatePermission($admin_id, $permission = array())
    {
        if (empty($permission)) {
            $pp = Db::table('admin')->where('id', $admin_id)->value('permission');
            if (!empty($pp)) {
                $pp = explode(',', substr($pp, 0, -1));
            } else {
                $pp = array();
            }
            $username = Db::table('admin')->where('id', $admin_id)->value('username');
            return json(['code' => 200, 'msg' => 'Query OK', 'data' => ['admin_id' => $admin_id, 'adminName' => $username, 'permission' => $pp]]);
        } else {
            $pstr = '';
            foreach ($permission as $pp) {
                $pstr .= $pp . ',';
            }
            Db::table('admin')->where('id', $admin_id)->save(['permission' => $pstr]);
            $pp = explode(',', substr($pstr, 0, -1));
            return json(['code' => 200, 'msg' => 'Update OK', 'data' => ['permission' => $pp]]);
        }
    }

}
