<?php

namespace app\admin\controller\User;

use app\common\arw\adjfut\src\Traverse;
use app\BaseController;
use app\exception\ErrorMsg;
use app\model\Role;
use app\common\model\Token;
use app\common\model\User\User as ModelUser;
use app\common\model\Role\Role as ModelRole;
use app\common\model\User\UserRole as ModelUserRole;
use app\model\UserRole;
use app\Request;
use think\db\Query;
use think\Exception;
use think\facade\Db;
use app\common\arw\adjfut\src\Validate;
use app\common\arw\adjfut\src\Excel;
use app\common\arw\adjfut\src\UploadFile;

class User extends BaseController
{
    /**
     * 获取用户信息
     *
     * @param Request $request
     * @date 2022-03-09
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function getUserInfo(Request $request): array
    {
        $user = $request->getCurrentUser();
        return [
            'code' => 0,
            'data' => [
                'user_name' => $user['user_name']
            ],
            'msg' => 'ok'
        ];
    }

    /**
     * 获取用户菜单
     *
     * @param Request $request
     * @return array
     * @date 2022-03-05
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function getUserMenu(Request $request)
    {
        // $user = $request->getCurrentUser();
        // $menus = [];
        // foreach ($user->roles as $role) {
        //     $menus = array_merge($menus, $role->menus->toArray());
        // }

        // array_multisort(array_column($menus, 'menu_order'), SORT_DESC, $menus);

        // var_dump($menus);

        $token = Token::getCurrent();
        $menus = $token->token_menu;

        $Traverse = new Traverse('menu_guid', 'menu_parent_guid');

        $tree = $Traverse->tree($menus, '0', function ($v) {
            return [
                'key' => $v['menu_guid'],
                'name' => $v['menu_name'],
                'url' => $v['menu_url'],
                'show' => $v['menu_show'],
                'icon' => $v['menu_icon'],
            ];
        });

        return [
            'code' => 0,
            'msg' => 'ok',
            'data' => $tree
        ];
    }

    /**
     * 获取用户列表
     *
     * @param Request $request
     * @date 2022-02-25
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function getUserList(Request $request): array
    {
        $user = $request->param('user');
        $con = [
            // 'user_status' => 1
        ];
        $search = [];
        if ($user) {
            $search['user_name'] = $user;
        }
      
        $query = ModelUser::scope(['admin'])
            ->withSearch(array_keys($search), $search)->where($con)
        ->leftjoin('user_role', 'user_role.user_guid = user.user_guid')
        ->join('role', join(' AND ', [
            'role.role_guid = user_role.role_guid',
            'role.role_status = 1',
            'role.role_delete_time IS NULL',
        ]), 'left')->where($con);
        $select =  self::pageWrapper($query)->field([
            'user.user_guid',
            'user.user_name',
            'user.user_phone',
            'user.user_position',
            'user.user_department',
            'user.user_img',
            'user.user_status',
            'role.role_name',
        ])
        ->append([
            'roles',
        ])
        ->group('user.user_guid')->order([
            'user.user_update_time' => 'desc'
        ])->select();
        $count =  $query->count();
        return [
            'code' => 0,
            'data' => $select,
            'count' => $count,
            'msg' => 'ok'
        ];
    }

    /**
     * 编辑用户
     *
     * @param Request $request
     * @date 2022-02-28
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function editUser(Request $request): array
    {
        $params = Validate::param([
            'user_guid' => 'require',
            'user_name' => 'require',
            'roles|角色' => 'require',
        ]);
        $model = ModelUser::where([
            'user_guid' => $params['user_guid']
        ])->find();
        if (!$model) {
            throwErrorMsg("用户不存在", 1);
        }
        $model->save($params);
        ModelUser::editUserRole($params);
        return [
            'code' => 0,
            'msg' => '编辑成功'
        ];
    }

    /**
     * 添加用户
     *
     * @param Request $request
     * @date 2022-02-28
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function addUser(Request $request): array
    {
        $params = Validate::param([
            'user_name' => 'require',
            'user_password' => 'require',
            'roles|角色' => 'require',
        ]);
        $params['user_status'] = 1;

        $model = ModelUser::create($params);

        $user_guid = $model->user_guid;

        ModelUser::addUserRole($user_guid, $params);

        return [
            'code' => 0,
            'msg' => '添加成功'
        ];
    }

    /**
     * 删除用户
     *
     * @param Request $request
     * @date 2022-02-28
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function deleteUser(Request $request): array
    {
        $params = $request->param();
        $this->validate($params, [
            'user_guid' => 'require',
        ]);
        $users = ModelUser::where([
            'user_guid' => explode(',', $params['user_guid'])
        ])->select();
        $users->delete();
        return [
            'code' => 0,
            'msg' => "删除成功"
        ];
    }

    /**
     * 更新用户状态
     *
     * @param Request $request
     * @date 2022-02-28
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function updateUserStatus(Request $request): array
    {
        $params = $request->param();
        $this->validate($params, [
            'user_guid' => 'require',
            'user_status' => 'require|in:1,2',
        ]);
        $user_status = $params['user_status'];
        $users = ModelUser::where([
            'user_guid' => explode(',', $params['user_guid'])
        ])->select();
        $users->update([
            'user_status' => $user_status
        ]);
        return [
            'code' => 0,
            'msg' => "更新成功"
        ];
    }

    /**
     * 重置用户密码
     *
     * @param Request $request
     * @date 2022-02-25
     * @example
     * @author admin
     * @since 1.0.0
     */
    public function resetUserPassword(Request $request): array
    {
        $params = Validate::param([
            'user_guid' => 'require',
            'password' => 'require',
        ]);
        $password = $params['password'];
        $users = ModelUser::select(explode(',', $params['user_guid']));
        // $users = ModelUser::where([
        //     'user_guid' => ['in', $params['user_guid']]
        // ])->select();
        $users->update([
            'user_password' => $password
        ]);
        return [
            'code' => 0,
            'msg' => "密码已重置为：$password ，请及时修改密码"
        ];
    }


    /**
     * 导出Excel
     */
    public function exportExcel(Request $request)
    {
        $user = $request->param('user');
        $con = [
            // 'user_status' => 1
        ];
        $search = [];
        if ($user) {
            $search['user_name'] = $user;
        }
      
        $select = ModelUser::scope(['admin'])
            ->where($con)->field([
            'user.user_guid',
            'user.user_name',
            'user.user_phone',
            'user.user_position',
            'user.user_department',
            'user.user_img',
            'role.role_name',
        ])
        ->append([
            'roles',
        ])
        ->withSearch(array_keys($search), $search)->where($con)
        ->leftjoin('user_role', 'user_role.user_guid = user.user_guid')
        ->join('role', join(' AND ', [
            'role.role_guid = user_role.role_guid',
            'role.role_status = 1',
            'role.role_delete_time IS NULL',
        ]), 'left')
        ->group('user.user_guid')->order([
            'user.user_update_time' => 'desc'
        ])->select();

        return ModelUser::exportExcel($select);
    }

    /**
     * 下载导入模板
     */
    public function downloadTemplate(Request $request)
    {
        $params = $request->param();
        $data = [
            [
                '用户名',
                '头像',
                '角色',
                '手机号',
                '密码',
            ]
        ];

        $data[] = [
            '负责人',
            'https://img13.360buyimg.com/n5/jfs/t1/195344/2/24691/95759/6295e145E6fae20b9/1172b44c351eeaab.jpg.avif',
            '管理员,部门负责人',
            '10086',
            '123456@aerwen',
        ];

        $excel = (new Excel())->exporTsheet($data);
        $excel->save('用户导入模板.xlsx');
    }

    /**
     * 导入excel
     */
    public function importExcel(Request $request)
    {
        $file = new UploadFile('uploads', 'fileExt:xlsx');
        $file->putFile('User');

        $msg = ModelUser::importExcel($file);

        return [
            'code' => 0,
            'msg' => $msg
        ];
    }

}
