package cn.pluss.platform.wx.impl;

import cn.hutool.core.date.DateUtil;
import cn.pluss.platform.entity.*;
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.user.impl.GeneralPushUtil;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.util.DateUtils;
import cn.pluss.platform.util.StringUtil;
import cn.pluss.platform.wx.WxPayNotifyService;
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 org.springframework.transaction.annotation.Transactional;

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

/**
 * @author DJH
 */
@Slf4j
@Service
public class WxPayNotifyServiceImpl extends BaseCallbackService implements WxPayNotifyService, 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 SystemConfigService systemConfigService;

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

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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void commonPayNotify(Map<String, Object> param) {
        if (!"SUCCESS".equals(param.get("result_code"))) {
            return;
        }

        // 商户订单号
        String ordersSn = (String) param.get("out_trade_no");

        assert ordersSn != null: "缺少订单号";

        if (ordersSn.startsWith(MerchantOrder.UPGRADE_ORDER_PREFIX)) {
            spreadUpgradePayNotify(param);
            return;
        }

        devicePayNotify(param);
    }

    @Override
    public void devicePayNotify(Map<String, Object> param) {
        // 商户订单号
        String orderNumber = (String) param.get("out_trade_no");
        String transNo = (String) param.get("transaction_id");
        // 实际支付的订单金额:单位 分
        // String amountpaid = (String) param.get("total_fee");
        // 用户openid
        // String openid = (String) param.get("openid");
        // 支付完成时间
        String tranDtStr = (String) param.get("time_end");
        Date tranDt = DateUtil.parse(tranDtStr, "yyyyMMddHHmmss").toJdkDate();

        devicePaySuccessNotify(orderNumber, transNo, transNo, tranDt, param);

        // // Double amount=Double.valueOf(amountpaid)*100;
        // DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
        // deviceMerchantBuy.setOrderNo(orderNumber);
        // deviceMerchantBuy = deviceMerchantBuyService.queryDeviceMerchantBuy(deviceMerchantBuy);
        // if ("1".equals(deviceMerchantBuy.getStatus())) {
        //     return;
        // }
        // deviceMerchantBuy.setStatus("1");
        // deviceMerchantBuy.setTransNo(transNo);
        //
        // deviceMerchantBuy.setTransDt(tranDt);
        // deviceMerchantBuyService.updateDeviceMerchantBuy(deviceMerchantBuy);
        //
        // DeviceOrderInfo deviceOrderInfo = new DeviceOrderInfo();
        // deviceOrderInfo.setOrderNo(orderNumber);
        // deviceOrderInfo = deviceOrderInfoService.getOne(new QueryWrapper<>(deviceOrderInfo));
        // deviceOrderInfo.setTransNo(transNo);
        // deviceOrderInfo.setUpdateTime(new Date());
        // deviceOrderInfoService.updateById(deviceOrderInfo);
    }

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

        String consumeTime = ((String) param.get("time_end"));
        Date transDt = DateUtils.parse(consumeTime, "yyyyMMddHHmmss");

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

        // 计算分润
        // merchantIncome(param);
        //
        // // 更新订单信息
        // updateOrderStatus(param);
    }

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

        mOrder.setThirdTransNo(tradeNo);
        // 交易付款时间
        String consumeTime = ((String) param.get("time_end"));
        mOrder.setStatus("1");
        mOrder.setTransDt(DateUtils.parse(consumeTime, "yyyyMMddHHmmss"));
        mOrder.setTransNo(tradeNo);
        Object profitAmt = param.get("profitAmt");
        if(StringUtil.isNotEmpty(profitAmt)){
            mOrder.setProfitShareMoney(Double.valueOf(profitAmt.toString()));
        }
        merchantOrderService.updateById(mOrder);
    }

    private void merchantIncome(Map<String,Object> param) {
        String orderSn = (String) param.get("out_trade_no");
        MerchantIncome merchantIncome = new MerchantIncome();
        merchantIncome.setDealCode(orderSn);
        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);

//        if (userApp2 == null) {
//            return;
//        }


        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(orderSn);
        merchantProfitService.saveMerchantProfit(profit);
        userAppService.updateById(userApp);
        param.put("profitAmt",profit.getPrice());
        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) {
        // 这里现有的逻辑不做更改
    }
}
