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

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.cases.polar.setting.rules.RuleTools;
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 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;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Random;

/**
 * @BelongsProject: xm-sportstest
 * @BelongsPackage: com.xiaomai.cases.polar.reserve
 * @Author: xuyamei
 * @CreateTime: 2024-06-24  09:14
 * @Description: 排队
 * @Version: 1.0
 */
public class TestAddToQueue extends BaseTestImpl {
    @Resource(name = "courseCategoryTools")
    CourseCategoryTools courseCategoryTools;
    @Resource(name = "courseTools")
    CourseTools courseTools;

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

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

    @Resource(name = "ruleTools")
    RuleTools ruleTools;
    MemberTools memberTools = new MemberTools();


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

    Tools tools = new Tools();

    String todayStartTimeTamp = CommUtil.oneKeyGetAddDay(1);


    //获取今天结束日期的时间戳
    String todayEndDateTimeTamp = CommUtil.getNDayEndTimeTamp(1);
    Long scheduleEndTime = TimeUtils.getTodayEndTime(1);
    private String ruldId;
    private JSONArray memberId1 = new JSONArray();
    private JSONArray memberId2 = new JSONArray();
    private JSONArray memberId3 = new JSONArray();
    private String scheduleId;
    private Long startTime;
    private String courseId;

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

    @Test(description = "创建团课课次>约课>修改课次容量>约课后进行排队>排队校验")
    public void testAddMemberReserve(){

        // 创建团课课次
        createGroupSchedule();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 创建约课学员A
        memberId1 = createMember("约课学员sandy");

        // 查询课次详情 查课次的开始时间
        JSONObject getScheduleItemDetail = groupScheduleTools.getScheduleItemDetail(scheduleId);
        startTime = getScheduleItemDetail.getLongValue("startTime");
        // 预约
        String reserveId = reserveTools.addReserve("","",memberId1.getString(1),xmAppApi.getLoginInfo().getAdminId(),memberId1.getString(0),1,scheduleId,startTime,true);
        memberId1.add(reserveId);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // 修改课次容量
        groupScheduleTools.editGroupSchedule(scheduleId,startTime,xmAppApi.getLoginInfo().getAdminId(),1,1);
        // 预约规则开启允许排队
        JSONObject getRules = ruleTools.getGroupBookingRules(); // 获取场馆团课预约规则
        String id = getRules.getString("id"); // 获取规则id
        Random random = new Random();
        int bookingSeatCount = random.nextInt(10)+1; // 席位
        ruleTools.saveGroupBookingRules(id,true,bookingSeatCount,true,true,random.nextInt(30)+10,true,random.nextInt(100)+10,random.nextInt(5)+1,false,random.nextInt(100)+10,"minutes",false,random.nextInt(100)+10,"minutes");

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

        // 创建排课学员A
        memberId2 = createMember("排队学员Amy");
        // 排队
        reserveId = reserveTools.addToQueue("",xmAppApi.getLoginInfo().getAdminId(),memberId2.getString(0),memberId2.getString(1),"",1,scheduleId,startTime,true);
        memberId2.add(reserveId);

        // check 1: 预约记录、会员详情预约记录、预约详情数据check
        checkReserve(memberId2.getString(0),reserveId,"QUEUE_PROCESS",memberId2.getString(1),"排队");

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


    }

    @DataProvider
    public Object[][] data(){
        return new Object[][]{
                {"memberId1","排队失败，无需重复添加","会员已约该课程，不可重复预约"},// 已经在课次排队
                {"memberId2","排队失败，无需重复添加","会员已约该课程，不可重复预约"} // 已排队再次排队

        };
    }
    @Test(priority = 1,description = "已经在课次中再次排队",dataProvider = "data")
    public void addToQueue2(String member,String message1 ,String message2){
        String memberId = member.equals(memberId1) ? memberId1.getString(0) : memberId2.getString(0);
        String benefitId = member.equals(memberId1) ? memberId1.getString(1) : memberId2.getString(1);
        reserveTools.addToQueue("",xmAppApi.getLoginInfo().getAdminId(),memberId,benefitId,"",1,scheduleId,startTime,false);
        Assert.assertTrue(dataApi.getBodyInJSON().getString("message").equals(message1) || dataApi.getBodyInJSON().getString("message").equals(message2),"排队提示信息不符合");
    }

    @Test(priority = 2,description = "在创建一个排队学员，进行排队，排在第二位，将第一位的排队取消，check 学员排在第一，将课次学员取消， check学员在课次中，并排队成功")
    public void addToQueue3(){
        // 预约规则开启允许排队
        JSONObject getRules = ruleTools.getGroupBookingRules(); // 获取场馆团课预约规则
        String id = getRules.getString("id"); // 获取规则id
        Random random = new Random();
        int bookingSeatCount = random.nextInt(10)+1; // 席位
        ruleTools.saveGroupBookingRules(id,true,bookingSeatCount,true,true,random.nextInt(30)+10,true,random.nextInt(100)+10,random.nextInt(5)+1,true,random.nextInt(100)+10,"minutes",true,random.nextInt(100)+10,"minutes");

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

        // 创建排课学员A
        memberId3 = createMember("排队学员yaya");
        // 操作1：排队
        String reserveId = reserveTools.addToQueue("",xmAppApi.getLoginInfo().getAdminId(),memberId3.getString(0),memberId3.getString(1),"",1,scheduleId,startTime,true);
        memberId3.add(reserveId);

        // check 1 预约记录详情
        JSONObject getDetailById = reserveTools.getDetailById(reserveId);
        // 正常的检查，看一下排在第几位
        Assert.assertEquals(getDetailById.getString("queueSort"),"2","排队后排队名次应该是第二位");

        // 操作2：将第一位"排队学员Amy"的排队取消
        reserveTools.cancelMemberReserve(memberId2.getString(3),true);
        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // check 2.1: 排队学员Amy 排队记录已取消
        checkReserve(memberId2.getString(0),memberId2.getString(3),"QUEUE_CANCEL",memberId2.getString(1),"排队");
        // check 2.2 排队学员Amy 会员卡消耗记录中包含该记录释放
        JSONArray consumeRecord = cardTools.fetchPageOfConsumeRecord(memberId2.getString(1),memberId2.getString(2)).getJSONObject("result").getJSONArray("records");
        String[] result2 = new String[] {"resourceId","consumeType","changeOfUsablePurchaseBalance"};
        String[] respect = new String[] {memberId2.getString(3),"CANCEL_QUEUE","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]);
        }

        //check 2.2 排队学员yaya 排在第一位
        getDetailById = reserveTools.getDetailById(reserveId);
        Assert.assertEquals(getDetailById.getString("queueSort"),"1","第一位的学员取消排队后排队名次应该是第1位");

        // 操作3：将约课的学员取消
        reserveTools.cancelMemberReserve(memberId1.getString(3),true);
        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // check 3.1 取消后，yaya的预约记录check
        checkReserve(memberId3.getString(0),reserveId,"SUCCESS",memberId3.getString(1),"从排队->预约");


    }




    @Test(priority = 3)
    public void del(){
        // 删除排课数据
        groupScheduleTools.delGroupRuleSchedule(ruldId,true);
        groupScheduleTools.delGroupScheduleItem(scheduleId);
    }



    /**
     * @description:买卡
     * @author: xuyamei
     * @date:  2024/6/24 19:42
     * @param courseId 课程id
     * @param memberId 会员id
     * @return: void
     **/
    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");
        }
    }


    // 创建团课课次
    public void createGroupSchedule(){
        // 查询存量的约课课程
        // 查询存量的课程分类
        String categoryId = courseCategoryTools.getCourseCategoryPage("瑜伽");
        courseId = courseTools.getPersonalOrGroupCourseId("GROUP", "空中瑜伽团课课程", categoryId, "STUDIO", "", 2, 1).getString(0);
        // 创建排课
        int[] minuteOffset = {60, 120, 180,  240, 300, 360,  420,  480, 540,  600,  660, 720, 780,  840,  900, 960, 1020, 1080, 1140, 1200, 1260};
        Random random = new Random();
        //1.1-创建排课日程
        groupScheduleTools.createGroupRuleSchedule(courseId, xmAppApi.getLoginInfo().getAdminId(), todayStartTimeTamp, todayEndDateTimeTamp, new ArrayList(), new ArrayList(), true, 1,minuteOffset[random.nextInt(20)]);
        //1.2-查询排课日程
        JSONArray getGroupRuleScheduleList = groupScheduleTools.getGroupRuleScheduleList(courseId, xmAppApi.getLoginInfo().getAdminId());
        //统计查询到的目标日程数量
        ruldId = XMJSONPath.readPath(getGroupRuleScheduleList.getJSONObject(0), "$.ruleId");
        Long scheduleEndTime = TimeUtils.getTodayEndTime(1);
        try {
            Thread.sleep(2500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 查询课次id
        JSONArray getGroupScheduleTable = groupScheduleTools.getGroupScheduleTable(Long.valueOf(todayStartTimeTamp), scheduleEndTime,courseId);
        for (int i = 0; i < getGroupScheduleTable.size(); i++){
            if (getGroupScheduleTable.getJSONObject(i).containsKey("ruleId")  && getGroupScheduleTable.getJSONObject(i).getString("ruleId").equals(ruldId)){
                scheduleId = getGroupScheduleTable.getJSONObject(i).getString("scheduleId");
                break;
            }
        }
    }

    /**
     * @description:创建学员并查询会员是否购买会员卡，如果已购买则查看权益，如果没有则进行购买
     * @author: xuyamei
     * @date:  2024/6/24 19:43
     * @param memberName：会员姓名
     * @return:
     **/
    public JSONArray createMember(String memberName){
        String memberId = "";
        // 查询存量的学员没有则创建学员
        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");
        }

        // 查询是否有可用的会员卡，没有则购买
        JSONArray listUserReservableBenefit = cardTools.listUserReservableBenefit(courseId, "GROUP_CLASS", "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, "GROUP_CLASS", "MEMBER", memberId, Long.parseLong(todayStartTimeTamp));
        }
        // 查询权益
        String benefitId = listUserReservableBenefit.getJSONObject(0).getString("benefitId");
        String memberCardId = listUserReservableBenefit.getJSONObject(0).getString("memberCardId");

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



    /**
     * @description:校验预约记录、会员详情预约记录、预约详情内容
     * @author: xuyamei
     * @date:  2024/6/24 19:32
     * @param memberId 会员id
     * @param reserveId 预约id
     * @param reserveState 预约状态
     * @param benefitId 权益id
     * @param message ：约课/排队/取消预约
     * @return: void
     **/
    public void checkReserve(String memberId,String reserveId,String reserveState,String benefitId,String message){
        // check 1.1 学员详情预约记录
        JSONArray getPageByMember = reserveTools.getPageByMember(courseId,reserveState,"","", startTime,scheduleEndTime,memberId,"GROUP_CLASS");
        // 要检查字段内容：约课id、权益id、预约人数、课程、课程类型、开始时间、预约状态、课次id
        String[] result = new String[] {"id","benefitId","reserveMemberNum","courseId","courseType","scheduleStartTime","reserveState","scheduleId"};
        String[] resultData = new String[] {reserveId,benefitId,"1",courseId,"GROUP_CLASS",startTime+"",reserveState,scheduleId};
        boolean 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],message+"产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
                }
            }
        }
        Assert.assertTrue(success,message+"在会员详情页面未查询到相关信息");
        // check 1.2 预约记录列表
        JSONArray getPageByStudio = reserveTools.getPageByStudio(courseId,reserveState,"","",startTime,scheduleEndTime,memberId,"GROUP_CLASS","");
        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],message+"产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
                }
                Assert.assertEquals(getPageByStudio.getJSONObject(i).getString("memberId"),memberId,"查询的约课数据不是同一个会员");
            }
        }
        Assert.assertTrue(success,"排队后在约课记录没有查询到相关信息");
        // check 1.3 预约记录详情
        JSONObject getDetailById = reserveTools.getDetailById(reserveId);
        for(int j = 0;j<result.length;j++){
            Assert.assertEquals(getDetailById.getString(result[j]),resultData[j],message+"产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
        }
        if(reserveState.equals("QUEUE_PROCESS")){
            // 除去正常的检查，看一下排在第几位
            Assert.assertEquals(getDetailById.getString("queueSort"),"1","排队后排队名次应该是第一位");
        }
        Assert.assertEquals(getDetailById.getString("memberId"),memberId,"查询的排队约课数据不是同一个会员");
    }



}
