package com.xiaomai.cases.polar.eleContract;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaomai.basetest.BaseTestImpl;
import com.xiaomai.cases.polar.finance.order.OrderTools;
import com.xiaomai.cases.polar.training.TrainingTools;
import com.xiaomai.enums.ApiModule;
import com.xiaomai.enums.LoginAccount;
import com.xiaomai.enums.RequestType;
import com.xiaomai.enums.Terminal;
import com.xiaomai.utils.TimeUtils;
import org.testng.Assert;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import javax.annotation.Resource;

/**
 * @BelongsProject: xm-sportstest
 * @BelongsPackage: com.xiaomai.cases.polar.eleContract
 * @Author: xuyamei
 * @CreateTime: 2024-08-05  18:01
 * @Description: 发起合同、撤回合同
 * @Version: 1.0
 */
public class TestStartContractV2 extends BaseTestImpl {

    @Resource(name = "eleContractTools")
    EleContractTools eleContractTools;

    @Resource(name = "trainingTools")
    TrainingTools trainingTools;
    @Resource(name = "orderTools")
    OrderTools orderTools;

    @BeforeMethod
    @Override
    public void beforeTest(){
        setTestInfo(ApiModule.Polar_EleContract,"API_startContractV2", LoginAccount.DZHT_PROD, Terminal.B,"xym");
        super.beforeTest();
    }

    private String eleContractId;
    private String studentId;

    @Test(description = "发起电子合同")
    public void testStartContractV2(){
        // 查询发起的合同的学员
        studentId = trainingTools.searchTargerMember("13120057004");

        // 获取合同模版编辑内容
        String templateId = eleContractTools.getNormalTemplateList("自动化").getJSONObject(0).getString("id");
        JSONObject getContractEditDisplay = eleContractTools.getContractEditDisplay(templateId);
        String contractName = "自动化发起合同"+ TimeUtils.getCurrentTime();

        JSONObject body = new JSONObject();
        body.put("targetId",studentId); // 学员id
        body.put("studioId",xmAppApi.getLoginInfo().getStudioId()); // 学员id
        body.put("adminId",xmAppApi.getLoginInfo().getAdminId()); // 学员id
        // contractList 存放模版具体的内容
        JSONArray contractList = new JSONArray();
        JSONObject contract = new JSONObject();
        contract.put("studioId",xmAppApi.getLoginInfo().getStudioId());
        contract.put("contractName",contractName);
        contract.put("templateId",templateId);

        JSONArray contractFiledRequestList = new JSONArray();
        int size = getContractEditDisplay.getJSONObject("templateVO").getJSONArray("fieldConfigVOList").size();

        // 企业信息和场馆信息塞进去
        for (int i = 0;i<getContractEditDisplay.getJSONArray("contractPdfVOList").getJSONObject(0).getJSONArray("contractFieldVOList").size();i++){
            JSONObject contractFiledRequest = new JSONObject();
            contractFiledRequest.put("id",getContractEditDisplay.getJSONArray("contractPdfVOList").getJSONObject(0).getJSONArray("contractFieldVOList").getJSONObject(i).getString("id"));
            contractFiledRequest.put("templateField",getContractEditDisplay.getJSONArray("contractPdfVOList").getJSONObject(0).getJSONArray("contractFieldVOList").getJSONObject(i).getString("templateField"));
            contractFiledRequest.put("value",getContractEditDisplay.getJSONArray("contractPdfVOList").getJSONObject(0).getJSONArray("contractFieldVOList").getJSONObject(i).getString("value"));
            contractFiledRequestList.add(contractFiledRequest);
        }


        // 模版中的其余信息
        for (int i=0;i<size;i++){
            JSONObject contractFiledRequest = new JSONObject();
            String templateField = getContractEditDisplay.getJSONObject("templateVO").getJSONArray("fieldConfigVOList").getJSONObject(i).getString("templateField");
            if (!templateField.equals("COMPANY_NAME") && !templateField.equals("TENANT_NAME") && !templateField.equals("COMPANY_SIGNATURE") && !templateField.equals("PERSON_SIGNATURE")) { // 获取的内容不包含类型为企业名称、校区名称、企业签章、家长签字
                contractFiledRequest.put("id", getContractEditDisplay.getJSONObject("templateVO").getJSONArray("fieldConfigVOList").getJSONObject(i).getString("id"));
                contractFiledRequest.put("templateField", templateField);
                contractFiledRequest.put("value", "");
                contractFiledRequestList.add(contractFiledRequest);
            } else if(templateField.equals("MEMBER_NAME")){
                contractFiledRequest.put("id", getContractEditDisplay.getJSONObject("templateVO").getJSONArray("fieldConfigVOList").getJSONObject(i).getString("id"));
                contractFiledRequest.put("templateField", templateField);
                contractFiledRequest.put("value", "测试学员");
                contractFiledRequestList.add(contractFiledRequest);
            } else if (templateField.equals("PHONE")){
                contractFiledRequest.put("id", getContractEditDisplay.getJSONObject("templateVO").getJSONArray("fieldConfigVOList").getJSONObject(i).getString("id"));
                contractFiledRequest.put("templateField", templateField);
                contractFiledRequest.put("value", "13120057004");
                contractFiledRequestList.add(contractFiledRequest);
            }

        }

        contract.put("contractFiledRequestList",contractFiledRequestList);
        contractList.add(contract);
        body.put("contractList",contractList);
        xmAppApi.doRequest(RequestType.JSON,params,body.toString(),headers).assetsSuccess(true);
        String taskId = xmAppApi.getBodyInJSON().getString("result");

        // 获取发起合同任务的状态
        eleContractTools.getStartContractV2Result(taskId);
        while (true){
            boolean result = eleContractTools.getStartContractV2Result(taskId);
            if (result){
                break;
            }
        }

        // 验证1：合同列表 合同状态为待签署
        boolean dataExist = false;
        JSONArray getContractPage = eleContractTools.getContractPage(studentId,"","").getJSONArray("records");
        for (int i=0;i<getContractPage.size();i++){
            if (getContractPage.getJSONObject(i).getString("name").equals(contractName)){
                dataExist = true;
                eleContractId = getContractPage.getJSONObject(i).getString("id");
                Assert.assertEquals(getContractPage.getJSONObject(i).getString("contractStatus"),"WAIT_C");
            }
        }
        Assert.assertTrue(dataExist,"发起合同后在合同列表没有查到相关合同");

        // 待签署的合同数量
        int total = Integer.parseInt(eleContractTools.getContractPage("","","WAIT_C").getString("total"));
        // 验证2：校验锁定额度
        int lockAmount =eleContractTools.getValidBalanceList().getJSONObject(0).getInteger("lockAmount");
        Assert.assertTrue(lockAmount==total,"锁定额度与合同列表中待签署合同数量不一致");

        // 验证3：合同状态、归属人
        JSONObject getContract = eleContractTools.getContract(eleContractId);
        String[] keys = {"contractStatus","targetId"};
        String[] values = {"WAIT_C",studentId};
        for (int i=0;i<keys.length;i++){
            Assert.assertEquals(getContract.getString(keys[i]),values[i],"合同状态、归属人与预期不一致");
        }

    }
    @Test(priority = 1,description = "复制签署地址")
    public void testGetContractSignUrl(){
        String URL= eleContractTools.getContractSignUrl(eleContractId);
        Assert.assertTrue(!URL.equals(""),"复制签署地址失败");

        // 验证一下有待签署的合同，不允许重新认证
        Assert.assertTrue(eleContractTools.checkBeforeResetVerify(),"有待签署的合同，但是重新认证校验返回的false");
    }

    @Test(priority = 1,description = "关联订单")
    public void testAssociate(){
        // 关联订单
        // 查询学员关联的id
        JSONObject body = new JSONObject();
        body.put("current",0);
        body.put("size",20);
        body.put("receiverId",studentId);
        body.put("supplierId",xmAppApi.getLoginInfo().getStudioId());
        body.put("type","SIGN");
        String[] status = {"WAITING", "PAID", "DELINQUENT"};
        body.put("states",status);
        body.put("brandId",xmAppApi.getLoginInfo().getBrandId());
        body.put("studioId",xmAppApi.getLoginInfo().getStudioId());
        body.put("operatorId",xmAppApi.getLoginInfo().getAdminId());
        JSONArray pageVoucher = orderTools.pageVoucher(body);

        // 获取一条订单id
        String orderId = "";
        String businessNo = "";
        for (int i=0;i<pageVoucher.size();i++){
            if (pageVoucher.getJSONObject(i).getString("source").equals("OFFLINE_SOURCE")){
                businessNo = pageVoucher.getJSONObject(i).getString("businessNo");
                orderId = pageVoucher.getJSONObject(i).getString("id");
            }
        }

        eleContractTools.associate(eleContractId,businessNo,orderId);

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

        // 验证1：合同详情 合同关联的订单id
        JSONObject getContract = eleContractTools.getContract(eleContractId);
        Assert.assertEquals(getContract.getString("associatedNo"),businessNo,"合同关联的订单号与实际不一致");
        Assert.assertEquals(getContract.getString("associatedId"),orderId,"合同关联的订单id与实际不一致");

    }


    @Test(priority = 3,description = "取消关联订单")
    public void testDisAssociate(){
        // 取消关联
        eleContractTools.disAssociate(eleContractId);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // 验证1：合同详情 合同关联的订单id
        JSONObject getContract = eleContractTools.getContract(eleContractId);
        Assert.assertEquals(getContract.getString("associatedNo"),"","合同取消关联的订单后关联的订单不为空");

    }
    @Test(priority = 4,description = "撤销电子合同")
    public void testRetractContract(){
        eleContractTools.retractContract(eleContractId);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        // 验证1：合同详情 合同状态为已撤回
        JSONObject getContract = eleContractTools.getContract(eleContractId);
        Assert.assertEquals(getContract.getString("contractStatus"),"REVOKE","合同状态非已撤回");

        // 待签署的合同数量
        int total = Integer.parseInt(eleContractTools.getContractPage("","","WAIT_C").getString("total"));
        // 验证2：校验锁定额度
        int lockAmount =eleContractTools.getValidBalanceList().getJSONObject(0).getInteger("lockAmount");
        Assert.assertTrue(lockAmount==total,"锁定额度与合同列表中待签署合同数量不一致");


    }


}
