package com.hzs.scm.no.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzs.common.core.enums.EYesNo;
import com.hzs.common.core.utils.DateUtils;
import com.hzs.common.domain.scm.no.ScmBillNo;
import com.hzs.scm.no.mapper.ScmBillNoMapper;
import com.hzs.scm.no.service.IScmBillNoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 订单编号规则设置 服务实现类
 */
@Service
public class ScmBillNoServiceImpl extends ServiceImpl<ScmBillNoMapper, ScmBillNo> implements IScmBillNoService {

    @Override
    public ScmBillNo queryScmBillNoByOrderType(Integer orderType) {
        QueryWrapper<ScmBillNo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ORDER_TYPE", orderType);
        List<ScmBillNo> scmBillNoList = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(scmBillNoList)) {
            return scmBillNoList.get(0);
        }
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized String createScmBillNoByOrderType(Integer orderType) {
        ScmBillNo scmBillNo = queryScmBillNoByOrderType(orderType);
        if (scmBillNo == null) {
            throw new RuntimeException("未配置订单编号规则，请配置订单编号规则！");
        }
        StringBuilder billNo = new StringBuilder(scmBillNo.getPrefixCode());
        if (EYesNo.YES.getIntValue() == scmBillNo.getContainYear()) {
            billNo.append(DateUtils.currentYear());
        }
        if (EYesNo.YES.getIntValue() == scmBillNo.getContainYear()) {
            billNo.append(String.format("%02d", DateUtils.currentMonth()));
        }
        if (EYesNo.YES.getIntValue() == scmBillNo.getContainYear()) {
            billNo.append(String.format("%02d", DateUtils.currentDay()));
        }
        billNo.append(String.format("%0" + scmBillNo.getEndDigit() + "d", scmBillNo.getNextValue()));
        baseMapper.updateScmBillNo(scmBillNo);
        // 位数+1
        return billNo.toString();
    }

}
