/*
 * 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.beust.jcommander.internal.Lists;
import com.google.common.base.Strings;
import com.house365.beans.entity.CmHouseCommentEntity;
import com.house365.beans.entity.CmHouseEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.vo.CmHouseCommentVo;
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.House365RestResponse;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.beans.response.CmDictionaryResponse;
import com.house365.ws.dao.interfaces.ICmHouseDao;
import com.house365.ws.interfaces.server.ICmDictionary;
import com.house365.ws.service.interfaces.ICmHouseCommentService;
import com.house365.ws.service.interfaces.ICmUserService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.CmCommonUtils;
import com.house365.ws.util.StringFileUtils;
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.*;

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

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

    @Autowired
    private ICmHouseCommentService<CmHouseCommentEntity> houseCommentService;

    @Autowired
    private ICmUserService<CmUserEntity> cmUserService;

    @Autowired
    private ICmHouseDao<CmHouseEntity> houseDao;

    @Autowired
    private ICmDictionary cmDictionary;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        Map<String, Object> resultMap = new HashMap<>();
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CmHouseCommentEntity> response = new House365RestResponse<>();
        // 业务校验统一入口
        try {
            //指定期间禁止评论
            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();
            }

            String cityKey = "";
            if (!StringUtils.isEmpty(map.get(CmConstant.CITY_KEY))) {
                cityKey = ((String[]) map.get(CmConstant.CITY_KEY))[0];
            }
            //此城市是否禁止评论
            CmDictionaryResponse forbidCityResponse = cmDictionary.getCmDictionaryById(14);
            String forbidCity = forbidCityResponse.getEntity().getDicValue();
            if (!Strings.isNullOrEmpty(forbidCity)) {
                List<String> forbidCityList = Lists.newArrayList(forbidCity.split(","));
                if (forbidCityList.contains(cityKey)) {

                    CmDictionaryResponse forbidTipResponse = cmDictionary.getCmDictionaryById(15);
                    String forbidTip = forbidTipResponse.getEntity().getDicValue();

                    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", forbidTip);
                    resultMap.put("msg", forbidTip);
                    return JSONObject.fromObject(resultMap).toString();
                }
            }

            CmCommonUtils.checkInterfaceParameter(CmConstant.CommentHouse, map);
            String[] contentArray = ((String[]) map.get(CmConstant.criticContent));
            boolean isForbid = StringFileUtils.hasForbiddenWord(contentArray[0]);
            if (isForbid) {
                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();
            }
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            CmUserEntity cmUser = cmUserService.registUserByUserId(map);
            if (cmUser == null) {
                throw new ServiceRunException("用户中心用户不存在!");
            }
            //保留用户给后面调用
            map.put("currentUserEntity", cmUser);

            Date gagDate = cmUser.getGagTime();
            if (gagDate != null && gagDate.compareTo(new Date()) > 0) {
                Calendar calGag = Calendar.getInstance();
                calGag.setTime(gagDate);
                Calendar calNow = Calendar.getInstance();
                Long minutesDif = (calGag.getTimeInMillis() - calNow.getTimeInMillis()) / 1000 / 60;
                //                Long hourDif = minutesDif / 60;
                //                if (hourDif == 0) {
                //                    if (minutesDif == 0) {
                //                        minutesDif = 1L;
                //                    }
                //                    throw new ServiceRunException("您已被禁言,距离解禁还有" + minutesDif + "分钟");
                //                } else {
                //                    throw new ServiceRunException("您已被禁言,距离解禁还有" + hourDif + "小时" + minutesDif % 60 + "分");
                //                }
                if (minutesDif > 0) {
                    throw new ServiceRunException("由于您之前的评论涉嫌违规，您已被限制评论");
                }
            }

            //校验评论次数是否超出限制
            //            if (houseCommentService.isCommentCountExceedLimit(cmUser)) {
            //                throw new ServiceRunException("评论失败,评论次数超过限制！");
            //            }
            String houseId = "";
            Integer channel = null;
            String cityKey = "";
            if (!StringUtils.isEmpty(map.get(CmConstant.HOUSEID))) {
                houseId = ((String[]) map.get(CmConstant.HOUSEID))[0];
            }
            if (!StringUtils.isEmpty(map.get(CmConstant.CHANNEL))) {
                channel = Integer.parseInt(((String[]) map.get(CmConstant.CHANNEL))[0]);
            }
            if (!StringUtils.isEmpty(map.get(CmConstant.CITY_KEY))) {
                cityKey = ((String[]) map.get(CmConstant.CITY_KEY))[0];
            }

            String ignoreCommentCity = MemoryPropertyPlaceholderConfigurer.getContextProperty(
                    "comment.ignoreCheckCity");
            HashSet ignoreCity = new HashSet<>();
            if (!Strings.isNullOrEmpty(ignoreCommentCity)) {
                ignoreCity = new HashSet(Arrays.asList(ignoreCommentCity.split(",")));
            }

            CmHouseEntity houseEntity = houseDao.getHouseByHouseId(Integer.valueOf(houseId), cityKey, channel);
            //如果是新楼盘,没有保存信息,肯定是第一次评价,只需检查是否已经评论5个楼盘
            Integer checkHouseId = houseEntity != null ? houseEntity.getId() : -1;

            CmDictionaryResponse cmDictionaryResponse = cmDictionary.getCmDictionaryById(2);
            String whiteList = cmDictionaryResponse.getEntity().getDicValue();
            if (!Strings.isNullOrEmpty(whiteList)) {
                whiteList = whiteList.startsWith(",") ? whiteList : "," + whiteList;
                whiteList = whiteList.endsWith(",") ? whiteList : "," + whiteList;
            }

            if (!whiteList.contains("," + cmUser.getPhoneNumber() + ",")) {
                if (!ignoreCity.contains(cityKey) && !houseCommentService.checkCountNum(cmUser.getId(), checkHouseId)) {
                    LOGGER.warn("您的评论过于频繁，请稍后再试 , userId:[{}],houseId[{}]", cmUser.getId(), checkHouseId);
                    resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                    resultMap.put("msg", "您的评论过于频繁，请稍后再试");
                    return JSONObject.fromObject(resultMap).toString();
                }
            }

            CmHouseCommentVo data = doBusiness(map);

            if (data == null || StringUtils.isEmpty(data.getResultCode())) {
                resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put("msg", "操作失败");
            } else if ("0".equals(data.getResultCode())) {
                resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put("msg", "接口调用异常或该用户不存在");
            } else if ("1".equals(data.getResultCode())) {
                resultMap.put("entity", data.getEntity());
                Map<String, Object> tempMap = new HashMap<>();
                tempMap.put("list", new int[]{});
                tempMap.put("total", 1);
                resultMap.put("data", tempMap);
                resultMap.put("result", ReturnAppResult.APP_SUCCESS.getResultCode());
                resultMap.put("msg", "操作成功");
            } else if ("2".equals(data.getResultCode())) {
                resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put("msg", "接口调用异常或该楼盘不存在");
            } else {
                resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put("msg", "接口异常，请校验参数并排查错误！");
            }
        } catch (ServiceRunException e) {
            LOGGER.error(e.getMessage());
            resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
            resultMap.put("msg", e.getMessage());
        }
        return JSONObject.fromObject(resultMap).toString();
    }

    /**
     * 业务层统逻辑处理
     *
     * @param  map
     * @return 统一返回参数
     * @throws ServiceRunException
     * @author yangyang
     * @version [v1.0.0, 2015年7月1日]
     * @since [产品/模块版本](可选)
     */
    protected CmHouseCommentVo doBusiness(Map<String, Object> map) throws ServiceRunException {
        try {
            return houseCommentService.transHouseComment(map);
        } catch (Exception ex) {
            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() {

    }
}
