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

import com.ssj.bean.weixin.order.domain.Order;
import com.ssj.bean.weixin.order.domain.OrderRefund;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.core.util.ResponseEntity;
import com.ssj.framework.weixin.pay.OrderHelper;
import com.ssj.framework.weixin.pay.OrderUtil;
import com.ssj.framework.weixin.pay.util.CommonUtil;
import com.ssj.framework.weixin.pay.util.ConfigUtil;
import com.ssj.framework.weixin.pay.util.PayCommonUtil;
import com.ssj.framework.weixin.pay.util.XMLUtil;
import com.ssj.service.weixin.order.service.OrderRefundService;
import com.ssj.service.weixin.order.service.OrderService;
import com.ssj.service.weixin.order.service.PayB2CService;
import com.ssj.service.weixin.payment.service.WeiXinPayB2CService;
import com.ssj.service.weixin.sales.service.LibOrderDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

@Service
@Transactional
public class WeiXinB2CServiceImpl  implements WeiXinPayB2CService {
	
	private static Logger logger = LoggerFactory.getLogger(WeiXinB2CServiceImpl.class);
	
	@Autowired
	private OrderService orderService;
	
	
	@Autowired
	private PayB2CService payB2CService;
	
	@Autowired
	private OrderRefundService orderRefundService;//退款
	@Autowired
	private LibOrderDetailsService libOrderDetailsService;//退款




	@Override
	public ResponseEntity refund(String orderId,String userId ,BigDecimal refund_fee) throws Exception{
		ResponseEntity  responseEntity= new  ResponseEntity();
		 
		Order order =orderService.getById(orderId);
		if(order != null){
			if(DateHelper.isThisMonth(order.getCreateTime())){
				if(userId.equals(order.getUserId()) && order.getOrderStatus() == 1){
					String orderNo = order.getOrderNo();
					BigDecimal  total_fee = order.getOrderMoney();
					if(total_fee.compareTo(refund_fee)<0){
						refund_fee = total_fee;
					}
					if(total_fee.compareTo(new BigDecimal(0))==0){
						responseEntity.failure("003","订单金额为0，不能退款");
						return  responseEntity;
					}
					logger.info("========需要退款的订单号和金额：orderNo:" + orderNo +",refund_fee:"+refund_fee);
					
					OrderHelper helper = new OrderHelper();
					String appid = ConfigUtil.APPID;
					String nonceStr = CommonUtil.CreateNoncestr();
					String mch_id = ConfigUtil.MCH_ID;//"1360047702";
					String refundCode = OrderUtil.getRefundCode();
					
					SortedMap<Object,Object> params  = new TreeMap<Object,Object>();
					params.put("appid", appid);
					params.put("mch_id", mch_id);
					params.put("nonce_str", nonceStr);
					params.put("out_trade_no", orderNo);//订单号
					params.put("out_refund_no", refundCode);//商户系统内部的退款单号，商户系统内部唯一，同一退款单号多次请求只退一笔
					params.put("total_fee", total_fee.multiply(new BigDecimal(100)).setScale(0,BigDecimal.ROUND_HALF_DOWN).toString());//订单总金额，单位为分，只能为整数
					params.put("refund_fee", refund_fee.multiply(new BigDecimal(100)).setScale(0,BigDecimal.ROUND_HALF_DOWN).toString());//(此处退款金额=订单总结额)退款总金额，订单总金额，单位为分，只能为整数
					params.put("op_user_id", mch_id);//操作员帐号, 默认为商户号
					String sign =  PayCommonUtil.createSign("UTF-8", params,ConfigUtil.PAYKEY);
					params.put("sign", sign);
					String result = helper.refundPost(params,"https://api.mch.weixin.qq.com/secapi/pay/refund","退款");
					logger.info("===请求微信退款接口返回结果:"+result);
					Map<String, Object> map = XMLUtil.doXMLParse(result);
					if (map.get("return_code").toString().equalsIgnoreCase("SUCCESS") && map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) {
						//数据库操作 
						OrderRefund re = new OrderRefund();
						re.setOrderNo(orderNo);
						re.setRefundNo(refundCode);
						re.setTransactionId((String)map.get("transaction_id"));
						re.setTotalFee(total_fee);
						re.setRefundTotalFee(refund_fee);
						re.setRefundStatus(1);
						re.setCreateTime(new Date());
						orderRefundService.save(re);
						libOrderDetailsService.updateOrderStatus(orderId);
						order.setOrderStatus(4);//已退款
						orderService.save(order);
					}
					responseEntity.success("退款成功");
				}else{
					responseEntity.failure("002","订单无效，不能退款");
				}
			}else{
				responseEntity.failure("001","订单已超时不能进行退款");
			}
		}else{
			responseEntity.failure("订单不存在");
		}
		return  responseEntity;
		
	}
}
