package cn.service.atv.impl;

import java.util.Arrays;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson2.JSONObject;
import cn.facade.abs.IService;
import cn.common.enums.ResultCode;
import cn.logger.AsyncLoggingFactory;
import cn.common.page.response.Result;
import cn.constant.CommonConst;
import cn.orm.sqltoy.model.Page;
import cn.orm.sqltoy.plus.Wrappers;
import cn.orm.sqltoy.plus.query.QueryWrapper;
import cn.orm.sqltoy.plus.update.UpdateWrapper;
import cn.pojo.atv.AtvBoardCardFault;
import cn.pojo.entity.TSysUser;
import cn.pojo.entity.TSysRolePerm;
import cn.schedule.core.AsyncManager;
import cn.service.atv.IAtvAppService;
import cn.service.token.JwtTokenService;
import cn.util.codec.EncryKit;
import cn.util.core.IsKit;
import cn.util.core.ServletKit;
import cn.util.string.StringKit;

@Service
public class AtvAppServiceImpl extends IService implements IAtvAppService
{
	@Autowired
	private JwtTokenService tokenService;

	@Override
	public Result<?> changPassword(JSONObject json)
	{
		//此字段是否必须由app传送过来
		String username = json.getString("username");
		//与上边等同
		TSysUser sysUser = this.getCurrentUser();
		username = sysUser.getUserName();
				
		String oldpassword = json.getString("oldpassword");
		String newpassword = json.getString("password");
		String confirmpassword = json.getString("confirmpassword");
		
		QueryWrapper<TSysUser> queryWrapper = Wrappers.wrapper(TSysUser.class)
				.eq("userName", username);
		TSysUser entity = daoService.findOne(queryWrapper);
		if(IsKit.isNull(entity)) {
			return Result.warnMsg("用户不存在！");
		}
		Boolean pTest = EncryKit.matchesPassword(oldpassword,entity.getPassword());
		if(!pTest) {
			return Result.warnMsg("旧密码输入错误!");
		}
		if (IsKit.isEmpty(newpassword)) {
			return Result.warnMsg("新密码不允许为空!");
		}
		if (!newpassword.equals(confirmpassword)) {
			return Result.warnMsg("两次输入密码不一致!");
		}
		String password = EncryKit.encryptPassword(newpassword);
		UpdateWrapper<TSysUser> updateWrapper = Wrappers.updateWrapper(TSysUser.class)
	                .set("password", password)
	                .eq("userName", username);
	    return daoService.update(updateWrapper)>0?
	    		Result.ok("密码重置成功!"): Result.warnMsg("密码重置失败!");
	}

	/**查询我的上报故障列表 待验证*/
	@Override
	public Result<?> queryMyFaultList(Map<String,Object> pageMap)
	{  
		String username = tokenService.getAppUserName(ServletKit.getRequest());
		//获取当前登录者
		QueryWrapper<AtvBoardCardFault> queryWrapper = Wrappers.wrapper(AtvBoardCardFault.class)
				.eq("submitUserId", username)
				.orderByDesc("createTime");
		Page<?> page = daoService.getPage(pageMap);
		Page<?> pageResult = daoService.findPage(queryWrapper,page);
		if(IsKit.isNullOrEmpty(pageResult)) {
			return Result.warnMsg(ResultCode.SQL_RUN.getMsg());
		}
		//List<?> entityList = pageResult.getRows();
		return Result.ok_ePlusList(pageResult.getRecordCount(),pageResult.getRows());
	}


	/**根据用户账号和请求地址判断是否有此权限(原根据用户账号查询菜单权限)*/
	@Override
	public boolean hasPermission(String username, String url) 
	{
		QueryWrapper<TSysUser> queryWrapper = Wrappers.wrapper(TSysUser.class)
				.select("roleIds")
				.ne("delFlag",CommonConst.CHAR_NUM_1)
				.ne("status",CommonConst.CHAR_NUM_1)
				.eq("userName",username);
		TSysUser entity = daoService.findOne(queryWrapper);
		if(IsKit.isNull(entity)){
			return false;
		}
		//in库表字符串含有:[]，即字段值类似：[1,2]
		String roleIds = StringKit.removeBracket(entity.getRoleIds()); 
		QueryWrapper<TSysRolePerm> wrapper = Wrappers.wrapper(TSysRolePerm.class)
				.select("component")
				.eq("component",url)
				.in("roleId",Arrays.asList(roleIds.split(",")));
		TSysRolePerm entityperm = daoService.findOne(wrapper);
		if(IsKit.isNull(entityperm)){
			return false;
		}
		return true;
	}
	/**校验用户是否有效*/
	@Override
	public Result<?> checkUserIsEffective(String username)
	{
		QueryWrapper<TSysUser> wrapper = Wrappers.wrapper(TSysUser.class)
				.eq("userName",username);
		TSysUser entity = daoService.findOne(wrapper);

		//情况1：根据用户信息查询，该用户不存在
		if (IsKit.isNull(entity)) {
			AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGIN_FAIL, "用户登录失败，用户不存在！"));
			return Result.warnMsg("该用户不存在，请注册!");
		}
		//情况2：根据用户信息查询，该用户已注销
		if (CommonConst.CHAR_NUM_1.equals(entity.getDelFlag())) {
			AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGIN_FAIL, "用户登录失败，用户已注销！"));
			return Result.warnMsg("该用户已注销!");
		}
		//情况3：根据用户信息查询，该用户已冻结
		if (CommonConst.CHAR_NUM_1.equals(entity.getStatus())) {
			AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGIN_FAIL, "用户登录失败，用户已冻结！"));
			return Result.warnMsg("该用户已冻结!");
		}
		return Result.ok(entity); 
	}

	@Override
	public TSysUser getCurrentUser()
	{ 
		String username = tokenService.getAppUserName(ServletKit.getRequest());
		return sysBaseService.getUserByName(username);
	}
}
