package com.ecep.contract.service.tasker;

import java.util.concurrent.atomic.AtomicReference;

import com.ecep.contract.ds.contract.service.ContractService;
import com.ecep.contract.ds.contract.tasker.AbstContractRepairTasker;
import com.ecep.contract.ds.contract.tasker.ContractRepairComm;
import com.ecep.contract.vo.ContractVo;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.util.StringUtils;

import com.ecep.contract.ContractPayWay;
import com.ecep.contract.MessageHolder;
import com.ecep.contract.ds.contract.model.Contract;

import lombok.Getter;

/**
 * 合同修复任务
 */
public class ContractRepairTasker extends AbstContractRepairTasker implements WebSocketServerTasker {
    @Getter
    private ContractVo contract;
    @Getter
    boolean repaired = false;


    private final ContractRepairComm comm = new ContractRepairComm();

    public ContractRepairTasker() {
    }

    public void init(JsonNode argsNode) {
        int contractId = argsNode.get(0).asInt();
        contract = getCachedBean(ContractService.class).findById(contractId);
    }

    @Override
    protected void repair(MessageHolder holder) {
        updateTitle("修复合同 " + contract.getCode() + " - " + contract.getName());
        ContractVo parent = null;

        if (contract.getPayWay() == ContractPayWay.PAY) {
            if (StringUtils.hasText(contract.getParentCode())) {
                parent = contractCtx.findContractByCode(contract.getParentCode());
                holder.info("找到上级合同 " + parent.getCode() + " - " + parent.getName());
            }
        }

        AtomicReference<ContractVo> contractProperty = new AtomicReference<>(contract);
        if (repair(contractProperty, parent, holder, progress -> updateProgress(progress, 1))) {
            repaired = true;
            updateProperty("repaired", true);
        }

        setContract(contractProperty.get());

        updateProgress(100, 100);
    }

    public void setContract(ContractVo contract) {
        this.contract = contract;
        updateProperty("contract", contract);
    }

}
