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.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;



    @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元",


        //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="1874413587237335042";

        //获取储值卡
        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
        String 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").getJSONObject("multiSpecInfo").getJSONArray("specCombinationList").getJSONObject(0).getString("id");
        BigDecimal price=new BigDecimal(getDetail_goods.getJSONObject("result").getJSONObject("multiSpecInfo").getJSONArray("specCombinationList").getJSONObject(0).getString("price"));
        int beforeInventory=Integer.parseInt(getDetail_goods.getJSONObject("result").getJSONObject("multiSpecInfo").getJSONArray("specCombinationList").getJSONObject(0).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"));//确认收入

        boolean checkAllowPurchase=Boolean.parseBoolean(goodCTools.checkAllowPurchase(id,memberId,price,beforeInventory,info).getJSONObject("result").getString("success"));

        //校验一下物品购买是否可以通过，为true才可以
        if(checkAllowPurchase==true) {

            JSONObject purchaseGoods = goodCTools.purchaseGoods(String.valueOf(cardPrice.add(cardBalance.setScale(2, RoundingMode.HALF_UP))), cardId1, memberId, "", "0.00", 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", "使用储值卡购买订单，全部抵扣完之后生成已完成订单");

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

            //校验2：数据中心-财务中心-营收明细-物品的确认收入增加对应的充值金额
            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);
            }

            //校验3：储值卡额度减少，剩余充值金额+赠送金额为0
            //获取储值卡详情
            JSONObject fetchDetailById1=cardTools.memberCardFindDetailById(cardId1);
            BigDecimal leftDepositPurchaseBenefitAmount=new BigDecimal(fetchDetailById1.getJSONObject("result").getJSONObject("depositBenefit").getString("leftPurchaseBalance"));
            BigDecimal leftDepositGiveBenefitAmount=new BigDecimal(fetchDetailById1.getJSONObject("result").getJSONObject("depositBenefit").getString("leftGiveBalance"));
            BigDecimal num=new BigDecimal("0.00");

            Assert.assertEquals(leftDepositPurchaseBenefitAmount,num,"使用储值卡全额抵扣购买物品，所使用的储值卡充值剩余金额应为0");
            Assert.assertEquals(leftDepositGiveBenefitAmount,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端退货退款成功后退单订单状态变为已完成");


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

            //校验2：数据中心-财务中心-营收明细-物品的确认收入应减少充值金额
            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)),"退掉使用储值卡全额抵扣购买的物品，确认收入减少储值卡充值金额");


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

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



        }


    }
    }
