package com.testor.ddd.functionConfiguration.domain.tableNum.service.impl;

import cn.hutool.core.util.StrUtil;
import com.testor.ddd.functionConfiguration.domain.tableNum.entity.TTableNumRepo;
import com.testor.ddd.functionConfiguration.domain.tableNum.service.TableNumService;
import com.testor.ddd.functionConfiguration.infrastructure.repository.tableNum.entity.TTableNumDO;
import com.tongtech.tfw.backend.common.biz.models.BaseResponse;
import com.tongtech.tfw.backend.common.constants.enumeration.BaseStatusEnum;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class TableNumServiceImpl implements TableNumService {

    @Resource
    private TTableNumRepo tableNumRepo;

    public Integer obtainMaxNum(String tableName, String fieldName){

        List<TTableNumDO> tableNumDOList = tableNumRepo.findList(tableName, fieldName);
        if(tableNumDOList == null || tableNumDOList.size()==0) {
            return 0;
        }
        TTableNumDO tableNumDo = tableNumDOList.get(0);
        return tableNumDo.getNum();
    }

    public BaseResponse saveMaxNum(String tableName, String fieldName, Integer maxNum){
        BaseResponse baseResponse = new BaseResponse<>();
        if(StrUtil.isBlank(tableName) || StrUtil.isBlank(fieldName) || maxNum == null) {
            baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
            baseResponse.setMsg("参数缺失");
            return baseResponse;
        }

        List<TTableNumDO> tableNumDOList = tableNumRepo.findList(tableName, fieldName);
        TTableNumDO tableNumDO;
        boolean result;
        if(tableNumDOList == null || tableNumDOList.size() == 0) {
            result = tableNumRepo.saveTableNum(tableName, fieldName, maxNum);
        } else {
            tableNumDO = tableNumDOList.get(0);
            if(maxNum <= tableNumDO.getNum()) {
                baseResponse.setCode(BaseStatusEnum.UN_DATA.code());
                baseResponse.setMsg("保存失败，已存在的数值大于传入的数值！");
                return baseResponse;
            }
            tableNumDO.setNum(maxNum);
            result = tableNumRepo.updateTableNumByEntity(tableNumDO);
        }

        if(result) {
            baseResponse.setCode(BaseStatusEnum.SUCCESS.code());
            return baseResponse;
        }
        baseResponse.setCode(BaseStatusEnum.UNKNOWN.code());
        baseResponse.setMsg("操作失败");
        return baseResponse;

    }
}
