package com.xiaomai.cases.polar.points;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.cases.polar.course.CourseTools;
import com.xiaomai.cases.polar.entry.EntryTool;
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.camp.CampScheduleTools;
import com.xiaomai.cases.polar.schedule.group.GroupScheduleTools;
import com.xiaomai.cases.polar.setting.courseCategory.CourseCategoryTools;
import com.xiaomai.cases.polar.training.TrainingTools;
import com.xiaomai.enums.ApiModule;
import com.xiaomai.enums.LoginAccount;
import com.xiaomai.enums.Terminal;
import com.xiaomai.utils.*;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

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

public class TestFindStatementPagePermission extends XMBaseTest {
    @BeforeMethod
    public void beforeTest(){
        xmAppApi.setApiModule(ApiModule.Polar_Points)
                .setApiName("API_findStatementPagePermission")
                .setLoginUser(LoginAccount.GYM_PROD)
                .setTerminal(Terminal.B);
        dal.setCase_owner("yangjian")
                .setCase_name(Thread.currentThread().getStackTrace()[1].getFileName().split("\\.")[0]);
        super.beforeTest();
    }

    @Resource(name = "pointsTools")
    PointsTools pointsTools;

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

    String cardId;

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

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

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

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

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

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

    @Resource(name = "campScheduleTools")
    CampScheduleTools campScheduleTools;

    EntryTool entryTool = new EntryTool();





    @Test(description = "场馆业务触发-积分")
    public void testFindAccountPagePermission() throws InterruptedException {


        //创建会员
        String phone = "13357537209";
        String memberId = trainingTools.searchTargerMember(phone);
        if (memberId.isEmpty()) {
            memberId = tools.create("积分学员", phone).getString("result");
        }
        //初始会员积分数
        int BeleftBalance = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));

        //创建会员卡
        int cardTotal = Integer.parseInt(orderTools.fetchPageOfMemberCard("积分自动化会员卡", "MEMBER_CARD").getJSONObject("result").getString("total"));
        if (cardTotal == 0) {
            cardId = cardTools.memberCardCreate("积分自动化会员卡").getString("result");
        }
        JSONObject memberCard = orderTools.fetchPageOfMemberCard("积分会员卡", "MEMBER_CARD");
        cardId = memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");//会员卡ID

        //会员卡购买
        BigDecimal quantity = new BigDecimal(memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getJSONArray("benefitList").getJSONObject(0).getString("balance"));
        float price = Float.parseFloat(memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("price"));
        int validPeriod = Integer.parseInt(memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("validPeriod"));
        String latestSnapshotId = orderTools.fetchDetailById(cardId, xmAppApi.getLoginInfo().getBrandId(), xmAppApi.getLoginInfo().getStudioId(), xmAppApi.getLoginInfo().getAdminId()).getJSONObject("result").getString("latestSnapshotId");//获取卡快照ID
        orderTools.signOrder(cardId, latestSnapshotId, quantity, price, validPeriod, latestSnapshotId, 0, "PURCHASE", "MEMBER_CARD", memberId, price, price, "1", true);//会员购买订单，1元单

        //核对购买会员卡后，积分数量对应上升
        Thread.sleep(1000);
        int afleftBalance1 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//购买会员卡后的会员积分数
        Assert.assertEquals(afleftBalance1, BeleftBalance + 15);//断言增加规则的积分数，后需要改




        //创建团课，预约对应团课，签到
        String todayStartTimeTamp = CommUtil.oneKeyGetAddDay(-1);
        String todayEndDateTimeTamp = CommUtil.getNDayEndTimeTamp(-1);
        String categoryId = courseCategoryTools.getCourseCategoryPage("积分");
        String 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)]);
        List<String> chiefCoachId = new ArrayList<>();
        chiefCoachId.add("自动化昵称");
        String chiefCoachIdS = groupScheduleTools.getStudioAdminId(chiefCoachId).get(0).toString();
        JSONArray result = groupScheduleTools.getGroupRuleScheduleList(courseId, chiefCoachIdS);
        String ruldId = XMJSONPath.readPath(result.getJSONObject(0), "$.ruleId");
        // 日程列表中新增一条刚创建的规则，匹配到对应的ruldId
        Long goalRuld = result.toJavaList(JSONObject.class).stream().filter(e -> e.getString("ruleId").equals(ruldId)).count();
        Assert.assertTrue(goalRuld == 1);
        //查看今天的课表，获取刚创建的日程中对应的课次ID
        groupScheduleTools.getGroupScheduleTable(Long.valueOf(todayStartTimeTamp),Long.valueOf(todayEndDateTimeTamp),courseId);
        JSONArray array = XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.timetableGroups");
        String scheduleId = array.toJavaList(JSONObject.class).stream()
                .flatMap(e -> e.getJSONArray("timetableList").toJavaList(JSONObject.class).stream())
                .filter(e -> null != e.getString("ruleId"))
                .filter(e ->e.getString("ruleId").equals(ruldId))
                .map(e -> e.getString("scheduleId"))//获取scheduleId
                .findFirst().orElse(null);

        JSONObject getScheduleItemDetail = groupScheduleTools.getScheduleItemDetail(scheduleId);
        long startTime = getScheduleItemDetail.getLongValue("startTime");

        cardTools.listUserReservableBenefit("1937126076413669378", "GROUP_CLASS", "MEMBER", memberId, Long.parseLong(todayStartTimeTamp));
        String benefitId=XMJSONPath.readPath(dataApi.getApi_response(),"$.result[0].benefitId");
        String reserveId = reserveTools.addReserve("","", benefitId,xmAppApi.getLoginInfo().getAdminId(), memberId,1,scheduleId,startTime,true);

        reserveTools.signIn(true,reserveId,false);//签到

        //断言签到后，积分+10
        Thread.sleep(1000);
        int afleftBalance2 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//购买会员卡后的会员积分数
        Assert.assertEquals(afleftBalance2, afleftBalance1 + 10);//断言增加规则的积分数，后需要改

        //撤销签到,积分还回去
        reserveTools.memberReserve_discardSignIn(reserveId);
        Thread.sleep(1000);
        int afleftBalance3 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//购买会员卡后的会员积分数
        Assert.assertEquals(afleftBalance3, afleftBalance1);//断言增加规则的积分数，后需要改

        //取消预约
        reserveTools.cancelMemberReserve(reserveId,true);//防止卡余额不足


        
        String categoryId1 = courseCategoryTools.getCourseCategoryPage("健美操");
        String courseId1 = courseTools.getPersonalOrGroupCourseId("PERSONAL", "自动化私教课", categoryId1, "STUDIO", "ONE_TO_MANY", 1, 1).getString(0);

        JSONArray personalCoachTime = reserveTools.getPersonalTimeBlocks(xmAppApi.getLoginInfo().getAdminId(),courseId1,TimeUtils.getTodayTime());

        // 获取当前日期的Calendar实例
        Calendar calendar = Calendar.getInstance();
        // 获取第一条的步长 转换成时间戳
        int minuteOffset1 = personalCoachTime.getJSONObject(0).getIntValue("minuteOffset")/60;
        calendar.set(Calendar.HOUR_OF_DAY, minuteOffset1);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        // 将Calendar对象转换为时间戳
        long timestamp = calendar.getTimeInMillis();
        String reserveId1 = reserveTools.addPersonalReserve("",courseId1,"1796482517508263938",memberId,benefitId,10,1,"",timestamp,true);

        //签到私教课
        reserveTools.signIn(true,reserveId1,false);
        Thread.sleep(1000);
        int afleftBalance4 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//购买会员卡后的会员积分数
        Assert.assertEquals(afleftBalance4, afleftBalance3 + 10);//断言增加规则的积分数，后需要改

        //撤销签到,积分还回去
        reserveTools.memberReserve_discardSignIn(reserveId1);
        Thread.sleep(1000);
        int afleftBalance5 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//购买会员卡后的会员积分数
        Assert.assertEquals(afleftBalance5, afleftBalance3);//断言归还的规则的积分数
        System.out.println("afleftBalance5--------"+afleftBalance5);

        reserveTools.cancelMemberReserve(reserveId1,true);//取消私教课预约

        //训练营
        //int price1 =100;//保留两位小数
        //double priceD =Double.parseDouble(String.valueOf(price1));//String 转double类型
        //trainingTools.doSignCampOrder(memberId,priceD,"1937838684124549121","");//报名训练营
        //int afleftBalance6 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//购买会员卡后的会员积分数
        //Assert.assertEquals(afleftBalance6, afleftBalance5+10);//断言报名训练营积分数

        JSONObject deposit = cardTools.tenantMemberCardCommonSearch("DEPOSIT_CARD", "积分储值卡");
        String cardId1= deposit.getJSONArray("result").getJSONObject(0).getString("id");

        //会员卡购买储值卡

        String latestSnapshotIdC = XMJSONPath.readPath(cardTools.fetchDetailById(cardId1), "$.result.latestSnapshotId");
        cardTools.signOrderDeposit(cardId1,latestSnapshotIdC,memberId,"100","0");

        Thread.sleep(1000);
        int afleftBalance6 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//购买会员卡后的会员积分数
        Assert.assertEquals(afleftBalance6, afleftBalance5+10);//断言购买储值卡积分数+10
        System.out.println("afleftBalance6--------"+afleftBalance6);
        String depositCardId = XMJSONPath.readPath(orderTools.fetchUserCardList("DEPOSIT", memberId, "NORMAL"), "$.result[0].id");

        List voucherResourceIds = new ArrayList();
        voucherResourceIds.add("");
        JSONObject body = new JSONObject();
        body.put("amount", 100);
        body.put("paymentWay", 3);
        body.put("voucherResourceIds", voucherResourceIds);
        List paymentWays = new ArrayList();
        paymentWays.add(body);

        cardTools.refundOrderDeposit(depositCardId,"0","100","100",memberId,"100",paymentWays,0,new BigDecimal(100),new BigDecimal(100));//操作退储值卡
        Thread.sleep(1000);
        int afleftBalance7 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));
        System.out.println("afleftBalance7--------"+afleftBalance7);
        Assert.assertEquals(afleftBalance7, afleftBalance5);//断退储值卡积分数-10


        //创建训练营
        String applyStartTime = String.valueOf(CommUtil.getWholeHourTimestamp()); //当前时间的整点+1小时，比如现在是13：00，然后获取的是14：00的时间戳
        String applyEndTime = CommUtil.oneKeyGetAddDay(1);//明天0点
        String openStartDate = applyEndTime;
        String openEndDate = CommUtil.getNDayEndTimeTamp(2);//后天23：59：59
        int price1 =100;//保留两位小数
        double priceD =Double.parseDouble(String.valueOf(price1));//String 转double类型
        String title = "积分训练营" + RandomStringUtil.randomString(6);

        List<String> trainerList = new ArrayList<>();
        trainerList.add("木头");
        trainerList.add("吴彦祖");
        trainerList.add("杜君丽");
        List trainerListIdS = groupScheduleTools.getStudioAdminId(trainerList);
        List<String> trainerListEdit = new ArrayList<>();
        trainerListEdit.add("杜君丽");
        List editTrainerListId=groupScheduleTools.getStudioAdminId(trainerListEdit);

        String campID=trainingTools.createThenPublishTraining(applyStartTime,applyEndTime,"1808462926413910017",openStartDate,openEndDate,priceD,title,40,1,trainerListIdS,"YES");
        System.out.println("campID--------"+campID);
        //报名训练营

        trainingTools.doSignCampOrder(memberId,priceD,campID,"");//报名训练营
        Thread.sleep(1000);
        int afleftBalance8 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//购买会员卡后的会员积分数
        Assert.assertEquals(afleftBalance8, afleftBalance7+10);//断言报名训练营积分数

        //退训练营
        trainingTools.getTrainingApplyRecordsList(campID, phone);
        String memberCardId = XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result").getJSONObject(0).getString("memberCardId");
        trainingTools.refundCampOrder(memberId,priceD,memberCardId,40,0,new BigDecimal(priceD),new BigDecimal(priceD));//退单训练营
        Thread.sleep(1000);
        int afleftBalance9 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//会员积分数
        Assert.assertEquals(afleftBalance9, afleftBalance8-10);//断言报名训练营积分数
        trainingTools.deleteTraining(campID);//删除训练营


        //训练营签到

        campScheduleTools.getCampScheduleTable(TimeUtils.getTodayTime(), TimeUtils.getTodayEndTime(), "1937865450415263745");//查看对应训练营排课
        String scheduleId1 = XMJSONPath.readPath(dataApi.getApi_response(), "$result.timetableGroups[0].timetableList[0].scheduleId");
        System.out.println("scheduleId1--------"+scheduleId1);

        campScheduleTools.getCampScheduleItemDetail(scheduleId1);//获取课次信息
        String reserveId2 = XMJSONPath.readPath(dataApi.getApi_response(), "$result.memberReserveList[0].id");
        reserveTools.signIn(true,reserveId2,false);//完成签到
        Thread.sleep(1000);
        int afleftBalance10 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//会员积分数
        Assert.assertEquals(afleftBalance10, afleftBalance9+10);//断言报名训练营积分数

        reserveTools.memberReserve_discardSignIn(reserveId2);
        Thread.sleep(1000);
        int afleftBalance11 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//会员积分数
        Assert.assertEquals(afleftBalance11, afleftBalance10-10);//断言撤销训练营签到积分-10

        //签单体验卡
        cardTools.doMemberCardcommonSearch("积分体验卡","EXPERIENCE_CARD");
        String memberCardId1 = XMJSONPath.readPath(dataApi.getApi_response(), "$.result[0].id");//获取第一张搜索体验卡ID

        cardTools.fetchDetailById(memberCardId1);
        BigDecimal quantity1= new BigDecimal(XMJSONPath.readPath(dataApi.getApi_response(),"$.result.benefitList[0].balance"));
        //BigDecimal entryQuantity = new BigDecimal(XMJSONPath.readPath(dataApi.getApi_response(),"$.result.benefitList[1].balance"));
        float price2=Float.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.benefitList[0].price"));
        float entryPrice = Float.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.benefitList[1].price"));
        int validPeriod1=Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.validPeriod"));
        String latestSnapshotId1=XMJSONPath.readPath(dataApi.getApi_response(), "$.result.latestSnapshotId");
        orderTools.signOrder1(memberCardId1,latestSnapshotId1,quantity1, BigDecimal.valueOf(99999),price2,entryPrice,validPeriod1,latestSnapshotId1,0,"PURCHASE","EXPERIENCE_CARD", memberId,price2+entryPrice,price2+entryPrice,"1");

        Thread.sleep(1000);
        int afleftBalance12 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//会员积分数
        Assert.assertEquals(afleftBalance12, afleftBalance11+40);//断言购买体验卡+40，400的单子加40积分

        String entryVoucherId = entryTool.listUserVenueEntryCard("EXPERIENCE",memberId).getJSONArray("result").getJSONObject(0).getString("id");//第一张可用入场的体验看

        entryTool.addmemberEntry("EXPERIENCE_CARD",entryVoucherId,memberId);//手动添加体验卡入场记录
        Thread.sleep(1000);
        int afleftBalance13 = Integer.parseInt(XMJSONPath.readPath(pointsTools.findAccountPagePermission(xmAppApi.getLoginInfo().getStudioId(), memberId), "$.result.records[0].leftBalance"));//会员积分数
        Assert.assertEquals(afleftBalance13, afleftBalance12+10);//入场签到+10










    }
}

