package com.cftech.like.web;

import com.alibaba.fastjson.JSONObject;
import com.cftech.core.sql.Conds;
import com.cftech.like.model.Like;
import com.cftech.like.service.LikeService;
import com.cftech.sys.security.AttrValidateUtil;
import com.esotericsoftware.minlog.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
/**
 * 前端点赞接口
 * Created by mubo 10/11/2017.
 */
@RestController
@RequestMapping("/mobile/auth/like")
public class MobileLikeController {

    @Autowired
    private LikeService likeService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 点赞
     * @Param moduleType 编号
     * @Param entityId  被点赞记录id
     * @Param type 0:点赞
     * @Param userId
     */
    @RequestMapping(value = "/like", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject like(Like like, String appid, HttpServletRequest request) {
        //判断参数是否合格
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("errorNo", 1);




        try {
            //saveResult = likeService.saveLike(like);
            likeService.saveModulLike(like);
                    rtnJson.put("errorNo",0);
                    Log.info("点赞成功");
        } catch (Exception e) {
            rtnJson.put("errorNo",1);
            rtnJson.put("errorMsg","系统异常");
            e.printStackTrace();
        }
        return rtnJson;
    }
    /**
     * 取消点赞
     * @Param moduleType 编号
     * @Param entityId  被点赞记录id
     * @Param type 0:点赞
     * @Param userId
     */
    @RequestMapping(value = "/clearLike", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject clearLike(Like like,String appid,HttpServletRequest request) {
        //判断参数是否合格
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("errorNo", 1);

        Boolean saveResult = false;
        try {
            //缓存key
                saveResult = likeService.clearLike(like);
                    rtnJson.put("errorNo",0);
                    Log.info("取消点赞成功");
        } catch (Exception e) {
            rtnJson.put("errorNo",1);
            rtnJson.put("errorMsg","系统异常");
            e.printStackTrace();
        }
        return rtnJson;
    }
    /**
     * 获取统计点赞数
     * @Param moduleType 编号
     * @Param entityId  被点赞记录id
     * @Param type 0：点赞
     * @Param userId
     * */
    @RequestMapping(value = "/getLikeCount", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getLikeCount(Like like,String appid,HttpServletRequest request) {
        //判断参数是否合格
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("errorNo", 1);
        boolean result = AttrValidateUtil.myValidateUtil(like,"moduleType","entityId","type","userId");
        if(!result){
            rtnJson.put("errorMsg","参数异常");
            return  rtnJson;
        }
        Integer saveResult = 0;
        try {
            Conds conds = new Conds();
            conds.equal("module_type",like.getModuleType());
            conds.equal("entity_id",like.getEntityId());
            conds.equal("type",like.getModuleType());
            conds.equal("user_id",like.getUserId());
            saveResult = likeService.getLikeCount(conds);
            rtnJson.put("errorNo",0);
            rtnJson.put("data",saveResult);
        } catch (Exception e) {
            rtnJson.put("errorNo",1);
            rtnJson.put("errorMsg","系统异常");
            e.printStackTrace();
        }
        return rtnJson;
    }
    /**
     * 获取缓存点赞数
     * @Param moduleType 编号
     * @Param entityId  被点赞记录id
     * @Param type 0：点赞
     * @Param userId
     * */
    @RequestMapping(value = "/getLikeCountOnCache", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getLikeCountOnCache(Like like,String appid,HttpServletRequest request) {
        //判断参数是否合格
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("errorNo", 1);
        boolean result = AttrValidateUtil.myValidateUtil(like,"moduleType","entityId","type","userId");
        if(!result){
            rtnJson.put("errorMsg","参数异常");
            return  rtnJson;
        }
        Integer saveResult = 0;
        try {
            //缓存key
            String redisCollectionKey = "LIKE:" + like.getAccountsId() + ":" + like.getModuleType() + ":" + like.getEntityId();
            Object resultValue=redisTemplate.opsForValue().get(redisCollectionKey);
            rtnJson.put("data",resultValue);
        } catch (Exception e) {
            //key不存在
            rtnJson.put("data",0);
            e.printStackTrace();
        }
        rtnJson.put("errorNo",0);
        return rtnJson;
    }
    /**
     * 获取点赞记录
     * @Param moduleType 编号
     * @Param entityId  被点赞记录id
     * @Param type 0：点赞
     * @Param userId
     * */
    @RequestMapping(value = "/getLikeByAttr", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JSONObject getlikeByAttr(Like like,String appid,HttpServletRequest request) {
        JSONObject rtnJson = new JSONObject();
        rtnJson.put("errorNo", 1);
        boolean result = false;
        Conds conds = new Conds();
        if(like.getId()!= null){
            conds.equal("t.id",like.getId());
            result = true;
        }else{
            result = AttrValidateUtil.myValidateUtil(like,"moduleType","entityId","type","userId");
            conds.equal("module_type",like.getModuleType());
            conds.equal("entity_id",like.getEntityId());
            conds.equal("type",like.getModuleType());
            conds.equal("user_id",like.getUserId());
        }
        if(!result){
            rtnJson.put("errorMsg","参数异常");
            return  rtnJson;
        }
        try {
            like = likeService.fetchSearchByConds(conds);
            rtnJson.put("errorNo",0);
            rtnJson.put("data",like);
        } catch (Exception e) {
            rtnJson.put("errorNo",1);
            rtnJson.put("errorMsg","系统异常");
            e.printStackTrace();
        }
        return rtnJson;
    }
    /**
     * 点赞操作缓存
     * */
    private Boolean changeRedisData(String path, Integer flag){
        StringRedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        //redisTemplate.setValueSerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        Object oldValue= null;
        try {
            oldValue = redisTemplate.opsForValue().get(path);
        } catch (Exception e) {
            Log.info("第一个点赞的人");
        }
        if(oldValue!=null){
            try {
                oldValue=redisTemplate.opsForValue().increment(path,flag);
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }else{
            if(flag==1){
                redisTemplate.opsForValue().set(path,flag.toString());
                oldValue=1l;
            }else{
                return false;
            }
        }
        return true;
    }
}