package org.linlinjava.jz.hm.web;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.linlinjava.jz.core.util.JsonUtil;
import org.linlinjava.jz.db.dao.HmAppUserloginLogMapper;
import org.linlinjava.jz.db.domain.HmAppUser;
import org.linlinjava.jz.db.domain.HmAppUserloginLog;
import org.linlinjava.jz.db.domain.HmEmployRelation;
import org.linlinjava.jz.hm.contants.AppUserContants;
import org.linlinjava.jz.hm.dto.TaobaoQueryDto;
import org.linlinjava.jz.hm.service.HmAppUserSerevice;
import org.linlinjava.jz.hm.service.HmEmployRelationService;
import org.linlinjava.jz.hm.util.HmResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

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

@Api(value = "小程序登录 个人信息获取", description = "小程序登录 个人信息获取")
@RestController
@RequestMapping("auth")
public class AuthController {

	@Autowired
	HmAppUserSerevice hmAppUserSerevice;

	@Autowired
	HmEmployRelationService hmEmployRelationService;

	@Autowired
	HmAppUserloginLogMapper hmAppUserloginLogMapper;



	@ApiOperation(value = "登录login", notes = "登录  usertype：1雇主、2保姆、3管家")
	@GetMapping(value = "login")
	public Object login(TaobaoQueryDto taobaoDto, String phone, HttpServletRequest request) {
		if (StringUtils.isBlank(phone)) {
			return HmResponseUtil.fail("手机号不能为空");
		}

		HmAppUser hu = hmAppUserSerevice.getUserInfo(phone);
		if (null == hu) {
			return HmResponseUtil.fail("账号有误");
		}

		hmAppUserSerevice.updateLastLoginTime(hu.getId(), taobaoDto.getSource_ip());
		insertUserLoginLog(taobaoDto, hu, "登录");

		Map<String, Object> data = new HashMap<String, Object>();
		data.put("userInfo", hu);

		// 返回关联的三者关系数据
		if(!AppUserContants.USER_TYPE_3.equals(hu.getUserType())) {//只有 雇主 保姆才返回关系
			List<HmEmployRelation> relationList = hmEmployRelationService.getRelation(hu.getId());
			data.put("relationList", relationList);
		}

		return HmResponseUtil.ok(data);
	}

	public void insertUserLoginLog(TaobaoQueryDto taobaoDto, HmAppUser sysUser,String comments) {
		HmAppUserloginLog record = new HmAppUserloginLog();
		record.setComments(comments + JsonUtil.getJson(taobaoDto));// taobao网关的参数
		record.setIpAddress(taobaoDto.getSource_ip());
		record.setUserId(sysUser.getId());

		hmAppUserloginLogMapper.insertSelective(record);
	}
}
