/*
 * 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.*;
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.web.util.SpringContextUtil;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.dao.interfaces.ICmHouseDao;
import com.house365.ws.dao.interfaces.ICmPraiseDao;
import com.house365.ws.service.interfaces.ICmHouseCommentReplyService;
import com.house365.ws.service.interfaces.ICmHouseCommentService;
import com.house365.ws.service.interfaces.ICmUserService;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.math.NumberUtils;
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;
import java.util.concurrent.TimeUnit;

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

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

    @Autowired
    private ICmHouseCommentService<CmHouseCommentEntity> houseCommentService;
    @Autowired
    private ICmHouseDao<CmHouseEntity> houseDao;
    @Autowired
    private ICmUserService<CmUserEntity> cmUserService;
    @Autowired
    private ICmPraiseDao<CmPraiseEntity> cmPraise;
    @Autowired
    private ICmHouseCommentReplyService<CmHouseCommentReplyEntity> houseCommentReplyService;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CmHouseCommentEntity> response = new House365RestResponse<CmHouseCommentEntity>();
        // 业务校验统一入口
        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 = doBusiness(map);

            if (resultMap.containsKey("isCache") && (boolean) resultMap.get("isCache")) {
                return resultMap.get("cacheJSON");
            }

            House365RestObject<CmHouseCommentEntity> data = (House365RestObject<CmHouseCommentEntity>) resultMap.get(
                    "result");
            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对象
     * @since [产品/模块版本](可选)
     */
    protected void checkInterfaceParameter(Map<String, Object> map) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : CmConstant.HouseCommentList) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                LOGGER.error("业务入口参数异常：" + str + "参数为空!");
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

    /**
     * 业务层统逻辑处理
     *
     * @param map parameters map
     * @return 统一返回参数
     * @throws ServiceRunException
     */
    protected Map<String, Object> doBusiness(Map<String, Object> map) throws ServiceRunException {
        Map<String, Object> resultMap = new HashMap<>();
        // 返回Json对象
        House365RestObject<CmHouseCommentEntity> restObject = new House365RestObject<>();
        try {

            Map<String, Object> searchParams = new HashMap<>();

            //楼盘Id
            Integer houseId = null;
            // 当前页
            Integer currentPage = null;
            // 当前页
            Integer pageSize = null;
            //物业类型
            Integer channel = 0;
            //城市编号
            String cityKey = null;
            //是否有图
            String hasPicture = null;
            //是否加精
            String isExcellent = null;
            //用户id
            String userId = null;
            //用户id类型
            Integer userIdType = null;
            //用户所在城市
            String userCityKey = null;

            if (map.get(CmConstant.USER_ID) != null && ((String[]) map.get(CmConstant.USER_ID)).length > 0) {
                userId = ((String[]) map.get(CmConstant.USER_ID))[0];
            }
            if (map.get(CmConstant.USERID_TYPE) != null && ((String[]) map.get(CmConstant.USERID_TYPE)).length > 0) {
                String[] array = ((String[]) map.get(CmConstant.USERID_TYPE));
                if (checkNumOfArrayParameter(array)) {
                    userIdType = Integer.parseInt(((String[]) map.get(CmConstant.USERID_TYPE))[0]);
                }
            }
            if (map.get(CmConstant.USER_CITY_KEY) != null && ((String[]) map.get(
                    CmConstant.USER_CITY_KEY)).length > 0) {
                userCityKey = ((String[]) map.get(CmConstant.USER_CITY_KEY))[0];
            }
            if (map.get(CmConstant.HOUSEID) != null && ((String[]) map.get(CmConstant.HOUSEID)).length > 0) {
                String[] array = ((String[]) map.get(CmConstant.HOUSEID));
                if (checkNumOfArrayParameter(array)) {
                    houseId = Integer.parseInt(((String[]) map.get(CmConstant.HOUSEID))[0]);
                }
            }
            if (map.get(CmConstant.PAGE) != null && ((String[]) map.get(CmConstant.PAGE)).length > 0) {
                String[] array = ((String[]) map.get(CmConstant.PAGE));
                if (checkNumOfArrayParameter(array)) {
                    currentPage = Integer.parseInt(((String[]) map.get(CmConstant.PAGE))[0]);
                }
            }
            if (map.get(CmConstant.PAGESIZE) != null && ((String[]) map.get(CmConstant.PAGESIZE)).length > 0) {
                String[] array = ((String[]) map.get(CmConstant.PAGESIZE));
                if (checkNumOfArrayParameter(array)) {
                    pageSize = Integer.parseInt(((String[]) map.get(CmConstant.PAGESIZE))[0]);
                }
            }
            if (map.get(CmConstant.CHANNEL) != null && ((String[]) map.get(CmConstant.CHANNEL)).length > 0) {
                String[] array = ((String[]) map.get(CmConstant.CHANNEL));
                if (checkNumOfArrayParameter(array)) {
                    channel = Integer.parseInt(((String[]) map.get(CmConstant.CHANNEL))[0]);
                }
            }
            if (map.get(CmConstant.CITY_KEY) != null && ((String[]) map.get(CmConstant.CITY_KEY)).length > 0) {
                cityKey = ((String[]) map.get(CmConstant.CITY_KEY))[0];
            }
            if (map.get(CmConstant.IS_EXCELLENT) != null && ((String[]) map.get(CmConstant.IS_EXCELLENT)).length > 0) {
                isExcellent = ((String[]) map.get(CmConstant.IS_EXCELLENT))[0];
            }
            if (map.get(CmConstant.HAS_PICTURE) != null && ((String[]) map.get(CmConstant.HAS_PICTURE)).length > 0) {
                hasPicture = ((String[]) map.get(CmConstant.HAS_PICTURE))[0];
            }

            RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");
            StringBuilder keyBuilder = new StringBuilder("comment_");
            keyBuilder.append(houseId).append("_").append(currentPage).append("_").append(currentPage).append(
                    "_").append(pageSize).append("_").append(channel).append("_").append(cityKey).append("_").append(
                    hasPicture).append("_").append(isExcellent).append("_").append(userId).append("_").append(
                    userIdType).append("_").append(userCityKey);

            String houseCommentKey = String.valueOf(houseId) + "_commentKeysKey";
            String cacheKey = keyBuilder.toString();
            String listResponse = "";
            String cacheValue = redisUtils.getValByKeyNew(cacheKey);

            if (!Strings.isNullOrEmpty(cacheKey) && cacheValue != null && !Strings.isNullOrEmpty(
                    cacheValue) && !"null".equalsIgnoreCase(cacheValue)) {

                if (!redisUtils.isSetMember(houseCommentKey, cacheKey)) {
                    redisUtils.setAdd(houseCommentKey, cacheKey);
                }

                if (redisUtils.hasKey(cacheKey)) {
                    resultMap.put("isCache", true);
                    resultMap.put("cacheJSON", redisUtils.getValByKeyNew(cacheKey));
                    return resultMap;
                }

            }

            resultMap.put("isCache", false);
            //获取本地楼盘id
            CmHouseEntity houseEntity = houseDao.getHouseByHouseId(houseId, cityKey, channel);
            if (houseEntity == null) {
                LOGGER.info("积分商城-无评论数据！houseEntity is null! houseId:[{}],citykey:[{}],channel[{}]", houseId, cityKey,
                        channel);
                restObject.setList(null);
                restObject.setTotal("0");
                resultMap.put("result", restObject);
                return resultMap;
            }

            Integer localHouseId = houseEntity.getId();
            searchParams.put("EQ_houseId", localHouseId);
            searchParams.put("EQ_isDeleted", 0);
            searchParams.put("EQ_checkStatus", 1);
            if (isExcellent != null && isExcellent.equals("true")) {
                searchParams.put("EQ_isExcellent", 1);
            }
            if (hasPicture != null && hasPicture.equals("true")) {
                searchParams.put("EQ_hasPictures", "true");
            }


            QueryParams<CmHouseCommentEntity> queryParams = new QueryParams<>(searchParams);
            Page page = new Page();
            page.setCurrentPage(currentPage);
            page.setPageSize(pageSize);

            //排序
            if (map.get(CmConstant.ORDER_FIELD) != null) {
                String orderField = ((String[]) map.get(CmConstant.ORDER_FIELD))[0];
                queryParams.setOrderColumn(orderField);
                if (map.get(CmConstant.ORDER_DESC_OR_ACS) != null) {
                    String ascOrDesc = ((String[]) map.get(CmConstant.ORDER_DESC_OR_ACS))[0];
                    queryParams.setOrderMode(ascOrDesc);
                }
            } else {
                queryParams.setOrderColumn("is_sticked desc , comment_date");
            }

            queryParams.setPaging(page);
            List<CmHouseCommentEntity> cmHouseCommentsList = houseCommentService.queryByPage(queryParams);
            if (!Strings.isNullOrEmpty(userId)) {
                //获取点赞情况
                CmUserEntity cmUser = cmUserService.getUserByUserIdCityKeyUserType(userId, userCityKey, userIdType);
                if (cmUser != null) {//用户不存在，则不可能点过赞
                    QueryParams<CmPraiseEntity> qp = new QueryParams<>();
                    Map<String, Object> qmap = new HashMap<>();
                    for (CmHouseCommentEntity cmEntity : cmHouseCommentsList) {
                        qmap.put("EQ_userId", cmUser.getId());
                        qmap.put("EQ_houseCriticId", cmEntity.getId());
                        qp.setSearchParams(qmap);
                        List<CmPraiseEntity> list = cmPraise.queryAll(qp);
                        if (list != null && list.size() > 0) {
                            cmEntity.setIsPraised(1);
                        }
                    }
                }
            }
            for (CmHouseCommentEntity repEntity : cmHouseCommentsList) {
                String newPhone = "";
                if (!Strings.isNullOrEmpty(repEntity.getCriticPhone())) {
                    newPhone = repEntity.getCriticPhone().subSequence(0,
                            3) + "****" + repEntity.getCriticPhone().subSequence(
                            7, 11);
                }
                repEntity.setCriticPhone(newPhone);

                if (repEntity.getIsAnonymous() != null && repEntity.getIsAnonymous() == 1) {
                    //使用匿名头像
                    repEntity.setUserPhoto("http://passport.house365.com/static/images/default_avatar_middle.png");
                }

                Map<String, Object> replyQueryMap = new HashMap<>();
                replyQueryMap.put("EQ_commentId", repEntity.getId());
                replyQueryMap.put("EQ_isReplyByManager", 1);
                replyQueryMap.put("EQ_isDeleted", 0);
                QueryParams<?> replyQuery = new QueryParams<>();
                replyQuery.setSearchParams(replyQueryMap);
                List<CmHouseCommentReplyEntity> managerReplylist = houseCommentReplyService.queryByPage(replyQuery);
                if (managerReplylist != null && managerReplylist.size() != 0) {
                    CmHouseCommentReplyEntity commentReply = managerReplylist.get(0);
                    commentReply.setCriticName("小编回复");
                    repEntity.setManagerReply(commentReply);
                }
            }

            restObject.setList(cmHouseCommentsList);
            restObject.setTotal(String.valueOf(queryParams.getPaging().getRecords()));

            House365RestResponse<CmHouseCommentEntity> response = new House365RestResponse<CmHouseCommentEntity>();
            response.setData(restObject);
            if (StringUtils.isEmpty(restObject.getTotal())) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("操作失败");
            } else {
                response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                response.setMsg("操作成功");
            }

            redisUtils.setAdd(houseCommentKey, cacheKey);
            redisUtils.setValueNew(cacheKey, JSONObject.fromObject(response).toString());
            redisUtils.setValueExpireNew(cacheKey, JSONObject.fromObject(response).toString(), 10, TimeUnit.DAYS);

            resultMap.put("result", restObject);
            return resultMap;
        } catch (Exception ex) {
            LOGGER.error("积分商城-楼盘评论列表数据异常！", ex);
            throw new ServiceRunException(ex.getMessage());
        }
    }

    private boolean checkNumOfArrayParameter(String[] parameter) {
        return (parameter.length > 0 && NumberUtils.isNumber(parameter[0]));
    }

    /**
     * 判断服务是否具有控制逻辑
     *
     * @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() {

    }
}
