package com.sv.service.api;

import com.enums.OrderPayEnum;
import com.enums.OrderTypeEnum;
import com.enums.PayTypeEnum;
import com.enums.VipTypeEnum;
import com.github.pagehelper.PageHelper;
import com.sv.dto.api.wechat.OrderPaySignResponse;
import com.sv.entity.*;
import com.sv.mapper.MemberCardOrderMapper;
import com.sv.service.api.config.WechatPayService;
import com.ydd.framework.core.common.Pagination;
import com.ydd.framework.core.common.utils.ValidationUtils;
import com.ydd.framework.core.exception.ExceptionCodeTemplate;
import com.ydd.framework.core.exception.ServiceException;
import com.ydd.framework.core.service.impl.BaseServiceImpl;
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 javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;

/**
 * Service - 用户会员卡订单
 *
 * @author lihong
 * @since 2018-08-03
 */
@Service("MemberCardOrderServiceApi")
@Transactional(readOnly = true)
public class MemberCardOrderService extends BaseServiceImpl {

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

	@Resource
	private MemberCardOrderMapper memberCardOrderMapper;
	@Resource
	private VenueCardService venueCardService;
    @Resource
    private OrderService orderService;
	@Resource
	private WechatPayService wechatPayService;
	@Resource
	private MemberAuthService memberAuthService;
	@Resource
	private MemberService memberService;
	@Resource
	private MemberCardService memberCardService;

	/**
	 * 创建用户会员卡订单
	 *
	 * @param memberCardOrder 用户会员卡订单
	 */
	@Transactional
    public void save(MemberCardOrder memberCardOrder) {
		if (memberCardOrder.getId() != null && memberCardOrder.getId() > 0) {
			// 更新
			memberCardOrderMapper.update(memberCardOrder);
		} else {
			// 新建
			memberCardOrderMapper.insert(memberCardOrder);
		}
	}

	/**
	 * 更新用户会员卡订单
 	 *
	 * @param memberCardOrder 用户会员卡订单
	 */
	@Transactional
    public void update(MemberCardOrder memberCardOrder) {
		memberCardOrderMapper.update(memberCardOrder);
	}

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

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

	/**
	 * 查询用户会员卡订单
	 *
	 * @param id 编号
	 * @return 用户会员卡订单
	 */
	public MemberCardOrder findById(Integer id) {
		return memberCardOrderMapper.findById(id);
	}

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

	/**
	 * 用户购买会员卡
	 * @param memberId 用户Id
	 * @param cardType 卡类型
	 * @param type 场馆类型
	 * @param venueId 场馆ID
	 * @return
	 */
	@Transactional
	public synchronized OrderPaySignResponse.WechatPayParam createCardOrder(Integer memberId,Integer cardType,
                                             Integer type,Integer venueId,Integer num,Integer platformId,String ip){
		// 判断用户是否登录
		if (memberId == null){
			throw new ServiceException(ExceptionCodeTemplate.NEED_LOGIN);
		}
		Member member = memberService.findById(memberId);
		memberService.verify(member);

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

		//参数校验
		ValidationUtils.assertNotNull(cardType,"请选择卡类型");
		ValidationUtils.assertNotNull(type);
		ValidationUtils.assertNotNull(venueId);

		// 根据场馆ID和会员卡类型查找‘会员卡的金额’
		VenueCard venueCard = venueCardService.findPrice(cardType,type,venueId);

		if (venueCard == null) {
			throw new ServiceException("无效的会员卡");
		}

		if (venueCard.getStatus() == 1){
		    throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.VIP_ERROR);
        }

        // 1.用户会员卡订单
        MemberCardOrder order = order( memberId, cardType, type, venueId,platformId);

        // 2.生成订单
		// 订单总价格，保留2位小数
		BigDecimal totalPrice = venueCard.getPrice().multiply(new BigDecimal(num));
        orderService.createOrder(memberId,order.getOrderSn(),totalPrice,platformId,PayTypeEnum.WEI_XIN.value,OrderTypeEnum.VIP_ORDER.value,OrderPayEnum.ORDER_NO_PAY.value);

        // 3.生成用户会员卡的状态为'未激活'
//		memberCardService.createCard(order,totalPrice);

        // 4.调支付
		OrderPaySignResponse.WechatPayParam wechatPayParam = createUnifiedOrder(order.getOrderSn(), memberId,ip);
		return wechatPayParam;
	}

    /**
     * 生成用户会员卡订单
     */
    @Transactional
    public MemberCardOrder order(Integer memberId,Integer cardType,Integer type,Integer venueId,
                                  Integer platformId){
        MemberCardOrder cardOrder = new MemberCardOrder();
        cardOrder.setPayStatus(OrderPayEnum.ORDER_NO_PAY.value);
        cardOrder.setMemberId(memberId);
        cardOrder.setCardType(VipTypeEnum.getByValue(cardType).getName());
        cardOrder.setVeneuType(type);
        cardOrder.setVenueId(venueId);
        cardOrder.setOrderSn(createSn());
        cardOrder.setPlatformId(platformId);
        memberCardOrderMapper.insert(cardOrder);
        return cardOrder;
    }

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

	/**
	 * 微信下单
	 *
	 * @param orderSn
	 * @param memberId
	 * @return
	 */
	@Transactional
	public OrderPaySignResponse.WechatPayParam createUnifiedOrder(String orderSn, Integer memberId, String ip) {
		Order order = orderService.findOrderSn(orderSn, memberId);
		if (order == null){
			throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.ORDER_ERROR);
		}
		return wechatPayService.createUnifiedOrder(orderSn, order.getPrice(), ip, "JSAPI", memberId);
	}

    /**
     * api 微信回调修改状态
     * @param orderSn
     * @return
     */
    @Transactional
    public MemberCardOrder paySuccess(String orderSn){
	    MemberCardOrder memberCard = memberCardOrderMapper.paySuccess(orderSn);
	    if (memberCard != null) {
            memberCard.setPayStatus(OrderPayEnum.PENDING_DELIVERY.value);
            memberCard.setModifiedTime(new Date());
            memberCardOrderMapper.update(memberCard);
        }
	    return memberCard;
    }
}

