package com.imooc.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.imooc.base.BaseInfoProperties;
import com.imooc.bo.VlogBO;
import com.imooc.enums.MessageEnum;
import com.imooc.enums.YesOrNo;
import com.imooc.mapper.MyLikedVlogMapper;
import com.imooc.mapper.VlogMapper;
import com.imooc.mapper.VlogMapperCustom;
import com.imooc.pojo.MyLikedVlog;
import com.imooc.pojo.Vlog;
import com.imooc.service.FansService;
import com.imooc.service.MsgService;
import com.imooc.service.VlogService;
import com.imooc.utils.PagedGridResult;
import com.imooc.vo.IndexVlogVO;
import org.apache.commons.lang3.StringUtils;
import org.n3r.idworker.Sid;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;

@Service
public class VlogServiceImpl extends BaseInfoProperties implements VlogService {

    @Autowired
    private VlogMapper vlogMapper;

    @Autowired
    private VlogMapperCustom vlogMapperCustom;

    @Autowired
    private MyLikedVlogMapper myLikedVlogMapper;

    @Autowired
    private FansService fansService;
    @Autowired
    private MsgService msgService;

    @Autowired
    private Sid sid;

    @Transactional
    @Override
    public void updateVlogStatus(String fileId,Integer status,String reason) {
//        Example example = new Example(Vlog.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("fileId", fileId);
//
//        Vlog pendingVlog = new Vlog();
//        pendingVlog.setStatus(status);
//        pendingVlog.setReason(reason);
//          vlogMapper.updateVlogStatus(fileId, example);

        // 示例：更新 vlog 表
        Map<String, Object> updateFields = new HashMap<>();
        updateFields.put("status", status);
        updateFields.put("reason", reason);

        vlogMapper.dynamicUpdate(
                "file_id",  // 主键字段名
                fileId,           // 主键值
                updateFields   // 更新字段
        );
    }

    @Transactional
    @Override
    public void updateVlogFirstImg(String fileId,String url,String fileUrl) {
//        Example example = new Example(Vlog.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("fileId", fileId);
//        Vlog pendingVlog = new Vlog();
//        pendingVlog.setFirstFrameImg(url);
//        pendingVlog.setUrl(fileUrl);
//
//        vlogMapper.updateByExampleSelective(pendingVlog, example);
        // 示例：更新 vlog 表
        Map<String, Object> updateFields = new HashMap<>();
        updateFields.put("first_frame_img", url);
        updateFields.put("url", fileUrl);

        vlogMapper.dynamicUpdate(
                "file_id",  // 主键字段名
                fileId,           // 主键值
                updateFields   // 更新字段
        );

    }

    @Transactional
    @Override
    public void createVlog(VlogBO vlogBO) {

//        String vid = sid.nextShort();
//
//        Vlog vlog = new Vlog();
//        BeanUtils.copyProperties(vlogBO, vlog);
//
//        vlog.setId(vid);
//
//        vlog.setLikeCounts(0);
//        vlog.setCommentsCounts(0);
//        vlog.setStatus(0);
//        vlog.setIsPrivate(YesOrNo.NO.type);
//
//        vlog.setCreatedTime(new Date());
//        vlog.setUpdatedTime(new Date());
//
//        vlogMapper.insert(vlog);
        String vid = sid.nextShort();
        Map<String, Object> vlog = new HashMap<>();

        vlog.put("id", vid);
        vlog.put("vloger_id", vlogBO.getVlogerId());
        vlog.put("url", vlogBO.getUrl());
        vlog.put("title", vlogBO.getTitle());
        vlog.put("width", vlogBO.getWidth());
        vlog.put("height", vlogBO.getHeight());
        vlog.put("is_private", YesOrNo.NO.type);
        vlog.put("created_time", new Date());
        vlog.put("updated_time", new Date());
        vlog.put("city_code", vlogBO.getCityCode());
        vlog.put("file_id", vlogBO.getFileId());
        vlog.put("first_frame_img", vlogBO.getFirstFrameImg());


        vlogMapper.dynamicInsert(vlog);

        //多条导入
//        List<Map<String, Object>> vlogList = new ArrayList<>();
//
//        Map<String, Object> vlog1 = new HashMap<>();
//        vlog1.put("id", sid.nextShort());
//        vlog1.put("title", "视频1");
//        vlogList.add(vlog1);
//
//        Map<String, Object> vlog2 = new HashMap<>();
//        vlog2.put("id", sid.nextShort());
//        vlog2.put("title", "视频2");
//        vlogList.add(vlog2);
//
//        vlogMapper.dynamicBatchInsert(vlogList);
    }

    @Override
    public PagedGridResult getIndexVlogList(String userId,
                                            String search,
                                            String cityCode,
                                            String status,
                                            Integer page,
                                            Integer pageSize) {

        PageHelper.startPage(page, pageSize);

        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(search)) {
            map.put("search", search);
        }
        if (StringUtils.isNotBlank(cityCode)) {
            map.put("cityCode", Integer.parseInt(cityCode));
        }
        if (StringUtils.isNotBlank(status)) {
            map.put("status", Integer.parseInt(status));
        }
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            System.err.println("key = " + entry.getKey() + ", value = " + entry.getValue()
                    + ", type = " + (entry.getValue() != null ? entry.getValue().getClass().getName() : "null"));
        }

        if(StringUtils.isNotBlank(userId)){
            // 从redis中获取举报信息
            String redisKey = REDIS_VIDEO_BLOCK + ":" + userId;
            Boolean hasKey = redis.keyIsExist(redisKey);
            if(hasKey){
                List<String> blockVdList = new ArrayList<>();
                ObjectMapper objectMapper = new ObjectMapper();
                List<String> reports = redis.lrange(redisKey, 0, -1);  // 查询用户的所有举报记录

                for (String report : reports) {
                    try {
                        Map<String, Object> reportMap = objectMapper.readValue(report, new TypeReference<Map<String, Object>>() {});
                        // 处理举报信息
                        String vlogId = (String) reportMap.get("vlogId");
                        blockVdList.add(vlogId);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
                map.put("blockVd",blockVdList);
            }
        }
        if(StringUtils.isNotBlank(userId)){
            // 从redis中获取拉黑信息
            String redisKey = REDIS_USER_BLOCK + ":" + userId;
            Boolean hasKey = redis.keyIsExist(redisKey);
            if(hasKey){
                List<String> blockUserList = new ArrayList<>();
                ObjectMapper objectMapper = new ObjectMapper();
                List<String> reports = redis.lrange(redisKey, 0, -1);  // 查询用户的所有举报记录

                for (String report : reports) {
                    try {
                        Map<String, Object> reportMap = objectMapper.readValue(report, new TypeReference<Map<String, Object>>() {});
                        // 处理拉黑信息
                        String vlogerId = (String) reportMap.get("vlogerId");
                        blockUserList.add(vlogerId);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
                map.put("blockUser",blockUserList);
            }
        }

        List<IndexVlogVO> list = vlogMapperCustom.getIndexVlogList(map);

        for (IndexVlogVO v : list) {
            String vlogerId = v.getVlogerId();
            String vlogId = v.getVlogId();

            if (StringUtils.isNotBlank(userId)) {
                // 用户是否关注该博主
                boolean doIFollowVloger = fansService.queryDoIFollowVloger(userId, vlogerId);
                v.setDoIFollowVloger(doIFollowVloger);

                // 判断当前用户是否点赞过视频
                v.setDoILikeThisVlog(doILikeVlog(userId, vlogId));
            }

            // 获得当前视频被点赞过的总数
            v.setLikeCounts(getVlogBeLikedCounts(vlogId));
            // 评论数
            v.setCommentsCounts(getVlogComment(vlogId));
        }

//        return list;
        return setterPagedGrid(list, page);
    }

    private IndexVlogVO setterVO(IndexVlogVO v, String userId) {
        String vlogerId = v.getVlogerId();
        String vlogId = v.getVlogId();

        if (StringUtils.isNotBlank(userId)) {
            // 用户是否关注该博主
            boolean doIFollowVloger = fansService.queryDoIFollowVloger(userId, vlogerId);
            v.setDoIFollowVloger(doIFollowVloger);

            // 判断当前用户是否点赞过视频
            v.setDoILikeThisVlog(doILikeVlog(userId, vlogId));
        }

        // 获得当前视频被点赞过的总数
        v.setLikeCounts(getVlogBeLikedCounts(vlogId));
        // 评论数
        v.setCommentsCounts(getVlogComment(vlogId));

        return v;
    }
//
    @Override
    public Integer getVlogBeLikedCounts(String vlogId) {
        String countsStr = redis.get(REDIS_VLOG_BE_LIKED_COUNTS + ":" + vlogId);
        if (StringUtils.isBlank(countsStr)) {
            countsStr = "0";
        }
        return Integer.valueOf(countsStr);
    }

    private Integer getVlogComment(String vlogId) {
        String countsStr = redis.get(REDIS_VLOG_COMMENT_COUNTS + ":" + vlogId);
        if (StringUtils.isBlank(countsStr)) {
            countsStr = "0";
        }
        return Integer.valueOf(countsStr);
    }


//
    private boolean doILikeVlog(String myId, String vlogId) {

        String doILike = redis.get(REDIS_USER_LIKE_VLOG + ":" + myId + ":" + vlogId);
        boolean isLike = false;
        if (StringUtils.isNotBlank(doILike) && doILike.equalsIgnoreCase("1")) {
            isLike = true;
        }
        return isLike;
    }
//
    @Override
    public IndexVlogVO getVlogDetailById(String userId, String vlogId) {

        Map<String, Object> map = new HashMap<>();
        map.put("vlogId", vlogId);

        List<IndexVlogVO> list = vlogMapperCustom.getVlogDetailById(map);

        if (list != null && list.size() > 0 && !list.isEmpty()) {
            IndexVlogVO vlogVO = list.get(0);
//            return vlogVO;
            return setterVO(vlogVO, userId);
        }

        return null;
    }

    @Transactional
    @Override
    public void changeToPrivateOrPublic(String userId,
                                        String vlogId,
                                        Integer yesOrNo) {
//        Example example = new Example(Vlog.class);
//        Example.Criteria criteria = example.createCriteria();
//        criteria.andEqualTo("id", vlogId);
//        criteria.andEqualTo("vlogerId", userId);
//
//        Vlog pendingVlog = new Vlog();
//        pendingVlog.setIsPrivate(yesOrNo);

        Map<String, Object> updates = new HashMap<>();
        updates.put("is_private", 2);
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("id", vlogId);
        conditions.put("vloger_id", userId);
        vlogMapper.updateVlogByConditions(
                updates,
                conditions
        );

    }

    @Transactional
    @Override
    public void changeVlogStatus(String userId,
                                 String vlogId,
                                 Integer status) {
        Map<String, Object> updates = new HashMap<>();
        updates.put("status", status);
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("id", vlogId);
        conditions.put("vloger_id", userId);
        vlogMapper.updateVlogByConditions(
                updates,
                conditions
        );

    }

    @Override
    public PagedGridResult queryMyVlogList(String userId,
                                           String myId,
                                           Integer page,
                                           Integer pageSize,
                                           Integer yesOrNo) {


        PageHelper.startPage(page, pageSize);
        Map<String, Object> map = new HashMap<>();
//        if (StringUtils.isNotBlank(search)) {
//            map.put("search", search);
//        }
//        if (StringUtils.isNotBlank(cityCode)) {
//            map.put("cityCode", cityCode);
//        }
//        if (StringUtils.isNotBlank(status)) {
//            map.put("status", status);
//        }

        map.put("vlogerId", userId);
        if (StringUtils.isNotBlank(myId)) {
            // 从redis中获取举报信息
            String redisKeyRp = REDIS_VIDEO_BLOCK + ":" + myId;
            Boolean hasKeyRp = redis.keyIsExist(redisKeyRp);
            if(hasKeyRp){
                List<String> blockVdList = new ArrayList<>();
                ObjectMapper objectMapper = new ObjectMapper();
                List<String> reports = redis.lrange(redisKeyRp, 0, -1);  // 查询用户的所有举报记录

                for (String report : reports) {
                    try {
                        Map<String, Object> reportMap = objectMapper.readValue(report, new TypeReference<Map<String, Object>>() {});
                        // 处理举报信息
                        String vlogId = (String) reportMap.get("vlogId");
                        blockVdList.add(vlogId);
                    } catch (JsonProcessingException e) {
                        e.printStackTrace();
                    }
                }
                map.put("blockVd",blockVdList);
            }
        }


        List<IndexVlogVO> list = vlogMapper.selectMyPublic(map);

        for (IndexVlogVO v : list) {
            String vlogId = v.getVlogId();
            // 获得当前视频被点赞过的总数
            v.setLikeCounts(getVlogBeLikedCounts(vlogId));
            // 评论数
            v.setCommentsCounts(getVlogComment(vlogId));
        }
        return setterPagedGrid(list, page);
    }

    @Transactional
    @Override
    public void userLikeVlog(String userId, String vlogId) {

        String rid = sid.nextShort();

        MyLikedVlog likedVlog = new MyLikedVlog();
        likedVlog.setId(rid);
        likedVlog.setVlogId(vlogId);
        likedVlog.setUserId(userId);
        likedVlog.setCreatedTime(new Date());

        myLikedVlogMapper.insert(likedVlog);
//        System.out.println(vlogId);
//
//        Vlog vlog = new Vlog();
//        vlog.setId(vlogId);
//        Vlog vlog1 = vlogMapper.selectOne(vlog);
//        System.out.println(vlog1.toString());
////        System.out.println(vlog1.getCreatedTime());

//        Vlog vlog2 = vlogMapper.selectByPrimaryKey(vlogId);
//        System.out.println(vlog2.toString());

//        Vlog vlog1 = vlogMapper.selectOne(new Vlog().setId(vlogId));
//        Vlog vlog = vlog1
//        System.out.println(vlog);

        // 系统消息：点赞短视频
        Vlog vlog = this.getVlog(vlogId);
        Map msgContent = new HashMap();
        msgContent.put("vlogId", vlogId);
        msgContent.put("vlogCover", vlog.getCover());
        msgService.createMsg(userId,
                            vlog.getVlogerId(),
                            MessageEnum.LIKE_VLOG.type,
                            msgContent);
    }
//
    @Override
    public Vlog getVlog(String id) {
//        Vlog vlog = vlogMapper.selectByPrimaryKey(id);
//        return vlog;
        Map<String, Object> map = new HashMap<>();
        map.put("vlogId", id);

        List<IndexVlogVO> list = vlogMapper.getVlogDetailFromId(map);

        if (list != null && list.size() > 0 && !list.isEmpty()) {
            IndexVlogVO result = list.get(0);
            Vlog vlogVO = new Vlog();
            BeanUtils.copyProperties(result, vlogVO);
            return vlogVO;
        }

        return null;
    }

    @Transactional
    @Override
    public void flushCounts(String vlogId, Integer counts) {
//
//        Vlog vlog = new Vlog();
//        vlog.setId(vlogId);
//        vlog.setLikeCounts(counts);
//        int i = vlogMapper.updateByPrimaryKeySelective(vlog);

        // 示例：更新 vlog 表
        Map<String, Object> updateFields = new HashMap<>();
        updateFields.put("like_counts", counts);

        vlogMapper.dynamicUpdate(
                "id",  // 主键字段名
                vlogId,           // 主键值
                updateFields   // 更新字段
        );

    }

    //
    @Transactional
    @Override
    public void userUnLikeVlog(String userId, String vlogId) {

        MyLikedVlog likedVlog = new MyLikedVlog();
        likedVlog.setVlogId(vlogId);
        likedVlog.setUserId(userId);

        myLikedVlogMapper.delete(likedVlog);
    }

    @Override
    public PagedGridResult getMyLikedVlogList(String userId,
                                              String myId,
                                              Integer page,
                                              Integer pageSize) {
        PageHelper.startPage(page, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        String useWho;
        if (StringUtils.isNotBlank(myId)) {
            useWho = myId;
        }else{
            useWho = userId;
        }
        // 从redis中获取拉黑信息
        String redisKey = REDIS_USER_BLOCK + ":" + useWho;
        Boolean hasKey = redis.keyIsExist(redisKey);
        if(hasKey){
            List<String> blockUserList = new ArrayList<>();
            ObjectMapper objectMapper = new ObjectMapper();
            List<String> reports = redis.lrange(redisKey, 0, -1);  // 查询用户的所有举报记录

            for (String report : reports) {
                try {
                    Map<String, Object> reportMap = objectMapper.readValue(report, new TypeReference<Map<String, Object>>() {});
                    // 处理拉黑信息
                    String vlogerId = (String) reportMap.get("vlogerId");
                    blockUserList.add(vlogerId);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
            map.put("blockUser",blockUserList);
            System.out.println(blockUserList);
        }

        // 从redis中获取举报信息
        String redisKeyRp = REDIS_VIDEO_BLOCK + ":" + useWho;
        Boolean hasKeyRp = redis.keyIsExist(redisKeyRp);
        if(hasKeyRp){
            List<String> blockVdList = new ArrayList<>();
            ObjectMapper objectMapper = new ObjectMapper();
            List<String> reports = redis.lrange(redisKeyRp, 0, -1);  // 查询用户的所有举报记录

            for (String report : reports) {
                try {
                    Map<String, Object> reportMap = objectMapper.readValue(report, new TypeReference<Map<String, Object>>() {});
                    // 处理举报信息
                    String vlogId = (String) reportMap.get("vlogId");
                    blockVdList.add(vlogId);
                } catch (JsonProcessingException e) {
                    e.printStackTrace();
                }
            }
            map.put("blockVd",blockVdList);
        }


        List<IndexVlogVO> list = vlogMapperCustom.getMyLikedVlogList(map);

        return setterPagedGrid(list, page);
    }

    @Override
    public PagedGridResult getMyFollowVlogList(String myId,
                                               Integer page,
                                               Integer pageSize) {
        PageHelper.startPage(page, pageSize);

        Map<String, Object> map = new HashMap<>();
        map.put("myId", myId);

        List<IndexVlogVO> list = vlogMapperCustom.getMyFollowVlogList(map);

        for (IndexVlogVO v : list) {
            String vlogerId = v.getVlogerId();
            String vlogId = v.getVlogId();

            if (StringUtils.isNotBlank(myId)) {
                // 用户必定关注该博主
                v.setDoIFollowVloger(true);

                // 判断当前用户是否点赞过视频
                v.setDoILikeThisVlog(doILikeVlog(myId, vlogId));
            }

            // 获得当前视频被点赞过的总数
            v.setLikeCounts(getVlogBeLikedCounts(vlogId));
        }

        return setterPagedGrid(list, page);
    }
//
    @Override
    public PagedGridResult getMyFriendVlogList(String myId,
                                               Integer page,
                                               Integer pageSize) {

        PageHelper.startPage(page, pageSize);

        Map<String, Object> map = new HashMap<>();
        map.put("myId", myId);

        List<IndexVlogVO> list = vlogMapperCustom.getMyFriendVlogList(map);

        for (IndexVlogVO v : list) {
            String vlogerId = v.getVlogerId();
            String vlogId = v.getVlogId();

            if (StringUtils.isNotBlank(myId)) {
                // 用户必定关注该博主
                v.setDoIFollowVloger(true);

                // 判断当前用户是否点赞过视频
                v.setDoILikeThisVlog(doILikeVlog(myId, vlogId));
            }

            // 获得当前视频被点赞过的总数
            v.setLikeCounts(getVlogBeLikedCounts(vlogId));
        }

        return setterPagedGrid(list, page);
    }

//    @Override
//    public Vlog getVlog(String id) {
//        return null;
//    }
}
