/*
 * Author: wangjian
 * 生成ServiceImpl
 */
package com.tofly.znb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.znb.common.constant.PjztEnum;
import com.tofly.znb.common.constant.SfbzEnum;
import com.tofly.znb.common.exception.FeesErrorCode;
import com.tofly.znb.common.exception.FeesException;
import com.tofly.znb.common.util.ServerUtil;
import com.tofly.znb.entity.YyZjzh;
import com.tofly.znb.entity.ZnbCsjsLog;
import com.tofly.znb.service.YyZjzhService;
import com.tofly.znb.service.ZnbCsjsLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.tofly.znb.mapper.YyZjzhMapper;

import java.math.BigDecimal;
import java.util.Date;

/**
 * 用户资金账号
 *
 * @author admin
 * @date Fri Aug 01 00:00:00 CST 2025
 */
@Service("yyZjzhService")
public class YyZjzhServiceImpl extends ServiceImpl<YyZjzhMapper, YyZjzh> implements YyZjzhService {
    @Autowired
    private ZnbCsjsLogService znbCsjsLogService;
    public BigDecimal znbkf(ZnbCsjsLog znbsf, String yhbh) {
        if (SfbzEnum.YSF.getValue().toString().equals(znbsf.getSfbz())) {
            throw new FeesException("用户已收费", FeesErrorCode.BUSINESS_ERROR);
        }

        if (PjztEnum.CH.getValue().equals(znbsf.getChbz())) {
            throw new FeesException("用户已冲红", FeesErrorCode.BUSINESS_ERROR);
        }

        YyZjzh zjzh = getById(yhbh);
        if (ObjectUtil.isNull(zjzh)) {
            zjzh = new YyZjzh();
            zjzh.setYhbh(yhbh);
            zjzh.setNbsyje(BigDecimal.ZERO);
            zjzh.setSyje(BigDecimal.ZERO);
            zjzh.setYfje(BigDecimal.ZERO);
            zjzh.setKjje(BigDecimal.ZERO);
            save(zjzh);
        }

        BigDecimal nbsyje = ObjectUtil.isNull(zjzh.getNbsyje()) ? BigDecimal.ZERO : zjzh.getNbsyje();
        BigDecimal yszje = znbsf.getYsje().add(znbsf.getZnj());

        // 余额扣减，更新账户余额
        BigDecimal ye = nbsyje.subtract(yszje);
        zjzh.setNbsyje(ye);
        updateById(zjzh);

        // 更新支付状态
        String sflsbh = ServerUtil.getSflsbh();
        znbsf.setSflsbh(sflsbh);
        znbsf.setSfrq(new Date());
        znbsf.setSfbz(SfbzEnum.YSF.getValue().toString());
        znbsf.setScye(nbsyje);
        znbsf.setBckj(yszje);
        znbsf.setBcye(ye);
        znbsf.setSflx("3");
        znbsf.setSfrybm("system");
        znbsf.setSfryxm("系统");
        znbsf.setCbjsbz("1");

        znbCsjsLogService.updateById(znbsf);
        return ye;
    }
}
