package com.bonus.gs.sub.evaluate.manager.controller;

import java.util.List;

import com.bonus.gs.sub.evaluate.manager.dao.UserDao;
import com.bonus.gs.sub.evaluate.manager.entity.LoginUser;
import com.bonus.gs.sub.evaluate.manager.entity.UserDto;
import com.bonus.gs.sub.evaluate.manager.model.SysUser;
import com.bonus.gs.sub.evaluate.manager.table.PageTableHandler;
import com.bonus.gs.sub.evaluate.manager.table.PageTableRequest;
import com.bonus.gs.sub.evaluate.manager.table.PageTableResponse;
import com.bonus.gs.sub.evaluate.manager.service.UserService;
import com.bonus.gs.sub.evaluate.manager.utils.*;
import com.bonus.gs.sub.evaluate.manager.utils.AjaxRes;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import com.bonus.gs.sub.evaluate.manager.annotation.LogAnnotation;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import javax.annotation.Resource;

/**
 * 用户相关接口
 */
@Api(tags = "用户")

@RestController
@RequestMapping("/users")
public class UserController {

	private static final Logger log = LoggerFactory.getLogger("adminLogger");

	@Autowired
	private UserService userService;
	@Autowired
	private UserDao userDao;

	@Resource
	private RedisTemplate<String, LoginUser> redisTemplate;


	@RequestMapping("/tokenVerify")
	public AjaxRes tokenVerify(String tokens, String loginName){
		System.err.println("tokens:"+tokens);
		AjaxRes ajaxRes = new AjaxRes();
		if(StringUtils.isBlank(tokens)){
			ajaxRes.setFailMsg("token不能为空");
			return ajaxRes;
		}
		Jackson2JsonRedisSerializer<LoginUser> serializer = new Jackson2JsonRedisSerializer<>(LoginUser.class);
		redisTemplate.setValueSerializer(serializer);
		String key= "tokens:"+tokens;
		LoginUser valur = redisTemplate.boundValueOps(key).get();

		if(valur!=null){
			if(valur.getUsername().equals(loginName)){
				int num = userService.getUserCount(loginName);
				String intro = valur.getIntro();
				if(num>0){
					ajaxRes.setSucceedMsg(intro);
					//ajaxRes.setSucceedMsg(AesCbcUtils.decrypt(intro));
				}else {
					ajaxRes.setFailMsg("系统为未找到符合用户，请联系管理员新增");
				}
			}else{
				ajaxRes.setFailMsg("登录名不匹配");
			}
		}else{
			ajaxRes.setFailMsg("token失效，未找到有效登录信息");
		}
		return  ajaxRes;
	}

	@LogAnnotation
	@PostMapping
	@ApiOperation(value = "保存用户")
	@PreAuthorize("hasAuthority('sys:user:add')")
	public SysUser saveUser(@RequestBody UserDto userDto) {
		SysUser u = userService.getUser(userDto.getUsername());
		if (u != null) {
			throw new IllegalArgumentException(userDto.getUsername() + "已存在");
		}

		return userService.saveUser(userDto);
	}

	@LogAnnotation
	@PutMapping
	@ApiOperation(value = "修改用户")
	@PreAuthorize("hasAuthority('sys:user:add')")
	public SysUser updateUser(@RequestBody UserDto userDto) {
		return userService.updateUser(userDto);
	}

	@LogAnnotation
	@PutMapping(params = "headImgUrl")
	@ApiOperation(value = "修改头像")
	public void updateHeadImgUrl(String headImgUrl) {
		SysUser user = UserUtil.getLoginUser();
		UserDto userDto = new UserDto();
		BeanUtils.copyProperties(user, userDto);
		userDto.setHeadImgUrl(headImgUrl);

		userService.updateUser(userDto);
		log.debug("{}修改了头像", user.getUsername());
	}

	@LogAnnotation
	@PutMapping("/{username}")
	@ApiOperation(value = "修改密码")
	@PreAuthorize("hasAuthority('sys:user:password')")
	public void changePassword(@PathVariable String username, String oldPassword, String newPassword) {
		userService.changePassword(username, oldPassword, newPassword);
	}

	@GetMapping
	@ApiOperation(value = "用户列表")
	@PreAuthorize("hasAuthority('sys:user:query')")
	public PageTableResponse listUsers(PageTableRequest request) {
		return new PageTableHandler(new PageTableHandler.CountHandler() {

			@Override
			public int count(PageTableRequest request) {
				return userDao.count(request.getParams());
			}
		}, new PageTableHandler.ListHandler() {

			@Override
			public List<SysUser> list(PageTableRequest request) {
				List<SysUser> list = userDao.list(request.getParams(), request.getOffset(), request.getLimit());
				return list;
			}
		}).handle(request);
	}

	@ApiOperation(value = "当前登录用户")
	@GetMapping("/current")
	public SysUser currentUser() {
		return UserUtil.getLoginUser();
	}

	@ApiOperation(value = "根据用户id获取用户")
	@GetMapping("/{id}")
	@PreAuthorize("hasAuthority('sys:user:query')")
	public SysUser user(@PathVariable Long id) {
		return userDao.getById(id);
	}

	@ApiOperation(value = "根据用户id修改密码")
	@PostMapping("/changePassWord")
	@ResponseBody
	public AjaxRes changePassWord(UserDto userDto) {
		AjaxRes ar = new AjaxRes();
		try {
			ar = userService.changePassWord(userDto);
		} catch (Exception e) {
			ar.setFailMsg(GlobalConst.DATA_FAIL);
		}
		return ar;
	}

}
