package xiaoqu.home.open.controller;

import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
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.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import xiaoqu.home.open.constant.Constants;
import xiaoqu.home.open.constant.Errors;
import xiaoqu.home.open.controller.input.LoginInput;
import xiaoqu.home.open.controller.output.LoginOutput;
import xiaoqu.home.open.controller.output.user.CompanyInfo;
import xiaoqu.home.open.controller.output.user.UserInfo;
import xiaoqu.home.open.model.db1.User;
import xiaoqu.home.open.model.db2.Authority;
import xiaoqu.home.open.model.db2.LoginLog;
import xiaoqu.home.open.publicBean.BaseOutput;
import xiaoqu.home.open.service.RedisService4;
import xiaoqu.home.open.service.RedisService5;
import xiaoqu.home.open.service.db1.UserService;
import xiaoqu.home.open.service.db2.AuthorityService;
import xiaoqu.home.open.service.db2.LoginLogService;
import xiaoqu.home.open.utils.IpUtils;
import xiaoqu.home.open.utils.ResultResponseBeanUtil;
import xiaoqu.home.open.utils.UserUtils;
import xiaoqu.home.open.utils.WrapperUtils;

/**********************
 * 客户登录接口
 *
 * @author wh
 */
@Controller
@Api(value = "登录",description = "登录")
public class LoginController {

	@Autowired
	private UserService userService;
	@Autowired
	private RedisService5 redisService5;
	@Autowired
	private RedisService4 redisService4;
	@Autowired
	private LoginLogService loginLogService;
	@Autowired
	private AuthorityService authorityService;
	
	/**************
	 * 登录服务
	 *
	 * @param input
	 * @return login
	 */
	@ApiOperation(value = "登录接口")
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public BaseOutput<LoginOutput> login(HttpServletRequest request, @Valid @RequestBody LoginInput input) {
		String number = input.getNumber();
		String code = input.getRandCode();
		// 获取客户基本信息
		String redisInCode = redisService4.get(Constants.verificationCode + number);
		if (redisInCode != null) {
			if (code.equals(redisInCode)) {
				QueryWrapper<User> queryWrapper = WrapperUtils.getWrapper(false);
				queryWrapper.eq("mobile", number);
				queryWrapper.last("limit 1");
				User sysUser = userService.getOne(queryWrapper);
				if (sysUser != null) {
					sysUser.setLastLoginTime(new Date());
					userService.updateById(sysUser);
					// 单点登录,先判断内存里是否有登录痕迹
					UserUtils.deleteUUID(number);
					// 获取uuid 保存客户的基本信息 有效期30天
					String sysUseruuid = UUID.randomUUID().toString().replaceAll("-", "");
					UserUtils.addUUID(sysUseruuid, number, sysUser);
					LoginOutput loginOutput = new LoginOutput();
					UserInfo userInfo = new UserInfo();
					userInfo.setUserId(sysUser.getId() + "");
					userInfo.setUuid(sysUseruuid);
					userInfo.setUserName(sysUser.getName());
					CompanyInfo companyInfo = new CompanyInfo();
					companyInfo.setEnterpriseType(sysUser.getEnterpriseType().toString());
					if(sysUser.getEnterpriseType()==1){
						String agentName = redisService5.get("name:Agent:" + sysUser.getAgentId());
						companyInfo.setCompanyName(agentName);
						companyInfo.setCompanyId(sysUser.getAgentId().toString());
					}else{
						String propertyName = redisService5.get("name:Properyt:" + sysUser.getPropertyId());
						companyInfo.setCompanyId(sysUser.getPropertyId().toString());
						companyInfo.setCompanyName(propertyName);
					}
					loginOutput.setUserInfo(userInfo);
					loginOutput.setCompanyInfo(companyInfo);
					Authority authority = authorityService.getById(sysUser.getPropertyAuthorityId());
					if(authority==null){
						return ResultResponseBeanUtil.fail(Errors.NOT_Register, "账号未分配权限，请联系负责人开通");
					}
					LoginLog loginLog = new LoginLog();
					loginLog.setModifyTime(new Date());
					loginLog.setCreateTime(new Date());
					loginLog.setCreateId(sysUser.getId());
					loginLog.setUserId(sysUser.getId());
					loginLog.setAgentId(sysUser.getAgentId());
					loginLog.setPropertyId(sysUser.getPropertyId()!=null?sysUser.getPropertyId():0);
					loginLog.setDistrictId(sysUser.getDistrictId()!=null?sysUser.getDistrictId():0);
					loginLog.setEnterpriseType(sysUser.getEnterpriseType());
					loginLog.setRoleType(sysUser.getRoleType());
					loginLog.setName(sysUser.getName());
					loginLog.setLoginType(0);
					loginLog.setLoginIp(IpUtils.getIpAddr(request) );
					loginLog.setMobile(sysUser.getMobile());
					loginLogService.save(loginLog);
					redisService4.remove(Constants.verificationCode + number);// 删除验证码
					return ResultResponseBeanUtil.success(loginOutput);
				} else {
					return ResultResponseBeanUtil.fail(Errors.NOT_Register, "账号未注册");
				}
			} else {
				return ResultResponseBeanUtil.fail(Errors.VER_CODE_FAIL, "验证码不对，请重新输入");
			}
		} else {
			return ResultResponseBeanUtil.fail(Errors.VER_CODE_FAIL, "验证码已经失效");
		}

	}

	@ApiOperation(value = "退出", notes = "退出")
	@ResponseBody
	@RequestMapping(value = "/logOut", method = RequestMethod.GET)
	public BaseOutput<String> logOut(HttpServletRequest request) {
		User user = UserUtils.getUser(request);
		// 清除掉缓存
		UserUtils.deleteUUID(user.getMobile());
		QueryWrapper<LoginLog> queryWrapper = WrapperUtils.getWrapper(false);
		queryWrapper.eq("user_id",user.getId());
		queryWrapper.eq("login_type",0);
		queryWrapper.orderByDesc("create_time");
		List<LoginLog> list = loginLogService.list(queryWrapper);
		if(!list.isEmpty()){
			LoginLog loginLog = list.get(0);
			loginLog.setModifyTime(new Date());
			loginLog.setLoginType(1);
			loginLogService.updateById(loginLog);
		}
		return ResultResponseBeanUtil.success("退出成功");
	}

}
