package com.sv.service.api;

import com.enums.MoneyLogEnum;
import com.enums.OrderPayEnum;
import com.enums.PayTypeEnum;
import com.github.pagehelper.PageHelper;
import com.sv.dto.api.MemberLessonTicketDetailDTO;
import com.sv.dto.api.wechat.BaseResult;
import com.sv.entity.MemberRefund;
import com.sv.entity.Order;
import com.sv.mapper.MemberRefundMapper;
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.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.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * Service - 用户退款记录表
 *
 * @author lihong
 * @since 2018-08-07
 */
@Service
@Transactional
public class MemberRefundService extends BaseServiceImpl {

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

	@Resource
	private MemberRefundMapper memberRefundMapper;
	@Resource
	private OrderService orderService;
	@Resource
	private WechatPayService wechatPayService;
	@Resource
    private MemberMoneyLogService memberMoneyLogService;

	/**
	 * 创建用户退款记录表
	 *
	 * @param memberRefund 用户退款记录表
	 */
	@Transactional
    public void save(MemberRefund memberRefund) {
		if (memberRefund.getId() != null && memberRefund.getId() > 0) {
			// 更新
			memberRefundMapper.update(memberRefund);
		} else {
			// 新建
			memberRefundMapper.insert(memberRefund);
		}
	}

	/**
	 * 更新用户退款记录表
 	 *
	 * @param memberRefund 用户退款记录表
	 */
	@Transactional
    public void update(MemberRefund memberRefund) {
		memberRefundMapper.update(memberRefund);
	}

	/**
	 * 删除用户退款记录表
	 *
	 * @param id 编号
   	 * @return 删除数量
	 */
	@Transactional
    public Integer delete(Integer id) {
		if (id == null || id <= 0) {
			return 0;
		}
		return memberRefundMapper.delete(id);
	}

	/**
	 * 删除用户退款记录表
	 *
	 * @param ids 编号数组
	 * @return 删除数量
	 */
	@Transactional
    public Integer deleteByIds(Integer[] ids) {
		if (ids == null || ids.length == 0) {
			return 0;
		}
		return memberRefundMapper.deleteByIds(ids);
	}

	/**
	 * 查询用户退款记录表
	 *
	 * @param id 编号
	 * @return 用户退款记录表
	 */
	public MemberRefund findById(Integer id) {
		return memberRefundMapper.findById(id);
	}

	/**
	 * 查询用户退款记录表
	 *
	 * @param pagination 分页信息
	 * @return 分页结果
	 */
	public Pagination findPage(Pagination pagination) {
		PageHelper.startPage(pagination.getPage(), pagination.getPageSize());
		PageHelper.orderBy("id desc");
		pagination.setQueryResult(memberRefundMapper.findAll());
		return pagination;
	}

	/**
	 * api 取消课程，增加用户退款记录表（微信支付）
	 */
	@Transactional(readOnly = false)
	public MemberRefund addMemberRefund(Integer memberId, MemberLessonTicketDetailDTO memberLessonTicket, String orderSn,Integer platformId){
		// 根据orderSn查出对应订单信息
		Order order = orderService.findOrderSn(orderSn,memberId);
		if (order == null){
			throw new ServiceException(com.sv.exception.api.ExceptionCodeTemplate.ORDER_ERROR);
		}

		MemberRefund memberRefund = new MemberRefund();
		memberRefund.setMemberId(memberId);
		memberRefund.setLessonId(memberLessonTicket.getLessonId());
		memberRefund.setMoney(order.getPrice());
		memberRefund.setOrderSn(orderSn);
		memberRefund.setTransactionId(order.getTradeSn());
		memberRefund.setOrderId(order.getId());
		memberRefund.setOutRefundNo(orderService.createSn());//商户退款单号
		memberRefund.setPlatformId(platformId);
		memberRefundMapper.insert(memberRefund);

		return memberRefund;
	}

	@Transactional(readOnly = false)
	public void refund(MemberRefund memberRefund){
		wechatPayService.refundMoney(memberRefund);
	}

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

    /**
     * 退款回调修信息
     */
	@Transactional(readOnly = false)
    public void updateInfo(String refundStatus,String outTradeNo,String successTime,Integer platformId){
        // 通过订单号查询‘用户退款记录表’
        try {
            MemberRefund memberRefund = memberRefundMapper.findByOrderSn(outTradeNo);
            if (refundStatus.equals(memberRefund.getRefundStatus())){
            	return;
			}
            memberRefund.setRefundStatus(refundStatus);
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date time = sdf.parse(successTime);
            memberRefund.setSuccessTime(time);
            memberRefundMapper.update(memberRefund);

            // 记录到‘用户账单（余额，微信，会员卡）记录’
            memberMoneyLogService.create(memberRefund.getMemberId(),platformId,MoneyLogEnum.REFUND.value,memberRefund.getMoney(),PayTypeEnum.WEI_XIN.value,
										null,null,null,memberRefund.getLessonId());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}

