package com.cirle.scientific.service.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.cirle.scientific.dao.OrderDao;
import com.cirle.scientific.po.SalesOrdersMain;
import com.cirle.scientific.service.OrderService;
import com.cirle.scientific.service.PayCallbackService;
import com.cirle.scientific.utils.DateUtil;

/**
 * 微信相关service
 */
@Component
@Transactional
public class PayCallbackServiceImpl implements PayCallbackService{

	private static Logger logger = LoggerFactory.getLogger(PayCallbackServiceImpl.class);

	@Autowired
	private OrderService orderService;

	@Autowired
	private OrderDao salesOrdersMainDao;
	
	@Override
	@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
	public Boolean updateStatus(String out_trade_no, String transaction_id, String time_end, Integer status,
			Integer payType) {

		logger.info("进入更改订单支付状态\n out_trade_no:" + out_trade_no + "  transaction_id:" + transaction_id + " time_end:"
				+ time_end);
		if (out_trade_no == null || "".equals(out_trade_no)) {
			logger.info("订单号为空");
			return false;
		}
		logger.info("time_end：" + time_end + "-status:" + status+ "-payType" + payType);
		// 获取订单信息
		SalesOrdersMain ordersMain = salesOrdersMainDao.getOrderInfo(out_trade_no.trim());
		logger.info("获取订单信息:" + ordersMain );
		if (ordersMain != null && ordersMain.getStatus() == 0) {
			logger.info("修改订单支付状态");
			// 更改订单支付状态
			ordersMain.setOrderId(ordersMain.getOrderId());
			if (payType == 2) {
				ordersMain.setWxpayOrderId(transaction_id);
			} else if (payType == 1) {
				ordersMain.setAlipayOrderId(transaction_id);
			}
			ordersMain.setPayType(payType);
			ordersMain.setStatus(status);
			if (time_end != null && !"".equals(time_end)) {
				ordersMain.setPayTime(DateUtil.getCalendarFromString(time_end, "yyyyMMddHHmmss"));
			}
			ordersMain = salesOrdersMainDao.save(ordersMain);

			//增加任务积分
			orderService.addTask(ordersMain.getMemCard(), ordersMain.getOrderType(), Integer.parseInt(ordersMain.getObjId()));
			
			if (status == 1) {
				orderService.savePurchased(ordersMain, 36500);
			}
		}
		return true;
	}
	
}
