/**
 * Description: CmHouseCommentReply业务实现类
 * Copyright:   Copyright (c)2015
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2015-08-11 上午 09:31:50
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2015-08-11   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.ws.service.impl;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmDictionaryEntity;
import com.house365.beans.entity.CmHouseCommentEntity;
import com.house365.beans.entity.CmHouseCommentReplyEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.system.QueryParams;
import com.house365.dao.system.interfaces.Dao;
import com.house365.rest.context.CmConstant;
import com.house365.rest.parameter.House365RestObject;
import com.house365.service.system.impl.DefaultServiceImpl;
import com.house365.ws.beans.response.CmDictionaryResponse;
import com.house365.ws.dao.interfaces.ICmHouseCommentDao;
import com.house365.ws.dao.interfaces.ICmHouseCommentReplyDao;
import com.house365.ws.dao.interfaces.ICmUserDao;
import com.house365.ws.interfaces.server.ICmDictionary;
import com.house365.ws.service.interfaces.ICmHouseCommentReplyService;
import com.house365.ws.service.interfaces.ICmHouseCommentService;
import com.house365.ws.service.interfaces.ICmUserService;
import com.house365.ws.util.CmCommonUtils;
import org.apache.commons.collections.CollectionUtils;
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 org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * CmHouseCommentReply业务实现类<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-11
 * @see
 * @since 1.0
 */
@Service("cmHouseCommentReplyService")
public class CmHouseCommentReplyServiceImpl<T extends CmHouseCommentReplyEntity> extends DefaultServiceImpl<T> implements ICmHouseCommentReplyService<T> {

    private static final Logger LOGGER = LoggerFactory.getLogger("InterfaceLog");

    /**
     * 自动注入的数据访问对象
     */
    @Autowired
    private ICmHouseCommentReplyDao<T> cmHouseCommentReplyDao;

    @Autowired
    private ICmHouseCommentDao<CmHouseCommentEntity> houseCommentDao;
    @Autowired
    private ICmUserDao<CmUserEntity> userDao;
    @Autowired
    private ICmUserService<CmUserEntity> cmUserService;

    @Autowired
    private ICmHouseCommentService cmHouseCommentService;

    @Autowired
    private ICmDictionary cmDictionary;

    @Override
    protected Dao<T> getDao() {
        return cmHouseCommentReplyDao;
    }

    @Override
    public House365RestObject<CmHouseCommentReplyEntity> transHouseCommentReply(Map<String, Object> map) {

        House365RestObject<CmHouseCommentReplyEntity> resultObj = new House365RestObject<>();
        // 楼盘评论Id
        String commentId = null;
        // 回复内容
        String replyContent = null;

        // 城市key
        String cityKey = null;
        int source = 0;
        try {
            CmHouseCommentReplyEntity entity = new CmHouseCommentReplyEntity();

            if (!StringUtils.isEmpty(map.get(CmConstant.COMMENTID))) {
                commentId = ((String[]) map.get(CmConstant.COMMENTID))[0];
            }
            if (!StringUtils.isEmpty(map.get("replyContent"))) {
                replyContent = ((String[]) map.get("replyContent"))[0];
            }
            if (!StringUtils.isEmpty(map.get(CmConstant.CITY_KEY))) {
                cityKey = ((String[]) map.get(CmConstant.CITY_KEY))[0];
            }

            if (!StringUtils.isEmpty(map.get("source"))) {
                source = Integer.parseInt(((String[]) map.get("source"))[0]);
                entity.setSource(source);
            }
            CmUserEntity userEntity = cmUserService.registUserByUserId(map);

            if (userEntity == null) {
                resultObj.setTotal("3");
                return resultObj;
            }

            CmDictionaryResponse forbidCityResponse = cmDictionary.getCmDictionaryById(16);
            boolean needCheck = false;
            String cityList = "";
            if (null != forbidCityResponse.getEntity()) {
                CmDictionaryEntity dictionaryEntity = forbidCityResponse.getEntity();
                cityList = "," + dictionaryEntity.getDicValue() + ",";

            }

            //保存city值
            cmUserService.update(userEntity);

            entity.setCriticId(userEntity.getId());
            //如果用户名为空，则存用户手机号码
            if (userEntity.getUserName() != null && (!userEntity.getUserName().trim().equals(""))) {
                entity.setCriticName(userEntity.getUserName());
            } else {
                //139****0935
                if (!Strings.isNullOrEmpty(userEntity.getPhoneNumber()) && userEntity.getPhoneNumber().length() >= 11) {
                    String newPhone = userEntity.getPhoneNumber().subSequence(0, 3) + "****" + userEntity.getPhoneNumber().subSequence(7, 11);
                    entity.setCriticName(newPhone);
                }
            }
            entity.setCriticPhone(userEntity.getPhoneNumber());
            entity.setContent(replyContent);
            entity.setCommentId(Integer.valueOf(commentId));

            CmHouseCommentEntity houseCommentEntity = houseCommentDao.getById(Integer.valueOf(commentId));
            if (houseCommentEntity == null) {
                resultObj.setTotal("2");
                return resultObj;
            }
            entity.setCommentContent(houseCommentEntity.getCriticContent());
            entity.setPraiseCount(0);
            entity.setCreateTime(new Date());
            entity.setIsDeleted(0);
            entity.setIsReported(0);
            entity.setCityKey(houseCommentEntity.getCityKey());
            entity.setCityName(houseCommentEntity.getCityName());
            entity.setUserPhoto(userEntity.getUserPhoto());
            entity.setSource(source);

            if (cityList.contains("," + entity.getCityKey() + ",")) {
                needCheck = true;
            }

            if (needCheck) {
                entity.setCheckStatus(0);
            } else {
                entity.setCheckStatus(1);
            }

            saveCommentReply((T) entity, userEntity, houseCommentEntity, needCheck);

            resultObj.setTotal("1");
            resultObj.setEntity(entity);
            return resultObj;

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return null;
        }
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    void saveCommentReply(T entity, CmUserEntity userEntity, CmHouseCommentEntity houseCommentEntity, boolean needCheck) {
        cmHouseCommentReplyDao.save(entity);
        //回复数量加1
        CmUserEntity commentUser = cmUserService.getById(houseCommentEntity.getCriticId());
        if (commentUser.getUnreadReply() != null) {
            int unreadReplyCount = commentUser.getUnreadReply() + 1;
            commentUser.setUnreadReply(unreadReplyCount);
            cmUserService.update(commentUser);
        }

        Integer cAmount = houseCommentEntity.getCommentAmount();
        if (cAmount == null) {
            cAmount = 0;
        }
        houseCommentEntity.setCommentAmount(cAmount + 1);

        if (!needCheck) {
            houseCommentDao.update(houseCommentEntity);
        }

        CmCommonUtils.callCRM(userEntity.getPhoneNumber(), userEntity.getCityId(), "103", "楼盘点评回复");

        if (!needCheck) {
            //楼盘回复不需要审核时，清除评论缓存
            cmHouseCommentService.removeCache(houseCommentEntity.getHouseId());
        }
    }

    @Override
    public List<CmHouseCommentReplyEntity> transHouseCommentReplyList(QueryParams<CmHouseCommentReplyEntity> queryParams) {
        try {
            List<CmHouseCommentReplyEntity> list = (List<CmHouseCommentReplyEntity>) cmHouseCommentReplyDao.queryByPage(queryParams);
            return list;
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public List<CmHouseCommentReplyEntity> queryAllByLastDay(QueryParams<CmHouseCommentReplyEntity> queryParams) {
        try {
            List<CmHouseCommentReplyEntity> list = (List<CmHouseCommentReplyEntity>) cmHouseCommentReplyDao.queryAllByLastDay(queryParams);
            if (CollectionUtils.isNotEmpty(list)) {
                for (CmHouseCommentReplyEntity entity : list) {
                    int criticId = entity.getCriticId();
                    String replyCriticId = entity.getReplyCriticId();
                    CmUserEntity userEntity = userDao.getById(criticId);
                    if (userEntity != null) {
                        entity.setCriticId(Integer.parseInt(userEntity.getUserId()));
                    }
                    if (org.apache.commons.lang3.StringUtils.isNotBlank(replyCriticId)) {
                        CmUserEntity user = userDao.getById(Integer.parseInt(replyCriticId));
                        if (user != null) {
                            entity.setReplyCriticId(user.getUserId());
                        }
                    }
                }
            }
            return list;
        } catch (Exception e) {
            return null;
        }
    }

}
