/**
 * Description: CmCreditRecordWS接口
 * 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.interfaces.impl;

import com.house365.beans.entity.CmCreditRecordEntity;
import com.house365.beans.entity.CmCreditRuleEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.CmConstant;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.ws.beans.request.CmCreditRecordListRequest;
import com.house365.ws.beans.request.CmCreditRecordRequest;
import com.house365.ws.beans.response.CmCreditRecordListResponse;
import com.house365.ws.beans.response.CmCreditRecordResponse;
import com.house365.ws.interfaces.server.ICmCreditRecord;
import com.house365.ws.service.interfaces.ICmCreditRecordService;
import com.house365.ws.service.interfaces.ICmCreditRuleService;
import com.house365.ws.service.interfaces.ICmUserService;
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 java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    /**
     * CmCreditRecord服务对象
     */
    @Autowired
    private ICmCreditRecordService<CmCreditRecordEntity> cmCreditRecordService;

    @Autowired
    private ICmUserService<CmUserEntity> userService;

    @Autowired
    private ICmCreditRuleService<CmCreditRuleEntity> ruleService;

    /**
     * CmCreditRecord列表查询
     *
     * @param request CmCreditRecord列表查询请求
     * @return CmCreditRecord列表查询响应
     */
    @Override
    public CmCreditRecordListResponse getCmCreditRecordList(CmCreditRecordListRequest request) {
        CmCreditRecordListResponse response = new CmCreditRecordListResponse();
        try {
            QueryParams<CmCreditRecordEntity> queryParams = getQueryParams(request);
            List<CmCreditRecordEntity> cmCreditRecords = cmCreditRecordService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(cmCreditRecords);
            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;
    }

    /**
     * 处理城市信息 关联用户表
     *
     * @param request 查询条件
     * @return 结果集
     */
    @Override
    public CmCreditRecordListResponse getCmCreditRecordListWithCity(CmCreditRecordListRequest request) {
        CmCreditRecordListResponse response = new CmCreditRecordListResponse();
        try {
            QueryParams<CmCreditRecordEntity> queryParams = getQueryParams(request);
            List<CmCreditRecordEntity> cmCreditRecords = cmCreditRecordService.queryByPageNew(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(cmCreditRecords);
            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;
    }

    public CmCreditRecordListResponse getCmStatisticsByPage(CmCreditRecordListRequest request) {
        CmCreditRecordListResponse response = new CmCreditRecordListResponse();
        try {
            QueryParams<CmCreditRecordEntity> queryParams = new QueryParams<>(request.getSearchParams());
            queryParams.setPaging(request.getPaging());
            List<CmCreditRecordEntity> cmCreditRecords = cmCreditRecordService.queryByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(cmCreditRecords);
            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;
    }

    /**
     * 保存加精积分
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @param user
     * @param commonId 所对应记录id
     * @return
     * @author yinchangming
     * @version [v1.0.0, 2015年11月5日]
     * @since [产品/模块版本](可选)
     */
    @Override
    public CmCreditRecordEntity saveAddExcellentRecord(CmUserEntity user, int commonId) throws Exception {
        return cmCreditRecordService.saveAddExcellentRecord(user, commonId);
    }

    /**
     * 保存CmCreditRecord
     *
     * @param request CmCreditRecord请求
     * @return 保存CmCreditRecord响应
     */
    @Override
    public CmCreditRecordResponse addCmCreditRecord(CmCreditRecordRequest request) {
        CmCreditRecordResponse response = new CmCreditRecordResponse();
        try {
            CmCreditRecordEntity entity = request.getEntity();
            cmCreditRecordService.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;
    }

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


    /**
     * 修改CmCreditRecord
     *
     * @param request 修改CmCreditRecord请求
     * @return 修改CmCreditRecord响应
     */
    @Override
    public CmCreditRecordResponse updateCmCreditRecord(CmCreditRecordRequest request) {
        CmCreditRecordResponse response = new CmCreditRecordResponse();
        try {
            cmCreditRecordService.update(request.getEntity());
            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;
    }

    /**
     * 扣除指定commentId,ruleId的积分
     *
     * @param
     * @return
     */
    @Override
    public void removeCredit(Integer commentId, Integer ruleId) {
        try {
            synchronized (this) {
                //扣除积分
                //根据评论ID和规则ID获取之前评论记录
                Map<String, Object> map = new HashMap<>(10);
                map.put("EQ_commentId", commentId);
                map.put("EQ_ruleId", ruleId);

                QueryParams<CmCreditRecordEntity> queryParams = new QueryParams<>(map);
                List<CmCreditRecordEntity> cmCreditRecords = cmCreditRecordService.queryByPage(queryParams);

                if (cmCreditRecords != null && cmCreditRecords.size() > 0) {
                    CmCreditRecordEntity record = cmCreditRecords.get(0);
                    //获取记录中添加的积分值
                    Integer amount = record.getAmount();

                    CmUserEntity userEntity = userService.getById(record.getUserId());
                    //根据记录中获取积分的userId获取用户当前积分
                    Integer credits = userEntity.getCredits();
                    //用户积分为0，则不进行积分扣除
                    if (credits <= 0) {
                        return;
                    }
                    if (ruleId == CmConstant.CREDITS_RULE_BROKER_COMMENT) {
                        ruleId = CmConstant.CREDITS_RULE_BROKER_COMMENT_REMOVE;
                    } else if (ruleId == CmConstant.CREDITS_RULE_HOUSE_COMMENT) {
                        ruleId = CmConstant.CREDITS_RULE_HOUSE_COMMENT_REMOVE;
                    }

                    CmCreditRuleEntity ruleEntity = ruleService.getById(ruleId);

                    if (ruleEntity != null) {
                        record.setId(null);

                        record.setRuleId(ruleEntity.getId());
                        record.setRuleName(ruleEntity.getCreditRuleName());

                        record.setHappenTime(new Date());
                        //如果可能出现负分，则置零，扣除积分为剩余积分
                        if (credits - amount < 0) {
                            record.setAmount(-credits);
                            record.setRemainingAmount(0);
                        } else {
                            record.setAmount(0 - amount);
                            record.setRemainingAmount(credits - amount);
                        }

                        cmCreditRecordService.save(record);
                    }

                    //修改user积分数
                    userEntity.setCredits((credits - amount) < 0 ? 0 : (credits - amount));
                    userService.update(userEntity);
                }
            }
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
            ex.printStackTrace();
        }
    }

    /**
     * 通过ID获取CmCreditRecord
     *
     * @param id 唯一标识
     * @return 通过ID获取CmCreditRecord响应
     */
    @Override
    public CmCreditRecordResponse getCmCreditRecordById(Integer id) {
        CmCreditRecordResponse response = new CmCreditRecordResponse();
        try {
            CmCreditRecordEntity entity = cmCreditRecordService.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
    public Integer getTotalCreditsByCondition(CmCreditRecordListRequest request) {
        QueryParams<CmCreditRecordEntity> queryParams = getQueryParams(request);
        return cmCreditRecordService.getTotalCreditsByCondition(queryParams);
    }

    @Override
    public Integer getDistinctUserCount(CmCreditRecordListRequest request) {
        QueryParams<CmCreditRecordEntity> queryParams = getQueryParams(request);
        return cmCreditRecordService.getDistinctUserCount(queryParams);
    }

    private QueryParams<CmCreditRecordEntity> getQueryParams(CmCreditRecordListRequest request) {
        QueryParams<CmCreditRecordEntity> queryParams = new QueryParams<>(
                request.getSearchParams());
        queryParams.setPaging(request.getPaging());
        queryParams.setOrderColumn(request.getOrderColumn());
        queryParams.setOrderMode(request.getOrderMode());
        return queryParams;
    }

    @Override
    public CmCreditRecordListResponse statisticsByPage(CmCreditRecordListRequest request) {
        CmCreditRecordListResponse response = new CmCreditRecordListResponse();
        try {
            QueryParams<CmCreditRecordEntity> queryParams = getQueryParams(request);
            List<CmCreditRecordEntity> cmCreditRecords = cmCreditRecordService.statisticsByPage(queryParams);
            response.setPaging(queryParams.getPaging());
            response.setObjectList(cmCreditRecords);
            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
    public Integer statisticsByPageCount(CmCreditRecordListRequest request) {
        QueryParams<CmCreditRecordEntity> queryParams = getQueryParams(request);
        return cmCreditRecordService.statisticsByPageCount(queryParams);
    }

    /**
     * 以下均为自动生成
     */

    @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() {
    }

}
