<?php

namespace app\controller\admin\system;

use app\BaseController;
use app\entity\SysUser;
use app\service\CurdService;
use think\db\exception\{DataNotFoundException, DbException, ModelNotFoundException};
use think\response\Json;

class UserController extends BaseController
{
    /**
     * 分页获取用户列表
     * @return Json
     * @throws DbException
     */
    public function page(): Json
    {
        $model = SysUser::with(['roles'])
            ->withSearch(['organizationId', 'username', 'nickname', 'sex'], [
                'organizationId' => $this->request->get('organizationId/d', 0),
                'username' => $this->request->get('username/s', ''),
                'nickname' => $this->request->get('nickname/s', ''),
                'sex' => $this->request->get('sex/d', 0),
            ])->append(['sexName']);

        $paginate = CurdService::getPaginate($this->request, $model);

        return $this->writeSuccess('success', $paginate);
    }

    /**
     * 新增用户
     * @return Json
     */
    public function add(): Json
    {
        $data = $this->request->post([
            'birthday' => null,
            'username' => '',
            'email' => '',
            'nickname' => '',
            'introduction' => '',
            'organizationId' => 0,
            'phone' => '',
            'sex' => '',
            'status' => 0,
            'roles' => [],
        ]);
        $data['roles'] = array_column((array)$data['roles'], 'roleId');

        $user = new SysUser();
        $user->save([
            'birthday' => $data['birthday'],
            'username' => $data['username'],
            'nickname' => $data['nickname'],
            'introduction' => $data['introduction'],
            'organization_id' => $data['organizationId'],
            'phone' => $data['phone'],
            'sex' => $data['sex'],
            'status' => $data['status'],
            'email' => $data['email'],
            'password' => password_hash($data['password'], PASSWORD_DEFAULT),
        ]);
        $user->roles()->saveAll($data['roles']);

        return $this->writeSuccess('添加成功');
    }

    /**
     * 更新用户信息
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function update(): Json
    {
        $data = $this->request->put([
            'userId' => 0,
            'birthday' => null,
            'username' => '',
            'email' => '',
            'nickname' => '',
            'introduction' => '',
            'organizationId' => 0,
            'phone' => '',
            'sex' => '',
            'status' => 0,
            'roles' => [],
        ]);
        $data['roles'] = array_column((array)$data['roles'], 'roleId');

        $user = SysUser::findOrFail($data['userId']);
        $updateOk = $user->save([
            'birthday' => $data['birthday'],
            'username' => $data['username'],
            'nickname' => $data['nickname'],
            'introduction' => $data['introduction'],
            'organization_id' => $data['organizationId'],
            'phone' => $data['phone'],
            'sex' => $data['sex'],
            'status' => $data['status'],
            'email' => $data['email'],
        ]);
        if (!$updateOk) {
            return $this->writeError('修改失败');
        }
        $user->roles()->attach($data['roles']);

        return $this->writeSuccess('修改成功');
    }

    /**
     * 批量删除用户
     * @return Json
     */
    public function batchRemove(): Json
    {
        $data = $this->request->delete();
        SysUser::destroy($data);
        return $this->writeSuccess('删除成功');
    }

    /**
     * 修改用户状态
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function updateStatus(): Json
    {
        $userId = $this->request->put('userId/d', 0);
        $status = $this->request->put('status/d', 0);
        SysUser::findOrfail($userId)->save(['status' => $status]);
        return $this->writeSuccess('操作成功');
    }

    /**
     * 修改用户密码
     * @return Json
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function updatePassword(): Json
    {
        $userId = $this->request->put('userId/d', 0);
        $password = $this->request->put('password/s', 0);

        SysUser::findOrfail($userId)->save(['password' => password_hash($password, PASSWORD_DEFAULT)]);

        return $this->writeSuccess('操作成功');
    }

    /**
     * 判断数据是否存在
     * @return Json
     */
    public function existence(): Json
    {
        $field = $this->request->get('field/s', '');
        $value = $this->request->get('value/s', '');
        try {
            SysUser::field('user_id')->where([$field => $value])->findOrFail();
        } catch (ModelNotFoundException|DataNotFoundException) {
            return $this->writeError("用户不存在");
        }
        return $this->writeSuccess('用户已存在');
    }
}