package com.xiaomai.cases.polar.experienceCard;

import com.alibaba.fastjson.JSONObject;
import com.xiaomai.cases.polar.admin.AdminTools;
import com.xiaomai.cases.polar.finance.order.OrderTools;
import com.xiaomai.cases.polar.experienceCard.ExperienceCardTools;

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

import java.math.BigDecimal;

/**
 * @Author zxy
 * @Description
 * @Date 2024/8/31 14:40
 */
public class TestActiveExperienceCard extends XMBaseTest {
    ExperienceCardTools experienceCardTools = new ExperienceCardTools();
    CardTools cardTools = new CardTools();
    OrderTools orderTools = new OrderTools();
    AdminTools adminTools=new AdminTools();
    String memberCardId;
    String title;
    BigDecimal quantity; //可用次数
    float price; //价格
    int validPeriod; //有效期
    String latestSnapshotId;//最近的快照ID
    BigDecimal entryQuantity;//入场权益
    float entryPrice;//入场权益价格
    @BeforeMethod
    public void beforeTest(){

        xmAppApi.setApiModule(ApiModule.Polar_Card)
                .setApiName("API_activateMemberCard")
                .setLoginUser(LoginAccount.GYM_PROD)
                .setTerminal(Terminal.B);

        dal.setCase_owner("zyx")
                .setCase_name(Thread.currentThread().getStackTrace()[1].getFileName().split("\\.")[0]);
        super.beforeTest();
    }

    @Test(description = "操作体验卡开卡")
    public void testActivateMemberCard() throws InterruptedException {
        //先检查下列表有没有数据，有数据才会执行下面的点代码,无数据则新建一个
        cardTools.doMemberCardcommonSearch("课程次数入场次数","EXPERIENCE_CARD");
        int listDatas = XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").size();
        if (listDatas > 0) {
            memberCardId = XMJSONPath.readPath(dataApi.getApi_response(), "$.result[0].id");
        } else {
            for (int i = 0; i < 3; i++) {
                title = "课程次数入场次数" + RandomStringUtil.randomString(3) + "-自动化创建";
                //check是否存在同名的体验卡，不存在则新建
                Boolean duplicate = experienceCardTools.checkTitleDuplicate(title, "EXPERIENCE_CARD").getBoolean("result");
                if (duplicate == false) {
                    Thread.sleep(3000);
                    memberCardId = experienceCardTools.create("EXPERIENCE_CARD", title, "全部", "YES", "课程次数入场次数",false).getString("result");
                    break;
                }
            }
        }
        //获取体验卡详情
        cardTools.fetchDetailById(memberCardId);
        quantity= new BigDecimal(XMJSONPath.readPath(dataApi.getApi_response(),"$.result.benefitList[0].balance"));
        entryQuantity = new BigDecimal(XMJSONPath.readPath(dataApi.getApi_response(),"$.result.benefitList[1].balance"));
        price=Float.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.benefitList[0].price"));
        entryPrice = Float.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.benefitList[1].price"));
        validPeriod=Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.validPeriod"));
        latestSnapshotId=XMJSONPath.readPath(dataApi.getApi_response(), "$.result.latestSnapshotId");

        //给会员签单-购买体验卡
        orderTools.signOrder1(memberCardId,latestSnapshotId,quantity,entryQuantity,price,entryPrice,validPeriod,latestSnapshotId,0,"FIRST_USED","EXPERIENCE_CARD", "1805435813468483586",price+entryPrice,price+entryPrice,"1");

        //获取该会员名下的体验卡列表
        cardTools.getUserMemberCardList("1805435813468483586","EXPERIENCE");
        String memberAccountCardId = "";
        memberAccountCardId = XMJSONPath.readPath(dataApi.getApi_response(), "$.result[0].id");

        //操作开卡
        JSONObject body = new JSONObject();
        body.put("operatorId", xmAppApi.getLoginInfo().getAdminId());
        body.put("studioId", xmAppApi.getLoginInfo().getStudioId());
        body.put("brandId", xmAppApi.getLoginInfo().getBrandId());
        body.put("memberCardId", memberAccountCardId);
        xmAppApi.doRequest(RequestType.JSON, params, body.toString(), headers).assetsSuccess(true);

        //查看售卖记录详情
        cardTools.memberCardFindDetailById(memberAccountCardId);
        Assert.assertEquals(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.state"), "NORMAL", "开卡后卡状态没变更为生效状态");
        String benefitId = XMJSONPath.readPath(dataApi.getApi_response(), "$.result.courseBenefit.id");

        //check生成一条变动记录
        cardTools.getMemberCardAccountOperateRecord(memberAccountCardId);
        Assert.assertTrue(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.records[0].operateType").equals("ACTIVATE"), "手动开卡后生成的变动记录第一条备注不是手动开卡ACTIVATE");
        Assert.assertTrue(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.records[0].remark").equals("手动开卡"), "手动开卡后生成的变动记录第一条备注不是手动开卡");

        //查看消耗记录
        cardTools.fetchPageOfConsumeRecord(benefitId, memberAccountCardId);
        int totalBefore = XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").size();
        Assert.assertTrue(totalBefore == 1, "会员购卡后没生成购买的消耗记录");
        Assert.assertTrue(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.records[0].consumeType").equals("PURCHASE"), "会员购卡后生成消耗记录不是购买");


        String ownerName=adminTools.getStudioAdmin(xmAppApi.getLoginInfo().getAdminId()).getJSONObject("result").getString("nickName");

        //操作退卡
        orderTools.refundOrder1(xmAppApi.getLoginInfo().getAdminId(),ownerName,2, 1,memberAccountCardId, quantity, entryQuantity,price, entryPrice,"EXPERIENCE_CARD", "1805435813468483586", "1",0,new BigDecimal(price+entryPrice),new BigDecimal(price+entryPrice));

        String refundOrderId = XMJSONPath.readPath(dataApi.getApi_response(), "$.result");

        //退卡成功后check 售卖记录详情状态：已退卡
        cardTools.memberCardFindDetailById(memberAccountCardId);
        Assert.assertEquals(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.state"), "REFUNDED", "退卡后卡卡账户状态没变更为已退卡状态");
        //退卡后check是否生成一条退卡的消耗记录
        cardTools.fetchPageOfConsumeRecord(benefitId, memberAccountCardId);
        int totalAfter = XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").size();
        Assert.assertTrue(totalAfter == 2, "会员退卡后没生成购买的消耗记录");
        Assert.assertTrue(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.records[0].consumeType").equals("REFUND"), "会员退卡后生成消耗记录不是退卡");

    }

}
