package com.house365.ws.interfaces.rest;

import com.house365.beans.entity.CmHouseCommentEntity;
import com.house365.beans.entity.CmPraiseEntity;
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.ws.service.interfaces.ICmHouseCommentService;
import com.house365.ws.service.interfaces.ICmPraiseService;
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 java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 〈一句话功能简述〉<br>
 * 点赞接口
 *
 * @author Administrator
 * @version [版本号, 2015年5月5日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@Component("houseCommentPraiseInterface")
public class HouseCommentPraiseInterfaceImpl implements IHouseCommentPraiseInterface {

    /**
     * ID
     */
    public static final String COMMENT_ID = "commentId";
    /**
     * 日志记录器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(HouseCommentPraiseInterfaceImpl.class);
    /**
     * 参数列表
     */
    private static final String[] PARAMS = { COMMENT_ID};//CmConstant.USER_ID, CmConstant.USERID_TYPE, CmConstant.PRAISE 
    
    
    @Autowired
    ICmHouseCommentService<CmHouseCommentEntity> cmHouseCommentService;
    
    @Autowired
    ICmPraiseService<CmPraiseEntity> cmPraiseService;
    
    @Autowired
    ICmUserService<CmUserEntity> cmUserService;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
     // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        Map<String,Object> response = new HashMap<String, Object>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map);
        } catch (IllegalServiceParameterException e) {
            response.put("result",ReturnAppResult.APP_FAIL.getResultCode());
            response.put("msg",e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        
        // 业务层统一处理
        try {
            
             
            Map<String,String> data = doBusiness(map);
            //设定返回值
            String code = data.get("code")==null?null:data.get("code").toString();
            if("1".equals(code)){
                response.put("result",ReturnAppResult.APP_FAIL.getResultCode());
                response.put("msg",data.get("msg").toString());
            }else{
                response.put("result",ReturnAppResult.APP_SUCCESS.getResultCode());
                response.put("msg","点赞成功");
            }
            
        } catch (ServiceRunException e) {
        	response.put("result",ReturnAppResult.APP_FAIL.getResultCode());
            response.put("msg",e.getMessage());
        }

        return JSONObject.fromObject(response).toString();
    }
    
    public Object exectueOld(Parameter parameter) throws ServiceRunException {
     // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        Map<String,Object> response = new HashMap<String, Object>();

        // 业务校验统一入口
        try {
            checkInterfaceParameter(map);
        } catch (IllegalServiceParameterException e) {
            response.put("result",ReturnAppResult.APP_FAIL.getResultCode());
            response.put("msg",e.getMessage());
            return JSONObject.fromObject(response).toString();
        }
        
        // 业务层统一处理
        try {
            
            String userId =  ((String[])map.get(CmConstant.USER_ID))[0];
            Integer userIdType =  Integer.parseInt(((String[])map.get(CmConstant.USERID_TYPE))[0]);
            String cityKey = map.get(CmConstant.CITY_KEY)==null?null:((String[])map.get(CmConstant.USERID_TYPE))[0];
            CmUserEntity cmUserEntity = cmUserService.getUserByUserIdCityKeyUserType(userId, cityKey, userIdType);
            if(cmUserEntity==null){
                response.put("result",ReturnAppResult.APP_FAIL.getResultCode());
                response.put("msg","用户不存在!");
            }
            map.put("currentUser", cmUserEntity);
            Map<String,String> data = doBusiness(map);
            //设定返回值
            String code = data.get("code")==null?null:data.get("code").toString();
            if("1".equals(code)){
                response.put("result",ReturnAppResult.APP_FAIL.getResultCode());
                response.put("msg",data.get("msg").toString());
            }else{
                response.put("result",ReturnAppResult.APP_SUCCESS.getResultCode());
                Integer praise =  Integer.parseInt(((String[])map.get(CmConstant.PRAISE))[0]);
                if(CmConstant.PRAISE_ON == praise){
                    response.put("msg","点赞成功");
                }else{
                    response.put("msg","取消点赞");
                }
            }
            
        } catch (ServiceRunException e) {
            response.put("result",ReturnAppResult.APP_FAIL.getResultCode());
            response.put("msg",e.getMessage());
        }

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

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

    /**
     * 业务层统逻辑处理 获取抢客户信息
     *
     * @param
     * @return 统一返回参数
     * @author nizhengjia
     * @version [v1.0.0, 2015年5月6日]
     * @since [产品/模块版本](可选)
     */
    protected Map<String,String> doBusinessOld(Map<String, Object> map) throws ServiceRunException {
        // 返回Json对象
        Map<String,String> resultMap = new HashMap<String, String>();
       try{
           CmUserEntity user = (CmUserEntity)map.get("currentUser");
           
           String id = ((String[])map.get(COMMENT_ID))[0];
           
           //获取楼盘点评信息
           CmHouseCommentEntity houseCommentEntity = cmHouseCommentService.getById(Integer.valueOf(id));
           if(houseCommentEntity==null){
               resultMap.put("code", "1");
               resultMap.put("msg", "评论不存在！");
               return resultMap;
           }
           //点评记录
           CmPraiseEntity praiseEntity = new CmPraiseEntity();
           praiseEntity.setUserId(user.getId());
           praiseEntity.setHouseCriticId(houseCommentEntity.getId());
           Integer praise =  Integer.parseInt(((String[])map.get(CmConstant.PRAISE))[0]);
           QueryParams<CmPraiseEntity> queryParams = new QueryParams<CmPraiseEntity>();
           Map<String, Object> qmap = new HashMap<String, Object>();
           qmap.put("EQ_userId", user.getId());
           qmap.put("EQ_houseCriticId", houseCommentEntity.getId());
           queryParams.setSearchParams(qmap);
           List<CmPraiseEntity> praiseList = cmPraiseService.queryAll(queryParams);
           //取消点赞
           if(praise==CmConstant.PRAISE_NOT){
               if(praiseList==null || praiseList.size()==0){
                   resultMap.put("code", "1");
                   resultMap.put("msg", "评论未点赞过！");
               }else{
                   for(CmPraiseEntity entity:praiseList){
                       cmPraiseService.delete(entity.getId());
                   }//消赞需要扣除一个点赞
                   if(houseCommentEntity.getPraiseAmount()!=null &&houseCommentEntity.getPraiseAmount()>1){
                       houseCommentEntity.setPraiseAmount(houseCommentEntity.getPraiseAmount()-1);
                       cmHouseCommentService.update(houseCommentEntity);
                   }
               }
           }
           //点赞
           if(praise==CmConstant.PRAISE_ON){
               if(praiseList==null || praiseList.size()==0){
                   Integer num = cmPraiseService.save(praiseEntity);
                   if(num>0){
                       if(houseCommentEntity.getPraiseAmount()==null){
                           houseCommentEntity.setPraiseAmount(0);
                       }
                       //更新楼盘点评信息
                       houseCommentEntity.setPraiseAmount(houseCommentEntity.getPraiseAmount()+1);
                       cmHouseCommentService.update(houseCommentEntity);
                   }
               }else{
                   resultMap.put("code", "1");
                   resultMap.put("msg", "评论已点赞过！");
               }
           }
        } catch (Exception e) {
        	e.printStackTrace();
            LOGGER.error(e.getMessage());
            throw new ServiceRunException("网络不给力，请刷新重试");
        }
        return resultMap;
    }
    
    
    /**
     * 业务层统逻辑处理 获取抢客户信息
     *
     * @param
     * @return 统一返回参数
     * @author nizhengjia
     * @version [v1.0.0, 2015年5月6日]
     * @since [产品/模块版本](可选)
     */
    protected Map<String,String> doBusiness(Map<String, Object> map) throws ServiceRunException {
        // 返回Json对象
        Map<String,String> resultMap = new HashMap<String, String>();
       try{
           
           String id = ((String[])map.get(COMMENT_ID))[0];
           
           //获取楼盘点评信息
           CmHouseCommentEntity houseCommentEntity = cmHouseCommentService.getById(Integer.valueOf(id));
           if(houseCommentEntity==null){
               resultMap.put("code", "1");
               resultMap.put("msg", "评论不存在！");
               return resultMap;
           }      
             
           //更新楼盘点评信息
           houseCommentEntity.setPraiseAmount(houseCommentEntity.getPraiseAmount()+1);
           cmHouseCommentService.update(houseCommentEntity);

           //清除楼盘评论缓存
           cmHouseCommentService.removeCache(houseCommentEntity.getHouseId());
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
            throw new ServiceRunException("网络不给力，请刷新重试");
        }
        return resultMap;
    }
    
    

    @Override
    public boolean isControlService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isLogService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isMonitorService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Object rollback() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void commit() {
        // TODO Auto-generated method stub

    }

}
