/*
 * Copyright (C), 2002-2015, 江苏三六五网络股份有限公司
 * FileName: ExchangeUserLoginInterfaceImpl.java
 * Author:   Administrator
 * Date:     2015年5月5日 下午2:57:41
 * Description: //模块目的、功能描述
 * History: //修改记录
 * <author>      <time>      <version>    <desc>
 * 修改人姓名             修改时间            版本号                  描述
 */
package com.house365.ws.interfaces.rest;

import com.house365.beans.entity.CmBrokerCommentEntity;
import com.house365.beans.entity.CmCreditRuleEntity;
import com.house365.beans.entity.CmHouseCommentEntity;
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.IllegalServiceParameterException;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.service.interfaces.ICmBrokerCommentService;
import com.house365.ws.service.interfaces.ICmCreditRuleService;
import com.house365.ws.service.interfaces.ICmUserService;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

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

/**
 * 〈一句话功能简述〉<br>
 * 〈功能详细描述〉
 *
 * @author Administrator
 * @version [版本号, 2015年5月5日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Component("brokerCommentInterface")
public class BrokerCommentInterfaceImpl implements IBrokerCommentInterface {

    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(BrokerCommentInterfaceImpl.class);

    @Autowired
    private ICmBrokerCommentService<CmBrokerCommentEntity> brokerCommentService;

    @Autowired
    private ICmCreditRuleService<CmCreditRuleEntity> cmCreditRuleService;

    @Autowired
    private ICmUserService<CmUserEntity> cmUserService;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CmBrokerCommentEntity> response = new House365RestResponse<CmBrokerCommentEntity>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map);
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            Map<String, Object> resultMap = new HashMap<>();
            //指定期间禁止评论
            Calendar startDate = Calendar.getInstance();
            startDate.set(2019, 2, 3, 0, 0, 0);
            Calendar endDate = Calendar.getInstance();
            endDate.set(2019, 2, 15, 0, 0, 0);
            Date now = new Date();
            if (now.before(endDate.getTime()) && now.after(startDate.getTime())) {
                resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                Map<String, Object> tempMap = new HashMap<>();
                tempMap.put("list", new int[] {});
                tempMap.put("total", 1);
                resultMap.put("data", tempMap);
                resultMap.put("error", "非常抱歉 本评论暂时关闭！");
                resultMap.put("msg", "非常抱歉 本评论暂时关闭！");
                return JSONObject.fromObject(resultMap).toString();
            }

            CmUserEntity cmUser = cmUserService.registUserByUserId(map);
            if (cmUser == null) {
                throw new ServiceRunException("用户中心用户不存在!");
            }


            Date gagDate = cmUser.getGagTime();
            if (gagDate != null && (new Date().getTime() < gagDate.getTime())) {
                throw new ServiceRunException("用户被禁言！");
            }


            //校验评论次数是否超出限制
          /*  if(isCommentCountExceedLimit(cmUser)){
                throw new ServiceRunException("评论失败,评论次数超过限制！");
            }*/

            House365RestObject<CmBrokerCommentEntity> data = doBusiness(map, cmUser);

            if (StringUtils.isEmpty(data.getTotal())) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("操作失败");
            } else if ("0".equals(data.getTotal())) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("接口调用异常或该用户不存在");
            } else if ("1".equals(data.getTotal())) {
                response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                response.setMsg("操作成功");
            } else if ("2".equals(data.getTotal())) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("接口调用异常或该经纪人不存在");
            }
            response.setData(data);
        } catch (ServiceRunException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
        }

        return JSONObject.fromObject(response).toString();
    }

    /**
     * 校验是否超出限制
     * 功能描述: <br>
     * 〈功能详细描述〉
     *
     * @return
     * @author yinchangming
     * @version [v1.0.0, 2015年8月31日]
     * @since [产品/模块版本](可选)
     */
    private boolean isCommentCountExceedLimit(CmUserEntity cmUser) {
        if (cmUser == null) {
            return false;
        }

        CmCreditRuleEntity ruleEntity = cmCreditRuleService.getById(CmConstant.CREDITS_RULE_BROKER_COMMENT);
        int countLimit = ruleEntity.getCountLimit();
        int dayCircle = ruleEntity.getCountCircle();

        QueryParams<CmHouseCommentEntity> queryParams = new QueryParams<CmHouseCommentEntity>();
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - dayCircle);
        Date oldTime = calendar.getTime();
        Map<String, Object> searchParams = new HashMap<String, Object>();
        searchParams.put("GTE_publishTime", oldTime);
        searchParams.put("EQ_criticId", cmUser.getId());
        queryParams.setSearchParams(searchParams);
        //List<CmHouseCommentEntity> commentList = houseCommentService.queryAll(queryParams);
        int totalCount = brokerCommentService.getTotalCount(queryParams);
        if (totalCount > countLimit) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 业务层统校验自己所需参数是否存在
     *
     * @param map 请求参数封装成Map对象
     * @return 统一返回参数
     * @author yangyang
     * @version [v1.0.0, 2015年8月18日]
     * @since [产品/模块版本](可选)
     */
    protected void checkInterfaceParameter(Map<String, Object> map) throws IllegalServiceParameterException {

        // 方法所需参数
        for (String str : CmConstant.BrokerComment) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                LOGGER.error("业务入口参数异常：" + str + "参数为空!");
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }

        }
    }

    /**
     * 业务层统逻辑处理
     *
     * @param
     * @return 统一返回参数
     * @throws ServiceRunException
     * @author yangyang
     * @version [v1.0.0, 2015年7月1日]
     * @since [产品/模块版本](可选)
     */
    protected House365RestObject<CmBrokerCommentEntity> doBusiness(
            Map<String, Object> map, CmUserEntity cmUser
    ) throws ServiceRunException {
        // 返回Json对象
        House365RestObject<CmBrokerCommentEntity> restObject = new House365RestObject<CmBrokerCommentEntity>();

        try {

            String result = brokerCommentService.transBrokerComment(map, cmUser);

            restObject.setTotal(result);
            return restObject;
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.error("积分商城-经纪人评价数据异常！");
            throw new ServiceRunException("网络不给力，请刷新重试");
        }
    }


    /**
     * 判断服务是否具有控制逻辑
     *
     * @return 是否判断
     */
    @Override
    public boolean isControlService() {

        return false;
    }

    /**
     * 判断服务是否需要记录日志
     *
     * @return 是否判断
     */
    @Override
    public boolean isLogService() {

        return false;
    }

    /**
     * 判断服务是否需要监控
     *
     * @return 是否判断
     */
    @Override
    public boolean isMonitorService() {

        return false;
    }

    /**
     * 事务回滚
     *
     * @return 事务回滚预留结果，暂无用途
     */
    @Override
    public Object rollback() {

        return null;
    }

    /**
     * 事务提交
     */
    @Override
    public void commit() {

    }
}
