package com.xiaomai.cases.polar.schedule.camp;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.cases.polar.finance.order.OrderTools;
import com.xiaomai.cases.polar.member.Tools;
import com.xiaomai.cases.polar.reserve.ReserveTools;
import com.xiaomai.cases.polar.schedule.group.GroupScheduleTools;
import com.xiaomai.cases.polar.training.TrainingTools;
import com.xiaomai.enums.ApiModule;
import com.xiaomai.enums.LoginAccount;
import com.xiaomai.enums.RequestType;
import com.xiaomai.enums.Terminal;
import com.xiaomai.utils.CommUtil;
import com.xiaomai.utils.XMJSONPath;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 编辑训练营排课规则
 *
 * @author adu
 * data 2024/7/10 17:46
 */

public class TestEditCampRuleSchedule extends SelectTargetTrainingCampAndGetInfo {
    @Resource(name = "groupScheduleTools")
    GroupScheduleTools groupScheduleTools;
    @Resource(name = "campScheduleTools")
    CampScheduleTools campScheduleTools;

    @Resource(name = "tools")
    Tools tools;
    @Resource(name = "reserveTools")
    ReserveTools reserveTools;
    @Resource(name = "trainingTools")
    TrainingTools trainingTools;

    @Resource(name = "orderTools")
    OrderTools orderTools;
    String campId = "";
    String chiefCoachId = "";
    String ruldId = "";
    String memberId = "";
    String orderId = "";
    String phone="";
    @BeforeClass
    @Override
    public void beforeTest() {
        setTestInfo(ApiModule.Polar_Schedule, "API_editCampRuleSchedule", LoginAccount.ADU_PROD, Terminal.B, "adu");
        super.beforeTest();
    }

    @Test(description = "编辑训练营排课规则")
    public void testEditCampRuleSchedule() throws InterruptedException {
        //获取选择的训练营ID
        campId = super.campId;
        //获取训练营活动的指定教练ID
        chiefCoachId = super.chiefCoachId;

        //从训练营活动中获取助教信息
        List<String> assistCoachIds = super.assistCoachIds;

        //创建训练营排课：按日期
        campScheduleTools.oneKeyCreateCampRuleSchedule(campId, chiefCoachId, super.courseId,
                super.traineeLowerLimit, super.traineeUpperLimit,
                "1140", super.openEndDate, true,
                "");

        //查询排课日程:根据训练营和教练查询
        Thread.sleep(2000);
        campScheduleTools.getCampRuleScheduleList(campId, "", chiefCoachId);
        Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result").size() == 1, "排课创建成功后，日程中没查询到对应数据");
        ruldId = XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result").getJSONObject(0).getString("ruleId");
        int scheduleClassHourBefore = XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result").getJSONObject(0).getJSONObject("campVO").getIntValue("scheduleClassHour");

        //创建排课后，学员报名关联的训练营活动
        //搜索目标会员
         phone= "15658063769";
        memberId = trainingTools.searchTargerMember(phone);
        if (memberId.isEmpty()) {
            memberId = tools.create("晨晨爸爸", phone).getString("result");
        }
        //给会员报名
        trainingTools.doSignCampOrder(memberId, this.price, this.campId,"");
        orderId = XMJSONPath.readPath(dataApi.getApi_response(), "$.result");
        Thread.sleep(5000);

        //check 预约记录（训练营预约记录，根据训练营活动筛选）
        JSONArray reserverList= reserveTools.getPageByStudio("","","","",null,
                null,"","TRAINING_CAMP",campId);

       //check 学员报名后生成的预约记录数量
       Assert.assertTrue(reserverList.size()==scheduleClassHourBefore,"排课后再报名训练营活动，生成课次的预约记录数量对不上");

        //下面要操作缩短结束日期，check
        String[] weekDaysArray = {"TUESDAY", "THURSDAY", "SATURDAY", "SUNDAY"};
        List<String> weekdaysList = Arrays.asList(weekDaysArray);
        int loopNum = campScheduleTools.queryExpectedLoopNum(CommUtil.getNDayEndTimeTamp(23), super.openEndDate, weekdaysList);

        //编辑训练营排课日程
        JSONObject body = new JSONObject();
        body.put("operatorId", xmAppApi.getLoginInfo().getAdminId());
        body.put("studioId", xmAppApi.getLoginInfo().getStudioId());
        body.put("brandId", xmAppApi.getLoginInfo().getBrandId());
        chiefCoachId = assistCoachIds.get(0).toString();
        body.put("chiefCoachId", chiefCoachId);//修改教练换人
        body.put("minMemberNum", super.traineeLowerLimit);
        body.put("maxMemberNum", super.traineeUpperLimit);
        body.put("minuteOffset", "1320");
        List<String> venueAreaIds = groupScheduleTools.getStockArea("流星花园秘密基地");
        body.put("venueAreaIds", venueAreaIds); //有空改为有数据
        List<String> assistTrainer = new ArrayList<>();
        assistTrainer.add(assistCoachIds.get(1).toString());
        body.put("assistCoachIds", assistTrainer); //空改成有数据
        body.put("ruleId", ruldId);
        body.put("spanMinutes", 50);
        body.put("endDate", CommUtil.getNDayEndTimeTamp(22)); //结束日期缩短了20天，
        body.put("force", true);
        body.put("retainBooking", true);
        xmAppApi.doRequest(RequestType.JSON, params, body.toString(), headers);
        Assert.assertTrue(Boolean.valueOf(XMJSONPath.readPath(xmAppApi.getApi_response(),"$.success"))==true,"调用接口返回结果："+XMJSONPath.readPath(xmAppApi.getApi_response(),"$.message"));
        Thread.sleep(1000);


        //查询训练营日程详情，check修改项是否被同步修改
        campScheduleTools.getCampRuleScheduleDetail(ruldId);
        Assert.assertEquals(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.chiefCoachId"), chiefCoachId);
        //Assert.assertEquals(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.endDate").substring(0, 9), CommUtil.getNDayEndTimeTamp(22).substring(0, 9));
        Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.venueAreaIds").containsAll(venueAreaIds), "场地有空改为有数据后，查看日程详情发现数据没变更");
        Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.assistCoachIds").containsAll(assistTrainer), "助教有空改为有数据后，查看日程详情发现数据没变更");
        Assert.assertEquals(XMJSONPath.getJSONObjectByReadPath(dataApi.getApi_response(), "$.result.campVO").getIntValue("totalClassHour"), super.totalClassHour, "总课时数有问题");
        int scheduleClassHourAfter = XMJSONPath.getJSONObjectByReadPath(dataApi.getApi_response(), "$.result.campVO").getIntValue("scheduleClassHour");
        //校验已排课次数是否同步变更:原排课次数-缩短日期那段时间的次数
        Assert.assertEquals(scheduleClassHourAfter, (scheduleClassHourBefore - loopNum));

        //check 编辑日程后（缩短日期）预约记录数量减少check
        JSONArray reserverListAfter= reserveTools.getPageByStudio("","","","",null,
                null,"","TRAINING_CAMP",campId);
        Assert.assertTrue(reserverListAfter.size()==scheduleClassHourAfter,"排课后再报名训练营活动，生成课次的预约记录数量对不上");
         //筛选出符合条件的数据有多少条
        // Long count = reserverListAfter.toJavaList(JSONObject.class).stream().filter(e -> e.getString("tenantMemberCardId").equals(campId)).count();

        //check 编辑日程后，对应的预约记录是否同步变更
        reserverListAfter.toJavaList(JSONObject.class).stream().forEach(object ->
                Assert.assertTrue(object.getJSONArray("assistCoachIds").containsAll(assistTrainer)&&
                        object.getJSONArray("areaIds").containsAll(venueAreaIds),"编辑日程后，预约记录没同步变更")
                );

        //作废学员训练营报名订单
        orderTools.discard(orderId,"重复录入","自动化测试作废训练营订单");
        //作废订单后，学员之前报名训练营生成的课次预约记录要被删除check
        Thread.sleep(2000);
        JSONArray reserverRecords= reserveTools.getPageByStudio("","","","",null,
                null,"","TRAINING_CAMP",campId);
        Assert.assertTrue(reserverRecords.size()==0,"作废学员订单后，训练营课次中对应的预约记录没有被删除哈");

    }

    @AfterTest(description = "删除此case创建的训练营排课日程")
    public void delData() {
        if (null != ruldId || !ruldId.isEmpty()) {
            campScheduleTools.delCampRuleSchedule(ruldId);
        }
        if (null != orderId || !orderId.isEmpty()) {
            trainingTools.fetchUserTrainingCardList(memberId);
            if (!XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result").getJSONObject(0).getString("state").equals("DISCARD")) {
                orderTools.discard(orderId, "重复录入", "自动化测试作废训练营订单");
            }
        }

        if (null != campId || !campId.isEmpty()) {
            this.getTrainingTools().deleteTraining(campId);
        }


    }

}

    