package com.xiaomai.cases.lunar.order;

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 com.xiaomai.utils.XMJSONPath;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import javax.annotation.Resource;

public class TestPurchaseByDeposit 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 info = new DataUserInfo();

    public JSONObject jsonObject;
    public String depositCardId;
    public String voucherId;
    @BeforeMethod
    @Override
    public void beforeTest(){
        setTestInfo(ApiModule.Lunar_Order,"API_purchaseCard", LoginAccount.GYM_MINIAPPC, Terminal.minApp,"xyy");
        super.beforeTest();
    }
    @DataProvider
    public  Object[][] dataProvider(){
        return new Object[][]{
                {"MEMBER_CARD","PURCHASE_MEMBER_CARD"},//会员卡
                {"EXPERIENCE_CARD","PURCHASE_EXPERIENCE_CARD"}//体验卡
        };
    }
    @Test(description = "C端下单时使用储值卡抵扣",dataProvider = "dataProvider")
    public void testPurchaseMemberCardByDeposit(String commodityCardType,String paymentScenario)throws InterruptedException{
        //获取会员信息
        String memberId = userTools.getMemberInfo().getString("memberId");
        Thread.sleep(1000);
        //获取第1张售卖中的卡
        if(commodityCardType=="MEMBER_CARD"){
            jsonObject = minCardTools.fetchOnSaleMemberCard("次卡-自动化");
        }else{
            jsonObject = minCardTools.fetchOnSaleMemberCard("自动化脚本创建体验卡",commodityCardType);
        }
        Thread.sleep(1000);
        //查询卡id跟价格
        String memberCardId = XMJSONPath.readPath(jsonObject,"$.result.records[0].id");
        String cardSnapshotId = XMJSONPath.readPath(orderCTools.findTenantCardDetailById(memberCardId,memberId),"$.result.latestSnapshotId");
        String price = XMJSONPath.readPath(orderCTools.findTenantCardDetailById(memberCardId,memberId),"$.result.price");
        //查询是否有可使用的储值卡，如果没有创建1张
        int num = XMJSONPath.getJSONArrayByReadPath(minCardTools.listUserUsableDepositCard(memberId,paymentScenario), "$.result.applicableList").size();
        if (num>1){
            for(int i=0; i<num-1; i++) {
                String leftBalance = XMJSONPath.readPath(minCardTools.listUserUsableDepositCard(memberId, paymentScenario), "$.result.applicableList[" + i + "].depositBenefit.leftBalance");
                //遍历储值卡的可用余额是否大于等于会员卡的价格
                if (Double.parseDouble(leftBalance) >= Double.parseDouble(price)) {
                    depositCardId = XMJSONPath.readPath(minCardTools.listUserUsableDepositCard(memberId, paymentScenario), "$.result.applicableList[" + i + "].id");
                    break;
                }else{
                    //切换B端校验
                    info.setTerminal(Terminal.B);
                    info.setLoginUser(LoginAccount.GYM_PROD);

                    //查询启用中的储值卡，获取储值卡id
                    String cardId = XMJSONPath.readPath(cardTools.fetchPageOfMemberCard("DEPOSIT_CARD",info), "$.result.records[0].id");
                    String latestSnapshotId = XMJSONPath.readPath(cardTools.fetchDetailById(cardId,info), "$.result.latestSnapshotId");
                    //购买1张储值卡
                    cardTools.signOrderDeposit(cardId,latestSnapshotId,memberId,"0.00","1000.00",info);
                    //获取C端第1张可使用的储值卡
                    depositCardId = XMJSONPath.readPath(minCardTools.listUserUsableDepositCard(memberId, paymentScenario), "$.result.applicableList[0].id");
                }
            }
            //查询要使用的储值卡消耗记录条数
            String depositBenefitId = XMJSONPath.readPath(minCardTools.findMemberCardDetailById(depositCardId),"$.result.depositBenefit.id");
            int total = Integer.parseInt(XMJSONPath.readPath(minCardTools.fetchPageOfConsumeRecord(depositCardId,depositBenefitId),"$.result.total"));

            //构建接口参数
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("activatePattern","FIRST_USED");
            jsonObject.put("cardId",memberCardId);
            jsonObject.put("cardSnapshotId",cardSnapshotId);
            jsonObject.put("memberId",memberId);
            jsonObject.put("memo","自动化使用储值卡抵扣");
            jsonObject.put("receivableAmount","0.00");
            jsonObject.put("studioId",xmAppApi.getLoginInfo().getStudioId());
            jsonObject.put("objectId", RandomStringUtil.randomString(16));
            jsonObject.put("depositCardId",depositCardId);//储值卡id
            jsonObject.put("depositAmount",price);
            jsonObject.put("commodityCardType",commodityCardType);
//        jsonObject.put("activityId",null);//优惠券id
//        jsonObject.put("activityAmount",null);//优惠券抵扣金额

            //调用请求
            xmAppApi.doRequest(RequestType.JSON,params,jsonObject.toString(),headers).assetsSuccess(true);
            voucherId = xmAppApi.getBodyInJSON().getJSONObject("result").getString("voucherId");//订单ID

            Thread.sleep(3000);
            //校验C端订单详情
            Assert.assertEquals(XMJSONPath.readPath(orderCTools.getDetail(voucherId),"$.result.state"),"PAID","创建签单订单成功,但订单状态不是已完成");
            Assert.assertEquals(XMJSONPath.readPath(orderCTools.getDetail(voucherId),"$.result.source"),"ONLINE_MALL","C端创建的签单订单,订单来源非会员创建");

            //检验储值卡的消耗记录新增1条
            JSONObject body = minCardTools.fetchPageOfConsumeRecord(depositCardId,depositBenefitId);
            Assert.assertTrue(Integer.parseInt(XMJSONPath.readPath(body,"$.result.total"))==total+1);
            Assert.assertEquals(XMJSONPath.readPath(body,"$.result.records[0].consumeType"),"DEPOSIT_SIGN_ORDER");//消耗类型：签单
            Assert.assertEquals(XMJSONPath.readPath(body,"$.result.records[0].changeOfGiveBalance"),"-"+price);//消耗赠送金额

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

            //作废订单
            orderTools.discard(voucherId,"其他","自动化作废订单",info);
        }

    }

}
