package com.inspect.system.controller;

import com.inspect.base.core.domain.Response;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.core.utils.poi.ExcelUtil;
import com.inspect.base.core.web.controller.BaseController;
import com.inspect.base.core.web.domain.AjaxResult;
import com.inspect.base.core.web.page.TableDataInfo;
import com.inspect.common.log.annotation.Log;
import com.inspect.common.log.enums.BizType;
import com.inspect.common.security.annotation.InnerAuth;
import com.inspect.common.security.annotation.RequiresPermissions;
import com.inspect.common.security.utils.SecurityUtils;
import com.inspect.system.base.domain.SysRole;
import com.inspect.system.base.domain.SysUser;
import com.inspect.system.base.model.LoginUser;
import com.inspect.system.service.ISysConfigService;
import com.inspect.system.service.ISysPermissionService;
import com.inspect.system.service.ISysPostService;
import com.inspect.system.service.ISysRoleService;
import com.inspect.system.service.ISysUserService;

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

import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping({"/user"})
public class SysUserController extends BaseController {
    private final ISysUserService userService;
    private final ISysRoleService roleService;
    private final ISysPostService postService;
    private final ISysPermissionService permissionService;
    private final ISysConfigService configService;

    public SysUserController(ISysUserService userService, ISysRoleService roleService, ISysPostService postService, ISysPermissionService permissionService, ISysConfigService configService) {
        this.userService = userService;
        this.roleService = roleService;
        this.postService = postService;
        this.permissionService = permissionService;
        this.configService = configService;
    }

    @RequiresPermissions({"system:user:list"})
    @GetMapping({"/list"})
    public TableDataInfo list(SysUser user) {
        this.startPage();
        List<SysUser> list = this.userService.selectUserList(user);
        return this.getDataTable(list);
    }

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

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

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

    @InnerAuth
    @GetMapping({"/info/{username}"})
    public Response<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = this.userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return Response.fail("用户名或密码错误");
        } else {
            Set<String> roles = this.permissionService.getRolePermission(sysUser.getUserId());
            Set<String> permissions = this.permissionService.getMenuPermission(sysUser.getUserId());
            LoginUser sysUserVo = new LoginUser();
            sysUserVo.setSysUser(sysUser);
            sysUserVo.setRoles(roles);
            sysUserVo.setPermissions(permissions);
            return Response.ok(sysUserVo);
        }
    }

    @InnerAuth
    public Response<Boolean> register(@RequestBody SysUser sysUser) {
        String username = sysUser.getUserName();
        return !"true".equals(this.configService.selectConfigByKey("sys.account.registerUser")) ? Response.fail("当前系统没有开启注册功能！") : ("1".equals(this.userService.checkUserNameUnique(username)) ? Response.fail("保存用户'" + username + "'失败，注册账号已存在") : Response.ok(Boolean.valueOf(this.userService.registerUser(sysUser))));
    }

    @GetMapping({"getInfo"})
    public AjaxResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        logger.info("[QINYL] getInfo userid {}", userId);
        Set<String> roles = this.permissionService.getRolePermission(userId);
        Set<String> permissions = this.permissionService.getMenuPermission(userId);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", this.userService.selectUserById(userId));
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        HashMap<String, Object> errorMap = this.userService.verifyUserUpdatePassTime(userId);
        ajax.put("updatePassMap", errorMap);
        return ajax;
    }

    @RequiresPermissions({"system:user:query"})
    @GetMapping({"/", "/{userId}"})
    public AjaxResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        this.userService.checkUserDataScope(userId);
        AjaxResult ajax = AjaxResult.success();
        List<SysRole> roles = this.roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter((r) -> {
            return !r.isAdmin();
        }).collect(Collectors.toList()));
        ajax.put("posts", this.postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            SysUser sysUser = this.userService.selectUserById(userId);
            ajax.put("data", sysUser);
            ajax.put("postIds", this.postService.selectPostListByUserId(userId));
            ajax.put("roleIds", sysUser.getRoles().stream().map(SysRole::getRoleId).collect(Collectors.toList()));
        }

        return ajax;
    }

    @RequiresPermissions({"system:user:add"})
    @Log(
            title = "用户管理",
            businessType = BizType.INSERT
    )
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        String allowIp = user.getAollowIp();
        if (StringUtils.isBlank(allowIp)) {
            return AjaxResult.error("请填写允许登录的ip");
        } else if ("1".equals(this.userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && "1".equals(this.userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && "1".equals(this.userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        } else {
            user.setCreateBy(SecurityUtils.getUsername());
            user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
            return this.toAjax(this.userService.insertUser(user));
        }
    }

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

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

    @RequiresPermissions({"system:user:edit"})
    @Log(
            title = "用户管理",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/resetPwd"})
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        this.userService.checkUserAllowed(user);
        this.userService.checkUserDataScope(user.getUserId());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return this.toAjax(this.userService.resetPwd(user));
    }

    @RequiresPermissions({"system:user:edit"})
    @Log(
            title = "用户管理",
            businessType = BizType.UPDATE
    )
    @PostMapping({"/changeStatus"})
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        this.userService.checkUserAllowed(user);
        this.userService.checkUserDataScope(user.getUserId());
        user.setUpdateBy(SecurityUtils.getUsername());
        return this.toAjax(this.userService.updateUserStatus(user));
    }

    @RequiresPermissions({"system:user:query"})
    @GetMapping({"/authRole/{userId}"})
    public AjaxResult authRole(@PathVariable("userId") Long userId) {
        AjaxResult ajax = AjaxResult.success();
        SysUser user = this.userService.selectUserById(userId);
        List<SysRole> roles = this.roleService.selectRolesByUserId(userId);
        ajax.put("user", user);
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter((r) -> {
            return !r.isAdmin();
        }).collect(Collectors.toList()));
        return ajax;
    }

    @RequiresPermissions({"system:user:edit"})
    @Log(
            title = "用户管理",
            businessType = BizType.GRANT
    )
    @PostMapping({"/authRole"})
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds) {
        this.userService.checkUserDataScope(userId);
        this.userService.insertUserAuth(userId, roleIds);
        return this.success();
    }
}
