package com.ruoyi.web.controller.platform;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.PlatformLog;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.platform.PlatformDept;
import com.ruoyi.common.core.domain.platform.PlatformRole;
import com.ruoyi.common.core.domain.platform.PlatformUser;
import com.ruoyi.common.core.domain.platform.dto.PlatformUserDTO;
import com.ruoyi.common.core.domain.platform.vo.PlatformRoleVO;
import com.ruoyi.common.core.domain.platform.vo.PlatformUserVO;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.DozerUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.platform.service.IPlatformDeptService;
import com.ruoyi.platform.service.IPlatformPostService;
import com.ruoyi.platform.service.IPlatformRoleService;
import com.ruoyi.platform.service.IPlatformUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

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

/**
 *@Description 用户信息
 *@Author zhushuyong
 *@Date 2021/5/26 14:44
 *@since:
 *@copyright: 版权所有2021 开源组织 gitee(https://gitee.com/jinzheyi)作者：朱述勇<br/>
 *            GitHub(https://github.com/jinzheyi)作者：朱述勇 。
 */
@Controller
@RequestMapping("/platform/user")
public class PlatformUserController extends BaseController
{
    private String prefix = "platform/user";

    @Autowired
    private IPlatformUserService userService;

    @Autowired
    private IPlatformRoleService roleService;

    @Autowired
    private IPlatformPostService postService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private IPlatformDeptService deptService;

    @RequiresPermissions("platform:user:view")
    @GetMapping()
    public String user() {
        return prefix + "/user";
    }

    @RequiresPermissions("platform:user:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(PlatformUserDTO userDTO) {
        startPage();
        List<PlatformUserVO> list = userService.selectUserList(userDTO);
        return getDataTable(list);
    }

    @PlatformLog(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("platform:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(PlatformUserDTO userDTO) {
        List<PlatformUserVO> list = userService.selectUserList(userDTO);
        ExcelUtil<PlatformUserVO> util = new ExcelUtil<PlatformUserVO>(PlatformUserVO.class);
        return util.exportExcel(list, "用户数据");
    }

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

    @RequiresPermissions("platform:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate() {
        ExcelUtil<PlatformUserDTO> util = new ExcelUtil<>(PlatformUserDTO.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 新增用户
     */
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        PlatformDept platformDept = deptService.getOne(new LambdaQueryWrapper<PlatformDept>()
                .eq(PlatformDept::getDeptType, Constants.YB));
        mmap.put("dept", platformDept);
        mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !DozerUtils.copyProperties(r, PlatformRole.class).isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());
        return prefix + "/add";
    }

    /**
     * 新增保存用户
     */
    @RequiresPermissions("platform:user:add")
    @PlatformLog(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated PlatformUserDTO user)
    {
        if (UserConstants.USER_NAME_NOT_UNIQUE.equals(userService.checkLoginNameUnique(user.getLoginName())))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，登录账号已存在");
        }
        else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("新增用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        user.setCreateBy(ShiroUtils.getPlatformUser().getLoginName());
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        List<PlatformRoleVO> roles = roleService.selectRolesByUserId(id);
        PlatformUserVO platformUserVO = userService.selectUserById(id);
        PlatformDept platformDept = deptService.getOne(new LambdaQueryWrapper<PlatformDept>()
                .eq(PlatformDept::getDeptType, Constants.YB));
        mmap.put("dept", platformDept);
        mmap.put("user", userService.selectUserById(id));
        mmap.put("roles", PlatformUser.isAdmin(platformUserVO.getUserType()) ? roles : roles.stream().filter(r -> !DozerUtils.copyProperties(r, PlatformRole.class).isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostsByUserId(id));
        return prefix + "/edit";
    }

    /**
     * 修改保存用户
     */
    @RequiresPermissions("platform:user:edit")
    @PlatformLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated PlatformUserDTO user)
    {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.USER_PHONE_NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.USER_EMAIL_NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return error("修改用户'" + user.getLoginName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(ShiroUtils.getPlatformUser().getLoginName());
        return toAjax(userService.updateUser(user));
    }

    @RequiresPermissions("platform:user:resetPwd")
    @GetMapping("/resetPwd/{id}")
    public String resetPwd(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("user", userService.selectUserById(id));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("platform:user:resetPwd")
    @PlatformLog(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(PlatformUserDTO user)
    {
        userService.checkUserAllowed(user);
        user.setSalt(ShiroUtils.randomSalt());
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), user.getSalt()));
        if (userService.resetUserPwd(user) > 0)
        {
            if (ShiroUtils.getPlatformUser().getId().equals(user.getId()))
            {
                ShiroUtils.setPlatformUser(userService.selectUserById(user.getId()));
            }
            return success();
        }
        return error();
    }

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{id}")
    public String authRole(@PathVariable("id") String id, ModelMap mmap)
    {
        PlatformUserVO user = userService.selectUserById(id);
        // 获取用户所属的角色列表
        List<PlatformRoleVO> roles = roleService.selectRolesByUserId(id);
        mmap.put("user", user);
        mmap.put("roles", PlatformUser.isAdmin(user.getUserType()) ? roles : roles.stream().filter(r -> !DozerUtils.copyProperties(r, PlatformRole.class).isAdmin()).collect(Collectors.toList()));
        return prefix + "/authRole";
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("platform:user:add")
    @PlatformLog(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public AjaxResult insertAuthRole(String userId, String[] roleIds)
    {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @RequiresPermissions("platform:user:remove")
    @PlatformLog(title = "用户管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(PlatformUserDTO user)
    {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(PlatformUserDTO user)
    {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(PlatformUserDTO user)
    {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @PlatformLog(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("platform:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(PlatformUserDTO user) {
        userService.checkUserAllowed(user);
        return toAjax(userService.changeStatus(user));
    }
}