package com.xunwang.education.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xunwang.commonutils.R;
import com.xunwang.commonutils.RedisIdWorker;
import com.xunwang.education.entity.*;
import com.xunwang.education.entity.dto.MyInviteInfoDto;
import com.xunwang.education.entity.socket.Commucation;
import com.xunwang.education.entity.socket.Type;
import com.xunwang.education.entity.vo.InviteCourseVo;
import com.xunwang.education.entity.vo.InviteStuNeedsVo;
import com.xunwang.education.feign.PayFeign;
import com.xunwang.education.feign.UserFeign;
import com.xunwang.education.handler.ChatEndpoint;
import com.xunwang.education.mapper.InviteInfoMapper;
import com.xunwang.education.service.InviteInfoService;
import com.xunwang.education.service.StudentRequirementsService;
import com.xunwang.education.service.TeacherCoursesService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Guan
 * @since 2023-01-03
 */
@RestController
@RequestMapping("/education/invite-info")
public class InviteInfoController {

    @Autowired
    private InviteInfoService inviteInfoService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Resource
    private ChatEndpoint chatEndpoint;

    @Resource
    private UserFeign userFeign;

    @Resource
    private PayFeign payFeign;

    @Resource
    private InviteInfoMapper inviteInfoMapper;

    @Resource
    private TeacherCoursesService teacherCoursesService;

    @Resource
    private StudentRequirementsService requirementsService;

    @ApiOperation("根据邀请号获取邀请信息")
    @GetMapping("/getInviteInfo")
    public R getInviteInfo(HttpServletRequest request) {
        String id = request.getParameter("id");
        InviteInfo one = inviteInfoService.getById(id);
        return R.ok().data("one", one);
    }

    @ApiOperation("找学员发送邀请")
    @PostMapping("/sendInvite")
    public R SendInvite(@RequestBody InviteCourseVo inviteCourseVo) throws IOException {
        LambdaQueryWrapper<InviteInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InviteInfo::getRequireId, inviteCourseVo.getRequireId()).eq(InviteInfo::getCourseId, inviteCourseVo.getCourseId()).eq(InviteInfo::getFromUid, inviteCourseVo.getUid()).eq(InviteInfo::getToUid, inviteCourseVo.getToUid());
        int count = inviteInfoService.count(wrapper);
        if (count > 0) {
            inviteInfoService.remove(wrapper);
        }

        InviteInfo inviteInfo = new InviteInfo();
        inviteInfo.setId(Long.toHexString(redisIdWorker.nextId("inviteId")));
        inviteInfo.setFromUname(inviteCourseVo.getFromUname());
        inviteInfo.setToUname(inviteCourseVo.getToUname());
        inviteInfo.setFromUid(inviteCourseVo.getUid());
        inviteInfo.setToUid(inviteCourseVo.getToUid());
        inviteInfo.setRequireId(inviteCourseVo.getRequireId());
        inviteInfo.setCourseId(inviteCourseVo.getCourseId());
        inviteInfo.setRequireSalary(new BigDecimal(inviteCourseVo.getSalary()));
        inviteInfo.setIdentity("教员");

        boolean save = inviteInfoService.save(inviteInfo);
        if (save) {
            // 5.向客户端(被邀请方)主动推送消息
            chatEndpoint.sendInvited(inviteInfo.getToUid(), inviteInfo.getId(), Commucation.INVITED.getMessage(), Type.INVITATION.getType());

            // 向关注公众号的发送消息
            String toUid = inviteInfo.getToUid();
            String unionid = userFeign.getUnionIdByUid(toUid);
            String attention = inviteInfoMapper.isAttention(unionid);
            if ("已关注".equals(attention)) {
                String fromUid = inviteInfo.getFromUid();
                String fromUname = inviteInfo.getFromUname();
                String phone = userFeign.getPhoneByUid(fromUid);
                String identity = inviteInfo.getIdentity();
                String subject = "";
                boolean flag = false;
                if ("教员".equals(identity)) {
                    String courseId = inviteInfo.getCourseId();
                    LambdaQueryWrapper<TeacherCourses> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(TeacherCourses::getCourseId, courseId).select(TeacherCourses::getSubject);
                    TeacherCourses one = teacherCoursesService.getOne(wrapper1);
                    subject = one.getSubject();
                } else {
                    String requireId = inviteInfo.getRequireId();
                    LambdaQueryWrapper<StuNeeds> wrapper2 = new LambdaQueryWrapper<>();
                    wrapper2.eq(StuNeeds::getRequireId, requireId).select(StuNeeds::getSubjectBig, StuNeeds::getSubjectSmall);
                    StuNeeds one = requirementsService.getOne(wrapper2);
                    String subjectBig = one.getSubjectBig();
                    String subjectSmall = one.getSubjectSmall();
                    subject = subjectBig + "/" + subjectSmall;
                    flag = true;
                }
                payFeign.sendTemplateMsgOrder(unionid, fromUname, phone, subject, "", flag);
            }

            return R.ok().message("邀请成功");
        } else {
            return R.ok().message("邀请失败");
        }
    }

    @ApiOperation("找老师发送邀请")
    @PostMapping("/sendTeacherInvite")
    public R sendTeacherInvite(@RequestBody InviteStuNeedsVo inviteCourseVo) throws IOException {
        LambdaQueryWrapper<InviteInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(InviteInfo::getRequireId, inviteCourseVo.getRequireId()).eq(InviteInfo::getCourseId, inviteCourseVo.getCourseId()).eq(InviteInfo::getFromUid, inviteCourseVo.getUid()).eq(InviteInfo::getToUid, inviteCourseVo.getToUid());
        int count = inviteInfoService.count(wrapper);
        if (count > 0) {
            inviteInfoService.remove(wrapper);
        }

        InviteInfo inviteInfo = new InviteInfo();
        inviteInfo.setId(Long.toHexString(redisIdWorker.nextId("inviteId")));
        inviteInfo.setFromUname(inviteCourseVo.getFromUname());
        inviteInfo.setToUname(inviteCourseVo.getToUname());
        inviteInfo.setFromUid(inviteCourseVo.getUid());
        inviteInfo.setToUid(inviteCourseVo.getToUid());
        inviteInfo.setRequireId(inviteCourseVo.getRequireId());
        inviteInfo.setCourseId(inviteCourseVo.getCourseId());
        inviteInfo.setRequireSalary(inviteCourseVo.getSalary());
        inviteInfo.setIdentity("学员");

        boolean save = inviteInfoService.save(inviteInfo);
        if (save) {
            // 5.向客户端(被邀请方)主动推送消息
            chatEndpoint.sendInvited(inviteInfo.getToUid(), inviteInfo.getId(), Commucation.INVITED.getMessage(), Type.INVITATION.getType());

            // 向关注公众号的发送消息
            String toUid = inviteInfo.getToUid();
            String unionid = userFeign.getUnionIdByUid(toUid);
            String attention = inviteInfoMapper.isAttention(unionid);
            if ("已关注".equals(attention)) {
                String fromUid = inviteInfo.getFromUid();
                String fromUname = inviteInfo.getFromUname();
                String phone = userFeign.getPhoneByUid(fromUid);
                String identity = inviteInfo.getIdentity();
                String subject = "";
                boolean flag = false;
                if ("教员".equals(identity)) {
                    String courseId = inviteInfo.getCourseId();
                    LambdaQueryWrapper<TeacherCourses> wrapper1 = new LambdaQueryWrapper<>();
                    wrapper1.eq(TeacherCourses::getCourseId, courseId).select(TeacherCourses::getSubject);
                    TeacherCourses one = teacherCoursesService.getOne(wrapper1);
                    subject = one.getSubject();
                } else {
                    String requireId = inviteInfo.getRequireId();
                    LambdaQueryWrapper<StuNeeds> wrapper2 = new LambdaQueryWrapper<>();
                    wrapper2.eq(StuNeeds::getRequireId, requireId).select(StuNeeds::getSubjectBig, StuNeeds::getSubjectSmall);
                    StuNeeds one = requirementsService.getOne(wrapper2);
                    String subjectBig = one.getSubjectBig();
                    String subjectSmall = one.getSubjectSmall();
                    subject = subjectBig + "/" + subjectSmall;
                    flag = true;
                }
                payFeign.sendTemplateMsgOrder(unionid, fromUname, phone, subject, "", flag);
            }
            return R.ok().message("邀请成功");
        } else {
            return R.ok().message("邀请失败");
        }
    }

    @ApiOperation("获取已读的邀请list")
    @GetMapping("/getSendedInvitationRead")
    public R getSendedInvitation(HttpServletRequest request){
        String status = "已读";
        List<MyInviteInfoDto> list = inviteInfoService.sendMyInviteInfoList(request, status);
        return R.ok().data("list",list);
    }

    @ApiOperation("获取未读的邀请list")
    @GetMapping("/getSendedInvitationUnread")
    public R getSendedInvitationUnread(HttpServletRequest request){
        String status = "未读";
        List<MyInviteInfoDto> list = inviteInfoService.sendMyInviteInfoList(request, status);
        return R.ok().data("list",list);
    }

    @ApiOperation("我收到的邀请list已读")
    @GetMapping("/getReceivedInvitationRead")
    public R getReceivedInvitationRead(HttpServletRequest request){
        String status = "已读";
        List<MyInviteInfoDto> list = inviteInfoService.receiveMyInviteInfoList(request, status);
        return R.ok().data("list",list);
    }

    @ApiOperation("我收到的邀请list未读")
    @GetMapping("/getReceivedInvitationUnread")
    public R getReceivedInvitationUnread(HttpServletRequest request){
        String status = "未读";
        List<MyInviteInfoDto> list = inviteInfoService.receiveMyInviteInfoList(request, status);
        return R.ok().data("list",list);
    }

    @ApiOperation("获取邀请详情")
    @GetMapping("/getInvitationDetail")
    public R getInvitationDetail(HttpServletRequest request) {
        InviteInfo invitationDetail = inviteInfoService.getInvitationDetail(request);
        return R.ok().data("one", invitationDetail);
    }
    
    //点击进入我收到的邀请详情，改变我方状态从未读变为待定，如果状态为非未读状态则不做修改
    @ApiOperation("修改我方操作状态为待定,阅读状态为已读")
    @GetMapping("/modifyStatusToHold")
    public R modifyStatusToHold(HttpServletRequest request){
        String id = request.getParameter("id");
        //修改操作状态
        inviteInfoService.modifyStatusToHold(id);
        return R.ok();
    }

    @ApiOperation("拒绝邀请")
    @GetMapping("/refuse")
    public R refuse(HttpServletRequest request){
        String id = request.getParameter("id");
        InviteInfo inviteInfo = new InviteInfo();
        inviteInfo.setOperateStatus("拒绝");
        QueryWrapper<InviteInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        inviteInfoService.update(inviteInfo,wrapper);
        return R.ok();
    }

    @ApiOperation("同意邀请")
    @GetMapping("/agree")
    public R agree(HttpServletRequest request) throws IOException {
        return inviteInfoService.agreeInvitation(request);
    }

}

