package com.xiaomai.cases.polar.member;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.cases.polar.clue.MemberTools;
import com.xiaomai.cases.polar.finance.order.OrderTools;
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.math.BigDecimal;

public class TestForceUpdate extends XMBaseTest {
    String cardId;

    String getDetailId;

    OrderTools orderTools=new OrderTools();

    CardTools cardTools=new CardTools();
    Tools tools= new Tools();

    MemberTools memberTools=new MemberTools();


    @BeforeMethod
    public void beforeTest(){
        xmAppApi.setApiModule(ApiModule.Polar_Clue)
                .setApiName("API_forceUpdate")
                .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  testForceUpdate() {


        //编辑正式会员信息

        //创建潜在会员
        JSONObject create = tools.create("潜在会员" + RandomStringUtil.randomString(3), RandomStringUtil.randomMobile("88"));
        String memberId = create.getString("result");

        //创建订单线索会员转正式会员（状态流转：线索转正式）

        //获取会员卡信息
        //获取会员卡列表,没有则新建一个
        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",true);
            getDetailId = orderResult.getString("result");

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

        }

        //获取正式会员列表
        JSONObject memberResult = tools.search("NORMAL", "NORMAL");

        int memberResultPages = Integer.parseInt(memberResult.getJSONObject("result").getString("pages"));
        int memberResultTotal = Integer.parseInt(memberResult.getJSONObject("result").getString("total"));


        for (int k = 0; k == memberResultPages + 1; k++) {
            int n = k == memberResultPages ? (memberResultTotal % 10 == 0 ? 10 : memberResultTotal % 10) : 10;
            JSONArray records = memberResult.getJSONObject("result").getJSONArray("records");
            boolean flag = true;
            for (int i = 0; i < n; i++) {
                String memberResultId = records.getJSONObject(i).getString("id");
                if (memberResultId.equals(memberId)) {
                    flag = true;
                    break;
                }
            }
            Assert.assertEquals(true, flag, "潜在会员购买订单已完成,但潜在会员转正式会员失败");
        }

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


        //编辑正式会员
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("brandId", xmAppApi.getLoginInfo().getBrandId());
        jsonObject.put("studioId", xmAppApi.getLoginInfo().getStudioId());
        jsonObject.put("operatorId", xmAppApi.getLoginInfo().getAdminId());
        jsonObject.put("status", "NORMAL");
        jsonObject.put("name", "自动化正式会员" + RandomStringUtil.randomString(2));
        jsonObject.put("phone", RandomStringUtil.randomMobile("22"));
        jsonObject.put("gender", "WOMEN");
        jsonObject.put("wechat", RandomStringUtil.randomMobile("66"));
        jsonObject.put("birthday", TimeUtils.getBeforeDayDate(10));
        jsonObject.put("idCardType", "IDENTITY");
        jsonObject.put("idCardCode", "411421199808080225");
        jsonObject.put("height", "186");
        jsonObject.put("weight", "76");
        jsonObject.put("trainTarget", "塑形");
        jsonObject.put("profession", "金融");
        jsonObject.put("incomeLevel", "亿万富翁");
        jsonObject.put("address", "地址");
        jsonObject.put("emergencyContactPerson", RandomStringUtil.randomString(3));
        jsonObject.put("emergencyContactPhone", RandomStringUtil.randomMobile("66"));
        jsonObject.put("resourceId", "1");
        jsonObject.put("intention", "HIGH");
        jsonObject.put("creatorId", xmAppApi.getLoginInfo().getAdminId());
        jsonObject.put("remark", "备注备注备注备注备注备注备注备注");
        jsonObject.put("memberId", memberId);


        xmAppApi.doRequest(RequestType.JSON, params, jsonObject.toJSONString(), headers).assetsSuccess(true);
        Assert.assertEquals(XMJSONPath.readPath(xmAppApi.getBodyInJSON(), "$success"), "true", "编辑正式会员信息失败");

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

        //校验编辑正式会员信息
        //获取正式会员详情
        JSONObject result = memberTools.findStudioMemberDetail(memberId).getJSONObject("result");
        Assert.assertEquals(result.getString("status"), "NORMAL", "订单购买成功后，潜在学员未转成正式会员");
        Assert.assertEquals(result.getString("gender"), "WOMEN", "编辑之后，性别编辑失败");
        Assert.assertEquals(result.getString("idCardType"), "IDENTITY", "编辑之后，证件类型编辑失败");
        Assert.assertEquals(result.getString("idCardCode"), "411421199808080225", "编辑之后，身份证号编辑失败");
        Assert.assertEquals(result.getString("height"), "186", "编辑之后，身高编辑失败");
        Assert.assertEquals(result.getString("weight"), "76", "编辑之后，体重编辑失败");
        Assert.assertEquals(result.getString("trainTarget"), "塑形", "编辑之后，训练目标编辑失败");
        Assert.assertEquals(result.getString("profession"), "金融", "编辑之后，职业编辑失败");
        Assert.assertEquals(result.getString("incomeLevel"), "亿万富翁", "编辑之后，收入水平编辑失败");
        Assert.assertEquals(result.getString("address"), "地址", "编辑之后，地址编辑失败");
        Assert.assertEquals(result.getString("resourceId"), "1", "编辑之后，来源编辑失败");
        Assert.assertEquals(result.getString("remark"), "备注备注备注备注备注备注备注备注", "编辑之后，备注编辑失败");


        //编辑流失会员信息


        //退单正式会员转流失会员（状态流转：正式转流失）

        //退单
        //创建退单订单
        //查询要退的卡id 从listUserRefundableCard-查询用户可退的会员卡列表中获取
        JSONObject listUserRefundableCardResult = orderTools.listUserRefundableCard("MEMBER", "", memberId);
        String listUserRefundableId = listUserRefundableCardResult.getJSONArray("result").getJSONObject(0).getString("id");

        //查询订单或者收支可退流水金额（包含乐动收银状态信息）
        boolean checkRefundableAmountResult = orderTools.checkRefundableAmount(getDetailId, price - price / 2).getBoolean("success");

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

        if (checkRefundableAmountResult == true) {
            //退单-会员卡
            JSONObject refundOrderResult = orderTools.refundOrder(0, listUserRefundableId, quantity, price - price / 2, "MEMBER_CARD",
                    memberId, price - price / 2, price - price / 2, "1");
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }

        //获取流失会员列表
        JSONObject historyResult = tools.search("HISTORY", "HISTORY").getJSONObject("result");
        String historyId = historyResult.getJSONArray("records").getJSONObject(0).getString("id");
        String historyStatus = historyResult.getJSONArray("records").getJSONObject(0).getString("status");
        Assert.assertEquals(historyId, memberId, "列表中的流失会员非上述正式转流失的会员");
        Assert.assertEquals(historyStatus, "HISTORY", "正式会员转流失会员失败");

        //获取会员详情
        JSONObject historyDetailResult = memberTools.findStudioMemberDetail(memberId).getJSONObject("result");
        String historyDetailStatus = historyDetailResult.getString("status");
        Assert.assertEquals(historyDetailStatus, "HISTORY", "正式会员退单已完成,正式会员转流失会员失败");

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

        //编辑流失会员
        JSONObject object = new JSONObject();
        object.put("brandId", xmAppApi.getLoginInfo().getBrandId());
        object.put("studioId", xmAppApi.getLoginInfo().getStudioId());
        object.put("operatorId", xmAppApi.getLoginInfo().getAdminId());
        object.put("status", "HISTORY");
        object.put("name", "自动化流失会员" + RandomStringUtil.randomString(2));
        object.put("phone", RandomStringUtil.randomMobile("22"));
        object.put("gender", "MAN");
        object.put("wechat", RandomStringUtil.randomMobile("66"));
        object.put("birthday", TimeUtils.getBeforeDayDate(10));
        object.put("idCardType", "IDENTITY");
        object.put("idCardCode", "411421199808080888");
        object.put("height", "196");
        object.put("weight", "86");
        object.put("trainTarget", "爵士");
        object.put("profession", "公务员");
        object.put("incomeLevel", "千万富翁");
        object.put("address", "河南省郑州市");
        object.put("emergencyContactPerson", RandomStringUtil.randomString(3));
        object.put("emergencyContactPhone", RandomStringUtil.randomMobile("66"));
        object.put("resourceId", "2");
        object.put("intention", "HIGH");
        object.put("creatorId", xmAppApi.getLoginInfo().getAdminId());
        object.put("remark", "备注");
        object.put("memberId", memberId);

        xmAppApi.doRequest(RequestType.JSON, params, object.toJSONString(), headers).assetsSuccess(true);
        Assert.assertEquals(XMJSONPath.readPath(xmAppApi.getBodyInJSON(), "$success"), "true", "编辑流失会员信息失败");

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

        //校验编辑流失会员信息
        //获取流失会员详情
        JSONObject historyDetailResult1 = memberTools.findStudioMemberDetail(memberId).getJSONObject("result");
        Assert.assertEquals(historyDetailResult1.getString("status"), "HISTORY", "退单成功后，正式学员未转成流失会员");
        Assert.assertEquals(historyDetailResult1.getString("gender"), "MAN", "编辑之后，性别编辑失败");
        Assert.assertEquals(historyDetailResult1.getString("idCardType"), "IDENTITY", "编辑之后，证件类型编辑失败");
        Assert.assertEquals(historyDetailResult1.getString("idCardCode"), "411421199808080888", "编辑之后，身份证号编辑失败");
        Assert.assertEquals(historyDetailResult1.getString("height"), "196", "编辑之后，身高编辑失败");
        Assert.assertEquals(historyDetailResult1.getString("weight"), "86", "编辑之后，体重编辑失败");
        Assert.assertEquals(historyDetailResult1.getString("trainTarget"), "爵士", "编辑之后，训练目标编辑失败");
        Assert.assertEquals(historyDetailResult1.getString("profession"), "公务员", "编辑之后，职业编辑失败");
        Assert.assertEquals(historyDetailResult1.getString("incomeLevel"), "千万富翁", "编辑之后，收入水平编辑失败");
        Assert.assertEquals(historyDetailResult1.getString("address"), "河南省郑州市", "编辑之后，地址编辑失败");
        Assert.assertEquals(historyDetailResult1.getString("resourceId"), "2", "编辑之后，来源编辑失败");
        Assert.assertEquals(historyDetailResult1.getString("remark"), "备注", "编辑之后，备注编辑失败");


    }

}
