package com.sqx.modules.chat.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.DateUtils;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.chat.dao.ChatContentDao;
import com.sqx.modules.chat.dao.ChatConversationDao;
import com.sqx.modules.chat.entity.ChatContent;
import com.sqx.modules.chat.entity.ChatConversation;
import com.sqx.modules.chat.service.ChatContentService;
import com.sqx.modules.chat.service.ChatConversationService;
import com.sqx.modules.firstLogin.service.HrService;
import com.sqx.modules.resumes.entity.PostPush;
import com.sqx.modules.resumes.service.CompanyService;
import com.sqx.modules.resumes.service.PostPushService;
import com.sqx.modules.resumes.service.ResumesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;


@Service
public class ChatConversationServiceImpl extends ServiceImpl<ChatConversationDao, ChatConversation> implements ChatConversationService {

    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock();
    @Autowired
    private UserService userService;
    @Autowired
    private ChatContentService chatContentService;
    @Autowired
    private PostPushService postPushService;
    @Autowired
    private HrService hrService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private ResumesService resumesService;


    @Override
    public PageUtils selectChatConversationPage(Integer page, Integer limit, Long userId, String nickName) {
        Integer userType = userService.getById(userId).getUserType();
        return new PageUtils(baseMapper.selectChatConversationPage(new Page<>(page, limit), userId, nickName, userType));
    }


    @Override
    public int insertChatConversation(ChatConversation chatConversation) {
        return baseMapper.insertChatConversation(chatConversation);
    }

    @Override
    public ChatConversation selectChatConversation(Long userId, Long focusedUserId) {
        ChatConversation chatConversation = baseMapper.selectOne(new QueryWrapper<ChatConversation>().eq("user_id", userId).eq("focused_user_id", focusedUserId));
        if (chatConversation != null) {
            return chatConversation;
        }
        return baseMapper.selectOne(new QueryWrapper<ChatConversation>().eq("focused_user_id", userId).eq("user_id", focusedUserId));
    }


    @Override
    public Result insertChatConversations(ChatConversation chatConversation) {
        reentrantReadWriteLock.writeLock().lock();
        try {
            ChatConversation chatConversation1 = baseMapper.selectOne(new QueryWrapper<ChatConversation>().eq("user_id", chatConversation.getUserId()).eq("focused_user_id", chatConversation.getFocusedUserId()));
            if (chatConversation1 == null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(new Date());
                chatConversation.setCreateTime(format);
                chatConversation.setUpdateTime(format);
                baseMapper.insert(chatConversation);
                return Result.success().put("data", chatConversation);
            } else {
                if (!chatConversation.getPostPushId().equals(chatConversation1.getPostPushId())) {
                    chatConversation1.setPostPushId(chatConversation.getPostPushId());
                    baseMapper.updateById(chatConversation1);
                }
            }
            return Result.success().put("data", chatConversation1);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发起聊天出错" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试");
    }

    @Override
    public PageUtils adminSelectChatConversationPage(Integer page, Integer limit, Long userId,String nickName){
        return new PageUtils(baseMapper.adminSelectChatConversationPage(new Page<>(page,limit),userId,nickName));
    }

    @Override
    public Result insertChatConversationByChatVideo(Long userId,ChatConversation chatConversation,String messageType){
        reentrantReadWriteLock.writeLock().lock();
        try{
            Long byUserId;
            if(chatConversation.getUserId().equals(userId)){
                byUserId=chatConversation.getFocusedUserId();
            }else{
                byUserId=chatConversation.getUserId();
            }
            ChatContent chatContent1 = chatContentService.selectUserChatVideo(userId);
            if(chatContent1!=null){
                return Result.error("您正在通话中！");
            }
            chatContent1 = chatContentService.selectUserChatVideo(byUserId);
            if(chatContent1!=null){
                return Result.error("对方正在通话中！");
            }
            //获取系统配置 开启聊天是否需要赠送礼物或者门票
            Long chatConversationId=null;
            ChatConversation chatConversation1 = selectChatConversation(chatConversation.getUserId(), chatConversation.getFocusedUserId());
            if(chatConversation1==null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String format = sdf.format(new Date());
                chatConversation.setCreateTime(format);
                chatConversation.setUpdateTime(format);
                baseMapper.insertChatConversation(chatConversation);
                chatConversationId=chatConversation.getChatConversationId();
            }else{
                chatConversationId=chatConversation1.getChatConversationId();
            }
            ChatContent chatContent = new ChatContent();
            chatContent.setStatus(1);
            chatContent.setCreateTime(DateUtils.format(new Date()));
            chatContent.setMessageType(messageType);
            chatContent.setVideoStatus(1);
            chatContent.setUserId(userId);
            chatContent.setByUserId(byUserId);
            chatContent.setChatConversationId(chatConversationId);
            chatContent.setResumesId(chatConversation.getResumesId());
            chatContent.setPostPushId(chatConversation.getPostPushId());
            chatContent.setUserType(chatConversation.getUserType());
            chatContentService.save(chatContent);

            return Result.success().put("data",chatContent);
        }catch (Exception e){
            e.printStackTrace();
            log.error("发起聊天出错"+e.getMessage(),e);
        }finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试");
    }

    @Override
    public Object getConversationList(Integer page,Integer limit ,ChatConversation chatConversation) {
        Page<ChatConversation> pages;
        if (page != null && limit != null) {
            pages = new Page<>(page, limit);
        } else {
            pages = new Page<>();
            pages.setSize(-1);
        }
        QueryWrapper<ChatConversation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",chatConversation.getUserId()).orderByAsc("update_time");
        IPage<ChatConversation> selectPage = baseMapper.selectPage(pages,wrapper);
        List<ChatConversation> chatConversations = selectPage.getRecords();
        for (ChatConversation chatConversation1 : chatConversations){
            PostPush postPush = postPushService.getById(chatConversation1.getPostPushId());
            chatConversation1.setPostPush(postPush);
            chatConversation1.setHr(hrService.getByUserId(String.valueOf(chatConversation1.getFocusedUserId())));
            chatConversation1.setCompany(companyService.getById(postPush.getCompanyId()));
            chatConversation1.setUserEntity(userService.getById(chatConversation1.getFocusedUserId()));
            chatConversation1.setResumes(resumesService.getById(chatConversation1.getResumesId()));
        }
        return  selectPage;
    }

}