package cn.api.atv.app;

import java.util.ArrayList;
import java.util.List;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.alibaba.fastjson2.JSONObject;
import cn.facade.abs.IService;
import cn.common.annotation.Log;
import cn.common.enums.BizOpType;
import cn.logger.AsyncLoggingFactory;
import cn.common.page.response.Result;
import cn.component.RedisKit;
import cn.constant.CommonConst;
import cn.pojo.atv.system.SysLoginModel;
import cn.pojo.entity.TSysUser;
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.LogKit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/app/sys")
public class LoginCtrl extends IService
{
	@Resource
	protected IAtvAppService appService;
	@Resource
	private JwtTokenService tokenService;
	@Resource
	private RedisKit redisUtil;

	/**登录*/
	@RequestMapping(value = "/mLogin", method = RequestMethod.POST)
	@Log(title = "APP-登录接口-mLogin", businessType = BizOpType.OTHER)
	public Result<?> mLogin(@RequestBody SysLoginModel sysLoginModel)
	{
		String username = sysLoginModel.getUsername();
		String password = sysLoginModel.getPassword();
		if(IsKit.isNullOrEmpty(username) || IsKit.isNullOrEmpty(password)) {
			return Result.warnMsg("用户账号或密码不能为空！");
		}
      	//1. 校验用户是否有效
		Result<?> result = appService.checkUserIsEffective(username);
		if(result.getCode() != 200) {
			return result;
		}
		//2. 校验用户名或密码是否正确
		TSysUser entity = (TSysUser) result.getData();
		String sysPassword = entity.getPassword();
		Boolean pTest = EncryKit.matchesPassword(password,sysPassword);
		if(!pTest) {
			return Result.warnMsg("用户账号或密码不对！");
		}
		//3.校验用户名是否是维护人员或工人报修
		boolean isWorker = appService.hasPermission(username, "/worker");
		boolean isWorkerRepair = appService.hasPermission(username, "/workerRepair");
		if (!isWorker && !isWorkerRepair) {
			return Result.warnMsg("您不是APP用户！");
		}
		List<String> menu = new ArrayList<>();
		if (isWorker) {//多角色 优先
			menu.add("/worker"); //上报故障
		}
		else if (isWorkerRepair) {
			menu.add("/workerRepair");//故障处理
		}
		//实验用  menu.add("/workerRepair");
		int orgCode = entity.getDeptId();
		if(IsKit.isNullOrEmpty(orgCode)) {
			return Result.warnMsg("用户暂未归属部门,不可登录!");
		}
		JSONObject obj = new JSONObject();
		//用户登录信息
		obj.put("userInfo", entity);

		//生成token
		String token = tokenService.appSign(username, sysPassword);
		// 设置超时时间
		redisUtil.set(CommonConst.PREFIX_USER_TOKEN + token, token);
		redisUtil.expire(CommonConst.PREFIX_USER_TOKEN + token, CommonConst.EXPIRE_TIME*2 / 1000);
		// 添加维护人员或工人报修权限
		obj.put("menu", menu);
		//token 信息
		obj.put("token", token);

		AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGIN_SUCCESS, "用户登录成功[移动端]！"));
		return Result.ok(obj);
	}
	/**退出登录*/
	@RequestMapping(value = "/logout")
	@Log(title = "APP-退出登录-logout", businessType = BizOpType.OTHER)
	public Result<?> logout(HttpServletRequest request)
	{
		//用户退出逻辑
		String token = request.getHeader(CommonConst.X_ACCESS_TOKEN);
		if(IsKit.isEmpty(token)) {
			return Result.warnMsg("退出登录失败！");
		}
		String username = tokenService.getAppUserName(token);
		TSysUser sysUser = sysBaseService.getUserByName(username);
		if(IsKit.isNotNull(sysUser)) 
		{
			AsyncManager.me().execute(AsyncLoggingFactory.insertLoginInfo(username, CommonConst.LOGOUT,"退出登录成功[移动端]！"));
			LogKit.info(" 用户名:  "+sysUser.getNickName()+",退出成功(App用户)！ ");
			//清空用户登录Token缓存
			redisUtil.del(CommonConst.PREFIX_USER_TOKEN + token);
			//清空用户的缓存信息（包括部门信息），例如sys:cache:user::<username>
			redisUtil.del(String.format("%s::%s", CommonConst.SYS_USERS_CACHE, sysUser.getUserName()));
			return Result.okMsg("退出登录成功！");
		}else {
			return Result.warnMsg("Token无效!");
		}
	}
	/**	移动端保存设备信息 */
	@RequestMapping(value = "/user/saveClientId", method = RequestMethod.GET)
	public Result<?> saveClientId(HttpServletRequest request, @RequestParam("clientId") String clientId) 
	{
		System.out.println("clientId-1:"+clientId);
		TSysUser entity;
		try {
			String username = tokenService.getAppUserName(request);
			entity = sysBaseService.getUserByName(username);
			if (IsKit.isNull(entity)) {
				return Result.warnMsg("未找到对应用户!");
			} else {
				entity.setClientId(clientId);
				daoService.update(entity);
			}
		} catch (Exception e) {
			LogKit.info(e.getMessage());
			return Result.warnMsg("操作失败!");
		}
		return Result.ok(entity);
	}
	/**
	 * 首页用户重置密码
	 */
	@RequestMapping(value = "/user/updatePassword", method = RequestMethod.PUT)
	@Log(title = "APP-首页用户重置密码-mLogin", businessType = BizOpType.OTHER)
	public Result<?> changPassword(@RequestBody JSONObject json) {
		return appService.changPassword(json);
	}
}
