package com.ssj.service.weixin.order.service.impl;

import com.ssj.bean.sys.cardinfo.domain.TbCardInfo;
import com.ssj.bean.weixin.order.domain.PayB2C;
import com.ssj.dao.weixin.order.dao.PayB2CDao;
import com.ssj.framework.cmb.service.CmbService;
import com.ssj.framework.cmb.util.XmlPacket;
import com.ssj.framework.core.common.service.BaseServiceImpl;
import com.ssj.framework.core.util.Constant;
import com.ssj.framework.weixin.pay.OrderUtil;
import com.ssj.service.sys.cardinfo.service.ICardInfoService;
import com.ssj.service.weixin.order.service.OrderService;
import com.ssj.service.weixin.order.service.PayB2CService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
@Service
@Transactional
public class PayB2CServiceImpl extends BaseServiceImpl<PayB2C, String> implements PayB2CService{
	 private static Logger logger = LoggerFactory.getLogger(PayB2CServiceImpl.class);
	@Autowired
	private PayB2CDao  payB2CDao;
	@Autowired
	private CmbService  cmbService;
	//@Autowired
	//private  LessonServiceService   lessonServiceService;
	@Autowired
	private  ICardInfoService   cardInfoService;
	@Autowired
	private  OrderService   orderService;

	@Override
	public PagingAndSortingRepository<PayB2C, String> getDao() {
		return payB2CDao;
	}
	@Override
	public void refundPayB2C(String userId,String orderNo,BigDecimal amount,String cardName,String account,String eacbnk,String eaccty) {
		if(amount.compareTo(new BigDecimal(0))>1){
			Integer  count =payB2CDao.getOrderNoCount(orderNo);
			if(count ==0){
				String  requestParameter=cmbService.getRequestDfStr(account, cardName, amount.toString(), orderNo, eacbnk, eaccty, "退款");
				PayB2C  payB2C  =new  PayB2C();
				payB2C.setAmount(amount);
				payB2C.setPayStatus(2);
				payB2C.setCreateTime(new Date());
				payB2C.setOrderNo(orderNo);
				payB2C.setUserId(userId);
				payB2C.setRequestParameter(requestParameter);
				payB2C.setType(1);
				this.save(payB2C);
			}
		}
	}

	@Override
	public void payB2C(String userId, String orderNo, BigDecimal amount, String cardName, String account, String eacbnk, String eaccty) {
		payB2CPublic(userId, orderNo, amount, cardName, account, eacbnk, eaccty, null);
	}

	@Override
	public void payB2C(String userId, String orderNo, BigDecimal amount, String cardName, String account, String eacbnk, String eaccty, String remark) {
		payB2CPublic(userId, orderNo, amount, cardName, account, eacbnk, eaccty, remark);
	}

	public void payB2CPublic(String userId, String orderNo, BigDecimal amount, String cardName, String account, String eacbnk, String eaccty, String remark) {
		Integer count = payB2CDao.getOrderNoCount(orderNo);
		if (count == 0) {
			String requestParameter = cmbService.getRequestDfStr(account, cardName, amount.toString(), orderNo, eacbnk, eaccty, remark);
			PayB2C payB2C = new PayB2C();
			payB2C.setAmount(amount);
			payB2C.setPayStatus(2);
			payB2C.setCreateTime(new Date());
			payB2C.setOrderNo(orderNo);
			payB2C.setUserId(userId);
			payB2C.setRequestParameter(requestParameter);
			payB2C.setType(2);
			this.save(payB2C);
		}
	}

	@Override
	public List<PayB2C> getYesterdayPayB2C(String startDate, String endDate) {
		return payB2CDao.getYesterdayPayB2C(startDate, endDate);
	}
	@Override
	public void timedRefund(int type) {
		/**
		 * 退款 退 最近14-7天内
		 */
		List<PayB2C> list =payB2CDao.timedLast7daysRefund(type,2);
		for (PayB2C payB2C : list) {
			try {
				 payB2C.setRequestTime(new Date());
				 String result=cmbService.df(payB2C.getRequestParameter());
				 payB2C.setRequestResult(result);
				 payB2C.setPayStatus(3);
				 logger.info("代付请求返回"+result);
				 if (result != null && result.length() > 0) {
		                XmlPacket pktRsp = XmlPacket.valueOf(result);
		                logger.info("XmlPacket请求返回"+pktRsp);
		                if (pktRsp != null) {
		                    String sRetCod = pktRsp.getRETCOD();
		                    payB2C.setRequestStataus(sRetCod);
		                    if (sRetCod.equals("0")) {
		                        Map propPayResult = pktRsp.getProperty("NTREQNBRY", 0);
		                        String REQNBR = (String) propPayResult.get("REQNBR");
		                        payB2C.setFlowNumber(REQNBR);
		                      //  payB2C.setPayStatus(3);
		                        logger.info("请求已被银行受理,message:{}", result);
		                    } else {
		                        logger.info("请求处理失败,message:{}", result);
		                        payB2C.setPayStatus(0);
		                    }
		               } else {
		            	   payB2C.setPayStatus(0);
		                logger.info("XmlPacket请求返回失败=", result);
		               }
		        }
				 this.save(payB2C);
				 
			} catch (Exception e) {
				logger.error("退款异常="+payB2C);
			}
		}
	}
	@Override
	public void inquireTimedRefund(int type) {
		List<PayB2C> list =payB2CDao.timedRefund(type,3);
		for (PayB2C payB2C : list) {
			try {
				 if(payB2C.getFlowNumber()!=null&&"0".equals(payB2C.getRequestStataus())){
					 String dfresult= cmbService.dfcx(payB2C.getFlowNumber());
					 payB2C.setFlowResult(dfresult);
					 payB2C.setPayTime(new Date());
					 logger.info("代付查询，message:{}", dfresult);
					 if (dfresult != null && dfresult.length() > 0) {
						 XmlPacket pktRsp = XmlPacket.valueOf(dfresult);
						  logger.info("XmlPacket请求返回"+pktRsp);
						 if (pktRsp != null) {
							 String sRetCod = pktRsp.getRETCOD();
							 if (sRetCod.equals("0")) {
								 Map propPayResult = pktRsp.getProperty("NTQATDQYZ", 0);
								 //S：成功；F：失败；C：撤消；I：数据录入
								 String STSCOD = propPayResult.get("STSCOD").toString();
								 if (Constant.CMB_DF_STATUS_S.equals(STSCOD)) {
									//成功
									 payB2C.setPayStatus(1);
								 }
								 if (Constant.CMB_DF_STATUS_I.equals(STSCOD)) {
									//录入
								 }
								 if (Constant.CMB_DF_STATUS_F.equals(STSCOD)) {
									 //失败
									 //失败原因
									 String ERRDSP = propPayResult.get("ERRDSP").toString();
									 payB2C.setFailMessage(ERRDSP);
									 payB2C.setPayStatus(0);
								 }
							 }
						 }
					 }
					 payB2C.setPayTime(new Date());
					 this.save(payB2C);
					 //退款成功，删除服务。
					 if(type==1&&payB2C.getPayStatus()==1){
						// lessonServiceService.refundLessonService(payB2C.getOrderNo());
						 orderService.updateOrderRefunds(payB2C.getOrderNo());//改为退款状态
					 }
				 }
			} catch (Exception e) {
				logger.error("代付查询="+payB2C);
			}
		}
	}
	@Override
	public void timePayment() {
		/**
		 * 结算上个月的工资(每月1号生产数据。)
		 */
		List<PayB2C> list =payB2CDao.lastMonthPay(2,2);
		for (PayB2C payB2C : list) {
			try {
				TbCardInfo cardInfo= cardInfoService.findByUserIdValid(payB2C.getUserId());
				if(cardInfo==null||cardInfo.getCardNum()==null||cardInfo.getCardName()==null){
					continue;
				}
				
				logger.info("打款参数"+payB2C);
				logger.info("银行卡参数"+cardInfo);
				String orderNo = OrderUtil.getOrderCode();//生成订单号
				payB2C.setOrderNo(orderNo);
				String  requestParameter=cmbService.getRequestDfStr(cardInfo.getCardNum(), cardInfo.getCardName(), payB2C.getAmount().toString(),
						orderNo, cardInfo.getCardBank(), cardInfo.getSubbranch(), "1对1");
				 logger.info("代付请求参数"+requestParameter);
				 payB2C.setRequestParameter(requestParameter);
				 payB2C.setRequestTime(new Date());
				 String result=cmbService.df(payB2C.getRequestParameter());
				 payB2C.setRequestResult(result);
				 payB2C.setPayStatus(3);
				 logger.info("代付请求返回"+result);
				 if (result != null && result.length() > 0) {
		                XmlPacket pktRsp = XmlPacket.valueOf(result);
		                logger.info("XmlPacket请求返回"+pktRsp);
		                if (pktRsp != null) {
		                    String sRetCod = pktRsp.getRETCOD();
		                    payB2C.setRequestStataus(sRetCod);
		                    if (sRetCod.equals("0")) {
		                        Map propPayResult = pktRsp.getProperty("NTREQNBRY", 0);
		                        String REQNBR = (String) propPayResult.get("REQNBR");
		                        payB2C.setFlowNumber(REQNBR);
		                      //  payB2C.setPayStatus(3);
		                        logger.info("请求已被银行受理,message:{}", result);
		                    } else {
		                        logger.info("请求处理失败,message:{}", result);
		                        payB2C.setPayStatus(0);
		                    }
		               } else {
		            	   payB2C.setPayStatus(0);
		                logger.info("XmlPacket请求返回失败=", result);
		               }
		        }
				 this.save(payB2C);
				 
			} catch (Exception e) {
				logger.error("代付请求异常="+payB2C);
				e.printStackTrace();
			}
		}
		
	}


}
