package com.fzm.mall.server.admin.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.admin.constant.MallResponseError;
import com.fzm.mall.server.admin.exception.MyException;
import com.fzm.mall.server.admin.order.mapper.PayMapper;
import com.fzm.mall.server.admin.order.model.Pay;
import com.fzm.mall.server.admin.order.service.IPayService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * <p>
 * 支付订单结果表 服务实现类
 * </p>
 *
 * @author wulixian
 * @since 2021-04-29
 */
@Service
@Transactional
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PayServiceImpl extends ServiceImpl<PayMapper, Pay> implements IPayService {

    private final PayMapper payMapper;

    /**
     * 订单协商“客服优惠价格”，支付订单支付“待支付金额”
     * @param oid
     * @param consultDiscountAmount
     */
    @Override
    public void consultDiscount(String oid, BigDecimal consultDiscountAmount) {
        QueryWrapper<Pay> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("state", Pay.PAY_STATE_TO_PAY).like("oids_json", oid);
        Pay pay = payMapper.selectOne(queryWrapper);
        BigDecimal zero = new BigDecimal(BigInteger.ZERO);
        BigDecimal unpaidAmount = pay.getUnpaidAmount().subtract(consultDiscountAmount);
        pay.setUnpaidAmount(unpaidAmount.compareTo(zero) == 1 ? unpaidAmount : zero);

        UpdateWrapper<Pay> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("pay_id", pay.getPayId())
                .eq("update_time", pay.getUpdateTime());
        int update = payMapper.update(pay, updateWrapper);
        if (update == 0) {
            throw new MyException(MallResponseError.UPDATE_FAIL);
        }
    }
}
