package com.storlead.centre.system;

import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.storlead.framework.auth.jwt.JwtUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.constant.DefContants;
import com.storlead.framework.common.util.ConvertUtils;
import com.storlead.framework.redis.RedisService;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.web.assemble.Result;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.pojo.entity.UserForm;
import com.storlead.user.pojo.vo.WeChatPhoneInfo;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.IJobService;
import com.storlead.user.service.IUserRoleService;
import com.storlead.user.service.IUserService;
import com.storlead.wx.util.WechatPhoneUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author scott
 * @since 2018-12-17
 */
@RestController
@RequestMapping("/lingcun")
@Api(tags="5.公共接口")
@Slf4j
public class LoginController {
	@Resource
	private IUserService sysUserService;

//    @Autowired
//    private EhCacheService ehCacheService;

	@Resource
    private IDepartService departService;

	@Resource
	private IUserRoleService userRoleService;

	@Autowired
	private RedisService redisService;


	@Value("${weixin.appid}")
	private String appid;

	@Value("${weixin.secret}")
	private String secret;

	private static final String BASE_CHECK_CODES = "qwertyuiplkjhgfdsazxcvbnmQWERTYUPLKJHGFDSAZXCVBNM1234567890";


	@RequestMapping(value = "/phone-login", method = RequestMethod.GET)
	@ApiOperation(value = "微信授权手机号登录接口", notes = "微信授权手机号登录接口")
	public Result login(String code) {
		// 1.请求微信接口服务，获取accessToken
		cn.hutool.json.JSONObject accessTokenJson = WechatPhoneUtil.getAccessToken(appid, secret);
		String accessToken = accessTokenJson.get("access_token",String.class);
//		code = code.replace("\"", "");
		// 2.请求微信接口服务，获取用户手机号信息
		cn.hutool.json.JSONObject phoneNumberJson = WechatPhoneUtil.getPhoneNumber(code, accessToken);
		WeChatPhoneInfo phoneInfo = phoneNumberJson.get("phone_info", WeChatPhoneInfo.class);
		System.out.println(phoneInfo);
		String phone = phoneInfo.getPurePhoneNumber();
		if (StringUtils.isEmpty(phone)){
			return Result.error("手机号获取失败");
		}
		UserEntity userInfo;
		userInfo = sysUserService.getOne(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getMobile,phone));
		if (Objects.isNull(userInfo)) {
			return Result.error("账号不存在");
		}
		if (!userInfo.getEnabled()) {
			return Result.error("该账号用户暂无登录权限");
		}

		LoginUser loginUser = new LoginUser();
		BeanUtils.copyProperties(userInfo,loginUser);

//		if (Objects.nonNull(userInfo.getJobId())) {
//			JobEntity job = jobService.getById(userInfo.getJobId());
//			if (Objects.nonNull(job)) {
//				loginUser.setJobName(job.getName());
//			}
//		}
//
//		if (Objects.nonNull(userInfo.getDeptId())) {
//			DeptEntity dept = departService.getById(userInfo.getDeptId());
//			if (Objects.nonNull(dept)) {
//				loginUser.setDeptJobDes(dept.getDeptJobDes());
//			}
//		}

		//用户登录信息
		String jwtToken = JwtUtil.createJWT(JSONObject.toJSONString(loginUser),loginUser.getMobile());
		String token = SecureUtil.md5(jwtToken);

		String json = JSONObject.toJSONString(loginUser);
		redisService.setCacheObject(token, json, 60 * 60 * 24L, TimeUnit.SECONDS);

//		Map<String, String> apiMap = new HashMap();
//		redisService.setCacheObject(RedisKeySaltConstant.API_CODE_REDIS + loginUser.getMobile(), apiMap);
		JSONObject obj = new JSONObject();
		obj.put("status",1);
		obj.put("token", token);
		return Result.ok(obj);
	}
//
//	@RequestMapping(value = "/login", method = RequestMethod.POST)
//	@ApiOperation(value = "用户登录接口", notes = "用户登录接口")
//	public Result login(@RequestBody SysLoginModel loginModel){
//		Result result = new Result<JSONObject>();
//		String username = loginModel.getUsername();
//		String password = loginModel.getPassword();
////		//1. 校验用户是否有效
//		UserEntity sysUser = sysUserService.getUserByName(username);
//		result = sysUserService.checkUserIsEffective(sysUser);
//		if(!result.isSuccess()) {
//			return result;
//		}
////		//2. 校验用户名或密码是否正确
//		String syspassword = sysUser.getPassword();
//		BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
//		if (!bCryptPasswordEncoder.matches(password, syspassword)) {
//			result.error500("用户名或密码错误");
//			return result;
//		}
//
//		LoginUser loginUser = new LoginUser();
//		BeanUtils.copyProperties(sysUser,loginUser);
//
//		DeptEntity dept = departService.getById(loginUser.getDeptId());
//		if (Objects.nonNull(dept)) {
//			if (StrUtil.isNotBlank(dept.getRouteCode())) {
//				List<String> codes = Arrays.asList(dept.getRouteCode().split(","));
//				loginUser.setSubCompanyCode(codes.get(1));
//				loginUser.setCompanyCode(codes.get(0));
//			}
//			loginUser.setDeptCode(dept.getRouteCode());
//		}
//
//		UserRoleType userRoleType = userRoleServicel.getUserRole(sysUser);
//		sysUser.setRoleType(userRoleType);
//		loginUser.setRoleType(userRoleType);
//
//		//用户登录信息
//		String jwtToken = JwtUtil.createJWT(JSONObject.toJSONString(loginUser),loginUser.getUserName());
//		String token = SecureUtil.md5(jwtToken);
//
//		String json = JSONObject.toJSONString(loginUser);
//		redisService.setCacheObject(token, json, 60 * 60 * 24L, TimeUnit.SECONDS);
//
//		Map<String, String> apiMap = new HashMap();
//		redisService.setCacheObject(RedisKeySaltConstant.API_CODE_REDIS + loginUser.getUserName(), apiMap);
//
//		JSONObject obj = new JSONObject();
//		obj.put("token", token);
//		return Result.ok(obj);
//	}


//	@RequestMapping(value = "/loginByMobile", method = RequestMethod.POST)
//	@ApiOperation(value = "用户短息登录接口", notes = "用户短息登录接口")
//	public Result<JSONObject> login(@RequestParam("mobile") @ApiParam(value = "手机号")String mobile,@RequestParam("code") @ApiParam(value = "手机验证码")String code){
//		Result<JSONObject> result = new Result<JSONObject>();
//		//1. 校验用户是否有效
//		User sysUser = sysUserService.getUserByMobile(mobile);
//		result = sysUserService.checkUserIsEffective(sysUser);
//		if(!result.isSuccess()) {
//			return result;
//		}
//
//
//		//2. 校验验证码是否正确
//		Result checkCodeReslut = smsService.checkCode(mobile, code);
//		if(!checkCodeReslut.isSuccess()){
//			return checkCodeReslut;
//		}
//		//用户登录信息
//		userInfo(sysUser, result);
//		return result;
//	}


	@ApiOperation("修改密码")
	@PostMapping("/modifyPass")
	public Object updateUserPass(@RequestBody @Validated UserForm param) {
		return sysUserService.updateUserPass(param);
	}


	/**
	 * 退出登录
	 * @param request
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/logout")
	@ApiOperation(value = "用户退出登录接口", notes = "用户退出登录接口")
	public Result<Object> logout(HttpServletRequest request) {
		//用户退出逻辑
		String token = request.getHeader(DefContants.ACCESS_TOKEN);
		if(ConvertUtils.isEmpty(token)) {
			return Result.error("退出登录失败！");
		}
		Boolean del = redisService.deleteObject(token);
		if (del) {
			return Result.ok("退出登录成功！");
		} else {
			Object obj = redisService.getCacheObject(token);
			if (obj == null) {
				return Result.error("退出登录成功！");
			}
			return Result.error("退出登录失败！");
		}
	}


	/**
	 * 用户信息
	 *
	 * @param request
	 * @return
	 */
	@GetMapping("/getUserBaseInfo")
	@ApiOperation(value = "根据token获取用户基本信息", notes = "根据token获取用户基本信息(header中传token)")
	public Result<JSONObject> getUserBaseInfo(HttpServletRequest request) {

		LoginUser loginUser =  LoginUserUtil.getLoginUser();
		// 生成token
		Result<JSONObject> result = new Result<JSONObject>();
		//用户退出逻辑
		String token = request.getHeader(DefContants.ACCESS_TOKEN);
		UserEntity sysUser = sysUserService.getUserByName(loginUser.getUserName());
		// 获取用户部门信息
		JSONObject obj = new JSONObject();
		DeptEntity dept = departService.getById(sysUser.getDeptId());
		obj.put("dept", dept);
		obj.put("userInfo", sysUser);
		result.setResult(obj);
		result.success("登录成功");
		return result;
	}
//
//	/**
//	 * 获取校验码
//	 */
//	@GetMapping(value = "/getCheckCode")
//	public Result<Map<String,String>> getCheckCode(){
//		Result<Map<String,String>> result = new Result<Map<String,String>>();
//		Map<String,String> map = new HashMap<String,String>();
//		try {
//			String code = RandomUtil.randomString(BASE_CHECK_CODES,4);
//			String key = MD5Util.MD5Encode(code+System.currentTimeMillis(), "utf-8");
//			ehCacheService.put(CommonConstant.CAPCHA_CACHE,key, code, 60);
//			map.put("key", key);
//			map.put("code",code);
//			result.setResult(map);
//			result.setSuccess(true);
//		} catch (Exception e) {
//			e.printStackTrace();
//			result.setSuccess(false);
//		}
//		return result;
//	}

	/**
	 * 获取手机验证码
	 * @return
	 */
//	@GetMapping(value = "/getPhoneCode")
//	@ApiOperation(value = "获取手机验证码", notes = "获取手机验证码")
//	public Result getPhoneCode(@RequestParam("mobile") @ApiParam(value = "手机号") String mobile){
//		try {
//			int code = RandomCodeUtil.RandomCheckCode();
//			return smsService.sendSms(mobile,code+"", SmsTypeEnum.Login_SMS.getCode(),null);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return Result.error("发送手机验证码失败");
//	}
}
