package com.platform.modules.app.controller;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.platform.common.annotation.SysLog;
import com.platform.common.utils.R;
import com.platform.common.validator.ValidatorUtils;
import com.platform.modules.app.form.LoginForm;
import com.platform.modules.app.service.UserService;
import com.platform.modules.app.utils.JwtUtils;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * APP登录授权
 */
@RestController
@RequestMapping("/app")
@Api(value = "APP登录接口", tags = "APP登录接口")
public class AppLoginController {
	@Autowired
	private UserService userService;
	@Autowired
	private JwtUtils jwtUtils;
	@Autowired
	private SysUserService sysUserService;

	@Value("${materia.basePath}")
	private String DOMAIN;
	/**
	 * 登录
	 */
	@SysLog("系统app用户登录")
	@PostMapping("login")
	@ApiOperation("登录")
	public R login(@RequestBody LoginForm form) {
		// 表单校验
		ValidatorUtils.validateEntity(form);

		// 用户登录
		// long userId = userService.login(form);
		SysUserEntity user = null;
		
		String regex = "^1\\d{10}$";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(form.getMobile());
		if(form.getMobile().length() == 11 && m.matches()){
			user = sysUserService.queryByMobile(form.getMobile());
		}else{
			user = sysUserService.queryByUserName(form.getMobile());
		}
		
		if (user == null || user.getUserId() == null) {
			return R.error("账号不存在");
		}

		// 账号不存在、密码错误
		if (!user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
			return R.error("账号或密码不正确");
		}

		// 生成token
		String token = jwtUtils.generateToken(user.getUserId() + "#" + user.getTenantId());

		Map<String, Object> map = new HashMap<>();
		map.put("token", token);
		map.put("expire", jwtUtils.getExpire());
		map.put("userId", user.getUserId());
		map.put("username", user.getUsername());
		map.put("userImg", DOMAIN + user.getUserImg());
		map.put("realname", user.getRealname());
		map.put("mobile", user.getMobile());
		map.put("email", user.getEmail());

		return R.ok(map);
	}

}
