package com.xiaomai.cases.polar.coupon;

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.schedule.camp.SelectTargetTrainingCampAndGetInfo;
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.RandomStringUtil;
import com.xiaomai.utils.XMJSONPath;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

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

/**
 * 测试定向发放优惠券
 *
 * @author adu
 * data 2024/7/27 17:16
 */

public class TestBatchSendCouponToMember extends SelectTargetTrainingCampAndGetInfo {
    @Resource(name = "couponTools")
    CouponTools couponTools;
    String memberId = "";
    @Resource(name = "tools")
    Tools tools;

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

    @Resource(name = "orderTools")
    OrderTools orderTools;
    String title = "";
    String couponId = "";

    @BeforeClass
    public void beforeTest() {
        setTestInfo(ApiModule.Polar_Coupon, "API_batchSendCoupon", LoginAccount.ADU_PROD, Terminal.B, "adu");
        super.beforeTest();
    }

    @Test(description = "定向发放优惠券 to 会员")
    public void testBatchSendCouponToMember() throws InterruptedException {
        //1.创建1个新的优惠券
        List<String> memberStatusLimits = new ArrayList<>();
        memberStatusLimits.add("POTENTIAL");
        memberStatusLimits.add("NORMAL");
        memberStatusLimits.add("HISTORY");
        title = "有门槛限领适用全部" + RandomStringUtil.randomString(3);
        couponId = couponTools.createCoupon("THRESHOLD", "FIXED", memberStatusLimits, title, true,
                "CERTAIN", 2, "RELATIVE", title + "优惠方式选择金额，满10元可以减10元，领取后1天内有效",false);
        //2.创建成功后，列表增加一条刚新建的优惠券，搜索可领取优惠券
        couponTools.getStudioCouponList("", "CLAIMABLE");
        Long goalData = XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("id").equals(couponId)).count();
        Assert.assertTrue(goalData == 1, "刚创建的优惠券在列表中搜索，后端没返回数据");

        //3.查看优惠券详情，check 优惠券的总数量，剩余数量，已发放数量
        couponTools.getCouponDetail(couponId);
        int quantityBefore = Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.quantity"));
        int inventoryBefore = Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.inventory"));
        int receivedBefore = Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.received"));
        Double preferential=Double.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.preferential"));

        //4.操作定向发放优惠券
        //搜索目标会员
        String phone = "15558121569";
        memberId = trainingTools.searchTargerMember(phone);
        if (memberId.isEmpty()) {
            memberId = tools.create("杜君丽", phone).getString("result");
        }
        JSONObject body = new JSONObject();
        List<String> receiverIds = new ArrayList<>();
        receiverIds.add(memberId);
        body.put("operatorId", xmAppApi.getLoginInfo().getAdminId());
        body.put("studioId", xmAppApi.getLoginInfo().getStudioId());
        body.put("brandId", xmAppApi.getLoginInfo().getBrandId());
        body.put("couponId", couponId);
        body.put("receiverIds", receiverIds);
        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"));
        String taskId = XMJSONPath.readPath(xmAppApi.getApi_response(), "$.result");

        //check任务中心生成一条任务
        Thread.sleep(2000);
        couponTools.getStudioBatchTaskPage();
        Long goalTask = XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("id").equals(taskId)).count();
        Assert.assertTrue(goalTask == 1, "刚操作的定向发放优惠券给学员，在任务中心查看，后端没返回目标数据");

        XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("id").equals(taskId)).forEach(object ->
                Assert.assertTrue(object.getInteger("totalNumber") == 1 && object.getInteger("failNumber") == 0 &&
                        object.getInteger("successNumber") == 1));

        //查看详情
        couponTools.getCouponDetail(couponId);
        Assert.assertTrue(Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.quantity"))==quantityBefore,"优惠券发放给会员后，总数量变化了，应该不变");
        Assert.assertTrue(Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.inventory"))+1==inventoryBefore,"优惠券发放给会员后，剩余库存没减少");
        Assert.assertTrue(Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.received"))-1==receivedBefore,"优惠券发放给会员后，已发放数据不对");

        //优惠券详情-已发放记录
        couponTools.getCouponReceiveRecord(couponId,"");
       Long countR= XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("couponId").equals(couponId)).count();
       Assert.assertTrue(countR==1,"操作定向发放优惠券后，发给一个学员，然后在优惠券详情已发放列表没匹配到数据");
       String goalRecordId=XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
               e.getString("couponId").equals(couponId)).map(e->e.getString("id")).findFirst().orElse(null);

        //会员详情-优惠券-已发放优惠券:待使用列表check
        couponTools.getMemberReceivedCoupon(memberId,"AVAILABLE");
        Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("id").equals(goalRecordId)).count()==1,"操作定向发放优惠券后，发给一个学员，然后在会员详情-优惠券-待使用列表没匹配到数据");

        //操作修改剩余库存
        couponTools.modifyCouponInventory(couponId,10);

        //剩余库存修改成功后，优惠券详情check 总数据，剩余库存，已发放数量
        couponTools.getCouponDetail(couponId);
        Assert.assertTrue(Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.quantity"))==11,"修改剩余库存后，优惠券的总数量对不上了");
        Assert.assertTrue(Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.inventory"))==10,"修改剩余库存后，剩余库存数量对不上");
        Assert.assertTrue(Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.received"))==1,"优惠券发放给会员后，已发放数据不对");

        //操作失效优惠券
        couponTools.InvalidCoupon(couponId);
        //查看优惠券详情，check状态
        couponTools.getCouponDetail(couponId);
        Assert.assertTrue(XMJSONPath.readPath(dataApi.getApi_response(),"$.result.status").equals("VOIDED"),"操作失效优惠券后，查看优惠券详情，后端返回的状态值不是VOIDED");

        //操作给刚发放优惠券的会员 去买训练营（使用优惠券）
        trainingTools.doSignCampOrder(memberId,this.price-preferential,this.campId,goalRecordId);
        String orderId=XMJSONPath.readPath(dataApi.getApi_response(),"$.result");

        //优惠券详情-已使用优惠券check
        couponTools.getCouponReceiveRecord(couponId,"USED");
        Long countRUse= XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().
                filter(e ->
                e.getString("couponId").equals(couponId)).
                filter(e ->
                        e.getString("status").equals("USED")).count();
        Assert.assertTrue(countRUse==1,"定向发放优惠券后，学员使用了优惠券，在优惠券详情-已使用记录中数据没匹配上");

        //会员详情-优惠券-已使用优惠券 为 1check
        couponTools.getMemberReceivedCoupon(memberId,"USED");
        Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("id").equals(goalRecordId)). filter(e ->
                e.getString("status").equals("USED")).count()==1,"会员使用优惠券后，会员详情-优惠券-已使用优惠券列表数据没有目标数据");

        //会员详情-优惠券-目标待使用优惠券为0
        couponTools.getMemberReceivedCoupon(memberId,"AVAILABLE");
        Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("id").equals(goalRecordId)). filter(e ->
                e.getString("status").equals("AVAILABLE")).count()==0,"会员使用优惠券后，会员详情-优惠券-待使用优惠券列表数据还有目标数据");

        //用完优惠券后check，优惠券详情已核销数量
        couponTools.getCouponDetail(couponId);
        Assert.assertTrue(Integer.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result.verified"))==1,"优惠券发放给会员,会员适用后，对应优惠券已使用数量不对");

        //操作作废订单，check优惠券是否返还给会员，优惠券中已发放数量中核销数量是否同步更新
        orderTools.discard(orderId,"重复录入","自动化测试作废训练营订单");

        //优惠券详情-已使用优惠券check
        couponTools.getCouponReceiveRecord(couponId,"USED");
       Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().
               filter(e ->
                       e.getString("couponId").equals(couponId)).
               filter(e ->
                       e.getString("status").equals("USED")).count()==0,"学员使用了优惠券报名，订单被作废后，在优惠券详情-已使用记录中数据还存在");

        //会员详情-优惠券-已使用优惠券check（退）
        couponTools.getMemberReceivedCoupon(memberId,"USED");
        Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("id").equals(goalRecordId)). filter(e ->
                e.getString("status").equals("USED")).count()==0,"会员使用优惠券后，再操作作废订单，会员详情-优惠券-已使用优惠券列表数据还有目标数据");
        //会员详情-优惠券-已发放check（+1）
        couponTools.getMemberReceivedCoupon(memberId,"AVAILABLE");
        Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("id").equals(goalRecordId)).count()==1,"会员使用优惠券下单，作废订单后，然后在会员详情-优惠券-待使用列表没匹配到数据");

        //优惠券详情-已发放记录-操作作废优惠券
        couponTools.abandonMembercouponReceiveRecord(goalRecordId);

        //优惠券详情，已发放记录列表，优惠券状态为已作废
        couponTools.getCouponReceiveRecord(couponId,"");
        Long countRAbandon= XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("couponId").equals(couponId)).filter(e ->
                e.getString("status").equals("ABANDONED")).count();
        Assert.assertTrue(countR==1,"操作定向发放优惠券后，再作废优惠券，然后在优惠券详情已发放列表没匹配到数据");

        //会员详情-优惠券-已作废优惠券check
        couponTools.getMemberReceivedCoupon(memberId,"ABANDONED");
        Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("id").equals(goalRecordId)).filter(e ->
                e.getString("status").equals("ABANDONED")).count()==1,"作废会员优惠券后，会员详情-优惠券-已作废优惠券列表数据没有目标数据");
        //会员详情-优惠券-已发放check（-1）
        couponTools.getMemberReceivedCoupon(memberId,"AVAILABLE");
        Assert.assertTrue(XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").toJavaList(JSONObject.class).stream().filter(e ->
                e.getString("id").equals(goalRecordId)).filter(e ->
                e.getString("status").equals("AVAILABLE")).count()==0,"作废会员优惠券后，然后在会员详情-优惠券-待使用列表还能匹配到数据");

        //最后要删除刚创建的训练营活动
        trainingTools.deleteTraining(this.campId);

    }
}

    