package com.tofly.feesapi.sfgl.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tofly.feesapi.sfgl.entity.YyPjbh;
import com.tofly.feesapi.sfgl.service.YyPjbhService;
import org.springframework.stereotype.Service;
import com.tofly.feesapi.sfgl.mapper.YyPjbhMapper;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.Date;

/**
 * 票据编号表
 */
@Service("yyPjbhService")
public class YyPjbhServiceImpl extends ServiceImpl<YyPjbhMapper, YyPjbh> implements YyPjbhService {

    @Override
    public String getPjh(String sfrybm) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Date now = new Date();
        String date = sdf.format(now);

        long count = this.count(
                new QueryWrapper<YyPjbh>().lambda()
                        .eq(YyPjbh::getCwrq, date)
                        .eq(YyPjbh::getSfrybm, sfrybm)
        );

        if (count == 0) {
            YyPjbh yyPjbh = new YyPjbh();
            yyPjbh.setCwrq(date);
            yyPjbh.setSfrybm(BigDecimal.valueOf(Long.parseLong(sfrybm)));
            yyPjbh.setPjh(BigDecimal.ONE);
            this.save(yyPjbh);
            return sfrybm + "" + date + String.format("%04d", BigDecimal.ONE.intValue());
        } else {
            YyPjbh yyPjbh = this.getOne(new QueryWrapper<YyPjbh>().lambda()
                    .eq(YyPjbh::getCwrq, date)
                    .eq(YyPjbh::getSfrybm, sfrybm));
            yyPjbh.setPjh(yyPjbh.getPjh().add(BigDecimal.ONE));
            this.updateById(yyPjbh);
            return sfrybm + "" + date + String.format("%04d", yyPjbh.getPjh().intValue());
        }
    }

}
