/**
 * Description: BaseTreeWS接口
 * Copyright:   Copyright (c)2017
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2017-12-08 下午 15:16:07
 * <p>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2017-12-08   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.interfaces.impl;

import com.google.common.base.Strings;
import com.house365.beans.entity.BaseTreeEntity;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.ws.beans.request.BaseTreeListRequest;
import com.house365.ws.beans.request.BaseTreeRequest;
import com.house365.ws.beans.response.BaseTreeListResponse;
import com.house365.ws.beans.response.BaseTreeResponse;
import com.house365.ws.interfaces.server.IBaseTree;
import com.house365.ws.service.interfaces.IBaseTreeService;
import com.house365.ws.service.interfaces.IHgsCacheUtil;
import com.house365.ws.system.ReturnResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.house365.rest.context.AppConstant.STATUS_DELETE;

/**
 * BaseTreeWS接口<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2017-12-08
 * @see
 * @since 1.0
 */
@Service("baseTree")
public class BaseTreeImpl implements IBaseTree {
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BaseTreeImpl.class);

    /**
     * BaseTree服务对象
     */
    @Autowired
    IBaseTreeService<BaseTreeEntity> baseTreeService;
    @Autowired
    private IHgsCacheUtil hgsCacheUtil;

    /**
     * BaseTree列表查询
     *
     * @param request BaseTree列表查询请求
     * @return BaseTree列表查询响应
     */
    @Override
    public BaseTreeListResponse getBaseTreeList(BaseTreeListRequest request) {
        BaseTreeListResponse response = new BaseTreeListResponse();
        try {
            QueryParams<BaseTreeEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<BaseTreeEntity> baseTrees = baseTreeService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(baseTrees);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 保存BaseTree
     *
     * @param request BaseTree请求
     * @return 保存BaseTree响应
     */
    @Override
    public BaseTreeResponse addBaseTree(BaseTreeRequest request) {
        BaseTreeResponse response = new BaseTreeResponse();
        try {
            BaseTreeEntity entity = request.getEntity();
            Integer id = baseTreeService.save(entity);
            hgsCacheUtil.delChildTreeCache(id);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 删除BaseTree通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除BaseTree响应
     */
    @Override
    public BaseTreeResponse deleteBaseTreeById(Integer id) {
        BaseTreeResponse response = new BaseTreeResponse();
        try {
            hgsCacheUtil.delChildTreeCache(id);
            BaseTreeEntity result = baseTreeService.getById(id);
            result.setStatus(STATUS_DELETE);
            baseTreeService.update(result);
            //            baseTreeService.delete(id);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 修改BaseTree
     *
     * @param request 修改BaseTree请求
     * @return 修改BaseTree响应
     */
    @Override
    public BaseTreeResponse updateBaseTree(BaseTreeRequest request) {
        BaseTreeResponse response = new BaseTreeResponse();
        try {
            hgsCacheUtil.delChildTreeCache(request.getEntity().getId());
            baseTreeService.update(request.getEntity());
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    /**
     * 通过ID获取BaseTree
     *
     * @param id 唯一标识
     * @return 通过ID获取BaseTree响应
     */
    @Override
    public BaseTreeResponse getBaseTreeById(Integer id) {
        BaseTreeResponse response = new BaseTreeResponse();
        try {
            BaseTreeEntity entity = baseTreeService.getById(id);
            response.setEntity(entity);
            response.setResultCode(ReturnResult.SUCCESS.getResultCode());
            response.setResultMessage(ReturnResult.SUCCESS.getResultMessage());
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            response.setResultCode(ReturnResult.FAIL.getResultCode());
            response.setResultMessage(ex.getMessage());
        }
        return response;
    }

    @Override
    public List<BaseTreeEntity> findRootAndChild() {
        BaseTreeEntity treeEntity = getRoot();
        List<BaseTreeEntity> treeEntities = null;
        if (treeEntity != null) {
            treeEntities = findChildByParentId(treeEntity.getId());
        }
        return treeEntities;
    }

    @Override
    public BaseTreeEntity getRoot() {
        return baseTreeService.getById(0);
    }

    @Override
    public BaseTreeEntity getRootBySourceType(String sourceType) {
        BaseTreeEntity root = null;
        Page page = new Page(1);
        Map<String, Object> map = new HashMap<>();
        map.put("EQ_hierarchy", 0);
        QueryParams<BaseTreeEntity> queryParams = new QueryParams<>(map);
        queryParams.setPaging(page);
        List<BaseTreeEntity> all = baseTreeService.queryAll(queryParams);
        if (!all.isEmpty()) {
            root = all.get(0);
        }
        return root;
    }

    @Override
    public void updateUrlPath(Integer parentId) {
        BaseTreeEntity parent = baseTreeService.getById(parentId);
        List<BaseTreeEntity> childList = findChildByParentId(parentId);
        if (childList.isEmpty()) {
            return;
        }
        for (BaseTreeEntity node : childList) {
            if (Strings.isNullOrEmpty(node.getUrlPath())) {
                node.setUrlPath(parent.getUrlPath() + "/" + node.getId());
                baseTreeService.update(node);
            }
            updateUrlPath(node.getId());
        }
    }

    @Override
    public List findChildrenListByPath(List parents) {
        return baseTreeService.findChildrenListByPath(parents);
    }

    @Override
    public List<BaseTreeEntity> findChildByParentId(int parentId) {
        BaseTreeEntity parent = baseTreeService.getById(parentId);
        if (parent != null) {
            Page page = new Page(Integer.MAX_VALUE);
            Map<String, Object> map = new HashMap<>();
            map.put("EQ_parentId", parent.getSourceId());
            if (parentId != 0) {
                map.put("EQ_sourceType", parent.getSourceType());
            }
            QueryParams<BaseTreeEntity> queryParams = new QueryParams<>(map);
            queryParams.setPaging(page);
            queryParams.setSearchParams(map);
            List<BaseTreeEntity> all = baseTreeService.queryAll(queryParams);
            return all;
        }

        return new ArrayList<>();
    }

    @Override
    public BaseTreeEntity appendChild(Integer parentId, BaseTreeEntity child) throws Exception {
        BaseTreeEntity parent = baseTreeService.getById(parentId);
        hgsCacheUtil.delChildTreeCache(parentId);
        QueryParams<BaseTreeEntity> queryParams = new QueryParams<>();
        queryParams.setPaging(new Page(Integer.MAX_VALUE));
        Map<String, Object> map = new HashMap<>();
        map.put("EQ_parentId", parent);
        queryParams.setSearchParams(map);
        List<BaseTreeEntity> brothers = baseTreeService.queryByPage(queryParams);
        int orderNum = 1;
        if (brothers.size() > 0) {
            for (BaseTreeEntity entity : brothers) {
                if (entity.getOrderNum() > orderNum) {
                    orderNum = entity.getOrderNum();
                }
            }
        }
        child.setOrderNum(orderNum);
        child.setParentId(parent.getId());
        child.setHierarchy(parent.getHierarchy() + 1);
        Integer id = baseTreeService.save(child);
        child.setSourceId(String.valueOf(id));
        child.setSourceType(parent.getSourceType());
        child.setUrlPath(parent.getUrlPath() + "/" + id);
        baseTreeService.update(child);
        return child;
    }

    /**
     * 以下均为自动生成
     */
    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {
    }


}
