package com.xiaomai.cases.polar.coupon;

import com.alibaba.fastjson.JSONObject;
import com.xiaomai.basetest.BaseTestImpl;
import com.xiaomai.client.DataUserInfo;
import com.xiaomai.enums.ApiModule;
import com.xiaomai.enums.RequestType;
import com.xiaomai.enums.Terminal;
import com.xiaomai.utils.CommUtil;
import com.xiaomai.utils.XMJSONPath;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.testng.Assert;

import java.util.ArrayList;
import java.util.List;

/**
 * 小麦乐动优惠券工具类
 *
 * @author adu
 * data 2024/7/25 17:32
 */
@Component("couponTools")
public class CouponTools extends BaseTestImpl {

    /**
     * 同一个ApiModule下的登录信息封装出一个类，减少代码冗余
     *
     * @param apiName
     * @param userInfo
     */
    public void setUP(String apiName, DataUserInfo... userInfo) {
        dataApi.setApiModule(ApiModule.Polar_Coupon)
                .setApiName(apiName)
                .setTerminal(Terminal.B);
        super.beforeDataRequest(userInfo);
    }

    /**
     * 创建优惠券
     *
     * @param useThresholdType      使用门槛：1无门槛 WITHOUT 2达到条件可用 THRESHOLD
     * @param receiveTimesUpperType 每人领取次数限制：1每人限领 FIXED 2不限制 WITHOUT
     * @param memberStatusLimits    可领取会员类型 ["POTENTIAL", "NORMAL", "HISTORY"] 一共3种，可以自己自定义选其中的某个或者全部
     * @param couponName            优惠券的名称
     * @param allScope              适用范围 全部：true，非全部：false
     * @param preferentialType      优惠方式：1金额 CERTAIN 2折扣 DISCOUNT
     * @param quantity              发放数量
     * @param validPeriodType       使用有效期方式：1固定期限 ABSOLUTE  2领取后生效 RELATIVE
     * @param memo                  备注
     * @param useForActivity        是否用于营销活动，true，false

     * @return 优惠券ID
     */
    public String createCoupon(String useThresholdType, String receiveTimesUpperType, List<String> memberStatusLimits, String couponName,
                               Boolean allScope, String preferentialType, int quantity, String validPeriodType, String memo,Boolean useForActivity) {

        setUP("API_createCoupon");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        JSONObject receiveCondition = new JSONObject();
        body.put("useThresholdType", useThresholdType);
        if (useThresholdType.equals("THRESHOLD")) {//使用门槛是达到条件可用
            body.put("useThreshold", 10);//目前没写成动态传参，固定为10元
        }
        receiveCondition.put("receiveTimesUpperType", receiveTimesUpperType);
        if (receiveTimesUpperType.equals("FIXED")) {
            receiveCondition.put("receiveTimesUpper", 1);//每人限领次数
        }
        receiveCondition.put("memberStatusLimits", memberStatusLimits);//可领取会员类型
        body.put("receiveCondition", receiveCondition);
        body.put("name", couponName);
        body.put("allScope", allScope);
        if (allScope.equals(false)) {//适用范围不是选全部时
            List<String> scope = new ArrayList<>();
            scope.add("TRAINING_CAMP");
            body.put("scope", scope);//此处固定写了适用范围为训练营
        }
        body.put("preferentialType", preferentialType);

        if (preferentialType.equals("CERTAIN")) {//优惠方式选择金额
            body.put("preferential", 10);
        }
        if (preferentialType.equals("DISCOUNT")) {//优惠方式选择金额
            body.put("preferential", 6.8);
        }

        body.put("quantity", quantity);
        body.put("validPeriodType", validPeriodType);
        if (validPeriodType.equals("RELATIVE")) {//有效期：领取后生效
            body.put("relativeDay", 1); //使用有效期：领取后 1天内
        }
        if (validPeriodType.equals("ABSOLUTE")) {//有效期：固定时间
            body.put("validPeriodStartTime", CommUtil.oneKeyGetAddDay(1));//有效期的开始时间:明天的0点
            body.put("validPeriodEndTime", CommUtil.getNDayEndTimeTamp(5));//有效期的结束时间：5天后的 23：59：59
        }
        if (null != memo || !memo.isEmpty()) {
            body.put("memo", memo);
        }
        body.put("useForActivity", useForActivity);
        if(useForActivity.equals(true)){ //如果开启用于营销活动
            body.put("quantity", -1); //发放数量不限制
            List<String> memberStatusLimitsA=new ArrayList<>();
            memberStatusLimitsA.add("POTENTIAL");
            memberStatusLimitsA.add("NORMAL");
            memberStatusLimitsA.add("HISTORY");
            receiveCondition.put("memberStatusLimits", memberStatusLimitsA);//可领取会员类型,默认选中所有
            receiveCondition.put("receiveTimesUpperType", "WITHOUT");//每人领取次数不限制
            body.put("receiveCondition", receiveCondition); //领取限制放开

            body.put("validPeriodType", "RELATIVE");//有效期：领取后生效[用于营销活动的优惠券，只支持选择领取后生效]
            body.put("validPeriodStartTime",null);
            body.put("validPeriodEndTime",null);
            body.put("relativeDay","30");//领取30天内有效
        }

        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs);
        Assert.assertTrue(Boolean.valueOf(XMJSONPath.readPath(dataApi.getApi_response(),"$.success"))==true,"调用接口返回结果："+XMJSONPath.readPath(dataApi.getApi_response(),"$.message"));
        return XMJSONPath.readPath(dataApi.getApi_response(), "$.result");

    }

    /**
     * 创建用于营销活动的优惠券
     * @param useThresholdType:"WITHOUT"无门槛，"THRESHOLD"达到条件可用
     * @param couponName
     * @param allScope 全部商品可用true，指定商品可用false
     * @param userInfos
     * @return
     */

    public String createStudioCoupon(String useThresholdType, String couponName, Boolean allScope,DataUserInfo...userInfos) {

        setUP("API_createCoupon",userInfos);

        String[] memberStatusLimits = {"POTENTIAL", "NORMAL", "HISTORY"};
        JSONObject receiveCondition = new JSONObject();
        receiveCondition.put("receiveTimesUpperType","WITHOUT");//每人领取次数不限制
        receiveCondition.put("memberStatusLimits",memberStatusLimits);//可领取会员类型

        JSONObject body = new JSONObject();
        body.put("useThresholdType", useThresholdType);
        if (useThresholdType.equals("THRESHOLD")) {//使用门槛是达到条件可用
            body.put("useThreshold", 10);//目前没写成动态传参，固定为10元
        }
        body.put("useForActivity", true);//开启营销活动开关
        body.put("quantityLimit", false);//若为true，则填写quantity
        body.put("receiveCondition", receiveCondition);
        body.put("name",couponName);
        body.put("validPeriodType", "RELATIVE");//有效期：领取后生效
        body.put("validPeriodStartTime",null);
        body.put("validPeriodEndTime",null);
        body.put("relativeDay","30");//领取30天内有效
        body.put("memo", "自动化脚本生成用于营销活动的优惠券");
        body.put("quantity","-1");//发放数量不限制
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("allScope",allScope);//全部可用
        if(allScope.equals(false)){
            String[] scope = {"MEMBER_CARD", "TRAINING_CAMP", "SINGLE_RESERVE", "EXPERIENCE_CARD"};//指定会员卡、体验卡、训练营、单次约课
            body.put("scope",scope);//指定商品范围
            body.put("preferentialType","DISCOUNT");//打折
            body.put("preferential",8.8);//打8.8折
        }else{
            body.put("preferentialType","CERTAIN");
            body.put("preferential",10);//直减10元
        }

        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs);
        Assert.assertTrue(Boolean.valueOf(XMJSONPath.readPath(dataApi.getApi_response(),"$.success"))==true,"调用接口返回结果："+XMJSONPath.readPath(dataApi.getApi_response(),"$.message"));
        return XMJSONPath.readPath(dataApi.getApi_response(), "$.result");

    }

    /**
     * 查看优惠券列表
     * @param nameLike 全局搜索中 根据优惠券名称搜索
     * @param status 列表中根据优惠券状态搜索
     */
    public void getStudioCouponList(String nameLike,String status){
        setUP("API_getStudioCouponList");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("current",0);
        body.put("size",100);
        if (!StringUtils.isEmpty(nameLike)) {
            body.put("nameLike", nameLike);
        }
        if (!StringUtils.isEmpty(status)) {
            body.put("status", status);
        }
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs).assetsSuccess(true);

    }

    /**
     * 查看优惠券详情
     * @param couponId
     */
    public void getCouponDetail(String couponId, DataUserInfo... dataUserInfos){
        setUP("API_getCouponDetail");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("id",couponId);
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs).assetsSuccess(true);
    }

    /**
     * 失效优惠券
     * @param couponId
     */
    public void InvalidCoupon(String couponId){
        setUP("API_ InvalidCoupon");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("id",couponId);
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs);
        Assert.assertTrue(Boolean.valueOf(XMJSONPath.readPath(dataApi.getApi_response(),"$.success"))==true,"调用接口返回结果："+XMJSONPath.readPath(dataApi.getApi_response(),"$.message"));

    }

    /**
     * 修改优惠券的剩余数量
     * @param couponId 优惠券ID
     * @param inventory 修改后的剩余数量
     */
    public void modifyCouponInventory(String couponId,int inventory){
        setUP("API_modifyCouponInventory");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("id",couponId);
        body.put("inventory",inventory);
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs);
        Assert.assertTrue(Boolean.valueOf(XMJSONPath.readPath(dataApi.getApi_response(),"$.success"))==true,"调用接口返回结果："+XMJSONPath.readPath(dataApi.getApi_response(),"$.message"));

    }


    /**
     * 任务中心
     */
    public void getStudioBatchTaskPage(){
        setUP("API_getStudioBatchTaskPage");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("current", 0);
        body.put("size", 500);
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs).assetsSuccess(true);

    }

    /**
     * 优惠券详情-查看已发放/已使用优惠券
     * @param couponId 优惠券ID
     * @param status 优惠券的适用状态，""表示已发放列表的状态，USED是已使用
     */
    public void getCouponReceiveRecord(String couponId,String status){
        setUP("API_getCouponReceiveRecord");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("current", 0);
        body.put("size", 500);
        body.put("couponId", couponId);
        body.put("status", status);
        if(status.isEmpty()){
            body.put("status", null);
        }
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs);
        Assert.assertTrue(Boolean.valueOf(XMJSONPath.readPath(dataApi.getApi_response(),"$.success"))==true,"调用接口返回结果："+XMJSONPath.readPath(dataApi.getApi_response(),"$.message"));

    }

    /**
     * 会员详情-查看会员已领取/已发放优惠券
     * @param memberId 会员ID
     * @param status 优惠券状态：待使用"AVAILABLE"， 已使用"USED"， 已过期"EXPIRED"，已作废"ABANDONED"
     */
    public void getMemberReceivedCoupon(String memberId,String status){
        setUP("API_getMemberReceivedCoupon");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("current", 0);
        body.put("size", 500);
        body.put("receiverId", memberId);
        body.put("status", status);
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs).assetsSuccess(true);
    }

    /**
     * 作废会员已领取/已发放的优惠券
     * @param recordId 对应的记录ID
     */
    public void abandonMembercouponReceiveRecord(String recordId,DataUserInfo...userInfo){
        setUP("API_abandonMembercouponReceiveRecord",userInfo);
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("id", recordId);
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs);
        Assert.assertTrue(Boolean.valueOf(XMJSONPath.readPath(dataApi.getApi_response(),"$.success"))==true,"调用接口返回结果："+XMJSONPath.readPath(dataApi.getApi_response(),"$.message"));


    }

    /**
     * 会员名下的优惠券
     * @param receiverId
     * @param status
     * @param userInfo
     * @return
     */
    public JSONObject pageMemberReceivedCoupon(String receiverId,String status,DataUserInfo...userInfo){
        setUP("API_pageMemberReceivedCoupon",userInfo);
        JSONObject body = new JSONObject();
        body.put("current", 0);
        body.put("receiverId", receiverId);
        body.put("size", 20);
        body.put("status", status);
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs);

        Assert.assertTrue(Boolean.valueOf(XMJSONPath.readPath(dataApi.getApi_response(),"$.success"))==true,"调用接口返回结果："+XMJSONPath.readPath(dataApi.getApi_response(),"$.message"));
        return dataApi.getBodyInJSON();
    }

    //定向发券
    public JSONObject batchSendCoupon(String couponId, String receiverId,DataUserInfo...userInfos) {
        dataApi.setApiModule(ApiModule.Polar_Coupon)
                .setApiName("API_batchSendCoupon")
                .setTerminal(Terminal.B);
        super.beforeDataRequest(userInfos);

        List receiverIds = new ArrayList();
        receiverIds.add(receiverId);

        //构建请求参数
        JSONObject object = new JSONObject();
        object.put("couponId", couponId);
        object.put("receiverIds",receiverIds);
        object.put("brandId", dataApi.getLoginInfo().getBrandId());
        object.put("studioId", dataApi.getLoginInfo().getStudioId());
        object.put("operatorId", dataApi.getLoginInfo().getAdminId());

        dataApi.doRequest(RequestType.JSON, dataparams, object.toString(), dataheadrs).assetsSuccess(true);
        return dataApi.getBodyInJSON();
    }
}

    