package com.wechat.service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.wechat.common.utils.StringsUtils;
import com.wechat.dao.MdeTicketCategoryDao;
import com.wechat.dao.MdeTicketDetailDao;
import com.wechat.dao.MdeUserDao;
import com.wechat.global.CustomException;
import com.wechat.global.base.dao.Pagination;
import com.wechat.global.base.dao.PagingResult;
import com.wechat.global.message.InfoMsg;
import com.wechat.model.dbEntity.MdeTicketCategory;
import com.wechat.model.dbEntity.MdeTicketDetail;
import com.wechat.model.dbEntity.MdeUser;
import com.wechat.model.requestDto.TicketReq;

/**
 * 
 * @author tangwc
 *
 */
@Service
public class MdeTicketDetailService {
	
	@Resource
	private MdeTicketDetailDao ticketDetailDao;
	@Resource
	private MdeTicketCategoryDao ticketCategoryDao;
	@Resource
	private MdeUserDao userDao;
	@Resource
	private CommonService commonService;
	
	
	public Map<String, Object> init(String userCode, String lang, String identityFlag) {
		return null;
	}
	/**
	 * 根据id获取券
	 * @param tdId
	 * @return
	 */
	public MdeTicketCategory getByCode(String tdId,String lang) {
//		return ticketDetailDao.getByIdOrCode(tdId,lang);
		return ticketCategoryDao.getByCode(tdId,lang);
	}
	/**
	 * 获取用户所有券 按照是否可使用与日期倒叙排序
	 * @param userCode
	 * @return
	 */
	public List<MdeTicketDetail> getByUserCode(String userCode,String lang){
		return ticketDetailDao.getByUserCode(userCode,lang);
	}
	/**
	 * 获取用户所有可使用券 日期倒叙排序
	 * @param userCode
	 * @return
	 */
	public List<MdeTicketDetail> getValidTicketByUser(String userCode,String identityFlag,String lang){
		return ticketDetailDao.getValidTicketByUser(userCode,identityFlag,lang);
	}
	
	/**
	 * 分页查询用户券
	 * @param page -> userCode,usedFlag,index,size
	 * @return
	 */
	public PagingResult<MdeTicketDetail> getTicketDetails(Pagination page) {
		return ticketDetailDao.getTicketDetails(page);
	}
	/**
	 * 新增用户券
	 * @param detail 
	 * @return
	 */
	public int insertTicket(MdeTicketDetail detail) {
		return ticketDetailDao.insertTicket(detail);
	}
	/**
	 * 修改用户券
	 * @return
	 */
	public int updateTicket() {
		MdeTicketDetail detail = new MdeTicketDetail();
		return ticketDetailDao.updateTicket(detail);
	}
	
	public int acquireTicket(TicketReq tParam, String lang) {
		int i=0;
		System.out.println("**************打印tdcode："+tParam.getTdCode());
		if(StringsUtils.isEmpty(tParam.getTdCode())) {
		    //新的券
			i=acquireMarketingTicket(tParam,lang);
		}else {
		    //分享券
			i=acquireSharedTicket(tParam,lang);
		}
		return i;
	}
	/**
	 * 领取分享的券
	 * @param param
	 * @param lang 
	 * @return
	 */
	public int acquireSharedTicket(TicketReq param, String lang) {
		// 判断该券是否在使用有效期内，然后是否可使用
		MdeTicketDetail detail = ticketDetailDao.getByTdCode(param.getTdCode(),lang);
		if(detail == null) {
			throw new CustomException(InfoMsg.ERROR_TICKET_USED);
		}
		Date d = new Date();

		detail.setTdCode(Long.toHexString(d.getTime())+StringsUtils.getRandomString(4));
		detail.setShareBy(detail.getUserCode());
		detail.setUpdateDate(d);
		detail.setUserName(param.getContactInfo().trim());
		MdeUser user = userDao.getUserInfoByIdOrUserName(param.getContactInfo());
		if(user != null) {
			if(user.getUserCode().equals(String.valueOf(detail.getUserCode()))) {
				throw new CustomException(InfoMsg.ERROR_GET_OWN_TICKET);
			}
			detail.setUpdateBy(user.getUserCode());
			detail.setUserCode(Long.valueOf(user.getUserCode()));
		}else 
		{
			detail.setUserCode(null);
		}
		
        //更新分享券
        int count= updateShareTicket(detail);
        if (count<1)
        {
            count= -1;
        }
        return count;
		
	}
	/**
	 * 领取营销的券
	 * @param param
	 * @param lang
	 * @return
	 */
	public int acquireMarketingTicket(TicketReq param, String lang) {
		// 检查该券是否被领取过
		MdeTicketDetail d_ = ticketDetailDao.getByTcCodeAndUserName(param);
		if(d_ !=null) {
			throw new CustomException(InfoMsg.ERROR_REPEAT_GET_TICKET);
		}
		// 获取券类别
		MdeTicketCategory ca = ticketCategoryDao.getInfoById(param.getTcCode());
		if(!"2".equals(ca.getIssuedType()))
		{
		    //不是营销券的情况
		    throw new CustomException(InfoMsg.ERROR_TICKET_USED);
		}else{
		    //券实例
	        MdeTicketDetail detail = new MdeTicketDetail();
	        detail.setTcCode(ca.getTcCode());// 券类别code(uuid)
	        
	        if(Integer.valueOf(ca.getIssuedNum())>0 && Integer.valueOf(ca.getLeftNum())<=0) {
	            //验证券的库存
	            throw new CustomException(InfoMsg.ERROR_TICKET_OUT);
	        }
	        //有库存则减库存
	        if(Integer.valueOf(ca.getIssuedNum())>0 && Integer.valueOf(ca.getLeftNum())>0) {
	            ticketCategoryDao.reduceLeftNum(ca.getTcCode());
	        }

	        MdeUser user = userDao.getUserInfoByIdOrUserName(param.getContactInfo());
	        detail.setUserName(param.getContactInfo());// 当前绑定用户名
	        if(user != null) {
	            detail.setUserCode(Long.valueOf(user.getUserCode()));// 当前绑定用户code
	            detail.setCreateBy(user.getUserCode());
	            detail.setUpdateBy(user.getUserCode());
	        }else {
	            detail.setCreateBy(param.getContactInfo());
	            detail.setUpdateBy(param.getContactInfo());
	        }
	        detail.setIdentityFlag(ca.getIdentityFlag());// 可使用身份标识[0-个人；1-企业]
	        detail.setShareFlag(ca.getShareFlag());// 可分享标识[0-不可分享；1-可分享]
	        detail.setAvailableFrom(ca.getAvailableFrom());// 使用时间from
	        detail.setAvailableTo(ca.getAvailableTo());// 使用时间to
	        
	        //新券领取
	        detail.setTdCode(Long.toHexString(new Date().getTime())+StringsUtils.getRandomString(4));// 券code（13位时间戳装16进制+4位随机字符）
	        detail.setUsedFlag("1");
	        detail.setVersionNo(1);
	        detail.setDelFlag(0);
	        return insertTicket(detail);
		}
	      
        
	}
	
	/**
	 * 更新用户注册前领取的优惠券
	 * @param userName
	 * @param userCode
	 * @return
	 */
	public int updateByUserName(String userName, String userCode) {
		return ticketDetailDao.updateByUserName(userName,userCode);
	}
	
	/**
     * 领取分享的优惠券
     * @param userName
     * @param userCode
     * @return
     */
    public int updateShareTicket(MdeTicketDetail detail) {
        return ticketDetailDao.updateShareTicket(detail);
    }
    
	/**
	 * 校验抵用券是否存在
	 * @param tcCode
	 * @param tdCode
	 * @param lang
	 * @return
	 */
	public MdeTicketDetail checkTdByCode(String userCode, String tcCode, String tdCode, String lang) {
		return ticketDetailDao.checkTdByCode(userCode, tcCode,tdCode,lang);
	}
	public int updateUsedFlag(String tdId) {
		return ticketDetailDao.updateUsedFlag(tdId);
	}
	
	
}
