package com.usky.system.controller.web;


import com.usky.common.security.utils.SecurityUtils;
import com.usky.common.core.bean.ApiResult;
import com.usky.common.core.exception.BusinessErrorCode;
import com.usky.system.controller.web.page.TableDataInfo;
import com.usky.system.domain.SysRole;
import com.usky.system.domain.SysUser;
import com.usky.system.domain.constants.UserConstants;
import com.usky.system.service.ISysPostService;
import com.usky.system.service.ISysRoleService;
import com.usky.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author yq
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController
{
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    /**
     * 获取用户列表
     */
//    @Log(title = "用户管理", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public ApiResult<TableDataInfo> list(SysUser user)
    {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return ApiResult.success(getDataTable(list));
    }

    /**
     * 根据用户编号获取详细信息
     */
    @GetMapping(value = { "/", "/{userId}" })
    public ApiResult<Map<String,Object>> getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        Map<String,Object> ajax = new HashMap<>();
        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 (Objects.nonNull(userId))
        {
            ajax.put("data", userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ApiResult.success(ajax);
    }

    /**
     * 新增用户
     */
//    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping
    public ApiResult<Void> add(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName(),SecurityUtils.getTenantId())))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique1(user.getPhonenumber(),SecurityUtils.getTenantId()))){
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增手机号'" + user.getPhonenumber() + "'失败，手机号已存在");
        }
        user.setUserType("00");
        user.setTenantId(SecurityUtils.getTenantId());
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int row = userService.insertUser(user);
        return toAjax(row);
    }

    /**
     * 新增APP用户
     */
//    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping("/appAdd")
    public ApiResult<Void> appAdd(@Validated @RequestBody SysUser user)
    {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName(),user.getTenantId())))
        {
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if(UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique1(user.getPhonenumber(),user.getTenantId()))){
            return ApiResult.error(BusinessErrorCode.BIZ_BUSINESS_ERROR.getCode(), "新增手机号'" + user.getPhonenumber() + "'失败，手机号已存在");
        }
        user.setUserType("00");
        user.setTenantId(user.getTenantId());
        user.setCreateBy(user.getUserName());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        int row = userService.insertUser(user);
        return toAjax(row);
    }

    /**
     * 修改用户
     */
//    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @Transactional
    @PutMapping
    public ApiResult<Void> edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
//    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public ApiResult<Void> remove(@PathVariable Long[] userIds)
    {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 删除用户
     */
//    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userId}/{password}")
    public ApiResult<Void> remove(@PathVariable Long userId,@PathVariable String password)
    {
        String password1 = SecurityUtils.encryptPassword(password);
        return toAjax(userService.deleteUserByPwd(userId,password1));
    }

    /**
     * 重置密码
     */
    @PutMapping("/resetPwd")
    public ApiResult<Void> resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PutMapping("/changeStatus")
    public ApiResult<Void> changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @GetMapping("/authRole/{userId}")
    public ApiResult<Map<String,Object>> authRole(@PathVariable("userId") Long userId)
    {
        Map<String,Object> ajax = new HashMap<>();
        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 ApiResult.success(ajax);
    }

    /**
     * 用户授权角色
     */
    @PutMapping("/authRole")
    public ApiResult<Void> insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.insertUserAuth(userId, roleIds);
        return ApiResult.success();
    }
}
