package org.wfc.user.controller;

import cn.hutool.core.util.StrUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.wfc.common.core.domain.LoginUser;
import org.wfc.common.core.domain.R;
import org.wfc.common.core.utils.MessageUtils;
import org.wfc.common.core.utils.StringUtils;
import org.wfc.common.core.utils.poi.ExcelUtil;
import org.wfc.common.core.web.controller.BaseController;
import org.wfc.common.core.web.domain.AjaxResult;
import org.wfc.common.core.web.page.TableDataInfo;
import org.wfc.common.security.annotation.InnerAuth;
import org.wfc.common.security.annotation.RequiresPermissions;
import org.wfc.common.security.service.TokenService;
import org.wfc.common.security.utils.SecurityUtils;
import org.wfc.user.api.domain.UDept;
import org.wfc.user.api.domain.URole;
import org.wfc.user.api.domain.UUser;
import org.wfc.user.domain.query.UserRepeatQuery;
import org.wfc.user.service.IUConfigService;
import org.wfc.user.service.IUDeptService;
import org.wfc.user.service.IUPermissionService;
import org.wfc.user.service.IUPostService;
import org.wfc.user.service.IURoleService;
import org.wfc.user.service.IUUserService;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户信息
 * 
 * @author wfc
 */
@RestController
@RequestMapping("/user")
public class UUserController extends BaseController
{
    @Autowired
    private IUUserService userService;

    @Autowired
    private IURoleService roleService;

    @Autowired
    private IUDeptService deptService;

    @Autowired
    private IUPostService postService;

    @Autowired
    private IUPermissionService permissionService;

    @Autowired
    private IUConfigService configService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private MessageSource messageSource;

    /**
     * 获取用户列表
     */
    @GetMapping("/test")
    public String test()
    {
        return MessageUtils.message("user.jcaptcha.error");
    }

    /**
     * 检查重复
     */
    @PostMapping("/checkRepeat")
    public R<Boolean> checkRepeat(@RequestBody UserRepeatQuery query)
    {
        UUser user = new UUser();
        BeanUtils.copyProperties(query, user);
        return R.ok(!userService.checkUserNameUnique(user) || !userService.checkPhoneUnique(user)
                || !userService.checkEmailUnique(user));
    }

    /**
     * 获取用户列表
     */
    @RequiresPermissions("Utem:user:list")
    @GetMapping("/list")
    public TableDataInfo list(UUser user)
    {
        startPage();
        List<UUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @PostMapping("/page")
    public TableDataInfo page(@RequestBody UUser user)
    {
        startPage();
        List<UUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

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

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

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

    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser<UUser>> info(@PathVariable("username") String username)
    {
        UUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user))
        {
            return R.fail("user.name.or.password.error");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        LoginUser<UUser> UUserVo = new LoginUser<UUser>();
        UUserVo.setUser(user);
        UUserVo.setRoles(roles);
        UUserVo.setPermissions(permissions);
        return R.ok(UUserVo);
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody UUser uUser)
    {
        String username = uUser.getUserName();
        if (!("true".equals(configService.selectConfigByKey("user.register"))))
        {
            return R.fail("user.not.register");
        }
        if (!userService.checkUserNameUnique(uUser))
        {
            return R.fail("user.register.save.error");
        }

        if (StrUtil.isNotBlank(uUser.getPhonenumber()) && !userService.checkPhoneUnique(uUser))
        {
            return R.fail("user.register.phone.save.error");
        }

        if (!userService.checkEmailUnique(uUser))
        {
            return R.fail("user.register.email.save.error");
        }

        return R.ok(userService.registerUser(uUser));
    }

    /**
     *记录用户登录IP地址和登录时间
     */
    @InnerAuth
    @PutMapping("/recordlogin")
    public R<Boolean> recordlogin(@RequestBody UUser UUser)
    {
        return R.ok(userService.updateUserProfile(UUser));
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser<UUser> loginUser = SecurityUtils.getLoginUser();
        UUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        if (!loginUser.getPermissions().equals(permissions))
        {
            loginUser.setPermissions(permissions);
            tokenService.refreshToken(loginUser);
        }
        Map<String, Object> data = new HashMap<>();

        data.put("user", user);
        data.put("roles", roles);
        data.put("permissions", permissions);

        return AjaxResult.success(data);
    }

    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("Utem:user:query")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId)
    {
        Map<String, Object> data = new HashMap<>();
        List<URole> roles = roleService.selectRoleAll();
        data.put("roles", UUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        data.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId))
        {
            userService.checkUserDataScope(userId);
            UUser UUser = userService.selectUserById(userId);
            data.put(AjaxResult.DATA_TAG, UUser);
            data.put("postIds", postService.selectPostListByUserId(userId));
            data.put("roleIds", UUser.getRoles().stream().map(URole::getRoleId).collect(Collectors.toList()));
        }
        return AjaxResult.success(data);
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("Utem:user:add")
    // @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody UUser user)
    {
        deptService.checkDeptDataScope(user.getDeptId());
        roleService.checkRoleDataScope(user.getRoleIds());
        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(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    // @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody UUser user)
    {
        userService.checkUserAllowed(user);
//        userService.checkUserDataScope(user.getUserId());
//        deptService.checkDeptDataScope(user.getDeptId());
//        roleService.checkRoleDataScope(user.getRoleIds());
        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(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

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

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

    /**
     * 状态修改
     */
    @RequiresPermissions("Utem:user:edit")
    // @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody UUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

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

    /**
     * 用户授权角色
     */
    @RequiresPermissions("Utem:user:edit")
    // @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PutMapping("/authRole")
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.checkUserDataScope(userId);
        roleService.checkRoleDataScope(roleIds);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @RequiresPermissions("Utem:user:list")
    @GetMapping("/deptTree")
    public AjaxResult deptTree(UDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }
}
