package com.bonus.hn.bearing.capacity.backstage.manager.controller;

import com.bonus.hn.bearing.capacity.backstage.manager.annotation.LogAnnotation;
import com.bonus.hn.bearing.capacity.backstage.companypro.entity.ProjectManagerBean;
import com.bonus.hn.bearing.capacity.backstage.manager.dao.UserDao;
import com.bonus.hn.bearing.capacity.backstage.manager.entity.MapBean;
import com.bonus.hn.bearing.capacity.backstage.manager.entity.UserDto;
import com.bonus.hn.bearing.capacity.backstage.manager.entity.ZNode;
import com.bonus.hn.bearing.capacity.backstage.manager.model.SysUser;
import com.bonus.hn.bearing.capacity.backstage.manager.service.UserService;
import com.bonus.hn.bearing.capacity.backstage.manager.table.PageTableHandler;
import com.bonus.hn.bearing.capacity.backstage.manager.table.PageTableRequest;
import com.bonus.hn.bearing.capacity.backstage.manager.table.PageTableResponse;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.AjaxRes;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.GlobalConst;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.R;
import com.bonus.hn.bearing.capacity.backstage.manager.utils.UserUtil;
import com.bonus.hn.bearing.capacity.backstage.project.entity.FileBean;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

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

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

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

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

	@Autowired
	private BCryptPasswordEncoder passwordEncoder;

	@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() {
		Objects.requireNonNull(UserUtil.getLoginUser()).setPassword(null);
		return UserUtil.getLoginUser();
	}

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


	/**-------------------------------------------用户管理新接口-----------------------------------------------------------------*/

	@LogAnnotation
	@PostMapping("getMsgContent")
	@ApiOperation(value = "用户管理-列表")
	public R getList(SysUser o){
		List<SysUser> list = userService.getMsgList(o);
		return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
	}

	@LogAnnotation
	@PostMapping("switchListen")
	@ApiOperation(value = "用户管理-用户锁定")
	public AjaxRes switchListen(SysUser bean) {
		AjaxRes ar = new AjaxRes();
		int result  = userService.updateSwitchListen(bean);
		if(result==1){
			ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
		}else {
			ar.setFailMsg(GlobalConst.DATA_FAIL);
		}
		return ar;
	}

	@LogAnnotation
	@PostMapping("getDepartmentTree")
	@ApiOperation(value = "用户管理-获取部门树")
	public AjaxRes getDepartmentTree() {
		AjaxRes ar = new AjaxRes();
		try {
			List<ZNode> list = userService.getDepartmentTree();
			ar.setSucceed(list);
		} catch (Exception e) {
			ar.setFailMsg(GlobalConst.DATA_FAIL);
		}
		return ar;
	}

	@LogAnnotation
	@PostMapping(value = "/getRole")
	@ApiOperation(value = "人员角色select列表")
	public List<MapBean> getRole() {
		List<MapBean> result = userService.getRole();
		return result;
	}

	@RequestMapping(value = "addInfo", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "用户管理-新增")
	public AjaxRes addInfo(@RequestBody SysUser bean) throws Exception {
		AjaxRes ar = new AjaxRes();
		int cb = userService.addInfo(bean);
		ar.setFailMsg(GlobalConst.DATA_FAIL);
		if(cb>0){
			ar.setFailMsg(GlobalConst.INIT_SUCCEED);
//			if (cb == 3){
//				ar.setFailMsg("人员已存在");
//			}
			if (cb == 5){
				ar.setFailMsg("手机号已存在");
			}
		}
		return  ar;
	}

	@RequestMapping(value = "updateInfo", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "用户管理-修改")
	public AjaxRes updateInfo(@RequestBody SysUser bean) throws Exception {
		AjaxRes ar = new AjaxRes();
		int cb = userService.updateInfo(bean);
		ar.setFailMsg(GlobalConst.DATA_FAIL);
		if(cb>0){
			ar.setFailMsg(GlobalConst.INIT_SUCCEED);
//			if (cb == 3){
//				ar.setFailMsg("人员已存在");
//			}
			if (cb == 5){
				ar.setFailMsg("手机号已存在");
			}
		}
		return  ar;
	}

	@RequestMapping(value = "updatePerson", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "个人信息-修改")
	public AjaxRes updatePerson(@RequestBody SysUser bean){
		AjaxRes ar = new AjaxRes();
		int cb = userService.updatePerson(bean);
		ar.setFailMsg(GlobalConst.DATA_FAIL);
		if(cb>0){
			ar.setFailMsg(GlobalConst.INIT_SUCCEED);
			if (cb == 5){
				ar.setFailMsg("手机号已存在");
			}
		}
		return  ar;
	}




	@RequestMapping(value = "getListPerson", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "个人信息-查询")
	public AjaxRes getListPerson(){
		AjaxRes ar = new AjaxRes();
		SysUser sysUser = userService.getListPerson();
		Map<String, Object> map = new HashMap<>(100);
		if(sysUser !=null){
			map.put("sysUser",sysUser);
		}
		ar.setSucceed(map,GlobalConst.DATA_SUCCEED);
		return ar;
	}

	@RequestMapping(value = "updateMyInfo", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "个人信息-修改")
	public AjaxRes updateMyInfo(@RequestBody SysUser bean) throws Exception {
		AjaxRes ar = new AjaxRes();
		int cb = userService.updateMyInfo(bean);
		ar.setFailMsg(GlobalConst.DATA_FAIL);
		if(cb>0){
			ar.setFailMsg(GlobalConst.INIT_SUCCEED);
		}
		return  ar;
	}

	@RequestMapping(value = "getListById", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "用户管理-查询人员信息")
	public AjaxRes getListById(String id){
		AjaxRes ar = new AjaxRes();
		SysUser sysUser = userService.getListById(id);
		Map<String, Object> map = new HashMap<>(100);
		if(sysUser !=null){
			map.put("sysUser",sysUser);
		}
		ar.setSucceed(map,GlobalConst.DATA_SUCCEED);
		return ar;
	}



	@LogAnnotation
	@PostMapping("delById")
	@ApiOperation(value = "用户管理-删除")
	public AjaxRes delById(SysUser bean) throws Exception {
		AjaxRes ar = new AjaxRes();
		//删除之前先查询出来
		Long userId = bean.getId();
		SysUser userDto = userDao.getEyId(userId);
		int result  = userService.delById(bean);
		if(result==1){
			ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
		}else {
			ar.setFailMsg(GlobalConst.DATA_FAIL);
		}

		return ar;
	}

	@LogAnnotation
	@PostMapping("resetPassword")
	@ApiOperation(value = "用户管理-重置密码")
	public AjaxRes resetPassword(SysUser bean) {
		AjaxRes ar = new AjaxRes();
		int result  = userService.resetPassword(bean);
		if(result==1){
			ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
		}else {
			ar.setFailMsg(GlobalConst.DATA_FAIL);
		}
		return ar;
	}

	@LogAnnotation
	@PostMapping("getSystemNotification")
	@ApiOperation(value = "个人信息-系统通知")
	public R getSystemNotification(SysUser o){
		List<SysUser> list = userService.getSystemNotification(o);
		return list.size() > 0 ? R.okTable(list, list.size()):R.failTable("暂无数据");
	}
	@LogAnnotation
	@PostMapping("getLoginLog")
	@ApiOperation(value = "个人信息-登录日志")
	public List<Map<String, Object>> getLoginLogs() {
		return userService.getLoginLogs();
	}

	@RequestMapping(value = "upLoginLog", method = RequestMethod.POST)
	@ApiOperation(value = "个人信息-公告状态变更")
	public AjaxRes upLoginLog(SysUser bean) {
		AjaxRes ar = new AjaxRes();
		int cb = userService.upLoginLog(bean);
		ar.setFailMsg(GlobalConst.DATA_FAIL);
		if(cb>0){
			ar.setFailMsg(GlobalConst.INIT_SUCCEED);
		}
		return  ar;
	}

	@RequestMapping(value = "getDownloadRecord", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "首页-导出/下载记录获取")
	public AjaxRes getDownloadRecord(FileBean o){
		AjaxRes ar = new AjaxRes();
		List<FileBean> fileBeans = userService.getDownloadRecord(o);
		Map<String, Object> map = new HashMap<>(100);
		if(fileBeans !=null){
			map.put("fileBeans",fileBeans);
		}
		ar.setSucceed(map, GlobalConst.DATA_SUCCEED);
		return ar;
	}

	@LogAnnotation
	@PostMapping("delRecordById")
	@ApiOperation(value = "首页-删除某条记录功能")
	public AjaxRes delRecordById(FileBean bean) {
		AjaxRes ar = new AjaxRes();
		int result  = userService.delRecordById(bean);
		if(result==1){
			ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
		}else {
			ar.setFailMsg(GlobalConst.DATA_FAIL);
		}
		return ar;
	}
	@LogAnnotation
	@PostMapping("delAll")
	@ApiOperation(value = "首页-清空记录功能")
	public AjaxRes delAll(FileBean bean) {
		AjaxRes ar = new AjaxRes();
		int result  = userService.delAll(bean);
		if(result > 0){
			ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
		}else {
			ar.setFailMsg(GlobalConst.DATA_FAIL);
		}
		return ar;
	}

	@LogAnnotation
	@PostMapping("delReadAlready")
	@ApiOperation(value = "系统通知-全部标记为已读")
	public AjaxRes delReadAlready(FileBean bean) {
		AjaxRes ar = new AjaxRes();
		int result  = userService.delReadAlready(bean);
		if(result > 0){
			ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
		}else {
			ar.setFailMsg(GlobalConst.DATA_FAIL);
		}
		return ar;
	}
}


