package com.pj.project.sys_user;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.pj.project.sys_user_password.SysUserPasswordService;
import com.pj.project.sys_user_sync.brd.SspServerBrdUtil;
import com.pj.project4sp.SP;
import com.pj.utils.sg.AjaxError;
import com.pj.utils.sg.AjaxJson;
import com.pj.utils.so.SoMap;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.sso.SaSsoUtil;


/**
 * Controller: sys_user -- 用户表
 * @author shengzhang 
 */
@RestController
@RequestMapping("/SysUser/")
public class SysUserController {

	/** 底层 Mapper 对象 */
	@Autowired
	SysUserMapper sysUserMapper;

	/** 底层 Service 对象 */
	@Autowired
	SysUserService sysUserService;

	/** 底层 Service 对象 */
	@Autowired
	SysUserPasswordService sysUserPasswordService;

	/** 增 */  
	@RequestMapping("add")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	@Transactional(rollbackFor = Exception.class)
	public AjaxJson add(SysUser s){
		// 新增 
		SysUser s2 = sysUserService.add(s);
		
		// $$ 向外广播
		SspServerBrdUtil.userAdd(s2, s.getPassword2());
		
		//  返回 
		return AjaxJson.getSuccessData(s2);
	}

	/** 删除用户（逻辑删除） */
	@RequestMapping("delete")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	@Transactional(rollbackFor = Exception.class)	
	public AjaxJson delete(long id){
		// 删除 
		sysUserService.delete(id);

		// $$ 向外广播
		SspServerBrdUtil.userDelete(id);
		
		return AjaxJson.getSuccess();
	}

	/** 批量删除用户（逻辑删除） */  
	@RequestMapping("deleteByIds")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	public AjaxJson deleteByIds(){
		List<Long> ids = SoMap.getRequestSoMap().getListByComma("ids", long.class); 
		List<String> resList = new ArrayList<>();
		for (Long id : ids) {
			try {
				SP.publicService.begin(() -> {
					// 删除 $$ 并广播
					sysUserService.delete(id);
					SspServerBrdUtil.userDelete(id);
					resList.add("用户id=" + id + "，删除成功；");
				});
			} catch (Exception e) {
				resList.add("用户id=" + id + "，删除失败：" + e.getMessage());
				e.printStackTrace();
			}
		}
		
		return AjaxJson.getSuccessData(resList);
	}
	
	/** 恢复用户 */
	@RequestMapping("unDelete")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	@Transactional(rollbackFor = Exception.class)	
	public AjaxJson unDelete(long id){
		// 开始修改 
		sysUserService.unDelete(id);

		// $$ 向外广播
		SysUser s2 = sysUserMapper.getById(id);
		String pw = sysUserMapper.getPwById(id);
		SspServerBrdUtil.userAdd(s2, pw);
		
		// 返回 
		return AjaxJson.getSuccess();
	}

	/** 批量恢复用户 */  
	@RequestMapping("unDeleteByIds")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	public AjaxJson unDeleteByIds(){
		List<Long> ids = SoMap.getRequestSoMap().getListByComma("ids", long.class); 
		List<String> resList = new ArrayList<>();
		for (Long id : ids) {
			try {
				SP.publicService.begin(() -> {
					// 恢复
					sysUserService.unDelete(id);
					// $$ 广播
					SysUser s2 = sysUserMapper.getById(id);
					String pw = sysUserMapper.getPwById(id);
					SspServerBrdUtil.userAdd(s2, pw);
					// 响应 
					resList.add("用户id=" + id + "，恢复成功；");
				});
			} catch (Exception e) {
				resList.add("用户id=" + id + "，恢复失败：" + e.getMessage());
				e.printStackTrace();
			}
		}
		
		return AjaxJson.getSuccessData(resList);
	}
	
	/** 彻底删除用户（物理删除） */
	@RequestMapping("realDelete")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	public AjaxJson realDelete(long id){
		
		// 开始删除 
		sysUserService.realDelete(id);
		
		// 返回 
		return AjaxJson.getSuccess();
	}

	/** 批量彻底删除用户（物理删除） */  
	@RequestMapping("realDeleteByIds")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	public AjaxJson realDeleteByIds(){
		List<Long> ids = SoMap.getRequestSoMap().getListByComma("ids", long.class); 
		List<String> resList = new ArrayList<>();
		for (Long id : ids) {
			try {
				// 删除 $$ 并广播
				SP.publicService.begin(() -> {
					// 开始删除 
					sysUserService.realDelete(id);
					// 响应 
					resList.add("用户id=" + id + "，彻底删除成功；");
				});
			} catch (Exception e) {
				resList.add("用户id=" + id + "，彻底删除失败：" + e.getMessage());
				e.printStackTrace();
			}
		}
		
		return AjaxJson.getSuccessData(resList);
	}
	
	/** 改 */
	@RequestMapping("update")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	@Transactional(rollbackFor = Exception.class)
	public AjaxJson update(SysUser s){
		// 修改 
		SysUser s2 = sysUserService.update(s);
		
		// $$ 向外广播
		SspServerBrdUtil.userUpdate(s2);

		//  返回 
		return AjaxJson.getSuccess();
	}

	/** 改状态  */
	@RequestMapping("updateStatus")
	@SaCheckPermission({SysUser.PERMISSION_CODE})
	public AjaxJson updateStatus(long id, int status) {
		// 修改状态 
		int line = SP.publicMapper.updateColumnById(SysUser.TABLE_NAME, "status", status, id);
		AjaxError.notLine(line, "状态修改失败");
		
		// $$ 向外广播
		SysUser s2 = sysUserMapper.getById(id);
		SspServerBrdUtil.userUpdate(s2);
		
		// 如果是禁用，就停掉其 Token 有效果性，使其账号的登录状态立即无效 
		if(status == 2) {
			SaSsoUtil.ssoLogout(id);
		}
		return AjaxJson.getSuccess();
	}
	
	/** 改密码 */
	@RequestMapping("updatePassword")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	@Transactional(rollbackFor = Exception.class, propagation=Propagation.REQUIRED)	
	public AjaxJson updatePassword(long id, String password){
		// 改密码 
		sysUserPasswordService.updatePassword(id, password);
		
		// $$ 向外广播
		SspServerBrdUtil.userUpdatePassword(id, password);
		
		return AjaxJson.getSuccess();
	}

	/** 查 - 根据id */  
	@RequestMapping("getById")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	public AjaxJson getById(Long id){
		SysUser s = sysUserMapper.getById(id);
		return AjaxJson.getSuccessData(s);
	}

	/** 查集合 - 根据条件（参数为空时代表忽略指定条件） */  
	@RequestMapping("getList")
	@SaCheckPermission(SysUser.PERMISSION_CODE)
	public AjaxJson getList() { 
		SoMap so = SoMap.getRequestSoMap();
		so.setByNull("isDel", 1);
		List<SysUser> list = sysUserMapper.getList(so.startPage());
		return AjaxJson.getPageData(so.getDataCount(), list);
	}
	
}
