package com.sv.service.api;

import com.enums.MoneyLogEnum;
import com.enums.OrderPayEnum;
import com.enums.OrderTypeEnum;
import com.enums.PayTypeEnum;
import com.github.pagehelper.PageHelper;
import com.sv.dto.api.wechat.BaseResult;
import com.sv.dto.api.wechat.OrderPaySignResponse;
import com.sv.entity.*;
import com.sv.exception.api.ExceptionCodeTemplate;
import com.sv.mapper.OrderMapper;
import com.sv.service.api.config.WechatPayService;
import com.ydd.framework.core.common.Pagination;
import com.ydd.framework.core.exception.ServiceException;
import com.ydd.framework.core.service.impl.BaseServiceImpl;
import com.ydd.oms.entity.enums.PayStatusEnum;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * Service - 订单
 *
 * @author lihong
 * @since 2018-08-03
 */
@Service("OrderServiceApi")
@Transactional
public class OrderService extends BaseServiceImpl {

	private final Logger logger = LoggerFactory.getLogger(OrderService.class);

	@Resource
	private OrderMapper orderMapper;
	@Resource
	private WechatPayService wechatPayService;
	@Resource
	private RechargeService rechargeService;
	@Resource
	private MemberCardOrderService memberCardOrderService;
	@Resource
	private MemberAuthService memberAuthService;
	@Resource
	private MemberService memberService;

	@Resource
	private MemberMoneyLogService memberMoneyLogService;

	/**
	 * 创建订单
	 *
	 * @param order 订单
	 */
	@Transactional
    public void save(Order order) {
		if (order.getId() != null && order.getId() > 0) {
			// 更新
			orderMapper.update(order);
		} else {
			// 新建
			orderMapper.insert(order);
		}
	}

	/**
	 * 更新订单
 	 *
	 * @param order 订单
	 */
	@Transactional
    public void update(Order order) {
		orderMapper.update(order);
	}

	/**
	 * 删除订单
	 *
	 * @param id 编号
   	 * @return 删除数量
	 */
	@Transactional
    public Integer delete(Integer id) {
		if (id == null || id <= 0) {
			return 0;
		}
		return orderMapper.delete(id);
	}

	/**
	 * 删除订单
	 *
	 * @param ids 编号数组
	 * @return 删除数量
	 */
	@Transactional
    public Integer deleteByIds(Integer[] ids) {
		if (ids == null || ids.length == 0) {
			return 0;
		}
		return orderMapper.deleteByIds(ids);
	}

	/**
	 * 查询订单
	 *
	 * @param id 编号
	 * @return 订单
	 */
	public Order findById(Integer id) {
		return orderMapper.findById(id);
	}

	/**
	 * 查询订单
	 *
	 * @param pagination 分页信息
	 * @return 分页结果
	 */
	public Pagination findPage(Pagination pagination) {
		PageHelper.startPage(pagination.getPage(), pagination.getPageSize());
		PageHelper.orderBy("id desc");
		pagination.setQueryResult(orderMapper.findAll());
		return pagination;
	}

	/**
	 * api 生成订单
	 * @param memberId
	 * @param platformId
	 */
	@Transactional
	public Order createOrder(Integer memberId, String orderSn,BigDecimal totalPrice,Integer platformId,Integer payType,Integer type,Integer payStatus){
		Order order = new Order();
		order.setPayStatus(payStatus);
		order.setMemberId(memberId);
		order.setOrderSn(orderSn);
		order.setPayType(payType);
		order.setPrice(totalPrice.setScale(2));
		order.setType(type);
		order.setPlatformId(platformId);
		orderMapper.insert(order);
		return order;
	}

	/**
	 * 根据用户Id，订单号查询订单
	 */
	Order findOrderSn(String orderSn,Integer memberId){
		return orderMapper.findOrderSn( orderSn, memberId);
	}

	/**
	 * api 更新prepay_id
	 */
	@Transactional
	public void updatePrepayId(String orderSn, String prepayId) {
		orderMapper.updatePrepayId(orderSn,prepayId);
	}

	/**
	 * api
	 */
	public Order findByOrderSn(String orderSn, Integer memberId) {
		return orderMapper.findOrderSn(orderSn, memberId);
	}

	/**
	 * api 支付成功
	 *
	 * @param orderId
	 */
	@Transactional
	public void paySuccess(Integer orderId, String tradeSn){
		Order order = new Order();
		order.setId(orderId);
		order.setPayStatus(OrderPayEnum.PENDING_DELIVERY.value);
		order.setTradeSn(tradeSn);
		order.setPayTime(new Date());
		orderMapper.update(order);
	}

	/**
	 * api 微信回调
	 */
	public BaseResult notifyWx(@RequestBody Map<String,String> params) throws IOException {
		wechatPayService.notify(params);
		return new BaseResult();
	}

	/**
	 * api 余额充值
	 */
	public OrderPaySignResponse.WechatPayParam createRecharge(Integer memberId,Integer platformId,Integer rechargeId,String ip){
		Recharge recharge = rechargeService.findById(rechargeId);
		if (recharge == null) {
			throw new ServiceException("充值失败");
		}

		if (memberId == null){
			throw new ServiceException(com.ydd.framework.core.exception.ExceptionCodeTemplate.NEED_LOGIN);
		}
		Member member = memberService.findById(memberId);
		memberService.verify(member);

		// 判断用户是否使用微信登录
		MemberAuth memberAuth = memberAuthService.findByMemberId(memberId);
		if (memberAuth == null){
			throw new ServiceException(ExceptionCodeTemplate.BUY_ERROR);
		}

		// 生成订单
		Order order = new Order();
		order.setMemberId(memberId);
		order.setOrderSn(createSn());
		order.setPayType(PayTypeEnum.WEI_XIN.value);
		order.setPrice(recharge.getRechargeMoney());
		order.setToMoney(recharge.getToMoney());
		order.setType(OrderTypeEnum.BALANCE_ORDER.value);
		order.setPlatformId(platformId);
		orderMapper.insert(order);

		// 调微信
		OrderPaySignResponse.WechatPayParam wechatPayParam = memberCardOrderService.createUnifiedOrder(order.getOrderSn(), memberId,ip);
		return wechatPayParam;
	}

	/**
	 * api
	 * 生成订单号
	 *
	 * @return
	 */
	public String createSn() {
		return DateFormatUtils.format(new Date(), "yyMMddHHmmss") + RandomStringUtils.randomNumeric(6);
	}

	/**
	 * 生成进场订单
	 * @param venue
	 * @param memberId
	 * @return
	 */
	public String createEnterVenueOrder(Venue venue, Integer memberId,PayTypeEnum payTypeEnum,BigDecimal price){
		//创建订单
		Order order = new Order();
		order.setOrderSn(createSn());
		order.setPayType(payTypeEnum.value);
		order.setPrice(price);
		order.setPayTime(new Date());
		order.setPayStatus(PayStatusEnum.PAYED.value.intValue());
		order.setType(OrderTypeEnum.BASKETBALL_ORDER.value);
		order.setPlatformId(venue.getPlatformId());
		order.setMemberId(memberId);
		orderMapper.insert(order);

		//扣除用户余额
		if(payTypeEnum.value.equals(PayTypeEnum.BALANCE.value)) {
			memberMoneyLogService.create(memberId, venue.getPlatformId(), MoneyLogEnum.JOIN.value, price.negate(), PayTypeEnum.BALANCE.value, null, venue.getId(), venue.getType(), null);
		}
		return order.getOrderSn();
	}
}

