package com.ruoyi.app.user;

import java.util.List;
import jakarta.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.app.utils.PayPush;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.system.domain.InfoUser;
import com.ruoyi.system.domain.vo.UserDTO;
import com.ruoyi.system.mapper.VideoCallMapper;
import com.ruoyi.system.service.IInfoUserService;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import com.ruoyi.system.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.VideoCall;
import com.ruoyi.system.service.IVideoCallService;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * VideoCallController
 *
 * @author ruoyi
 * @date 2024-03-05
 */
@Api(value = "VideoCallController", description = "视频呼叫")
@RestController
@RequestMapping("/system/call")
public class VideoCallController extends BaseController
{
    @Autowired
    private IVideoCallService videoCallService;
    @Autowired
    private IInfoUserService infoUserService;
    @Autowired
    private VideoCallMapper videoCallMapper;
    /**
     *
     * @param token
     * @return
     */
    @ApiOperation("主动挂断电话请求")
    @Anonymous
    @Auth
    @GetMapping("/ringoff")
    public AjaxResult ringoff(@RequestHeader String token) {
        JwtUtil jwtUtil = new JwtUtil();
        String id = jwtUtil.getusid(token);
        QueryWrapper<VideoCall> wrapper = new QueryWrapper<>();
        wrapper.eq("call_id",id).or().eq("user_id",id);
        List<VideoCall> call = videoCallService.list(wrapper);
        if(call.size()==0){
            return error(MessageUtils.message("no.user.call.status.not.exis"));
        }else {
            for (int i=0;i<call.size();i++){
                InfoUser user = infoUserService.getById(String.valueOf(id).equals(String.valueOf(call.get(i).getUserId()))?call.get(i).getCallId():call.get(i).getUserId());
                videoCallService.deleteVideoCallById(call.get(i).getId());
                PayPush push = new PayPush();
                if(user.getUserType().equals("0")){
                    push.apppush(
                        user.getCid(),
                        MessageUtils.message("no.message.push.end.call"),
                        MessageUtils.message("no.message.push.call.hangup"),
                        ""
                    );
                }
                if(user.getUserType().equals("1")){
                    push.shpush(
                        user.getCid(),
                        MessageUtils.message("no.message.push.end.call"),
                        MessageUtils.message("no.message.push.call.hangup"),
                        ""
                    );
                }
                if(user.getUserType().equals("2")){
                    push.qspush(
                        user.getCid(),
                        MessageUtils.message("no.message.push.end.call"),
                        MessageUtils.message("no.message.push.call.hangup"),
                        ""
                    );
                }
            }
            return success(MessageUtils.message("no.user.call.hangup.success"));
        }
    }
    /**
     *
     * @param token
     * @return
     */
    @ApiOperation("获取通话内容消息")
    @Anonymous
    @Auth
    @GetMapping("/getCall")
    public AjaxResult getCall(@RequestHeader String token) {
        JwtUtil jwtUtil = new JwtUtil();
        Long id = Long.valueOf(jwtUtil.getusid(token));
        QueryWrapper<VideoCall> wrapper = new QueryWrapper<>();
        wrapper.eq("call_id",id).or().eq("user_id",id);
        VideoCall call = videoCallService.getOne(wrapper);
        if(call==null){
            return error(MessageUtils.message("no.user.call.not.exist"));
        }
        JSONObject obj = new JSONObject();
        String content=call.getContent();
        String answer=call.getAnswer();
        JSONObject jscon=JSONObject.parseObject(content);
        JSONObject jsansw=JSONObject.parseObject(answer);
        obj.put("content",jscon);
        obj.put("answer",jsansw);
        return success(MessageUtils.message("no.action.success"), obj);

    }

    /**
     * 用户提交呼叫信息
     * @param token
     * @param videoCall
     * @return
     */
    @ApiOperation("用户提交呼叫信息")
    @Anonymous
    @Auth
    @RepeatSubmit(message = "请求过于频繁")
    @PostMapping("/userCall")
    public AjaxResult userCall(@RequestHeader String token, @RequestBody VideoCall videoCall) {
        JwtUtil jwtUtil = new JwtUtil();
        Long id = Long.valueOf(jwtUtil.getusid(token));
        QueryWrapper<VideoCall> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id",id).or().eq("call_id",id);;
        VideoCall call = videoCallService.getOne(wrapper);
        if(call==null){
            QueryWrapper<VideoCall> query = new QueryWrapper<>();
            query.eq("call_id",videoCall.getCallId()).or().eq("user_id",videoCall.getCallId());
            VideoCall videoCall1 = videoCallService.getOne(query);
            if(videoCall1==null){
                VideoCall video = new VideoCall();
                PayPush push = new PayPush();
                video.setUserId(id);
                video.setCallId(videoCall.getCallId());
                video.setContent(videoCall.getContent());
                videoCallService.saveOrUpdate(video);
                InfoUser colluser = infoUserService.getById(videoCall.getCallId());
                InfoUser falluser = infoUserService.getById(id);
                if(colluser.getUserType().equals("0")){
                    push.apppush(
                        colluser.getCid(),
                        MessageUtils.message("no.message.push.call.calling"),
                        falluser.getNickName()+MessageUtils.message("no.message.push.call.request"),
                        String.valueOf(falluser.getUserId())
                    );
                }
                if(colluser.getUserType().equals("1")){
                    push.shpush(
                        colluser.getCid(),
                        MessageUtils.message("no.message.push.call.calling"),
                        falluser.getNickName()+MessageUtils.message("no.message.push.call.request"),
                        String.valueOf(falluser.getUserId())
                    );
                }
                if(colluser.getUserType().equals("2")){
                    push.qspush(
                        colluser.getCid(),
                        MessageUtils.message("no.message.push.call.calling"),
                        falluser.getNickName()+MessageUtils.message("no.message.push.call.request"),
                        String.valueOf(falluser.getUserId())
                    );
                }
                return success(MessageUtils.message("no.user.call.calling.success"));
            }else {
                return error(MessageUtils.message("no.user.call.other.is.calling"));
            }
        }else {
            if(call.getCallId().equals(id)){
                PayPush push = new PayPush();
                call.setAnswer(videoCall.getContent());
                videoCallService.updateVideoCall(call);
                InfoUser colluser = infoUserService.getById(call.getUserId());
                InfoUser falluser = infoUserService.getById(id);
                if(colluser.getUserType().equals("0")){
                    push.apppush(
                        colluser.getCid(),
                        MessageUtils.message("no.message.push.call.accept"),
                        falluser.getNickName() + MessageUtils.message("no.message.push.call.agree"),
                        String.valueOf(falluser.getUserId())
                    );
                }
                if(colluser.getUserType().equals("1")){
                    push.shpush(
                        colluser.getCid(),
                        MessageUtils.message("no.message.push.call.accept"),
                        falluser.getNickName() + MessageUtils.message("no.message.push.call.agree"),
                        String.valueOf(falluser.getUserId())
                    );
                }
                if(colluser.getUserType().equals("2")){
                    push.qspush(
                        colluser.getCid(),
                        MessageUtils.message("no.message.push.call.accept"),
                        falluser.getNickName() + MessageUtils.message("no.message.push.call.agree"),
                        String.valueOf(falluser.getUserId())
                    );
                }
                return success(MessageUtils.message("no.user.call.accept.success"));
            }else{
                PayPush push = new PayPush();
                call.setCallId(videoCall.getCallId());
                call.setContent(videoCall.getContent());
                videoCallService.updateVideoCall(call);
                InfoUser colluser = infoUserService.getById(call.getCallId());
                InfoUser falluser = infoUserService.getById(id);
                if(colluser.getUserType().equals("0")){
                    push.apppush(
                        colluser.getCid(),
                        MessageUtils.message("no.message.push.call.calling"),
                        falluser.getNickName()+MessageUtils.message("no.message.push.call.request"),
                        String.valueOf(falluser.getUserId())
                    );
                }
                if(colluser.getUserType().equals("1")){
                    push.shpush(
                        colluser.getCid(),
                        MessageUtils.message("no.message.push.call.calling"),
                        falluser.getNickName()+MessageUtils.message("no.message.push.call.request"),
                        String.valueOf(falluser.getUserId())
                    );
                }
                if(colluser.getUserType().equals("2")){
                    push.qspush(
                        colluser.getCid(),
                        MessageUtils.message("no.message.push.call.calling"),
                        falluser.getNickName()+MessageUtils.message("no.message.push.call.request"),
                        String.valueOf(falluser.getUserId())
                    );
                }
                return success(MessageUtils.message("no.user.call.request.success"));
            }
        }
    }
    /**
     * 查询VideoCall列表
     */
    @ApiOperation("查询VideoCall列表")
    @PreAuthorize("@ss.hasPermi('system:call:list')")
    @GetMapping("/list")
    public TableDataInfo list(VideoCall videoCall)
    {
        startPage();
        List<VideoCall> list = videoCallService.selectVideoCallList(videoCall);
        return getDataTable(list);
    }

    /**
     * 导出VideoCall列表
     */
    @ApiOperation("导出VideoCall列表")
    @PreAuthorize("@ss.hasPermi('system:call:export')")
    @Log(title = "VideoCall", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, VideoCall videoCall)
    {
        List<VideoCall> list = videoCallService.selectVideoCallList(videoCall);
        ExcelUtil<VideoCall> util = new ExcelUtil<VideoCall>(VideoCall.class);
        util.exportExcel(response, list, MessageUtils.message("no.export.excel.videocall"));
    }

    /**
     * 获取VideoCall详细信息
     */
    @ApiOperation("获取VideoCall详细信息")
    @PreAuthorize("@ss.hasPermi('system:call:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(videoCallService.selectVideoCallById(id));
    }

    /**
     * 新增VideoCall
     */
    @ApiOperation("新增VideoCall")
    @PreAuthorize("@ss.hasPermi('system:call:add')")
    @Log(title = "VideoCall", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody VideoCall videoCall)
    {
        return toAjax(videoCallService.insertVideoCall(videoCall));
    }

    /**
     * 修改VideoCall
     */
    @ApiOperation("修改VideoCall")
    @PreAuthorize("@ss.hasPermi('system:call:edit')")
    @Log(title = "VideoCall", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody VideoCall videoCall)
    {
        return toAjax(videoCallService.updateVideoCall(videoCall));
    }

    /**
     * 删除VideoCall
     */
    @ApiOperation("删除VideoCall")
    @PreAuthorize("@ss.hasPermi('system:call:remove')")
    @Log(title = "VideoCall", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(videoCallService.deleteVideoCallByIds(ids));
    }
}
