package com.cku.service;

import java.math.BigDecimal;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cab.dao.CabThirdPartyMapper;
import com.cab.dao.UserMapper;
import com.cab.model.CabThirdParty;
import com.cab.model.User;
import com.cku.core.ZAErrorCode;
import com.cku.core.ZAException;
import com.cku.dao.CkuDogMapper;
import com.cku.dao.CkuDvUserMapper;
import com.cku.dao.CkuMemberBalanMapper;
import com.cku.dao.CkuShowsBaoMingMapper;
import com.cku.dao.CkuUserMapper;
import com.cku.dao.CkuUserPayListMapper;
import com.cku.dao.EventRelatedMapper;
import com.cku.dao.FrequentlyUsedUsersMapper;
import com.cku.dao.SPCartsMapper;
import com.cku.dao.SPOrderInfoMapper;
import com.cku.model.CkuDog;
import com.cku.model.CkuDvUserModel;
import com.cku.model.CkuMemberBalance;
import com.cku.model.CkuOrder;
import com.cku.model.CkuShowsBaoMing;
import com.cku.model.CkuUser;
import com.cku.model.CkuUserPayList;
import com.cku.model.EventRelatedModel;
import com.cku.model.SPCarts;
import com.cku.model.SPOrderInfo;
import com.cku.util.AESUtils;
import com.cku.util.Debugger;
import com.cku.util.MD5Generator;

@Service("ckuDogEnteredService")
public class CkuDogEnteredServiceImpl {
	
	@Autowired
	public EventRelatedMapper eventRelatedMapper;
	
	@Autowired
	public CkuDogMapper ckuDogMapper;
	
	@Autowired
	public CkuShowsBaoMingMapper ckuShowsBaoMingMapper;
	
	@Autowired
	public SPOrderInfoMapper sPOrderInfoMapper;
	
	@Autowired
	public SPCartsMapper sPCartsMapper;
	
	@Autowired
	public CabThirdPartyMapper cabThirdPartyMapper;
	
	@Autowired
	public CkuDvUserMapper ckuDvUserMapper;
	
	@Autowired
	public CkuMemberBalanMapper ckuMemberBalanMapper;
	
	@Autowired
	public CkuUserPayListMapper ckuUserPayListMapper;
	
	@Autowired
	public CkuUserMapper ckuUserMapper;
	
	@Autowired
	public FrequentlyUsedUsersMapper frequentlyUsedUsersMapper;
	
	@Autowired
	public UserMapper userMapper;
	/**
	 * 
	 * @Description：犬只赛事报名
	 * @author: zhuoHeng
	 * @version: 2016年4月19日 上午10:01:22
	 * @param phone 
	 * @param name 
	 * @throws SQLException 
	 */
	@Transactional
	public CkuOrder dogEventEntered(Long userId,String showNum,String pedigreeNum,String detil,String ageGroup) throws SQLException{
		SimpleDateFormat df = new SimpleDateFormat("yyMMddHHmmss");
		List<CkuDog> dogList = ckuDogMapper.getMatchCost(pedigreeNum, null);
		//根据cab用户id查询出第三方表中对应的CKU账号信息
		CabThirdParty cabThirdParty = cabThirdPartyMapper.selectByUserId(new Long(userId).intValue());
		String dvUserId = "-1";
		if(cabThirdParty != null){
			dvUserId = cabThirdParty.getCkuUserId();
		}
		//根据CKU账号id查询出CKU账号信息
		CkuDvUserModel ckuDvUserModel = ckuDvUserMapper.getckuMemberByUserId(dvUserId);
		List<CkuUser> list = ckuUserMapper.getUserMessage(ckuDvUserModel.getCkuId());
		Date date = new Date();
		int payPid = 0;
		int max = 99;
		int min = 10;
		double bmFei = 0;
		BigDecimal money = new BigDecimal(0);
		String random = String.valueOf((int)Math.floor(Math.random()*(max-min+1)+min));
		String orderID = df.format(date)+random+"@"+ckuDvUserModel.getCkuId();
		String[] strs = showNum.split(",");
		EventRelatedModel eventRelatedModel = new EventRelatedModel();
		for (int i = 0; i < strs.length; i++) {
			eventRelatedModel = eventRelatedMapper.getSpecificEventByShowNum(strs[i].trim());
			bmFei += money.add(eventRelatedModel.getBmFei()).doubleValue();
			eventRelatedModel.getGameType();//举办类型（自办or合办）
			eventRelatedModel.getOrganizer();//举办方
		}
		if("自办".equals(eventRelatedModel.getGameType())){
			if("北京".equals(eventRelatedModel.getOrganizer())){
				payPid = 45;
			} else if("杭州".equals(eventRelatedModel.getOrganizer())){
				payPid = 141;
			}
		}else if("合办".equals(eventRelatedModel.getGameType())){
			if("北京".equals(eventRelatedModel.getOrganizer())){
				payPid = 140;
			} else if("杭州".equals(eventRelatedModel.getOrganizer())){
				payPid = 142;
			}
		}
		insertEntered(dogList,showNum,bmFei,orderID,date,ckuDvUserModel.getCkuId(),payPid,detil,ageGroup,list.get(0));
		insertSPOrderInfo(ckuDvUserModel,bmFei,orderID,date);
		insertSPCarts(ckuDvUserModel,orderID,bmFei,date,payPid);
		CkuOrder ckuOrder = new CkuOrder();
		ckuOrder.setOrderID(orderID);
		ckuOrder.setTypeId(payPid);
		return ckuOrder;
	}
	
	/**
	 * 
	 * @Description：赛事报名表生成未支付报名信息
	 * @author: zhuoHeng
	 * @version: 2016年4月19日 下午4:39:03
	 * @param phone 
	 * @param name 
	 */
	public void insertEntered(List<CkuDog> dogList,String showNum,double bmFei,String orderID,Date date,String ckuId,Integer payPid,
			String detil,String ageGroup,CkuUser ckuUser){
		CkuShowsBaoMing ckuShowsBaoMing = new CkuShowsBaoMing();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//订单生成来源
		ckuShowsBaoMing.setEntryNo("CAIB");
		//犬主人
		ckuShowsBaoMing.setDogOwner(dogList.get(0).getDogOwner());
		List<CkuUser> list = ckuUserMapper.getUserMessage(dogList.get(0).getMemberNum());
		//犬主英文名
		if(list.size()>0){
			ckuShowsBaoMing.setDogOwnerE(list.get(0).getNameSpelling());
		}
		//会员号
		ckuShowsBaoMing.setUserNo(ckuId);
		//赛事编号
		ckuShowsBaoMing.setShowNum(showNum);
		//备注
		ckuShowsBaoMing.setRemark(detil);
		//报名费
		ckuShowsBaoMing.setEntryFee(String.valueOf(bmFei));
		//请假及取消
		ckuShowsBaoMing.setLeaveCancel("否");
		//赛场请假
		ckuShowsBaoMing.setShowLeave("否");
		//犬种中文名
		ckuShowsBaoMing.setBreedName(dogList.get(0).getDogtype());
		//犬种英文名
		ckuShowsBaoMing.setBreedNameE(dogList.get(0).getTypeEgName());
		//FCI代码
		ckuShowsBaoMing.setFciCode(dogList.get(0).getDogType());
		//犬种类组
		ckuShowsBaoMing.setBreedGroup(dogList.get(0).getTypeGroup());
		//犬名
		ckuShowsBaoMing.setDogName(dogList.get(0).getDogEgName());
		//犬性别
		ckuShowsBaoMing.setGender(dogList.get(0).getDogGender());
		//出生日期
		ckuShowsBaoMing.setBirth(dogList.get(0).getDogBirthday());
		//年龄组别
		ckuShowsBaoMing.setAgeGroup(ageGroup);
		//CKU血统证书号
		ckuShowsBaoMing.setCkuStudbookNum(dogList.get(0).getPedigreeNum());
		//国外血统证书号
		ckuShowsBaoMing.setForeignStudbookNum(dogList.get(0).getOverseasRegCertifi());
		//芯片号
		ckuShowsBaoMing.setMicrochipNo(dogList.get(0).getIdentifiSign());
		//父犬血统证号
		ckuShowsBaoMing.setFstudbookNum(dogList.get(0).getfPedigreeNum());
		if(dogList.size()>0){
			if(dogList.get(0).getfPedigreeNum()!=null){
				List<CkuDog> fList = ckuDogMapper.getMatchCost(dogList.get(0).getfPedigreeNum(), null);
				if(fList.size()>0){
					//父犬名
					ckuShowsBaoMing.setFdogName(fList.get(0).getDogEgName());
				}
			}
			if(dogList.get(0).getmPedigreeNum()!=null){
				List<CkuDog> mList = ckuDogMapper.getMatchCost(dogList.get(0).getmPedigreeNum(), null);
				if(mList.size()>0){
					//母犬名
					ckuShowsBaoMing.setMdogName(mList.get(0).getDogEgName());
				}
			}
			dogList.get(0).getmPedigreeNum();
		}
		//母犬血统证号
		ckuShowsBaoMing.setMstudbookNum(dogList.get(0).getmPedigreeNum());
		//繁殖人
		ckuShowsBaoMing.setBreeder(dogList.get(0).getBreeder());
		//操作人员
		ckuShowsBaoMing.setOptUser(ckuId.trim()+":"+sdf.format(new Date()));
		//项目类型(根据gameType、organizer来判断)
		ckuShowsBaoMing.setPayPid(payPid);
		//订单金额
		ckuShowsBaoMing.setOrderPrice(new BigDecimal(bmFei));
		//订单号
		ckuShowsBaoMing.setRunningNumber(orderID);
		//订单生成时间
		ckuShowsBaoMing.setAddTime(date);
		//支付状态
		ckuShowsBaoMing.setPayout("8");
		//支付会员号
		ckuShowsBaoMing.setPayCkuid(ckuId);
		//添加牵犬师信息
		ckuShowsBaoMing.setSponsorDetil(detil);
		ckuShowsBaoMing.setDelTag("0");
		ckuShowsBaoMing.setInfoConfirm("0");
		ckuShowsBaoMingMapper.insertSelective(ckuShowsBaoMing);
	}
	
	/**
	 * 
	 * @Description：订单表生成未支付订单信息
	 * @author: zhuoHeng
	 * @version: 2016年4月19日 下午4:59:30
	 */
	public void insertSPOrderInfo(CkuDvUserModel ckuDvUserModel,double bmFei,String orderID,Date date){
		
		SPOrderInfo record = new SPOrderInfo();
		
		record.setCkuId(ckuDvUserModel.getCkuId());
		record.setUsername(ckuDvUserModel.getUserName());
		record.setOrderid(orderID);
		record.setSpPrices(new BigDecimal(bmFei));
		record.setPayconfirm("0");
		record.setAddTime(date);
		record.setSpIntegral(1);
		
		sPOrderInfoMapper.insertSelective(record);
	}
	
	/**
	 * 
	 * @Description：购物车表生成未支付订单信息
	 * @author: zhuoHeng
	 * @version: 2016年4月19日 下午5:11:30
	 */
	public void insertSPCarts(CkuDvUserModel ckuDvUserModel,String orderID,double bmFei,Date date,Integer payPid){
		SPCarts sPCarts = new SPCarts();
		sPCarts.setOrderid(orderID);
		sPCarts.setCkuId(ckuDvUserModel.getCkuId());
		sPCarts.setPid(payPid);//增加项目类型
		sPCarts.setTotalPrice(new BigDecimal(bmFei));
		sPCarts.setAddTime(date);
		sPCarts.setSpIntegral((int)bmFei);
		sPCarts.setSpPrice(new BigDecimal(bmFei));
		sPCartsMapper.insertSelective(sPCarts);
	}
	
	/**
	 * 
	 * @Description：余额支付赛事费用
	 * @author: zhuoHeng
	 * @version: 2016年4月20日 上午10:21:24
	 * @throws Exception 
	 */
	@Transactional
	public void eventBalancePayment(Long userId,String orderID,String pid,String payPsw,String dynamic) throws Exception{
		
		User user = userMapper.selectByPrimaryId(new Long(userId).intValue());
		byte[] content = Base64.getDecoder().decode(user.getPayPassWord());
		String realPassword = new String(AESUtils.decrypt(content));
		String md5 = MD5Generator.generate(realPassword + dynamic);
		Debugger.doAssert(payPsw.equalsIgnoreCase(md5), ZAErrorCode.ZA_ERC_INVALID_PAYPASSWORD, "支付密码错误");
		
		String dvUserId = "-1";
		String ckuUserId = "-1";
		//根据cab用户id查询出第三方表中对应的CKU账号信息
		CabThirdParty cabThirdParty = cabThirdPartyMapper.selectByUserId(new Long(userId).intValue());
		if(cabThirdParty != null){
			dvUserId = cabThirdParty.getCkuUserId();
		}
		//根据CKU账号id查询出CKU账号信息
		CkuDvUserModel ckuDvUserModel = ckuDvUserMapper.getckuMemberByUserId(dvUserId);
		if(ckuDvUserModel != null){
			ckuUserId = ckuDvUserModel.getCkuId();
		}
		//根据CKU会员号查询出对应用户的余额信息
		CkuMemberBalance ckuMemberBalance = ckuMemberBalanMapper.getCkuMemberBalance(ckuUserId);
		
		if(ckuMemberBalance==null){
			ckuMemberBalance = new CkuMemberBalance();
			String str = "0.0000";
			ckuMemberBalance.setMoneyAmount(str);
		}
		//获取CKU账户余额
		BigDecimal money = new BigDecimal(ckuMemberBalance.getMoneyAmount());
		double amount=0;
		String[] orderIds;
		String[] pids;
		//合并支付订单
		if(orderID.contains(",")){
			orderIds = orderID.split(",");
			pids = pid.split(",");
			for (int i = 0; i < orderIds.length; i++) {
				//根据订单号查询出该订单应支付金额
				SPOrderInfo sPOrderInfo = sPOrderInfoMapper.selectByOrderID(orderIds[i], ckuUserId);
				amount = money.subtract(sPOrderInfo.getSpPrices()).doubleValue();
				Debugger.doAssert(amount>0, ZAErrorCode.ZA_BALANCE_ENOUGH, "账户余额不足");
				
				ckuMemberBalanMapper.updateMemberBalance(new BigDecimal(amount),ckuUserId);
				ckuShowsBaoMingMapper.updateShowBaomingPayOut(orderIds[i]);
				sPOrderInfoMapper.updateOrderPayConfim(orderIds[i]);
				sPCartsMapper.updateSPCartsPayConfirm(orderIds[i]);
				CkuUserPayList ckuUserPayList = new CkuUserPayList();
				ckuUserPayList.setUserId(ckuUserId);
				ckuUserPayList.setMoneyType(pids[i]);
				ckuUserPayList.setMoneyDate(new Date());
				ckuUserPayList.setMoneyAmount(sPOrderInfo.getSpPrices());
				ckuUserPayList.setMoneyWay("cku.org");
				ckuUserPayList.setRunningNumber(orderIds[i]);
				ckuUserPayList.setPayState("1");
				ckuUserPayList.setOutTradeNo(orderIds[i]);
				ckuUserPayList.setAlipayS("caib");
				ckuUserPayList.setAddTime(new Date());
				ckuUserPayList.setOperater(ckuUserId);
				ckuUserPayListMapper.insertSelective(ckuUserPayList);
			}
		} else {//单独支付订单
			//根据订单号查询出该订单应支付金额
			SPOrderInfo sPOrderInfo = sPOrderInfoMapper.selectByOrderID(orderID, ckuUserId);
			amount = money.subtract(sPOrderInfo.getSpPrices()).doubleValue();
			Debugger.doAssert(amount>0, ZAErrorCode.ZA_BALANCE_ENOUGH, "账户余额不足");
			
			ckuMemberBalanMapper.updateMemberBalance(new BigDecimal(amount),ckuUserId);
			ckuShowsBaoMingMapper.updateShowBaomingPayOut(orderID);
			sPOrderInfoMapper.updateOrderPayConfim(orderID);
			sPCartsMapper.updateSPCartsPayConfirm(orderID);
			CkuUserPayList ckuUserPayList = new CkuUserPayList();
			ckuUserPayList.setUserId(ckuUserId);
			ckuUserPayList.setMoneyType(pid);
			ckuUserPayList.setMoneyDate(new Date());
			ckuUserPayList.setMoneyAmount(sPOrderInfo.getSpPrices());
			ckuUserPayList.setMoneyWay("cku.org");
			ckuUserPayList.setRunningNumber(orderID);
			ckuUserPayList.setPayState("1");
			ckuUserPayList.setOutTradeNo(orderID);
			ckuUserPayList.setAlipayS("caib");
			ckuUserPayList.setAddTime(new Date());
			ckuUserPayList.setOperater(ckuUserId);
			ckuUserPayListMapper.insertSelective(ckuUserPayList);
		}
	}
	
	/**
	 * 
	 * @Description：赛事报名取消订单
	 * @author: zhuoHeng
	 * @version: 2016年4月21日 下午1:10:37
	 */
	@Transactional
	public void cancelTheOrder(Long userId,String orderID){
		ckuShowsBaoMingMapper.deleteByOrderId(new Long(userId).intValue(),orderID);
		sPCartsMapper.deleteByOrderId(new Long(userId).intValue(),orderID);
		sPOrderInfoMapper.deleteByOrderId(new Long(userId).intValue(),orderID);
	}

}
