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.coupon.CouponTools;
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.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;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author zxy
 * @Description
 * @Date 2024/12/5 15:08
 */
public class TestSignAreaTimesOrder extends XMBaseTest {
    Tools tools = new Tools();
    CouponTools couponTools = new CouponTools();
    @Resource(name = "venueAreaTools")
    VenueAreaTools venueAreaTools;
    @Resource(name = "cardTools")
    CardTools cardTools;
    @Resource(name = "orderTools")
    OrderTools orderTools;
    DataUserInfo info = new DataUserInfo();
    String depositCardId;
    String price = "199";//设置场地全场价格
    String memberId;
    String depositAmount;
    String suiteId;
    String groupId;
    String userCouponId;
    @BeforeMethod
    public void beforeTest() {
        xmAppApi.setApiModule(ApiModule.Polar_Setting)
                .setApiName("API_signAreaTimesOrder")
                .setLoginUser(LoginAccount.GYM_PROD)
                .setTerminal(Terminal.B);
        dal.setCase_owner("zyx")
                .setCase_name(Thread.currentThread().getStackTrace()[1].getFileName().split("\\.")[0]);
        super.beforeTest();

    }

    @Test(description = "代预约场地")
    public void testSignAreaTimesOrder() {
        //获取当天的0点
        String reserveDay = String.valueOf(TimeUtils.getTodayTime());
        //1.创建场地
        String title = "代预约场地" + System.currentTimeMillis();
        groupId = venueAreaTools.createVenueArea(title);
        //2.创建场地组
        String suiteName = "西湖场地组" + RandomStringUtil.randomString(5);
        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);
        //检验该场地组时间块有数值
        Assert.assertTrue(venueAreaTools.getSuiteProxyReserveTimeBlock(reserveDay,suiteId).getJSONObject("result").getJSONArray("venueReserveTimeBlockVOS").size() > 0);
        //获取用户
        memberId = tools.search("NORMAL", "NORMAL").getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");

        //查询启用中的储值卡，获取储值卡id
        String cardId = XMJSONPath.readPath(cardTools.fetchPageOfMemberCard("DEPOSIT_CARD"), "$.result.records[0].id");
        String latestSnapshotId = XMJSONPath.readPath(cardTools.fetchDetailById(cardId), "$.result.latestSnapshotId");
        //购买1张储值卡
        cardTools.signOrderDeposit(cardId, latestSnapshotId, memberId, "0.00", "1000.00");
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //获取会员可使用的储值卡
        depositCardId = XMJSONPath.readPath(orderTools.fetchUserCardList("DEPOSIT", memberId, "NORMAL"), "$.result[0].id");


        //查询是否有可使用的优惠券，如果没有创建1张
        String couponName = "场地预约优惠券";
        couponTools.getStudioCouponList(couponName, "CLAIMABLE");
        String couponId = "";
        if (XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").size() == 1) {
            couponId = XMJSONPath.readPath(dataApi.getApi_response(), "$.result.records[0].id");
        } else {//创建新的用于场地预约的优惠券-固定金额10元
            List<String> memberStatusLimitsA = new ArrayList<>();
            memberStatusLimitsA.add("POTENTIAL");
            memberStatusLimitsA.add("NORMAL");
            memberStatusLimitsA.add("HISTORY");

            couponId = couponTools.createCoupon("WITHOUT", "WITHOUT", memberStatusLimitsA, couponName+RandomStringUtil.randomString(5), true,
                    "CERTAIN", 10, "RELATIVE", couponName + "", false);
        }

        //定向发放优惠券
        couponTools.batchSendCoupon(couponId, memberId);
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //获取会员名下待使用的优惠券
        userCouponId = couponTools.pageMemberReceivedCoupon(memberId,"AVAILABLE").getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");

        depositAmount = String.valueOf(Integer.parseInt(price)-10-1);//场地价格-优惠券抵扣10元-直减/折扣1元

        //允许场地冲突并且预约场地
        Assert.assertEquals((venueAreaTools.checkAllowProxyVenueBooking("1410","1440",price,groupId,reserveDay,suiteId,areaId)),"true");
        //检验该场地冲突
        Assert.assertEquals(XMJSONPath.readPath(venueAreaTools.checkMemberVenueBookingConflict1("1410","1440",price,groupId,reserveDay,suiteId,areaId,"",title,suiteName,memberId),"$.result.conflict"),"false");

        //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 bookingAreaTimesInfo = new JSONObject();
        bookingAreaTimesInfo.put("areaTimeInfos", areaTimeInfos);
        bookingAreaTimesInfo.put("deductionAmount", 1);
        bookingAreaTimesInfo.put("groupId", groupId);
        bookingAreaTimesInfo.put("reserveDay", reserveDay);
        bookingAreaTimesInfo.put("suiteId", suiteId);
        bookingAreaTimesInfo.put("venueAreaId", areaId);

        //构建请求参数
        JSONObject object = new JSONObject();
        object.put("depositAmount", depositAmount);
        object.put("depositCardId", depositCardId);
        object.put("bookingAreaTimesInfo", bookingAreaTimesInfo);
        object.put("memberId", memberId);
        object.put("memo", "自动化脚本创建的代预约");
        object.put("objectId", RandomStringUtil.randomString(16));
        object.put("userCouponId", userCouponId);
        object.put("receivableAmount", "0.00");
        object.put("studioId", xmAppApi.getLoginInfo().getStudioId());
        object.put("brandId", xmAppApi.getLoginInfo().getBrandId());
        object.put("operatorId", xmAppApi.getLoginInfo().getAdminId());

        xmAppApi.doRequest(RequestType.JSON,params,object.toString(),headers).assetsSuccess(true);

        String voucherId = xmAppApi.getBodyInJSON().getJSONObject("result").getString("id");//订单ID
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        //校验订单详情
        JSONObject res = orderTools.getDetail(voucherId);
        Assert.assertEquals(XMJSONPath.readPath(res, "$.result.state"), "PAID", "创建签单订单成功,但订单状态不是已完成");
        Assert.assertEquals(XMJSONPath.readPath(res,"$.result.source"), "OFFLINE_SOURCE");

        //根据订单ID获取订场记录
        JSONObject res1 = venueAreaTools.getByVoucher1(voucherId);
        Assert.assertEquals(XMJSONPath.readPath(res1, "$.result.state"),"RESERVED");//预约类型：已预约
        String id = res1.getJSONObject("result").getString("id");

        //操作b端取消预约并且预约详情为已取消
        venueAreaTools.cancelVenueBookingRecord1(id);
        Assert.assertEquals(XMJSONPath.readPath(venueAreaTools.getVenueBookingRecordDetail1(id), "$.result.state"),"CANCELLED");//预约类型：已取消

        //检验b端订单变成已作废
        Assert.assertEquals(XMJSONPath.readPath(orderTools.getDetail(voucherId), "$.result.state"), "DISCARD");

    }

    @Test(description = "清理数据",priority =1)
    public void del()
    {

        //b端场地组移除场地
        venueAreaTools.unbindVenueAreas(suiteId,groupId);
        //b端删除场地组
        venueAreaTools.saveVenueAreaSuite(suiteId,"DELETE");
        //b端删除场地
        venueAreaTools.deleteVenueArea(groupId);
        //作废优惠券
        couponTools.abandonMembercouponReceiveRecord(userCouponId);
        //退优惠券
        cardTools.refundOrderDeposit(depositCardId,"1000","0","0",memberId,"0",new JSONArray());
    }

}
