package com.xiaomai.cases.polar.member;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.cases.polar.clue.MemberTools;
import com.xiaomai.cases.polar.course.CourseTools;
import com.xiaomai.cases.polar.finance.order.OrderTools;
import com.xiaomai.cases.polar.memberCard.CardTools;
import com.xiaomai.cases.polar.setting.courseCategory.CourseCategoryTools;
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 org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

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

/**
 * @Author zxy
 * @Description
 * @Date 2024/6/28 17:13
 */
public class TestAppointCoach extends XMBaseTest {
    Tools tools = new Tools();
    MemberTools memberTools = new MemberTools();
    String memberId;
    String courseId;
    CardTools cardTools = new CardTools();
    OrderTools orderTools = new OrderTools();
    @Resource(name = "courseCategoryTools")
    CourseCategoryTools courseCategoryTools;
    @Resource(name = "courseTools")
    CourseTools courseTools;


    @BeforeMethod
    public void beforeTest(){

        xmAppApi.setApiModule(ApiModule.Polar_Clue)
                .setApiName("API_appointCoach")
                .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 testAppointCoach(){
        String name = "自动化潜在会员"+ RandomStringUtil.randomString(3);
        String phone = RandomStringUtil.randomMobile("666");

        String categoryId = courseCategoryTools.getCourseCategoryPage("瑜伽");
        courseId = courseTools.getPersonalOrGroupCourseId("GROUP", "空中瑜伽团课课程", categoryId, "STUDIO", "", 2, 1).getString(0);

        //查看是否有存量的正式和流失会员，若有则取存量数据，没有则查看是否有存量的潜在会员，若有则给潜在会员购卡变为正式会员，没有存量的则新建潜在会员后再购卡变为正式会员
        JSONArray array = tools.search("NORMAL","NORMAL").getJSONObject("result").getJSONArray("records");
        //查看是否有存量的流失会员
        JSONArray array1 = tools.search("HISTORY","HISTORY").getJSONObject("result").getJSONArray("records");

        int size = array.size();
        int size1 = array1.size();

        if(size != 0){
            memberId = array.getJSONObject(0).getString("id");
        }
        else if(size == 0 && size1 != 0){
            memberId = array1.getJSONObject(0).getString("id");
        }
        else {
            memberId = memberTools.create(name,phone).getString("result");
            JSONArray listUserReservableBenefit = cardTools.listUserReservableBenefit(courseId, "GROUP_CLASS", "MEMBER", memberId, TimeUtils.getTodayTime());
            if (listUserReservableBenefit.size() == 0) {
                // 购买适用的会员卡
                signOrder(courseId, memberId);
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                listUserReservableBenefit = cardTools.listUserReservableBenefit(courseId, "GROUP_CLASS", "MEMBER", memberId, TimeUtils.getTodayTime());
            }
        }

        List memberIds = new ArrayList();
        memberIds.add(memberId);

        List memberStatusList = new ArrayList();
        String coachId = memberTools.fetchStaff("AS_COACH",memberStatusList,"").getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");

        JSONObject object = new JSONObject();
        object.put("memberIds",memberIds);
        object.put("coachId",coachId);
        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);
        Assert.assertEquals(memberTools.findStudioMemberDetail(memberId).getJSONObject("result").getString("coachId"),coachId);
    }

    // 买卡
    public void signOrder(String courseId,String memberId){
        // 查询存量的卡
        JSONObject fetchPageOfMemberCard = cardTools.fetchPageOfMemberCard(courseId,"MEMBER_CARD");
        int total = Integer.parseInt(fetchPageOfMemberCard.getString("total"));
        String cardId = "";
        BigDecimal quantity = new BigDecimal(0);
        float price = 0;
        int validPeriod = 0;
        if (total == 0) {
            cardId = cardTools.memberCardCreate("约课使用会员卡"+TimeUtils.getCurrentTime()).getString("result");
        }
        cardId = fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("id");
        quantity =  new BigDecimal(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getJSONArray("benefitList").getJSONObject(0).getString("balance"));
        price = Float.parseFloat(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("price"));
        validPeriod = Integer.parseInt(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("validPeriod"));

        //获取签单要用的卡快照id
        String latestSnapshotId = orderTools.fetchDetailById(cardId,xmAppApi.getLoginInfo().getBrandId(),xmAppApi.getLoginInfo().getStudioId(),xmAppApi.getLoginInfo().getAdminId()).getJSONObject("result").getString("latestSnapshotId");

        //检查会员对该卡是否超出购买上限
        boolean limitResult= orderTools.checkAllowPurchase("MEMBER_CARD",cardId,cardId,"1",xmAppApi.getLoginInfo().getBrandId(),xmAppApi.getLoginInfo().getStudioId(),xmAppApi.getLoginInfo().getAdminId()).getBoolean("success");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        if( limitResult == true){
            //创建订单
            JSONObject orderResult=orderTools.signOrder(cardId,latestSnapshotId,quantity,price,validPeriod,latestSnapshotId, price/2,"PURCHASE",
                    "MEMBER_CARD",memberId,price-price/2,price-price/2,"1",true);        }
    }
}
