package cn.pluss.platform.pay.impl;


import cn.pluss.platform.device.DeviceOrderInfoService;
import cn.pluss.platform.device.MercOrderDetailService;
import cn.pluss.platform.device.MercOrderNewService;
import cn.pluss.platform.deviceMerchantBuy.DeviceMerchantBuyService;
import cn.pluss.platform.entity.*;
import cn.pluss.platform.mapper.MerchantBaseInfoMapper;
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.openAccount.OpenAccountRecordService;
import cn.pluss.platform.pay.PayCallbackService;
import cn.pluss.platform.systemConfig.SystemConfigService;
import cn.pluss.platform.userApp.UserAppService;
import cn.pluss.platform.userInfo.UserInfoService;
import cn.pluss.platform.user.impl.GeneralPushUtil;
import cn.pluss.platform.util.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

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

/**
 * 聚合一些基本操作
 * @author SSS
 */
@Slf4j
public abstract class BaseCallbackService implements PayCallbackService {

    @Autowired
    protected MerchantOrderService moService;

    @Autowired
    protected MerchantProfitService merchantProfitService;

    @Autowired
    protected SystemConfigService systemConfigService;

    @Autowired
    protected MerchantIncomeService merchantIncomeService;

    @Autowired
    protected UserAppService userAppService;

    @Autowired
    protected NoticeService noticeService;

    @Autowired
    protected UserInfoService uiService;

    @Autowired
    protected DeviceMerchantBuyService deviceMerchantBuyService;

    @Autowired
    protected DeviceOrderInfoService deviceOrderInfoService;

    @Autowired
    protected MercOrderNewService monService;

    @Autowired
    protected MercOrderDetailService modService;

    @Autowired
    private GeneralPushUtil generalPushUtil;

    @Autowired
    private OpenAccountRecordService openAccountRecordService;

    @Autowired
    private MerchantBaseInfoMapper merchantBaseInfoMapper;
    /**
     * 升级支付成功回调
     * @param orderNumber 订单号
     * @param thirdOrderNumber 通道订单号, 通道方订单号, 随行付、瑞银信、银盛等
     * @param transNo 支付方订单流水号，通常是、支付宝、微信、云闪付等
     * @param transDt 交易完成时间
     * @param allParams 其他
     */
    public void upgradeSuccessNotify(String orderNumber, String thirdOrderNumber, String transNo, Date transDt, Map<String, Object> allParams) {

        // MerchantIncome merchantIncome = new MerchantIncome();
        // merchantIncome.setDealCode(orderNumber);
        // 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 = uiService.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(orderNumber);
        // merchantProfitService.saveMerchantProfit(profit);
        // userAppService.updateById(userApp);
        // 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");
        // }
        //
        // MerchantOrder mOrder = new MerchantOrder().setOrderNumber(orderNumber);
        // mOrder = moService.getOne(new QueryWrapper<>(mOrder));
        //
        // mOrder.setThirdTransNo(thirdOrderNumber);
        // // 交易付款时间
        // mOrder.setStatus("1");
        // mOrder.setTransDt(transDt);
        // mOrder.setTransNo(transNo);
        // Object profitAmt = profit.getPrice();
        // if(StringUtil.isNotEmpty(profitAmt)){
        //     mOrder.setProfitShareMoney(Double.valueOf(profitAmt.toString()));
        // }
        // moService.updateById(mOrder);

        // ================== 以上是老的升级逻辑 ================
        MerchantOrder mo = moService.getLockByOrderNumber(orderNumber);
        MerchantIncome merchantIncome = new MerchantIncome();
        merchantIncome.setDealCode(orderNumber);
        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 = uiService.queryUserInfo(userInfo);
        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());

        // "分润金额合计为-" + targetProfit.toPlainString() + "-" + "从-" + currentLevelNum + "-升到-" + targetLevelNum
        String[] split = mo.getRemark().split("-");
        double profitData = Double.parseDouble(split[1]);
        profit.setPrice(profitData);
        userApp.setLevelCode("LV" + split[5]);
        content = "您的直接推荐 " + userName + "付费升级到VIP" + split[5] + ", 收益" + profitData + "元";

        profit.setType("4");
        profit.setCreateDt(new Date());
        profit.setOrderDt(merchantIncome.getCreateTime());
        profit.setStatus("1");
        profit.setOrderNumber(orderNumber);
        merchantProfitService.saveMerchantProfit(profit);
        userAppService.updateById(userApp);
        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");
        }

        MerchantOrder mOrder = new MerchantOrder().setOrderNumber(orderNumber);
        mOrder = moService.getOne(new QueryWrapper<>(mOrder));

        mOrder.setThirdTransNo(thirdOrderNumber);
        // 交易付款时间
        mOrder.setStatus("1");
        mOrder.setTransDt(transDt);
        mOrder.setTransNo(transNo);
        Object profitAmt = profit.getPrice();
        if(StringUtil.isNotEmpty(profitAmt)){
            mOrder.setProfitShareMoney(Double.valueOf(profitAmt.toString()));
        }
        moService.updateById(mOrder);
    }

    /**
     * 升级支付成功回调
     * @param orderNumber 订单号
     * @param thirdOrderNumber 通道订单号, 通道方订单号, 随行付、瑞银信、银盛等
     * @param transNo 支付方订单流水号，通常是、支付宝、微信、云闪付等
     * @param transDt 交易完成时间
     * @param allParams 其他
     */
    public void devicePaySuccessNotify(String orderNumber, String thirdOrderNumber, String transNo, Date transDt, Map<String, Object> allParams) {
        DeviceMerchantBuy deviceMerchantBuy = new DeviceMerchantBuy();
        deviceMerchantBuy.setOrderNo(orderNumber);
        deviceMerchantBuy = deviceMerchantBuyService.queryDeviceMerchantBuy(deviceMerchantBuy);

        if (deviceMerchantBuy == null) {
            return;
        }

        if ("1".equals(deviceMerchantBuy.getStatus())) {
            return;
        }

        deviceMerchantBuy.setStatus("1");
        deviceMerchantBuy.setTransNo(transNo);
        deviceMerchantBuy.setTransDt(transDt);
        deviceMerchantBuyService.updateDeviceMerchantBuy(deviceMerchantBuy);

        DeviceOrderInfo deviceOrderInfo = new DeviceOrderInfo();
        deviceOrderInfo.setOrderNo(orderNumber);
        deviceOrderInfo = deviceOrderInfoService.getOne(new QueryWrapper<>(deviceOrderInfo));
        deviceOrderInfo.setTransNo(transNo);
        deviceOrderInfo.setUpdateTime(new Date());
        deviceOrderInfo.setStatus("1");
        deviceOrderInfoService.updateById(deviceOrderInfo);

        
        //TODO 兼容ios版本落后 iso版本更新后删除该代码
        String merchantCode = deviceMerchantBuy.getMerchantCode();
        if(StringUtil.isNotEmpty(merchantCode)){
            MerchantBaseInfo merchant = merchantBaseInfoMapper.queryByMerchantCode(merchantCode);
            if(merchant != null){
                openAccountRecordService.operatAccountOpen(deviceMerchantBuy,merchant,deviceOrderInfo);
            }
        }
    }
}
