package com.ym.mec.biz.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.huifu.adapay.Adapay;
import com.huifu.adapay.notify.MQTTCallbackHandler;
import com.ym.mec.biz.dal.dao.HfMemberDao;
import com.ym.mec.biz.dal.dao.SysConfigDao;
import com.ym.mec.biz.dal.entity.HfMember;
import com.ym.mec.biz.dal.entity.StudentPaymentOrder;
import com.ym.mec.biz.dal.entity.TenantPaymentOrder;
import com.ym.mec.biz.dal.enums.DealStatusEnum;
import com.ym.mec.thirdparty.adapay.ConfigInit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;


@Service
public class NotifyCallback implements MQTTCallbackHandler {

    @Autowired
    private StudentPaymentOrderService studentPaymentOrderService;
    @Autowired
    private TenantPaymentOrderService tenantPaymentOrderService;
    @Autowired
    private HfMemberDao hfMemberDao;

    private static NotifyCallback notifyCallback;

    @Value("${spring.profiles.active:dev}")
    private String profiles;

    @Value("${spring.application.name}")
    private String appName;

    @PostConstruct
    public void init() {
        notifyCallback = this;
//        if (!profiles.equals("prod") && !appName.equals("student-server")) {
//            Adapay.debug = true;
//            // prodMode 模式，默认为生产模式，false可以使用mock模式
//            Adapay.prodMode = false;
//        }
        Adapay.setDeviceID(appName);
    }

    /**
     * 用户接收并处理支付成功的异步消息
     *
     * @param payment 成功的支付对象
     * @throws Exception 异常
     */
    @Override
    public void paymentSuccessMessageArrived(String payment) throws Exception {
        System.out.println(String.format("receive paymentSuccess  msg=%s", payment));
        JSONObject dataObj = JSON.parseObject(payment);
        if (!dataObj.getString("app_id").equals(ConfigInit.appId)) {
            return;
        }
        String orderNo = dataObj.getString("order_no");
        StudentPaymentOrder studentPaymentOrder = notifyCallback.studentPaymentOrderService.findOrderByOrderNo(orderNo);

        if (studentPaymentOrder != null) {
            Map<String, String> notifyMap = new HashMap<>();
            notifyMap.put("channelType", dataObj.getString("pay_channel"));
            notifyMap.put("tradeState", "1");
            notifyMap.put("totalMoney", dataObj.getString("pay_amt"));
            notifyMap.put("merOrderNo", dataObj.getString("order_no"));
            notifyCallback.studentPaymentOrderService.updateOrder(notifyMap);
            return;
        }
        TenantPaymentOrder tenantPaymentOrder = notifyCallback.tenantPaymentOrderService.queryByOrderNo(orderNo);
        if (tenantPaymentOrder != null) {
            tenantPaymentOrder.setStatus(DealStatusEnum.SUCCESS);
            tenantPaymentOrder.setPaymentBusinessChannel(dataObj.getString("pay_channel"));
            tenantPaymentOrder.setActualAmount(new BigDecimal(dataObj.getString("pay_amt")));
            notifyCallback.tenantPaymentOrderService.paymentForCallback(tenantPaymentOrder);
        }
    }

    /**
     * 用户接收并处理支付失败的异步消息
     *
     * @param payment 失败的支付对象
     * @throws Exception 异常
     */
    @Override
    public void paymentFailedMessageArrived(String payment) throws Exception {
        System.out.println(String.format("receive paymentFailed msg=%s", payment));

        JSONObject dataObj = JSON.parseObject(payment);
        if (!dataObj.getString("app_id").equals(ConfigInit.appId)) {
            return;
        }

        String orderNo = dataObj.getString("order_no");
        StudentPaymentOrder studentPaymentOrder = notifyCallback.studentPaymentOrderService.findOrderByOrderNo(orderNo);

        if (studentPaymentOrder != null) {
            Map<String, String> notifyMap = new HashMap<>();
            notifyMap.put("channelType", dataObj.getString("pay_channel"));
            notifyMap.put("tradeState", "0");
            notifyMap.put("totalMoney", dataObj.getString("pay_amt"));
            notifyMap.put("merOrderNo", dataObj.getString("order_no"));
            notifyMap.put("remarks", dataObj.getString("error_msg"));
            notifyCallback.studentPaymentOrderService.updateOrder(notifyMap);
            return;
        }
        TenantPaymentOrder tenantPaymentOrder = notifyCallback.tenantPaymentOrderService.queryByOrderNo(orderNo);
        if (tenantPaymentOrder != null) {
            tenantPaymentOrder.setStatus(DealStatusEnum.FAILED);
            tenantPaymentOrder.setPaymentBusinessChannel(dataObj.getString("pay_channel"));
            notifyCallback.tenantPaymentOrderService.paymentForCallback(tenantPaymentOrder);
        }
    }


    /**
     * 用户接收并处理关闭支付交易成功的异步消息
     *
     * @param payment 关闭成功的支付对象
     * @throws Exception 异常
     */
    @Override
    public void paymentCloseSuccessMessageArrived(String payment) throws Exception {
        System.out.println(String.format("receive paymentCloseSuccess msg=%s", payment));
        JSONObject dataObj = JSON.parseObject(payment);
        if (!dataObj.getString("app_id").equals(ConfigInit.appId)) {
            return;
        }
        String orderNo = dataObj.getString("order_no");
        StudentPaymentOrder studentPaymentOrder = notifyCallback.studentPaymentOrderService.findOrderByOrderNo(orderNo);

        if (studentPaymentOrder != null) {
            Map<String, String> notifyMap = new HashMap<>();
            notifyMap.put("channelType", dataObj.getString("pay_channel"));
            notifyMap.put("tradeState", "0");
            notifyMap.put("totalMoney", dataObj.getString("pay_amt"));
            notifyMap.put("merOrderNo", dataObj.getString("order_no"));
            notifyMap.put("remarks", dataObj.getString("error_msg"));
            notifyCallback.studentPaymentOrderService.updateOrder(notifyMap);
            return;
        }
        TenantPaymentOrder tenantPaymentOrder = notifyCallback.tenantPaymentOrderService.queryByOrderNo(orderNo);
        if (tenantPaymentOrder != null) {
            tenantPaymentOrder.setStatus(DealStatusEnum.FAILED);
            tenantPaymentOrder.setPaymentBusinessChannel(dataObj.getString("pay_channel"));
            tenantPaymentOrderService.paymentForCallback(tenantPaymentOrder);
        }
    }

    /**
     * 用户接收并处理关闭支付交易失败的异步消息
     *
     * @param payment 关闭失败的支付对象
     * @throws Exception 异常
     */
    @Override
    public void paymentCloseFailedMessageArrived(String payment) throws Exception {
        System.out.println(String.format("receive paymentCloseFailed msg=%s", payment));
    }

    @Override
    public void paymentReverseFailedMessageArrived(String payment) throws Exception {

        System.out.println(String.format("receive payment ReverseFailed msg=%s", payment));
    }

    @Override
    public void paymentReverseSuccessMessageArrived(String payment) throws Exception {
        System.out.println(String.format("receive payment ReverseSuccess msg=%s", payment));
    }

    /**
     * 用户接收并处理退款成功的异步消息
     *
     * @param refund 成功的退款对象
     * @throws Exception 异常
     */
    @Override
    public void refundSuccessMessageArrived(String refund) throws Exception {
        System.out.println(String.format("receive refundSuccess msg=%s", refund));
    }

    /**
     * 用户接收并处理退款失败的异步消息
     *
     * @param refund 失败的退款对象
     * @throws Exception 异常
     */
    @Override
    public void refundFailedMessageArrived(String refund) throws Exception {
        System.out.println(String.format("receive refundFailed   msg=%s", refund));
    }

    @Override
    public void corpMemberSuccessMessageArrived(String corpMember) throws Exception {
        System.out.println(String.format("receive corpMember   msg=%s", corpMember));
        JSONObject corpMemberObj = JSON.parseObject(corpMember);
        if (!corpMemberObj.getString("app_id").equals(ConfigInit.appId)) {
            return;
        }
        String memberId = corpMemberObj.getString("member_id");
        HfMember hfMember = notifyCallback.hfMemberDao.getByMemberId(memberId);
        if (hfMember == null || !hfMember.getStatus().equals("pending")) {
            return;
        }
        hfMember.setStatus("succeeded");
        hfMember.setMemo(corpMemberObj.getString("audit_desc"));
        if (corpMemberObj.containsKey("audit_state") && corpMemberObj.getString("audit_state").equals("E")) {
            JSONObject accounts = JSON.parseObject(corpMemberObj.getString("settle_accounts"));
            hfMember.setSettleAccountId(accounts.getString("id"));
        }
        notifyCallback.hfMemberDao.update(hfMember);
    }

    @Override
    public void corpMemberFailedMessageArrived(String corpMember) throws Exception {
        System.out.println(String.format("receive corpMember  msg=%s", corpMember));
        JSONObject corpMemberObj = JSON.parseObject(corpMember);
        if (!corpMemberObj.getString("app_id").equals(ConfigInit.appId)) {
            return;
        }
        String memberId = corpMemberObj.getString("member_id");
        HfMember hfMember = notifyCallback.hfMemberDao.getByMemberId(memberId);
        if (hfMember == null || !hfMember.getStatus().equals("pending")) {
            return;
        }
        hfMember.setStatus("failed");
        hfMember.setMemo(corpMemberObj.getString("audit_desc"));
        notifyCallback.hfMemberDao.update(hfMember);
    }

    @Override
    public void unknowMessageArrived(String message) throws Exception {
        System.out.println(String.format("receive unknow  msg=%s", message));
    }

    @Override
    public void drawCashFailedMessageArrived(String drawCash) throws Exception {
        System.out.println(String.format("receive unknow  msg=%s", drawCash));

    }

    @Override
    public void drawCashSuccessedMessageArrived(String drawCash) throws Exception {

        System.out.println(String.format("receive unknow  msg=%s", drawCash));

    }

    @Override
    public void pagePaymentFailedMessageArrived(String arg0) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void pagePaymentSuccessedMessageArrived(String arg0) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void connectionLost(String message) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("mqtt...........lost.............");

    }

    @Override
    public void connectSuccess() throws Exception {
        System.out.println("mqtt...........connect.............");
    }
}
