package ${basePackage}.module.system.mgr;

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


/**
 * PROFILES - 系统配置
 *
 * @author author
 * @version 0.0.1
 * @since 2020-05-24
 */
@Transactional
@Service
public class ProfilesManagerImpl implements 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.setActive(request.getActive());
            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, "[" + request.getKey() + "]键已存在，请检查!");
                return response;
            }
        }

        long id = IDgenerator.nextId();
        Profiles entity = MapperUtil.map(request, 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;
        }

        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<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;
    }
}
