package com.ruoyi.cai.notice;

import com.alibaba.fastjson.JSON;
import com.ruoyi.cai.config.CaiProperties;
import com.ruoyi.cai.domain.Gift;
import com.ruoyi.cai.domain.User;
import com.ruoyi.cai.mq.handle.dto.WindowRechargeDTO;
import com.ruoyi.cai.notice.data.NoticeR;
import com.ruoyi.cai.notice.data.WindowNoticeR;
import com.ruoyi.cai.notice.data.child.*;
import com.ruoyi.cai.notice.dto.CashSuccessSendMesDTO;
import com.ruoyi.cai.notice.enums.MessageBaseTypeEnum;
import com.ruoyi.cai.service.AccountService;
import com.ruoyi.cai.service.UserService;
import com.ruoyi.cai.util.CaiDateUtil;
import com.ruoyi.cai.util.CaiNumUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.yunxin.YunExecutor;
import com.ruoyi.yunxin.Yunxin;
import com.ruoyi.yunxin.resp.SendMsgResp;
import com.ruoyi.yunxin.resp.YxCommonR;
import com.ruoyi.yunxin.resp.YxDataR;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class YunxinHttpService {

    /**
     * 网易云信的 "动态通知" id
     */
    private final static Long FOLLOW_NOTICE_ID = 11L;
    @Autowired
    private Yunxin yunxin;
    @Autowired
    private AccountService accountService;
    @Autowired
    private CaiProperties caiProperties;
    @Autowired
    private UserService userService;

    /**
     *  注册赠送消息
     */
    public void registerRewardCoin(Long toUid,Long rewardCoin,Long totalCoin){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("系统奖励");
            data.setCurrentDate();
            data.setTxt1("陌生人交友需谨慎，添加陌生人微信,QQ失去平台监管有极大被骗风险，凡是诱导加微信，QQ引导到其他平台或以色情为由索取礼物的行为，请大家及时举报，一经查明直接永久封号，良好的交友氛围需大家共同维护，希望大家提高自我警惕性杜绝被骗");
            data.addFields("注册奖励",rewardCoin+caiProperties.getCoinName());
            data.addFields("总"+caiProperties.getCoinName(),totalCoin+caiProperties.getCoinName());
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }

    /**
     * 充值云贝成功消息
     */
    public void rechargeCoinSendMessage(Long toUid,Long rewardCoin,Long totalCoin){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("购买成功");
            data.setCurrentDate();
            data.addFields("购买"+caiProperties.getCoinName(),rewardCoin+caiProperties.getCoinName());
            data.addFields("总"+caiProperties.getCoinName(),totalCoin+caiProperties.getCoinName());
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }


    /**
     * 收到礼物发送消息
     */
    public void getGiftSendMessage(Long toUid, Gift gift, Long incomeCoin, Long totalCoin){
        if(gift == null){
            return;
        }
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("收到礼物");
            data.setCurrentDate();
            data.addFields("礼物名称",gift.getName());
            data.addFields("礼物单价",gift.getPrice()+caiProperties.getCoinName());
            data.addFields("收入"+caiProperties.getCoinName(),incomeCoin+caiProperties.getCoinName());
            data.addFields("总"+caiProperties.getCoinName(),totalCoin+caiProperties.getCoinName());
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }

    /**
     * 邀请奖励
     */
    @Deprecated
    public void inviteRewardSendMessage(Long toUid,String type,String sourceNickname,String sourceUsercode,Long incomeCoin){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            String str = "";
            if("recharge".equals(type)){
                str = "用户充值奖励";
            }else if("reward".equals(type)){
                str = "奖励分成";
            }
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("邀请奖励");
            data.setCurrentDate();
            data.addFields("用户昵称",sourceNickname);
            data.addFields("用户蜜瓜号",sourceUsercode);
            data.addFields(str,incomeCoin+caiProperties.getCoinName());
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }

    /**
     * 用户充值，邀请人返现
     */
    public void inviteCashbackSendMessage(Long toUid,Long sourceId,BigDecimal rate, Long payCoin, Long incomeCoin){
        User sourceUser = userService.getById(sourceId);
        if(sourceUser == null){
            return;
        }
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("充值分成");
            data.setTxt1(String.format("充值分成：每一笔账户充值将给其邀请账户额外赠送%s的%s", CaiNumUtil.rateToStr(rate), caiProperties.getCoinName()));
            data.setCurrentDate();
            data.addFields("充值用户",sourceUser.getNickname());
            data.addFields("蜜瓜号",sourceUser.getUsercode());
            data.addFields("充值金额",payCoin+caiProperties.getCoinName());
            data.addFields("充值分成",incomeCoin+caiProperties.getCoinName());
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }

    /**
     * 提现审核转账发送消息【提现审核成功】
     */
    public void cashSuccessSendMessage(Long toUid, LocalDateTime cashTime, BigDecimal cashMoney, BigDecimal realCashMonty,
                                       String cardAccount,LocalDateTime verifyTime){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("提现成功");
            data.setCurrentDate();
            data.addFields("提现时间", CaiDateUtil.localDateTimeToString(cashTime));
            data.addFields("提现金额",cashMoney.toString()+"元");
            data.addFields("提现方式","支付宝");
            data.addFields("到账金额",realCashMonty.toString()+"元");
            data.addFields("到账账户","支付宝("+cardAccount+")");
            data.addFields("审核时间",CaiDateUtil.localDateTimeToString(verifyTime));
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }

    public void batchCashSuccessSendMessage(List<CashSuccessSendMesDTO> dtos){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            for (CashSuccessSendMesDTO dto : dtos) {
                ExtNoticeData data = new ExtNoticeData();
                data.setAction(1);
                data.setTitle("提现成功");
                data.setCurrentDate();
                data.addFields("提现时间", CaiDateUtil.localDateTimeToString(dto.getCashTime()));
                data.addFields("提现金额",dto.getCashMoney().toString()+"元");
                data.addFields("提现方式","支付宝");
                data.addFields("到账金额",dto.getRealCashMonty().toString()+"元");
                data.addFields("到账账户","支付宝("+dto.getCardAccount()+")");
                data.addFields("审核时间",CaiDateUtil.localDateTimeToString(dto.getVerifyTime()));
                NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
                YxDataR<SendMsgResp> r = yunxin.sendToNotice(dto.getToUid(), notice);
                if(r == null || !r.isSuccess()){
                    log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
                }
            }
        });
    }


    /**
     * 提现审核转账发送消息【提现审核失败】
     */
    public void cashFailSendMessage(Long toUid, LocalDateTime cashTime, BigDecimal cashMoney, String remark){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("提现失败");
            data.setCurrentDate();
            data.addFields("提现时间", CaiDateUtil.localDateTimeToString(cashTime));
            data.addFields("提现金额",cashMoney.toString()+"元");
            data.addFields("提现方式","支付宝");
            data.setTxt2(remark);
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }

    /**
     * 举报发送消息
     */
    public void reportSendMessage(Long toUid){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("已收到你的举报信息");
            data.setTxt1("感谢您提交的举报信息，拒绝不良风气，良好的氛围需要大家共同维护。");
            data.setCurrentDate();
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }

    /**
     * 关注发送消息
     * @param toUid
     */
    public void followedSendMessage(Long toUid,
                                    User followUser,
                                    LocalDateTime followTime){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            SendFollowNoticeData data = new SendFollowNoticeData();
            data.setUserid(followUser.getId());
            data.setNickname(followUser.getNickname());
            data.setAvatar(followUser.getAvatar());
            data.setAge(followUser.getAge());
            data.setCity(followUser.getCity());
            data.setTime(CaiDateUtil.localDateTimeToString(followTime));
            data.setSex(followUser.getGender());
            NoticeR<SendFollowNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.SEND_FOLLOW, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }

    /**
     * 通过女神认证发送消息
     */
    public void passAnchorSendMessage(Long toUid){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("恭喜你通过自拍认证，成为平台女神");
            data.setCurrentDate();
            data.addFields("设置服务价格","请到“我的-->女神设置”处设置");
            data.addFields("找男生聊聊","首页右上角点击“男生”按钮查找在线男生");
            data.addFields("赚钱小秘密一","多给在线男生打招呼");
            data.addFields("赚钱小秘密二","照片越好看，男生越喜欢");
            data.addFields("赚钱小秘密三","勤发动态，让他感受到你的美");
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }


    /**
     * 更改女神邀请比例
     */
    @Deprecated
    public void changeInviteConfigSendMessage(Long toUid){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("恭喜成为邀请女神");
            data.setCurrentDate();
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }

    /**
     * 发送礼物自定义消息 (发送方和接收方的消息)
     */
    public void sendGiftMessage(Long fromUid,Long toUid,Gift gift,Integer giftCount){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            SendGiftMessageNoticeData data = new SendGiftMessageNoticeData();
            data.setGift_id(gift.getId());
            data.setGift_name(gift.getName());
            data.setGift_url(gift.getImg());
            data.setGift_count(giftCount);
            data.setFrom_uid(fromUid);
            data.setTo_uid(toUid);
            NoticeR<SendGiftMessageNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.SEND_GIFT_MESSAGE, data);
            YxDataR<SendMsgResp> r = yunxin.sendToUserNotice(toUid, fromUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }


    /**
     * 收到守护符通知
     */
    public void getGuardMessage(Long toUid,Long num,Long price,Long incomeCoin,Long totalCoin){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("收到守护符");
            data.setCurrentDate();
            data.addFields("守护类型",num+"个守护符");
            data.addFields("守护单价",price+caiProperties.getCoinName());
            data.addFields("收入"+caiProperties.getCoinName(),incomeCoin+caiProperties.getCoinName());
            data.addFields("总"+caiProperties.getCoinName(),totalCoin+caiProperties.getCoinName());
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }


    /**
     * 发送上线了批量自定义消息
     */
    public void sendOnlineAttentionNotice(List<Long> toUid,User loginUser){
        SendOnlineAttentionNoticeData data = new SendOnlineAttentionNoticeData();
        data.setUserid(loginUser.getId());
        data.setNickname(loginUser.getNickname());
        data.setAvatar(loginUser.getAvatar());
        data.setAge(loginUser.getAge());
        data.setCity(loginUser.getCity());
        data.setTime(CaiDateUtil.getCurrentTimeStr());
        data.setSex(loginUser.getGender());
        NoticeR<SendOnlineAttentionNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.SEND_ONLINE_ATTENTION, data);
        YxDataR<YxCommonR> r = yunxin.batchSendToNotice(toUid, notice);
        if(r == null || !r.isSuccess()){
            log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
        }
    }

    /**
     * 取消女神通知
     */
    public void cancelAnchorMessage(Long toUid){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("取消女神通知");
            data.setCurrentDate();
            data.setTxt1("因多次违规或被投诉,已被取消女神资格！");
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }


    /**
     * 动态审核通知
     */
    public void dynamicAuditMessage(Long toUid){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("动态审核通知");
            data.setCurrentDate();
            data.setTxt1("您的动态因不符合规范,已被删除，多次违规会被取消大咖资格或封号处理");
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }


    /**
     * 相册审核通知 TODO
     */
    public void albumAuditMessage(Long toUid){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("相册审核通知");
            data.setCurrentDate();
            data.setTxt1("您上传的照片不符合要求,已被删除，多次违规会被取消大咖资格或封号处理，请按照指引上传符合要求的照片");
            data.setLink_type(1);
            data.setLink_url("/index/about/album_rule.html");
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }


    /**
     * 昵称重置审核通知
     */
    public void nickAuditMessage(Long toUid){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            ExtNoticeData data = new ExtNoticeData();
            data.setAction(1);
            data.setTitle("重置昵称通知");
            data.setCurrentDate();
            data.setTxt1("您的昵称不合格，已被重置，多次违规会被封号！");
            NoticeR<ExtNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.TXT, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }


    /**
     * 发送充值飘窗提醒
     */
    public void sendRechargeWindowsAmount(List<Long> toIds, WindowRechargeDTO windowRecharge){
        SendRechargeWindowsAmountNoticeData data = new SendRechargeWindowsAmountNoticeData();
        data.setId(windowRecharge.getId());
        data.setNickname(windowRecharge.getNickname());
        data.setAvatar(windowRecharge.getAvatar());
        data.setAmount(windowRecharge.getAmount());
        data.setTime(System.currentTimeMillis());
        WindowNoticeR<SendRechargeWindowsAmountNoticeData> notice = WindowNoticeR.ok(MessageBaseTypeEnum.RECHARGE_WINDOWS_AMOUNT, data);
        YxDataR<YxCommonR> r = yunxin.sendBatchAttachMsgNotice(toIds, notice);
        if(r == null || !r.isSuccess()){
            log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
        }
    }


    /**
     * 发送礼物飘窗提醒
     */
    public void sendGiftWindowsAmount(List<Long> toUid, SendGiftWindowsAmountNoticeData data){
        WindowNoticeR<SendGiftWindowsAmountNoticeData> notice = WindowNoticeR.ok(MessageBaseTypeEnum.SEND_GIFT_WINDOWS_AMOUNT, data);
        data.setTime(System.currentTimeMillis());
        YxDataR<YxCommonR> r = yunxin.sendBatchAttachMsgNotice(toUid, notice);
        if(r == null || !r.isSuccess()){
            log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
        }
    }


    /**
     * 动态通知
     */
    @Deprecated
    public void sendFollowDynamicBath(Long toUid, User user,String image,String content){
        YunExecutor.YUN_EXECUTOR.execute(() -> {
            SendFollowDynamicNoticeData data = new SendFollowDynamicNoticeData();
            data.setUserid(user.getId());
            data.setNickname(user.getNickname());
            data.setAvatar(user.getAvatar());
            data.setAge(user.getAge().intValue());
            data.setCity(user.getCity());
            data.setTime(CaiDateUtil.getCurrentTimeStr());
            data.setImage(image);
            data.setTitle(content);
            NoticeR<SendFollowDynamicNoticeData> notice = NoticeR.ok(MessageBaseTypeEnum.SEND_FOLLOW_DYNAMIC, data);
            YxDataR<SendMsgResp> r = yunxin.sendToNotice(toUid, notice);
            if(r == null || !r.isSuccess()){
                log.error("云信发送失败【sendCallAsync】r={}", JSON.toJSONString(r));
            }
        });
    }


}
