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

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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 TestRefundOrder extends XMBaseTest {


    String memberId;

    String cardId;

    Tools tools=new Tools();

    OrderTools orderTools=new OrderTools();

    RevenueAndExpenditureTools revenueAndExpenditureTools=new RevenueAndExpenditureTools();

    CardTools cardTools=new CardTools();

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

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

            //获取签单订单详情
            JSONObject getSignDetailResult=orderTools.getDetail(getDetailId);
            String signBusinessNo = getSignDetailResult.getJSONObject("result").getString("businessNo");

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

            //查询要退的卡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){

                //退单-会员卡
                JSONObject refundOrderResult=orderTools.refundOrder(0,listUserRefundableId,quantity,price - price / 2,"MEMBER_CARD",
                        memberId,price - price / 2,price - price / 2,"1");

                String refundOrderSuccess=refundOrderResult.getString("success");
                String refundOrderGetDetailId=refundOrderResult.getString("result");
                Assert.assertEquals(refundOrderSuccess,"true","创建退单订单失败");


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

                //获取订单详情
                JSONObject getDetailResult=orderTools.getDetail(refundOrderGetDetailId);
                String id = getDetailResult.getJSONObject("result").getString("id");
                String businessNo = getDetailResult.getJSONObject("result").getString("businessNo");//退单订单的businessNo
                String state=getDetailResult.getJSONObject("result").getString("state");
                Assert.assertEquals(id.equals(refundOrderGetDetailId),true,"获取创建的退单订单详情失败");
                Assert.assertEquals(state,"PAID","获取创建的退单订单未完成");


                //获取订单支付记录
                JSONObject listByVoucherIdResult=orderTools.listByVoucherId(refundOrderGetDetailId);
                String listByVoucherId = listByVoucherIdResult.getJSONArray("result").getJSONObject(0).getString("voucherId");//退单订单的id
                String paymentWayId=listByVoucherIdResult.getJSONArray("result").getJSONObject(0).getJSONObject("paymentWay").getString("id");
                String listByVoucherState=listByVoucherIdResult.getJSONArray("result").getJSONObject(0).getString("state");
                String id1=listByVoucherIdResult.getJSONArray("result").getJSONObject(0).getString("id");//收支的id
                Assert.assertEquals(listByVoucherId.equals(refundOrderGetDetailId),true,"获取创建的退单订单的支付记录失败");
                Assert.assertEquals(listByVoucherState,"NORMAL","获取创建的退单订单的支付记录状态未是已完成");


                //获取订单管理列表
                JSONObject pageVoucherResult=orderTools.pageVoucher1(xmAppApi.getLoginInfo().getStudioId(),businessNo);
                int total=Integer.parseInt(pageVoucherResult.getJSONObject("result").getString("total"));
                Assert.assertEquals(total>=1,true,"订单管理列表获取创建的退单订单失败");

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

                //获取收支明细
                JSONObject pageNormalIncomeExpenseResult=revenueAndExpenditureTools.pageNormalIncomeExpense(paymentWayId,"EXPENSE", "REFUND",
                        xmAppApi.getLoginInfo().getStudioId());
                int pageNormalIncomeExpensePages=Integer.parseInt(pageNormalIncomeExpenseResult.getJSONObject("result").getString("pages"));
                int pageNormalIncomeExpenseTotal=Integer.parseInt(pageNormalIncomeExpenseResult.getJSONObject("result").getString("total"));


                for(int k=0; k == pageNormalIncomeExpensePages+1; k++){
                    int n =k==pageNormalIncomeExpensePages ? (pageNormalIncomeExpenseTotal%10==0 ? 10 : pageNormalIncomeExpenseTotal%10) : 10;
                    JSONArray records=pageNormalIncomeExpenseResult.getJSONObject("result").getJSONArray("records");
                    boolean flag=true;
                    for(int i=0; i<n; i++){
                        String pageNormalIncomeExpenseId=records.getJSONObject(i).getString("id");
                        if(pageNormalIncomeExpenseId.equals(id1)){
                            flag = true;
                            break;
                        }
                    }
                    Assert.assertEquals(true,flag,"创建退单订单未生成对应的收支明细");
                }

                //获取收支详情
                JSONObject getResult=revenueAndExpenditureTools.get(id1);
                String getBusinessNo=getResult.getJSONObject("result").getString("businessNo");
                String getState=getResult.getJSONObject("result").getString("state");

                Assert.assertEquals(getBusinessNo.equals(businessNo),true,"获取创建的退单订单的收支详情失败");
                Assert.assertEquals(getState,"NORMAL","创建的退单订单的收支明细状态未是已完成");


                //校验获取会员下的退卡的会员卡是否生成已退卡卡包

                //获取会员下的退掉的会员卡
                JSONObject fetchUserCardListResult=orderTools.fetchUserCardList("MEMBER",memberId,"REFUNDED");
                String fetchUserCardListId=fetchUserCardListResult.getJSONArray("result").getJSONObject(0).getString("id");//权益ID

                //获取售卖详情
                JSONObject findDetailByIdResult=cardTools.memberCardFindDetailById(fetchUserCardListId);
                String findDetailByIdState=findDetailByIdResult.getJSONObject("result").getString("state");//卡状态
                String findDetailByIdTradeOrderNumber=findDetailByIdResult.getJSONObject("result").getString("tradeOrderNumber");//所关联的签单订单号
                Assert.assertEquals(findDetailByIdTradeOrderNumber.equals(signBusinessNo),true,"创建已完成退单订单，未生成已退卡卡包");//断言的别意：生成的卡包所关联的签单订单号和上述创建签单订单的订单号一致不一致的校验
                Assert.assertEquals(findDetailByIdState,"REFUNDED","创建退单已完成订单，未生成已退卡卡包");

            }

           else {
                Assert.assertEquals(checkRefundableAmountResult, false, "无可退金额");
            }

        }

        }

}
