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

import com.alibaba.fastjson.JSONArray;
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, "1",false);
            String getDetailId = orderResult.getString("result");


            try {
                Thread.sleep(20000);
            } 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.add(new BigDecimal(price).setScale(2, RoundingMode.HALF_UP)),"创建已支付订单，数据中心-营收数据汇总-全部-待消耗金额应该增加对应的金额");

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



            //根据商品类型全部加起来的确认收入查全部(覆盖一下商品类型的新接口)
            JSONObject getCommodityTypeCostDetail=financeDataTools.getCommodityTypeCostDetail("DAY","LEFT_AMOUNT_DESC",TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime());
            int getCommodityTypeCostDetail_total=Integer.parseInt(getCommodityTypeCostDetail.getJSONObject("result").getString("total"));
            Assert.assertEquals(getCommodityTypeCostDetail_total,9,"获取商品类型不是9个");

            JSONObject getCommodityTypeCostDetail_result=getCommodityTypeCostDetail.getJSONObject("result");
            //确认收入
            BigDecimal confirmedAmount1=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(0).getString("confirmedAmount"));
            BigDecimal confirmedAmount2=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(1).getString("confirmedAmount"));
            BigDecimal confirmedAmount3=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(2).getString("confirmedAmount"));
            BigDecimal confirmedAmount4=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(3).getString("confirmedAmount"));
            BigDecimal confirmedAmount5=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(4).getString("confirmedAmount"));
            BigDecimal confirmedAmount6=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(5).getString("confirmedAmount"));
            BigDecimal confirmedAmount7=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(6).getString("confirmedAmount"));
            BigDecimal confirmedAmount8=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(7).getString("confirmedAmount"));
            BigDecimal confirmedAmount9=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(8).getString("confirmedAmount"));



//            //待消耗金额--之前有脏数据，不好订正就不校验待消耗金额了
//            BigDecimal leftAmount1=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(0).getString("leftAmount"));
//            BigDecimal leftAmount2=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(1).getString("leftAmount"));
//            BigDecimal leftAmount3=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(2).getString("leftAmount"));
//            BigDecimal leftAmount4=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(3).getString("leftAmount"));
//            BigDecimal leftAmount5=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(4).getString("leftAmount"));
//            BigDecimal leftAmount6=new BigDecimal(getCommodityTypeCostDetail_result.getJSONArray("records").getJSONObject(5).getString("leftAmount"));

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

            //校验所有商品类型的确认收入加起来=全部的确认收入
            Assert.assertEquals(confirmedAmount1.setScale(2, RoundingMode.HALF_UP).add(confirmedAmount2.setScale(2, RoundingMode.HALF_UP)).add(confirmedAmount3.setScale(2, RoundingMode.HALF_UP))
                    .add(confirmedAmount4.setScale(2, RoundingMode.HALF_UP)).add(confirmedAmount5.setScale(2, RoundingMode.HALF_UP))
                    .add(confirmedAmount6.setScale(2, RoundingMode.HALF_UP)).add(confirmedAmount7.setScale(2, RoundingMode.HALF_UP))
                            .add(confirmedAmount8.setScale(2, RoundingMode.HALF_UP)).add(confirmedAmount9.setScale(2, RoundingMode.HALF_UP)),afterConfirmedAmount,"营收明细所有商品类型的确认收入加起来应该等于营收数据全部的确认收入");

//            //校验所有商品类型的待消耗金额加起来=全部的待消耗金额
//            Assert.assertEquals(leftAmount1.setScale(2, RoundingMode.HALF_UP).add(leftAmount2.setScale(2, RoundingMode.HALF_UP)).add(leftAmount3.setScale(2, RoundingMode.HALF_UP))
//                    .add(leftAmount4.setScale(2, RoundingMode.HALF_UP)).add(leftAmount5.setScale(2, RoundingMode.HALF_UP))
//                    .add(leftAmount6.setScale(2, RoundingMode.HALF_UP)),afterLeftAmount1,"所有商品类型的待消耗金额加起来不等于全部的待消耗金额");

            //再查一下当前营收数据-会员卡
            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"));//待消耗金额


            //②消耗之后，筛选全部和会员卡的待消耗金额减少，确认收入增加
            //获取会员下的购买的会员卡
            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(20000);
            } 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,afterConfirmedAmount.add(new BigDecimal(price).setScale(2, RoundingMode.HALF_UP)),"手动扣完所有次数之后，数据中心-营收数据汇总-全部-确认收入应该增加对应的金额");
            Assert.assertEquals(afterLeftAmount2,afterLeftAmount.subtract(new BigDecimal(price).setScale(2, RoundingMode.HALF_UP)),"手动扣完所有次数，数据中心-营收数据汇总-全部-待消耗金额应该减少对应的金额");

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





        }


    }
    }
