package com.xiaomai.cases.lunar.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.basetest.BaseTestImpl;
import com.xiaomai.cases.lunar.minMemberCard.MinCardTools;
import com.xiaomai.cases.lunar.user.UserTools;
import com.xiaomai.cases.polar.finance.order.OrderTools;
import com.xiaomai.cases.polar.memberCard.CardTools;
import com.xiaomai.client.DataUserInfo;
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 org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import javax.annotation.Resource;
import java.math.BigDecimal;

public class TestPurchaseCard extends BaseTestImpl {
    @Resource(name = "userTools")
    UserTools userTools;
    @Resource(name = "minCardTools")
    MinCardTools minCardTools;
    @Resource(name = "cardTools")
    CardTools cardTools;
    @Resource(name = "orderCTools")
    OrderCTools orderCTools;
    @Resource(name = "orderTools")
    OrderTools orderTools;
    DataUserInfo dataUserInfo = new DataUserInfo();

    public String memberId;
    public String cardId;

    @BeforeMethod
    @Override
    public void beforeTest(){
        setTestInfo(ApiModule.Lunar_Order,"API_purchaseCard", LoginAccount.GYM_MINIAPPC, Terminal.minApp,"yff");
        super.beforeTest();
    }

    @Test(description = "C端购买订单")
    public void testPurchaseCard(){

        //获取会员信息
        memberId = userTools.getMemberInfo().getString("memberId");

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

        //获取会员卡
        cardId = minCardTools.fetchOnSaleMemberCard("C端0元会员卡自动化").getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");

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

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("activatePattern","PURCHASE");
        jsonObject.put("cardId",cardId);
        jsonObject.put("cardSnapshotId",cardId);
        jsonObject.put("memberId",memberId);
        jsonObject.put("memo", RandomStringUtil.randomString(6));
        jsonObject.put("receivableAmount",0);
        jsonObject.put("studioId",dataApi.getLoginInfo().getStudioId());
        jsonObject.put("objectId", RandomStringUtil.randomString(16));

        xmAppApi.doRequest(RequestType.JSON,params,jsonObject.toString(),headers).assetsSuccess(true);
        JSONObject response=xmAppApi.getBodyInJSON();
        String success=response.getString("success");
        String signId=response.getJSONObject("result").getString("voucherId");//订单ID
        Assert.assertEquals(success,"true","C端创建0元签单失败");

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


        //校验C端订单详情
        JSONObject getDetail=orderCTools.getDetail(signId);
        String getDetailId=getDetail.getJSONObject("result").getString("id");
        String getDetailBusinessNo=getDetail.getJSONObject("result").getString("businessNo");
        String getDetailState=getDetail.getJSONObject("result").getString("state");
        String getDetailSource=getDetail.getJSONObject("result").getString("source");
        String getDetailSuccess=getDetail.getString("success");
        Assert.assertEquals(getDetailSuccess,"true","获取创建的签单订单详情失败");
        Assert.assertEquals(getDetailId.equals(signId),true,"获取签单订单详情和创建的签单订单ID不一致");
        Assert.assertEquals(getDetailState,"PAID","创建签单订单成功,但订单状态不是已完成");
        Assert.assertEquals(getDetailSource,"ONLINE_MALL","C端创建的签单订单,订单来源非会员创建");


        //校验C端订单列表
        JSONObject pageOrder=orderCTools.pageOrder(memberId);
        int pageOrderPages=Integer.parseInt(pageOrder.getJSONObject("result").getString("pages"));
        int pageOrderTotal=Integer.parseInt(pageOrder.getJSONObject("result").getString("total"));


        for(int k=0; k == pageOrderPages+1; k++){
            int n =k==pageOrderPages ? (pageOrderTotal%10==0 ? 10 : pageOrderTotal%10) : 10;
            JSONArray records=pageOrder.getJSONObject("result").getJSONArray("records");
            boolean flag=true;
            for(int i=0; i<n; i++){
                String pageOrderId=records.getJSONObject(i).getString("id");
                if(pageOrderId.equals(signId)){
                    flag = true;
                    break;
                }
            }
            Assert.assertEquals(true,flag,"在订单列表中未查询到创建的签单订单");
        }


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

        //切换B端校验
        dataUserInfo.setTerminal(Terminal.B);
        dataUserInfo.setLoginUser(LoginAccount.GYM_PROD);

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

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

        //校验获取B端签单订单详情
        JSONObject getDetailBResult=orderTools.getDetail(signId,dataUserInfo);
        String getDetailBId = getDetailBResult.getJSONObject("result").getString("id");
        String getDetailBBusinessNo = getDetailBResult.getJSONObject("result").getString("businessNo");
        String getDetailBSource=getDetailBResult.getJSONObject("result").getString("source");
        String getDetailBmemberId=getDetailBResult.getJSONObject("result").getJSONObject("receiver").getString("id");//会员id
        BigDecimal quantity= new BigDecimal(getDetailBResult.getJSONObject("result").getJSONArray("voucherItems").getJSONObject(0).getJSONObject("purchaseCardSkuAttr").getJSONArray("skuItemAttrs").getJSONObject(0).getString("quantity"));
        Assert.assertEquals(getDetailBId.equals(signId),true,"C端创建的签单订单在B端和C端展示的订单id不一致");
        Assert.assertEquals(getDetailBBusinessNo.equals(getDetailBusinessNo),true,"C端创建的签单订单在B端和C端展示的订单号不一致");
        Assert.assertEquals(getDetailBSource,"ONLINE_MALL","C端创建的签单订单,B端展示订单来源非会员创建");

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

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

        //获取会员下的购买的会员卡
        JSONObject fetchUserCardListResult=orderTools.fetchUserCardList("MEMBER",getDetailBmemberId,"NORMAL",dataUserInfo);
        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(getDetailBBusinessNo),true,"创建C端已完成订单，未生成卡包");//断言的别意：生成的卡包的订单号和上述创建订单的订单号一致不一致的校验
        Assert.assertEquals(findDetailByIdState,"NORMAL","创建即时生效的已完成订单，未生成生效中卡包");

        //B端退C端订单

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

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


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

        if(checkRefundableAmountResult == true) {

            //退单-会员卡
            JSONObject refundOrderResult = orderTools.refundOrder(0, listUserRefundableId, quantity, 0, "MEMBER_CARD",
                    getDetailBmemberId, 0, 0, "1",0,new BigDecimal(0),new BigDecimal(0),dataUserInfo);
            String refundOrderSuccess = refundOrderResult.getString("success");
            String refundOrderGetDetailId = refundOrderResult.getString("result");
            Assert.assertEquals(refundOrderSuccess, "true", "创建的C端订单退单失败");

        }

    }

}
