package com.xiaomai.cases.polar.training;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.client.DataUserInfo;
import com.xiaomai.enums.ApiModule;
import com.xiaomai.enums.RequestType;
import com.xiaomai.enums.Terminal;
import com.xiaomai.utils.*;
import org.springframework.stereotype.Component;
import org.testng.Assert;
import org.testng.Reporter;

import java.util.List;

/**
 * 训练营活动相关工具类
 *
 * @author adu
 * data 2024/7/3 15:12
 */
@Component("trainingTools")
public class TrainingTools extends XMBaseTest {
    String applyStartTime1 = String.valueOf(CommUtil.getWholeHourTimestamp()); //当前时间的整点
    String applyEndTime1 = CommUtil.oneKeyGetAddDay(1);//明天0点
    String openStartDate0 = applyEndTime1;
    String openEndDate0 = CommUtil.getNDayEndTimeTamp(2);//后天23：59：59

    long currentTimestamp = System.currentTimeMillis();
    // 在当前时间的基础上，加上10分钟（1000毫秒*60*10）
    long futureTimestamp = currentTimestamp + 600000;
    String futureTimestampS = String.valueOf(futureTimestamp);

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

    /**
     * 新建训练营活动：保存并发布
     *
     * @param applyStartTime    报名开始时间
     * @param applyEndTime      报名结束时间
     * @param courseId          关联课程ID
     * @param openStartDate     开营开始时间
     * @param openEndDate       开营结束时间
     * @param price             售卖价格
     * @param title             训练营活动名称
     * @param totalClassHour    总课次数
     * @param traineeLowerLimit 开营人数
     * @param trainerList       上课教练
     * @param xcxSaleStatus     是否开启小程序售卖 YES，NO
     * @return 创建的训练营活动ID
     */
    public String createThenPublishTraining(String applyStartTime, String applyEndTime, String courseId, String openStartDate,
                                            String openEndDate, Double price, String title, int totalClassHour,
                                            int traineeLowerLimit, List<String> trainerList, String xcxSaleStatus) {
        setUP("API_createThenPublishTraining");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId()); // 场馆
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("applyEndTime", applyEndTime);//报名结束时间
        body.put("applyStartTime", applyStartTime);//报名开始时间
        body.put("courseId", courseId); //关联课程ID
        body.put("creatorId", dataApi.getLoginInfo().getAdminId()); // 创建人即操作者
        body.put("openEndDate", openEndDate); //开营开始时间
        body.put("openStartDate", openStartDate); //开营结束时间
        body.put("price", price); //售卖价格
        body.put("surfaceUrl", "https://xiaomai-res.oss-cn-hangzhou.aliyuncs.com/xmfit/course_cover/training_camp_0.png"); // 默认活动封面图
        body.put("title", title); // 训练营活动名称：杭州自动化测试训练营
        body.put("totalClassHour", totalClassHour); // 总课次数
        body.put("traineeLowerLimit", traineeLowerLimit); // 开营人数
        body.put("traineeUpperLimit", 99); // 人数上限
        body.put("trainerList", trainerList); // 上课教练
        body.put("xcxSaleStatus", xcxSaleStatus); //是否开启小程序售卖
        body.put("underlinePrice", 99999.99); //划线价
        //图文介绍不设置，所以回归时check下 图文介绍
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs);
        if (XMJSONPath.readPath(dataApi.getApi_response(), "$.message").equals("训练营名称不能重复")) {
            return "";
        }
        Assert.assertTrue(Boolean.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.success")) == true, "调用接口返回结果：" + XMJSONPath.readPath(dataApi.getApi_response(), "$.message"));
        return XMJSONPath.readPath(dataApi.getApi_response(), "$.result");
    }

    /**
     * 引用时可以继承 BaseCreateTrainingData 这个类，然后直接传值就可以
     * 价格0元，一键创建已发布且报名中的训练营活动
     *
     * @param applyStartTime 报名开始时间，要早于第二天的0点，最好是晚于当前时间半个小时
     * @param courseId       需要传入课程ID
     * @param trainerList    需要传入教练
     * @return 活动ID
     */
    public String oneKeyCreateTraining(String courseId, List<String> trainerList, String applyStartTime) {
        setUP("API_createThenPublishTraining");
        String courseName = "训练营课程-感统课";
        String trainingTitle = "三期36天训练营感统课" + RandomStringUtil.randomString(5);
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId()); // 场馆
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("applyEndTime", applyEndTime1);//报名结束时间
        body.put("applyStartTime", applyStartTime);//报名开始时间
        body.put("courseId", courseId); //关联课程ID
        body.put("creatorId", dataApi.getLoginInfo().getAdminId()); // 创建人即操作者
        body.put("openEndDate", openEndDate0); //开营结束时间
        body.put("openStartDate", openStartDate0); //开营开始时间
        body.put("price", 0); //售卖价格
        body.put("surfaceUrl", "https://xiaomai-res.oss-cn-hangzhou.aliyuncs.com/xmfit/course_cover/training_camp_0.png"); // 默认活动封面图
        body.put("title", trainingTitle);
        body.put("totalClassHour", 2); // 总课次数
        body.put("traineeLowerLimit", 1); // 开营人数
        body.put("traineeUpperLimit", 99); // 人数上限
        body.put("trainerList", trainerList); // 上课教练
        body.put("xcxSaleStatus", "YES"); //开启小程序售卖
        body.put("underlinePrice", 19.9); //划线价
        //图文介绍不设置，所以回归时check下 图文介绍
        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");


    }


    /**
     * 提供训练营活动名称，课程ID和教练ID 快速创建未发布的活动
     *
     * @param title       训练营活动名称，可以传空，有默认值
     * @param courseId
     * @param trainerList
     * @return
     */
    public String createTrainingNoPublish(String title, String courseId, List<String> trainerList) {
        setUP("API_createTrainingNoPublish");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId()); // 场馆
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("applyEndTime", applyEndTime1);//报名结束时间
        body.put("applyStartTime", applyStartTime1);//报名开始时间
        body.put("courseId", courseId); //关联课程ID
        body.put("creatorId", dataApi.getLoginInfo().getAdminId()); // 创建人即操作者
        body.put("openEndDate", openEndDate0); //开营开始时间
        body.put("openStartDate", openStartDate0); //开营结束时间
        body.put("price", 0.01); //售卖价格
        body.put("surfaceUrl", "https://xiaomai-res.oss-cn-hangzhou.aliyuncs.com/xmfit/course_cover/training_camp_0.png"); // 默认活动封面图
        body.put("title", title); // 训练营活动名称："杭州自动化测试训练营-未发布"
        if (title.isEmpty()) {
            body.put("title", "杭州自动化测试训练营-未发布");
        }

        body.put("totalClassHour", 2); // 总课次数
        body.put("traineeLowerLimit", 2); // 开营人数
        body.put("traineeUpperLimit", 99); // 人数上限
        body.put("trainerList", trainerList); // 上课教练
        body.put("xcxSaleStatus", "YES"); //开启小程序售卖
        body.put("underlinePrice", 99999.99); //划线价
        //图文介绍不设置，所以回归时check下 图文介绍
        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 id 活动ID
     */
    public void deleteTraining(String id) {
        setUP("API_deleteTraining");
        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", id);
        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 id
     */
    public void delTrainingFail(String id) {
        setUP("API_deleteTraining");
        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", id);
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs).assetsSuccess(false);
    }

    /**
     * 根据训练营活动名称全局搜索
     *
     * @param title 活动名称
     */
    public void commonSearchTraining(String title) {
        setUP("API_commonSearchTraining");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("title", title);
        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 title 活动名称
     */
    public JSONObject fetchAppliableCampList(String title) {
        setUP("API_fetchAppliableCampList");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("title", title);
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs);
        JSONObject response = dataApi.getBodyInJSON();
        return response;

    }

    /**
     * 训练营活动列表搜索
     *
     * @param courseId  根据关联课程搜索，可传""
     * @param stateList 根据活动状态搜索
     *                  不指定时传空，new ArrayList<>()
     *                  未发布：UNPUBLISHED
     *                  报名未开始：APPLY_NOT_START
     *                  报名中：APPLYING
     *                  待开营：TO_BE_OPEN
     *                  进行中：OPENING
     *                  已结束：CLOSED
     *                  已取消：CANCEL
     */
    public void searchTrainingList(String courseId, String trainingName, List<String> stateList) {
        setUP("API_searchTrainingList");
        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("courseId", courseId);
        body.put("stateList", stateList);
        if (!trainingName.isEmpty()) {
            body.put("title", trainingName);
        }

        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 title 活动名称
     * @return 返回校验结果 true 是有重名不通过，false 是无重名 可创建
     */
    public Boolean checkTrainingTitleDuplicate(String title) {
        setUP("API_checkTrainingTitleDuplicate");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("title", title);
        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 Boolean.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.result"));
    }

    /**
     * 查看训练营活动详情：基础信息
     *
     * @param id 活动ID
     */
    public void findTrainingDetailById(String id) {
        setUP("API_findTrainingDetailById");
        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", id);
        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 trainingCampId 训练营ID
     * @param content        根据手机号/会员姓名搜索
     */
    public void getTrainingApplyRecordsList(String trainingCampId, String content) {
        setUP("API_getTrainingApplyRecordsList");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("trainingCampId", trainingCampId);
        if (null != content || !content.isEmpty()) {
            body.put("content", content);
        }
        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"));

    }

    /**
     * B 端操作：在训练营活动详情-报名学员-给学员报名
     *
     * @param memberId         会员ID
     * @param receivableAmount 支付金额
     * @param campId           训练营活动ID
     * @param userCouponId     已发放给学员的优惠券记录ID
     */
    public void doSignCampOrder(String memberId, Double receivableAmount, String campId, String userCouponId) {
        setUP("API_signOrderCamp");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        if (userCouponId != null || !userCouponId.isEmpty()) {
            body.put("userCouponId", userCouponId);
        }

        body.put("salesmanId", dataApi.getLoginInfo().getAdminId());
        body.put("operationTime", TimeUtils.getCurrentTime());
        body.put("objectId", RandomStringUtil.randomString(20));
        body.put("memberId", memberId);
        body.put("receivableAmount", receivableAmount);

        JSONObject campInfo = new JSONObject();
        campInfo.put("campId", campId);
        body.put("camp", campInfo);
        JSONArray paymentWays = new JSONArray();
        JSONObject payObject = new JSONObject();
        payObject.put("amount", receivableAmount);
        payObject.put("paymentWay", "1");
        payObject.put("voucherResourceIds", new JSONArray());
        paymentWays.add(payObject);
        body.put("paymentWays", paymentWays);
        dataApi.doRequest(RequestType.JSON, dataparams, body.toString(), dataheadrs);
        Reporter.log(XMJSONPath.readPath(dataApi.getApi_response(), "$.message"));
        Assert.assertTrue(Boolean.valueOf(XMJSONPath.readPath(dataApi.getApi_response(), "$.success")) == true, "调用接口返回结果：" + XMJSONPath.readPath(dataApi.getApi_response(), "$.message"));

    }

    /**
     * 查看训练营活动-报名会员-报名详情
     *
     * @param trainingAccountId 即memberCardId，从查看报名会员列表返回数据中获取对应学员的报名数据（memberCardId）
     */
    public void getTrainingAccountDetailById(String trainingAccountId) {
        setUP("API_getTrainingAccountDetailById");
        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", trainingAccountId);
        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 refundAmount 退出金额
     * @param memberCampId 会员的训练营账户ID
     * @param quantity     退出购买数量
     */
    public void refundCampOrder(String memberId, Double refundAmount, String memberCampId, int quantity) {
        setUP("API_refundCampOrder");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());

        body.put("operationTime", TimeUtils.getCurrentTime());
        body.put("objectId", RandomStringUtil.randomString(20));
        body.put("memberId", memberId);
        body.put("receivableAmount", refundAmount);
        //退单内容
        JSONObject campInfo = new JSONObject();
        campInfo.put("memberCampId", memberCampId);
        campInfo.put("giftQuantity", 0);
        campInfo.put("quantity", quantity);
        campInfo.put("refundAmount", refundAmount);
        body.put("camp", campInfo);
        //结算方式
        JSONArray paymentWays = new JSONArray();
        JSONObject payObject = new JSONObject();
        payObject.put("amount", refundAmount);
        payObject.put("paymentWay", "1");
        payObject.put("voucherResourceIds", new JSONArray());
        paymentWays.add(payObject);
        body.put("paymentWays", paymentWays);
        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 content 手机号/姓名
     * @return 返回搜索的的目标数据第一条的会员ID
     */
    public String searchTargerMember(String content) {
        dataApi.setApiModule(ApiModule.Polar_Clue)
                .setApiName("API_searchMember")
                .setTerminal(Terminal.B);
        super.beforeDataRequest();
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("content", content);
        body.put("searchType", "COMMON");
        body.put("current", 0);
        body.put("size", 20);
        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"));
        int tatal = XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").size();
        if (tatal > 0) {
            return XMJSONPath.getJSONArrayByReadPath(dataApi.getApi_response(), "$.result.records").getJSONObject(0).getString("id");
        }
        return "";

    }

    /**
     * 查看训练营报名记录
     *
     * @param tenantMemberCardId  训练营对应ID
     * @param purchaseChannel     来源即购买渠道 ：线下办理（B_OFF_LINE） 和 上线购买（C_ON_LINE），线上购买的case要等小程序买了之后check
     * @param memberCardStateList 报名记录状态：生效中["NORMAL"]，已结束 ["EXPIRED"]，已用尽["USED_UP"]，已退费["REFUNDED"]，已作废["DISCARD"]
     */
    public void searchTrainingAccountRecordsList(String tenantMemberCardId, String purchaseChannel, List<String> memberCardStateList) {
        setUP("API_searchTrainingAccountRecordsList");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("accountType", "TRAINING");
        body.put("current", 0);
        body.put("size", 20);
        if (!tenantMemberCardId.isEmpty()) {
            body.put("tenantMemberCardId", tenantMemberCardId);
        }
        if (!purchaseChannel.isEmpty()) {
            body.put("purchaseChannel", purchaseChannel);
        }
        body.put("memberCardStateList", memberCardStateList);
        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
     */
    public void fetchUserTrainingCardList(String memberId) {
        setUP("API_getMemberTrainingCardRecords");
        JSONObject body = new JSONObject();
        body.put("operatorId", dataApi.getLoginInfo().getAdminId());
        body.put("studioId", dataApi.getLoginInfo().getStudioId());
        body.put("brandId", dataApi.getLoginInfo().getBrandId());
        body.put("accountType", "TRAINING");
        body.put("current", 0);
        body.put("size", 20);
        body.put("memberId", memberId);
        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"));


    }


}

