package com.energy.manage.service.controller.system;

import com.energy.manage.common.base.Page;
import com.energy.manage.common.constant.Constants;
import com.energy.manage.common.constant.redis.ManagerRedisKeyConstant;
import com.energy.manage.common.po.system.SysRolePO;
import com.energy.manage.common.po.system.SysUserInfoPO;
import com.energy.manage.common.reponse.ResultResp;
import com.energy.manage.common.util.BCryptTools;
import com.energy.manage.service.config.annotations.PassToken;
import com.energy.manage.service.config.annotations.UserLoginToken;
import com.energy.manage.service.domain.dto.system.*;
import com.energy.manage.service.domain.vo.system.PermissionVo;
import com.energy.manage.service.domain.vo.system.UserRoleVo;
import com.energy.manage.service.domain.vo.system.UserVo;
import com.energy.manage.service.service.system.SysPermissionService;
import com.energy.manage.service.service.system.SysRoleService;
import com.energy.manage.service.service.system.SysUserInfoService;
import com.energy.manage.service.util.JwtUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author sy
 * @menu: 后台用户表
 * @date 2021-10-18 13:32:05
 */
@Slf4j
@RestController
@CrossOrigin
@RequestMapping("sysuserinfo")
@Api(value = "SysUserInfoController", tags = "系统用户管理")
public class SysUserInfoController {

    @Autowired
    private SysUserInfoService sysUserInfoService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 添加后台用户
     * @return
     */
    @UserLoginToken
    @PostMapping(value = "addUser")
    @ApiOperation(value = "添加后台用户", notes = "areaInfo = provinceId,cityId,areaId;provinceId,cityId,areaId;")
    public ResultResp addUser(@RequestBody UserAddDto userAddDto) {
        if (StringUtils.isEmpty(userAddDto.getPhone()) || StringUtils.isEmpty(userAddDto.getUserName()) || !Optional.ofNullable(userAddDto.getRoleId()).isPresent()) {
            return ResultResp.NOTNULLPARAM();
        }
        SysUserInfoPO userPO = new SysUserInfoPO();
        userPO.setLoginName(userAddDto.getLoginName());
        userPO = sysUserInfoService.selectOne(userPO);
        if (null != userPO) {
            log.info("登录名已被占用！");
            return ResultResp.EXISTSUSER();
        }
        SysUserInfoPO sysUserInfoPO = new SysUserInfoPO();
        sysUserInfoPO.setUserPhone(userAddDto.getPhone());
        sysUserInfoPO = sysUserInfoService.selectOne(sysUserInfoPO);
        if (null != sysUserInfoPO) {
            log.info("手机号已被占用！");
            return ResultResp.FAIL("手机号已被占用！");
        }
        userPO = new SysUserInfoPO();
        userPO.setUserPhone(userAddDto.getPhone());
        userPO.setState(Constants.GLOBAL_IN_USE);
        userPO.setLoginName(userAddDto.getLoginName());
        userPO.setUserName(userAddDto.getUserName());
        userPO.setUserPassword(BCryptTools.hashpw(userAddDto.getPwd()));
        userPO.setCreateTime(new Date());
        boolean flag = sysUserInfoService.addSystemUser(userPO, userAddDto.getRoleId());
        if (flag) {
            return ResultResp.SUCCESS();
        }
        return ResultResp.FAIL();
    }

    /**
     * 获取后台用户分页
     * @return
     */
    @UserLoginToken
    @PostMapping(value = "getUserByName")
    @ApiOperation(value = "获取后台用户分页")
    public ResultResp<Page<UserRoleVo>> getUserByName(@RequestBody UserByNameDto userByNameDto) {
        Page<UserRoleVo> page = sysUserInfoService.getUserByName(userByNameDto.getPageNum(), userByNameDto.getPageSize(), userByNameDto.getUserName(), userByNameDto.getRoleId());
        return ResultResp.SUCCESS(page);
    }

    /**
     * 获取后台用户
     *
     * @param userId
     * @return
     */
    @UserLoginToken
    @GetMapping(value = "getUserById")
    @ApiOperation(value = "获取后台用户")
    public ResultResp<UserRoleVo> getUserById(@RequestParam Integer userId) {
        UserRoleVo user = sysUserInfoService.getUserById(userId);
        return ResultResp.SUCCESS(user);
    }

    /**
     * 启用后台用户
     * @return
     */
    @UserLoginToken
    @PostMapping(value = "enableUser")
    @ApiOperation(value = "启用后台用户")
    public ResultResp enableUser(@RequestBody UserDto userDto) {
        if (!Optional.ofNullable(userDto.getUserId()).isPresent()) {
            return ResultResp.NOTNULLPARAM();
        }
        SysUserInfoPO userPO = new SysUserInfoPO();
        userPO.setId(userDto.getUserId());
        userPO.setState(Constants.GLOBAL_IN_USE);
        boolean flag = sysUserInfoService.updateUser(userPO);
        if (flag) {
            return ResultResp.SUCCESS();
        }
        return ResultResp.FAIL();
    }

    /**
     * 禁用后台用户
     * @return
     */
    @UserLoginToken
    @PostMapping(value = "disableUser")
    @ApiOperation(value = "禁用后台用户")
    public ResultResp disableUser(@RequestBody UserDto userDto) {
        if (!Optional.ofNullable(userDto.getUserId()).isPresent()) {
            return ResultResp.NOTNULLPARAM();
        }
        SysUserInfoPO userPO = new SysUserInfoPO();
        userPO.setId(userDto.getUserId());
        userPO = sysUserInfoService.selectOne(userPO);
        if (null == userPO) {
            return ResultResp.FAIL("没有该用户");
        }
        userPO.setState(Constants.GLOBAL_NOT_USE);
        boolean flag = sysUserInfoService.updateUser(userPO);
        if (flag) {

            stringRedisTemplate.delete(String.format(ManagerRedisKeyConstant.SYSTEM_USER_LOGIN_INFO, userPO.getUserPhone()));
            return ResultResp.SUCCESS();
        }
        return ResultResp.FAIL();
    }

    /**
     * 删除后台用户
     *
     * @param userDto
     * @return
     */
    @UserLoginToken
    @PostMapping(value = "deleteUser")
    @ApiOperation(value = "删除后台用户")
    public ResultResp deleteUser(@RequestBody UserDto userDto) {
        if (!Optional.ofNullable(userDto.getUserId()).isPresent()) {
            return ResultResp.NOTNULLPARAM();
        }
        SysUserInfoPO userPO = new SysUserInfoPO();
        userPO.setId(userDto.getUserId());
        userPO = sysUserInfoService.selectOne(userPO);
        if (null == userPO) {
            return ResultResp.FAIL("没有该用户");
        }
        boolean flag = sysUserInfoService.deleteUser(userPO);
        if (flag) {
            stringRedisTemplate.delete(String.format(ManagerRedisKeyConstant.SYSTEM_USER_LOGIN_INFO, userPO.getUserPhone()));
            return ResultResp.SUCCESS();
        }
        return ResultResp.FAIL();
    }

    /**
     * 后台重置密码
     *
     * @return
     */
    @UserLoginToken
    @PostMapping(value = "resetPWD")
    @ApiOperation(value = "后台重置密码")
    public ResultResp updateUser(@RequestBody UserDto userDto) {
        if (!Optional.ofNullable(userDto.getUserId()).isPresent()) {
            return ResultResp.NOTNULLPARAM();
        }
        SysUserInfoPO userPO = new SysUserInfoPO();
        userPO.setId(userDto.getUserId());
        userPO.setUserPassword(BCryptTools.hashpw(Constants.GLOBAL_DEFAULT_PWD));
        boolean flag = sysUserInfoService.updateUser(userPO);
        if (flag) {
            return ResultResp.SUCCESS();
        }
        return ResultResp.FAIL();
    }

    /**
     * 修改后台用户
     * @return
     */
    @UserLoginToken
    @PostMapping(value = "updateUser")
    @ApiOperation(value = "修改后台用户")
    public ResultResp updateUser(@RequestBody UserUpdateDto userUpdateDto) {

        if (StringUtils.isEmpty(userUpdateDto.getPhone()) || StringUtils.isEmpty(userUpdateDto.getUserName()) || !Optional.ofNullable(userUpdateDto.getRoleId()).isPresent()) {
            return ResultResp.NOTNULLPARAM();
        }
        if (StringUtils.isEmpty(userUpdateDto.getPhone()) || StringUtils.isEmpty(userUpdateDto.getUserName()) ||
                !Optional.ofNullable(userUpdateDto.getRoleId()).isPresent() || !Optional.ofNullable(userUpdateDto.getUserId()).isPresent()) {
            return ResultResp.NOTNULLPARAM();
        }
        SysUserInfoPO userPO = new SysUserInfoPO();
        userPO.setId(userUpdateDto.getUserId());
        userPO.setUserPhone(userUpdateDto.getPhone());
        userPO.setUserName(userUpdateDto.getUserName());
        userPO.setLoginName(userUpdateDto.getLoginName());
        boolean flag = sysUserInfoService.updateUserRole(userPO, userUpdateDto.getRoleId());
        if (flag) {
            return ResultResp.SUCCESS();
        }
        return ResultResp.FAIL();
    }

    /**
     * 修改密码
     * @return
     */
    @UserLoginToken
    @PostMapping(value = "updatePWD")
    @ApiOperation(value = "修改密码")
    public ResultResp updatePWD(@RequestBody UserUpdatePwdDto userUpdatePwdDto) {
        if (StringUtils.isEmpty(userUpdatePwdDto.getOldPWD()) || StringUtils.isEmpty(userUpdatePwdDto.getNewPWD()) || !Optional.ofNullable(userUpdatePwdDto.getUserId()).isPresent()) {
            return ResultResp.NOTNULLPARAM();
        }
        return sysUserInfoService.updateUserPWD(userUpdatePwdDto.getUserId(), userUpdatePwdDto.getOldPWD(), userUpdatePwdDto.getNewPWD());
    }

    /**
     * 用户登录
     *
     * @param loginDto
     * @return
     */
    @PassToken
    @PostMapping(value = "open/userLogin")
    @ApiOperation(value = "用户登录")
    public ResultResp<Map<String, Object>> userLogin(@RequestBody LoginDto loginDto) {

        String userName = loginDto.getUserName();
        String password = loginDto.getPassword();

        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            return ResultResp.NOTNULLPARAM();
        }

        SysUserInfoPO userPO = new SysUserInfoPO();
        userPO.setLoginName(userName);
        userPO = sysUserInfoService.selectOne(userPO);
        if (null == userPO || null == userPO.getId()) {
            return ResultResp.NOTEXISTSUSER();
        }

        if (userPO.getState().equals(0)) {
            return ResultResp.FAIL("此账户已经禁用！");
        }

        if (!BCryptTools.checkpw(password, userPO.getUserPassword())) {
            return ResultResp.ERRORPWD();
        }

        List<PermissionVo> list = permissionService.getRolePermissionByUserId(userPO.getId());
        SysRolePO rolePO = sysRoleService.getSysRole(userPO.getId());
        String token = JwtUtil.getLoginToken(userPO.getId(), userPO.getLoginName(), userPO.getUserPhone(), userPO.getUserPassword(), rolePO.getId());
        userPO.setUserPassword(null);
        Map<String, Object> map = new HashMap<>();
        map.put("role", rolePO);
        map.put("permission", list);
        map.put("userInfo", userPO);
        map.put("token", token);
        if (!CollectionUtils.isEmpty(list)) {
            stringRedisTemplate.opsForValue().set(String.format(ManagerRedisKeyConstant.SYSTEM_USER_LOGIN_INFO, userName), token);
        }
        return ResultResp.SUCCESS(map);
    }

    /**
     * 用户退出
     * @return
     */
    @UserLoginToken
    @PostMapping(value = "userLogout")
    @ApiOperation(value = "用户退出")
    public ResultResp userLogout(@RequestBody UserLogoutDto userLogoutDto) {
        stringRedisTemplate.delete(String.format(ManagerRedisKeyConstant.SYSTEM_USER_LOGIN_INFO, userLogoutDto.getPhone()));
        return ResultResp.SUCCESS();
    }

    /**
     * 根据userId获取用户详情
     *
     * @param userId
     * @return
     */
    @UserLoginToken
    @GetMapping(value = "getUserInfoByUserId")
    @ApiOperation(value = "根据userId获取用户详情")
    public ResultResp<UserVo> getUserInfoByUserId(@RequestParam Integer userId) {
        if (!Optional.ofNullable(userId).isPresent()) {
            return ResultResp.NOTNULLPARAM();
        }
        UserVo vo = sysUserInfoService.getUserInfoByUserId(userId);
        return ResultResp.SUCCESS(vo);
    }


//    public static void main(String[] args) {
//        System.out.println(BCryptTools.checkpw("123456","$2a$10$t0ZYLlopxXmwpwdQ4xfTr.84sk.U8EpguUeNkAPXdm0MF4I3N5jOa"));
//    }

}
