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

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

import com.google.common.base.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.house365.beans.entity.CmBrokerCommentEntity;
import com.house365.beans.entity.CmCommentReportEntity;
import com.house365.beans.entity.CmHouseCommentEntity;
import com.house365.beans.entity.CmHouseCommentReplyEntity;
import com.house365.beans.entity.CmHouseEntity;
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.service.system.impl.DefaultServiceImpl;
import com.house365.ws.beans.request.CmHouseRequest;
import com.house365.ws.beans.response.CmHouseCommentResponse;
import com.house365.ws.beans.response.CmHouseResponse;
import com.house365.ws.dao.interfaces.ICmBrokerCommentDao;
import com.house365.ws.dao.interfaces.ICmCommentReportDao;
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.ICmCreditRecord;
import com.house365.ws.interfaces.server.ICmHouse;
import com.house365.ws.service.interfaces.ICmCommentReportService;

/**
 * CmCommentReport业务实现类<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-14
 * @see
 * @since 1.0
 */
@Service("cmCommentReportService")
public class CmCommentReportServiceImpl<T extends CmCommentReportEntity> extends DefaultServiceImpl<T> implements ICmCommentReportService<T> {
    /**
     * 自动注入的数据访问对象
     */
    @Autowired
    private ICmCommentReportDao<T> cmCommentReportDao;

    @Autowired
    private ICmHouseCommentDao<CmHouseCommentEntity> houseCommentDao;

    @Autowired
    private ICmBrokerCommentDao<CmBrokerCommentEntity> brokerCommentDao;

    @Autowired
    private ICmHouseCommentReplyDao<CmHouseCommentReplyEntity> commentReplyDao;

    @Autowired
    private ICmUserDao<CmUserEntity> userDao;

    @Autowired
    private ICmCreditRecord cmCreditRecord;

    @Autowired
    private ICmHouse cmHouse;

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

    @Override
    public Integer tranDeleteCommentReport(String id, String isNoTalk, String isIgnored) {
        try {
            if (!StringUtils.isEmpty(id)) {
                if (id.contains(",")) {
                    String[] ids = id.split(",");
                    for (int i = 0; i < ids.length; i++) {

                        CmCommentReportEntity entity = this.getById(Integer.valueOf(ids[i]));
                        /* 忽略： 不显示该条举报即isIgnored=1 isDeleted=1
                         * 删除：删除该举报及关联的评论 isIgnored=2 isDeleted=1
                         * 删除并禁言：删除该举报及关联的评论并禁言该评论的会员48小时 isIgnored=2 isDeleted=1
                         */
                        //数据逻辑删除
                        entity.setIsDeleted(1);
                        //忽略
                        if (!StringUtils.isEmpty(isIgnored) && "true".equals(isIgnored)) {
                            entity.setIsIgnored(1);
                        } else {
                            //逻辑删除关联的评论
                            Integer commentType = entity.getCommentType();
                            Integer commentId = entity.getCommentId();
                            if (commentType == 1)//楼盘点评
                            {
                                //更新用户积分
                                CmHouseCommentEntity commentEntity = houseCommentDao.getById(commentId);
                                commentEntity.setIsDeleted(1);
                                houseCommentDao.update(commentEntity);
                                //更新评论数量
                                decreaseHouseCommentAmount(commentEntity.getHouseId(),
                                        commentEntity.getCriticPictures());
                                //扣除积分
                                cmCreditRecord.removeCredit(Integer.valueOf(ids[i]),
                                        CmConstant.CREDITS_RULE_HOUSE_COMMENT);
                            } else if (commentType == 2)//楼盘点评回复
                            {
                                CmHouseCommentReplyEntity commentReplyEntity = commentReplyDao.getById(commentId);
                                commentReplyEntity.setIsDeleted(1);
                                commentReplyDao.update(commentReplyEntity);
                                //更新评论回复数量
                                decreaseHouseCommentReplyAmount(commentReplyEntity.getCriticId());
                            } else if (commentType == 3)//经纪人评价
                            {
                                CmBrokerCommentEntity commentEntity = brokerCommentDao.getById(commentId);
                                commentEntity.setIsDeleted(1);
                                brokerCommentDao.update(commentEntity);
                            }

                            entity.setIsIgnored(2);
                        }
                        //禁言48小时
                        if (!Strings.isNullOrEmpty(isNoTalk) && !"0".equals(isNoTalk)) {
                            Calendar c = Calendar.getInstance();
                            c.add(Calendar.HOUR, Integer.parseInt(isNoTalk));
                            CmUserEntity userEntity = userDao.getById(entity.getCriticId());
                            if (userEntity != null && userEntity.getGagTime() == null || userEntity.getGagTime().compareTo(
                                    new Date()) <= 0) {
                                userEntity.setGagTime(c.getTime());
                                userDao.update(userEntity);
                            }
                        }
                        this.update((T) entity);
                    }
                } else {
                    CmCommentReportEntity entity = this.getById(Integer.valueOf(id));

                    //数据逻辑删除
                    entity.setIsDeleted(1);
                    //忽略
                    if (!StringUtils.isEmpty(isIgnored) && "true".equals(isIgnored)) {
                        entity.setIsIgnored(1);
                    } else {
                        //逻辑删除关联的评论
                        Integer commentType = entity.getCommentType();
                        Integer commentId = entity.getCommentId();
                        if (commentType == 1)//楼盘点评
                        {
                            CmHouseCommentEntity commentEntity = houseCommentDao.getById(commentId);
                            commentEntity.setIsDeleted(1);
                            //更新条数
                            //更新评论数量
                            decreaseHouseCommentAmount(commentEntity.getHouseId(), commentEntity.getCriticPictures());
                            houseCommentDao.update(commentEntity);
                            //扣除积分
                            cmCreditRecord.removeCredit(Integer.valueOf(id), CmConstant.CREDITS_RULE_HOUSE_COMMENT);
                        } else if (commentType == 2)//楼盘点评回复
                        {
                            CmHouseCommentReplyEntity commentReplyEntity = commentReplyDao.getById(commentId);
                            commentReplyEntity.setIsDeleted(1);
                            //更新评论回复数量
                            decreaseHouseCommentReplyAmount(commentReplyEntity.getCriticId());
                            commentReplyDao.update(commentReplyEntity);
                        } else if (commentType == 3)//经纪人评价
                        {
                            CmBrokerCommentEntity commentEntity = brokerCommentDao.getById(commentId);
                            commentEntity.setIsDeleted(1);
                            brokerCommentDao.update(commentEntity);
                        }

                        entity.setIsIgnored(2);
                    }
                    //禁言48小时
                    if (!Strings.isNullOrEmpty(isNoTalk) && !"0".equals(isNoTalk)) {
                        Calendar c = Calendar.getInstance();
                        c.add(Calendar.HOUR, Integer.parseInt(isNoTalk));
                        CmUserEntity userEntity = userDao.getById(entity.getCriticId());

                        if (userEntity != null && userEntity.getGagTime() == null || userEntity.getGagTime().compareTo(
                                new Date()) <= 0) {
                            userEntity.setGagTime(c.getTime());
                            userDao.update(userEntity);
                        }

                    }
                    this.update((T) entity);
                }
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public String transCommentReport(Map<String, Object> map) {

        // 评论Id
        String commentId = null;
        // 评论类型
        String commentType = null;
        // 举报原因
        String reportReason = null;
        // 城市key
        String cityKey = null;
        //用户ID类型
        Integer useridType = null;
        //举报类型
        Integer source = null;
        try {


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

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

            if (!StringUtils.isEmpty(map.get(CmConstant.USERID_TYPE))) {
                useridType = Integer.parseInt(((String[]) map.get(CmConstant.USERID_TYPE))[0]);
            }

            if (!StringUtils.isEmpty(map.get(CmConstant.SOURCE))) {
                source = Integer.parseInt(((String[]) map.get(CmConstant.SOURCE))[0]);
            }

            CmCommentReportEntity commentReportEntity = null;
            CmUserEntity userEntity = null;
            //评论者
            Integer criticId = null;
            String criticName = null;
            String criticPhone = null;
            String criticPictures = null;
            String criticContent = null;
            Date commentTime = null;
            Integer reportCount = 0;
            //查看被举报条目是否存在，存在则更新
            QueryParams<CmCommentReportEntity> queryParams = new QueryParams<CmCommentReportEntity>();
            Map<String, Object> qmap = new HashMap<String, Object>();
            qmap.put("EQ_commentId", commentId);
            qmap.put("EQ_commentType", commentType);
            queryParams.setSearchParams(qmap);
            List<T> list = cmCommentReportDao.queryAll(queryParams);
            //如果已经存在则更新
            if (list.size() > 0) {
                commentReportEntity = list.get(0);
                criticId = commentReportEntity.getCriticId();
                if (commentReportEntity.getReportCount() == null) {
                    commentReportEntity.setReportCount(1);
                } else {
                    commentReportEntity.setReportCount(commentReportEntity.getReportCount() + 1);
                }
                //设置用户被举报次数
                userEntity = userDao.getById(criticId);
                if (userEntity == null) {
                    commentReportEntity.setCriticReportedCount(0);
                } else {
                    if (userEntity.getReportedCount() == null) {
                        commentReportEntity.setCriticReportedCount(0);
                    } else {
                        commentReportEntity.setCriticReportedCount(userEntity.getReportedCount());
                    }
                }
                cmCommentReportDao.update((T) commentReportEntity);
            } else {
                commentReportEntity = new CmCommentReportEntity();

                if ("1".equals(commentType)) {

                    CmHouseCommentEntity houseCommentEntity = houseCommentDao.getById(Integer.valueOf(commentId));
                    if (houseCommentEntity == null) {
                        return "2";
                    }
                    commentReportEntity.setCityKey(houseCommentEntity.getCityKey());
                    commentReportEntity.setCityName(houseCommentEntity.getCityName());
                    criticId = houseCommentEntity.getCriticId();
                    criticName = houseCommentEntity.getCriticName();
                    criticPhone = houseCommentEntity.getCriticPhone();
                    criticPictures = houseCommentEntity.getCriticPictures();
                    criticContent = houseCommentEntity.getCriticContent();
                    commentTime = houseCommentEntity.getCommentDate();
                    if (houseCommentEntity.getReportCount() == null) {
                        houseCommentEntity.setReportCount(1);
                    } else {
                        houseCommentEntity.setReportCount(houseCommentEntity.getReportCount() + 1);
                    }
                    reportCount = houseCommentEntity.getReportCount();
                    houseCommentDao.update(houseCommentEntity);

                } else if ("2".equals(commentType)) {
                    CmHouseCommentReplyEntity commentReplyEntity = commentReplyDao.getById(Integer.valueOf(commentId));
                    if (commentReplyEntity == null) {
                        return "2";
                    }
                    commentReportEntity.setCityKey(commentReplyEntity.getCityKey());
                    commentReportEntity.setCityName(commentReplyEntity.getCityName());
                    criticId = commentReplyEntity.getCriticId();
                    criticName = commentReplyEntity.getCriticName();
                    criticPhone = commentReplyEntity.getCriticPhone();
                    criticContent = commentReplyEntity.getContent();
                    commentTime = commentReplyEntity.getCreateTime();
                    if (commentReplyEntity.getReportCount() == null) {
                        commentReplyEntity.setReportCount(1);
                    } else {
                        commentReplyEntity.setReportCount(commentReplyEntity.getReportCount() + 1);
                    }
                    reportCount = commentReplyEntity.getReportCount();
                    commentReplyDao.update(commentReplyEntity);
                } else if ("3".equals(commentType)) {
                    CmBrokerCommentEntity brokerCommentEntity = brokerCommentDao.getById(Integer.valueOf(commentId));
                    if (brokerCommentEntity == null) {
                        return "2";
                    }
                    commentReportEntity.setCityKey(brokerCommentEntity.getCityKey());
                    commentReportEntity.setCityName(brokerCommentEntity.getCityName());
                    criticId = brokerCommentEntity.getCriticCode();
                    criticName = brokerCommentEntity.getCriticName();
                    criticPhone = brokerCommentEntity.getCriticPhone();
                    criticContent = brokerCommentEntity.getCriticContent();
                    commentTime = brokerCommentEntity.getPublishTime();
                }

                commentReportEntity.setCommentId(Integer.valueOf(commentId));
                commentReportEntity.setCriticId(criticId);
                commentReportEntity.setCriticName(criticName);
                commentReportEntity.setCriticPhone(criticPhone);
                commentReportEntity.setCriticPictures(criticPictures);
                commentReportEntity.setContent(criticContent);
                commentReportEntity.setCommentTime(commentTime);
                commentReportEntity.setCommentType(Integer.valueOf(commentType));
                commentReportEntity.setSource(source);
                commentReportEntity.setReportCount(reportCount);
                commentReportEntity.setReportReason(reportReason);
                commentReportEntity.setReportDetailReason(null);
                commentReportEntity.setCreateTime(new Date());


                commentReportEntity.setIsDeleted(0);
                commentReportEntity.setIsIgnored(0);
                //设置用户被举报次数
                userEntity = userDao.getById(criticId);
                if (userEntity == null) {
                    commentReportEntity.setCriticReportedCount(0);
                } else {
                    if (userEntity.getReportedCount() == null) {
                        commentReportEntity.setCriticReportedCount(0);
                    } else {
                        commentReportEntity.setCriticReportedCount(userEntity.getReportedCount());
                    }
                }
                cmCommentReportDao.save((T) commentReportEntity);

            }


            //获取用户信息
            //CmUserEntity userEntity = userDao.getUserByUserId(criticId, cityKey, useridType);

            //评论人不存在，则返回
            if (userEntity == null) {
                return "0";
            }

            if (userEntity.getReportedCount() == null) {
                userEntity.setReportedCount(0);
            }
            commentReportEntity.setCriticReportedCount(userEntity.getReportedCount() + 1);
            //用户举报次数+1
            userEntity.setReportedCount(userEntity.getReportedCount() + 1);
            userDao.update(userEntity);

            return "1";

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 新房评论减一
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param houseId
     * @author yinchangming
     * @version [v1.0.0, 2015年11月6日]
     * @since [产品/模块版本](可选)
     */
    private void decreaseHouseCommentAmount(Integer houseId, String images) {
        CmHouseResponse house = cmHouse.getCmHouseById(houseId);
        CmHouseEntity houseEntity = house.getEntity();
        if (images != null && !(images.trim().equals(""))) {
            if (houseEntity.getWithPictureCount() != null && houseEntity.getWithPictureCount() > 0) {
                houseEntity.setWithPictureCount(houseEntity.getWithPictureCount() - 1);
            }
        } else {
            if (houseEntity.getNoPictureCount() != null && houseEntity.getNoPictureCount() > 0) {
                houseEntity.setNoPictureCount(houseEntity.getNoPictureCount() - 1);
            }
        }
        if (houseEntity.getTotolCommetAmount() != null && houseEntity.getTotolCommetAmount() > 0) {
            houseEntity.setTotolCommetAmount(houseEntity.getTotolCommetAmount() - 1);
        }
        CmHouseRequest houser = new CmHouseRequest();
        houser.setEntity(houseEntity);
        cmHouse.updateCmHouse(houser);
    }

    /**
     * 评论回复数减一
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @author yinchangming
     * @version [v1.0.0, 2015年11月6日]
     * @since [产品/模块版本](可选)
     */
    private void decreaseHouseCommentReplyAmount(Integer houseCommnetId) {
        CmHouseCommentEntity houseComment = houseCommentDao.getById(houseCommnetId);
        if (houseComment != null) {
            houseComment.setCommentAmount(houseComment.getCommentAmount() - 1);
            houseCommentDao.update(houseComment);
        }
    }

}
