package com.xiaomai.cases.polar.finance.order;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.basetest.BaseTestImpl;
import com.xiaomai.cases.polar.clue.MemberTools;
import com.xiaomai.cases.polar.member.Tools;
import com.xiaomai.cases.polar.memberCard.CardTools;
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 org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.math.BigDecimal;

/**
 * @BelongsProject: xm-sportstest
 * @BelongsPackage: com.xiaomai.cases.polar.finance.order
 * @Author: xuyamei
 * @CreateTime: 2024-12-12  10:02
 * @Description: 创建先享后付订单
 * @Version: 1.0
 */
public class TestSignOrderAxf extends BaseTestImpl {

    MemberTools memberTools = new MemberTools();


    OrderTools orderTools = new OrderTools();
    CardTools cardTools = new CardTools();

    Tools tools = new Tools();
    @BeforeMethod
    @Override
    public void beforeTest(){
        setTestInfo(ApiModule.Polar_Finance,"API_signOrderAxf", LoginAccount.GYM_PROD, Terminal.B,"xym");
        super.beforeTest();
    }


    @Test
    public void testSignOrderAxf(){
        String memberId = "";

        // 查询存量的学员没有则创建学员
        if (tools.commonSearch("先享后付学员嘉艺","NORMAL").getJSONArray("result").size()>0){
            memberId = tools.commonSearch("先享后付学员嘉艺","NORMAL").getJSONArray("result").getJSONObject(0).getString("id");
        }else if (tools.commonSearch("先享后付学员嘉艺","HISTORY").getJSONArray("result").size()>0){
            memberId = tools.commonSearch("先享后付学员嘉艺","HISTORY").getJSONArray("result").getJSONObject(0).getString("id");
        }else if (tools.commonSearch("先享后付学员嘉艺","POTENTIAL").getJSONArray("result").size()>0){
            memberId = tools.commonSearch("先享后付学员嘉艺","POTENTIAL").getJSONArray("result").getJSONObject(0).getString("id");
        }else{
            memberId = memberTools.create("先享后付学员嘉艺", RandomStringUtil.randomMobile("213")).getString("result");
        }

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

        // 查询存量的卡
        JSONObject fetchPageOfMemberCard = orderTools.fetchPageOfMemberCard("","MEMBER_CARD").getJSONObject("result");
        int total = Integer.parseInt(fetchPageOfMemberCard.getString("total"));
        String cardId = "";
        if (total == 0) {
            cardId = cardTools.memberCardCreate("创建先享后付订单"+ TimeUtils.getCurrentTime()).getString("result");
        }
        cardId = fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("id");
        BigDecimal quantity =  new BigDecimal(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getJSONArray("benefitList").getJSONObject(0).getString("balance"));
        float price = Float.parseFloat(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("price"));
        int validPeriod = Integer.parseInt(fetchPageOfMemberCard.getJSONArray("records").getJSONObject(0).getString("validPeriod"));
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

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

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


        JSONObject jsonObject=new JSONObject();
        jsonObject.put("salesmanId",xmAppApi.getLoginInfo().getAdminId());
        jsonObject.put("operationTime", TimeUtils.getCurrentTime());

        JSONObject card = new JSONObject();
        card.put("cardId",cardId);
        card.put("cardSnapshotId",latestSnapshotId);

        JSONObject cardChange=new JSONObject();
        cardChange.put("quantity",quantity);
        cardChange.put("price",price);
        cardChange.put("validPeriod",validPeriod);
        cardChange.put("latestSnapshotId",latestSnapshotId);


        card.put("cardChange",cardChange);
        card.put("deductionAmount",0);//优惠金额（元）
        card.put("activatePattern","PURCHASE");
        card.put("commodityCardType","MEMBER_CARD");
        jsonObject.put("card",card);


        jsonObject.put("objectId", RandomStringUtil.randomString(20));
        jsonObject.put("studioId",xmAppApi.getLoginInfo().getStudioId());
        jsonObject.put("memberId",memberId);
        jsonObject.put("receivableAmount",price);//应收金额
        jsonObject.put("operatorId",xmAppApi.getLoginInfo().getAdminId());


        JSONObject axfOrderInfo = new JSONObject();
        axfOrderInfo.put("totalPeriod","2"); //总期数
        axfOrderInfo.put("cycleType","MONTH"); // 按月扣款
        axfOrderInfo.put("periodType","SAME_EACH_PERIOD"); // 扣款每期一致
        axfOrderInfo.put("cycleValue",1); // 按月1号
        axfOrderInfo.put("chargeNow", false);

        JSONArray periodPriceList = new JSONArray();
        for (int i = 0; i < 2; i++){
            JSONObject priceObj = new JSONObject();
            priceObj.put("period",i+1);  // 期数
            priceObj.put("salePrice",price/2); // 每期还款金额
            periodPriceList.add(priceObj);

        }
        axfOrderInfo.put("periodPriceList",periodPriceList);
        jsonObject.put("axfOrderInfo",axfOrderInfo);


        JSONArray paymentWays = new JSONArray();
        JSONObject object = new JSONObject();
        object.put("amount",price);//支付金额
        object.put("paymentWay","7"); // 7先享后付支付
        JSONArray voucherResourceIds = new JSONArray();//支付凭证
        voucherResourceIds.add("");
        object.put("voucherResourceIds",voucherResourceIds);
        paymentWays.add(object);

        jsonObject.put("paymentWays",paymentWays);
        jsonObject.put("brandId",xmAppApi.getLoginInfo().getBrandId());

        xmAppApi.doRequest(RequestType.JSON, params, jsonObject.toJSONString(), headers).assetsSuccess(true);

        JSONObject bodyInJSON = xmAppApi.getBodyInJSON();
        String getDetailId = bodyInJSON.getString("result");

        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        // 校验订单详情状态：待支付、先享后付状态为签约中
        JSONObject getDetailResult = orderTools.getDetail(getDetailId);
        String state = getDetailResult.getJSONObject("result").getString("state");
        Assert.assertEquals(state,"WAITING","先享后付订单创建成功后订单状态不是待支付");
        String axfState = getDetailResult.getJSONObject("result").getString("axfState");
        Assert.assertEquals(axfState,"PROCESS","先享后付订单安心付状态不是签约中");


        orderTools.discard(getDetailId, "重复录入","作废订单");
    }

}
