package com.muchinfo.mtp3century.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.muchinfo.mtp.proto.*;
import com.muchinfo.mtp3century.service.ISendMsgService;
import com.muchinfo.mtp3common.enumtype.FunCodeConstants;
import com.muchinfo.mtp3common.enumtype.SysConstants;
import com.muchinfo.mtp3common.utils.DateTimeUtils;
import com.muchinfo.mtp3common.utils.EncryptionUtils;
import com.muchinfo.mtp3common.vo.ProtoHelper;
import com.muchinfo.mtp3interface.mapper.IUseraccountMapper;
import com.muchinfo.mtp3pojos.entity.Taaccount;
import com.muchinfo.mtp3pojos.entity.Useraccount;
import com.muchinfo.mtp3pojos.entity.Userinfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class SendMsgServiceImpl implements ISendMsgService {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    private IUseraccountMapper iUseraccountMapper;
    @Resource
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendCustomerInfo(Userinfo ui, Long accountid, String changetype, int clientAccountType) {
        try {
            BankMI1.m2bRegistCustomerInfoReq.Builder uBuilder = BankMI1.m2bRegistCustomerInfoReq.newBuilder();
            Common.MessageHead.Builder uhd = Common.MessageHead.newBuilder();
            uhd.setFunCode(FunCodeConstants.FunCode_Trade_m2bRegistCustomerInfoReq);
            uhd.setClientTime(System.currentTimeMillis());
            uBuilder.setHeader(uhd);

            uBuilder.setExtOperatorID(System.currentTimeMillis());
            uBuilder.setAccountCode(accountid.toString());
            uBuilder.setTradeDate(DateTimeUtils.format(new Date(), DateTimeUtils.DATE_CHAR_PATTERN));
            uBuilder.setChangeType(changetype);
            if (ui.getUserinfotype() == null) {
                // 默认个人
                uBuilder.setClientType(1);
            } else {
                uBuilder.setClientType(ui.getUserinfotype());
            }

            if (ui.getCustomername() != null)
                uBuilder.setClientName(ui.getCustomername());

            uBuilder.setClientAccountType(clientAccountType);
            uBuilder.setCertType(ui.getCardtypeid() == null ? "" : ui.getCardtypeid().toString());
            uBuilder.setCertId(ui.getCardnum());
            if (ui.getSex() == null) {
                uBuilder.setSex("2");
            } else {
                if (ui.getSex() == 0)
                    uBuilder.setSex("2");
                else
                    uBuilder.setSex(ui.getSex().toString());
            }
            uBuilder.setContactUserEmail(StringUtils.isBlank(ui.getEmail()) ? "" : EncryptionUtils.decryptForAES(ui.getEmail()));
            uBuilder.setContactUserFax(StringUtils.isBlank(ui.getFax()) ? "" : ui.getFax());

            uBuilder.setContactUserName(StringUtils.isBlank(ui.getContactname()) ? "" : ui.getContactname());
            uBuilder.setLegalName(StringUtils.isBlank(ui.getLegalpersonname()) ? "" : ui.getLegalpersonname());
            uBuilder.setContactUserTel(StringUtils.isBlank(ui.getMobile()) ? "" : EncryptionUtils.decryptForAES(ui.getMobile()));

            Useraccount userAcc = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", ui.getUserid()));
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("broker_code", userAcc.getMemberuserid());
            jsonObj.put("user_code", userAcc.getUserid());
            //银行信息
            if (StringUtils.isNotBlank(ui.getBankaccount())) {
                jsonObj.put("card_no", EncryptionUtils.decryptForAES(ui.getBankaccount()));
                jsonObj.put("card_bank_no", ui.getBankid());
            }
            if (userAcc.getUsertype() == 5 || userAcc.getUsertype() == 3) {
                Useraccount memAcc = iUseraccountMapper.selectOne(new QueryWrapper<Useraccount>().eq("userid", userAcc.getMemberuserid()));
                uBuilder.setRelatedAcc(memAcc.getReckonaccountid() == null ? "" : memAcc.getReckonaccountid().toString());
            } else if (userAcc.getUsertype() == 2) {
                uBuilder.setRelatedAcc(userAcc.getReckonaccountid() == null ? "" : userAcc.getReckonaccountid().toString());
            }
            uBuilder.setExtendInfo(jsonObj.toString());

            sendMsg(uBuilder.build().toByteArray(),
                    SysConstants.RabbitBankNtfKey,
                    FunCodeConstants.FunCode_Trade_m2bRegistCustomerInfoReq);
            log.info("[sendCustomerInfo]发送客户信息上传请求");
            log.info(uBuilder.build().toString());
        } catch (Exception e) {
            log.error("sendCustomerInfo failed,error message: " + Arrays.toString(e.getStackTrace()));
        }
    }

    @Override
    public void sendMsg(byte[] byteArray, String topic, Integer funcode) {
        try {
            byte[] body = ProtoHelper.getNTAS(byteArray, funcode);
            rabbitTemplate.send(topic, new Message(body, new MessageProperties()));
        } catch (Exception e) {
            log.error("sendMsg failed,error message: " + Arrays.toString(e.getStackTrace()));
        }
    }

    @Override
    public void sendSMSConnetion(Integer templateId, String recPhone, List<String> params) {
        try {
            ShortMessageMtp1.ShortMsgSendReq.Builder smsbuilder = ShortMessageMtp1.ShortMsgSendReq.newBuilder();
            smsbuilder.setMsgType(2);
            smsbuilder.setPriority(2);
            smsbuilder.setScheduledTime("");
            smsbuilder.addRecvPhone(recPhone);
            smsbuilder.setTemplateID(templateId);

            if (params != null && !params.isEmpty()) {
                params.forEach(p -> smsbuilder.addParamValues(p.replaceAll("\\*", "-")));
            }
            // 添加消息头
            Common.MessageHead.Builder headBuil = Common.MessageHead.newBuilder();
            headBuil.setFunCode(FunCodeConstants.FunCode_Trade_ShortMsgSendReq);
            smsbuilder.setHeader(headBuil.build());
            byte[] body = ProtoHelper.getNTAS(smsbuilder.build().toByteArray(),
                    FunCodeConstants.FunCode_Trade_ShortMsgSendReq);
            MessageProperties msgProperties = new MessageProperties();
            msgProperties.setHeader("messageType", "protoBuf");
            rabbitTemplate.send(SysConstants.RabbitShortMessage, new Message(body, msgProperties));
        } catch (Exception e) {
            log.error("sendSMSConnetion failed,error message: " + Arrays.toString(e.getStackTrace()));
        }
    }

    @Override
    public void sendLoginMsg(Set<Long> set_msg, Integer type, Integer ntfmode) {
        try {
            if (set_msg == null || set_msg.size() == 0)
                return;
            // 0 新增帐号 1 删除帐号  2 修改帐号 3 修改帐号个性化 4 修改账户权限 5 删除三方登陆信息
            NotifyMI1.LoginAccChangeNtf.Builder builder = NotifyMI1.LoginAccChangeNtf.newBuilder();
            Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
            hd.setFunCode(FunCodeConstants.FunCode_Trade_LoginAccChangeNtf);
            hd.setClientTime(System.currentTimeMillis());
            builder.setHeader(hd);
            PublicMI1.NotifyHead.Builder nhd = PublicMI1.NotifyHead.newBuilder();
            nhd.setNtfMode(ntfmode);
            builder.setNtfHeader(nhd);
            set_msg.forEach(p -> {
                NotifyMI1.LoginAccChange.Builder lab = NotifyMI1.LoginAccChange.newBuilder();
                lab.setChangeType(type);
                lab.setLoginId(p);
                builder.addLoginAccChange(lab);
            });

            sendMsg(builder.build().toByteArray(), SysConstants.RabbitNtfKey, FunCodeConstants.FunCode_Trade_LoginAccChangeNtf);
            log.info(builder.build().toString());
        } catch (Exception e) {
            log.error("sendLoginMsg failed,error message: " + Arrays.toString(e.getStackTrace()));
        }
    }

    @Override
    public void sendM2BUnregistCustomerInfo(List<Taaccount> tas) {
        try {
            // 发送用户注销消息给中心\银行接口
            if (tas == null) return;

            if (tas != null && !tas.isEmpty()) {
                Long time = System.currentTimeMillis();
                for (int i = 0; i < tas.size(); i++) {
                    //				Object[] ob = (Object[])sign.get(i);
                    String accountCode = tas.get(i).getAccountid().toString();
                    BankMI1.m2bUnregistCustomerInfoReq.Builder builder = BankMI1.m2bUnregistCustomerInfoReq.newBuilder();
                    Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
                    hd.setClientTime(time);
                    hd.setFunCode(FunCodeConstants.FunCode_Trade_m2bUnregistCustomerInfoReq);
                    builder.setHeader(hd);
                    builder.setExtOperatorID(time + i);
                    //				builder.setCusBankID(ob[1].toString());
                    builder.setTradeDate(DateTimeUtils.format(new Date(), DateTimeUtils.DATE_CHAR_PATTERN));
                    builder.setAccountCode(accountCode);

                    byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(), FunCodeConstants.FunCode_Trade_m2bUnregistCustomerInfoReq);
                    rabbitTemplate.send(SysConstants.RabbitBankNtfKey, new Message(body, new MessageProperties()));

                    log.info("用户注销发送注销消息 589835(10801)给中心\\银行接口：" + accountCode);
                }
            }
        } catch (Exception e) {
            log.error("sendM2BUnregistCustomerInfo failed,error message: " + Arrays.toString(e.getStackTrace()));
        }
    }

    @Override
    public void sendUserChangeMsg(Long accountid, Long userid, Integer usertype, Integer accounttype, Integer ntfmode) {
        try {
            NotifyMI1.UserChangeNtf.Builder builder = NotifyMI1.UserChangeNtf.newBuilder();

            Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
            if (accountid != 0) {
                hd.setAccountID(accountid);
            }
            hd.setFunCode(FunCodeConstants.FunCode_Trade_UserChangeNtf);
            hd.setClientTime(System.currentTimeMillis());
            builder.setHeader(hd);

            PublicMI1.NotifyHead.Builder nhd = PublicMI1.NotifyHead.newBuilder();
            if (accountid != 0) {
                nhd.addAccountIDs(accountid);
            }
            nhd.setNtfMode(ntfmode);
            builder.setNtfHeader(nhd);

            if (accountid != 0) {
                NotifyMI1.AccountDataChange.Builder ac = NotifyMI1.AccountDataChange.newBuilder();
                ac.setAccountId(accountid);
                ac.setChangeType(accounttype);
                builder.addAccountChange(ac);
            }
            builder.setChangeType(usertype);
            builder.setUserId(userid);
            sendMsg(builder.build().toByteArray(), SysConstants.RabbitNtfKey, FunCodeConstants.FunCode_Trade_UserChangeNtf);

            log.info(builder.build().toString());
        } catch (Exception e) {
            log.error("sendUserChangeMsg failed,error message: " + Arrays.toString(e.getStackTrace()));
        }
    }

    @Override
    public void sendUserChangeMsg(Long accountid, Long userid, Integer type, Integer ntfmode) {
        try {
            NotifyMI1.UserChangeNtf.Builder builder = NotifyMI1.UserChangeNtf.newBuilder();

            Common.MessageHead.Builder hd = Common.MessageHead.newBuilder();
            if (accountid != 0) {
                hd.setAccountID(accountid);
            }
            hd.setFunCode(FunCodeConstants.FunCode_Trade_UserChangeNtf);
            hd.setClientTime(System.currentTimeMillis());
            builder.setHeader(hd);

            PublicMI1.NotifyHead.Builder nhd = PublicMI1.NotifyHead.newBuilder();
            if (accountid != 0) {
                nhd.addAccountIDs(accountid);
            }
            nhd.setNtfMode(ntfmode);
            builder.setNtfHeader(nhd);

            if (accountid != 0) {
                NotifyMI1.AccountDataChange.Builder ac = NotifyMI1.AccountDataChange.newBuilder();
                ac.setAccountId(accountid);
                ac.setChangeType(type);
                builder.addAccountChange(ac);
            }
            if (type == 1) {
                builder.setChangeType(2);
            } else {
                builder.setChangeType(type);
            }
            builder.setUserId(userid);
            sendMsg(builder.build().toByteArray(), SysConstants.RabbitNtfKey, FunCodeConstants.FunCode_Trade_UserChangeNtf);

            log.info(builder.build().toString());
        } catch (Exception e) {
            log.error("sendUserChangeMsg failed,error message: " + Arrays.toString(e.getStackTrace()));
        }
    }

    /**
     * 管理端个性化风控通知
     */
    @Override
    public void sendAccountConfigChangeNtf(Integer nt, Integer ct, Long userid, Long accountid,
                                           Long goodsid, Long groupid, Integer rt) {
        try {
            NotifyMI1.AccountConfigChangeNtf.Builder builder = NotifyMI1.AccountConfigChangeNtf.newBuilder();
            Common.MessageHead.Builder mh = Common.MessageHead.newBuilder();
            mh.setFunCode(FunCodeConstants.FunCode_Trade_AccountConfigChangeNtf);
            builder.setHeader(mh);
            PublicMI1.NotifyHead.Builder nf = PublicMI1.NotifyHead.newBuilder();
            nf.setNtfMode(0);
            builder.setNtfHeader(nf);
            builder.setNtfType(nt);
            builder.setChangType(ct);
            if (userid != null) {
                builder.setUserid(userid);
            }
            if (accountid != null) {
                builder.setAccountid(accountid);
            }
            if (goodsid != null) {
                builder.setGoodsid(goodsid);
            }
            if (rt != null) {
                if (rt == 2) {
                    builder.setRoletype(2);
                } else if (userid <= 9999) {
                    builder.setRoletype(1);
                }
            }
            if (groupid != null) {
                builder.setGroupid(groupid);
            }

            log.info(builder.build().toString());
            byte[] body = ProtoHelper.getNTAS(builder.build().toByteArray(), FunCodeConstants.FunCode_Trade_AccountConfigChangeNtf, 0);
            rabbitTemplate.send(SysConstants.RabbitNtfKey, new Message(body, new MessageProperties()));
        } catch (Exception e) {
            log.error("sendAccountConfigChangeNtf failed,error message: " + Arrays.toString(e.getStackTrace()));
        }
    }
}
