package com.xiaomai.cases.polar.data.financeData;

import com.alibaba.fastjson.JSONObject;
import com.xiaomai.cases.polar.finance.order.OrderTools;
import com.xiaomai.cases.polar.member.Tools;
import com.xiaomai.cases.polar.memberCard.CardTools;
import com.xiaomai.enums.ApiModule;
import com.xiaomai.enums.LoginAccount;
import com.xiaomai.enums.Terminal;
import com.xiaomai.utils.RandomStringUtil;
import com.xiaomai.utils.TimeUtils;
import com.xiaomai.utils.XMBaseTest;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class TestGetCostData extends XMBaseTest {

    FinanceDataTools financeDataTools=new FinanceDataTools();
    OrderTools orderTools = new OrderTools();
    Tools tools = new Tools();

    CardTools cardTools=new CardTools();

    String memberId;
    String cardId;

    @BeforeMethod
    public void beforeTest(){
        xmAppApi.setApiModule(ApiModule.Polar_Data)
                .setApiName("API_getCostData")
                .setLoginUser(LoginAccount.GYM_PROD)
                .setTerminal(Terminal.B);

        dal.setCase_owner("yff")
                .setCase_name(Thread.currentThread().getStackTrace()[1].getFileName().split("\\.")[0]);
        super.beforeTest();
    }

    @Test(description = "获取数据中心-财务数据-营收数据")
    public void testGetCostData() {

        //注意完成一些操作，再校验数据中心的数据一定要等待几秒，数据中心很容易因为没有等待几秒而核对不上

        //先查一下当前营收数据-全部
        JSONObject beforeGetCostData=financeDataTools.getCostData_all("DAY",TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime());
        BigDecimal beforeConfirmedAmount=new BigDecimal(beforeGetCostData.getJSONObject("result").getString("confirmedAmount"));//确认收入
        BigDecimal beforeLeftAmount=new BigDecimal(beforeGetCostData.getJSONObject("result").getString("leftAmount"));//待消耗金额

        //先查一下当前营收数据-会员卡
        JSONObject beforeGetCostDataMember_card=financeDataTools.getCostData_type("DAY","MEMBER_CARD",TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime());
        BigDecimal beforeConfirmedAmountMember_card=new BigDecimal(beforeGetCostDataMember_card.getJSONObject("result").getString("confirmedAmount"));//确认收入
        BigDecimal beforeLeftAmountMember_card=new BigDecimal(beforeGetCostDataMember_card.getJSONObject("result").getString("leftAmount"));//待消耗金额

        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        //①创建部分支付订单，筛选全部和会员卡的确认收入和待消耗金额都无变化
        //造订单相关数据
        String name = "创建订单潜在会员"+ RandomStringUtil.randomString(3);
        String phone = RandomStringUtil.randomMobile("666");

        //获取会员ID,没有则新建一个
        int memberTotal = Integer.parseInt(tools.search("NORMAL","NORMAL").getJSONObject("result").getString("total"));
        if (memberTotal == 0) {
            memberId = tools.create(name,phone).getString("result");
        }
        memberId=tools.search("NORMAL","NORMAL").getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        //获取会员卡信息
        //获取会员卡列表,没有则新建一个
        int cardTotal = Integer.parseInt(orderTools.fetchPageOfMemberCard("次卡","MEMBER_CARD").getJSONObject("result").getString("total"));
        if (cardTotal == 0) {
            cardId = cardTools.memberCardCreate("次卡-创建订单会员卡"+TimeUtils.getCurrentTime()).getString("result");
        }
        JSONObject memberCard=orderTools.fetchPageOfMemberCard("次卡","MEMBER_CARD");
        cardId=memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");
        BigDecimal quantity= new BigDecimal(memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getJSONArray("benefitList").getJSONObject(0).getString("balance"));
        float price= Float.parseFloat(memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("price"));
        int validPeriod= Integer.parseInt(memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("validPeriod"));

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        //获取签单要用的卡快照id
        String latestSnapshotId=orderTools.fetchDetailById(cardId,xmAppApi.getLoginInfo().getBrandId(),xmAppApi.getLoginInfo().getStudioId(),xmAppApi.getLoginInfo().getAdminId()).getJSONObject("result").getString("latestSnapshotId");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        //检查会员对该卡是否超出购买上限
        boolean limitResult=orderTools.checkAllowPurchase("MEMBER_CARD",cardId,memberId,"1",xmAppApi.getLoginInfo().getBrandId(),xmAppApi.getLoginInfo().getStudioId(),xmAppApi.getLoginInfo().getAdminId()).getBoolean("success");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        if(limitResult == true) {

            //创建部分支付订单
            JSONObject orderResult = orderTools.signOrder(cardId, latestSnapshotId, quantity, price, validPeriod, latestSnapshotId, 0, "PURCHASE",
                    "MEMBER_CARD", memberId, price, price / 2, "1");
            String getDetailId = orderResult.getString("result");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            //获取订单详情
            JSONObject getDetailResult = orderTools.getDetail(getDetailId);
            BigDecimal unpaidAmount = new BigDecimal(getDetailResult.getJSONObject("result").getString("unpaidAmount"));//欠费金额

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }


            //先查一下当前营收数据-全部
            JSONObject afterGetCostData=financeDataTools.getCostData_all("DAY",TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime());
            BigDecimal afterConfirmedAmount=new BigDecimal(afterGetCostData.getJSONObject("result").getString("confirmedAmount"));//确认收入
            BigDecimal afterLeftAmount=new BigDecimal(afterGetCostData.getJSONObject("result").getString("leftAmount"));//待消耗金额

            //先查一下当前营收数据-会员卡
            JSONObject afterGetCostDataMember_card=financeDataTools.getCostData_type("DAY","MEMBER_CARD",TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime());
            BigDecimal afterConfirmedAmountMember_card=new BigDecimal(afterGetCostDataMember_card.getJSONObject("result").getString("confirmedAmount"));//确认收入
            BigDecimal afterLeftAmountMember_card=new BigDecimal(afterGetCostDataMember_card.getJSONObject("result").getString("leftAmount"));//待消耗金额


            //校验1：
            //校验部分支付订单对于营收数据-全部的确认收入和待消耗金额无变化
            Assert.assertEquals(afterConfirmedAmount, beforeConfirmedAmount,"创建部分支付订单，数据中心-营收数据汇总-全部-确认收入应该无变化");
            Assert.assertEquals(afterLeftAmount,beforeLeftAmount,"创建部分支付订单，数据中心-营收数据汇总-全部-待消耗金额应该无变化");

            //校验部分支付订单对于营收数据-会员卡的确认收入和待消耗金额无变化
            Assert.assertEquals(afterConfirmedAmountMember_card, beforeConfirmedAmountMember_card,"创建部分支付订单，数据中心-营收数据汇总-会员卡-确认收入应该无变化");
            Assert.assertEquals(afterLeftAmountMember_card,beforeLeftAmountMember_card,"创建部分支付订单，数据中心-营收数据汇总-会员卡-待消耗金额应该无变化");


            //②继续收款，订单变成已支付，待消耗金额应该增加
            //继续收款
            JSONObject pay=orderTools.pay(unpaidAmount,"1",getDetailId);

            //获取订单详情
            JSONObject getDetailResult1 = orderTools.getDetail(getDetailId);
            BigDecimal receivableAmount1 = new BigDecimal(getDetailResult1.getJSONObject("result").getString("receivableAmount"));//应收金额
            BigDecimal paidAmount1 = new BigDecimal(getDetailResult1.getJSONObject("result").getString("paidAmount"));//已支付金额


            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }


            //再查一下当前营收数据-全部
            JSONObject afterGetCostData1=financeDataTools.getCostData_all("DAY",TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime());
            BigDecimal afterConfirmedAmount1=new BigDecimal(afterGetCostData1.getJSONObject("result").getString("confirmedAmount"));//确认收入
            BigDecimal afterLeftAmount1=new BigDecimal(afterGetCostData1.getJSONObject("result").getString("leftAmount"));//待消耗金额

            //再查一下当前营收数据-会员卡
            JSONObject afterGetCostDataMember_card1=financeDataTools.getCostData_type("DAY","MEMBER_CARD",TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime());
            BigDecimal afterConfirmedAmountMember_card1=new BigDecimal(afterGetCostDataMember_card1.getJSONObject("result").getString("confirmedAmount"));//确认收入
            BigDecimal afterLeftAmountMember_card1=new BigDecimal(afterGetCostDataMember_card1.getJSONObject("result").getString("leftAmount"));//待消耗金额


            //校验2：
            //校验已支付订单对于营收数据-全部的待消耗金额应该增加对应的金额，确认收入应该无变化
            Assert.assertEquals(afterConfirmedAmount1,afterConfirmedAmount ,"创建已支付订单，数据中心-营收数据汇总-全部-确认收入应该无变化");
            Assert.assertEquals(afterLeftAmount1,afterLeftAmount.add(paidAmount1.setScale(2, RoundingMode.HALF_UP)),"创建已支付订单，数据中心-营收数据汇总-全部-待消耗金额应该增加对应的金额");

            //校验已支付订单对于营收数据-会员卡的待消耗金额应该增加对应的金额，确认收入应该无变化
            Assert.assertEquals(afterConfirmedAmountMember_card1, afterConfirmedAmountMember_card,"创建已支付订单，数据中心-营收数据汇总-会员卡-确认收入应该无变化");
            Assert.assertEquals(afterLeftAmountMember_card1,afterLeftAmountMember_card.add(paidAmount1.setScale(2, RoundingMode.HALF_UP)),"创建已支付订单，数据中心-营收数据汇总-会员卡-待消耗金额应该增加对应的金额");


            //③消耗之后，筛选全部和会员卡的待消耗金额减少，确认收入增加
            //获取会员下的购买的会员卡
            JSONObject fetchUserCardListResult=orderTools.fetchUserCardList("MEMBER",memberId,"NORMAL");
            String memberCardId=fetchUserCardListResult.getJSONArray("result").getJSONObject(0).getString("id");//memberCardId
            String benefitId=fetchUserCardListResult.getJSONArray("result").getJSONObject(0).getJSONObject("courseBenefit").getString("id");//benefitId
            String balance=fetchUserCardListResult.getJSONArray("result").getJSONObject(0).getJSONObject("courseBenefit").getString("leftBalance");//memberCardId

            //手动扣次，扣完
            cardTools.manualDeduct(benefitId,memberCardId,balance);


            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }


            //再查一下当前营收数据-全部
            JSONObject afterGetCostData2=financeDataTools.getCostData_all("DAY",TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime());
            BigDecimal afterConfirmedAmount2=new BigDecimal(afterGetCostData2.getJSONObject("result").getString("confirmedAmount"));//确认收入
            BigDecimal afterLeftAmount2=new BigDecimal(afterGetCostData2.getJSONObject("result").getString("leftAmount"));//待消耗金额

            //再查一下当前营收数据-会员卡
            JSONObject afterGetCostDataMember_card2=financeDataTools.getCostData_type("DAY","MEMBER_CARD",TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime());
            BigDecimal afterConfirmedAmountMember_card2=new BigDecimal(afterGetCostDataMember_card2.getJSONObject("result").getString("confirmedAmount"));//确认收入
            BigDecimal afterLeftAmountMember_card2=new BigDecimal(afterGetCostDataMember_card2.getJSONObject("result").getString("leftAmount"));//待消耗金额


            //校验3：
            //校验手动扣次之后营收数据-筛选全部的待消耗金额应该减少对应的金额，确认收入应该增加对应的金额
            Assert.assertEquals(afterConfirmedAmount2,afterConfirmedAmount1.add(paidAmount1.setScale(2, RoundingMode.HALF_UP)),"手动扣完所有次数之后，数据中心-营收数据汇总-全部-确认收入应该增加对应的金额");
            Assert.assertEquals(afterLeftAmount2,afterLeftAmount1.subtract(paidAmount1.setScale(2, RoundingMode.HALF_UP)),"手动扣完所有次数，数据中心-营收数据汇总-全部-待消耗金额应该减少对应的金额");

            //校验手动扣次之后营收数据-筛选会员卡的待消耗金额应该减少对应的金额，确认收入应该增加对应的金额
            Assert.assertEquals(afterConfirmedAmountMember_card2, afterConfirmedAmountMember_card1.add(paidAmount1.setScale(2, RoundingMode.HALF_UP)),"手动扣完所有次数之后，数据中心-营收数据汇总-会员卡-确认收入应该增加对应的金额");
            Assert.assertEquals(afterLeftAmountMember_card2,afterLeftAmountMember_card1.subtract(paidAmount1.setScale(2, RoundingMode.HALF_UP)),"手动扣完所有次数，数据中心-营收数据汇总-会员卡-待消耗金额应该减少对应的金额");





        }


    }
    }
