package ${domain}.module.wsvr.mgr;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ${domain}.frame.auth.LocalData;
import ${domain}.frame.auth.Token;
import ${domain}.frame.base.ErrorType;
import ${domain}.frame.utils.IDgenerator;
import ${domain}.frame.utils.MapperUtil;
import ${domain}.frame.utils.Message;
import ${domain}.frame.utils.ValidationUtil;
import ${domain}.module.wsvr.mpr.ProfilesMapper;
import ${domain}.module.wsvr.req.ProfilesCreateRequest;
import ${domain}.module.wsvr.req.ProfilesDeleteRequest;
import ${domain}.module.wsvr.req.ProfilesFindRequest;
import ${domain}.module.wsvr.req.ProfilesUpdateRequest;
import ${domain}.module.wsvr.rsp.ProfilesCreateResponse;
import ${domain}.module.wsvr.rsp.ProfilesDeleteResponse;
import ${domain}.module.wsvr.rsp.ProfilesFindResponse;
import ${domain}.module.wsvr.rsp.ProfilesUpdateResponse;

/**
 * PROFILES - 系统配置
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2020-07-06
 */
@Transactional
@Service
public class ProfilesManagerImpl implements ${domain}.module.wsvr.mgr.ProfilesManager {

    @Autowired
    private ProfilesMapper profilesMapper;

    /**
     * 插入
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public ProfilesCreateResponse create(ProfilesCreateRequest request, Token token) {
        ProfilesCreateResponse response = new ProfilesCreateResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        {// 配置键唯一检查
            ProfilesFindRequest profilesFindRequest = new ProfilesFindRequest();
            profilesFindRequest.setKey(request.getKey());
            ProfilesFindResponse profilesFindResponse = this.find(profilesFindRequest, token);
            if (profilesFindResponse.hasError()) {
                response.addErrors(profilesFindResponse.getErrors());
                return response;
            } else if (profilesFindResponse.getTotalCount() > 0) {
                response.addError(ErrorType.UNIQUENESS_ERROR, "[key]配置键已存在，请检查!");
                return response;
            }
        }

        long id = IDgenerator.nextId();
        ${domain}.module.wsvr.ent.Profiles entity = MapperUtil.map(request, ${domain}.module.wsvr.ent.Profiles.class);
        entity.setId(id);

        long result = profilesMapper.insert(entity, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.CREATE_FAILURE);
            return response;
        }
        response.setId(id);

        return response;
    }

    /**
     * 逻辑删除
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public ProfilesDeleteResponse delete(ProfilesDeleteRequest request, Token token) {
        ProfilesDeleteResponse response = new ProfilesDeleteResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        long result = profilesMapper.delete(request.getId(), token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.DELETE_FAILURE);
            return response;
        }
        response.setResult(result);

        return response;
    }

    /**
     * 更新
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public ProfilesUpdateResponse update(ProfilesUpdateRequest request, Token token) {
        ProfilesUpdateResponse response = new ProfilesUpdateResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        ${domain}.module.wsvr.ent.Profiles entity = profilesMapper.getById(request.getId(), token);
        if (entity == null) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.GET_FAILURE);
            return response;
        }

        MapperUtil.map(request, entity);
        long result = profilesMapper.update(entity, token);
        if (1L != result) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.UPDATE_FAILURE);
            return response;
        }
        response.setResult(result);

        return response;
    }

    /**
     * 查询
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    @Transactional(readOnly = true)
    public ProfilesFindResponse find(ProfilesFindRequest request, Token token) {
        ProfilesFindResponse response = new ProfilesFindResponse();

        ValidationUtil.validate(request, response);
        if (response.hasError()) {
            return response;
        }

        if (request.getPageSize() != 0) {
            PageHelper.startPage(request.getPageNumber(), request.getPageSize());
        }
        if (StringUtil.isNotEmpty(request.getSortKey())) {
            PageHelper.orderBy(request.getSortKey() + " " + request.getSortType());
        }
        PageInfo<${domain}.module.wsvr.ent.Profiles> pageInfo = new PageInfo<>(profilesMapper.find(request, token));

        response.setResult(pageInfo.getList());
        response.setTotalCount(pageInfo.getTotal());

        return response;
    }

    /**
     * 获得当前环境配置
     *
     * @param key          键
     * @param defaultValue 默认值
     * @return
     */
    @Override
    public String getString(String key, String defaultValue) {
        ProfilesFindRequest profilesFindRequest = new ProfilesFindRequest();
        profilesFindRequest.setActive(LocalData.getActive());
        profilesFindRequest.setKey(key);
        ProfilesFindResponse profilesFindResponse = this.find(profilesFindRequest, LocalData.getSysToken());
        if (profilesFindResponse.hasError() || profilesFindResponse.getResult().size() == 0) {
            return defaultValue;
        }

        return profilesFindResponse.getResult().get(0).getValue();
    }

    /**
     * 获得当前环境配置
     *
     * @param key          键
     * @param defaultValue 默认值
     * @return
     */
    @Override
    public int getInt(String key, int defaultValue) {
        String string = this.getString(key, "");
        if (!StringUtil.isEmpty(string)) {
            try {
                return Integer.parseInt(string);
            } catch (Exception ignored) {

            }
        }
        return defaultValue;
    }

    /**
     * 获得当前环境配置
     *
     * @param key          键
     * @param defaultValue 默认值
     * @return
     */
    @Override
    public long getLong(String key, long defaultValue) {
        String string = this.getString(key, "");
        if (!StringUtil.isEmpty(string)) {
            try {
                return Long.parseLong(string);
            } catch (Exception ignored) {

            }
        }
        return defaultValue;
    }
}
