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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.entity.UserEntity;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.chat.dao.RoomAuditDao;
import com.sqx.modules.chat.entity.ChatContent;
import com.sqx.modules.chat.entity.ChatConversation;
import com.sqx.modules.chat.entity.RoomAudit;
import com.sqx.modules.chat.service.ChatContentService;
import com.sqx.modules.chat.service.ChatConversationService;
import com.sqx.modules.chat.service.RoomAuditService;
import com.sqx.modules.common.service.CommonInfoService;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.trtc.v20190722.TrtcClient;
import com.tencentcloudapi.trtc.v20190722.models.RemoveUserByStrRoomIdRequest;
import com.tencentcloudapi.trtc.v20190722.models.RemoveUserByStrRoomIdResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 房间
 */
@Service
public class RoomAuditServiceImpl extends ServiceImpl<RoomAuditDao, RoomAudit> implements RoomAuditService {

    @Autowired
    private ChatConversationService chatConversationService;
    @Autowired
    private CommonInfoService commonInfoService;
    @Autowired
    private ChatContentService chatContentService;
    @Autowired
    private UserService userService;

    @Override
    public String notifyRoomAudit(JSONObject jsonObject){
        String suggestion = jsonObject.getString("Suggestion");
        JSONArray labelsArray = jsonObject.getJSONArray("Labels");
        StringBuilder labels=new StringBuilder();
        if(labelsArray!=null && labelsArray.size()>0){
            for (int i=0;i<labelsArray.size();i++){
                JSONObject jsonObject1 = labelsArray.getJSONObject(i);
                labels.append(jsonObject1.getString("Label"));
                if((i+1)<labelsArray.size()){
                    labels.append(",");
                }
            }
        }
        JSONArray imageSegmentsArray = jsonObject.getJSONArray("AudioSegments");
        StringBuilder urls=new StringBuilder();
        StringBuilder texts=new StringBuilder();
        if(imageSegmentsArray!=null && imageSegmentsArray.size()>0){
            for (int i=0;i<imageSegmentsArray.size();i++){
                JSONObject jsonObject1 = imageSegmentsArray.getJSONObject(i);
                JSONObject result = jsonObject1.getJSONObject("Result");
                if(result!=null){
                    String url = result.getString("Url");
                    String text = result.getString("Text");
                    urls.append(url);
                    texts.append(text);
                    if((i+1)<imageSegmentsArray.size()){
                        urls.append(",");
                        texts.append(",");
                    }

                }
            }
        }


        //根据url获取信息 segment-trtc/{sdk_app_id}/audio_{room_id}_{user_id}_{timestamp}.mp3（音频格式）
        String url = urls.toString();
        if(!"Pass".equals(suggestion) &&StringUtils.isNotEmpty(url)){
            RoomAudit roomAudit=new RoomAudit();
            String[] split = url.split(",");
            String urlStr = split[0];
            String appId=urlStr.substring(urlStr.indexOf("segment-trtc/")+13,urlStr.indexOf("/audio_"));
            String audio=urlStr.substring(urlStr.indexOf("/audio_")+7,urlStr.indexOf(".mp3"));
            String[] s1 = audio.split("_");
            String roomNo=s1[0];
            String userId=s1[1];
            String timestamp=s1[2];
            roomAudit.setRoomNo(roomNo);
            roomAudit.setUserId(Long.parseLong(userId));
            ChatConversation chatConversation = chatConversationService.getById(roomNo);
            if(userId.equals(chatConversation.getUserId().toString())){
                roomAudit.setRoomUserId(chatConversation.getFocusedUserId());
            }else{
                roomAudit.setRoomUserId(chatConversation.getUserId());
            }
            roomAudit.setUrlTime(DateUtils.format(new Date(Long.parseLong(String.valueOf(timestamp+"000")))));
            roomAudit.setSuggestion(suggestion);
            roomAudit.setLabels(labels.toString());
            roomAudit.setUrl(url);
            roomAudit.setStatus(1);
            roomAudit.setAudioText(texts.toString());
            roomAudit.setCreateTime(DateUtils.format(new Date()));
            baseMapper.insert(roomAudit);
        }

//
        return "success";
    }

    @Override
    public Result selectRoomAuditList(Integer page,Integer limit,Long userId,Long roomUserId, String roomName, String roomNo,
                                      String roomUserName,String roomPhone, String userName,String phone,Integer status){
        return Result.success().put("data",new PageUtils(baseMapper.selectRoomAuditList(new Page<>(page,limit),userId,roomUserId,
                roomName,roomNo,roomUserName,roomPhone,userName,phone,status)));
    }

    @Override
    public Result auditRoomAudit(String ids,Integer status,Integer auditType,String auditContent){
        for (String id:ids.split(",")){
            try {
                RoomAudit roomAudit = baseMapper.selectById(id);
                if(roomAudit.getStatus()==1){
                    roomAudit.setAuditTime(DateUtils.format(new Date()));
                    if(status==1){
                        roomAudit.setStatus(2);
                        roomAudit.setAuditType(auditType);
                        roomAudit.setAuditContent(auditContent);
                        //封号
                        //踢出直播间
                        UserEntity userEntity = userService.selectUserById(roomAudit.getUserId());
                        if(userEntity!=null){
                            userEntity.setStatus(2);
                            userService.updateById(userEntity);
                        }
                        userEntity = userService.selectUserById(roomAudit.getRoomUserId());
                        if(userEntity!=null){
                            userEntity.setStatus(2);
                            userService.updateById(userEntity);
                        }
                    }else{
                        roomAudit.setStatus(3);
                    }
                    baseMapper.updateById(roomAudit);
                }
            }catch (Exception e){
                e.printStackTrace();
                log.error("审核直播间违规异常："+e.getMessage(),e);
            }

        }
        return Result.success();
    }


    public Result roomRemoveUser(String roomNo,Long userId){
        String secretId = commonInfoService.findOne(815).getValue();
        String secretKey = commonInfoService.findOne(816).getValue();
        String sdkAppId = commonInfoService.findOne(814).getValue();
        try{
            Credential cred = new Credential(secretId, secretKey);
            // 实例化一个http选项，可选的，没有特殊需求可以跳过
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("trtc.tencentcloudapi.com");
            // 实例化一个client选项，可选的，没有特殊需求可以跳过
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            TrtcClient client = new TrtcClient(cred, "ap-beijing", clientProfile);
            // 实例化一个请求对象,每个接口都会对应一个request对象
            RemoveUserByStrRoomIdRequest req = new RemoveUserByStrRoomIdRequest();
            req.setSdkAppId(Long.parseLong(sdkAppId));
            req.setRoomId(roomNo);

            String[] userIds1 = {String.valueOf(userId)};
            req.setUserIds(userIds1);
            // 返回的resp是一个RemoveUserByStrRoomIdResponse的实例，与请求对象对应
            RemoveUserByStrRoomIdResponse resp = client.RemoveUserByStrRoomId(req);
            String s = RemoveUserByStrRoomIdResponse.toJsonString(resp);
            JSONObject jsonObject=JSONObject.parseObject(s);
            JSONObject response = jsonObject.getJSONObject("Response");
            if(response!=null){
                JSONObject error = response.getJSONObject("Error");
                if(error!=null){
                    String message = error.getString("Message");
                    log.error("移除用户异常："+message);
                    return Result.error("移除用户失败，请稍后再试！");
                }
            }
            ChatConversation chatConversation = chatConversationService.getById(roomNo);
            ChatContent chatContent = chatContentService.selectUserChatVideo(chatConversation.getUserId());
            chatContent.setVideoStatus(5);
            chatContentService.updateById(chatContent);
            return Result.success("移除成功！");
        } catch (TencentCloudSDKException e) {
            log.error("移除用户错误！"+e.getErrorCode(),e);
        }
        return Result.error("系统繁忙，请稍后再试！");
    }


}
