package com.yunfeiyun.agmp.common.web.system.controller;

import com.yunfeiyun.agmp.common.constant.AmqpConstant;
import com.yunfeiyun.agmp.common.constant.ErrorCode;
import com.yunfeiyun.agmp.common.core.domain.AjaxResult;
import com.yunfeiyun.agmp.common.core.page.TableDataInfo;
import com.yunfeiyun.agmp.common.exception.BizException;
import com.yunfeiyun.agmp.common.framework.web.service.ISysRoleService;
import com.yunfeiyun.agmp.common.framework.web.service.ISysSyncService;
import com.yunfeiyun.agmp.common.framework.web.service.ISysUserService;
import com.yunfeiyun.agmp.common.web.system.service.ISysDeptService;
import com.yunfeiyun.agmp.common.annotation.Log;
import com.yunfeiyun.agmp.common.core.controller.BaseController;
import com.yunfeiyun.agmp.common.core.domain.entity.SysDept;
import com.yunfeiyun.agmp.common.core.domain.entity.SysRole;
import com.yunfeiyun.agmp.common.core.domain.entity.SysUser;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseRole;
import com.yunfeiyun.agmp.common.core.domain.model.IBaseUser;
import com.yunfeiyun.agmp.common.enums.BusinessType;
import com.yunfeiyun.agmp.common.utils.DateUtils;
import com.yunfeiyun.agmp.common.utils.SecurityUtils;
import com.yunfeiyun.agmp.common.utils.StringUtils;
import com.yunfeiyun.agmp.common.utils.poi.ExcelUtil;
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 org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.stream.Collectors;

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

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysSyncService sysSyncService;
    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user)
    {
        startPage();
        List<IBaseUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @GetMapping("/select/list")
    public TableDataInfo selectList(SysUser user)
    {
        List<IBaseUser> list = userService.selectUserListOfAuth(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user)
    {
        List<IBaseUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, (List)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 = getLoginname();
        String message = userService.importUser((List)userList, updateSupport, operName);
        return success(message);
    }

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

    /**
     * 根据用户编号获取角色详细信息，无id全部
     */
    @PreAuthorize("@ss.hasPermi('system:user:roleassign')")
    @GetMapping(value = { "/", "/{userId}" })
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) String userId)
    {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<IBaseRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        if (StringUtils.isNotNull(userId))
        {
            IBaseUser sysUser = userService.selectUserById(userId);
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("roleIds", sysUser.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))
        {
            throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
        }
        else if (StringUtils.isNotEmpty(user.getUserMobile()) && !userService.checkPhoneUnique(user))
        {
            throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
        }
        else if (StringUtils.isNotEmpty(user.getUserEmail()) && !userService.checkEmailUnique(user))
        {
            throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
        }
        user.setUserCreator(getUserId());
        user.setUserCreateddate(DateUtils.dateTimeNow());
        user.setUserModifier(getUserId());
        user.setUserModifieddate(getUserId());
        String pwdSrc = user.getUserLoginpwd();
        user.setUserLoginpwd(SecurityUtils.encryptPassword(user.getUserLoginpwd()));
        user.setUserId(user.getId());
        int n = userService.insertUser(user);
        //插入完后更新
        user.setUserLoginpwd(pwdSrc);
        sysSyncService.syncUser( user , AmqpConstant.cmdAdd);
        return toAjax(n);
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        if (!userService.checkUserNameUnique(user))
        {
            throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
        }
        else if (StringUtils.isNotEmpty(user.getUserMobile()) && !userService.checkPhoneUnique(user))
        {
            throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
        }
        else if (StringUtils.isNotEmpty(user.getUserEmail()) && !userService.checkEmailUnique(user))
        {
            throw new BizException(ErrorCode.ADD_DUPLICATE_ERROR.getCode(),ErrorCode.ADD_DUPLICATE_ERROR.getMessage());
        }
        user.setUserModifier(getUserId());
        user.setUserModifieddate(DateUtils.dateTimeNow());
        //sysSyncService.syncUser( user , AmqpConstant.cmdUpdate);
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{userIds}")
    public AjaxResult remove(@PathVariable  String[] userIds)
    {
        if (ArrayUtils.contains(userIds, getUserId()))
        {
            throw new BizException(ErrorCode.DEL_CURNODE_ERROR.getCode(),ErrorCode.DEL_CURNODE_ERROR.getMessage());
        }
        //sysSyncService.syncDept( userIds.toString() , AmqpConstant.cmdDelete);
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:resetPwd')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUserLoginpwd(SecurityUtils.encryptPassword(user.getUserLoginpwd()));
        user.setUserModifier(getUserId());
        user.setUserModifieddate(DateUtils.dateTimeNow());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user)
    {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getUserId());
        user.setUserModifier(getLoginname());
        return toAjax(userService.updateUserStatus(user));
    }

    /**
     * 根据用户编号获取授权角色
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping("/authRole/info")
    public AjaxResult authRole(@RequestParam("userId") String userId)
    {
        AjaxResult ajax = AjaxResult.success();
        IBaseUser user = userService.selectUserById(userId);
        List<IBaseRole> 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")
    public AjaxResult insertAuthRole(String userId, String[] roleIds)
    {
        userService.checkUserDataScope(userId);
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    /**
     * 获取部门树列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/dept/tree")
    public AjaxResult deptTree(SysDept dept)
    {
        return success(deptService.selectDeptTreeList(dept));
    }
}
