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 ${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.Dict;
import ${basePackage}.module.system.mpr.DictMapper;
import ${basePackage}.module.system.req.DictCreateRequest;
import ${basePackage}.module.system.req.DictDeleteRequest;
import ${basePackage}.module.system.req.DictFindRequest;
import ${basePackage}.module.system.req.DictGetRequest;
import ${basePackage}.module.system.req.DictItemFindRequest;
import ${basePackage}.module.system.req.DictLoadRequest;
import ${basePackage}.module.system.req.DictUpdateRequest;
import ${basePackage}.module.system.rsp.DictCreateResponse;
import ${basePackage}.module.system.rsp.DictDeleteResponse;
import ${basePackage}.module.system.rsp.DictFindResponse;
import ${basePackage}.module.system.rsp.DictGetResponse;
import ${basePackage}.module.system.rsp.DictItemFindResponse;
import ${basePackage}.module.system.rsp.DictLoadResponse;
import ${basePackage}.module.system.rsp.DictUpdateResponse;

import java.util.List;

/**
 * DICT - 字典
 *
 * @author wangbing
 * @version 0.0.1
 * @since 2017-01-01
 */
@Transactional
@Service
public class DictManagerImpl implements DictManager {

    @Autowired
    private DictMapper dictMapper;

    @Autowired
    private DictItemManager dictItemManager;

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

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

        {// 检查字典名称是否重复
            DictFindRequest dictFindRequest = new DictFindRequest();
            dictFindRequest.setDictName(request.getDictName());
            DictFindResponse dictFindResponse = this.find(dictFindRequest, token);
            if (dictFindResponse.hasError()) {
                response.addErrors(dictFindResponse.getErrors());
                return response;
            } else if (dictFindResponse.getTotalCount() > 0) {
                response.addError(ErrorType.BUSINESS_ERROR, "字典名称重复");
                return response;
            }
        }

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

        long result = dictMapper.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 DictDeleteResponse delete(DictDeleteRequest request, Token token) {
        DictDeleteResponse response = new DictDeleteResponse();

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

        long result = dictMapper.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 DictUpdateResponse update(DictUpdateRequest request, Token token) {
        DictUpdateResponse response = new DictUpdateResponse();

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

        long result = dictMapper.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 DictFindResponse find(DictFindRequest request, Token token) {
        DictFindResponse response = new DictFindResponse();

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

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

        return response;
    }

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

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

        Dict po = dictMapper.get(request, token);

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

        return response;
    }

    @Override
    public DictLoadResponse load(DictLoadRequest request, Token token) {
        DictLoadResponse response = new DictLoadResponse();

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

        DictFindRequest dictFindRequest = new DictFindRequest();
        dictFindRequest.setDictName(request.getDictName());
        dictFindRequest.setValid(true);
        List<Dict> dicts = dictMapper.find(dictFindRequest, token);
        if (dicts.size() == 0) {
            response.addError(ErrorType.BUSINESS_ERROR, "[" + request.getDictName() + "]字典不存在");
            return response;
        } else if (dicts.size() > 1) {
            response.addError(ErrorType.BUSINESS_ERROR, "字典重复异常，请联系管理员");
            return response;
        }
        response.setDict(dicts.get(0));

        DictItemFindRequest dictItemFindRequest = new DictItemFindRequest();
        dictItemFindRequest.setDictName(request.getDictName());
        dictItemFindRequest.setValid(true);
        dictItemFindRequest.setPageSize(0);
        DictItemFindResponse dictItemFindResponse = dictItemManager.find(dictItemFindRequest, token);
        if (dictItemFindResponse.hasError()) {
            response.addErrors(dictItemFindResponse.getErrors());
            return response;
        }
        response.setDictItems(dictItemFindResponse.getResult());
        return response;
    }
}
