package com.wechat.controller;

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

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.wechat.common.Constants;
import com.wechat.common.utils.Md5Utils;
import com.wechat.common.utils.StringsUtils;
import com.wechat.global.base.BaseController;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.MdeEducationExperience;
import com.wechat.model.dbEntity.MdeHotelCompany;
import com.wechat.model.dbEntity.MdePositionAnotherName;
import com.wechat.model.dbEntity.MdeUser;
import com.wechat.model.dto.AuzUserInfoDto;
import com.wechat.model.requestDto.ExperienceResp;
import com.wechat.model.requestDto.RegisterResp;
import com.wechat.model.responseDto.ResultEntity;
import com.wechat.service.AuthorizedService;
import com.wechat.service.CommonService;
import com.wechat.service.MdeHotelCompanyService;
import com.wechat.service.MdeUserService;
import com.wechat.service.PersonCeneterService;
import com.wechat.service.RegisterService;
import com.wechat.service.WeiXinService;

@Controller
@RequestMapping("register")
public class RegisterController extends BaseController {
	@Value("#{configProperties['upload.base.path']}")
	private String basePackagePath;
	@Value("#{configProperties['upload.path.image']}")
	private String baseImagePackagePath;
	@Value("#{configProperties['compress.image.size']}")
	private int compressImageSize;
	
	@Value("#{configProperties['upload.path.image.temporary']}")
	private String imageTemporary;
	
	//在职证明 营业执照
	@Value("#{configProperties['upload.path.image.onjob']}")
	private String imageOnjob;

	@Value("#{configProperties['url.base']}")
	private String urlBase;
	
	@Autowired
	private RegisterService registerService;

	@Autowired
	private MdeHotelCompanyService mdeHotelCompanyService;
	
	@Autowired
	private PersonCeneterService personCenterService;

	@Autowired
	CommonService commonService;
	
	@Resource
	private AuthorizedService authorizedService;

	@Resource
	private MdeUserService mdeUserService;

	/**
	 * 注册页面初始化 获取酒店品牌 区分国际
	 * 
	 * @return
	 */
	@RequestMapping(value = "")
	@ResponseBody
	public ResultEntity<Map<String, Object>> initRegisterPage(HttpServletRequest req) {
		// 获取酒店品牌，区分国际国内
		String lang = commonService.getLanguage(req);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("1", registerService.getHotelBrandList("1", lang));
		map.put("2", registerService.getHotelBrandList("2", lang));
		return new ResultEntity<Map<String, Object>>(InfoMsg.SUCCESS_REQUEST, map);
	}


	/**
	 * 用户注册
	 * @param request
	 * @throws Exception
	 * @author jadyn.wu
	 */
	@RequestMapping(value = "userInfoSubmit", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<String> userInfoSubmit(@RequestBody RegisterResp jo, HttpServletRequest request, HttpServletResponse resp) throws Exception {
		MdeUser userInfo = new MdeUser();
		
		// 身份标识[0-个人；1-企业]
		String identityFlag = jo.getIdentityFlag();
		userInfo.setIdentityFlag(identityFlag);
		// 国家电话区号（列 +86）
		String phoneCode = jo.getPhoneCode();
		// 登录名[手机号-个人/邮箱-企业]
		String userName = StringsUtils.trim(jo.getUserName());
		// 密码
		String password = StringsUtils.trim(jo.getPassword());
		// 用户姓名/企业名称
		String name = StringsUtils.trim(jo.getName());
		// 外文名称
		String foreignName = StringsUtils.trim(jo.getForeignName());
		// 短信验证码
		String phoneCheckCode = StringsUtils.trim(jo.getPhoneCheckCode());
		//推广渠道来源
		String inviter = jo.getInviter();
		if(!StringsUtils.isEmpty(inviter))
		{
			//拼接 用户id短码+活动id
			inviter = inviter.split(Constants.UNDER_LINE)[0]+Constants.UNDER_LINE+commonService.getActId();
		}
		
		ResultEntity<String> entity = new ResultEntity<String>();

		// 共通内容验证
		if (StringUtils.isEmpty(jo.getHeadPortrait()) || StringUtils.isEmpty(userName) || StringUtils.isEmpty(password) || StringUtils.isEmpty(phoneCheckCode)
				|| StringUtils.isEmpty(name) || StringUtils.isEmpty(identityFlag)) {
			log.error("[出现空数据]HeadPortrait:"+jo.getHeadPortrait()+"--userName:"+userName+"--password:"+password+"--phoneCheckCode:"+phoneCheckCode+"--name:"+name+"--identityFlag:"+identityFlag);
			return new ResultEntity<String>(InfoMsg.ERROR_INCOMPLETE_INFORMATION);
		}else {
			//用户名初始值
			userInfo.setUserName(userName);
			// 针对国外手机的个人用户
			if ("0".equals(identityFlag)) {
				String[] phoneCodeSplit = phoneCode.split("-");
				if (phoneCodeSplit == null || phoneCodeSplit.length != 3) {
					return new ResultEntity<>(InfoMsg.ERROR_PHONECODE_ERROR);
				}
				String phoneCodeStr = phoneCodeSplit[0]; // 国际手机区号码
				// 设值
				userInfo.setPhoneCode(phoneCodeStr); // 国际手机区号码
				if (!phoneCodeStr.equals("86")) {
					userInfo.setUserName("+" + phoneCodeStr + userName); // 如+86123456 （国际）
				}
				
				// 个人注册验证短信
				if (!commonService.validateCode(phoneCheckCode, userInfo.getUserName())) {
					return new ResultEntity<String>(InfoMsg.ERROR_VERIFICATIONCODE);
				}
			} else {
				// 企业注册验证短信
				if (!commonService.validateCode(phoneCheckCode, jo.getEntPhone())) {
					return new ResultEntity<String>(InfoMsg.ERROR_VERIFICATIONCODE);
				}
			}
			
			// 验证是否注册过
			MdeUser mdeUser = mdeUserService.checkUserNameIsRegester(userInfo.getUserName());
			if (mdeUser != null)
			{
				if ("0".equals(identityFlag)) {
					return new ResultEntity<>(InfoMsg.ERROR_PHONE_IS_EXSIT);
				} else {
				return new ResultEntity<>(InfoMsg.ERROR_EMAIL_IS_EXSIT);}
			}

			//密码进行二次加密后存储
			userInfo.setPassword(Md5Utils.EncoderPassword(password));
			userInfo.setName(name);
			userInfo.setForeignName(StringsUtils.isEmpty(foreignName) ? "" : foreignName);
			
			//记录推广渠道来源
			userInfo.setInviter(StringsUtils.isEmpty(inviter) ? "" : inviter);
			
			//微信端静默登陆的情况下
			if(!StringsUtils.isEmpty(jo.getCode()))
			{
				//登录来源0.pc 1.移动端
				//获取用户微信信息
				AuzUserInfoDto auzUserInfoDto = authorizedService.getUserInfoDetail(jo.getCode(), "1");
				userInfo.setUnionId(auzUserInfoDto.getUnionid());
				userInfo.setOpenId(auzUserInfoDto.getOpenid());
			}
			
			//第三方登陆的情况下
			if (StringsUtils.isNotEmpty(jo.getType())) {
				userInfo = registerService.theThirdRegister(jo, userInfo);
			}
			if ("0".equals(identityFlag)) {
				//个人注册
				entity = registerService.personalRegister(jo, userInfo, resp, request);
			} else {
				//企业注册
				entity = registerService.companyRegister(jo, userInfo, resp, request);	
			}
			
			//记录登陆历史
			commonService.addLoginHis(request,userInfo.getUserCode());
			
			return entity;
		}
		
	}

	
	/**
	 * 工作简历及教育经历提交
	 * 
	 * @param mdeWorkExperiences
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "experienceSubmit", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<String> experienceSubmit(@RequestBody ExperienceResp resp, HttpServletRequest req) throws Exception {
		String lang = commonService.getLanguage(req);
		String userCode = commonService.getUserCode(req);
		
		//工作经验入参验证
		if (!registerService.validated(resp.getMdeWorkExperienceList())) {
			return new ResultEntity<>(InfoMsg.ERROR_INCOMPLETE_INFORMATION);
		}else {
			//工作经验保存
			if (!registerService.expericnceSubmit(resp.getMdeWorkExperienceList(),userCode, req).getCode().equals("0")) {
				return new ResultEntity<>(InfoMsg.ERROR_INSERT_ERROR);
			}
		}
		
		//教育履历修
		MdeEducationExperience edu = resp.getEducationExperience();
		if(edu != null)
		{
			if(edu.getEducation() == null || StringsUtils.isEmpty(edu.getSchName()) || StringsUtils.isEmpty(edu.getSpeciality())|| edu.getEnterDate() == null)
			{
				return new ResultEntity<>(InfoMsg.ERROR_INCOMPLETE_INFORMATION);
			}
			edu.setUserCode(userCode);
			if (personCenterService.modefyEducationExperience(edu,lang) != 1) {
				return new ResultEntity<>(InfoMsg.ERROR_INSERT_ERROR);
			}
		}

		return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
	}
	

	/**
	 * 企业执照上传
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "upload", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<String> upload(HttpServletRequest request) throws Exception {
		MultipartFile picture = ((MultipartHttpServletRequest) request).getFile("picture");
		if (picture.isEmpty()) {
			return new ResultEntity<>(InfoMsg.ERROR_NULL_PARAM);
		}
		return registerService.upload(picture,imageOnjob);
	}

	/**
	 * 在职证明上传
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "uploadOnJobImage", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<String> uploadOnJobImage(HttpServletRequest request) throws Exception {
		MultipartFile onJobImage = ((MultipartHttpServletRequest) request).getFile("onJobImage");
		if (onJobImage.isEmpty()) {
			return new ResultEntity<>(InfoMsg.ERROR_NULL_PARAM);
		}
		return registerService.upload(onJobImage,imageOnjob);
	}
	
	/**
	 * 在职证明\营业执照上传 手机
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "uploadOnJobImageWx", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<String> uploadOnJobImage(@RequestParam String pictureId) throws Exception {
		return commonService.uploadByWx(pictureId,imageOnjob);
	}
	

	/**
	 * 获取所有职位
	 * 
	 * @return
	 */
	@RequestMapping(value = "getAllPositionAnotherName")
	@ResponseBody
	public ResultEntity<List<MdePositionAnotherName>> getAllPositionAnotherName() {

		return registerService.getAllPositionAnotherName();
	}

	/**
	 * 根据语言获取所有酒店
	 * 
	 * @return
	 */
	@RequestMapping(value = "getAllHotelCompany")
	@ResponseBody
	public ResultEntity<List<MdeHotelCompany>> getAllHotelCompany(HttpServletRequest req) {
		String lang = commonService.getLanguage(req);
		Map<String, String> map = new HashMap<String, String>();
		map.put("lang", lang);
		List<MdeHotelCompany> list = mdeHotelCompanyService.getAllHotelCompanyByLang(map);
		return new ResultEntity<List<MdeHotelCompany>>(InfoMsg.SUCCESS_REQUEST, list);
	}

	
	/**
	 * 头像上传-手机
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "uploadHeadPortrait", method = RequestMethod.POST)
	@ResponseBody
	public ResultEntity<String> uploadHeadPortrait(@RequestParam String pictureId) throws Exception {
		return commonService.uploadByWx(pictureId,imageTemporary);
	}
	

}
