package cn.stylefeng.team.project.modular.maxsort.biz;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.stylefeng.roses.kernel.rule.exception.base.ServiceException;
import cn.stylefeng.team.project.api.SystemCodeApi;
import cn.stylefeng.team.project.api.constants.ProjectConstants;
import cn.stylefeng.team.project.api.enums.SystemCodeTypeEnum;
import cn.stylefeng.team.project.api.exception.enums.ProjectExceptionEnum;
import cn.stylefeng.team.project.api.pojo.SystemCodeInfo;
import cn.stylefeng.team.project.api.util.Base25Util;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class SystemCodeService implements SystemCodeApi {

    private static final String SELECT_MAX_SYS_CODE = "select system_code from {} order by system_code desc limit 0,1;";

    @Override
    public SystemCodeInfo createNewSystemCode(SystemCodeTypeEnum systemCodeTypeEnum) {

        String tableName = systemCodeTypeEnum.getTableName();
        String appCode = systemCodeTypeEnum.getAppCode();

        String finalSql = StrUtil.format(SELECT_MAX_SYS_CODE, tableName);

        Map<String, Object> result = SqlRunner.db().selectOne(finalSql);

        if (result == null) {
            return zeroReturn(appCode);
        }

        Object sysCodeInteger = result.get("system_code");
        if (sysCodeInteger != null) {
            int sysCodeNumber = Convert.toInt(sysCodeInteger) + 1;
            String encodeNumber = Base25Util.encode(sysCodeNumber);
            return new SystemCodeInfo(ProjectConstants.SYSTEM_CODE_PREFIX + appCode + "-" + encodeNumber, sysCodeNumber);
        }

        return zeroReturn(appCode);
    }

    @Override
    public void validateSystemCodeShow(SystemCodeTypeEnum systemCodeTypeEnum, int systemCode, String systemCodeShow) {
        String appCode = systemCodeTypeEnum.getAppCode();
        String encodeNumber = Base25Util.encode(systemCode);
        String systemCodeShowFinal = ProjectConstants.SYSTEM_CODE_PREFIX + appCode + "-" + encodeNumber;
        if (!systemCodeShowFinal.equals(systemCodeShow)) {
            throw new ServiceException(ProjectExceptionEnum.SYS_CODE_ERROR);
        }
    }

    @Override
    public SystemCodeInfo addNumber(SystemCodeTypeEnum systemCodeTypeEnum, int originSystemCodeNumber, int addNumber) {
        int resultNumber = originSystemCodeNumber + addNumber;
        String encodeNumber = Base25Util.encode(resultNumber);
        return new SystemCodeInfo(ProjectConstants.SYSTEM_CODE_PREFIX + systemCodeTypeEnum.getAppCode() + "-" + encodeNumber, resultNumber);
    }

    private SystemCodeInfo zeroReturn(String appCode) {
        String zeroEncode = Base25Util.encode(1);
        return new SystemCodeInfo(ProjectConstants.SYSTEM_CODE_PREFIX + appCode + "-" + zeroEncode, 1);
    }

}
