package com.xiaomai.cases.polar.finance.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.cases.polar.admin.AdminTools;
import com.xiaomai.cases.polar.finance.revenueAndExpenditure.RevenueAndExpenditureTools;
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;

public class TestDiscard extends XMBaseTest {
    String memberId;

    String cardId;
    Tools tools=new Tools();

    OrderTools orderTools=new OrderTools();

    RevenueAndExpenditureTools revenueAndExpenditureTools=new RevenueAndExpenditureTools();

    CardTools cardTools=new CardTools();
    AdminTools adminTools=new AdminTools();

    @BeforeMethod
    public void beforeTest(){
        xmAppApi.setApiModule(ApiModule.Polar_Finance)
                .setApiName("API_discard")
                .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 testDiscard(){


        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, price/2,"PURCHASE",
                    "MEMBER_CARD",memberId,price-price/2,price-price/2,"1",true);
            String success=orderResult.getString("success");
            String getDetailId=orderResult.getString("result");
            Assert.assertEquals(success,"true","创建订单失败");

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

            //获取签单订单详情
            JSONObject getDetailResult=orderTools.getDetail(getDetailId);
            String id = getDetailResult.getJSONObject("result").getString("id");
            String businessNo = getDetailResult.getJSONObject("result").getString("businessNo");
            Assert.assertEquals(id.equals(getDetailId),true,"获取创建的订单详情失败");



            //创建退单订单
            //查询要退的卡id 从listUserRefundableCard-查询用户可退的会员卡列表中获取
            JSONObject listUserRefundableCardResult=orderTools.listUserRefundableCard("MEMBER","",memberId);
            String listUserRefundableId=listUserRefundableCardResult.getJSONArray("result").getJSONObject(0).getString("id");

            //查询订单或者收支可退流水金额（包含乐动收银状态信息）
            boolean checkRefundableAmountResult=orderTools.checkRefundableAmount(getDetailId,price - price / 2).getBoolean("success");

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

            if(checkRefundableAmountResult == true) {

                String ownerName=adminTools.getStudioAdmin(xmAppApi.getLoginInfo().getAdminId()).getJSONObject("result").getString("nickName");

                //退单-会员卡
                JSONObject refundOrderResult=orderTools.refundOrder(xmAppApi.getLoginInfo().getAdminId(),ownerName,0,listUserRefundableId,quantity,price - price / 2,"MEMBER_CARD",
                        memberId,price - price / 2,price - price / 2,"1",0,new BigDecimal(price - price / 2),new BigDecimal(price - price / 2));
                String refundOrderGetDetailId=refundOrderResult.getString("result");

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



                //校验是否可以作废退单订单
                boolean checkDiscardRefundVoucherResult = orderTools.checkDiscardVoucher(refundOrderGetDetailId).getBoolean("success");

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

                if (checkDiscardRefundVoucherResult == true) {

                    JSONObject refundDiscardResult = orderTools.discard(refundOrderGetDetailId, "重复录入", "已作废退单订单" + RandomStringUtil.randomString(10));
                    String refundDiscardSuccess = refundDiscardResult.getString("success");
                    Assert.assertEquals(refundDiscardSuccess, "true", "退单订单作废失败");

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

                    //验证退单订单状态
                    //获取退单订单详情--订单状态：已作废
                    JSONObject refundGetDetailResult = orderTools.getDetail(refundOrderGetDetailId);
                    String refundState = refundGetDetailResult.getJSONObject("result").getString("state");
                    String refundBusinessNo = refundGetDetailResult.getJSONObject("result").getString("businessNo");
                    Assert.assertEquals(refundState, "DISCARD", "退单订单作废，但退单订单状态未是已作废");

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

                    //获取退单订单退款记录--退款记录被作废
                    JSONObject refundListByVoucherIdResult = orderTools.listByVoucherId(refundOrderGetDetailId);
                    String  refundListByVoucherId = refundListByVoucherIdResult.getJSONArray("result").getJSONObject(0).getString("id");//收支的id
                    String  refundListByVoucherState = refundListByVoucherIdResult.getJSONArray("result").getJSONObject(0).getString("state");
                    String refundPaymentWayId = refundListByVoucherIdResult.getJSONArray("result").getJSONObject(0).getJSONObject("paymentWay").getString("id");
                    Assert.assertEquals(refundListByVoucherState, "DISCARD", "退单订单的支付记录未被作废");

                    //获取已作废收支明细
                    JSONObject refundPageDiscardIncomeExpenseResult = revenueAndExpenditureTools.pageDiscardIncomeExpense(refundPaymentWayId, "EXPENSE", "REFUND",
                            xmAppApi.getLoginInfo().getStudioId());

                    int refundPageDiscardIncomeExpensePages = Integer.parseInt(refundPageDiscardIncomeExpenseResult.getJSONObject("result").getString("pages"));
                    int refundPageDiscardIncomeExpenseTotal = Integer.parseInt(refundPageDiscardIncomeExpenseResult.getJSONObject("result").getString("total"));


                    for (int k = 0; k == refundPageDiscardIncomeExpensePages + 1; k++) {
                        int n = k == refundPageDiscardIncomeExpensePages ? (refundPageDiscardIncomeExpenseTotal % 10 == 0 ? 10 : refundPageDiscardIncomeExpenseTotal % 10) : 10;
                        JSONArray refundRecords = refundPageDiscardIncomeExpenseResult.getJSONObject("result").getJSONArray("records");
                        boolean flag = true;
                        for (int i = 0; i < n; i++) {
                            String refundPageDiscardIncomeExpenseId = refundRecords.getJSONObject(i).getString("id");
                            if (refundPageDiscardIncomeExpenseId.equals(refundListByVoucherId)) {
                                flag = true;
                                break;
                            }
                        }
                        Assert.assertEquals(true, flag, "退单订单的收支明细未被作废");
                    }

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

                    //获取已作废收支详情
                    JSONObject refundGetResult = revenueAndExpenditureTools.get(refundListByVoucherId);
                    String refundGetBusinessNo = refundGetResult.getJSONObject("result").getString("businessNo");
                    String refundGetState = refundGetResult.getJSONObject("result").getString("state");
                    Assert.assertEquals(refundGetBusinessNo.equals(refundBusinessNo), true, "退单订单的收支明细未被作废");
                    Assert.assertEquals(refundGetState, "DISCARD", "退单订单的收支明细未被作废");

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




                //校验是否可以作废签单订单
                boolean checkDiscardSignVoucherResult = orderTools.checkDiscardVoucher(getDetailId).getBoolean("success");

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

                if (checkDiscardSignVoucherResult == true) {

                    JSONObject discardResult = orderTools.discard(getDetailId, "重复录入", "已作废签单订单" + RandomStringUtil.randomString(10));
                    String discardSuccess = discardResult.getString("success");
                    Assert.assertEquals(discardSuccess, "true", "签单订单作废失败");

                    //验证签单订单状态
                    //获取签单订单详情--订单状态：已作废
                    JSONObject getDetailResult1 = orderTools.getDetail(getDetailId);
                    String state = getDetailResult1.getJSONObject("result").getString("state");
                    Assert.assertEquals(state, "DISCARD", "签单订单作废，但签单订单状态未是已作废");

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

                    //获取签单订单支付记录--支付记录被作废
                    JSONObject listByVoucherIdResult = orderTools.listByVoucherId(getDetailId);
                    String listByVoucherId = listByVoucherIdResult.getJSONArray("result").getJSONObject(0).getString("id");//收支的id
                    String listByVoucherState = listByVoucherIdResult.getJSONArray("result").getJSONObject(0).getString("state");
                    String paymentWayId = listByVoucherIdResult.getJSONArray("result").getJSONObject(0).getJSONObject("paymentWay").getString("id");
                    Assert.assertEquals(listByVoucherState, "DISCARD", "签单订单的支付记录未被作废");

                    //获取已作废收支明细
                    JSONObject pageDiscardIncomeExpenseResult = revenueAndExpenditureTools.pageDiscardIncomeExpense(paymentWayId, "INCOME", "SIGN",
                            xmAppApi.getLoginInfo().getStudioId());

                    int pageDiscardIncomeExpensePages = Integer.parseInt(pageDiscardIncomeExpenseResult.getJSONObject("result").getString("pages"));
                    int pageDiscardIncomeExpenseTotal = Integer.parseInt(pageDiscardIncomeExpenseResult.getJSONObject("result").getString("total"));


                    for (int k = 0; k == pageDiscardIncomeExpensePages + 1; k++) {
                        int n = k == pageDiscardIncomeExpensePages ? (pageDiscardIncomeExpenseTotal % 10 == 0 ? 10 : pageDiscardIncomeExpenseTotal % 10) : 10;
                        JSONArray records = pageDiscardIncomeExpenseResult.getJSONObject("result").getJSONArray("records");
                        boolean flag = true;
                        for (int i = 0; i < n; i++) {
                            String pageDiscardIncomeExpenseId = records.getJSONObject(i).getString("id");
                            if (pageDiscardIncomeExpenseId.equals(listByVoucherId)) {
                                flag = true;
                                break;
                            }
                        }
                        Assert.assertEquals(true, flag, "签单订单的收支明细未被作废");
                    }

                    //获取已作废收支详情
                    JSONObject getResult = revenueAndExpenditureTools.get(listByVoucherId);
                    String getBusinessNo = getResult.getJSONObject("result").getString("businessNo");
                    String getState = getResult.getJSONObject("result").getString("state");
                    Assert.assertEquals(getBusinessNo.equals(businessNo), true, "签单订单的收支明细未被作废");
                    Assert.assertEquals(getState, "DISCARD", "签单订单的收支明细未被作废");


                } else {
                    Assert.assertEquals(checkDiscardSignVoucherResult, false, "签单订单不能作废");
                }

                }
            }
        }

        }

}
