package com.ecep.contract.ds.contract.tasker;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.util.StringUtils;

import com.ecep.contract.ContractPayWay;
import com.ecep.contract.MessageHolder;
import com.ecep.contract.cloud.u8.YongYouU8Service;
import com.ecep.contract.cloud.u8.ctx.ContractCtx;
import com.ecep.contract.cloud.u8.ctx.PurchaseBillVoucherCtx;
import com.ecep.contract.cloud.u8.ctx.PurchaseOrderCtx;
import com.ecep.contract.cloud.u8.ctx.SalesBillVoucherCtx;
import com.ecep.contract.cloud.u8.ctx.SalesOrderCtx;
import com.ecep.contract.constant.CloudServiceConstant;
import com.ecep.contract.ds.contract.model.Contract;
import com.ecep.contract.ds.contract.service.ContractService;
import com.ecep.contract.ds.customer.model.SalesOrder;
import com.ecep.contract.ds.project.service.ProjectService;
import com.ecep.contract.ds.vendor.model.PurchaseOrder;
import com.ecep.contract.ui.Tasker;
import com.ecep.contract.vo.ContractVo;

import lombok.Getter;

public abstract class AbstContractRepairTasker extends Tasker<Object> {
    @Getter
    protected boolean filesUpdated = false;
    @Getter
    protected boolean itemsUpdated = false;
    @Getter
    protected boolean playPlanUpdated = false;
    @Getter
    protected boolean saleOrderUpdated = false;

    protected final ContractCtx contractCtx = new ContractCtx(this);
    protected SalesOrderCtx salesOrderCtx = null;
    protected SalesBillVoucherCtx salesBillVoucherCtx = null;
    protected PurchaseOrderCtx purchaseOrderCtx = null;
    protected PurchaseBillVoucherCtx purchaseBillVoucherCtx = null;

    SalesOrderCtx getSalesOrderCtx() {
        if (salesOrderCtx == null) {
            salesOrderCtx = new SalesOrderCtx(this);
        }
        return salesOrderCtx;
    }

    SalesBillVoucherCtx getSalesBillVoucherCtx() {
        if (salesBillVoucherCtx == null) {
            salesBillVoucherCtx = new SalesBillVoucherCtx(this);
        }
        return salesBillVoucherCtx;
    }

    PurchaseOrderCtx getPurchaseOrderCtx() {
        if (purchaseOrderCtx == null) {
            purchaseOrderCtx = new PurchaseOrderCtx(this);
        }
        return purchaseOrderCtx;
    }

    PurchaseBillVoucherCtx getPurchaseBillVoucherCtx() {
        if (purchaseBillVoucherCtx == null) {
            purchaseBillVoucherCtx = new PurchaseBillVoucherCtx(this);
        }
        return purchaseBillVoucherCtx;
    }

    @Override
    protected Object execute(MessageHolder holder) throws Exception {
        try {
            YongYouU8Service u8Service = getBean(YongYouU8Service.class);
            u8Service.initialize(contractCtx);
        } catch (NoSuchBeanDefinitionException ignored) {
            holder.warn("无法使用 " + CloudServiceConstant.U8_NAME + " 服务");
        }
        try {
            repair(holder);
        } catch (CannotGetJdbcConnectionException e) {
            throw new RuntimeException("无法获取的数据库连接", e);
        }
        return null;
    }

    protected abstract void repair(MessageHolder holder);

    /**
     * rs 数据从 CM_List 表中读取
     */
    protected boolean repairFromCMList(Map<String, Object> rs, MessageHolder holder) {
        String contractID = (String) rs.get("strContractID");
        String guid = (String) rs.get("GUID");
        String contractName = (String) rs.get("strContractName");
        String state = (String) rs.get("strState");

        holder.info("同步合同 " + contractID + " " + contractName);
        ContractVo contract = contractCtx.findOrCreatByGuidOrContractId(guid, contractID, holder);
        if (contract == null) {
            holder.warn("未知合同" + contractID + ", " + rs.get("strContractName"));
            return false;
        }

        boolean modified = false;
        if (contractCtx.updateText(contract::getCode, contract::setCode, contractID, holder, "合同编号")) {
            ContractService contractService = contractCtx.getContractService();
            ContractVo dup = contractService.findByCode(contractID);
            if (dup != null) {
                Contract contractEntity = contractService.getById(dup.getId());
                if (!Objects.equals(contract, contractEntity)) {
                    contractService.delete(contractEntity);
                    holder.warn("删除重复的合同 " + dup.getCode());
                }
            }
            modified = true;
        }
        if (contractCtx.updateText(contract::getGuid, contract::setGuid, guid, holder, "GUID")) {
            ContractService contractService = contractCtx.getContractService();
            var dup = contractService.findByGuid(guid);
            if (dup != null) {
                if (!Objects.equals(contract.getId(), dup.getId())) {
                    Contract dupEntity = contractService.getById(dup.getId());
                    contractService.delete(dupEntity);
                    holder.warn("删除重复的合同 " + dup.getCode());
                }
            }
            modified = true;
        }

        if (contractCtx.updateText(contract::getState, contract::setState, state, holder, "合同状态")) {
            modified = true;
        }

        if (modified) {
            contract = save(contract);
        }

        ContractVo parent = null;

        if (contract.getPayWay() == ContractPayWay.PAY) {
            if (StringUtils.hasText(contract.getParentCode())) {
                parent = contractCtx.findContractByCode(contract.getParentCode());
            }
        }
        AtomicReference<ContractVo> refer = new AtomicReference<>(contract);
        try {
            return repair(refer, parent, holder, progress -> {
            });
        } catch (Exception e) {
            holder.error(state);
            return false;
        }
    }

    protected ContractVo save(ContractVo contract) {
        return contractCtx.save(contract);
    }

    /**
     * @param contractProperty
     * @param holder
     * @param progress
     * @return
     */
    public boolean repair(
            AtomicReference<ContractVo> contractProperty,
            ContractVo parent, MessageHolder holder, Consumer<Double> progress) {
        boolean repaired = false;
        boolean modified = false;
        ContractVo contract = contractProperty.get();

        progress.accept(0.1);
        if (contractCtx.updateContractDetailByGuid(contract, contract.getGuid(), holder)) {
            modified = true;
        }
        progress.accept(0.2);
        if (contractCtx.updateContractExec(contract, holder)) {
            modified = true;
        }
        progress.accept(0.3);
        if (contractCtx.updateContractAmount(contract, holder)) {
            modified = true;
        }
        progress.accept(0.4);
        if (contractCtx.updateParentContract(contract, holder)) {
            modified = true;
        }
        if (contractCtx.updateContractPath(contract, holder)) {
            modified = true;
        }
        progress.accept(0.5);
        if (modified) {
            contract = save(contract);
            contractProperty.set(contract);
            modified = false;
            repaired = true;
        }
        progress.accept(0.6);
        if (contractCtx.syncContractItems(contract, holder)) {
            itemsUpdated = true;
            modified = true;
        }
        progress.accept(0.66);
        if (contractCtx.syncContractPayPlan(contract, holder)) {
            playPlanUpdated = true;
        }
        progress.accept(0.7);
        if (contractCtx.updateContractProject(contract, parent, holder)) {
            modified = true;
        }
        if (modified) {
            contract = save(contract);
            contractProperty.set(contract);
            modified = false;
            repaired = true;
        }
        progress.accept(0.8);
        // 销售合同
        if (contract.getPayWay() == ContractPayWay.RECEIVE) {
            syncSaleOrder(contract, holder);
            syncChildrenContract(contract, holder, p -> progress.accept(p * 0.1 + 0.8));

        } else if (contract.getPayWay() == ContractPayWay.PAY) {
            syncPurchaseOrder(contract, holder);
        }
        progress.accept(0.9);
        if (contractCtx.syncContractFiles(contract, holder)) {
            filesUpdated = true;
            repaired = true;
        }
        progress.accept(1.0);
        return repaired;
    }

    private void syncChildrenContract(ContractVo parent, MessageHolder holder, Consumer<Double> progress) {
        ContractService contractService = contractCtx.getContractService();
        ProjectService projectService = getCachedBean(ProjectService.class);
        List<Contract> list = contractService.findAllByParent(parent);
        for (int i = 0; i < list.size(); i++) {
            Contract v0 = list.get(i);
            ContractVo v1 = v0.toVo();
            holder.info("子合同 ： " + v1.getCode() + " " + v1.getName());
            MessageHolder subHolder = holder.sub(" -- ");
            boolean modified = false;
            Integer projectId = parent.getProject();
            if (projectId == null) {
                projectId = v1.getProject();
            }
            AtomicReference<ContractVo> contractProperty = new AtomicReference<>(v1);
            try {
                repair(contractProperty, parent, subHolder, p -> {
                });
                v1 = contractProperty.get();

                var projectVo = projectId == null ? null : projectService.findById(projectId);
                if (contractCtx.updateContractProject(v1, projectVo, subHolder)) {
                    modified = true;
                }
            } catch (Exception e) {
                throw new RuntimeException("同步子合同失败, 合同编号：" + v1.getCode(), e);
            }
            if (modified) {
                try {
                    v1 = save(v1);
                } catch (Exception e) {
                    throw new RuntimeException("#" + v1.getId() + ", ver=" + v1.getVersion(), e);
                }
                modified = false;
            }
            progress.accept((double) i / list.size());
        }
    }

    /**
     * 同步合同的销售订单
     *
     * @param contract 合同
     * @param holder   消息
     */
    private void syncSaleOrder(ContractVo contract, MessageHolder holder) {
        SalesOrderCtx ctx = getSalesOrderCtx();
        if (ctx.getRepository() == null) {
            return;
        }
        List<SalesOrder> orders = ctx.syncByContract(contract, holder);
        if (orders == null) {
            return;
        }
        SalesBillVoucherCtx voucherCtx = getSalesBillVoucherCtx();
        for (SalesOrder order : orders) {
            voucherCtx.syncBySalesOrder(order, holder);
        }
    }

    /**
     * 同步合同采购订单
     *
     * @param contract 合同
     * @param holder   消息
     */
    private void syncPurchaseOrder(ContractVo contract, MessageHolder holder) {
        PurchaseOrderCtx ctx1 = getPurchaseOrderCtx();
        if (ctx1.getRepository() != null) {
            List<PurchaseOrder> orders = ctx1.syncByContract(contract, holder);
            if (orders == null) {
                holder.warn("没有采购订单异常");
            }
        }

        PurchaseBillVoucherCtx ctx2 = getPurchaseBillVoucherCtx();
        if (ctx2.getRepository() != null) {
            ctx2.syncByContract(contract, holder);
        }
    }
}
