package com.fzm.mall.server.front.asset.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fzm.mall.server.front.asset.mapper.UserAssetMapper;
import com.fzm.mall.server.front.asset.model.TranOrder;
import com.fzm.mall.server.front.asset.model.TranPay;
import com.fzm.mall.server.front.asset.mapper.TranPayMapper;
import com.fzm.mall.server.front.asset.model.UserAsset;
import com.fzm.mall.server.front.asset.service.ITranOrderService;
import com.fzm.mall.server.front.asset.service.ITranPayService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fzm.mall.server.front.asset.service.IUserAssetService;
import com.fzm.mall.server.front.enums.CoinNameEnum;
import com.fzm.mall.server.front.order.model.Order;
import com.fzm.mall.server.front.order.model.Pay;
import com.fzm.mall.server.front.order.model.PayRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fzm
 * @since 2021-09-08
 */
@Service
public class TranPayServiceImpl extends ServiceImpl<TranPayMapper, TranPay> implements ITranPayService {

    @Autowired
    private UserAssetMapper userAssetMapper;

    @Autowired
    private ITranOrderService tranOrderService;
    @Override
    public int pay(String uid, String pid) {
        TranPay pay = getByPidAndUid(pid);
        if(pay.getStatus()==0){
            UserAsset coin = userAssetMapper.getCoin(uid, CoinNameEnum.MALLCOIN.value());
            int i = userAssetMapper.deleteAmount(coin.getId(),pay.getAmount());
            if(i == 1){
                pay.setStatus(1);
                updateById(pay);
                String oid = pay.getOid();
                TranOrder tranOrder = tranOrderService.getByOid(oid);
                tranOrder.setStatus(1);
                tranOrderService.updateById(tranOrder);
                return  1;
            }else{
            //资产不足
            return  0;
        }
        }else{
            //订单处于不可支付状态
            return  -1;
        }
    }

    @Override
    public TranPay getByOid(String oid) {
        QueryWrapper<TranPay> q = new QueryWrapper<>();
        q.eq("oid",oid);
        return  getOne(q);
    }

    @Override
    public TranPay getByPid(String pid) {
        QueryWrapper<TranPay> q = new QueryWrapper<>();
        q.eq("pay_id",pid);
        return  getOne(q);
    }

    private TranPay getByPidAndUid(String pid) {
        QueryWrapper<TranPay> q = new QueryWrapper<>();
        q.eq("pay_id",pid);
        return  getOne(q);
    }
}
