package com.yida.data.system.controller;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yida.data.common.core.common.ModuleName;
import com.yida.data.common.core.common.ResultBean;
import com.yida.data.common.core.entity.FebsResponse;
import com.yida.data.common.core.entity.QueryRequest;
import com.yida.data.common.core.entity.constant.StringConstant;
import com.yida.data.common.core.entity.system.EduUserLogo;
import com.yida.data.common.core.entity.system.LoginLog;
import com.yida.data.common.core.entity.system.SystemUser;
import com.yida.data.common.core.entity.system.SystemUserMenu;
import com.yida.data.common.core.entity.system.UserRole;
import com.yida.data.common.core.entity.system.enums.OperationLogTypeEnum;
import com.yida.data.common.core.exception.FebsException;
import com.yida.data.common.core.utils.ExcelUtil;
import com.yida.data.common.core.utils.FebsUtil;
import com.yida.data.log.annotation.OperationLog;
import com.yida.data.system.dto.MenuForUserDTO;
import com.yida.data.system.service.EduUserLogoService;
import com.yida.data.system.service.ILoginLogService;
import com.yida.data.system.service.IUserDataPermissionService;
import com.yida.data.system.service.IUserRoleService;
import com.yida.data.system.service.IUserService;
import com.yida.data.system.service.SystemUserMenuService;
import com.yida.data.system.vo.ExportUserInfoVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author MrBird
 */
@Slf4j
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("user")
public class UserController {

    private final IUserService userService;
    private final IUserDataPermissionService userDataPermissionService;
    private final ILoginLogService loginLogService;
    private final PasswordEncoder passwordEncoder;
    private final IUserRoleService userRoleService;
    private final SystemUserMenuService systemUserMenuService;
    private final EduUserLogoService eduUserLogoService;

    @GetMapping("success")
    public void loginSuccess(HttpServletRequest request) {
        String currentUsername = FebsUtil.getCurrentUsername();
        // update last login time
        userService.updateLoginTime(currentUsername);
        // save login log
        LoginLog loginLog = new LoginLog();
        loginLog.setUsername(currentUsername);
        loginLog.setSystemBrowserInfo(request.getHeader("user-agent"));
        loginLogService.saveLoginLog(loginLog);
    }

    @GetMapping("index")
    public FebsResponse index() {
        Map<String, Object> data = new HashMap<>(5);
        // 获取系统访问记录
        Long totalVisitCount = loginLogService.findTotalVisitCount();
        data.put("totalVisitCount", totalVisitCount);
        Long todayVisitCount = loginLogService.findTodayVisitCount();
        data.put("todayVisitCount", todayVisitCount);
        Long todayIp = loginLogService.findTodayIp();
        data.put("todayIp", todayIp);
        // 获取近期系统访问记录
        List<Map<String, Object>> lastTenVisitCount = loginLogService.findLastTenDaysVisitCount(null);
        data.put("lastTenVisitCount", lastTenVisitCount);
        SystemUser param = new SystemUser();
        param.setUsername(FebsUtil.getCurrentUsername());
        List<Map<String, Object>> lastTenUserVisitCount = loginLogService.findLastTenDaysVisitCount(param);
        data.put("lastTenUserVisitCount", lastTenUserVisitCount);
        return new FebsResponse().data(data);
    }


    @GetMapping
//    @PreAuthorize("hasAuthority('user:view') and hasAnyRole('role:admin', 'role:agent:admin', 'role:education:principal')")
    public FebsResponse userList(QueryRequest queryRequest, SystemUser user) {
        Map<String, Object> dataTable = FebsUtil.getDataTable(userService.findUserDetailList(user, queryRequest));
        return new FebsResponse().data(dataTable);
    }

    @GetMapping("check/{username}")
    public boolean checkUserName(@NotBlank(message = "{required}") @PathVariable String username) {
        return userService.findByName(username) == null;
    }

    @PostMapping
    @PreAuthorize("hasAuthority('user:add')")
    @OperationLog(module = ModuleName.USER, methods = "新增用户", type = OperationLogTypeEnum.INSERT)
    public void addUser(@Valid SystemUser user) {
        userService.createUser(user);
    }

    @PutMapping
    @PreAuthorize("hasAuthority('user:update')")
    @OperationLog(module = ModuleName.USER, methods = "修改用户", type = OperationLogTypeEnum.UPDATE)
    public void updateUser(@Valid SystemUser user) {
        userService.updateUser(user);
    }

    @GetMapping("/{userId}")
    @PreAuthorize("hasAuthority('user:update')")
    public FebsResponse findUserDataPermissions(@NotBlank(message = "{required}") @PathVariable String userId) {
        String dataPermissions = userDataPermissionService.findByUserId(userId);
        return new FebsResponse().data(dataPermissions);
    }

    @DeleteMapping("/{userIds}")
    @PreAuthorize("hasAuthority('user:delete')")
    @OperationLog(module = ModuleName.USER, methods = "删除用户", type = OperationLogTypeEnum.DELETE)
    public void deleteUsers(@NotBlank(message = "{required}") @PathVariable String userIds) {
        String[] ids = userIds.split(StringConstant.COMMA);
        userService.deleteUsers(ids);
    }

    @GetMapping("/updatePassword")
    @OperationLog(module = ModuleName.USER, methods = "修改密码", type = OperationLogTypeEnum.UPDATE)
    public void updatePassword(String password, String newPassword, String repeatPassword) {
        userService.updatePassword(password, newPassword, repeatPassword, FebsUtil.getCurrentUsername());
    }

    @GetMapping("/validatePassword")
    public ResultBean validatePassword(String password) {
        userService.validatePassword(password, FebsUtil.getCurrentUsername());
        return ResultBean.buildSuccess();
    }

    @PutMapping("profile")
    @OperationLog(module = ModuleName.USER, methods = "修改个人信息", type = OperationLogTypeEnum.UPDATE)
    public void updateProfile(@Valid SystemUser user) throws FebsException {
        userService.updateProfile(user);
    }

    @PutMapping("avatar")
    @OperationLog(module = ModuleName.USER, methods = "修改头像", type = OperationLogTypeEnum.UPDATE)
    public void updateAvatar(@NotBlank(message = "{required}") String avatar) {
        userService.updateAvatar(avatar);
    }

    @GetMapping("password/check")
    public boolean checkPassword(@NotBlank(message = "{required}") String password) {
        String currentUsername = FebsUtil.getCurrentUsername();
        SystemUser user = userService.findByName(currentUsername);
        return user != null && passwordEncoder.matches(password, user.getPassword());
    }

    @PutMapping("password")
    @OperationLog(module = ModuleName.USER, methods = "修改密码", type = OperationLogTypeEnum.UPDATE)
    public void updatePassword(@NotBlank(message = "{required}") String password) {
        userService.updatePassword(password);
    }

    @PutMapping("password/reset")
    @PreAuthorize("hasAuthority('user:reset')")
    @OperationLog(module = ModuleName.USER, methods = "重置用户密码", type = OperationLogTypeEnum.UPDATE)
    public void resetPassword(@NotBlank(message = "{required}") String usernames) {
        String[] usernameArr = usernames.split(StringConstant.COMMA);
        userService.resetPassword(usernameArr);
    }

    @PostMapping("excel")
    @PreAuthorize("hasAuthority('user:export')")
    public void export(QueryRequest queryRequest, SystemUser user, HttpServletResponse response) {
        List<SystemUser> users = userService.findUserDetailList(user, queryRequest).getRecords();
        List<ExportUserInfoVO> userInfoVOS = users.stream().map(x -> {
            ExportUserInfoVO userInfoVO = new ExportUserInfoVO();
            BeanUtils.copyProperties(x, userInfoVO);
            userInfoVO.setSex("0".equals(x.getSex()) ? "男" : "1".equals(x.getSex()) ? "女" : "保密");
            userInfoVO.setStatus("0".equals(x.getStatus()) ? "锁定" : "有效");
            return userInfoVO;
        }).collect(Collectors.toList());
        ExcelUtil.export("用户数据", ExportUserInfoVO.class, userInfoVOS, response);
    }

    @GetMapping("/getInfoByUsername")
    public ResultBean getInfoByUsername(String username) {
        return ResultBean.buildSuccess(userService.findUserDetail(username));
    }

    @GetMapping("/getInfoById")
    public ResultBean getInfoById(Long id) {
        return ResultBean.buildSuccess(userService.getOne(Wrappers.lambdaQuery(new SystemUser()).eq(SystemUser::getUserId, id)));
    }

    @GetMapping("/listInfoById")
    public ResultBean listInfoById(Long[] ids) {
        return ResultBean.buildSuccess(userService.listByIds(Arrays.asList(ids)));
    }

    @ApiOperation("锁定或解锁用户")
    @GetMapping("/lockUser")
    @OperationLog(module = ModuleName.USER, methods = "锁定或解锁用户", type = OperationLogTypeEnum.UPDATE)
    public ResultBean lockUser(Long id) {
        userService.lockUser(id);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("重置密码")
    @GetMapping("/resetPwd")
    @OperationLog(module = ModuleName.USER, methods = "重置密码", type = OperationLogTypeEnum.UPDATE)
    public ResultBean resetPwd(Long id) {
        userService.resetPwd(id);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("添加用户")
    @PostMapping("/add")
    @OperationLog(module = ModuleName.USER, methods = "添加用户", type = OperationLogTypeEnum.INSERT)
    public ResultBean add(@RequestBody SystemUser systemUser) {
        return ResultBean.buildSuccess(userService.createUser(systemUser));
    }

    @PostMapping("/update")
    @OperationLog(module = ModuleName.USER, methods = "修改用户", type = OperationLogTypeEnum.UPDATE)
    public ResultBean updateUserWithName(@RequestBody SystemUser user) {
        userService.updateUserWithName(user);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("批量删除用户")
    @PostMapping("/delUser")
    @OperationLog(module = ModuleName.USER, methods = "批量删除用户", type = OperationLogTypeEnum.DELETE)
    public ResultBean delUser(@RequestBody String[] ids) {
        userService.deleteUsers(ids);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("添加用户角色")
    @PostMapping("/addUserRole")
    @OperationLog(module = ModuleName.USER, methods = "添加用户角色", type = OperationLogTypeEnum.UPDATE)
    public ResultBean addUserRole(@RequestBody UserRole[] userRole) {
        userRoleService.bindRoleByRoleName(userRole);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("绑定openId")
    @GetMapping("/bindOpenId")
    public ResultBean bindOpenId(Long userId, String openId) {
        SystemUser user = new SystemUser();
        user.setUserId(userId);
        user.setOpenId(openId);
        userService.updateById(user);
        return ResultBean.buildSuccess();
    }


    @ApiOperation("新增用户对应菜单")
    @PostMapping("/saveUserMenu")
    @OperationLog(module = ModuleName.USER, methods = "新增用户对应菜单", type = OperationLogTypeEnum.UPDATE)
    public ResultBean saveUserMenu(@RequestBody MenuForUserDTO menuForUserDTO) {
        systemUserMenuService.saveUserMenu(menuForUserDTO);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("修改用户对应菜单")
    @PostMapping("/updateUserMenu")
    @OperationLog(module = ModuleName.USER, methods = "修改用户对应菜单", type = OperationLogTypeEnum.UPDATE)
    public ResultBean updateUserMenu(@RequestBody MenuForUserDTO menuForUserDTO) {
        systemUserMenuService.updateUserMenu(menuForUserDTO);
        return ResultBean.buildSuccess();
    }

    @ApiOperation("删除用户对应菜单")
    @GetMapping("/removeUserMenu")
    @OperationLog(module = ModuleName.USER, methods = "删除用户对应菜单", type = OperationLogTypeEnum.UPDATE)
    public ResultBean removeUserMenu(@ApiParam("用户id") @RequestParam Long userId) {
        systemUserMenuService.remove(Wrappers.lambdaQuery(new SystemUserMenu())
            .eq(SystemUserMenu::getUserId, userId));
        return ResultBean.buildSuccess();
    }

    @ApiOperation("查询用户对应菜单")
    @GetMapping("/findUserMenu")
    public ResultBean<List<Long>> findUserMenu(@ApiParam("用户id") @RequestParam Long userId) {
        return ResultBean.buildSuccess(systemUserMenuService.findUserMenu(userId));
    }

    @ApiOperation("查询用户菜单logo")
    @GetMapping("/getLogo")
    public ResultBean<EduUserLogo> getLogo(Long userId) {
        return ResultBean.buildSuccess(eduUserLogoService.getById(userId));
    }

    @ApiOperation("保存logo")
    @PostMapping("/saveLogo")
    @OperationLog(module = ModuleName.USER, methods = "保存logo", type = OperationLogTypeEnum.INSERT)
    public ResultBean saveLogo(@RequestBody EduUserLogo logo) {
        eduUserLogoService.saveOrUpdate(logo);
        return ResultBean.buildSuccess();
    }

}
