/*
 *
 *      Copyright (c) 2018-2025, avenue All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the pig4cloud.com developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: avenue
 *
 */

package com.emergency.avenue.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.emergency.avenue.admin.api.dto.UserDTO;
import com.emergency.avenue.admin.api.dto.UserInfo;
import com.emergency.avenue.admin.api.entity.SysRole;
import com.emergency.avenue.admin.api.entity.SysUser;
import com.emergency.avenue.admin.api.vo.UserExcelVO;
import com.emergency.avenue.admin.api.vo.UserVO;
import com.emergency.avenue.admin.service.SysUserService;
import com.emergency.avenue.common.core.constant.CommonConstants;
import com.emergency.avenue.common.core.exception.ErrorCodes;
import com.emergency.avenue.common.core.util.MsgUtils;
import com.emergency.avenue.common.core.util.R;
import com.emergency.avenue.common.excel.annotation.RequestExcel;
import com.emergency.avenue.common.excel.annotation.ResponseExcel;
import com.emergency.avenue.common.log.annotation.SysLog;
import com.emergency.avenue.common.security.annotation.Inner;
import com.emergency.avenue.common.security.util.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author avenue
 * @date 2018/12/16
 */
@RestController
@AllArgsConstructor
@RequestMapping("/user")
@Tag(description = "user", name = "用户管理模块")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class SysUserController {

	private final SysUserService userService;

	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();

	/**
	 * 获取指定用户全部信息
	 * @return 用户信息
	 */
	@Inner
	@Operation(summary = "获取指定用户全部信息", description = "获取指定用户全部信息")
	@GetMapping("/info/{username}")
	public R<UserInfo> info(@PathVariable String username) {
		SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
		if (user == null) {
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_USERINFO_EMPTY, username));
		}
		return R.ok(userService.findUserInfo(user));
	}

	/**
	 * 获取当前用户全部信息
	 * @return 用户信息
	 */
	@Operation(summary = "获取当前用户全部信息", description = "获取当前用户全部信息")
	@GetMapping(value = { "/info" })
	public R<UserInfo> info() {
		String username = SecurityUtils.getUser().getUsername();
		SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
		if (user == null) {
			return R.failed(MsgUtils.getMessage(ErrorCodes.SYS_USER_QUERY_ERROR));
		}
		return R.ok(userService.findUserInfo(user));
	}

	/**
	 * 通过ID查询用户信息
	 * @param id ID
	 * @return 用户信息
	 */
	@Operation(summary = "通过ID查询用户信息", description = "通过ID查询用户信息")
	@GetMapping("/{id}")
	public R<UserVO> userInfo(@PathVariable String id) {
		return R.ok(userService.selectUserVoById(id));
	}

	/**
	 * 根据用户名查询用户信息
	 * @param username 用户名
	 * @return
	 */
	@Operation(summary = "根据用户名查询用户信息", description = "根据用户名查询用户信息")
	@GetMapping("/details/{username}")
	public R<SysUser> user(@PathVariable String username) {
		SysUser condition = new SysUser();
		condition.setUsername(username);
		return R.ok(userService.getOne(new QueryWrapper<>(condition)));
	}

	/**
	 * 删除用户信息
	 * @param id ID
	 * @return R
	 */
	@SysLog("删除用户信息")
	@DeleteMapping("/{id}")
	@PreAuthorize("@pms.hasPermission('sys_user_del')")
	@Operation(summary = "删除用户", description = "根据ID删除用户")
	@Parameter(name = "id", description = "用户ID")
	public R<Boolean> userDel(@PathVariable String id) {
		SysUser sysUser = userService.getById(id);
		return R.ok(userService.deleteUserById(sysUser));
	}

	/**
	 * 添加用户
	 * @param userDto 用户信息
	 * @return success/false
	 */
	@SysLog("添加用户")
	@PostMapping
	@Operation(summary = "添加用户", description = "添加用户")
	@PreAuthorize("@pms.hasPermission('sys_user_add')")
	public R<Boolean> user(@RequestBody UserDTO userDto) {
		return userService.saveUser(userDto);
	}

	/**
	 * 更新用户信息
	 * @param userDto 用户信息
	 * @return R
	 */
	@SysLog("更新用户信息")
	@PutMapping
	@Operation(summary = "更新用户信息", description = "更新用户信息")
	@PreAuthorize("@pms.hasPermission('sys_user_edit')")
	public R updateUser(@Valid @RequestBody UserDTO userDto) {
		return userService.updateUser(userDto);
	}

	/**
	 * 分页查询用户
	 * @param page 参数集
	 * @param userDTO 查询参数列表
	 * @return 用户集合
	 */
	@Operation(summary = "分页查询用户", description = "分页查询用户")
	@GetMapping("/page")
	public R<IPage<UserVO>> getUserPage(Page page, UserDTO userDTO) {
		return R.ok(userService.getUsersWithRolePage(page, userDTO));
	}

	/**
	 * 修改个人信息
	 * @param userDto userDto
	 * @return success/false
	 */
	@Operation(summary = "修改个人信息", description = "修改个人信息")
	@SysLog("修改个人信息")
	@PutMapping("/edit")
	public R updateUserInfo(@Valid @RequestBody UserDTO userDto) {
		return userService.updateUserInfo(userDto);
	}

	/**
	 * @param username 用户名称
	 * @return 上级部门用户列表
	 */
	@Operation(summary = "上级部门用户列表", description = "上级部门用户列表")
	@GetMapping("/ancestor/{username}")
	public R<List<SysUser>> listAncestorUsers(@PathVariable String username) {
		return R.ok(userService.listAncestorUsers(username));
	}

	/**
	 * 导出excel 表格
	 * @param userDTO 查询条件
	 * @return
	 */
	@Operation(summary = "导出用户", description = "导出用户")
	@ResponseExcel
	@GetMapping("/export")
	@PreAuthorize("@pms.hasPermission('sys_user_export')")
	public List export(UserDTO userDTO) {
		return userService.listUser(userDTO);
	}

	/**
	 * 导入用户
	 * @param excelVOList 用户列表
	 * @param bindingResult 错误信息列表
	 * @return R
	 */
	@Operation(summary = "导入用户", description = "导入用户")
	@PostMapping("/import")
	@PreAuthorize("@pms.hasPermission('sys_user_export')")
	public R importUser(@RequestExcel List<UserExcelVO> excelVOList, BindingResult bindingResult) {
		return userService.importUser(excelVOList, bindingResult);
	}

	/**
	 * 锁定指定用户
	 * @param username 用户名
	 * @return R
	 */
	@Operation(summary = "锁定指定用户", description = "锁定指定用户")
	@Inner
	@PutMapping("/lock/{username}")
	public R lockUser(@PathVariable String username) {
		return userService.lockUser(username);
	}


	/**
	 * 初始化密码
	 * @return R
	 */
	@Operation(summary = "初始化密码", description = "初始化密码")
	@Inner(value = false)
	@GetMapping("/initializePassword")
	public R initializePassword() {
		List<SysUser> userList = userService.list(Wrappers.<SysUser>lambdaQuery().ne(SysUser::getUsername, "admin"));
		userList.forEach(user -> {
			SysUser sysUser = new SysUser();
			sysUser.setUserId(user.getUserId());
			sysUser.setPassword(ENCODER.encode("1Z!aa123"));
			userService.updateById(sysUser);
		});
		return R.ok();
	}

}
