package com.tofly.third.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.third.common.constant.PjztEnum;
import com.tofly.third.common.constant.SfbzEnum;
import com.tofly.third.common.exception.BusinessException;
import com.tofly.third.common.util.ServerUtil;
import com.tofly.third.entity.YyZjzh;
import com.tofly.third.entity.ZnbCsjsLog;
import com.tofly.third.mapper.YyZjzhMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
public class YyZjzhService extends ServiceImpl<YyZjzhMapper, YyZjzh> {

    @Autowired
    private ZnbCsjsLogService znbCsjsLogService;

    public BigDecimal znbkf(ZnbCsjsLog znbsf, String yhbh) {
        if (SfbzEnum.YSF.getValue().toString().equals(znbsf.getSfbz())) {
            throw new BusinessException("用户已收费");
        }

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

        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;
    }

}
