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

import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.house365.beans.constant.CommentConstant;
import com.house365.beans.entity.CmBrokerCommentEntity;
import com.house365.beans.entity.CmBrokerEntity;
import com.house365.beans.entity.CmCreditRecordEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.entity.KlfCityEntity;
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.dao.interfaces.ICmBrokerCommentDao;
import com.house365.ws.dao.interfaces.ICmBrokerDao;
import com.house365.ws.dao.interfaces.ICmCreditRecordDao;
import com.house365.ws.dao.interfaces.ICmUserDao;
import com.house365.ws.service.interfaces.ICmBrokerCommentService;
import com.house365.ws.util.CityUtil;
import com.house365.ws.util.PhpInterfaceUtils;

/**
 * CmBrokerComment业务实现类<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-10
 * @see
 * @since 1.0
 */
@Service("cmBrokerCommentService")
public class CmBrokerCommentServiceImpl<T extends CmBrokerCommentEntity> extends DefaultServiceImpl<T> implements ICmBrokerCommentService<T> {
    /**
     * 自动注入的数据访问对象
     */
    @Autowired
    private ICmBrokerCommentDao<T> cmBrokerCommentDao;

    @Autowired
    private ICmBrokerDao<CmBrokerEntity> cmBrokerDao;

    @Autowired
    private ICmUserDao<CmUserEntity> userDao;

    @Autowired
    private ICmCreditRecordDao<CmCreditRecordEntity> creditRecordDao;

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

    /*
     * 删除经纪人
     */
    @Override
    public Integer tranDeleteBroker(String id, String isNoTalk) {

        try {
            if (!StringUtils.isEmpty(id)) {
                if (id.contains(",")) {
                    String[] ids = id.split(",");
                    for (int i = 0; i < ids.length; i++) {

                        CmBrokerCommentEntity entity = cmBrokerCommentDao.getById(Integer.valueOf(ids[i]));

                        if (entity != null) {
                            //数据逻辑删除
                            entity.setIsDeleted(1);
                            //禁言48小时
                            if (!StringUtils.isEmpty(isNoTalk) && "true".equals(isNoTalk)) {
                                Calendar c = Calendar.getInstance();
                                c.add(Calendar.DAY_OF_MONTH, 2);

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

                            cmBrokerCommentDao.update((T) entity);

                            //扣除积分
                            creditRecordDao.removeCredit(Integer.valueOf(ids[i]),
                                                         CmConstant.CREDITS_RULE_BROKER_COMMENT);
                        }

                    }
                } else {
                    CmBrokerCommentEntity entity = cmBrokerCommentDao.getById(Integer.valueOf(id));

                    if (entity != null) {
                        //数据逻辑删除
                        entity.setIsDeleted(1);
                        //禁言48小时
                        if (!StringUtils.isEmpty(isNoTalk) && "true".equals(isNoTalk)) {
                            Calendar c = Calendar.getInstance();
                            c.add(Calendar.DAY_OF_MONTH, 2);

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

                        cmBrokerCommentDao.update((T) entity);

                        //扣除积分
                        creditRecordDao.removeCredit(Integer.valueOf(id), CmConstant.CREDITS_RULE_BROKER_COMMENT);
                    }
                }
            }
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public String transBrokerComment(Map<String, Object> map, CmUserEntity userEntity) throws Exception {

        // 经纪人Id
        String brokerId = null;

        // 评分
        String criticScore = null;
        // 评论内容
        String criticContent = null;
        // 标签
        String labels = null;
        // 是否匿名
        String isAnonymous = null;
/*        // 城市Id
        String cityId = null;
        // 城市Name
        String cityName = null;*/
        // 城市key
        String cityKey = null;
        //评论来源
        int source = 0;

        CmBrokerCommentEntity entity = new CmBrokerCommentEntity();

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

        if (!StringUtils.isEmpty(map.get("criticContent"))) {
            criticContent = ((String[]) map.get("criticContent"))[0];
        }
        if (!StringUtils.isEmpty(map.get("criticScore"))) {
            criticScore = ((String[]) map.get("criticScore"))[0];
            entity.setCriticScore(Float.parseFloat(criticScore));
        }
        if (!StringUtils.isEmpty(map.get("labels"))) {
            labels = ((String[]) map.get("labels"))[0];
        }
        if (!StringUtils.isEmpty(map.get("isAnonymous"))) {
            isAnonymous = ((String[]) map.get("isAnonymous"))[0];
            entity.setIsAnonymous(Integer.valueOf(isAnonymous));
        } else {
            entity.setIsAnonymous(null);
        }
        if (!StringUtils.isEmpty(map.get("source"))) {
            source = Integer.parseInt(((String[]) map.get("source"))[0]);
            entity.setSource(source);
        }

        if (!StringUtils.isEmpty(map.get(CmConstant.CITY_KEY))) {
            cityKey = ((String[]) map.get(CmConstant.CITY_KEY))[0];
        }
        CmBrokerEntity brokerEntity = cmBrokerDao.getBrokerByBrokerId(Integer.valueOf(brokerId));

        if (brokerEntity != null) {
            entity.setBrokerName(brokerEntity.getBrokerName());
            entity.setBrokerCompanyName(brokerEntity.getBrokerCompanyName());
            entity.setBrokerPhone(brokerEntity.getBrokerPhone());
        } else {
            brokerEntity = PhpInterfaceUtils.getBrokerByRemoteInterface(brokerId, cityKey);

            if (brokerEntity != null) {
                int id = cmBrokerDao.save(brokerEntity);
                brokerEntity.setId(id);
            } else {
                return "2";
            }

            entity.setBrokerName(brokerEntity.getBrokerName());
            entity.setBrokerCompanyName(brokerEntity.getBrokerCompanyName());
            entity.setBrokerPhone(brokerEntity.getBrokerPhone());
        }

        //经纪人评论
        entity.setBrokerId(brokerEntity.getId());
        entity.setCriticContent(criticContent);
        entity.setLabels(labels);
        entity.setIsAnonymous(Integer.valueOf(isAnonymous));
        entity.setPublishTime(new Date());
        //entity.setCityId(Integer.valueOf(cityId));
        //entity.setCityName(cityName);
        entity.setCityKey(cityKey);
        //增加默认值
        if (CmConstant.ShiYeBu.equals(cityKey)) {
            entity.setCityKey(CmConstant.ShiYeBu);
            entity.setCityName(CmConstant.ShiYeBuStr);
        } else {
            entity.setCityKey(cityKey);
            KlfCityEntity cityMap = CityUtil.getCityByCityKey(cityKey);
            if (cityMap != null)
                entity.setCityName(cityMap.getName());
        }
        entity.setIsReaded(0);
        entity.setUserPhoto(userEntity.getUserPhoto());
        entity.setIsKicked(0);
        entity.setIsDeleted(0);
        entity.setIsReported(0);
        entity.setCriticName(userEntity.getUserName());
        entity.setCriticPhone(userEntity.getPhoneNumber());
        entity.setSource(source);
        //CmUserEntity user = userEntity;//userDao.getUserByUserId(Integer.valueOf(userId));
        entity.setCriticCode(userEntity.getId());
        entity.setBrokerId(brokerEntity.getId());
        Integer commentId = cmBrokerCommentDao.save((T) entity);


        //处理labels
        Set<String> labelSet = new HashSet<String>();
        if (labels != null && (!labels.trim().equals(""))) {
            String[] array = labels.split(",");
            for (String str : array) {
                labelSet.add(str);
            }
        }
        if (brokerEntity.getLabels() != null && (!brokerEntity.getLabels().trim().equals(""))) {
            String[] array = brokerEntity.getLabels().split(",");
            for (String str : array) {
                labelSet.add(str);
            }
        }
        Object[] strArray = labelSet.toArray();
        String labelsAll = "";
        if (strArray.length > 0) {
            for (Object str : strArray) {
                labelsAll += (str + ",");
            }
        }
        brokerEntity.setLabels(labelsAll);

        //更新broker 评分
        brokerEntity.setTotalCommetAmount(brokerEntity.getTotalCommetAmount() + 1);
        switch (criticScore) {
            case "1":
                brokerEntity.setOneStarAmount(brokerEntity.getOneStarAmount() + 1);
                break;
            case "2":
                brokerEntity.setTwoStarAmount(brokerEntity.getTwoStarAmount() + 1);
                break;
            case "3":
                brokerEntity.setThreeStarAmount(brokerEntity.getThreeStarAmount() + 1);
                break;
            case "4":
                brokerEntity.setFourStarAmount(brokerEntity.getFourStarAmount() + 1);
                break;
            case "5":
                brokerEntity.setFiveStarAmount(brokerEntity.getFiveStarAmount() + 1);
                break;
            default:
                break;
        }

        cmBrokerDao.update(brokerEntity);


        //如果是网页版则不记录积分
        if (CommentConstant.COMMENT_SOURCE_APP != source) {
            return "1";
        }

        //添加积分记录
        CmCreditRecordEntity recordEntity = creditRecordDao.saveBrokerCommentRecord(userEntity, commentId);

        //积分余额
        Integer remainingAmount = userEntity.getCredits() + recordEntity.getAmount();
        //recordEntity.setRemainingAmount(remainingAmount);
        //对用户表积分余额进行操作
        userEntity.setCredits(remainingAmount);
        userDao.update(userEntity);

        return "1";

    }

    @Override
    public List<CmBrokerCommentEntity> transBrokerCommentList(QueryParams<CmBrokerCommentEntity> queryParams) {
        try {
            List<CmBrokerCommentEntity> list = (List<CmBrokerCommentEntity>) cmBrokerCommentDao.queryByPage(
                queryParams);
            return list;
        } catch (Exception e) {
            return null;
        }
    }
}
