package com.xunmei.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xunmei.common.core.domain.R;
import com.xunmei.common.core.utils.StringUtils;
import com.xunmei.common.core.web.controller.BaseController;
import com.xunmei.common.core.web.domain.AjaxResult;
import com.xunmei.common.core.web.page.TableDataInfo;
import com.xunmei.common.log.annotation.Log;
import com.xunmei.common.log.enums.BusinessType;
import com.xunmei.common.security.annotation.InnerAuth;
import com.xunmei.common.security.annotation.RequiresPermissions;
import com.xunmei.common.security.utils.SaltHelper;
import com.xunmei.common.security.utils.SecurityUtils;
import com.xunmei.system.api.domain.*;
import com.xunmei.system.api.model.LoginUser;
import com.xunmei.system.domain.SysUserRole;
import com.xunmei.system.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.ArrayUtils;
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 org.springframework.web.multipart.MultipartFile;

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

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

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysConfigService configService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Autowired
    private ISysUserInformationService sysUserInformationService;

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


    /**
     * 获取当前用户信息
     */
    @InnerAuth
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);

        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        //获取当前用户的角色数据。
        List<SysRole> sysRoles = roleService.selectRolesByUserId(sysUser.getId());
        sysUser.setRoles(sysRoles);

        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser);
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setOrgId(sysUserVo.getOrgId());
        sysUserVo.setName(sysUserVo.getName());
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 注册用户信息
     */
    @InnerAuth
    @PostMapping("/register")
    public R<Boolean> register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUsername();
        if (!("true".equals(configService.selectConfigByKey("sys.account.registerUser")))) {
            return R.fail("当前系统没有开启注册功能！");
        }
        if (!userService.checkUserNameUnique(sysUser)) {
            return R.fail("保存用户'" + username + "'失败，注册账号已存在");
        }
        return R.ok(userService.registerUser(sysUser));
    }

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

    /**
     * 根据用户编号获取详细信息
     */
    @RequiresPermissions("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", roles);
        ajax.put("posts", null);
        if (StringUtils.isNotNull(userId)) {
            SysUserInformation informationByUserId = sysUserInformationService.getInformationByUserId(userId);
            if (null == informationByUserId) {
                informationByUserId = new SysUserInformation();
            }
            SysUser sysUser = userService.selectUserById(userId);
            List<SysUserRole> userRoles = sysUserRoleService.list(new QueryWrapper<SysUserRole>().eq("user_id", userId));
            sysUser.setRoles(roles);
            String sex = "男";
            String status = "禁用";
            if (null != sysUser) {
                if (sysUser.getGender().equals("1")) {
                    sex = "女";
                }
                if (sysUser.getIsLock().equals("0")) {
                    status = "启用";
                }
            }
            ajax.put(AjaxResult.DATA_TAG, sysUser);
            ajax.put("information", informationByUserId);
            ajax.put("postIds", null);
            ajax.put("roleIds", userRoles.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));
            ajax.put("roleName", roleService.getRoleName(userId));
            ajax.put("sex", sex);
            ajax.put("status", status);
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhone()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
//        else if (StringUtils.isNotEmpty(user.get()) && !userService.checkEmailUnique(user))
//        {
//            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setCreateTime(new Date());
        //isp的加密方式
        final String salt = SaltHelper.salt();
        user.setSalt(salt);
        user.setPassword(SaltHelper.exec(user.getPassword(), salt));
        userService.insertUser(user);
//        if (user.getId()!=null&&user.getRoleIds()!=null&&user.getRoleIds().length > 0) {
//            for (Long roleId :
//                    user.getRoleIds()) {
//                SysUserRole sysUserRole = new SysUserRole();
//                sysUserRole.setUserId(user.getId());
//                sysUserRole.setRoleId(roleId);
//                sysUserRoleService.insertSysUserRole(sysUserRole);
//            }
//
//        }

//        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return AjaxResult.success();
    }

    /**
     * 修改用户
     */
    @RequiresPermissions("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        if (!userService.checkUserNameUnique(user)) {
            return error("修改用户'" + user.getUsername() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhone()) && !userService.checkPhoneUnique(user)) {
            return error("修改用户'" + user.getUsername() + "'失败，手机号码已存在");
        }
//        else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user))
//        {
//            return error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
//        }
        if (user.getRoleIds() != null && user.getRoleIds().length > 0) {
            sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", user.getId()));
            for (Long roleId :
                    user.getRoleIds()) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(user.getId());
                sysUserRole.setRoleId(roleId);
                sysUserRole.setCreateTime(new Date());
                sysUserRoleService.insertSysUserRole(sysUserRole);
            }

        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @RequiresPermissions("system: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("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        userService.checkUserDataScope(user.getId());
        final String salt = SaltHelper.salt();
        user.setSalt(salt);
//        user.setPassword(SaltHelper.exec(user.getPassword(), userService.selectUserById(user.getId()).getSalt()));
        user.setPassword(SaltHelper.exec(user.getPassword(), salt));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

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

    /**
     * 根据用户编号获取授权角色
     */
    @RequiresPermissions("system:user:query")
    @GetMapping("/authRole/{userId}")
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = userService.selectUserById(userId);
        List<SysRole> roles = roleService.selectRolesByUserId(userId);
        List<SysUserRole> userRoles = sysUserRoleService.selectSysUserRoleListByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("userRoles", userRoles);
        return ajax;
    }

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

    /**
     * 获取用户列表
     */
    @InnerAuth
    @PostMapping("/sync/list")
    public R<List<SysUser>> syncUserList(@RequestBody SysUser user) {
        try {
            return R.ok(userService.selectSyncUserList(user));
        } catch (Exception e) {
            return R.fail(e.getMessage());
        }
    }

    @InnerAuth
    @GetMapping("/getUserById")
    public SysUser getUserById(Long id) {
        return userService.selectUserById(id);
    }

    /**
     * 查询机构列表
     */
    @ApiOperation(value = "批量保存同步用户数据")
    @InnerAuth
    @PostMapping("/sync/batch")
    public R<Boolean> batchSaveSyncSysOrgs(@RequestBody List<SysUser> sysUserList) {
        userService.batchSaveOrUpdate(sysUserList);
        return R.ok(true);
    }
    /**
     * 查询机构列表
     */
    @ApiOperation(value = "记录用户最后一次登录")
    @InnerAuth
    @PostMapping("/userLoginInfo")
    public R<Boolean> userLoginInfo(Long id,Date loginTime, String loginIp) {
        SysUser sysUser = userService.selectUserById(id);
        sysUser.setLastIp(loginIp);
        sysUser.setLastTime(loginTime);
        userService.saveOrUpdate(sysUser);
        return R.ok(true);
    }


}
