package cn.pluss.platform.ali.impl;

import cn.pluss.platform.ali.AliPayNotifyService;
import cn.pluss.platform.device.MercOrderNewService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.merchantIncome.MerchantIncomeService;
import cn.pluss.platform.merchantOrder.MerchantOrderService;
import cn.pluss.platform.merchantProfit.MerchantProfitService;
import cn.pluss.platform.notice.NoticeService;
import cn.pluss.platform.pay.PayCallbackService;
import cn.pluss.platform.pay.impl.BaseCallbackService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.util.ParametersUtil;
import cn.pluss.platform.util.StringUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author DJH
 */
@Slf4j
@Service
public class AliPayNotifyServiceImpl extends BaseCallbackService implements AliPayNotifyService, PayCallbackService {

    @Autowired
    private GeneralPushUtil generalPushUtil;

    @Setter(onMethod_ = {@Autowired})
    private MerchantOrderService merchantOrderService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantIncomeService merchantIncomeService;

    @Setter(onMethod_ = {@Autowired})
    private UserAppService userAppService;

    @Setter(onMethod_ = {@Autowired})
    private UserInfoService userInfoService;

    @Setter(onMethod_ = {@Autowired})
    private MerchantProfitService merchantProfitService;

    @Setter(onMethod_ = {@Autowired})
    private SystemConfigService systemConfigService;

    @Setter(onMethod_ = {@Autowired})
    private NoticeService noticeService;

    @Setter(onMethod_ = {@Autowired})
    private MercOrderNewService mercOrderNewService;

    @Override
    public void commonPayNotify(Map<String, Object> param) {
        // 商家订单号
        String orderNumber = (String) param.get("out_trade_no");

        if (orderNumber != null && orderNumber.startsWith(MerchantOrder.UPGRADE_ORDER_PREFIX)) {
            spreadUpgradePayNotify(param);
            return;
        }

        devicePayNotify(param);
    }

    private void checkSign(Map<String, String> params) throws AlipayApiException {
        boolean signVerified = AlipaySignature.rsaCheckV1(params, ParametersUtil.ZY_PUB, "UTF-8", "RSA2");
        if (!signVerified) {
            throw new MsgException("支付宝回调验签失败");
        }
    }

    @Override
    public void devicePayNotify(Map<String, Object> param) {
        String tradeNumber = (String) param.get("trade_no");
        // 商家订单号
        String orderNumber = (String) param.get("out_trade_no");
        // 交易付款时间
        String consumeTime = (String) param.get("gmt_payment");
        Date transDt = DateUtils.parse(consumeTime, "yyyy-MM-dd HH:mm:ss");

        devicePaySuccessNotify(orderNumber, tradeNumber, tradeNumber, transDt, param);
        mercOrderNewService.devicePaySuccessNotifyV2(orderNumber, tradeNumber,tradeNumber, transDt, null);
    }

    @Override
    public void spreadUpgradePayNotify(Map<String, Object> param) {
        String orderNumber = (String) param.get("out_trade_no");// 微信交易流水号
        String tradeNo = (String) param.get("trade_no");

        String consumeTime = (String) param.get("gmt_payment");
        Date transDt = DateUtils.parse(consumeTime, "yyyy-MM-dd HH:mm:ss");

        upgradeSuccessNotify(orderNumber, tradeNo, tradeNo, transDt, param);

        // 计算分润 profitAmt
        try {
            merchantIncome(param);
        }catch (Exception e){
            log.error("升级回调更新分润异常，订单号:{},异常信息:{}",param.get("out_trade_no"),e.getMessage());
            e.printStackTrace();
        }
        // 更新订单信息
        updateOrderStatus(param);

    }

    /**
     * 更新订单信息和状态
     *
     * @param param 订单回调信息
     */
    private void updateOrderStatus(Map<String, Object> param) {
        // 商户订单号
        String orderNumber = (String) param.get("out_trade_no");
        // 支付宝交易号
        String tradeNo = (String) param.get("trade_no");
        MerchantOrder mOrder = new MerchantOrder().setOrderNumber(orderNumber);
        mOrder = merchantOrderService.getOne(new QueryWrapper<>(mOrder));

        mOrder.setThirdTransNo(tradeNo);
        // 交易付款时间
        String consumeTime = (String) param.get("gmt_payment");
        mOrder.setStatus("1");
        mOrder.setTransDt(DateUtils.parse(consumeTime, "yyyy-MM-dd HH:mm:ss"));
        mOrder.setTransNo(tradeNo);
        String profitAmt = (String) param.get("profitAmt");
        if(StringUtil.isNotEmpty(profitAmt)){
            mOrder.setProfitShareMoney(Double.valueOf(profitAmt));
        }
        merchantOrderService.updateById(mOrder);
    }

    private void merchantIncome(Map<String, Object> param) {
        String ordersSn = (String) param.get("out_trade_no");
        MerchantIncome merchantIncome = new MerchantIncome();
        merchantIncome.setDealCode(ordersSn);
        merchantIncome = merchantIncomeService.queryMerchantIncome(merchantIncome);
        merchantIncome.setDealStatus(1);
        merchantIncomeService.updateMerchantIncome(merchantIncome);

        UserApp userApp = new UserApp();
        userApp.setUserId(merchantIncome.getUserId().longValue());
        userApp = userAppService.queryUserApp(userApp);

        String content = "";

        if (userApp == null || userApp.getParentId() == null) {
            return;
        }


        UserApp userApp2 = new UserApp();
        userApp2.setUserId(userApp.getParentId());
        userApp2 = userAppService.queryUserApp(userApp2);

        String userName = "";

        UserInfo userInfo = new UserInfo();
        userInfo.setId(userApp.getUserId());
        userInfo = userInfoService.queryUserInfo(userInfo);
        String twoConfigValue = systemConfigService.querySystemConfigValue("twoUpVipAmount");
        String threeConfigValue = systemConfigService.querySystemConfigValue("threeUpVipAmount");
        userName = userInfo.getLoginName().substring(0, 11);

        userName = StringUtil.isHideMobile(userName);

        MerchantProfit profit = new MerchantProfit();
        profit.setUserId(userApp.getParentId());
        profit.setMerchantCode("M800202008254990744");
        profit.setMerchantName("安象科技公司");
        profit.setConsumeFee(merchantIncome.getDealFee());
        Double twoVipAmountD = 999.00;
        Double twoVipShapeAmtD = 500.00;
        Double threeVipAmountD = 9999.00;
        Double threeVipShapeAmtD = 5000.00;
        if (StringUtil.isNotEmpty(twoConfigValue)) {
            String twoVipAmount = twoConfigValue.split("-")[0];
            String twoVipShapeAmount = twoConfigValue.split("-")[1];
            twoVipAmountD = Double.valueOf(twoVipAmount);
            twoVipShapeAmtD = Double.valueOf(twoVipShapeAmount);
        }
        if (StringUtil.isNotEmpty(threeConfigValue)) {
            String threeVipAmount = threeConfigValue.split("-")[0];
            String threeVipShapeAmount = threeConfigValue.split("-")[1];
            threeVipAmountD = Double.valueOf(threeVipAmount);
            threeVipShapeAmtD = Double.valueOf(threeVipShapeAmount);
        }
        if (twoVipAmountD.equals(merchantIncome.getDealFee())) {
            profit.setPrice(twoVipShapeAmtD);
            userApp.setLevel(2);
            content = "您的直接推荐 " + userName + "付费升级v2,收益" + twoVipShapeAmtD + "元";
        }
        if (threeVipAmountD.equals(merchantIncome.getDealFee())) {
            profit.setPrice(threeVipShapeAmtD);
            userApp.setLevel(3);
            content = "您的直接推荐 " + userName + "付费升级v3,收益" + threeVipShapeAmtD + "元";
        }

        profit.setType("4");
        profit.setCreateDt(new Date());
        profit.setOrderDt(merchantIncome.getCreateTime());
        profit.setStatus("1");
        profit.setOrderNumber(ordersSn);
        merchantProfitService.saveMerchantProfit(profit);
        userAppService.updateById(userApp);
        param.put("profitAmt",profit.getPrice().toString());

        List<String> alias = new ArrayList<>();
        log.info("=========推送人userId======" + profit.getUserId() + "=========金额=======" + profit.getPrice());
        alias.add(profit.getUserId() + "");

        if (userApp2 != null) {
            Notice notice = new Notice(0, 7, userApp2);
            notice.setConrtent(content);

            noticeService.saveNotice(notice);
            generalPushUtil.sendAllPlatByAlias(alias, "升级分润通知", content, "0");
        }
    }

    @Override
    public void orderCallback(Map<String, Object> callbackData) {

    }
}
