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

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

import com.house365.beans.entity.CmCreditRuleEntity;
import com.house365.ws.dao.interfaces.ICmCreditRuleDao;
import com.house365.ws.dao.interfaces.ICmUserDao;
import com.house365.ws.service.interfaces.ICmUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.house365.beans.entity.CmCreditRecordEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.system.QueryParams;
import com.house365.dao.system.interfaces.Dao;
import com.house365.service.system.impl.DefaultServiceImpl;
import com.house365.ws.dao.interfaces.ICmCreditRecordDao;
import com.house365.ws.service.interfaces.ICmCreditRecordService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import static com.house365.rest.context.CmConstant.CREDITS_RULE_POST;
import static com.house365.rest.context.CmConstant.CREDITS_RULE_QUESTION_MINUS;
import static com.house365.rest.context.CmConstant.CREDITS_RULE_SENDGIFT;

/**
 * CmCreditRecord业务实现类<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-14
 * @see
 * @since 1.0
 */
@Service("cmCreditRecordService")
public class CmCreditRecordServiceImpl<T extends CmCreditRecordEntity> extends DefaultServiceImpl<T> implements ICmCreditRecordService<T> {

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

    @Autowired
    private ICmUserDao<CmUserEntity> cmUserDao;

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

    @Autowired
    private ICmCreditRuleDao creditRuleDao;

    @Autowired
    ICmUserService<CmUserEntity> iCmUserService;

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

    /**
     * 保存加精积分
     */
    @Override
    public CmCreditRecordEntity saveAddExcellentRecord(CmUserEntity user, int commonId) throws Exception {
        return cmCreditRecordDao.saveAddExcellentRecord(user, commonId);
    }

    @Override
    public Integer getTotalCreditsByCondition(QueryParams<CmCreditRecordEntity> queryParams) {
        return cmCreditRecordDao.getTotalCreditsByCondition(queryParams);
    }

    //按条件获取邀请记录总数
    @Override
    public Integer getUserInviteCount(QueryParams<CmCreditRecordEntity> queryParams) {
        return cmCreditRecordDao.getUserInviteCount(queryParams);
    }

    @Override
    public Integer getDistinctUserCount(QueryParams<CmCreditRecordEntity> queryParams) {
        return cmCreditRecordDao.getDistinctUserCount(queryParams);
    }

    @Override
    public List<CmCreditRecordEntity> statisticsByPage(QueryParams<?> queryParams) {
        return cmCreditRecordDao.statisticsByPage(queryParams);
    }

    @Override
    public Integer statisticsByPageCount(QueryParams<CmCreditRecordEntity> queryParams) {
        return cmCreditRecordDao.statisticsByPageCount(queryParams);
    }

    @Override
    public List<CmCreditRecordEntity> queryByPageNew(QueryParams<CmCreditRecordEntity> queryParams) {
        return cmCreditRecordDao.queryByPageNew(queryParams);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public synchronized CmCreditRecordEntity transAddCreditByQuestion(CmUserEntity user, String questionId) {
        try {
            //添加积分记录
            CmCreditRecordEntity recordEntity = cmCreditRecordDao.saveQuestion(user, questionId);
            if (recordEntity == null) {
                LOGGER.error("积分记录保存失败!!!");
                return recordEntity;
            }
            user.setUpdateTime(new Date());
            user.setCredits(recordEntity.getRemainingAmount());
            cmUserDao.update(user);
            iCmUserService.clearUserCache(user.getUserId());
            return recordEntity;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return null;
        }
    }

    //业主社区发帖回帖
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public synchronized CmCreditRecordEntity transAddCreditByBbs(CmUserEntity user) throws Exception {
        try {
            CmCreditRuleEntity cmCreditRuleEntity = (CmCreditRuleEntity) creditRuleDao.getById(CREDITS_RULE_POST);

            Map info = iCmUserService.getUserCreditTask(user.getUserId());
            int done = ((BigDecimal) info.get("posttime")).intValue();

            //超出可赠送数量
            if (done >= cmCreditRuleEntity.getCountLimit()) {
                LOGGER.error("超出允许次数!!!");
                return null;
            }

            //添加积分记录
            CmCreditRecordEntity recordEntity = cmCreditRecordDao.saveBBSRecord(user);
            if (recordEntity == null) {
                LOGGER.error("积分记录保存失败!!!");
                return recordEntity;
            }

            user.setUpdateTime(new Date());
            user.setCredits(recordEntity.getRemainingAmount());
            cmUserDao.update(user);

            iCmUserService.clearUserCache(user.getUserId());
            return recordEntity;
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            throw e;
        }
    }

    //房博士提问扣积分
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public synchronized CmCreditRecordEntity transQestionMinusCredit(
        CmUserEntity user, Integer credit
    ) throws Exception {
        try {
            //            CmCreditRuleEntity cmCreditRuleEntity = (CmCreditRuleEntity) creditRuleDao.getById(CREDITS_RULE_QUESTION_MINUS);

            //添加积分记录
            CmCreditRecordEntity recordEntity = cmCreditRecordDao.saveQuestionMinusRecord(user, credit);
            if (recordEntity == null) {
                LOGGER.error("积分记录保存失败!!!");
                throw new Exception("积分记录保存失败");
            }

            user.setUpdateTime(new Date());
            user.setCredits(recordEntity.getRemainingAmount());
            cmUserDao.update(user);
            iCmUserService.clearUserCache(user.getUserId());

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

    //房博士送心意扣积分
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    public synchronized CmCreditRecordEntity transSendGiftCredit(
        CmUserEntity user
    ) throws Exception {
        try {

            CmCreditRuleEntity cmCreditRuleEntity = (CmCreditRuleEntity) creditRuleDao.getById(CREDITS_RULE_SENDGIFT);

            //添加积分记录
            CmCreditRecordEntity recordEntity = cmCreditRecordDao.saveRecord(user, CREDITS_RULE_SENDGIFT,
                                                                             cmCreditRuleEntity.getCredits());
            if (recordEntity == null) {
                LOGGER.error("积分记录保存失败!!!");
                throw new Exception("积分记录保存失败");
            }

            user.setUpdateTime(new Date());
            user.setCredits(recordEntity.getRemainingAmount());
            cmUserDao.update(user);
            iCmUserService.clearUserCache(user.getUserId());

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

}
