package xyz.wbsite.module.admin.mgr;

import xyz.wbsite.frame.utils.IDgenerator;
import xyz.wbsite.frame.utils.Message;
import xyz.wbsite.frame.base.ErrorType;
import xyz.wbsite.frame.base.Token;
import xyz.wbsite.frame.utils.MapperUtil;
import xyz.wbsite.frame.utils.ValidationUtil;
import xyz.wbsite.module.admin.ent.Rules;
import xyz.wbsite.module.admin.mpr.RulesMapper;
import xyz.wbsite.module.admin.req.RulesCreateRequest;
import xyz.wbsite.module.admin.req.RulesDeleteRequest;
import xyz.wbsite.module.admin.req.RulesFindRequest;
import xyz.wbsite.module.admin.req.RulesUpdateRequest;
import xyz.wbsite.module.admin.rsp.RulesCreateResponse;
import xyz.wbsite.module.admin.rsp.RulesDeleteResponse;
import xyz.wbsite.module.admin.rsp.RulesFindResponse;
import xyz.wbsite.module.admin.rsp.RulesUpdateResponse;
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;

/**
 * RULES - 配置规则
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2021-02-08
 */
@Transactional
@Service
public class RulesManagerImpl implements RulesManager {

    @Autowired
    private RulesMapper rulesMapper;

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

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

        {// 规则目标唯一检查
            RulesFindRequest rulesFindRequest = new RulesFindRequest();
            rulesFindRequest.setRuleFor(request.getRuleFor());
            RulesFindResponse rulesFindResponse = this.find(rulesFindRequest, token);
            if (rulesFindResponse.hasError()) {
                response.addErrors(rulesFindResponse.getErrors());
                return response;
            } else if (rulesFindResponse.getTotalCount() > 0) {
                response.addError(ErrorType.UNIQUENESS_ERROR, "[ruleFor]规则目标已存在，请检查!");
                return response;
            }
        }

        {// 规则名称唯一检查
            RulesFindRequest rulesFindRequest = new RulesFindRequest();
            rulesFindRequest.setRuleName(request.getRuleName());
            RulesFindResponse rulesFindResponse = this.find(rulesFindRequest, token);
            if (rulesFindResponse.hasError()) {
                response.addErrors(rulesFindResponse.getErrors());
                return response;
            } else if (rulesFindResponse.getTotalCount() > 0) {
                response.addError(ErrorType.UNIQUENESS_ERROR, "[ruleName]规则名称已存在，请检查!");
                return response;
            }
        }

        long id = IDgenerator.nextId();
        Rules entity = MapperUtil.map(request, Rules.class);
        entity.setId(id);

        long result = rulesMapper.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 RulesDeleteResponse delete(RulesDeleteRequest request, Token token) {
        RulesDeleteResponse response = new RulesDeleteResponse();

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

        long result = rulesMapper.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 RulesUpdateResponse update(RulesUpdateRequest request, Token token) {
        RulesUpdateResponse response = new RulesUpdateResponse();

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

        Rules entity = rulesMapper.getById(request.getId(), token);
        if (entity == null) {
            response.addError(ErrorType.BUSINESS_ERROR, Message.GET_FAILURE);
            return response;
        }

        MapperUtil.map(request, entity);
        long result = rulesMapper.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 RulesFindResponse find(RulesFindRequest request, Token token) {
        RulesFindResponse response = new RulesFindResponse();

        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<Rules> pageInfo = new PageInfo<>(rulesMapper.find(request, token));

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

        return response;
    }
}
