package com.xiaomai.cases.polar.setting.venue;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.finance.order.OrderTools;
import com.xiaomai.cases.polar.memberCard.CardTools;
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.RandomStringUtil;
import com.xiaomai.utils.TimeUtils;
import com.xiaomai.utils.XMBaseTest;
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 TestPurchaseAreaTimes extends XMBaseTest {
    @Resource(name = "venueAreaTools")
    VenueAreaTools venueAreaTools;
    @Resource(name = "userTools")
    UserTools userTools;
    @Resource(name = "minCardTools")
    MinCardTools minCardTools;
    @Resource(name = "cardTools")
    CardTools cardTools;
    @Resource(name = "orderCTools")
    OrderCTools orderCTools;
    @Resource(name = "orderTools")
    OrderTools orderTools;
    DataUserInfo info = new DataUserInfo();
    String depositCardId;
    String price = "1.99";//设置场地全场价格
    @BeforeMethod
    public void beforeTest(){
        xmAppApi.setApiModule(ApiModule.Lunar_VenueArea)
                .setApiName("API_purchaseAreaTimes")
                .setLoginUser(LoginAccount.GYM_MINIAPPC)
                .setTerminal(Terminal.minApp);
        dal.setCase_owner("xyy")
                .setCase_name(Thread.currentThread().getStackTrace()[1].getFileName().split("\\.")[0]);
        super.beforeTest();

    }
    @Test(description = "小程序使用储值卡购买场地预约")
    public void testPurchaseAreaTimesByDeposit() throws InterruptedException {
        //获取小程序可预约的场地数
        int enableReserveSuiteNum = venueAreaTools.getEnableReserveVenueAreaSuiteList().getJSONArray("result").size();
        int suiteNum = venueAreaTools.getVenueAreaSuitePage().getJSONArray("result").size();
        //切换B端校验
        info.setTerminal(Terminal.B);
        info.setLoginUser(LoginAccount.GYM_PROD);
        //1.创建场地
        String groupId = venueAreaTools.saveVenueArea(info);
        //2.创建场地组
        String suiteName = "西湖场地组" + RandomStringUtil.randomString(5);
        String suiteId = venueAreaTools.createOrEditVenueAreaSuite(null,suiteName,info);
        //3.场地组绑定场地
        venueAreaTools.bindVenueAreas(suiteId, groupId, info);
        //获取全场的areaId,一般全场的areaId为groupId+1以此类推；
        String areaId = String.valueOf(Long.valueOf(groupId)+1);
        //获取场地组的时间区间，并检验是否有返回值
        Assert.assertTrue(venueAreaTools.getSuiteVenueAreaTimeList(suiteId,info).getJSONArray("result").size()>0);
        //有返回值就可以批量创建可预约时间
        venueAreaTools.createBatchNormalDate(suiteId, groupId,price,info);
        //检验c端的场地组数量+1
        Assert.assertTrue(venueAreaTools.getEnableReserveVenueAreaSuiteList().getJSONArray("result").size()==enableReserveSuiteNum+1);
        Assert.assertTrue(venueAreaTools.getVenueAreaSuitePage().getJSONArray("result").size()==suiteNum+1);
        //检验该场地组时间块有数值
        Assert.assertTrue(venueAreaTools.getSuiteReserveTimeBlock(suiteId).getJSONObject("result").getJSONArray("venueReserveTimeBlockVOS").size()>0);
        //检验c端的场地详情为启用中
        Assert.assertEquals(XMJSONPath.readPath(venueAreaTools.getVenueAreaSuiteDetail(suiteId),"$.result.state"),"ON");
        //获取用户
        String memberId = userTools.getMemberInfo().getString("memberId");
        //获取当天的0点
        String reserveDay = String.valueOf(TimeUtils.getTodayTime());
        //查询是否有可使用的储值卡，如果没有创建1张
        int num = XMJSONPath.getJSONArrayByReadPath(minCardTools.listUserUsableDepositCard(memberId, "ORDER_VENUE"), "$.result.applicableList").size();
        if (num > 1) {
            for (int i = 0; i < num - 1; i++) {
                String leftBalance = XMJSONPath.readPath(minCardTools.listUserUsableDepositCard(memberId, "ORDER_VENUE"), "$.result.applicableList[" + i + "].depositBenefit.leftBalance");
                //遍历储值卡的可用余额是否大于等于会员卡的价格
                if (Double.parseDouble(leftBalance) >= Double.parseDouble(price)) {
                    depositCardId = XMJSONPath.readPath(minCardTools.listUserUsableDepositCard(memberId, "ORDER_VENUE"), "$.result.applicableList[" + i + "].id");
                    break;
                } else {
                    //查询启用中的储值卡，获取储值卡id
                    String cardId = XMJSONPath.readPath(cardTools.fetchPageOfMemberCard("DEPOSIT_CARD", info), "$.result.records[0].id");
                    String latestSnapshotId = XMJSONPath.readPath(cardTools.fetchDetailById(cardId, info), "$.result.latestSnapshotId");
                    //b端购买1张储值卡
                    cardTools.signOrderDeposit(cardId, latestSnapshotId, memberId, "0.00", "1000.00", info);
                    //获取C端第1张可使用的储值卡
                    depositCardId = XMJSONPath.readPath(minCardTools.listUserUsableDepositCard(memberId, "ORDER_VENUE"), "$.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"));

            //场地预约列表的已预约数据
            int bookingNum = Integer.parseInt(XMJSONPath.readPath(venueAreaTools.pageMemberVenueBooking("RESERVED",memberId),"$.result.total"));
            //检验场地预约前该场地规则
            Assert.assertEquals(XMJSONPath.readPath(venueAreaTools.venueAreaBookingRulesGet(),"$.result.brandId"),xmAppApi.getLoginInfo().getBrandId());

            //4.小程序预约场地
            JSONArray areaTimeInfos = new JSONArray();
            JSONObject areaTime = new JSONObject();
            areaTime.put("startMinute", "1410");//预约开始时间23:30
            areaTime.put("endMinute", "1440");//预约结束时间24:00
            areaTime.put("price",price);//该场地组全场的单价
            areaTimeInfos.add(areaTime);

            //构建请求参数
            JSONObject object = new JSONObject();
            object.put("depositAmount",price);
            object.put("depositCardId", depositCardId);
            object.put("areaTimeInfos", areaTimeInfos);

            object.put("groupId", groupId);//场地id
            object.put("memberId", memberId);
            object.put("memo", "自动化脚本创建的场地预约");
            object.put("objectId", RandomStringUtil.randomString(16));
            object.put("receivableAmount", "0.00");
            object.put("reserveDay", reserveDay);//预约当天
            object.put("studioId", xmAppApi.getLoginInfo().getStudioId());
            object.put("suiteId", suiteId);//场地组id
            object.put("venueAreaId", areaId);

            //调用请求
            xmAppApi.doRequest(RequestType.JSON, params, object.toString(), headers).assetsSuccess(true);
            String voucherId = xmAppApi.getBodyInJSON().getJSONObject("result").getString("id");//订单ID
            Thread.sleep(3000);
            //校验c端订单详情
            Assert.assertEquals(XMJSONPath.readPath(orderCTools.getDetail(voucherId), "$.result.state"), "PAID", "创建签单订单成功,但订单状态不是已完成");
            Assert.assertEquals(XMJSONPath.readPath(orderCTools.getDetail(voucherId), "$.result.source"), "ONLINE_MALL", "C端创建的签单订单,订单来源非会员创建");

            //检验c端我的预约场地数据+1
            Assert.assertTrue(Integer.parseInt(XMJSONPath.readPath(venueAreaTools.pageMemberVenueBooking("RESERVED",memberId),"$.result.total"))==bookingNum+1);
            //检验c端预约详情状态为已预约
            Assert.assertEquals(XMJSONPath.readPath(venueAreaTools.getByVoucher(voucherId), "$.result.state"),"RESERVED");//预约类型：已预约

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

            //操作c端取消预约并且预约详情为已取消
            String venueBookingRecordId = XMJSONPath.readPath(venueAreaTools.getByVoucher(voucherId), "$.result.id");
            venueAreaTools.getCheckInIdentifier(venueBookingRecordId);//检验入场码生效
            venueAreaTools.cancelVenueBookingRecord(venueBookingRecordId);
            Assert.assertEquals(XMJSONPath.readPath(venueAreaTools.getByVoucher(voucherId), "$.result.state"),"CANCELLED");//预约类型：已取消

            //检验c端储值卡金额退回
            JSONObject jsBody = minCardTools.fetchPageOfConsumeRecord(depositCardId, depositBenefitId);
            Assert.assertTrue(Integer.parseInt(XMJSONPath.readPath(jsBody, "$.result.total")) == total + 2);
            Assert.assertEquals(XMJSONPath.readPath(jsBody, "$.result.records[0].consumeType"), "DEPOSIT_DISCARD_SIGN_ORDER");//消耗类型：作废签单
            Assert.assertEquals(XMJSONPath.readPath(jsBody, "$.result.records[0].changeOfGiveBalance"), price);//退回赠送金额

            //检验b端订单变成已作废
            Assert.assertEquals(XMJSONPath.readPath(orderTools.getDetail(voucherId,info), "$.result.state"), "DISCARD");
            //清理数据
            //b端删除场地组
            venueAreaTools.saveVenueAreaSuite(suiteId,"DELETE",info);
            //b端删除场地
            venueAreaTools.deleteVenueArea(groupId,info);
        }
    }
}

