package co.yixiang.yshop.module.order.api;

import co.yixiang.yshop.module.member.api.user.MemberUserNowMoneyApi;
import co.yixiang.yshop.module.member.api.user.dto.IncreaseNowMoneyDTO;
import co.yixiang.yshop.module.order.api.rechargeorder.RechargeOrderApi;
import co.yixiang.yshop.module.order.api.rechargeorder.dto.RechargeOrderDTO;
import co.yixiang.yshop.module.order.controller.admin.rechargeorder.vo.RechargeOrderUpdateReqVO;
import co.yixiang.yshop.module.order.convert.rechargeorder.RechargeOrderConvert;
import co.yixiang.yshop.module.order.dal.dataobject.rechargeorder.RechargeOrderDO;
import co.yixiang.yshop.module.order.enums.ReachargeOrderStatusEnum;
import co.yixiang.yshop.module.order.service.rechargeorder.RechargeOrderService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;

@Service
public class RechargeOrderApiImpl implements RechargeOrderApi {

    @Resource
    private RechargeOrderService rechargeOrderService;

    @Resource
    private MemberUserNowMoneyApi memberUserNowMoneyApi;

    @Override
    public RechargeOrderDTO getPayParam(String id) {
        RechargeOrderDO rechargeOrder = rechargeOrderService.getRechargeOrder(id);
        return RechargeOrderConvert.INSTANCE.convert02(rechargeOrder);
    }

    @Override
    public void handleWeChatPayNotify(String orderId) throws Exception {
        // 增加余额
        RechargeOrderDO rechargeOrder = rechargeOrderService.getRechargeOrder(orderId);
        // 判断重复回调
        if (rechargeOrder.getStatus().equals(ReachargeOrderStatusEnum.SUCCESS.getValue())) {
            return;
        }
        RechargeOrderUpdateReqVO updateReqVO = new RechargeOrderUpdateReqVO();
        updateReqVO.setId(rechargeOrder.getId());
        updateReqVO.setStatus(ReachargeOrderStatusEnum.SUCCESS.getValue());
        // 更新状态
        rechargeOrderService.updateRechargeOrder(updateReqVO);
        // 增加余额

        IncreaseNowMoneyDTO increaseNowMoneyDTO = new IncreaseNowMoneyDTO();
        increaseNowMoneyDTO.setId(rechargeOrder.getUserId());
        increaseNowMoneyDTO.setAmount(new BigDecimal(rechargeOrder.getRechargeAmount()));
        increaseNowMoneyDTO.setLink(orderId);
        increaseNowMoneyDTO.setMark("微信支付充值" + rechargeOrder.getRechargeAmount() + "元");

        memberUserNowMoneyApi.increaseNowMoney(increaseNowMoneyDTO);

        if (rechargeOrder.getGiftAmount() != null && rechargeOrder.getGiftAmount() > 0) {
            increaseNowMoneyDTO = new IncreaseNowMoneyDTO();
            increaseNowMoneyDTO.setId(rechargeOrder.getUserId());
            increaseNowMoneyDTO.setAmount(new BigDecimal(rechargeOrder.getGiftAmount()));
            increaseNowMoneyDTO.setLink(orderId);
            increaseNowMoneyDTO.setMark("充值赠送" + rechargeOrder.getGiftAmount() + "元");

            memberUserNowMoneyApi.increaseNowMoney(increaseNowMoneyDTO);
        }

    }
}
