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

import com.alibaba.fastjson.JSONArray;
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.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 com.xiaomai.utils.XMBaseTest;
import com.xiaomai.utils.XMJSONPath;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import java.io.IOException;
import java.math.BigDecimal;

public class TestUploadResources extends XMBaseTest {


    String memberId;

    String cardId;

    String id1;


    Tools tools=new Tools();

    OrderTools orderTools=new OrderTools();

    CardTools cardTools=new CardTools();

    @BeforeMethod
    public void beforeTest(){
        xmAppApi.setApiModule(ApiModule.Polar_Finance)
                .setApiName("API_uploadResources")
                .setLoginUser(LoginAccount.GYM_PROD)
                .setTerminal(Terminal.B);
        dal.setCase_owner("yff")
                .setCase_name(Thread.currentThread().getStackTrace()[1].getFileName().split("\\.")[0]);
        super.beforeTest();
    }

    @Test(description = "收支（收支明细&订单详情-支付记录）上传支付凭证-3张")
    public void testUploadResources()  {


        String name = "创建订单潜在会员"+ RandomStringUtil.randomString(3);
        String phone = RandomStringUtil.randomMobile("666");

        //获取会员ID,没有则新建一个
        int memberTotal = Integer.parseInt(tools.search("NORMAL","NORMAL").getJSONObject("result").getString("total"));
        if (memberTotal == 0) {
            memberId = tools.create(name,phone).getString("result");
        }
        memberId=tools.search("NORMAL","NORMAL").getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");

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

        //获取会员卡信息
        //获取会员卡列表,没有则新建一个
        int cardTotal = Integer.parseInt(orderTools.fetchPageOfMemberCard("次卡","MEMBER_CARD").getJSONObject("result").getString("total"));
        if (cardTotal == 0) {
            cardId = cardTools.memberCardCreate("次卡-创建订单会员卡"+ TimeUtils.getCurrentTime()).getString("result");
        }
        JSONObject memberCard=orderTools.fetchPageOfMemberCard("次卡","MEMBER_CARD");
        cardId=memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("id");
        BigDecimal quantity= new BigDecimal(memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getJSONArray("benefitList").getJSONObject(0).getString("balance"));
        float price= Float.parseFloat(memberCard.getJSONObject("result").getJSONArray("records").getJSONObject(0).getString("price"));
        int validPeriod= Integer.parseInt(memberCard.getJSONObject("result").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);
        }

        //检查会员对该卡是否超出购买上限
        boolean limitResult=orderTools.checkAllowPurchase("MEMBER_CARD",cardId,memberId,"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");
            String success = orderResult.getString("success");
            String getDetailId = orderResult.getString("result");
            Assert.assertEquals(success, "true", "创建签单订单失败");

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

            //获取订单支付记录
            JSONObject listByVoucherIdResult=orderTools.listByVoucherId(getDetailId);
            id1=listByVoucherIdResult.getJSONArray("result").getJSONObject(0).getString("id");//收支的id


            //上传图片
            JSONObject jsonObject=new JSONObject();
            jsonObject.put("id",id1);

            JSONArray resourceIds=new JSONArray();
            resourceIds.add("1808067425522491394");
            resourceIds.add("1808067425522491394");
            resourceIds.add("1808067425522491394");
            jsonObject.put("resourceIds",resourceIds);

            jsonObject.put("brandId",xmAppApi.getLoginInfo().getBrandId());
            jsonObject.put("studioId",xmAppApi.getLoginInfo().getStudioId());
            jsonObject.put("operatorId",xmAppApi.getLoginInfo().getAdminId());

            xmAppApi.doRequest(RequestType.JSON,params,jsonObject.toJSONString(),headers).assetsSuccess(true);
            JSONObject response=xmAppApi.getBodyInJSON();
            String uploadResourcesSuccess=response.getString("success");
            Assert.assertEquals(uploadResourcesSuccess,"true","上传图片失败");


        }

    }
    @Test(description = "收支（收支明细&订单详情-支付记录）上传支付凭证-资源不能超过3个")
    public void testUploadResources_add() {

        //上传图片
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("id",id1);

        JSONArray resourceIds=new JSONArray();
        resourceIds.add("1808067425522491394");
        resourceIds.add("1808067425522491394");
        resourceIds.add("1808067425522491394");
        resourceIds.add("1808067425522491394");
        jsonObject.put("resourceIds",resourceIds);

        jsonObject.put("brandId",xmAppApi.getLoginInfo().getBrandId());
        jsonObject.put("studioId",xmAppApi.getLoginInfo().getStudioId());
        jsonObject.put("operatorId",xmAppApi.getLoginInfo().getAdminId());

        xmAppApi.doRequest(RequestType.JSON,params,jsonObject.toJSONString(),headers);
        String uploadResourcesSuccess=xmAppApi.getBodyInJSON().getString("success");
        Assert.assertEquals(uploadResourcesSuccess,"false","支付凭证资源不能超过3个");


    }
}
