package com.xiaomai.cases.lunar.goods;

import com.alibaba.fastjson.JSONObject;
import com.xiaomai.basetest.BaseTestImpl;
import com.xiaomai.cases.lunar.order.OrderCTools;
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.client.DataUserInfo;
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;
import java.math.RoundingMode;

public class TestPurchaseGoods extends BaseTestImpl {

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

    String memberId;

    UserTools userTools=new UserTools();

    DataUserInfo info = new DataUserInfo();



    OrderCTools orderCTools=new OrderCTools();

    OrderTools orderTools=new OrderTools();

    FinanceDataTools financeDataTools=new FinanceDataTools();


    String orderId1;
    String orderId2;
    String orderId3;



    @BeforeMethod
    @Override
    public void beforeTest(){
        setTestInfo(ApiModule.Lunar_Goods,"API_purchaseGoods", LoginAccount.GYM_MINIAPPC, Terminal.minApp,"yff");
        super.beforeTest();
    }


    @Test(description = "购买非0元多规格物品")
    public void testPurchaseGoods_WAITING() {
        //涉及到订单的都使用存量物品数据，因为购买过物品就不能被删除了，所以不会买一次新建一个

//        "id": "1874413681302990849",
//                "name": "自动化禁用-购买订单单规格1元",
//        "id": "1874413587237335042",
//                "name": "自动化禁用-购买订单多规格1元",
//        "id": "1874413193018896386",
//                "name": "自动化禁用-购买订单多规格0元",
//        "id": "1874411064376061954",
//                "name": "自动化禁用-购买订单单规格0元",

        //case1:购买多规格非0元物品生成待支付订单

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


        //切换端位
        info.setTerminal(Terminal.B);
        info.setLoginUser(LoginAccount.GYM_PROD);

        String goodsId1="1874413587237335042";

        //获取C端商品详情
        JSONObject getDetail_goods_C=goodCTools.getDetail_goods_C(goodsId1);
        String id=getDetail_goods_C.getJSONObject("result").getJSONObject("multiSpecInfo").getJSONArray("specCombinationList").getJSONObject(0).getString("id");
        BigDecimal price=new BigDecimal(getDetail_goods_C.getJSONObject("result").getJSONObject("multiSpecInfo").getJSONArray("specCombinationList").getJSONObject(0).getString("price"));
        int beforeInventory=Integer.parseInt(getDetail_goods_C.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(),info);
        BigDecimal beforeConfirmedAmount=new BigDecimal(beforeGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入

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

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


            //购买非0元多规格物品
            JSONObject  purchaseGoods=new JSONObject();
            purchaseGoods.put("depositAmount","0.00");
            purchaseGoods.put("depositCardId",null);
            purchaseGoods.put("memberId",memberId);
            purchaseGoods.put("memo","");
            purchaseGoods.put("objectId", RandomStringUtil.randomString(16));
            purchaseGoods.put("receivableAmount",price);
            purchaseGoods.put("goodsSpecId",id);
            purchaseGoods.put("price",price);
            purchaseGoods.put("quantity",1);
            purchaseGoods.put("studioId",dataApi.getLoginInfo().getStudioId());

            xmAppApi.doRequest(RequestType.JSON, params, purchaseGoods.toString(), headers).assetsSuccess(true);
            JSONObject purchaseGoodsResponse = xmAppApi.getBodyInJSON();
            orderId1=purchaseGoodsResponse.getJSONObject("result").getString("id");

            //校验1：获取B端订单详情：待支付状态
            JSONObject getDetailResult = orderTools.getDetail(orderId1,info);
            String businessNo= getDetailResult.getJSONObject("result").getString("businessNo");//订单号
            String state=getDetailResult.getJSONObject("result").getString("state");
            Assert.assertEquals(state,"WAITING","未生成待支付物品订单");

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

            //校验2：C端商品详情库存数-1
            JSONObject afterGetDetail_goods_C=goodCTools.getDetail_goods_C(goodsId1);
            int afterInventory=Integer.parseInt(afterGetDetail_goods_C.getJSONObject("result").getJSONObject("multiSpecInfo").getJSONArray("specCombinationList").getJSONObject(0).getString("inventory"));
            Assert.assertEquals(afterInventory,beforeInventory-1,"购买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(),info);
            BigDecimal afterConfirmedAmount=new BigDecimal(afterGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入
            Assert.assertEquals(afterConfirmedAmount,beforeConfirmedAmount,"购买1个物品生成待支付订单后，财务中心-营收明细-物品的确认收入应无变化");




            //case2：C端取消订单

            JSONObject cancel=orderCTools.cancel(orderId1);

            //校验1：获取B端订单详情：已取消状态
            JSONObject getDetailResult_cancel = orderTools.getDetail(orderId1,info);
            String businessNo_cancel= getDetailResult_cancel.getJSONObject("result").getString("businessNo");//订单号
            String state_cancel=getDetailResult_cancel.getJSONObject("result").getString("state");
            Assert.assertEquals(state_cancel,"CANCEL","C端取消物品订单后，订单状态未从待支付变更为已取消");


            //校验2：C端商品详情库存数+1
            JSONObject lastGetDetail_goods_C=goodCTools.getDetail_goods_C(goodsId1);
            int lastInventory=Integer.parseInt(lastGetDetail_goods_C.getJSONObject("result").getJSONObject("multiSpecInfo").getJSONArray("specCombinationList").getJSONObject(0).getString("inventory"));
            Assert.assertEquals(lastInventory,afterInventory+1,"取消购买1个物品的待支付订单后，应返回1个库存数");


            //校验3：权益未涉及，数据中心的确认收入没有变化
            //获取数据中心-财务中心-营收明细-物品的确认收入
            JSONObject lastGetCostData_type=financeDataTools.getCostData_type("DAY","GOODS", TimeUtils.getTodayTime(),TimeUtils.getTodayEndTime(),info);
            BigDecimal lastConfirmedAmount=new BigDecimal(lastGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入
            Assert.assertEquals(lastConfirmedAmount,afterConfirmedAmount,"取消购买1个物品的待支付订单后，财务中心-营收明细-物品的确认收入应无变化");


        }
        else {
            System.out.println("物品购买校验未通过，不能下单");
        }

    }


    @Test(description = "购买0元多规格物品")
    public void testPurchaseGoods_PAID() {

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

        //切换端位
        info.setTerminal(Terminal.B);
        info.setLoginUser(LoginAccount.GYM_PROD);


        String goodsId2="1874413193018896386";

        //获取C端商品详情
        JSONObject getDetail_goods_C=goodCTools.getDetail_goods_C(goodsId2);
        String id=getDetail_goods_C.getJSONObject("result").getJSONObject("multiSpecInfo").getJSONArray("specCombinationList").getJSONObject(0).getString("id");
        BigDecimal price=new BigDecimal(getDetail_goods_C.getJSONObject("result").getJSONObject("multiSpecInfo").getJSONArray("specCombinationList").getJSONObject(0).getString("price"));
        int beforeInventory=Integer.parseInt(getDetail_goods_C.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(),info);
        BigDecimal beforeConfirmedAmount=new BigDecimal(beforeGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入

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

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


            //购买非0元多规格物品
            JSONObject  purchaseGoods=new JSONObject();
            purchaseGoods.put("depositAmount","0.00");
            purchaseGoods.put("depositCardId",null);
            purchaseGoods.put("memberId",memberId);
            purchaseGoods.put("memo","");
            purchaseGoods.put("objectId", RandomStringUtil.randomString(16));
            purchaseGoods.put("receivableAmount",price);
            purchaseGoods.put("goodsSpecId",id);
            purchaseGoods.put("price",price);
            purchaseGoods.put("quantity",1);
            purchaseGoods.put("studioId",dataApi.getLoginInfo().getStudioId());

            xmAppApi.doRequest(RequestType.JSON, params, purchaseGoods.toString(), headers).assetsSuccess(true);
            JSONObject purchaseGoodsResponse = xmAppApi.getBodyInJSON();
            orderId2=purchaseGoodsResponse.getJSONObject("result").getString("id");

            //校验1：获取B端订单详情：待支付状态
            JSONObject getDetailResult = orderTools.getDetail(orderId2,info);
            String businessNo= getDetailResult.getJSONObject("result").getString("businessNo");//订单号
            String state=getDetailResult.getJSONObject("result").getString("state");
            Assert.assertEquals(state,"PAID","未生成已完成物品订单");

            //校验2：C端商品详情库存数-1
            JSONObject afterGetDetail_goods_C=goodCTools.getDetail_goods_C(goodsId2);
            int afterInventory=Integer.parseInt(afterGetDetail_goods_C.getJSONObject("result").getJSONObject("multiSpecInfo").getJSONArray("specCombinationList").getJSONObject(0).getString("inventory"));
            Assert.assertEquals(afterInventory,beforeInventory-1,"购买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(),info);
            BigDecimal afterConfirmedAmount=new BigDecimal(afterGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入
            Assert.assertEquals(afterConfirmedAmount,beforeConfirmedAmount.add(price.setScale(2, RoundingMode.HALF_UP)),"购买1个物品生成待支付订单后，财务中心-营收明细-物品的确认收入应增加对应物品的价格");



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

        }
        else {
            System.out.println("物品购买校验未通过，不能下单");
        }


    }


    @Test(description = "购买0元单规格物品")
    public void testPurchaseGoods_PAID_single() {

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

        //切换端位
        info.setTerminal(Terminal.B);
        info.setLoginUser(LoginAccount.GYM_PROD);


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


        String goodsId3="1874411064376061954";
        //获取C端商品详情
        JSONObject getDetail_goods_C=goodCTools.getDetail_goods_C(goodsId3);
        String id=getDetail_goods_C.getJSONObject("result").getString("id");
        BigDecimal price=new BigDecimal(getDetail_goods_C.getJSONObject("result").getJSONObject("singleSpecInfo").getString("price"));
        int beforeInventory=Integer.parseInt(getDetail_goods_C.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(),info);
        BigDecimal beforeConfirmedAmount=new BigDecimal(beforeGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入

            //购买0元单规格物品
            JSONObject  purchaseGoods=new JSONObject();
            purchaseGoods.put("depositAmount","0.00");
            purchaseGoods.put("depositCardId",null);
            purchaseGoods.put("memberId",memberId);
            purchaseGoods.put("memo","");
            purchaseGoods.put("objectId", RandomStringUtil.randomString(16));
            purchaseGoods.put("receivableAmount",price);
            purchaseGoods.put("goodsSpecId",goodsId3);
            purchaseGoods.put("price",price);
            purchaseGoods.put("quantity",1);
            purchaseGoods.put("studioId",dataApi.getLoginInfo().getStudioId());

            xmAppApi.doRequest(RequestType.JSON, params, purchaseGoods.toString(), headers).assetsSuccess(true);
            JSONObject purchaseGoodsResponse = xmAppApi.getBodyInJSON();
            orderId3=purchaseGoodsResponse.getJSONObject("result").getString("id");

            //校验1：获取B端订单详情：已完成状态
            JSONObject getDetailResult = orderTools.getDetail(orderId3,info);
            String businessNo= getDetailResult.getJSONObject("result").getString("businessNo");//订单号
            String state=getDetailResult.getJSONObject("result").getString("state");
            Assert.assertEquals(state,"PAID","未生成已完成物品订单");

            //校验2：C端商品详情库存数-1
            JSONObject afterGetDetail_goods_C=goodCTools.getDetail_goods_C(goodsId3,info);
            int afterInventory=Integer.parseInt(afterGetDetail_goods_C.getJSONObject("result").getJSONObject("singleSpecInfo").getString("inventory"));
            Assert.assertEquals(afterInventory,beforeInventory-1,"购买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(),info);
            BigDecimal afterConfirmedAmount=new BigDecimal(afterGetCostData_type.getJSONObject("result").getString("confirmedAmount"));//确认收入
            Assert.assertEquals(afterConfirmedAmount,beforeConfirmedAmount.add(price.setScale(2, RoundingMode.HALF_UP)),"购买1个物品生成待支付订单后，财务中心-营收明细-物品的确认收入应增加对应物品的价格");
            


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

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

    orderTools.discard(orderId3, "重复录入", "已作废签单订单" + RandomStringUtil.randomString(10),info);

    }

}
