package com.xiaomai.cases.polar.goods;

import com.alibaba.fastjson.JSONObject;
import com.xiaomai.cases.lunar.goods.GoodCTools;
import com.xiaomai.cases.lunar.user.UserTools;
import com.xiaomai.cases.polar.data.financeData.FinanceDataTools;
import com.xiaomai.cases.polar.finance.order.OrderTools;
import com.xiaomai.cases.polar.goods.Tools.GoodTools;
import com.xiaomai.cases.polar.memberCard.CardTools;
import com.xiaomai.client.DataUserInfo;
import com.xiaomai.enums.ApiModule;
import com.xiaomai.enums.LoginAccount;
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 java.math.BigDecimal;
import java.math.RoundingMode;

public class TestGoodsOrderByDeposit extends XMBaseTest {


    GoodTools goodTools=new GoodTools();
    GoodCTools goodCTools=new GoodCTools();



    DataUserInfo info =new DataUserInfo();
    UserTools userTools=new UserTools();

    OrderTools orderTools=new OrderTools();

    CardTools cardTools=new CardTools();

    FinanceDataTools financeDataTools=new FinanceDataTools();

    String memberId;

    String voucherId;



    @BeforeMethod
    public void beforeTest() {
        xmAppApi.setApiModule(ApiModule.Polar_Goods)
                .setApiName("API_refundGoods")
                .setLoginUser(LoginAccount.GYM_PROD)
                .setTerminal(Terminal.B);

        dal.setCase_owner("yff")
                .setCase_name(Thread.currentThread().getStackTrace()[1].getFileName().split("\\.")[0]);
        super.beforeTest();
    }

    @Test(description = "使用储值卡购买单规格&退货退款->作废退&作废购买")
    public void TestGoodsOrderByDeposit() {

        //涉及到订单的都使用存量物品数据，因为购买过物品就不能被删除了，所以不会买一次新建一个

//        "id": "1874413681302990849",
//                "name": "自动化禁用-购买订单单规格1元",
//        "id": "1874413587237335042",
//                "name": "自动化禁用-购买订单多规格1元",
        //存量储值卡：自动化用于物品储值卡1元禁用


        //case1：使用储值卡购买非0订单,储值卡全额抵扣->已完成，物品权益到账，储值卡额度减少

        //切换端位
        info.setTerminal(Terminal.minApp);
        info.setLoginUser(LoginAccount.GYM_MINIAPPC);

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


        //获取会员信息
        //获取用户
        memberId = userTools.getMemberInfo(info).getString("memberId");

        String goodsId1="1874413681302990849";

        //获取储值卡
        JSONObject tenantMemberCardCommonSearch=cardTools.tenantMemberCardCommonSearch("DEPOSIT_CARD","自动化用于物品储值卡1元禁用");
        String cardId=tenantMemberCardCommonSearch.getJSONArray("result").getJSONObject(0).getString("id");
        //获取储值卡详情
        JSONObject fetchDetailById=cardTools.fetchDetailById(cardId);
        String latestSnapshotId=fetchDetailById.getJSONObject("result").getString("latestSnapshotId");
        BigDecimal cardPrice=new BigDecimal(fetchDetailById.getJSONObject("result").getJSONArray("benefitList").getJSONObject(0).getString("price"));
        BigDecimal cardBalance=new BigDecimal(fetchDetailById.getJSONObject("result").getJSONArray("benefitList").getJSONObject(0).getString("balance"));


        //1.购储值卡,获取购卡订单id
        voucherId = cardTools.signOrderDeposit(cardId,latestSnapshotId,memberId,String.valueOf(cardPrice),String.valueOf(cardBalance));

        //获取已售储值卡ID，使用储值卡抵扣的时候需要的ID
        JSONObject listUserUsableDepositCardB=cardTools.listUserUsableDepositCardB(memberId,"GOODS").getJSONObject("result").getJSONArray("applicableList").getJSONObject(0);
        String cardId1=listUserUsableDepositCardB.getString("id");

        //获取B端商品详情
        JSONObject getDetail_goods=goodTools.getDetail_goods(goodsId1);
        String id=getDetail_goods.getJSONObject("result").getString("id");
        BigDecimal price=new BigDecimal(getDetail_goods.getJSONObject("result").getJSONObject("singleSpecInfo").getString("price"));
        int beforeInventory=Integer.parseInt(getDetail_goods.getJSONObject("result").getJSONObject("singleSpecInfo").getString("inventory"));

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

        //获取数据中心-财务中心-营收明细-物品的确认收入
        JSONObject beforeGetCostData_type=financeDataTools.getCostData_type("DAY","GOODS", TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime());
        BigDecimal beforeConfirmedAmount=new BigDecimal(beforeGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入

        //购买物品
        JSONObject purchaseGoods = goodCTools.purchaseGoods(String.valueOf(cardPrice.add(cardBalance.setScale(2, RoundingMode.HALF_UP))),
                cardId1, memberId, "", String.valueOf(price.subtract(cardPrice.add(cardBalance.setScale(2, RoundingMode.HALF_UP)))), id, price, 1, info);
        String signOrderId1 = purchaseGoods.getJSONObject("result").getString("id");

        //校验1：获取B端订单详情：已完成状态
        JSONObject getDetailResult_delinquent = orderTools.getDetail(signOrderId1);
        String state_delinquent = getDetailResult_delinquent.getJSONObject("result").getString("state");
        Assert.assertEquals(state_delinquent, "PAID", "使用储值卡购买订单，全部抵扣完之后生成已完成的物品订单");


        //校验2：购买后库存数减少
        //获取B端商品详情
        JSONObject signGetDetail_goods=goodTools.getDetail_goods(goodsId1);
        int signInventory=Integer.parseInt(signGetDetail_goods.getJSONObject("result").getJSONObject("singleSpecInfo").getString("inventory"));
        Assert.assertEquals(signInventory,beforeInventory-1,"使用储值卡全额抵扣购买物品成功后，物品库存数应减少1个");

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

        //校验3：数据中心-财务中心-营收明细-物品的确认收入增加对应的充值金额
        JSONObject afterGetCostData_type = financeDataTools.getCostData_type("DAY", "GOODS", TimeUtils.getTodayTime(), TimeUtils.getTodayEndTime());
        BigDecimal afterConfirmedAmount = new BigDecimal(afterGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入
        Assert.assertEquals(afterConfirmedAmount,beforeConfirmedAmount.add(cardPrice.setScale(2,RoundingMode.HALF_UP)),"使用储值卡全额抵扣购买物品，确认收入增加储值卡充值金额");


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

        //校验4：储值卡额度减少，剩余充值金额+赠送金额为0
        //获取储值卡详情
        JSONObject fetchDetailById1=cardTools.memberCardFindDetailById(cardId1);
        BigDecimal leftDepositPurchaseBenefitAmount1=new BigDecimal(fetchDetailById1.getJSONObject("result").getJSONObject("depositBenefit").getString("leftPurchaseBalance"));
        BigDecimal leftDepositGiveBenefitAmount1=new BigDecimal(fetchDetailById1.getJSONObject("result").getJSONObject("depositBenefit").getString("leftGiveBalance"));
        BigDecimal num=new BigDecimal("0.00");
        Assert.assertEquals(leftDepositPurchaseBenefitAmount1,num,"使用储值卡全额抵扣购买物品，所使用的储值卡充值剩余金额应为0");
        Assert.assertEquals(leftDepositGiveBenefitAmount1,num,"使用储值卡全额抵扣购买物品，所使用的储值卡赠送剩余金额应为0");





        //case2：退掉使用储值卡购买非0订单，物品权益退回，储值卡额度返还


        //拉取这个会员的物品列表
        JSONObject listLeftGoodsItem=goodTools.listLeftGoodsItem(memberId);
        String refundId=listLeftGoodsItem.getJSONArray("result").getJSONObject(0).getString("id");

        //B端退单时获取订单可退物品（退单界面）
        JSONObject getLeftGoodsItem=goodTools.getLeftGoodsItem(refundId);
        int quantity=Integer.parseInt(getLeftGoodsItem.getJSONObject("result").getString("leftQuantity"));
        BigDecimal refundAmount=new BigDecimal(getLeftGoodsItem.getJSONObject("result").getString("leftPaidAmount"));
        String voucherItemId=getLeftGoodsItem.getJSONObject("result").getString("id");
        BigDecimal receivableAmount=new BigDecimal(getLeftGoodsItem.getJSONObject("result").getString("leftPaidAmount"));
        BigDecimal amount=new BigDecimal(getLeftGoodsItem.getJSONObject("result").getString("leftConsumeAmount"));


        //退货退款物品
        JSONObject refundGoods=goodTools.refundGoods(quantity,refundAmount,true,voucherItemId,memberId,receivableAmount,amount,"1",cardPrice,cardBalance,cardId1);
        String refundOrderId1=refundGoods.getString("result");


        //校验：
        //校验1：获取B端订单详情：退单已完成状态
        JSONObject getDetailResult_refund = orderTools.getDetail(refundOrderId1);
        String state_refund = getDetailResult_refund.getJSONObject("result").getString("state");
        Assert.assertEquals(state_refund, "PAID", "B端退货退款成功后退单物品订单状态变为已完成");

        //校验2：退货退款后库存数减少
        //获取B端商品详情
        JSONObject refundGetDetail_goods=goodTools.getDetail_goods(goodsId1);
        int refundInventory=Integer.parseInt(refundGetDetail_goods.getJSONObject("result").getJSONObject("singleSpecInfo").getString("inventory"));
        Assert.assertEquals(refundInventory,signInventory+1,"使用储值卡全额抵扣购买物品退货退款成功后，物品库存数应增加1个");


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



        //校验3：数据中心-财务中心-营收明细-物品的确认收入应减少充值金额
        JSONObject refundAfterGetCostData_type = financeDataTools.getCostData_type("DAY", "GOODS", TimeUtils.getTodayTime(), TimeUtils.getTodayEndTime());
        BigDecimal refundAfterConfirmedAmount = new BigDecimal(refundAfterGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入
        Assert.assertEquals(refundAfterConfirmedAmount,afterConfirmedAmount.subtract(cardPrice.setScale(2,RoundingMode.HALF_UP)),"退掉使用储值卡全额抵扣购买的物品，确认收入减少储值卡充值金额");


        //校验4：储值卡额度增加，剩余充值金额+赠送金额增加
        //获取储值卡详情
        JSONObject fetchDetailById2=cardTools.memberCardFindDetailById(cardId1);
        BigDecimal leftDepositPurchaseBenefitAmount2=new BigDecimal(fetchDetailById2.getJSONObject("result").getJSONObject("depositBenefit").getString("leftPurchaseBalance"));
        BigDecimal leftDepositGiveBenefitAmount2=new BigDecimal(fetchDetailById2.getJSONObject("result").getJSONObject("depositBenefit").getString("leftGiveBalance"));

        Assert.assertEquals(leftDepositPurchaseBenefitAmount2,cardPrice,"退掉使用储值卡全额抵扣购买的物品，所使用的储值卡充值剩余金额应返回对应的金额");
        Assert.assertEquals(leftDepositGiveBenefitAmount2,cardBalance,"使用储值卡全额抵扣购买物品，所使用的储值卡赠送剩余金额应返回对应的金额");



        //case3：作废退掉使用储值卡购买非0订单，物品权益返还，储值卡额度减少

        JSONObject discardRefundOrder=orderTools.discard(refundOrderId1, "重复录入", "已作废物品退货退款订单" + RandomStringUtil.randomString(10));

        //校验：
        //校验1：获取B端订单详情：退单已作废状态
        JSONObject getDetailResult_discardRefund = orderTools.getDetail(refundOrderId1);
        String state_discardRefund = getDetailResult_discardRefund.getJSONObject("result").getString("state");
        Assert.assertEquals(state_discardRefund, "DISCARD", "B端作废退货退款订单后，订单状态应由已完成变为已作废");


        //校验2：退货退款后库存数减少
        //获取B端商品详情
        JSONObject disRefundGetDetail_goods=goodTools.getDetail_goods(goodsId1);
        int disRefundInventory=Integer.parseInt(disRefundGetDetail_goods.getJSONObject("result").getJSONObject("singleSpecInfo").getString("inventory"));
        Assert.assertEquals(disRefundInventory,refundInventory-1,"B端作废退货退款订单后，物品库存数应减少1个");

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


        //校验3：数据中心-财务中心-营收明细-物品的确认收入应增加充值金额
        JSONObject disRefundAfterGetCostData_type = financeDataTools.getCostData_type("DAY", "GOODS", TimeUtils.getTodayTime(), TimeUtils.getTodayEndTime());
        BigDecimal disRefundAfterConfirmedAmount = new BigDecimal(disRefundAfterGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入
        Assert.assertEquals(disRefundAfterConfirmedAmount,refundAfterConfirmedAmount.add(cardPrice.setScale(2,RoundingMode.HALF_UP)),"作废退掉使用储值卡全额抵扣购买的物品，确认收入增加储值卡充值金额");


        //校验4：储值卡额度增加，剩余充值金额+赠送金额增加
        //获取储值卡详情
        JSONObject fetchDetailById3=cardTools.memberCardFindDetailById(cardId1);
        BigDecimal leftDepositPurchaseBenefitAmount3=new BigDecimal(fetchDetailById3.getJSONObject("result").getJSONObject("depositBenefit").getString("leftPurchaseBalance"));
        BigDecimal leftDepositGiveBenefitAmount3=new BigDecimal(fetchDetailById3.getJSONObject("result").getJSONObject("depositBenefit").getString("leftGiveBalance"));
        BigDecimal num1=new BigDecimal("0.00");
        Assert.assertEquals(leftDepositPurchaseBenefitAmount3,num1,"作废退掉使用储值卡全额抵扣购买的物品，所使用的储值卡充值剩余金额应为0");
        Assert.assertEquals(leftDepositGiveBenefitAmount3,num1,"作废退掉使用储值卡全额抵扣购买物品，所使用的储值卡赠送剩余金额应为0");


        //case4：作废购买订单，物品权益退回，储值卡额度返还

        JSONObject discardSignOrder=orderTools.discard(signOrderId1, "重复录入", "已作废物品购买订单" + RandomStringUtil.randomString(10));

        //校验：
        //校验1：获取B端订单详情：购买订单已作废状态
        JSONObject getDetailResult_discardSign = orderTools.getDetail(signOrderId1);
        String state_discardRefund_discardSign = getDetailResult_discardSign.getJSONObject("result").getString("state");
        Assert.assertEquals(state_discardRefund_discardSign, "DISCARD", "B端作废购买订单后，签单订单状态由已完成变为已作废");


        //校验2：退货退款后库存数减少
        //获取B端商品详情
        JSONObject disSignGetDetail_goods=goodTools.getDetail_goods(goodsId1);
        int disSignInventory=Integer.parseInt(disSignGetDetail_goods.getJSONObject("result").getJSONObject("singleSpecInfo").getString("inventory"));
        Assert.assertEquals(disSignInventory,disRefundInventory+1,"B端作废购买订单后，物品库存数应增加1个");

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


        //校验3：数据中心-财务中心-营收明细-物品的确认收入应减少充值金额
        JSONObject disSignAfterGetCostData_type = financeDataTools.getCostData_type("DAY", "GOODS", TimeUtils.getTodayTime(), TimeUtils.getTodayEndTime());
        BigDecimal disSignAfterConfirmedAmount = new BigDecimal(disSignAfterGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入
        Assert.assertEquals(disSignAfterConfirmedAmount,disRefundAfterConfirmedAmount.subtract(cardPrice.setScale(2,RoundingMode.HALF_UP)),"作废使用储值卡全额抵扣购买的物品，确认收入减少储值卡充值金额");


        //校验4：储值卡额度增加，剩余充值金额+赠送金额增加
        //获取储值卡详情
        JSONObject fetchDetailById4=cardTools.memberCardFindDetailById(cardId1);
        BigDecimal leftDepositPurchaseBenefitAmount4=new BigDecimal(fetchDetailById4.getJSONObject("result").getJSONObject("depositBenefit").getString("leftPurchaseBalance"));
        BigDecimal leftDepositGiveBenefitAmount4=new BigDecimal(fetchDetailById4.getJSONObject("result").getJSONObject("depositBenefit").getString("leftGiveBalance"));
        Assert.assertEquals(leftDepositPurchaseBenefitAmount4,cardPrice,"作废使用储值卡全额抵扣购买的物品，所使用的储值卡充值剩余金额应返回对应的金额");
        Assert.assertEquals(leftDepositGiveBenefitAmount4,cardPrice,"作废使用储值卡全额抵扣购买物品，所使用的储值卡赠送剩余金额应返回对应的金额");


    }

    @Test(description ="作废签单订单",priority = 1)
    public void  discard(){
        //作废储值卡签单订单
        orderTools.discard(voucherId, "重复录入", "已作废储值卡签单订单" + RandomStringUtil.randomString(10));


    }

    }
