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

import com.beust.jcommander.internal.Lists;
import com.google.common.base.Strings;
import com.house365.beans.entity.CmHouseCommentEntity;
import com.house365.beans.entity.CmHouseEntity;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.beans.request.CmHouseCommentListRequest;
import com.house365.ws.beans.request.CmHouseCommentRequest;
import com.house365.ws.beans.response.CmHouseCommentListResponse;
import com.house365.ws.beans.response.CmHouseCommentResponse;
import com.house365.ws.interfaces.server.ICmHouseComment;
import com.house365.ws.service.interfaces.ICmHouseCommentService;
import com.house365.ws.service.interfaces.ICmHouseService;
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 org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

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

    /**
     * CmHouseComment服务对象
     */
    @Autowired
    private ICmHouseCommentService<CmHouseCommentEntity> cmHouseCommentService;

    @Autowired
    private ICmHouseService cmHouseService;

    /**
     * CmHouseComment列表查询
     *
     * @param request CmHouseComment列表查询请求
     * @return CmHouseComment列表查询响应
     */
    @Override
    public CmHouseCommentListResponse getCmHouseCommentList(CmHouseCommentListRequest request) {
        CmHouseCommentListResponse response = new CmHouseCommentListResponse();
        try {
            QueryParams<CmHouseCommentEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            queryParams.setOrderColumn(request.getOrderColumn());
            queryParams.setOrderMode(request.getOrderMode());
            List<CmHouseCommentEntity> cmHouseComments = cmHouseCommentService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(cmHouseComments);
            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;
    }

    /**
     * 保存CmHouseComment
     *
     * @param request CmHouseComment请求
     * @return 保存CmHouseComment响应
     */
    @Override
    public CmHouseCommentResponse addCmHouseComment(CmHouseCommentRequest request) {
        CmHouseCommentResponse response = new CmHouseCommentResponse();
        try {
            CmHouseCommentEntity entity = request.getEntity();
            cmHouseCommentService.save(entity);
            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;
    }

    /**
     * 删除CmHouseComment通过唯一标识
     *
     * @param id 唯一标识
     * @return 删除CmHouseComment响应
     */
    @Override
    public CmHouseCommentResponse deleteCmHouseCommentById(Integer id) {
        CmHouseCommentResponse response = new CmHouseCommentResponse();
        try {
            cmHouseCommentService.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;
    }

    /**
     * 修改CmHouseComment
     *
     * @param request 修改CmHouseComment请求
     * @return 修改CmHouseComment响应
     */
    @Override
    public CmHouseCommentResponse updateCmHouseComment(
            CmHouseCommentRequest request
    ) {
        CmHouseCommentResponse response = new CmHouseCommentResponse();
        try {
            cmHouseCommentService.update(request.getEntity());
            //清除楼盘评论缓存
            this.removeCache(request.getEntity().getHouseId());

            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获取CmHouseComment
     *
     * @param id 唯一标识
     * @return 通过ID获取CmHouseComment响应
     */
    @Override
    public CmHouseCommentResponse getCmHouseCommentById(Integer id) {
        CmHouseCommentResponse response = new CmHouseCommentResponse();
        try {
            CmHouseCommentEntity entity = cmHouseCommentService.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
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public House365RestResponse checkHouseComment(String commentIds, String op) throws Exception {
        House365RestResponse restResponse = new House365RestResponse();

        List<String> ids = new ArrayList<>();

        if (commentIds.contains(",")) {
            ids = Lists.newArrayList(commentIds.split(","));
        } else {
            ids.add(commentIds);
        }

        Map<String, CmHouseEntity> houseEntityMap = new HashMap<>();

        for (String cid : ids) {
            CmHouseCommentResponse response = getCmHouseCommentById(Integer.valueOf(cid));

            if (null != response.getEntity()) {
                CmHouseCommentEntity cmHouseCommentEntity = response.getEntity();

                if ("pass".equalsIgnoreCase(op) && cmHouseCommentEntity.getCheckStatus() != 1) {
                    cmHouseCommentEntity.setCheckStatus(1);

                    CmHouseEntity houseEntity = null;
                    if (houseEntityMap.containsKey(cmHouseCommentEntity.getHouseId())) {
                        houseEntity = houseEntityMap.get(cmHouseCommentEntity.getHouseId());
                    } else {
                        houseEntity = (CmHouseEntity) cmHouseService.getById(cmHouseCommentEntity.getHouseId());
                    }

                    Integer commentAmount = houseEntity.getTotolCommetAmount();
                    houseEntity.setTotolCommetAmount(commentAmount + 1);
                    if (!Strings.isNullOrEmpty(cmHouseCommentEntity.getCriticPictures())) {
                        houseEntity.increaseWithPictureCount();
                    }

                    cmHouseService.update(houseEntity);

                    try {
                        cmHouseCommentService.doChangeUserCredit(cmHouseCommentEntity.getId(),
                                cmHouseCommentEntity.getCriticId(),
                                cmHouseCommentEntity.getHouseId());
                    } catch (Exception e) {
                        LOGGER.error(e.getMessage());
                        throw e;
                    }

                } else if ("forbid".equalsIgnoreCase(op) && cmHouseCommentEntity.getCheckStatus() != 2 && cmHouseCommentEntity.getCheckStatus() != 1) {
                    //已审核和未通过的不处理
                    cmHouseCommentEntity.setCheckStatus(2);
                }


                //save after add credit , because checkstatus will be check
                CmHouseCommentRequest commentRequest = new CmHouseCommentRequest();
                commentRequest.setEntity(cmHouseCommentEntity);
                updateCmHouseComment(commentRequest);
            }

        }

        restResponse.setResult("1");
        restResponse.setMsg("success");
        return restResponse;
    }

    @Override
    public Integer deleteHouseComment(String id, String isNoTalk) {
        return cmHouseCommentService.transDeleteHouseComment(id, isNoTalk);
    }

    @Override
    public void removeCache(Integer houseId) {
        cmHouseCommentService.removeCache(houseId);
    }

    /**
     * 以下均为自动生成
     */
    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        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() {
    }

}
