package com.xiaomai.cases.polar.reserve.personal;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.basetest.BaseTestImpl;
import com.xiaomai.cases.polar.clue.MemberTools;
import com.xiaomai.cases.polar.course.CourseTools;
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.cases.polar.reserve.ReserveTools;
import com.xiaomai.cases.polar.schedule.group.GroupScheduleTools;
import com.xiaomai.cases.polar.setting.courseCategory.CourseCategoryTools;
import com.xiaomai.enums.ApiModule;
import com.xiaomai.enums.LoginAccount;
import com.xiaomai.enums.Terminal;
import com.xiaomai.utils.CommUtil;
import com.xiaomai.utils.RandomStringUtil;
import com.xiaomai.utils.TimeUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Random;

/**
 * @BelongsProject: xm-sportstest
 * @BelongsPackage: com.xiaomai.cases.polar.reserve.personal
 * @Author: xuyamei
 * @CreateTime: 2024-07-26  16:25
 * @Description: 一对一和一对多私教课预约
 * @Version: 1.0
 */
public class TestReservePerson extends BaseTestImpl {

    @Resource(name = "courseCategoryTools")
    CourseCategoryTools courseCategoryTools;
    @Resource(name = "courseTools")
    CourseTools courseTools;

    @Resource(name = "reserveTools")
    ReserveTools reserveTools;

    @Resource(name = "groupScheduleTools")
    GroupScheduleTools groupScheduleTools;


    MemberTools memberTools = new MemberTools();

    OrderTools orderTools = new OrderTools();
    CardTools cardTools = new CardTools();

    Tools tools = new Tools();

    String todayStartTimeTamp = CommUtil.oneKeyGetAddDay(0);


    //获取今天结束日期的时间戳
    Long todayEndDateTimeTamp = TimeUtils.getTodayEndTime();
    private String benefitId;
    private Long timestamp;
    private String memberId;
    private String scheduleId;
    private String courseId;
    private String coachedId;
    private String memberCardId;
    private String reserveId;
    JSONArray member2 = new JSONArray();
    JSONArray member1 = new JSONArray();

    @BeforeClass
    @Override
    public void beforeTest() {
        setTestInfo(ApiModule.Polar_Reserve, "API_addPersonalReserve", LoginAccount.GYM_PROD, Terminal.B, "xym");
        super.beforeTest();
    }


    @Test
    public void testReservePerson(){
        // 第一步：查询存量的约课课程
        // 查询存量的课程分类
        String categoryId = courseCategoryTools.getCourseCategoryPage("瑜伽");
        courseId = courseTools.getPersonalOrGroupCourseId("PERSONAL", "普拉提一对一私教课程", categoryId, "STUDIO", "ONE_TO_ONE", 1, 1).getString(0);
        String courseName = courseTools.getPersonalOrGroupCourseId("PERSONAL", "普拉提一对一私教课程", categoryId, "STUDIO", "ONE_TO_ONE", 1, 1).getString(1);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 第二步：查询存量的学员，如果没有则新建
        createMember("私教约课学员佳佳",courseId);

        // 第三步：查询存量的私教教练，并将教练添加到课程中
        // 获取到员工
        // 获取教练列表
        JSONObject pageStudioPersonalCoach = reserveTools.pageStudioPersonalCoach("");
        int total = pageStudioPersonalCoach.getInteger("total");
        Random rand = new Random();
        // 随机取1个教练
        coachedId = pageStudioPersonalCoach.getJSONArray("records").getJSONObject(rand.nextInt(total>10?10:total)).getString("id");
        // 编辑私教课程教练添加到课程中
        courseTools.editPersonalCourse(categoryId,courseId,courseName,10,coachedId,"1");

        // 第四步：创建私教特殊可约时间
        JSONObject specialTimeInfoRequest = new JSONObject();
        // 可约时间类型
        specialTimeInfoRequest.put("dutyType", "ON_DUTY");
        // 设置特定日期
        JSONArray selectedDates = new JSONArray();
        selectedDates.add(TimeUtils.getTodayTime());
        specialTimeInfoRequest.put("selectedDates", selectedDates);
        // 如果是可约时间非全天休息，则传可约时间段
        // 时间段 00:00 ~ 23:59
        JSONArray timePeriodInfos = new JSONArray();
        JSONObject timeInfo = new JSONObject();
        timeInfo.put("minuteOffset", 0);
        timeInfo.put("spanMinutes", 1380);
        timePeriodInfos.add(timeInfo);
        specialTimeInfoRequest.put("timePeriodInfos", timePeriodInfos);
        // 设置特殊可约时间
        reserveTools.createSpecialDate(coachedId,"ON_DUTY",specialTimeInfoRequest);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 第五步：获取老师第一条可约时间
        JSONArray personalCoachTime = reserveTools.getPersonalTimeBlocks(coachedId,courseId,TimeUtils.getTodayTime());

        // 获取当前日期的Calendar实例
        Calendar calendar = Calendar.getInstance();
        // 获取第一条的步长 转换成时间戳
        int minuteOffset = personalCoachTime.getJSONObject(0).getIntValue("minuteOffset")/60;
        calendar.set(Calendar.HOUR_OF_DAY, minuteOffset);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 将Calendar对象转换为时间戳
        timestamp = calendar.getTimeInMillis();

        reserveId = reserveTools.addPersonalReserve("",courseId,coachedId,memberId,benefitId,10,1,"",timestamp,true);

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


        // 从课表查询scheduleId
        JSONArray personalScheduleTable = reserveTools.getPersonalScheduleTable(timestamp, TimeUtils.getTodayEndTime(), courseId);
        for (int i = 0; i < personalScheduleTable.size(); i++) {
            for (int j = 0; j < personalScheduleTable.getJSONObject(i).getJSONArray("reserveIds").size(); j++){
                if (personalScheduleTable.getJSONObject(i).getString("startTime").equals(String.valueOf(timestamp)) && personalScheduleTable.getJSONObject(i).getJSONArray("reserveIds").getString(j).equals(reserveId)) {
                    scheduleId = personalScheduleTable.getJSONObject(i).getString("scheduleId");
                    break;
                }
            }

        }

        // check 1：课次学员是否包含该会员
        JSONObject getScheduleItemDetail = groupScheduleTools.getScheduleItemDetail(scheduleId);
        JSONArray reserveIds = getScheduleItemDetail.getJSONArray("reserveIds");
        boolean success = false;
        for (int i = 0; i < reserveIds.size(); i++){
            if(reserveIds.getString(i).equals(reserveId)){
                success = true;
            }
        }
        Assert.assertTrue(success,"约课后课次详情学员不在课次中");

        // check 2: 预约记录是否包含该预约
        // check 2.1 学员详情预约记录
        JSONArray getPageByMember = reserveTools.getPageByMember(courseId,"SUCCESS","",coachedId, timestamp,todayEndDateTimeTamp,memberId,"PERSONAL");
        String[] result = new String[] {"id","benefitId","reserveMemberNum","courseId","courseType","scheduleStartTime","reserveState","scheduleId"};
        String[] resultData = new String[] {reserveId,benefitId,"1",courseId,"PERSONAL",timestamp+"","SUCCESS",scheduleId};
        success = false;
        for(int i =0;i<getPageByMember.size();i++){
            if (getPageByMember.getJSONObject(i).getString("id").equals(reserveId)){
                success = true;
                for(int j = 0;j<result.length;j++){
                    Assert.assertEquals(getPageByMember.getJSONObject(i).getString(result[j]),resultData[j],"约课产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
                }
            }
        }
        Assert.assertTrue(success,"约课后在会员详情页面未查询到相关信息");
        // check 2.2 预约记录列表
        JSONArray getPageByStudio = reserveTools.getPageByStudio(courseId,"SUCCESS","",coachedId,timestamp,TimeUtils.getTodayEndTime(),memberId,"PERSONAL","");
        success = false;
        for(int i =0;i<getPageByStudio.size();i++){
            if (getPageByStudio.getJSONObject(i).getString("id").equals(reserveId)){
                success = true;
                for(int j = 0;j<result.length;j++){
                    Assert.assertEquals(getPageByStudio.getJSONObject(i).getString(result[j]),resultData[j],"约课产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
                }
                Assert.assertEquals(getPageByStudio.getJSONObject(i).getString("memberId"),memberId,"查询的约课数据不是同一个会员");
            }
        }
        Assert.assertTrue(success,"约课后在约课记录没有查询到相关信息");
        // check 2.3 预约记录详情
        JSONObject getDetailById = reserveTools.getDetailById(reserveId);
        for(int j = 0;j<result.length;j++){
            Assert.assertEquals(getDetailById.getString(result[j]),resultData[j],"约课产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
        }
        Assert.assertEquals(getDetailById.getString("memberId"),memberId,"查询的约课数据不是同一个会员");

        // check 3： 会员卡消耗记录中包含该记录锁定
        JSONArray consumeRecord = cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId).getJSONObject("result").getJSONArray("records");
        String[] result2 = new String[] {"resourceId","consumeType","changeOfUsablePurchaseBalance"};
        String[] respect = new String[] {reserveId,"RESERVE","-1.00"};
        String[] message = new String[] {"会员卡消耗记录中记录的资源id与实际约课记录id不符合","会员卡消耗记录中记录的资源id与实际约课记录类型不符合","会员卡消耗记录中记录的资源id与实际约课记录余额不符合"};
        for (int i = 0; i < result2.length; i++){
            Assert.assertEquals(consumeRecord.getJSONObject(0).getString(result2[i]),respect[i],message[i]);
        }

    }



    @Test(description = "取消一对一私教课，课次删除",priority = 1)
    public void testReservePerson_cancel() {
        reserveTools.cancelMemberReserve(reserveId,true);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // check 1：课次已删除,课表没有该条数据
        JSONArray personalScheduleTable = reserveTools.getPersonalScheduleTable(timestamp,TimeUtils.getTodayEndTime(),courseId);
        boolean flag = true;
        if (personalScheduleTable != null){
            for (int i = 0; i < personalScheduleTable.size(); i++){
                if (personalScheduleTable.getJSONObject(i).getString("scheduleId").equals(scheduleId)){
                    scheduleId = personalScheduleTable.getJSONObject(i).getString("scheduleId");
                    flag = false;
                    break;
                }
            }
        }
        Assert.assertTrue(flag,"取消约课后课次未删除");


        // check 2：会员详情 - 预约记录已取消
        JSONArray getPageByMember = reserveTools.getPageByMember(courseId,"RESERVE_CANCEL","","", timestamp,TimeUtils.getTodayEndTime(),memberId,"PERSONAL");
        for(int i =0;i<getPageByMember.size();i++){
            if (getPageByMember.getJSONObject(i).getString("id").equals(reserveId)){
                Assert.assertEquals(getPageByMember.getJSONObject(i).getString("reserveState"),"RESERVE_CANCEL","取消约课状态不是已取消");
            }
        }

        // check 3：预约记录列表中已取消
        JSONArray getPageByStudio = reserveTools.getPageByStudio(courseId,"RESERVE_CANCEL","","",timestamp,TimeUtils.getTodayEndTime(),memberId,"PERSONAL","");;
        for(int i =0;i<getPageByStudio.size();i++){
            if (getPageByStudio.getJSONObject(i).getString("id").equals(reserveId)){
                Assert.assertEquals(getPageByStudio.getJSONObject(i).getString("reserveState"),"RESERVE_CANCEL","取消约课状态不是已取消");

            }
        }

        // check 4： 会员卡消耗记录中包含该记录锁定的次数释放
        JSONArray consumeRecord = cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId).getJSONObject("result").getJSONArray("records");
        String[] result2 = new String[] {"resourceId","consumeType","changeOfUsablePurchaseBalance"};
        String[] respect = new String[] {reserveId,"CANCEL_RESERVE","1.00"};
        String[] message1 = new String[] {"会员卡消耗记录中记录的资源id与实际约课记录id不符合","会员卡消耗记录中记录的资源id与实际约课记录类型不符合","会员卡消耗记录中记录的资源id与实际约课记录余额不符合"};
        for (int i = 0; i < result2.length; i++){
            Assert.assertEquals(consumeRecord.getJSONObject(0).getString(result2[i]),respect[i],message1[i]);
        }

    }

    @Test(description = "预约1VN课次，其他学员可再次进行预约",priority = 2)
    public void testReservePerson_1VN() {
        // 第一步：查询存量的约课课程
        // 查询存量的课程分类
        String categoryId = courseCategoryTools.getCourseCategoryPage("瑜伽");
        courseId = courseTools.getPersonalOrGroupCourseId("PERSONAL", "普拉提器械1V3私教课程", categoryId, "STUDIO", "ONE_TO_MANY", 3, 1).getString(0);
        String courseName = courseTools.getPersonalOrGroupCourseId("PERSONAL", "普拉提器械1V3私教课程", categoryId, "STUDIO", "ONE_TO_MANY", 3, 1).getString(1);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 第二步：查询存量的学员，如果没有则新建
        member1 = createMember("1V3私教约课学员李萌",courseId);

        // 第三步：查询存量的私教教练，并将教练添加到课程中
        // 获取到员工
        // 获取教练列表
        JSONObject pageStudioPersonalCoach = reserveTools.pageStudioPersonalCoach("");
        int total = pageStudioPersonalCoach.getInteger("total");
        Random rand = new Random();
        // 随机取1个教练
        coachedId = pageStudioPersonalCoach.getJSONArray("records").getJSONObject(rand.nextInt(total>10?10:total)).getString("id");
        // 编辑私教课程教练添加到课程中
        courseTools.editPersonalCourse(categoryId,courseId,courseName,10,coachedId,"3");

        // 第四步：创建私教特殊可约时间
        JSONObject specialTimeInfoRequest = new JSONObject();
        // 可约时间类型
        specialTimeInfoRequest.put("dutyType", "ON_DUTY");
        // 设置特定日期
        JSONArray selectedDates = new JSONArray();
        selectedDates.add(TimeUtils.getTodayTime());
        specialTimeInfoRequest.put("selectedDates", selectedDates);
        // 如果是可约时间非全天休息，则传可约时间段
        // 时间段 00:00 ~ 23:59
        JSONArray timePeriodInfos = new JSONArray();
        JSONObject timeInfo = new JSONObject();
        timeInfo.put("minuteOffset", 60);
        timeInfo.put("spanMinutes", 1380);
        timePeriodInfos.add(timeInfo);
        specialTimeInfoRequest.put("timePeriodInfos", timePeriodInfos);
        // 设置特殊可约时间
        reserveTools.createSpecialDate(coachedId,"ON_DUTY",specialTimeInfoRequest);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 第五步：获取老师第一条可约时间
        JSONArray personalCoachTime = reserveTools.getPersonalTimeBlocks(coachedId,courseId,TimeUtils.getTodayTime());

        // 获取当前日期的Calendar实例
        Calendar calendar = Calendar.getInstance();
        // 获取第一条的步长 转换成时间戳
        int minuteOffset = personalCoachTime.getJSONObject(0).getIntValue("minuteOffset")/60;
        calendar.set(Calendar.HOUR_OF_DAY, minuteOffset);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 将Calendar对象转换为时间戳
        timestamp = calendar.getTimeInMillis();

        // 李萌预约生成课次
        reserveId = reserveTools.addPersonalReserve("",courseId,coachedId,memberId,benefitId,10,1,"",timestamp,true);
        member1.add(reserveId);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // 从课表查询scheduleId
        JSONArray personalScheduleTable = reserveTools.getPersonalScheduleTable(timestamp, TimeUtils.getTodayEndTime(), courseId);
        for (int i = 0; i < personalScheduleTable.size(); i++) {
            for (int j = 0; j < personalScheduleTable.getJSONObject(i).getJSONArray("reserveIds").size(); j++){
                if (personalScheduleTable.getJSONObject(i).getString("startTime").equals(String.valueOf(timestamp)) && personalScheduleTable.getJSONObject(i).getJSONArray("reserveIds").getString(j).equals(reserveId)) {
                    scheduleId = personalScheduleTable.getJSONObject(i).getString("scheduleId");
                    break;
                }
            }

        }

        // check 1：课次学员是否包含该会员
        JSONObject getScheduleItemDetail = groupScheduleTools.getScheduleItemDetail(scheduleId);
        JSONArray reserveIds = getScheduleItemDetail.getJSONArray("reserveIds");
        boolean success = false;
        for (int i = 0; i < reserveIds.size(); i++){
            if(reserveIds.getString(i).equals(member1.getString(3))){
                success = true;
            }
        }
        Assert.assertTrue(success,"约课后课次详情学员不在课次中");

        // 学员2进行预约
        member2 = createMember("1V3私教约课学员2程晨",courseId);
        reserveId = reserveTools.addPersonalReserve("",courseId,coachedId,member2.getString(0),member2.getString(1),10,1,scheduleId,timestamp,true);
        member2.add(reserveId);

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


        // check 1：课次学员是否包含该会员
        getScheduleItemDetail = groupScheduleTools.getScheduleItemDetail(scheduleId);
        reserveIds = getScheduleItemDetail.getJSONArray("reserveIds");
        success = false;
        for (int i = 0; i < reserveIds.size(); i++){
            if(reserveIds.getString(i).equals(member2.getString(3))){
                success = true;
            }
        }
        Assert.assertTrue(success,"约课后课次详情学员不在课次中");

        // check 2: 预约记录是否包含该预约
        // check 2.1 学员详情预约记录
        JSONArray getPageByMember = reserveTools.getPageByMember(courseId,"SUCCESS","",coachedId, timestamp,todayEndDateTimeTamp,memberId,"PERSONAL");
        String[] result = new String[] {"id","benefitId","reserveMemberNum","courseId","courseType","scheduleStartTime","reserveState","scheduleId"};
        String[] resultData = new String[] {member2.getString(3),member2.getString(1),"1",courseId,"PERSONAL",timestamp+"","SUCCESS",scheduleId};
        success = false;
        for(int i =0;i<getPageByMember.size();i++){
            if (getPageByMember.getJSONObject(i).getString("id").equals(member2.getString(3))){
                success = true;
                for(int j = 0;j<result.length;j++){
                    Assert.assertEquals(getPageByMember.getJSONObject(i).getString(result[j]),resultData[j],"约课产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
                }
            }
        }
        Assert.assertTrue(success,"约课后在会员详情页面未查询到相关信息");
        // check 2.2 预约记录列表
        JSONArray getPageByStudio = reserveTools.getPageByStudio(courseId,"SUCCESS","",coachedId,timestamp,TimeUtils.getTodayEndTime(),member2.getString(0),"PERSONAL","");
        success = false;
        for(int i =0;i<getPageByStudio.size();i++){
            if (getPageByStudio.getJSONObject(i).getString("id").equals(member2.getString(3))){
                success = true;
                for(int j = 0;j<result.length;j++){
                    Assert.assertEquals(getPageByStudio.getJSONObject(i).getString(result[j]),resultData[j],"约课产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
                }
                Assert.assertEquals(getPageByStudio.getJSONObject(i).getString("memberId"),member2.getString(0),"查询的约课数据不是同一个会员");
            }
        }
        Assert.assertTrue(success,"约课后在约课记录没有查询到相关信息");
        // check 2.3 预约记录详情
        JSONObject getDetailById = reserveTools.getDetailById(member2.getString(3));
        for(int j = 0;j<result.length;j++){
            Assert.assertEquals(getDetailById.getString(result[j]),resultData[j],"约课产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
        }
        Assert.assertEquals(getDetailById.getString("memberId"),member2.getString(0),"查询的约课数据不是同一个会员");

        // check 3： 会员卡消耗记录中包含该记录锁定
        JSONArray consumeRecord = cardTools.fetchPageOfConsumeRecord(member2.getString(1),member2.getString(2)).getJSONObject("result").getJSONArray("records");
        String[] result2 = new String[] {"resourceId","consumeType","changeOfUsablePurchaseBalance"};
        String[] respect = new String[] {member2.getString(3),"RESERVE","-1.00"};
        String[] message = new String[] {"会员卡消耗记录中记录的资源id与实际约课记录id不符合","会员卡消耗记录中记录的资源id与实际约课记录类型不符合","会员卡消耗记录中记录的资源id与实际约课记录余额不符合"};
        for (int i = 0; i < result2.length; i++){
            Assert.assertEquals(consumeRecord.getJSONObject(0).getString(result2[i]),respect[i],message[i]);
        }

    }


    @Test(description = "删除课次",priority = 3)
    public void testReservePerson_del() {
        // 课次中的一个会员取消预约
        reserveTools.cancelMemberReserve(member1.getString(3),true);
        // check 1:课次还存在 且课次中不包含该学员
        JSONObject getScheduleItemDetail = groupScheduleTools.getScheduleItemDetail(scheduleId);
        JSONArray reserveIds = getScheduleItemDetail.getJSONArray("reserveIds");
        boolean success = false;
        for (int i = 0; i < reserveIds.size(); i++){
            if(reserveIds.getString(i).equals(member1.getString(3))){
                success = true;
            }
        }
        Assert.assertFalse(success,"取消约课后课次详情学员还在课次中");

        // 删除该课次
        reserveTools.delPersonalScheduleItem(scheduleId);
        // 课次学员取消预约
        // check 1：课次已删除,课表没有该条数据
        JSONArray personalScheduleTable = reserveTools.getPersonalScheduleTable(timestamp,TimeUtils.getTodayEndTime(),courseId);
        boolean flag = true;
        if (personalScheduleTable != null){
            for (int i = 0; i < personalScheduleTable.size(); i++){
                if (personalScheduleTable.getJSONObject(i).getString("scheduleId").equals(scheduleId)){
                    scheduleId = personalScheduleTable.getJSONObject(i).getString("scheduleId");
                    flag = false;
                    break;
                }
            }
        }
        Assert.assertTrue(flag,"取消约课后课次未删除");


        // check 2：会员详情 - 预约记录已取消
        JSONArray getPageByMember = reserveTools.getPageByMember(courseId,"RESERVE_CANCEL","","", timestamp,TimeUtils.getTodayEndTime(),member2.getString(0),"PERSONAL");
        for(int i =0;i<getPageByMember.size();i++){
            if (getPageByMember.getJSONObject(i).getString("id").equals(member2.getString(3))){
                Assert.assertEquals(getPageByMember.getJSONObject(i).getString("reserveState"),"RESERVE_CANCEL","取消约课状态不是已取消");
            }
        }

        // check 3：预约记录列表中已取消
        JSONArray getPageByStudio = reserveTools.getPageByStudio(courseId,"RESERVE_CANCEL","","",timestamp,TimeUtils.getTodayEndTime(),member2.getString(0),"PERSONAL","");;
        for(int i =0;i<getPageByStudio.size();i++){
            if (getPageByStudio.getJSONObject(i).getString("id").equals(member2.getString(3))){
                Assert.assertEquals(getPageByStudio.getJSONObject(i).getString("reserveState"),"RESERVE_CANCEL","取消约课状态不是已取消");

            }
        }

        // check 4： 会员卡消耗记录中包含该记录锁定的次数释放
        JSONArray consumeRecord = cardTools.fetchPageOfConsumeRecord(member2.getString(1),member2.getString(2)).getJSONObject("result").getJSONArray("records");
        String[] result2 = new String[] {"resourceId","consumeType","changeOfUsablePurchaseBalance"};
        String[] respect = new String[] {member2.getString(3),"CANCEL_RESERVE","1.00"};
        String[] message1 = new String[] {"会员卡消耗记录中记录的资源id与实际约课记录id不符合","会员卡消耗记录中记录的资源id与实际约课记录类型不符合","会员卡消耗记录中记录的资源id与实际约课记录余额不符合"};
        for (int i = 0; i < result2.length; i++){
            Assert.assertEquals(consumeRecord.getJSONObject(0).getString(result2[i]),respect[i],message1[i]);
        }

    }






    /**
     * @description:查询学员
     * @author: xuyamei
     * @date:  2024/7/26 16:41
     * @param memberName
     * @return: com.alibaba.fastjson.JSONArray
     **/
    public JSONArray createMember(String memberName,String courseId){
        // 查询存量的学员没有则创建学员，
        if (tools.commonSearch(memberName,"NORMAL").getJSONArray("result").size()>0){
            memberId = tools.commonSearch(memberName,"NORMAL").getJSONArray("result").getJSONObject(0).getString("id");
        }else if (tools.commonSearch(memberName,"HISTORY").getJSONArray("result").size()>0){
            memberId = tools.commonSearch(memberName,"HISTORY").getJSONArray("result").getJSONObject(0).getString("id");
        }else if (tools.commonSearch(memberName,"POTENTIAL").getJSONArray("result").size()>0){
            memberId = tools.commonSearch(memberName,"POTENTIAL").getJSONArray("result").getJSONObject(0).getString("id");
        }else{
            memberId = memberTools.create(memberName, RandomStringUtil.randomMobile("203")).getString("result");
        }

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

        // 查询是否有可用的会员卡，没有则购买
        JSONArray listUserReservableBenefit = cardTools.listUserReservableBenefit(courseId, "PERSONAL", "MEMBER", memberId, Long.parseLong(todayStartTimeTamp));
        if (listUserReservableBenefit.size() == 0) {
            // 购买适用的会员卡
            signOrder(courseId, memberId);
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            listUserReservableBenefit = cardTools.listUserReservableBenefit(courseId, "PERSONAL", "MEMBER", memberId, Long.parseLong(todayStartTimeTamp));
        }
        // 查询权益
        benefitId = listUserReservableBenefit.getJSONObject(0).getString("benefitId");
        memberCardId = listUserReservableBenefit.getJSONObject(0).getString("memberCardId");

        JSONArray members = new JSONArray();
        members.add(memberId);
        members.add(benefitId);
        members.add(memberCardId);
        return members;
    }

    // 买卡
    public void signOrder(String courseId,String memberId){
        // 查询存量的卡
        JSONObject fetchPageOfMemberCard = cardTools.fetchPageOfMemberCard(courseId,"MEMBER_CARD");
        int total = Integer.parseInt(fetchPageOfMemberCard.getString("total"));
        String cardId = "";
        BigDecimal quantity = new BigDecimal(0) ;
        float price = 0;
        int validPeriod = 0;
        if (total == 0) {
            cardId = cardTools.memberCardCreate("私教约课使用会员卡"+ TimeUtils.getCurrentTime()).getString("result");
        }
        cardId = fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("id");
        quantity =  new BigDecimal(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getJSONArray("benefitList").getJSONObject(0).getString("balance"));
        price = Float.parseFloat(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("price"));
        validPeriod = Integer.parseInt(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("validPeriod"));

        //获取签单要用的卡快照id
        String latestSnapshotId = orderTools.fetchDetailById(cardId,xmAppApi.getLoginInfo().getBrandId(),xmAppApi.getLoginInfo().getStudioId(),xmAppApi.getLoginInfo().getAdminId()).getJSONObject("result").getString("latestSnapshotId");

        //检查会员对该卡是否超出购买上限
        boolean limitResult= orderTools.checkAllowPurchase("MEMBER_CARD",cardId,cardId,"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);
        }
    }


}
