package com.boman.system.controller;

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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.boman.common.core.utils.obj.ObjectUtils;
import com.boman.system.service.*;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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 com.boman.domain.constant.UserConstants;
import com.boman.domain.dto.R;
import com.boman.common.core.utils.SecurityUtils;
import com.boman.common.core.utils.StringUtils;
import com.boman.common.core.utils.poi.ExcelUtil;
import com.boman.common.core.web.controller.BaseController;
import com.boman.domain.dto.AjaxResult;
import com.boman.domain.TableDataInfo;
import com.boman.common.log.annotation.Log;
import com.boman.common.log.enums.BusinessType;
import com.boman.common.security.annotation.PreAuthorize;
import com.boman.domain.SysRole;
import com.boman.domain.SysUser;
import com.boman.system.api.model.LoginUser;

/**
 * 用户信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController
{

    private static final Logger LOGGER = LoggerFactory.getLogger(SysUserController.class);
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysDeptService deptService;

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

    @Log(title = "修改用户的小程序唯一标识", businessType = BusinessType.UPDATE)
    @PostMapping("/updateUnionId")
    public AjaxResult updateUnionId(@RequestBody SysUser sysUser) {
        return userService.updateUnionId(sysUser);
    }

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

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize(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 = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

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

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }

        LoginUser sysUserVo = packPermDeptRoles(sysUser);
        return R.ok(sysUserVo);
    }

    /**
     * 获取当前用户信息
     */
    @PostMapping("/packInfo")
    public LoginUser packInfo(@RequestBody SysUser sysUser) {
        return packPermDeptRoles(sysUser);
    }

    private LoginUser packPermDeptRoles(SysUser sysUser) {
        LoginUser sysUserVo = new LoginUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser.getId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser.getId());

        // todo
/*        if (ObjectUtils.isNotEmpty(sysUser.getDeptId())) {
            // 当前人所在部门和下级部门的deptIdList
            List<SysDept> sysDepts = deptService.listChildrenDepts(sysUser.getDeptId());
            if (ObjectUtils.isNotEmpty(sysDepts)) {
                // 所有部门
                List<Long> childrenDeptIds = ObjectUtils.map(sysDepts, SysDept::getId);
                if (ObjectUtils.isNotEmpty(childrenDeptIds)) {
                    List<SysUser> users = userService.listByDeptId(childrenDeptIds);
                    sysUserVo.setDeptUserIds(getUserIds(users));

                    // 去除本部门后的所有子部门
                    List<Long> child = ObjectUtils.filter(childrenDeptIds, deptId -> !deptId.equals(sysUser.getDeptId()));
                    List<SysUser> childUsers = userService.listByDeptId(child);
                    sysUserVo.setSubDeptUserIds(getUserIds(childUsers));
                }
            }
        }*/

        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return sysUserVo;
    }

    private List<Long> getUserIds(List<SysUser> users) {
        List<Long> userIdList = Lists.newArrayListWithCapacity(0);
        if (ObjectUtils.isNotEmpty(users)) {
            userIdList = ObjectUtils.map(users, SysUser::getId);
        }
        return userIdList;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        Long id = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(id);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(id);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", userService.selectUserById(id));
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize(hasPermi = "system:user:query")
    @GetMapping(value = { "/", "/{id}" })
    public AjaxResult getInfo(@PathVariable(value = "id", required = false) Long id)
    {
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(id) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(id))
        {
            ajax.put(AjaxResult.DATA_TAG, userService.selectUserById(id));
            ajax.put("postIds", postService.selectPostListById(id));
            ajax.put("roleIds", roleService.selectRoleListById(id));
        }
        return ajax;
    }

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

    /**
     * 修改用户
     */
    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user)
    {
        //userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user)))
        {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize(hasPermi = "system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }

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

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

    /**
     * 部门下所有人
     */
//    @PreAuthorize(hasPermi = "system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PostMapping("/listByDeptId")
    public List<SysUser> listByDeptId(@RequestBody List<Long> deptIdList) {
       return userService.listByDeptId(deptIdList);
    }

    /**
     * 为用户档案定制新增接口
     * @param result 结果
     * @return
     */
    @PostMapping("/addUser")
    public void addUser(@Validated @RequestBody List<JSONObject> result) {
         userService.addUser(result);
    }


    /**
     * 获取全部用户列表
     */
    @GetMapping("/userListAll")
    public List<SysUser> selectUserListAll()
    {
        return userService.selectUserListAll();
    }

    /**
     * 功能描述: queryByOpenId
     *
     * @param openId openId
     * @return com.boman.domain.SysUser
     */
    @GetMapping("/queryByOpenId/{openId}")
    public SysUser queryByOpenId(@PathVariable("openId") String openId){
        return userService.queryByOpenId(openId);
    }

    /**
     * 功能描述: getByPhone
     *
     * @param phone phone
     * @return com.boman.domain.SysUser
     */
    @GetMapping("/getByPhone/{phone}")
    public SysUser getByPhone(@PathVariable("phone") String phone) {
        SysUser sysUser = userService.getByPhone(phone);
        LOGGER.info("getByPhone: 请求结果:{}",JSON.toJSONString(sysUser));
        return ObjectUtils.requireNonNull(sysUser, String.format("手机号 [%s] 对应的用户不存在", phone));
    }


}
