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.RequestType;
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.DataProvider;
import org.testng.annotations.Test;

import java.math.BigDecimal;


public class TestSignOrder 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_signOrder")
                .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 testSignOrder(){

        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");
            String state=getDetailResult.getJSONObject("result").getString("state");
            Assert.assertEquals(id.equals(getDetailId),true,"获取创建的签单订单详情失败");
            Assert.assertEquals(state,"PAID","获取创建的签单订单未完成");


            //校验获取订单支付记录
            JSONObject listByVoucherIdResult=orderTools.listByVoucherId(getDetailId);
            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(getDetailId),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,"INCOME", "SIGN",
                    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","创建的签单订单的收支明细状态未是已完成");

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

            //校验获取会员下的购买的会员卡是否生成卡包

            //获取会员下的购买的会员卡
            JSONObject fetchUserCardListResult=orderTools.fetchUserCardList("MEMBER",memberId,"NORMAL");
            String fetchUserCardListId=fetchUserCardListResult.getJSONArray("result").getJSONObject(0).getString("id");//memberCardId

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


        }

        else {
            Assert.assertEquals(limitResult, false, "无法购买，已达到最多购买N张的上限");


        }

    }


    @DataProvider
    public Object[][] dataProvider(){
        return new Object[][]{
                {true,"发放商品权益"},
                {false,"不发放商品权益"}
        };
    }

    @Test(description = "部分支付不发放商品权益")
    public void testSignOrder2(boolean directReceive,String memo) {
        // 查询存量的学员没有则创建学员
        if (tools.commonSearch("刘青","NORMAL").getJSONArray("result").size()>0){
            memberId = tools.commonSearch("刘青","NORMAL").getJSONArray("result").getJSONObject(0).getString("id");
        }else if (tools.commonSearch("刘青","HISTORY").getJSONArray("result").size()>0){
            memberId = tools.commonSearch("刘青","HISTORY").getJSONArray("result").getJSONObject(0).getString("id");
        }else if (tools.commonSearch("刘青","POTENTIAL").getJSONArray("result").size()>0){
            memberId = tools.commonSearch("刘青","POTENTIAL").getJSONArray("result").getJSONObject(0).getString("id");
        }else{
            memberId = tools.create("刘青", RandomStringUtil.randomMobile("214")).getString("result");
        }


        // 查询存量的卡
        JSONObject fetchPageOfMemberCard = orderTools.fetchPageOfMemberCard("","MEMBER_CARD").getJSONObject("result");
        int total = Integer.parseInt(fetchPageOfMemberCard.getString("total"));
        String cardId = "";
        if (total == 0) {
            cardId = cardTools.memberCardCreate("创建先享后付订单"+ TimeUtils.getCurrentTime()).getString("result");
        }
        cardId = fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("id");
        BigDecimal quantity =  new BigDecimal(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getJSONArray("benefitList").getJSONObject(0).getString("balance"));
        float price = Float.parseFloat(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("price"));
        int validPeriod = Integer.parseInt(fetchPageOfMemberCard.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);
        }



        JSONObject jsonObject = new JSONObject();
        jsonObject.put("salesmanId",xmAppApi.getLoginInfo().getAdminId());
        jsonObject.put("operationTime", TimeUtils.getCurrentTime());

        JSONObject card = new JSONObject();
        card.put("cardId",cardId);
        card.put("cardSnapshotId",latestSnapshotId);

        JSONObject cardChange = new JSONObject();
        cardChange.put("quantity",quantity);
        cardChange.put("price",price);
        cardChange.put("validPeriod",validPeriod);
        cardChange.put("latestSnapshotId",latestSnapshotId);

        card.put("cardChange",cardChange);
        card.put("deductionAmount",0);//优惠金额（元）
        card.put("activatePattern","PURCHASE");
        card.put("commodityCardType","MEMBER_CARD");
        jsonObject.put("card",card);


        jsonObject.put("objectId", RandomStringUtil.randomString(20));
        jsonObject.put("studioId",xmAppApi.getLoginInfo().getStudioId());
        jsonObject.put("memberId",memberId);
        jsonObject.put("receivableAmount",price);//应收金额
        jsonObject.put("directReceive",directReceive); //是否发放权益
        jsonObject.put("operatorId",xmAppApi.getLoginInfo().getAdminId());


        JSONArray paymentWays = new JSONArray();
        jsonObject.put("paymentWays",paymentWays);
        jsonObject.put("brandId",xmAppApi.getLoginInfo().getBrandId());

        xmAppApi.doRequest(RequestType.JSON, params, jsonObject.toJSONString(), headers).assetsSuccess(true);

        JSONObject bodyInJSON = xmAppApi.getBodyInJSON();
        String getDetailId = bodyInJSON.getString("result");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        JSONObject getDetailResult = orderTools.getDetail(getDetailId);
        String businessNo = getDetailResult.getJSONObject("result").getString("businessNo");
        String state = getDetailResult.getJSONObject("result").getString("state");
        if (directReceive){
            Assert.assertEquals(state,"DELINQUENT","选择先使用后补交，订单状态为待补交状态");
        }else{
            Assert.assertEquals(state,"WAITING","选择全额支付后才发放商品，订单状态为待支付状态");
        }


        if (directReceive){
            //校验获取会员下的购买的会员卡是否生成卡包
            //获取会员下的购买的会员卡
            JSONObject fetchUserCardListResult=orderTools.fetchUserCardList("MEMBER",memberId,"NORMAL");
            String fetchUserCardListId=fetchUserCardListResult.getJSONArray("result").getJSONObject(0).getString("id");//memberCardId

            //获取售卖详情
            JSONObject findDetailByIdResult=cardTools.memberCardFindDetailById(fetchUserCardListId);
            String findDetailByIdTradeOrderNumber = findDetailByIdResult.getJSONObject("result").getString("tradeOrderNumber");//订单号
            Assert.assertEquals(findDetailByIdTradeOrderNumber.equals(businessNo),true,"已发放商品，未生成卡包");//断言的别意：生成的卡包的订单号和上述创建订单的订单号一致不一致的校验
        }


        orderTools.discard(getDetailId, "重复录入","作废订单");

    }

}
