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.minMemberCard.MinCardTools;
import com.xiaomai.cases.lunar.order.OrderCTools;
import com.xiaomai.cases.lunar.user.UserTools;
import com.xiaomai.cases.polar.course.CourseTools;
import com.xiaomai.cases.polar.memberCard.CardTools;
import com.xiaomai.cases.polar.reserve.ReserveTools;
import com.xiaomai.cases.polar.setting.courseCategory.CourseCategoryTools;
import com.xiaomai.client.DataUserInfo;
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.RandomStringUtil;
import com.xiaomai.utils.TimeUtils;
import com.xiaomai.utils.XMJSONPath;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import javax.annotation.Resource;

public class TestSingleReserveByDeposit 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 = "orderCTools")
    OrderCTools orderCTools;
    @Resource(name = "minCardTools")
    MinCardTools minCardTools;
    @Resource(name = "cardTools")
    CardTools cardTools;
    DataUserInfo info = new DataUserInfo();
    public String depositCardId;
    public String reservePrice;
    public String courseId;
    public String chiefCoachId;
    public String voucherId;
    public String reserveId;

    @BeforeMethod
    @Override
    public void beforeTest(){
        setTestInfo(ApiModule.Lunar_Reserve,"API_createSingleReserve", LoginAccount.GYM_MINIAPPC, Terminal.minApp,"xyy");
        super.beforeTest();
    }
    @Test(description = "小程序使用储值卡单次预约私教课")
    public void testSingleReserveByDeposit() throws InterruptedException {
        //b端先创建私教可单次预约的课程
        createPersonalSchedule();
        //获取会员id
        String memberId = userTools.getMemberInfo().getString("memberId");
        //查询是否有可使用的储值卡，如果没有创建1张
        int num = XMJSONPath.getJSONArrayByReadPath(minCardTools.listUserUsableDepositCard(memberId,"SINGLE_PAY_RESERVE"), "$.result.applicableList").size();
        if (num>1){
            for(int i=0; i<num-1; i++) {
                String leftBalance = XMJSONPath.readPath(minCardTools.listUserUsableDepositCard(memberId, "SINGLE_PAY_RESERVE"), "$.result.applicableList[" + i + "].depositBenefit.leftBalance");
                //遍历储值卡的可用余额是否大于等于私教课的价格
                if (Double.parseDouble(leftBalance) >= Double.parseDouble(reservePrice)) {
                    depositCardId = XMJSONPath.readPath(minCardTools.listUserUsableDepositCard(memberId, "SINGLE_PAY_RESERVE"), "$.result.applicableList[" + i + "].id");
                    break;
                }
                else{
                    //切换B端校验
                    info.setTerminal(Terminal.B);
                    info.setLoginUser(LoginAccount.GYM_PROD);

                    //查询启用中的储值卡，获取储值卡id
                    String cardId = XMJSONPath.readPath(cardTools.fetchPageOfMemberCardByTitle("DEPOSIT_CARD","0元储值卡",info), "$.result.records[0].id");
                    String latestSnapshotId = XMJSONPath.readPath(cardTools.fetchDetailById(cardId,info), "$.result.latestSnapshotId");
                    //购买1张储值卡
                    cardTools.signOrderDeposit(cardId,latestSnapshotId,memberId,"0.00","1000.00",info);
                    //获取C端第1张可使用的储值卡
                    depositCardId = XMJSONPath.readPath(minCardTools.listUserUsableDepositCard(memberId, "SINGLE_PAY_RESERVE"), "$.result.applicableList[0].id");
                }
            }
            //查询要使用的储值卡消耗记录条数
            String depositBenefitId = XMJSONPath.readPath(minCardTools.findMemberCardDetailById(depositCardId),"$.result.depositBenefit.id");
            int total = Integer.parseInt(XMJSONPath.readPath(minCardTools.fetchPageOfConsumeRecord(depositCardId,depositBenefitId),"$.result.total"));

            JSONObject body = new JSONObject();
            body.put("addToQueue",false);//排队
            body.put("areaIds",null);//场地
            body.put("chiefCoachId",chiefCoachId);//私教id
            body.put("courseId",courseId);//私教可单次约课的课程id
            body.put("memberId",memberId);//会员id
            body.put("objectId", RandomStringUtil.randomString(16));
            body.put("receivableAmount","0.00");
            body.put("scheduleStartTime", CommUtil.oneKeyGetAddDay(2));//约课开始时间：当前后2天
            body.put("spanMinutes",10);
            body.put("studioId",xmAppApi.getLoginInfo().getStudioId());
            body.put("brandId",xmAppApi.getLoginInfo().getBrandId());
            body.put("memo","脚本使用储值卡单约预约私教课");
            body.put("depositCardId",depositCardId);//储值卡id
            body.put("depositAmount",reservePrice);//储值卡抵扣金额

            //调用请求
            xmAppApi.doRequest(RequestType.JSON,params,body.toString(),headers).assetsSuccess(true);
            voucherId = xmAppApi.getBodyInJSON().getString("result");//订单ID
            Thread.sleep(5000);
            reserveId = reserveCTools.getDetailById(voucherId).getString("reserveId");//约课id

            Thread.sleep(3000);
            //校验C端订单详情
            Assert.assertEquals(XMJSONPath.readPath(orderCTools.getDetail(voucherId),"$.result.state"),"PAID","创建签单订单成功,但订单状态不是已完成");
            Assert.assertEquals(XMJSONPath.readPath(orderCTools.getDetail(voucherId),"$.result.voucherItems[0].skuType"),"SINGLE_RESERVE","C端创建的签单订单,商品类型非单次约课");

            //检验储值卡的消耗记录新增1条
            Assert.assertTrue(Integer.parseInt(XMJSONPath.readPath(minCardTools.fetchPageOfConsumeRecord(depositCardId,depositBenefitId),"$.result.total"))==total+1);
            Assert.assertEquals(XMJSONPath.readPath(minCardTools.fetchPageOfConsumeRecord(depositCardId,depositBenefitId),"$.result.records[0].consumeType"),"DEPOSIT_SIGN_ORDER");//消耗类型：签单
            Assert.assertEquals(XMJSONPath.readPath(minCardTools.fetchPageOfConsumeRecord(depositCardId,depositBenefitId),"$.result.records[0].changeOfGiveBalance"),"-"+reservePrice);//消耗赠送金额为单次约课的价格

            //检验预约详情的预约状态及类型
            Assert.assertEquals(XMJSONPath.readPath(reserveCTools.getReserveDetailById(reserveId),"$.accountType"),"SINGLE_RESERVE");//预约方式：自主预约
            Assert.assertEquals(XMJSONPath.readPath(reserveCTools.getReserveDetailById(reserveId),"$.reserveState"),"SUCCESS");//预约状态

            //数据清理
            //取消约课
            reserveCTools.cancelMemberReserve(reserveId,memberId,true);
            Thread.sleep(2000);
            //检验预约状态为取消
            Assert.assertEquals(XMJSONPath.readPath(reserveCTools.getReserveDetailById(reserveId),"$.reserveState"),"RESERVE_CANCEL");//预约取消
            //储值卡金额退还
            Assert.assertTrue(Integer.parseInt(XMJSONPath.readPath(minCardTools.fetchPageOfConsumeRecord(depositCardId,depositBenefitId),"$.result.total"))==total+2);
            Assert.assertEquals(XMJSONPath.readPath(minCardTools.fetchPageOfConsumeRecord(depositCardId,depositBenefitId),"$.result.records[0].consumeType"),"DEPOSIT_DISCARD_SIGN_ORDER");//消耗类型：作废签单
            Assert.assertEquals(XMJSONPath.readPath(minCardTools.fetchPageOfConsumeRecord(depositCardId,depositBenefitId),"$.result.records[0].changeOfGiveBalance"),reservePrice);//消耗赠送金额为单次约课的价格
            //订单状态为取消
            Assert.assertEquals(XMJSONPath.readPath(orderCTools.getDetail(voucherId),"$.result.state"),"DISCARD");

        }
    }

    // 准备数据：创建私教可单次预约的数据
    public void createPersonalSchedule()throws InterruptedException{
        info.setTerminal(Terminal.B);
        info.setLoginUser(LoginAccount.GYM_PROD);

        reservePrice = "1.00";//设置单次约课价格为1元一节

        // 第一步：查询存量的约课课程
        // 查询存量的课程分类
        String categoryId = courseCategoryTools.getCourseCategoryPage("普拉提");
        courseId = courseTools.getPersonalOrGroupCourseId("PERSONAL", "普拉提器械1VN私教课程", categoryId, "STUDIO", "ONE_TO_MANY", 20, 1,info).getString(0);
        String courseName = courseTools.getPersonalOrGroupCourseId("PERSONAL", "普拉提器械1VN私教课程", categoryId, "STUDIO", "ONE_TO_MANY", 20, 1,info).getString(1);
        Thread.sleep(1000);

        // 第二步：查询存量的私教教练，并将教练添加到课程中
        // 获取教练列表
        JSONObject pageStudioPersonalCoach = reserveTools.pageStudioPersonalCoach("",info);
        // 获取超管
        chiefCoachId = pageStudioPersonalCoach.getJSONArray("records").getJSONObject(0).getString("id");
        // 编辑私教课程教练添加到课程中
        courseTools.editPersonalCourse(categoryId,courseId,courseName,chiefCoachId,reservePrice,info);

        // 第三步：创建私教可约时间
        // 设置可约时间
        JSONArray normalTimeInfoRequests = new JSONArray();
        JSONObject infoRequests = new JSONObject();
        JSONArray timePeriodInfos = new JSONArray();
        //设置全天0：00-23：55可约
        JSONObject timeInfo = new JSONObject();
        timeInfo.put("minuteOffset",0);
        timeInfo.put("spanMinutes",1435);
        timePeriodInfos.add(timeInfo);
        infoRequests.put("timePeriodInfos",timePeriodInfos);

        // 每星期
        String[] weekdays = {"MONDAY", "TUESDAY", "WEDNESDAY", "THURSDAY", "FRIDAY", "SATURDAY", "SUNDAY"};
        infoRequests.put("weekdays",weekdays);
        normalTimeInfoRequests.add(infoRequests);
        // 设置可约时间
        reserveTools.createNormalDate(chiefCoachId,normalTimeInfoRequests,info);
        Thread.sleep(1000);
    }
}
