package com.patzn.lims.res.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.patzn.lims.core.api.PtAssert;
import com.patzn.lims.core.web.BaseServiceImpl;
import com.patzn.lims.res.entity.LmsCodeRule;
import com.patzn.lims.res.entity.LmsCodeRuleRecord;
import com.patzn.lims.res.mapper.LmsCodeRuleRecordMapper;
import com.patzn.lims.res.service.ILmsCodeRuleRecordService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 编号规则记录 服务实现类
 * </p>
 *
 * @author patzn
 * @since 2018-06-06
 */
@Service
public class LmsCodeRuleRecordServiceImpl extends BaseServiceImpl<LmsCodeRuleRecordMapper, LmsCodeRuleRecord> implements ILmsCodeRuleRecordService {


    @Override
    public int getNextSn(LmsCodeRule codeRule, String vary) {
        Long codeRuleId = codeRule.getId();
        LmsCodeRuleRecord codeRuleRecord = null;
        if (StringUtils.isBlank(codeRule.getIgnoreNum())) {
            codeRuleRecord = baseMapper.selectOne(Wrappers.query(new LmsCodeRuleRecord().setCodeRuleId(codeRuleId).setVary(vary)));
        } else {
            try {
                String ignoreNum = codeRule.getIgnoreNum();
                String[] ignores = ignoreNum.split(",");
                for (String i : ignores) {
                    vary = deleteIndexChar(vary, Integer.parseInt(i));
                }
                codeRuleRecord = baseMapper.selectOne(Wrappers.query(new LmsCodeRuleRecord().setCodeRuleId(codeRuleId).setVary(vary)));
            } catch (Exception e) {

                PtAssert.fail("编号生成失败，请联系管理员");
            }


        }


        if (null == codeRuleRecord) {
            LmsCodeRuleRecord crr = new LmsCodeRuleRecord();
            crr.setCodeRuleId(codeRuleId);
            crr.setSn(1);
            crr.setVary(vary);
            if (super.save(crr)) {
                return 1;
            }
        }
        // 获取下一个序列号
        return this.nextSn(codeRuleRecord.getId(), codeRuleRecord.getSn());
    }


    /**
     * <p>
     * 下一个 SN
     * </p>
     *
     * @param id 主键 ID
     * @param sn 序列号
     * @return
     */
    private int nextSn(long id, int sn) {
        int next = sn + 1;
        LmsCodeRuleRecord crr = new LmsCodeRuleRecord();
        crr.setSn(next);
        if (!super.update(crr, Wrappers.<LmsCodeRuleRecord>query().eq("id", id).eq("sn", sn))) {
            // 重复递归寻找可用序列
            next = this.nextSn(id, next);
        }
        return next;
    }


    public static String deleteIndexChar(String str, int index) {
        if (StringUtils.isBlank(str)) {
            return str;
        }

        StringBuilder sb = new StringBuilder();
        int length = str.length();

        for (int j = 0; j < length; j++) {
            if (j != index) {
                sb.append(str.charAt(j));

            }
        }
        return sb.toString();
    }


}
