/*
 * 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.google.common.base.Strings;
import com.house365.beans.entity.CmHouseCommentEntity;
import com.house365.beans.entity.CmHouseCommentReplyEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.commons.system.HttpClientUtil;
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.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.web.util.StringExtUtils;
import com.house365.ws.dao.interfaces.ICmHouseCommentDao;
import com.house365.ws.dao.interfaces.ICmHouseCommentReplyDao;
import com.house365.ws.service.interfaces.ICmHouseCommentReplyService;
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.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
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.io.IOException;
import java.util.*;

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

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

    @Autowired
    private ICmHouseCommentReplyService<CmHouseCommentReplyEntity> houseCommentReplyService;

    @Autowired
    private ICmUserService<CmUserEntity> cmUserService;

    @Autowired
    private ICmHouseCommentReplyDao<CmHouseCommentReplyEntity> cmHouseCommentReplyDao;

    @Autowired
    private ICmHouseCommentDao<CmHouseCommentEntity> houseCommentDao;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        //返回参数
        Map<String, Object> resultMap = new HashMap<>();
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<String> response = new House365RestResponse<>();
        String[] contentArray = ((String[]) map.get("replyContent"));
        String[] city = ((String[]) map.get("city"));
        // 业务校验统一入口
        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();
            }

            CmCommonUtils.checkInterfaceParameter(CmConstant.HouseCommentReply, map);
            boolean isForbid = StringFileUtils.hasForbiddenWord(contentArray[0]);
            if (isForbid) {
                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("error", "您的评论中包含屏蔽词，请修改后提交");
                resultMap.put("msg", "您的评论中包含屏蔽词，请修改后提交");
                return JSONObject.fromObject(resultMap).toString();
            }
        } catch (IllegalServiceParameterException e) {
            LOGGER.error(e.getMessage(), 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("用户中心用户不存在!");
            }

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

            House365RestObject<CmHouseCommentReplyEntity> data = doBusiness(map);

            //楼主id
            String commentId = "";
            //回复的楼主id
            String replyCommentId = "";

            String phones = "";

            String originalComment = "";

            if (cmUser.getUserName() != null && (!cmUser.getUserName().trim().equals(""))) {
                cmUser.setUserName(cmUser.getUserName());
            } else {
                //139****0935
                if (!Strings.isNullOrEmpty(cmUser.getPhoneNumber()) && cmUser.getPhoneNumber().length() >= 11) {
                    String newPhone = cmUser.getPhoneNumber().subSequence(0, 3) + "****" + cmUser.getPhoneNumber().subSequence(7, 11);
                    cmUser.setUserName(newPhone);
                }
            }

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

            if (!StringUtils.isEmpty(map.get("hostCommentId"))) {
                replyCommentId = ((String[]) map.get("hostCommentId"))[0];
            }

            if (StringUtils.isEmpty(replyCommentId)) {
                CmHouseCommentEntity houseCommentEntity = houseCommentDao.getById(Integer.valueOf(commentId));
                originalComment = houseCommentEntity.getCriticContent();
                String commentPhone = houseCommentEntity.getCriticPhone();
                if (!commentPhone.equalsIgnoreCase(cmUser.getPhoneNumber())) {
                    phones = commentPhone;
                }
            } else {
                CmHouseCommentEntity houseCommentEntity = houseCommentDao.getById(Integer.valueOf(commentId));
                String hostCommentPhone = houseCommentEntity.getCriticPhone();
                if (!hostCommentPhone.equalsIgnoreCase(cmUser.getPhoneNumber())) {
                    phones = hostCommentPhone + ',';
                }

                CmHouseCommentReplyEntity cmHouseCommentReplyEntity = cmHouseCommentReplyDao.getById(Integer.valueOf(replyCommentId));
                String commentPhone = cmHouseCommentReplyEntity.getCriticPhone();
                originalComment = cmHouseCommentReplyEntity.getContent();
                if (!commentPhone.equalsIgnoreCase(cmUser.getPhoneNumber())) {
                    phones += commentPhone + ',';
                }
            }

            if (!StringUtils.isEmpty(phones)) {
                List<NameValuePair> updateParams = new ArrayList<>();
                updateParams.add(new BasicNameValuePair("serviceCode", "Mps"));
                updateParams.add(new BasicNameValuePair("serviceName", "AddMessage"));
                updateParams.add(new BasicNameValuePair("app", "1"));
                updateParams.add(new BasicNameValuePair("source", "二手房"));
                updateParams.add(new BasicNameValuePair("phone", phones));
                updateParams.add(new BasicNameValuePair("cities", city[0]));
                updateParams.add(new BasicNameValuePair("alert", "您有一条楼盘点评回复可查看"));
                updateParams.add(new BasicNameValuePair("title", "您有一条楼盘点评回复可查看"));
                updateParams.add(new BasicNameValuePair("bizType", "4"));
                JSONObject TFRouteType = new JSONObject();
                TFRouteType.put("TFRouteType", 1055);

                TFRouteType.put("TFRouteParm", StringExtUtils.string2Base64("lppl_id=" + data.getEntity().getCommentId().toString()));
                updateParams.add(new BasicNameValuePair("extra", TFRouteType.toString()));
                JSONObject showmessage = new JSONObject();
                showmessage.put("lppl_id", data.getEntity().getCommentId());
                showmessage.put("lppl_reply", cmUser.getUserName() + ":" + contentArray[0]);
                showmessage.put("lppl_comment", originalComment);
                showmessage.put("source", "0");
                updateParams.add(new BasicNameValuePair("showmessage", showmessage.toString()));

                LOGGER.debug(MemoryPropertyPlaceholderConfigurer.getContextProperty("housecommentreply.url.test"));
                LOGGER.debug(updateParams.toString());
                try {
                    String updateResponse = HttpClientUtil.doGet(MemoryPropertyPlaceholderConfigurer.getContextProperty("housecommentreply.url.test"), updateParams, 10000, null);
                    LOGGER.debug(updateResponse);
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("操作失败");
                }
            }
            if (data == null || StringUtils.isEmpty(data.getTotal())) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("操作失败");
            } else if ("2".equals(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 ("3".equals(data.getTotal())) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("该用户不存在");
            } else if ("1".equals(data.getTotal())) {
                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", "操作成功");
                return JSONObject.fromObject(resultMap).toString();
            }

        } catch (ServiceRunException e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
        }

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

    /**
     * 业务层统逻辑处理
     *
     * @param map map
     * @return 统一返回参数
     * @throws ServiceRunException
     * @since [产品/模块版本](可选)
     */
    protected House365RestObject<CmHouseCommentReplyEntity> doBusiness(Map<String, Object> map) throws ServiceRunException {
        try {
            return houseCommentReplyService.transHouseCommentReply(map);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), 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() {

    }
}
