package com.ruoyi.web.controller.system;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.TreeSelect;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysPostService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author ruoyi
 */
@Api(tags = "6.1.1-用户管理")
@RestController
@RequestMapping("/system/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;


    @ApiOperation("获取用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
//        startPage();
        startPage("desc", "u.create_time");
        List<SysUser> list = userService.selectUserList(user);

        for (SysUser data : list) {
            data.setSearchValue(null);
            data.setParams(null);
            data.setCreateBy(null);
            data.setCreateTime(null);
            data.setUpdateBy(null);
            data.setUpdateTime(null);
            data.setDelFlag(null);
            data.setPhonenumber(null);
            data.setSex(null);
            data.setAvatar(null);
            data.setPassword(null);
            data.setLoginIp(null);
            data.setLoginDate(null);
            data.setSourceId(null);
            data.setCasUserPback(null);
        }
        return getDataTable(list);
    }

/*
    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }
    */
/*

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }
*/

    /**
     * 根据用户编号获取详细信息
     */
    @ApiOperation("查询用户详情")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(
            @ApiParam(name = "userId", value = "用户ID", required = false)
            @PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser data = userService.selectUserById(userId);
            data.setSearchValue(null);
            data.setParams(null);
            data.setCreateBy(null);
            data.setCreateTime(null);
            data.setUpdateBy(null);
            data.setUpdateTime(null);
            data.setDelFlag(null);
            data.setPhonenumber(null);
            data.setSex(null);
            data.setAvatar(null);
            data.setPassword(null);
            data.setLoginIp(null);
            data.setLoginDate(null);
            data.setSourceId(null);
            data.setCasUserPback(null);
            ajax.put(AjaxResult.DATA_TAG, data);
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", data.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation("用户修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "主键", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "nickName", value = "用户姓名", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "email", value = "用户邮箱", dataType = "String", dataTypeClass = String.class),
            @ApiImplicitParam(name = "status", value = "账号状态", dataType = "String", dataTypeClass = String.class),
    })
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        if (ArrayUtils.contains(userIds, getUserId())) {
            return error("当前用户不能删除");
        }
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    @ApiOperation("用户状态修改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "主键", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "status", value = "账号状态", dataType = "String", dataTypeClass = String.class),

    })
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return ajax;
    }

    /**
     * 用户授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    @ApiOperation("用户授权角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "roleIds", value = "角色数组ID", dataType = "Long[]", dataTypeClass = Long[].class),
    })
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }


    /**
     * 获取部门树列表
     */
    @ApiOperation("获取部门树列表")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(SysDept dept) {
        dept.setStatus("0");
        List<TreeSelect> treeSelects = deptService.selectDeptTreeListPostCheck(dept);

        return success(treeSelects);
    }


    /**
     * 获取用户列表
     */
    @ApiOperation("查询用户列表（分页）支持部门ID、岗位名称筛选")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "deptId", value = "部门ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "deptName", value = "部门名称", dataType = "String", dataTypeClass = String.class),

            @ApiImplicitParam(name = "postId", value = "岗位ID", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "postName", value = "岗位名称", dataType = "String", dataTypeClass = String.class),

            @ApiImplicitParam(name = "nickName", value = "人员姓名", dataType = "String", dataTypeClass = String.class),

            @ApiImplicitParam(name = "pageNum", value = "页码从1开始", dataType = "Integer", dataTypeClass = Integer.class),
            @ApiImplicitParam(name = "pageSize", value = "分页大小", dataType = "Integer", dataTypeClass = Integer.class),
//            @ApiImplicitParam(name = "orderBy", value = "排序字段", dataType = "String", dataTypeClass = String.class)
    })
    @GetMapping("/postUserList")
    public TableDataInfo postUserList(Long deptId, String deptName, Long postId, String postName, String nickName) {
//        pageNum: 1
//        pageSize: 10
//        deptName: 部门名称
//        postName: 岗位名称
//        nickName: 人员名称
//        startPage();
        startPage("desc", "u.create_time");
        List<SysUser> list = userService.postUserList(deptId, deptName, postId, postName, nickName, null, null);
//        return getDataTable(list);
        List<SysUser> resultList = new ArrayList<>();
        for (SysUser data : list) {
            SysUser result = new SysUser();
            result.setUserId(data.getUserId());
            result.setNickName(data.getNickName());
            result.setDeptName(data.getDeptName());
            result.setPostName(data.getPostName());
            result.setDeptId(data.getDeptId());
            resultList.add(result);
        }
        return getDataTable(resultList);
    }
}
