/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package io.renren.modules.sys.controller;

import io.renren.common.annotation.SysLog;
import io.renren.common.utils.Constant;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.common.validator.Assert;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.entity.SysUserTokenEntity;
import io.renren.modules.sys.form.PasswordForm;
import io.renren.modules.sys.service.SysUserRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.SysUserTokenService;
import io.renren.modules.sys.service.alg.SysLoginAlgService;
import io.renren.modules.sys.service.alg.SysUserAlgService;
import io.renren.modules.sys.service.alg.SysUserRoleAlgService;
import io.renren.modules.sys.service.bigdata.SysLoginBigDataService;
import io.renren.modules.sys.service.bigdata.SysUserBigDataService;
import io.renren.modules.sys.service.cloud.SysLoginCloudService;
import io.renren.modules.sys.service.cloud.SysUserCloudService;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 系统用户
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {
	@Autowired
	private SysUserService sysUserService;
	@Autowired
	private SysUserRoleService sysUserRoleService;

	//算法平台
	@Autowired
	private SysUserAlgService sysUserAlgService;
	//云平台
	@Autowired
	private SysUserCloudService sysUserCloudService;
	//大数据平台
	@Autowired
	private SysUserBigDataService sysUserBigDataService;

//	@Autowired
//	private SysLoginAlgService sysLoginAlgService;
//	@Autowired
//	private SysLoginCloudService sysLoginCloudService;
//	@Autowired
//	private SysLoginBigDataService sysLoginBigDataService;
//	@Autowired
//	private SysUserTokenService sysUserTokenService;


	/**
	 * 所有用户列表
	 */
	@GetMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam Map<String, Object> params){
		//只有超级管理员，才能查看所有管理员列表
		if(getUserId() != Constant.SUPER_ADMIN){
			params.put("createUserId", getUserId());
		}
		PageUtils page = sysUserService.queryPage(params);

		return R.ok().put("page", page);
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@GetMapping("/info")
	public R info(){
		return R.ok().put("user", getUser());
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@PostMapping("/password")
	public R password(@RequestBody PasswordForm form){
		Assert.isBlank(form.getNewPassword(), "新密码不为能空");
		
		//sha256加密
		String password = new Sha256Hash(form.getPassword(), getUser().getSalt()).toHex();
		//sha256加密
		String newPassword = new Sha256Hash(form.getNewPassword(), getUser().getSalt()).toHex();
				
		//更新密码
		boolean b = sysUserAlgService.updatePassword(getUserId(), password, newPassword);
		boolean b1 = sysUserBigDataService.updatePassword(getUserId(), password, newPassword);
		boolean b2 = sysUserCloudService.updatePassword(getUserId(), password, newPassword);
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if(!flag){
			return R.error("原密码不正确");
		}
		
		return R.ok();
	}
	
	/**
	 * 用户信息
	 */
	@GetMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId){
		SysUserEntity user = sysUserService.getById(userId);
		
		//获取用户所属的角色列表
		List<Long> roleIdList = sysUserRoleService.queryRoleIdList(userId);
		user.setRoleIdList(roleIdList);
		
		return R.ok().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@PostMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, AddGroup.class);

		// 保证四个数据库中的salt和password相同
		String salt = RandomStringUtils.randomAlphanumeric(20);
		String password = new Sha256Hash(user.getPassword(), salt).toHex();

		// 将前端获取的权限分别交给不同平台
		List<Long> roleIdList = user.getRoleIdList();
		Long bigData = roleIdList.get(0);
		Long alg = roleIdList.get(1);
		List<Long> bigDataRoleList = new ArrayList<>();
		List<Long> algRoleList = new ArrayList<>();
		bigDataRoleList.add(bigData);
		algRoleList.add(alg);



		if(alg != null){
			//算法平台
			user.setRoleIdList(algRoleList);
			List<SysUserEntity> list1 = sysUserAlgService.list();
			for(SysUserEntity sysUserEntity : list1){
				if(sysUserEntity.getUsername().equals(user.getUsername())) return R.error("已存在重复名称的用户");
			}
			user.setCreateUserId(getUserId());
			sysUserAlgService.saveUser(user,salt,password);
		}

		if(bigData != null){
			//大数据平台
			user.setRoleIdList(bigDataRoleList);
			List<SysUserEntity> list3 = sysUserBigDataService.list();
			for(SysUserEntity sysUserEntity : list3){
				if(sysUserEntity.getUsername().equals(user.getUsername())) return R.error("已存在重复名称的用户");
			}
			user.setCreateUserId(getUserId());
			sysUserBigDataService.saveUser(user,salt,password);
		}



		//云平台
		List<SysUserEntity> list2 = sysUserCloudService.list();
		for(SysUserEntity sysUserEntity : list2){
			if(sysUserEntity.getUsername().equals(user.getUsername())) return R.error("已存在重复名称的用户");
		}
		user.setCreateUserId(getUserId());
		sysUserCloudService.saveUser(user,salt,password);



		// 统一登录平台
		List<SysUserEntity> list = sysUserService.list();
		for(SysUserEntity sysUserEntity : list){
			if(sysUserEntity.getUsername().equals(user.getUsername())) return R.error("已存在重复名称的用户");
		}
		user.setCreateUserId(getUserId());
		sysUserService.saveUser(user,salt,password);

		SysUserEntity tarUser = sysUserService.queryByUserName(user.getUsername());

//		// 在user_token表中创建该用户
//		//当前时间
//		Date now = new Date();
//		//过期时间
//		Date expireTime = new Date(now.getTime() + 3600 * 12 * 1000);
//		SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
//		tokenEntity.setUserId(tarUser.getUserId());
//		tokenEntity.setToken("1");
//		tokenEntity.setUpdateTime(now);
//		tokenEntity.setExpireTime(expireTime);
//
//		sysLoginAlgService.save(tokenEntity);
//		sysLoginCloudService.save(tokenEntity);
//		sysLoginBigDataService.save(tokenEntity);
//		sysUserTokenService.save(tokenEntity);

		return R.ok();
	}
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@PostMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody SysUserEntity user){
		ValidatorUtils.validateEntity(user, UpdateGroup.class);

		user.setCreateUserId(getUserId());
		sysUserService.update(user);
		
		return R.ok();
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@PostMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds){
		if(ArrayUtils.contains(userIds, 1L)){
			return R.error("系统管理员不能删除");
		}
		
		if(ArrayUtils.contains(userIds, getUserId())){
			return R.error("当前用户不能删除");
		}
		
		sysUserService.deleteBatch(userIds);
		
		return R.ok();
	}
}
