package com.bonus.boot.manager.manager.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bonus.boot.manager.basic.controller.AESCBCUtils;
import com.bonus.boot.manager.manager.annotation.LogAnnotation;
import com.bonus.boot.manager.manager.dao.UserDao;
import com.bonus.boot.manager.manager.entity.AddressConfiguration;
import com.bonus.boot.manager.manager.entity.R;
import com.bonus.boot.manager.manager.entity.UnifyBean;
import com.bonus.boot.manager.manager.entity.UserDto;
import com.bonus.boot.manager.manager.model.SysUser;
import com.bonus.boot.manager.manager.service.UserService;
import com.bonus.boot.manager.manager.table.PageTableHandler;
import com.bonus.boot.manager.manager.table.PageTableRequest;
import com.bonus.boot.manager.manager.table.PageTableResponse;
import com.bonus.boot.manager.manager.utils.AjaxRes;
import com.bonus.boot.manager.manager.utils.GlobalConst;
import com.bonus.boot.manager.manager.utils.UserUtil;
import io.jsonwebtoken.Claims;
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.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 用户相关接口
 */
@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() {
		return UserUtil.getLoginUser();
	}

	@GetMapping("/getTokenKey")
	@ResponseBody
	public String getTokenKey(String jwtToken) throws IOException {
		String userName="";
		Claims claims = JwtUtils.parseToken(jwtToken);
		userName = (String) claims.get(SecurityConstants.DETAILS_USERNAME);
		return userName;
	}


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

	@LogAnnotation
	@PostMapping("resetUserPwd")
	@ApiOperation(value = "重置密码")
	public AjaxRes resetUserPwd(@RequestBody SysUser user) {
		AjaxRes ar = new AjaxRes();
		user.setPassword(passwordEncoder.encode("NXdtxny@123"));
		int result = userDao.resetUserPwd(user.getPassword(),user.getUserId());
		if (result == 1){
			ar.setSucceedMsg(GlobalConst.UPDATE_SUCCEED);
		}else {
			ar.setFailMsg(GlobalConst.UPDATE_FAIL);
		}
		return ar;
	}

/**-------------------------------------------以上为老代码,以下为layui新页面所使用的方法-----------------------------------------------------------------*/
	
	@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("暂无数据");
	}

	@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 == 4){
				ar.setFailMsg("人员年龄不符合标准");
			}
			if (cb == 5){
				ar.setFailMsg("手机号已存在");
			}
			int ks = 0;
			if (cb != 3 && cb != 5){
				String token = login();
				String isActive = addUser(bean.getUsername(), bean.getPhone(),token);
				if(isActive.equals("1")){
					ks = 1;
					ar.setFailMsg(GlobalConst.INIT_SUCCEED);
				}else{
					for (int i = 0; i < 3; i++) {
						isActive = addUser(bean.getUsername(), bean.getPhone(),token);
						if(isActive.equals("1")){
							ks = 1;
							ar.setFailMsg(GlobalConst.INIT_SUCCEED);
							break;
						}
					}
				}

				//三次都未推送成功 修改推送状态
				if(ks!=1){
					userService.updateUnify(bean.getId());
					ar.setFailMsg(GlobalConst.INIT_SUCCEED);
				}
			}else {
				ar.setFailMsg(GlobalConst.DATA_FAIL);
			}
		}
		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("手机号已存在");
			}
			int ks = 0;
			if (cb != 3 && cb != 5){
				String token = login();
				String isActive = addUser(bean.getUsername(), bean.getPhone(),token);
				if(isActive.equals("1")){
					ks = 1;
					ar.setFailMsg(GlobalConst.INIT_SUCCEED);
				}else{
					for (int i = 0; i < 3; i++) {
						isActive = addUser(bean.getUsername(), bean.getPhone(),token);
						if(isActive.equals("1")){
							ks = 1;
							ar.setFailMsg(GlobalConst.INIT_SUCCEED);
							break;
						}
					}
				}

				//三次都未推送成功 修改推送状态
				if(ks!=1){
					userService.updateUnify(bean.getId());
					ar.setFailMsg(GlobalConst.INIT_SUCCEED);
				}
			}else {
				ar.setFailMsg(GlobalConst.DATA_FAIL);
			}

		}
		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<>();
		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 ks = 0;
		String token = login();
		String isActive = deldctUnifyUser(userDto.getUsername(),userDto.getPhone(),token);
		if(isActive.equals("1")){
			ks = 1;
		}else{
			for (int i = 0; i < 3; i++) {
				isActive = deldctUnifyUser(userDto.getUsername(),userDto.getPhone(),token);
				if(isActive.equals("1")){
					ks = 1;
					break;
				}
			}
		}
		//三次都未推送成功
		if(ks!=1){
			ar.setFailMsg(GlobalConst.DATA_FAIL);
		}else{
			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("resetPasswordForOne")
	@ApiOperation(value = "用户管理-第一次重置密码")
	public AjaxRes resetPasswordForOne(SysUser bean) {
		AjaxRes ar = new AjaxRes();
		int result  = userService.resetPasswordForOne(bean);
		if(result==1){
			ar.setSucceedMsg(GlobalConst.DATA_SUCCEED);
		}else {
			ar.setFailMsg(GlobalConst.DATA_FAIL);
		}
		return ar;
	}



	//统一平台登录接口 获取token
	public static String login() throws Exception {
		String phone = "15955081965";
		String phones = AESCBCUtils.encrypt(phone, AESCBCUtils.sKey);
		String password = "ccw1998@YYT";
		String passwords = AESCBCUtils.encrypt(password, AESCBCUtils.sKey);
		String user = "{'phone':'" + phones + "','pd':'" + passwords + "'}";
		JSONObject object = JSON.parseObject(user);
//		String result = HttpClientUtils.doHttpPost("http://112.29.103.165:1616/ynuw/sys/api/userLogin", object, null);
		String result = HttpClientUtils.doHttpPost(AddressConfiguration.UNIFICATION_URL + "/ynuw/sys/api/userLogin", object, null);
		JSONObject jsonObject = JSONObject.parseObject(result);
		String string = JSONObject.parseObject(jsonObject.getString("data")).getString("token");
		return string;
	}

	//统一平台后台新增接口 获取token
	public String addUser(String userName, String phone, String token) throws Exception {
		String isActive = "";
		List<UnifyBean> list = new ArrayList<>();
		UnifyBean userVo = new UnifyBean();
		userVo.setUserName(userName);
		userVo.setPhone(phone);
		userVo.setSystemName("健康体检");
		String permissionQuery = userService.getPermissionQuerys(userVo);
		userVo.setAuth(permissionQuery);
		userVo.setIsBlacklist("0");
		userVo.setAccountStatus("1");
		list.add(userVo);
		String s = JSON.toJSONString(list);
		String encrypt = AESCBCUtils.encrypt(s, AESCBCUtils.sKey);
		String params = "{'params':'" + encrypt + "'}";
		JSONObject object = JSON.parseObject(params);
//		String result = HttpClientUtils.doHttpPost("http://112.29.103.165:1616/ynuw/sys/api/putUser", object, token);
		String result = HttpClientUtils.doHttpPost(AddressConfiguration.UNIFICATION_URL + "/ynuw/sys/api/putUser", object, token);
		JSONObject jsonObject = JSONObject.parseObject(result);
		String code = jsonObject.getString("code");
		System.err.println("新增code="+code);
		if("200".equals(code)){
			JSONArray data = jsonObject.getJSONArray("data");
			System.err.println("新增data="+data);
			if(data.size() == 0){
				isActive = "1";
			}else{
				isActive = "0";
			}
		}else{
			isActive = "0";
		}
		return isActive;
	}

	//统一平台修改接口 获取token
	private String updateUnifyUser(String userName, String phone, String token) throws Exception {
		String isActive = "";
		List<UnifyBean> list = new ArrayList<>();
		UnifyBean userVo = new UnifyBean();
		userVo.setUserName(userName);
		userVo.setPhone(phone);
		userVo.setSystemName("健康体检");
		userVo.setAuth("后台");
		userVo.setIsBlacklist("0");
		userVo.setAccountStatus("1");
		list.add(userVo);
		String s = JSON.toJSONString(list);
		String encrypt = AESCBCUtils.encrypt(s, AESCBCUtils.sKey);
		String params = "{'params':'" + encrypt + "'}";
		JSONObject object = JSON.parseObject(params);
		String result = HttpClientUtils.doHttpPost(AddressConfiguration.UNIFICATION_URL + "/ynuw/sys/api/updateUser", object, token);
		JSONObject jsonObject = JSONObject.parseObject(result);
		String code = jsonObject.getString("code");
		System.err.println("修改code="+code);
		if(code.equals("200")){
			JSONArray data = jsonObject.getJSONArray("data");
			System.err.println("修改data="+data);
			if(data.size() == 0){
				isActive = "1";
			}else{
				isActive = "0";
			}
		}else{
			isActive = "0";
		}
		return isActive;
	}

	private String deldctUnifyUser(String userName, String phone, String token) throws Exception {
		String isActive = "";
		List<UnifyBean> list = new ArrayList<>();
		UnifyBean userVo = new UnifyBean();
		userVo.setUserName(userName);
		userVo.setPhone(phone);
		userVo.setSystemName("健康体检");
		list.add(userVo);
		String s = JSON.toJSONString(list);
		String encrypt = AESCBCUtils.encrypt(s, AESCBCUtils.sKey);
		String params = "{'params':'" + encrypt + "'}";
		JSONObject object = JSON.parseObject(params);
//		String result = HttpClientUtils.doHttpPost("http://112.29.103.165:1616/ynuw/sys/api/delUser", object, token);
		String result = HttpClientUtils.doHttpPost(AddressConfiguration.UNIFICATION_URL + "/ynuw/sys/api/delUser", object, token);
		JSONObject jsonObject = JSONObject.parseObject(result);
		String code = jsonObject.getString("code");
		System.err.println("删除code="+code);
		if(code.equals("200")){
			JSONArray data = jsonObject.getJSONArray("data");
			System.err.println("删除data="+data);
			if(data.size() == 0){
				isActive = "1";
			}else{
				isActive = "0";
			}
		}else{
			isActive = "0";
		}
		return isActive;
	}

}
