package ${basePackage}.module.system.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 org.springframework.transaction.interceptor.TransactionAspectSupport;
import ${basePackage}.frame.base.ErrorType;
import ${basePackage}.frame.auth.Token;
import ${basePackage}.frame.utils.IDgenerator;
import ${basePackage}.frame.utils.MapperUtil;
import ${basePackage}.frame.utils.Message;
import ${basePackage}.frame.utils.ValidationUtil;
import ${basePackage}.module.system.ent.RoleRes;
import ${basePackage}.module.system.mpr.RoleResMapper;
import ${basePackage}.module.system.req.RoleResCheckRequest;
import ${basePackage}.module.system.req.RoleResCreateRequest;
import ${basePackage}.module.system.req.RoleResDeleteRequest;
import ${basePackage}.module.system.req.RoleResFindRequest;
import ${basePackage}.module.system.req.RoleResGetRequest;
import ${basePackage}.module.system.req.RoleResUpdateRequest;
import ${basePackage}.module.system.rsp.RoleResCheckResponse;
import ${basePackage}.module.system.rsp.RoleResCreateResponse;
import ${basePackage}.module.system.rsp.RoleResDeleteResponse;
import ${basePackage}.module.system.rsp.RoleResFindResponse;
import ${basePackage}.module.system.rsp.RoleResGetResponse;
import ${basePackage}.module.system.rsp.RoleResUpdateResponse;

/**
 * ROLE_RES - 角色资源关系
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2017-01-01
 */
@Transactional
@Service
public class RoleResManagerImpl implements RoleResManager {

    @Autowired
    private RoleResMapper roleResMapper;

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

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

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

        long result = roleResMapper.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 RoleResDeleteResponse delete(RoleResDeleteRequest request, Token token) {
        RoleResDeleteResponse response = new RoleResDeleteResponse();

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

        long result = roleResMapper.delete(request, 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 RoleResUpdateResponse update(RoleResUpdateRequest request, Token token) {
        RoleResUpdateResponse response = new RoleResUpdateResponse();

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

        long result = roleResMapper.update(request, 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 RoleResFindResponse find(RoleResFindRequest request, Token token) {
        RoleResFindResponse response = new RoleResFindResponse();

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

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

        return response;
    }

    /**
     * 获得对象
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    @Transactional(readOnly = true)
    public RoleResGetResponse get(RoleResGetRequest request, Token token) {
        RoleResGetResponse response = new RoleResGetResponse();

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

        RoleRes po = roleResMapper.get(request, token);

        if (po != null) {
            response.setRoleRes(po);
        } else {
            response.addError(ErrorType.BUSINESS_ERROR, Message.GET_FAILURE);
        }

        return response;
    }

    /**
     * 选中或取消资源
     *
     * @param request 请求对象
     * @param token   令牌
     * @return 响应
     */
    public RoleResCheckResponse check(RoleResCheckRequest request, Token token) {
        RoleResCheckResponse response = new RoleResCheckResponse();

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

        RoleResFindRequest roleResFindRequest = new RoleResFindRequest();
        roleResFindRequest.setRoleId(request.getRoleId());
        roleResFindRequest.setResId(request.getResId());
        RoleResFindResponse roleResFindResponse = this.find(roleResFindRequest, token);
        if (roleResFindResponse.hasError()) {
            response.addErrors(roleResFindResponse.getErrors());
            return response;
        }

        if (request.getChecked() && roleResFindResponse.getResult().size() == 0) {
            RoleResCreateRequest roleResCreateRequest = new RoleResCreateRequest();
            roleResCreateRequest.setRoleId(request.getRoleId());
            roleResCreateRequest.setRoleCode(request.getRoleCode());
            roleResCreateRequest.setResId(request.getResId());
            roleResCreateRequest.setResCode(request.getResCode());
            RoleResCreateResponse roleResCreateResponse = this.create(roleResCreateRequest, token);
            if (roleResCreateResponse.hasError()) {
                response.addErrors(roleResCreateResponse.getErrors());
                return response;
            }
        } else if (!request.getChecked() && roleResFindResponse.getResult().size() > 0) {
            for (RoleRes roleRes : roleResFindResponse.getResult()) {
                RoleResDeleteRequest roleResDeleteRequest = new RoleResDeleteRequest();
                roleResDeleteRequest.setId(roleRes.getId());
                RoleResDeleteResponse roleResDeleteResponse = this.delete(roleResDeleteRequest, token);
                if (roleResDeleteResponse.hasError()) {
                    response.addErrors(roleResDeleteResponse.getErrors());
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return response;
                }
            }
        }

        return response;
    }
}
