/*
 * 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.CmHouseCommentReplyEntity;
import com.house365.beans.entity.CmReplyPraiseEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.system.Page;
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.dao.interfaces.ICmReplyPraiseDao;
import com.house365.ws.service.interfaces.ICmHouseCommentReplyService;
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.HashMap;
import java.util.List;
import java.util.Map;

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

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

    @Autowired
    private ICmUserService<CmUserEntity> cmUserService;
    @Autowired
    private ICmReplyPraiseDao<CmReplyPraiseEntity> cmReplyPraise;
    @Autowired
    private ICmHouseCommentReplyService<CmHouseCommentReplyEntity> houseCommentReplyService;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CmHouseCommentReplyEntity> response = new House365RestResponse<CmHouseCommentReplyEntity>();
        // 业务校验统一入口
        try {
            checkInterfaceParameter(map);
        } catch (IllegalServiceParameterException e) {
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg(e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        // 业务层统一处理
        try {
            House365RestObject<CmHouseCommentReplyEntity> data = doBusiness(map);
            response.setData(data);
            if (StringUtils.isEmpty(data.getTotal())) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("操作失败");
            } else {
                response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                response.setMsg("操作成功");
            }

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

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

    /**
     * 业务层统校验自己所需参数是否存在
     *
     * @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.HouseCommentReplyList) {
            // 如果不存在跳出 同时抛出相应异常
            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<CmHouseCommentReplyEntity> doBusiness(
        Map<String, Object> map
    ) throws ServiceRunException {
        // 返回Json对象
        House365RestObject<CmHouseCommentReplyEntity> restObject = new House365RestObject<CmHouseCommentReplyEntity>();
        try {
            Map<String, Object> searchParams = new HashMap<String, Object>();

            // 评论Id
            String commentId = null;
            // 当前页
            String currentPage = null;
            // 页数
            String pageSize = null;
   /*     //用户id
        String userId=null;
        //用户id类型
        Integer userIdType=null;
        //用户所在城市
        String userCityKey=null;
        if (!StringUtils.isEmpty(map.get(CmConstant.USER_ID))) {
            userId = ((String[]) map.get(CmConstant.USER_ID))[0];
        }
        if (!StringUtils.isEmpty(map.get(CmConstant.USERID_TYPE))) {
            userIdType = Integer.parseInt(((String[]) map.get(CmConstant.USERID_TYPE))[0]);
        }
        if (!StringUtils.isEmpty(map.get(CmConstant.USER_CITY_KEY))) {
            userCityKey = ((String[]) map.get(CmConstant.USER_CITY_KEY))[0];
        }*/
            if (!StringUtils.isEmpty(map.get(CmConstant.COMMENTID))) {
                commentId = ((String[]) map.get(CmConstant.COMMENTID))[0];
            }
            if (!StringUtils.isEmpty(map.get(CmConstant.PAGE))) {
                currentPage = ((String[]) map.get(CmConstant.PAGE))[0];
            }
            if (!StringUtils.isEmpty(map.get(CmConstant.PAGESIZE))) {
                pageSize = ((String[]) map.get(CmConstant.PAGESIZE))[0];
            }
            searchParams.put("EQ_commentId", commentId);
            searchParams.put("EQ_isDeleted", 0);
            searchParams.put("EQ_isReplyByManager", 0);
            searchParams.put("EQ_checkStatus", 1);
            Page page = new Page();
            if (null != currentPage) {
                page.setCurrentPage(Integer.valueOf(currentPage));

            }
            if (null != pageSize) {
                page.setPageSize(Integer.valueOf(pageSize));
            }
            QueryParams<CmHouseCommentReplyEntity> queryParams = new QueryParams<CmHouseCommentReplyEntity>(
                searchParams);
            queryParams.setOrderColumn("create_time");
            queryParams.setOrderMode("desc");
            queryParams.setPaging(page);
            List<CmHouseCommentReplyEntity> replyList = houseCommentReplyService.transHouseCommentReplyList(
                queryParams);
            for (CmHouseCommentReplyEntity repEntity : replyList) {
                String newPhone = "";
                if (!Strings.isNullOrEmpty(repEntity.getCriticPhone()) && repEntity.getCriticPhone().length() >= 11) {
                    newPhone = repEntity.getCriticPhone().subSequence(0,
                                                                      3) + "****" + repEntity.getCriticPhone().subSequence(
                        7, 11);
                }
                repEntity.setCriticPhone(newPhone);
            }
        /*if(userId!=null){
            //获取点赞情况
            CmUserEntity cmUser = cmUserService.getUserByUserIdCityKeyUserType(userId, userCityKey, userIdType);
            if(cmUser!=null){//用户不存在，则不可能点过赞
                QueryParams<CmReplyPraiseEntity> qp = new QueryParams<CmReplyPraiseEntity>();
                Map<String,Object> qmap = new HashMap<String, Object>();
                for(CmHouseCommentReplyEntity cmEntity : replyList){
                    qmap.put("EQ_userId", cmUser.getId());
                    qmap.put("EQ_houseCriticId", cmEntity.getId());
                    qp.setSearchParams(qmap);
                    List<CmReplyPraiseEntity> list = cmReplyPraise.queryAll(qp);
                    if(list!=null && list.size()>0){
                        cmEntity.setIsPraised(1);
                    }
                }
            }
        }*/

            restObject.setList(replyList);
            restObject.setTotal(String.valueOf(queryParams.getPaging().getRecords()));
            return restObject;
        } catch (Exception ex) {
            ex.printStackTrace();
            LOGGER.error("积分商城-楼盘回复列表数据异常！");
            throw new ServiceRunException("网络不给力，请刷新重试");
        }
    }


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

        return false;
    }

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

        return false;
    }

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

        return false;
    }

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

        return null;
    }

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

    }
}
