package com.xiaomai.cases.polar.training;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.basetest.BaseTestImpl;
import com.xiaomai.cases.polar.finance.order.OrderTools;
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.XMJSONPath;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

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

public class TestSignCampOrderByDeposit extends BaseTestImpl {

    @Resource(name = "trainingTools")
    TrainingTools trainingTools;
    @Resource(name = "tools")
    Tools tools;

    @Resource(name = "cardTools")
    CardTools cardTools;

    @Resource(name = "orderTools")
    OrderTools orderTools;
    String memberId = "";

    String signOrderDepositOrderId = "";

    String depositCardId;

    String depositBenefitId;

    String orderId;

    @BeforeClass
    @Override
    public void beforeTest() {
        setTestInfo(ApiModule.Polar_Training, "API_signOrderCamp", LoginAccount.GYM_PROD, Terminal.B, "yff");
        super.beforeTest();
    }


    @Test(description = "使用储值卡抵扣购买存量的训练营")
    public void testSignCampOrderByDeposit(){

        //注意：储值卡用的是存量的：存量储值卡充0赠1000   训练营用的是存量的：杭州自动化测试训练营A：999.99元

        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);
        }

        //购买储值卡
        //查询存量储值卡
        //查询启用中的储值卡，获取储值卡id
        JSONObject deposit = cardTools.tenantMemberCardCommonSearch("DEPOSIT_CARD", "存量储值卡充0赠1000");
        String cardId = deposit.getJSONArray("result").getJSONObject(0).getString("id");
        String latestSnapshotId = XMJSONPath.readPath(cardTools.fetchDetailById(cardId), "$.result.latestSnapshotId");

        //购买1张储值卡
        signOrderDepositOrderId = cardTools.signOrderDeposit(cardId,latestSnapshotId,memberId,"0.00","1000.00");//购买储值卡订单ID

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

        //获取第1张可使用的储值卡
        JSONObject depositCard = cardTools.listUserUsableDepositCardB(memberId, "APPLY_TRAINING_CAMP");

        depositCardId = depositCard.getJSONObject("result").getJSONArray("applicableList").getJSONObject(0).getString("id");
        depositBenefitId = depositCard.getJSONObject("result").getJSONArray("applicableList").getJSONObject(0).getJSONObject("depositBenefit").getString("id");
        BigDecimal leftBalance = new BigDecimal(depositCard.getJSONObject("result").getJSONArray("applicableList").getJSONObject(0).getJSONObject("depositBenefit").getString("leftBalance"));//储值卡可用金额


        // 获取存量训练营活动
        JSONObject fetchAppliableCampList = trainingTools.fetchAppliableCampList("杭州自动化测试训练营A");
        String id=fetchAppliableCampList.getJSONArray("result").getJSONObject(0).getString("id");
        BigDecimal price = new BigDecimal(fetchAppliableCampList.getJSONArray("result").getJSONObject(0).getString("price"));



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

        JSONObject campJSONObject=new JSONObject();
        campJSONObject.put("campId",id);
        body.put("camp",campJSONObject);
        body.put("objectId", RandomStringUtil.randomString(16));
        body.put("studioId", xmAppApi.getLoginInfo().getStudioId());
        body.put("memberId", memberId);
        body.put("receivableAmount", "0");
        body.put("operatorId",xmAppApi.getLoginInfo().getAdminId());

        JSONArray paymentWaysJSONArray=new JSONArray();
        body.put("paymentWays",paymentWaysJSONArray);

        body.put("depositCardId", depositCardId);
        body.put("depositCardName", "存量储值卡充0赠1000");
        body.put("depositAmount", price);
        body.put("brandId",xmAppApi.getLoginInfo().getBrandId());

        xmAppApi.doRequest(RequestType.JSON, params, body.toString(), headers).assetsSuccess(true);

        orderId = xmAppApi.getBodyInJSON().getString("result");

        // check 1:订单详情
        JSONArray voucherItems = orderTools.getDetail(orderId).getJSONObject("result").getJSONArray("voucherItems");
        String[] keys = new String[]{"skuId", "skuType"};
        String[] expect = new String[]{id, "TRAINING_CAMP"};
        for (int i = 0; i < keys.length; i++) {
            Assert.assertTrue(voucherItems.getJSONObject(0).getString(keys[i]).equals(expect[i]));
        }

        //check 2：已购:生效中的训练营列表增加数据
        JSONArray fetchUserCardListResult=orderTools.fetchUserCardList("TRAINING",memberId,"NORMAL").getJSONArray("result");
        String title=fetchUserCardListResult.getJSONObject(0).getString("title");

        Assert.assertEquals(fetchUserCardListResult.size()>0,true,"使用储值卡购买训练营成功后，已购训练营列表数据小于1");
        Assert.assertEquals(title,"杭州自动化测试训练营A","已购训练营名称和购买的训练营名称非同一个");


        //check 3：校验储值卡消耗列表增加签单类型的消耗记录，以及签单消耗记录的剩余金额=储值卡剩余金额-购买的训练营金额
        JSONObject consumeRecord = cardTools.fetchPageOfConsumeRecord(depositBenefitId,depositCardId);
        String consumeType = consumeRecord.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("consumeType");
        BigDecimal leftUsableGiveBalance = new BigDecimal(consumeRecord.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("leftGiveBalance"));//可用赠送金额--注意：校验这个只适用于购买为0，使用赠送金额购买训练营的情况，所以只检验了赠送金额

        Assert.assertEquals(consumeType, "DEPOSIT_SIGN_ORDER", "使用储值卡签单训练营，消耗记录非签单类型");
        Assert.assertEquals(leftUsableGiveBalance.equals(leftBalance.subtract(price.setScale(2, RoundingMode.HALF_UP))), true, "使用储值卡签单训练营，签单消耗记录的剩余金额非扣除购买训练营使用的储值卡金额后的剩余金额");

    }

    @Test(description = "作废使用储值卡购买的训练营订单数据，为了下次再购买", priority = 2)
    public void delOrderData() {
        orderTools.discard(orderId, "重复录入", "作废使用储值卡购买的训练营订单");
        try{
            Thread.sleep(3000);
        }catch (InterruptedException e){
            throw new RuntimeException(e);
        }

    }

    @Test(description = "作废购买储值卡订单数据", priority = 3)
    public void delsignOrderDepositOrderData() {
        orderTools.discard(signOrderDepositOrderId, "重复录入", "作废购买储值卡订单");
    }

}
