package com.xiaomai.cases.lunar.reserve;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.basetest.BaseTestImpl;
import com.xiaomai.cases.lunar.user.UserTools;
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.client.DataUserInfo;
import com.xiaomai.enums.ApiModule;
import com.xiaomai.enums.LoginAccount;
import com.xiaomai.enums.Terminal;
import com.xiaomai.utils.CommUtil;
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.lunar.reserve
 * @Author: xuyamei
 * @CreateTime: 2024-06-26  11:16
 * @Description: 小程序排队
 * @Version: 1.0
 */
public class TestAddToQueue extends BaseTestImpl {
    @Resource(name = "userTools")
    UserTools userTools;

    @Resource(name = "reserveCTools")
    ReserveCTools reserveCTools;

    @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;

    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 memberInfo = new JSONArray();

    private JSONArray memberReserveInfo = new JSONArray(); // 约课学员

    private String scheduleId;
    private Long startTime;
    private String courseId;
    private String memberId;
    private String chiefCoachId;

    @BeforeMethod
    @Override
    public void beforeTest(){
        setTestInfo(ApiModule.Lunar_Reserve,"API_addToQueue", LoginAccount.GYM_MINIAPPC, Terminal.minApp,"xym");
        super.beforeTest();
    }

    @Test
    public void testAddToQueue() {
        memberId = userTools.getMemberInfo().getString("memberId");
        // 创建团课课次
        createGroupSchedule();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 获取会员权益
        memberInfo = getMemberBenefit(memberId,"");

        // 获取约课学员A
        memberReserveInfo = getMemberBenefit("","约课学员朱莉");

        // 课次详情获取上课老师和上课时间
        JSONObject memberScheduleItemDetail = reserveCTools.getMemberScheduleItemDetail(scheduleId, memberId);
        startTime = memberScheduleItemDetail.getLongValue("startTime");
        chiefCoachId = memberScheduleItemDetail.getString("chiefCoachId");

        DataUserInfo dataUserInfo = new DataUserInfo();
        dataUserInfo.setTerminal(Terminal.B);
        dataUserInfo.setLoginUser(LoginAccount.GYM_PROD);
        // B端代预约
        String reserveId = reserveTools.addReserve("","",memberReserveInfo.getString(1),chiefCoachId,memberReserveInfo.getString(0),1,scheduleId,startTime,true,dataUserInfo);
        memberReserveInfo.add(reserveId);

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

        // 修改课次容量
        groupScheduleTools.editGroupSchedule(scheduleId,startTime,dataApi.getLoginInfo().getAdminId(),1,1,dataUserInfo);
        // 预约规则开启允许排队
        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,false,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);
        }

        reserveId = reserveCTools.addToQueue("",chiefCoachId,memberInfo.getString(0),memberInfo.getString(1),"",1,scheduleId,startTime,true);
        memberInfo.add(reserveId);

        // 验证课次详情、预约记录、预约详情、B端预约详情内容
        checkResult("QUEUE_PROCESS", "QUEUE_PROCESS","排队");

    }

    @DataProvider
    public Object[][] data(){
        return new Object[][]{
                {"reserve","FULL_CAPACITY","会员已约该课程，不可重复预约"},// 已经排队再次预约
                {"queue","排队失败，无需重复添加","会员已约该课程，不可重复预约"}, // 已排队再次排队
                {"cancel","排队取消成功",""},
                {"notQueue","排队失败，课次未开放预约",""},
                {"queuing","排队成功",""}

        };
    }
    @Test(priority = 2,dataProvider = "data")
    public void testAddToQueue2(String type,String msg,String msg2) {
        DataUserInfo dataUserInfo = new DataUserInfo();
        dataUserInfo.setTerminal(Terminal.B);
        dataUserInfo.setLoginUser(LoginAccount.GYM_PROD);

        switch(type) {
            case "reserve":
                reserveCTools.memberReserveAdd("",chiefCoachId,memberInfo.getString(1),"",memberInfo.getString(0),1,scheduleId,startTime,false);
                if (dataApi.getBodyInJSON().containsKey("result")){
                    // 有时候会提示满员
                    Assert.assertTrue(dataApi.getBodyInJSON().getJSONObject("result").getString("resultCode").equals(msg),"排队异常提示信息不符合");
                }else {
                    Assert.assertTrue(dataApi.getBodyInJSON().getString("message").equals(msg2),"排队异常提示信息不符合");
                }
                break;
            case "queue":
                reserveCTools.addToQueue("",chiefCoachId,memberInfo.getString(0),memberInfo.getString(1),"",1,scheduleId,startTime,false);
                Assert.assertTrue(dataApi.getBodyInJSON().getString("message").equals(msg) || dataApi.getBodyInJSON().getString("message").equals(msg2),"排队异常提示信息不符合");
                break;
            case "cancel":
                // 取消排队
                reserveCTools.cancelMemberReserve(memberInfo.getString(2),memberInfo.getString(0),true);
                // 取消验证课次详情、预约记录、预约详情、B端预约详情内容
                checkResult("QUEUE_CANCEL", "QUEUE_CANCEL","取消排队");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                break;
            case "notQueue":
                // 预约规则开启允许排队
                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,1,false,random.nextInt(100)+10,"minutes",false,random.nextInt(100)+10,"minutes");

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

                reserveCTools.addToQueue("",chiefCoachId,memberInfo.getString(0),memberInfo.getString(1),"",1,scheduleId,startTime,false);
                Assert.assertEquals(dataApi.getBodyInJSON().getString("message"),msg,"排队异常提示信息不符合");
                break;
            case "queuing":
                // 预约规则开启允许排队
                getRules = ruleTools.getGroupBookingRules(); // 获取场馆团课预约规则
                id = getRules.getString("id"); // 获取规则id
                random = new Random();
                bookingSeatCount = random.nextInt(10)+1; // 席位
                ruleTools.saveGroupBookingRules(id,true,bookingSeatCount,true,true,random.nextInt(30)+10,false,random.nextInt(100)+10,random.nextInt(5)+1,false,random.nextInt(100)+10,"minutes",false,random.nextInt(100)+10,"minutes");

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

                String reserveId = reserveCTools.addToQueue("",chiefCoachId,memberInfo.getString(0),memberInfo.getString(1),"",1,scheduleId,startTime,true);
                memberInfo.set(2,reserveId);  //将原来的id替换成新的id

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

                // 扩大课次人数上限容量
                groupScheduleTools.editGroupSchedule(scheduleId,startTime,chiefCoachId,1,2,dataUserInfo);

                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                // check 扩容后学员进入到课次
                // 验证课次详情、预约记录、预约详情、B端预约详情内容
                checkResult("SUCCESS","UN_SIGNED","排队进入课次");

        }

    }





    @Test(priority = 3)
    public void del(){
        DataUserInfo dataUserInfo = new DataUserInfo();
        dataUserInfo.setTerminal(Terminal.B);
        dataUserInfo.setLoginUser(LoginAccount.GYM_PROD);
        // 删除排课数据
        groupScheduleTools.delGroupRuleSchedule(ruldId,true,dataUserInfo);
        // 删除课次
        groupScheduleTools.delGroupScheduleItem(scheduleId,dataUserInfo);
    }


    // 创建团课课次
    public void createGroupSchedule(){
        DataUserInfo dataUserInfo = new DataUserInfo();
        dataUserInfo.setTerminal(Terminal.B);
        dataUserInfo.setLoginUser(LoginAccount.GYM_PROD);
        // 查询存量的约课课程
        // 查询存量的课程分类
        String categoryId = courseCategoryTools.getCourseCategoryPage("瑜伽");
        courseId = courseTools.getPersonalOrGroupCourseId("GROUP", "C端约课瑜伽团课课程", categoryId, "STUDIO", "", 2, 1,dataUserInfo).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, dataApi.getLoginInfo().getAdminId(), todayStartTimeTamp, todayEndDateTimeTamp, new ArrayList(), new ArrayList(), true, 1,minuteOffset[random.nextInt(20)],dataUserInfo);
        //1.2-查询排课日程
        JSONArray getGroupRuleScheduleList = groupScheduleTools.getGroupRuleScheduleList(courseId, dataApi.getLoginInfo().getAdminId(),dataUserInfo);
        //统计查询到的目标日程数量
        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 memberTimetable = reserveCTools.memberTimetable(memberId,Long.valueOf(todayStartTimeTamp), scheduleEndTime);
        for (int i = 0; i < memberTimetable.size(); i++){
            if (memberTimetable.getJSONObject(i).getString("ruleId").equals(ruldId)){
                scheduleId = memberTimetable.getJSONObject(i).getString("scheduleId");
                break;
            }
        }
    }

    /**
     * @description:买卡
     * @author: xuyamei
     * @date:  2024/6/24 19:42
     * @param courseId 课程id
     * @param memberId 会员id
     * @return: void
     **/
    public void signOrder(String courseId,String memberId){
        DataUserInfo dataUserInfo = new DataUserInfo();
        dataUserInfo.setTerminal(Terminal.B);
        dataUserInfo.setLoginUser(LoginAccount.GYM_PROD);

        // 查询存量的卡
        JSONObject fetchPageOfMemberCard = cardTools.fetchPageOfMemberCard(courseId,"MEMBER_CARD",dataUserInfo);
        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(),dataUserInfo).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,dataApi.getLoginInfo().getBrandId(),dataApi.getLoginInfo().getStudioId(),dataApi.getLoginInfo().getAdminId(),dataUserInfo).getJSONObject("result").getString("latestSnapshotId");

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


    /**
     * @description:查询会员是否购买会员卡，如果已购买则查看权益，如果没有则进行购买
     * @author: xuyamei
     * @date:  2024/6/24 19:43
     * @param memberId：会员id
     * @return:
     **/
    public JSONArray getMemberBenefit(String memberId,String memberName){
        DataUserInfo dataUserInfo = new DataUserInfo();
        dataUserInfo.setTerminal(Terminal.B);
        dataUserInfo.setLoginUser(LoginAccount.GYM_PROD);

        if (memberId.equals("")){
            // 查询存量的学员没有则创建学员，// todo 先手动新建
            if (tools.commonSearch(memberName,"NORMAL",dataUserInfo).getJSONArray("result").size()>0){
                memberId = tools.commonSearch(memberName,"NORMAL",dataUserInfo).getJSONArray("result").getJSONObject(0).getString("id");
            }else if (tools.commonSearch(memberName,"HISTORY",dataUserInfo).getJSONArray("result").size()>0){
                memberId = tools.commonSearch(memberName,"HISTORY",dataUserInfo).getJSONArray("result").getJSONObject(0).getString("id");
            }else{
                memberId = tools.commonSearch(memberName,"POTENTIAL",dataUserInfo).getJSONArray("result").getJSONObject(0).getString("id");
            }
        }

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

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


    public void checkResult(String reserveState,String signInState,String mes){
        // check 1：查询小程序课次详情，学员是预约状态
        JSONObject memberScheduleItemDetail = reserveCTools.getMemberScheduleItemDetail(scheduleId,memberId);
        String[] result = new String[] {"memberId","scheduleId","reserveId","reserveState","benefitId","courseType"};
        String[] resultData = new String[] {memberInfo.getString(0),scheduleId,memberInfo.getString(2),reserveState,memberInfo.getString(1),"GROUP_CLASS"};
        if (reserveState.equals("QUEUE_PROCESS") || reserveState.equals("RESERVE_CANCEL") ){
            // 校验预约排队之后约课课次详情按钮展示
            Assert.assertEquals(memberScheduleItemDetail.getJSONObject("memberScheduleInfoVO").getString("memberOperation"),reserveState.equals("QUEUE_PROCESS")?"TO_CANCEL_QUEUING":"TO_CANCEL_RESERVE",mes+"产生的数据与实际数据不符合");
            for(int j = 0;j<4;j++){
                Assert.assertEquals(memberScheduleItemDetail.getJSONObject("memberScheduleInfoVO").getString(result[j]),resultData[j],mes+"产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
            }
        }else if (reserveState.equals("QUEUE_CANCEL")){
            Assert.assertEquals(memberScheduleItemDetail.getJSONObject("memberScheduleInfoVO").getString("memberOperation"),"TO_QUEUING",mes+"产生的数据与实际数据不符合");
        }

        // check 2：查询小程序预约记录
        JSONArray getPageByMember = reserveCTools.getPageByMember(signInState,"",startTime,scheduleEndTime,memberId,"GROUP_CLASS");
        boolean success = false;
        for(int i =0;i<getPageByMember.size();i++){
            if (getPageByMember.getJSONObject(i).getString("id").equals(memberInfo.getString(2))){
                success = true;
                for(int j = 0;j<result.length;j++){
                    String resultString = result[j].equals("reserveId")?"id":result[j];
                    Assert.assertEquals(getPageByMember.getJSONObject(i).getString(resultString),resultData[j],mes+"产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
                }
                Assert.assertEquals(getPageByMember.getJSONObject(i).getString("memberId"),memberInfo.getString(0),"查询的"+mes+"数据不是同一个会员");
            }
        }
        Assert.assertTrue(success,mes+"预约记录没有查询到相关信息");
        // check 3：查询小程序预约详情
        JSONObject getDetailById = reserveCTools.getReserveDetailById(memberInfo.getString(2));
        for(int j = 0;j<result.length;j++){
            String resultString = result[j].equals("reserveId")?"id":result[j];
            Assert.assertEquals(getDetailById.getString(resultString),resultData[j],mes+"产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
        }
        if(reserveState.equals("QUEUE_PROCESS")){
            // 除去正常的检查，看一下排在第几位
            Assert.assertEquals(getDetailById.getString("queueSort"),"1","排队后排队名次应该是第一位");
        }
        Assert.assertEquals(getDetailById.getString("memberId"),memberInfo.getString(0),"查询的"+mes+"数据不是同一个会员");

        // check 4：查询B端预约详情
        DataUserInfo dataUserInfo = new DataUserInfo();
        dataUserInfo.setTerminal(Terminal.B);
        dataUserInfo.setLoginUser(LoginAccount.GYM_PROD);

        result = new String[] {"id","benefitId","reserveMemberNum","courseId","courseType","scheduleStartTime","reserveState","scheduleId"};
        resultData = new String[] {memberInfo.getString(2),memberInfo.getString(1),"1",courseId,"GROUP_CLASS",startTime+"",reserveState,scheduleId};
        getDetailById = reserveTools.getDetailById(memberInfo.getString(2),dataUserInfo);
        for(int j = 0;j<result.length;j++){
            Assert.assertEquals(getDetailById.getString(result[j]),resultData[j],mes+"产生的数据与实际数据不符合"+result[j]+"："+resultData[j]);
        }
        if(reserveState.equals("QUEUE_PROCESS")){
            // 除去正常的检查，看一下排在第几位
            Assert.assertEquals(getDetailById.getString("queueSort"),"1","排队后排队名次应该是第一位");
        }
        Assert.assertEquals(getDetailById.getString("memberId"),memberInfo.getString(0),"查询的"+mes+"数据不是同一个会员");


    }
}
