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

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

import javax.annotation.Resource;
import java.util.UUID;

public class TestRefundOrderDeposit extends XMBaseTest {
    String memberId;
    String price = "100.00";//储值卡价格
    @Resource(name = "tools")
    Tools tools;
    @Resource(name = "orderTools")
    OrderTools orderTools;
    @Resource(name = "cardTools")
    CardTools cardTools;
    @Resource(name = "adminTools")
    AdminTools adminTools;
    @BeforeMethod
    public void beforeTest(){
        xmAppApi.setApiModule(ApiModule.Polar_Finance)
                .setApiName("API_refundOrderDeposit")
                .setLoginUser(LoginAccount.GYM_PROD)
                .setTerminal(Terminal.B);
        dal.setCase_owner("xyy")
                .setCase_name(Thread.currentThread().getStackTrace()[1].getFileName().split("\\.")[0]);
        super.beforeTest();
    }
    @Test(description = "购买储值卡->退储值卡->作废退卡->作废购卡")
    public void testRefundOrderDeposit() throws InterruptedException {
        //定义会员名称和手机号
        String name = "储值卡会员"+ RandomStringUtil.randomString(3);
        String phone = RandomStringUtil.randomMobile("266");

        //获取会员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");

        //查询启用中的储值卡，获取储值卡id
        String cardId = XMJSONPath.readPath(cardTools.fetchPageOfMemberCard("DEPOSIT_CARD"), "$.result.records[0].id");
        String latestSnapshotId = XMJSONPath.readPath(cardTools.fetchDetailById(cardId), "$.result.latestSnapshotId");
        //1.购储值卡,获取购卡订单id
        String voucherId = cardTools.signOrderDeposit(cardId,latestSnapshotId,memberId,"0.00",price);
        Thread.sleep(3000);
        //通过搜索接口查询该会员名下第1张已售卖的储值卡
        String benefitId = XMJSONPath.readPath(orderTools.fetchUserCardList("DEPOSIT",memberId,"NORMAL"),"$.result[0].depositBenefit.id");
        String memberCardId = XMJSONPath.readPath(orderTools.fetchUserCardList("DEPOSIT",memberId,"NORMAL"),"$.result[0].id");
        //先查询消耗记录的条数
        int num = Integer.parseInt(XMJSONPath.readPath(cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId),"$.result.total"));
        //2.退储值卡
        JSONObject card = new JSONObject();
        card.put("giftAmount",price);
        card.put("memberCardId",memberCardId);
        card.put("rechargeAmount",0);
        card.put("refundAmount",0);
        card.put("commodityCardType","DEPOSIT_CARD");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("operationTime",System.currentTimeMillis());

        JSONArray businessOwners=new JSONArray();
        JSONObject businessOwners1=new JSONObject();
        businessOwners1.put("ownerId",xmAppApi.getLoginInfo().getAdminId());
        String ownerName=adminTools.getStudioAdmin(xmAppApi.getLoginInfo().getAdminId()).getJSONObject("result").getString("nickName");
        businessOwners1.put("ownerName",ownerName);
        businessOwners1.put("percent",100);
        businessOwners.add(businessOwners1);
        jsonObject.put("businessOwners",businessOwners);

        jsonObject.put("card",card);
        jsonObject.put("objectId", UUID.randomUUID().toString());
        jsonObject.put("studioId",xmAppApi.getLoginInfo().getStudioId());
        jsonObject.put("memberId",memberId);
        jsonObject.put("receivableAmount",0);
        jsonObject.put("operatorId",xmAppApi.getLoginInfo().getAdminId());
        jsonObject.put("paymentWays",new JSONArray());
        jsonObject.put("brandId",xmAppApi.getLoginInfo().getBrandId());
        jsonObject.put("fee",0);
        jsonObject.put("refundableAmount",0);
        jsonObject.put("refundAmount",0);

        //调用请求
        xmAppApi.doRequest(RequestType.JSON,params,jsonObject.toJSONString(),headers).assetsSuccess(true);
        String refundOrderId = XMJSONPath.readPath(xmAppApi.getBodyInJSON(), "$.result");
        //订单状态为已退款
        Assert.assertEquals(XMJSONPath.readPath(orderTools.getDetail(refundOrderId), "$.result.state"), "PAID");
        Assert.assertEquals(XMJSONPath.readPath(orderTools.getDetail(refundOrderId),"$.result.type"),"REFUND");
        //储值卡状态=已退卡,剩余金额=0
        Assert.assertEquals(XMJSONPath.readPath(cardTools.memberCardFindDetailById(memberCardId),"$.result.state"),"REFUNDED");
        Assert.assertEquals(XMJSONPath.readPath(cardTools.memberCardFindDetailById(memberCardId),"$.result.price"),"0.00");
        //储值卡消耗记录新增1条，并且类型为退卡,退款金额=购买金额
        Assert.assertTrue(Integer.parseInt(XMJSONPath.readPath(cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId), "$.result.total")) ==num+1);
        Assert.assertEquals(XMJSONPath.readPath(cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId), "$.result.records[0].consumeType"),"REFUND");
        Assert.assertEquals(XMJSONPath.readPath(cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId), "$.result.records[0].changeOfGiveBalance"),"-"+price);

        //3.作废退卡
        orderTools.discard(refundOrderId,"其他","自动化作废退储值卡订单");
        Thread.sleep(3000);
        //储值卡状态生效中
        Assert.assertEquals(XMJSONPath.readPath(cardTools.memberCardFindDetailById(memberCardId),"$.result.state"),"NORMAL");
        //储值卡消耗记录新增1条，并且类型为取消退卡
        Assert.assertTrue(Integer.parseInt(XMJSONPath.readPath(cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId), "$.result.total")) ==num+2);
        Assert.assertEquals(XMJSONPath.readPath(cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId), "$.result.records[0].consumeType"),"CANCEL_REFUND");
        Assert.assertEquals(XMJSONPath.readPath(cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId), "$.result.records[0].changeOfGiveBalance"),price);

        //4.作废购卡
        orderTools.discard(voucherId,"其他","自动化作废储值卡订单");
        Thread.sleep(3000);
        //check储值卡状态为已作废
        Assert.assertEquals(XMJSONPath.readPath(cardTools.memberCardFindDetailById(memberCardId),"$.result.state"),"DISCARD");
        //check剩余金额=0
        Assert.assertEquals(XMJSONPath.readPath(cardTools.memberCardFindDetailById(memberCardId),"$.result.depositBenefit.leftBalance"),"0.00");
        //check消耗记录有1条作废订单记录
        Assert.assertTrue(Integer.parseInt(XMJSONPath.readPath(cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId), "$.result.total")) ==num+3);
        Assert.assertEquals(XMJSONPath.readPath(cardTools.fetchPageOfConsumeRecord(benefitId,memberCardId),"$.result.records[0].consumeType"),"DISCARD_ORDER");
    }

}
