package com.wechat.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.wechat.common.utils.StringsUtils;
import com.wechat.dao.MdeJobAdvertisedDao;
import com.wechat.dao.MdeJobInvitationRelDao;
import com.wechat.global.CustomException;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.MdeJobAdvertised;
import com.wechat.model.dbEntity.MdeJobInvitationRel;
import com.wechat.model.dbEntity.MdeUser;
import com.wechat.model.requestDto.PositionInvitedReq;
import com.wechat.model.requestDto.TMsg3ParamsDto;
import com.wechat.model.requestDto.TMsgSendBaseReq;
import com.wechat.model.requestDto.TMsgValueReq;
import com.wechat.model.responseDto.ResultEntity;

@Service
public class MdeJobInvitationRelService {

	@Autowired
	private MdeJobInvitationRelDao mdeJobInvitationRelDao;

	@Autowired
	private CommonService commonService;

	@Autowired
	private MdeJobAdvertisedDao mdeJobAdvertisedDao;

	@Autowired
	private VerificationCodeService verificationCodeService;

	@Autowired
	private MdeUserService mdeUserService;

	@Value("#{configProperties['position_template_id']}")
	private String positionTemplateId; // 职位邀请 推送模板Id
	
	@Value("#{configProperties['position_url']}")
	private String positionUrl; // 模板跳转地址
	
	@Autowired
	private TemplateMsgService templateMsgService;
	
	/**
	 * 邀请投递简历
	 * 
	 * @param mdeJobInvitationRel
	 * @return
	 */
	@Transactional
	public ResultEntity<String> invitationDeliver(HttpServletRequest req, MdeJobInvitationRel mdeJobInvitationRel) {
		// 邀请投递信息入库
		try {
			MdeUser mdeUser = mdeUserService.getFullInfo(mdeJobInvitationRel.getUserCode()); // 被邀请用户
			String publisher = commonService.getUserCode(req);
			MdeUser publisherCompany = mdeUserService.getFullInfo(publisher); // 企业信息
			mdeJobInvitationRel.setPublisher(publisher);
			mdeJobInvitationRel.setStatus("0"); // 新邀请
			MdeJobAdvertised mdeJob = mdeJobAdvertisedDao.findByPublisherAndJobId(mdeJobInvitationRel);
			// 职位不存在
			if (mdeJob == null) {
				return new ResultEntity<>(InfoMsg.ERROR_NOPOSITION_ERROR);
			}
			mdeJobInvitationRelDao.insert(mdeJobInvitationRel);
			String openId = mdeUser.getOpenId();
			// 微信通知 推送
			if (StringsUtils.isNotEmpty(openId)) {
				TMsgSendBaseReq positionInvitedReq = organizationParam(mdeUser, publisherCompany, mdeJobInvitationRel);
				String errorCode = templateMsgService.sendTMsg(positionInvitedReq); // 微信消息推送
				if (!"0".equals(errorCode)) {
					//发送失败再次尝试
					templateMsgService.sendTMsg(positionInvitedReq); // 微信消息推送
				} 
			} else {
				String userName = mdeUser.getUserName();
				// 判断是否是大陆手机号 (手机号 如+8612345)
				if (mdeUser.getPhoneCode().equals("86")) {
					// 邀请成功 发送短信 （大陆）
					boolean flag = StringsUtils.isEmpty(mdeUser.getForeignName());
					verificationCodeService.sendInvitation(userName, mdeUser.getName(),flag?mdeUser.getName():mdeUser.getForeignName());
				} else {
					// 国际
					userName = userName.substring(mdeUser.getPhoneCode().length() + 1, userName.length()); // 截取手机号
					// 手机号 开头为0 去掉
					if (userName.startsWith("0")) {
						userName = userName.substring(1, userName.length());
					}
					verificationCodeService.sendInternationalInvitation(mdeUser.getPhoneCode(), userName, mdeUser.getName());
				}
			}
		} catch (Exception e) {
			throw new CustomException(InfoMsg.ERROR_INVITATION_ERROR);
		}
		// 获取酒店邀请信息
		ArrayList<String> invationInfo = commonService.getRecievedHotelInvationInfo(mdeJobInvitationRel.getUserCode());
		invationInfo.add(mdeJobInvitationRel.getJobId().toString());
		// 更新用户被邀请投递简历
		commonService.updateUserInvatedCvCount(mdeJobInvitationRel.getUserCode(), invationInfo);
		return new ResultEntity<>(InfoMsg.SUCCESS_REQUEST);
	}

	/**
	 * 企业点击投递简历 获取企业正在招聘的职位
	 * 
	 * @param req
	 * @return
	 */
	public List<MdeJobAdvertised> clickInvitation(HttpServletRequest req) {
		String publisher = commonService.getUserCode(req);
		// 获取已经投递过该职位的用户code
		List<MdeJobAdvertised> alreadyAdvertisedByJobId = mdeJobAdvertisedDao.getAlreadyAdvertisedByJobId(publisher);
		List<MdeJobAdvertised> mdeJobAdvertisedList = mdeJobAdvertisedDao.getByPublisher(publisher);
		for (MdeJobAdvertised mdeJobAdvertised : mdeJobAdvertisedList) {
			for (MdeJobAdvertised job : alreadyAdvertisedByJobId) {
				if (job.getJobId() == mdeJobAdvertised.getJobId()) {
					List<MdeJobInvitationRel> userCodeList = mdeJobAdvertised.getUserCodeList();
					if (CollectionUtils.isNotEmpty(job.getUserCodeList())) {
						userCodeList.addAll(job.getUserCodeList());
					}
				}
			}

		}
		return mdeJobAdvertisedList;
	}

	/**
	 * 组织 微信推送信息
	 * @return
	 */
	private TMsgSendBaseReq organizationParam(MdeUser user,MdeUser publisher,MdeJobInvitationRel mdeJobInvitationRel) {
		TMsgSendBaseReq invited = new TMsgSendBaseReq();
		invited.setTemplate_id(positionTemplateId);
		invited.setUrl(positionUrl);
		invited.setTouser(user.getOpenId());
		TMsg3ParamsDto dto = new TMsg3ParamsDto();
		dto.setFirst(user.getName()+"，你好。有企业HR向您发出了职位邀请。");
		dto.setKeyword1(new TMsgValueReq(mdeJobInvitationRel.getJobName(),"#173177"));
		dto.setKeyword2(new TMsgValueReq(publisher.getName(),"#173177"));
		dto.setKeyword3(new TMsgValueReq(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),"#173177"));
		dto.setRemark(mdeJobInvitationRel.getInvitation());
		invited.setData(dto);
		return invited;
	}
	
}
