package com.usoft.fin.grpc.bl;

import com.alibaba.fastjson.JSON;
import com.google.protobuf.InvalidProtocolBufferException;
import com.usoft.bizcode.utils.BizCodeUtil;
import com.usoft.fin.grpc.api.entity.MessageEntity;
import com.usoft.fin.grpc.api.entity.PagingInfo;
import com.usoft.fin.grpc.api.entity.ResponseHeader;
import com.usoft.fin.grpc.api.protobuf.*;
import com.usoft.fin.grpc.bl.constants.Status;
import com.usoft.fin.grpc.bl.constants.TableCode;
import com.usoft.fin.grpc.dal.entity.*;
import com.usoft.fin.grpc.dal.mapper.*;
import com.usoft.fin.grpc.entity.PageInfo;
import com.usoft.fin.grpc.utils.VerifyParamsUtil;
import com.usoft.protobuf.utils.ProtoBufUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * U融链消息
 * @author: huyy
 * @date: 2018/8/29 8:36
 */
@Service
public class MessageBl {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageBl.class);

    @Autowired
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    private DrawApplyMapper drawApplyMapper;

    @Autowired
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    private RepayDetailMapper repayDetailMapper;

    @Autowired
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    private RepayMapper repayMapper;

    @Autowired
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    private CreditApplyMapper creditApplyMapper;

    @Autowired
    private MessagesMapper messagesMapper;

    public static final int UNREAD = 0;

    /**
     * 提款消息
     *
     * @param code
     */
    public void drawDrawMessage(String code) throws InvalidProtocolBufferException {
        DrawApply drawApply = drawApplyMapper.findByCode(code);
        String getCode = drawApply.getCode();
        int getDrawAmount = drawApply.getDrawAmount();
        BigDecimal getMonthRate = drawApply.getMonthRate();
        int getMaturity = drawApply.getMaturity();
        int receiverEnuu = drawApply.getEnuu();
        StringBuffer buffer = new StringBuffer();
        //拼接消息内容
        buffer.append("【英唐保理-应收宝】  您好！您的编号为").append(getCode).append("的提款成功！提款本金为").append(getDrawAmount).append("元，月利率为").append(getMonthRate).append("，融资期限为：").append(getMaturity).append("天。如有疑问，请联系您的客户经理，客户经理：周波，联系方式：15016714151。");
        String content = buffer.toString();
        String type = "FINANCE_DRAW";
//      Map<String, Object> data = new ModelMap(4);
        ModelMap data = new ModelMap();
        data.put("提款编号", getCode);
        data.put("本金(元)", getDrawAmount);
        data.put("月利率(%)", getMonthRate);
        data.put("融资期限(天)", getMaturity);
        //发送消息
        sendMessage(type, content, JSON.toJSONString(data), receiverEnuu);
    }

    /**
     * 还款消息
     *
     * @param code
     */
    public void repayDrawMessage(String code) throws InvalidProtocolBufferException {
        List<RepayDetail> repayDetails = repayDetailMapper.findByRepayCode(code);
        BigDecimal totalPrincipal = new BigDecimal(0);
        BigDecimal totalInterest = new BigDecimal(0);
        // 计算改用户还款记录中还款本金和利息的总和
        for (RepayDetail repayDetail : repayDetails) {
            BigDecimal repayPrincipal = repayDetail.getActualRepayPrincipal();
            totalPrincipal = totalPrincipal.add(repayPrincipal);
            BigDecimal repayInterest = repayDetail.getActualRepayInterest();
            totalInterest = totalInterest.add(repayInterest);
        }
        // 通过还款编号查询用户还款表，获取用户信息
        Repay repay = repayMapper.findByCode(code);
        int receiverEnuu = repay.getEnuu();
        String getCode = repay.getCode();
        StringBuffer buffer = new StringBuffer();
        //拼接消息内容
        buffer.append("【英唐保理-应收宝】  您好！您的编号为").append(getCode).append("的融资已还款！已还款本金总计为：").append(totalPrincipal).append("元，利息总计为：").append(totalInterest).append("元。如有疑问，请联系您的客户经理，客户经理：周波，联系方式：15016714151。");
        String content = buffer.toString();
        String type = "FINANCE_REPAY";
//      Map<String, Object> data = new ModelMap(3);
        ModelMap data = new ModelMap();
        data.put("提款编号", getCode);
        data.put("已还款本金总计(元)", totalPrincipal);
        data.put("利息总计(元)", totalInterest);
        //发送消息
        sendMessage(type, content, JSON.toJSONString(data), receiverEnuu);
    }


    /**
     * 额度信息
     *
     * @param code
     */
    public void auditCreditMessage(String code) throws InvalidProtocolBufferException {
        //通过用户编号获取额度表信息
        CreditApply creditApply = creditApplyMapper.findByCode(code);
        String getCode = creditApply.getCode();
        String isPass = null;
        if (creditApply.getStatus() == Status.CREDIT_APPLY_PASS.value()) {
            isPass = "已通过";
        } else {
            isPass = "未通过";
        }
        int receiverEnuu = creditApply.getEnuu();
        StringBuffer buffer = new StringBuffer();
        //拼接消息内容
        buffer.append("【英唐保理-应收宝】  您的编号为").append(getCode).append("的额度申请").append(isPass).append("！详情请联系您的客户经理！客户经理：周波，联系方式：15016714151。");
        String content = buffer.toString();
        String type = "FINANCE_CREDIT";
//      Map<String, Object> data = new ModelMap(2);
        ModelMap data = new ModelMap();
        data.put("编号", getCode);
        data.put("是否通过", isPass);
        //发送消息
        sendMessage(type, content, JSON.toJSONString(data), receiverEnuu);
    }

    /**
     * 发送消息方法
     *
     * @param type
     * @param content
     * @param remark
     * @param receiverEnuu
     */
    @Transactional(rollbackFor = Exception.class)
    public SaveMessagesResponse.Builder sendMessage(String type, String content, String remark, int receiverEnuu) throws InvalidProtocolBufferException {
        SaveMessagesResponse.Builder response = SaveMessagesResponse.newBuilder();
        MessageEntity.Builder message = MessageEntity.newBuilder();
        //获取当前日期
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String nowTime = df.format(now);
        message.setMsCode(BizCodeUtil.genBizCode(TableCode.T_MESSAGES.getCode()))
                .setMsType(type)
                .setMsContent(content)
                .setMsRemark(remark)
                .setMsReceiverenuu(receiverEnuu)
                .setMsCreateTime(nowTime);
        Messages messages = ProtoBufUtil.toBean(message, Messages.class);
        messagesMapper.insert(messages);
        LOGGER.info("保存消息到数据库中，消息: {}", messages);
        response.setResponseHeader(ResponseHeader.newBuilder());
        return response;
    }

    /**
     * 获取消息并分页
     * <p> msIsread=2,显示所有消息,msIsread=0,显示未读消息。若msIsread=1,显示已读消息。</p>
     * @param request
     * @return
     * @throws InvalidProtocolBufferException
     */
    public GetMessagesResponse.Builder getMessages(GetMessagesRequest request) throws InvalidProtocolBufferException {
        GetMessagesResponse.Builder response = GetMessagesResponse.newBuilder();
        VerifyParamsUtil.notNull(request.getMsReceiverenuu(), "企业UU号不能为空");
        int number = request.getPageNumber();
        int size = request.getPageSize();
        //若msIsread=2, 显示所有消息, msIsread=0, 显示未读消息。 若msIsread=1, 显示已读消息。
        int count = messagesMapper.countByEnuuAndIsread(request.getMsReceiverenuu(), request.getMsIsread());
        PageInfo pageInfo = new PageInfo(number, size, count);
        List<Messages> messagesList = messagesMapper.findListByEnuuAndIsread(pageInfo.getStartIndex(), size, request.getMsReceiverenuu(), request.getMsIsread());
        response.setPagingInfo(ProtoBufUtil.toProtoBuf(PagingInfo.newBuilder(), pageInfo));
        for (Messages message : messagesList) {
            response.addMessages(ProtoBufUtil.toProtoBuf(MessageEntity.newBuilder(), message));
        }
        return response;
    }

    /**
     * 获取未读消息数量
     *
     * @param request
     * @return
     */
    public GetUnreadCountResponse.Builder getUnreadCount(GetUnreadCountRequest request) {
        GetUnreadCountResponse.Builder response = GetUnreadCountResponse.newBuilder();
        VerifyParamsUtil.notNull(request.getMsReceiverenuu(), "企业UU号不能为空");
        int count = messagesMapper.countByEnuuAndIsread(request.getMsReceiverenuu(), UNREAD);
        response.setCount(count);
        response.setResponseHeader(ResponseHeader.newBuilder());
        return response;
    }


    /**
     * 设为已读
     *
     * @param request
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public SetReadResponse.Builder setRead(SetReadRequest request) {
        SetReadResponse.Builder response = SetReadResponse.newBuilder();
        VerifyParamsUtil.hasText(request.getMsCode(), "消息偏码不能为空");
        messagesMapper.updateIsReadByMsCode(request.getMsCode());
        return response;
    }

}