package com.ecep.contract.cloud.u8;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;

import org.hibernate.Hibernate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;

import com.ecep.contract.MessageHolder;
import com.ecep.contract.SpringApp;
import com.ecep.contract.cloud.u8.ctx.CompanyCtx;
import com.ecep.contract.cloud.u8.ctx.VendorCtx;
import com.ecep.contract.constant.CloudServiceConstant;
import com.ecep.contract.ds.company.service.CompanyService;
import com.ecep.contract.ds.contract.tasker.AbstContractRepairTasker;
import com.ecep.contract.ds.vendor.service.VendorEntityService;
import com.ecep.contract.ds.vendor.service.VendorService;
import com.ecep.contract.model.CloudYu;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.Vendor;
import com.ecep.contract.model.VendorEntity;

import lombok.Setter;

/**
 * 供应商同步任务
 */
public class VendorSyncTask extends AbstContractRepairTasker {
    private static final Logger logger = LoggerFactory.getLogger(VendorSyncTask.class);
    private final VendorCtx vendorCtx = new VendorCtx();
    private VendorService vendorService;
    private VendorEntityService vendorEntityService;
    private YongYouU8Repository repository;
    @Setter
    private YongYouU8Service yongYouU8Service;

    public VendorSyncTask() {
        updateTitle("用友U8系统-同步供应商");
    }

    private VendorService getVendorService() {
        if (vendorService == null) {
            vendorService = SpringApp.getBean(VendorService.class);
        }
        return vendorService;
    }

    private VendorEntityService getVendorEntityService() {
        if (vendorEntityService == null) {
            vendorEntityService = SpringApp.getBean(VendorEntityService.class);
        }
        return vendorEntityService;
    }

    @Override
    protected void repair(MessageHolder holder) {
        try {
            yongYouU8Service = getBean(YongYouU8Service.class);
        } catch (BeansException e) {
            holder.warn("未启用 " + CloudServiceConstant.U8_NAME + " 服务");
            return;
        }
        repository = SpringApp.getBean(YongYouU8Repository.class);
        yongYouU8Service.initialize(vendorCtx);

        AtomicInteger counter = new AtomicInteger(0);
        Long total = repository.countAllVendors();
        updateTitle("用友U8系统-同步供应商，合计 " + total + " 条");

        try (Stream<Map<String, Object>> stream = repository.queryAllVendorForStream()) {
            stream.forEach(rs -> {
                if (isCancelled()) {
                    updateMessage("Cancelled");
                    return;
                }
                try {
                    String venCode = (String) rs.get("cVenCode");
                    MessageHolder subHolder = holder.sub(counter.get() + " / " + total + "> " + venCode + " ");
                    boolean modified = false;
                    VendorEntity entity = vendorCtx.findOrCreateByCode(venCode, subHolder);
                    Map<String, Object> map = repository.findVendorByVendCode(entity.getCode());
                    if (map == null) {
                        subHolder.error("供应商项不存在：" + venCode);
                        return;
                    }
                    if (vendorCtx.applyEntityDetail(entity, map, subHolder)) {
                        modified = true;
                    }
                    if (modified) {
                        entity = getVendorEntityService().save(entity);
                    }
                    updateCompanyNameAndAbbName(entity, subHolder);
                    updateCloudYu(entity);

                } catch (Exception e) {
                    logger.error("Vendor sync failure {}, data = {}", e.getMessage(), rs, e);
                    updateMessage(e.getMessage());
                    throw e;
                }
                updateProgress(counter.incrementAndGet(), total);
            });
        }
    }

    private void updateCloudYu(VendorEntity entity) {
        Vendor vendor = entity.getVendor();
        if (vendor == null) {
            return;
        }
        if (!Hibernate.isInitialized(vendor)) {
            vendor = getVendorService().findById(vendor.getId());
        }
        Company company = vendor.getCompany();
        if (company == null) {
            return;
        }
        CloudYu cloudYu = yongYouU8Service.getOrCreateCloudYu(company);
        if (cloudYu == null) {
            return;
        }
        cloudYu.setVendorUpdateDate(LocalDate.now());
        cloudYu.setCloudLatest(LocalDateTime.now());
        cloudYu.setExceptionMessage("");
        yongYouU8Service.save(cloudYu);
    }

    private void updateCompanyNameAndAbbName(VendorEntity entity, MessageHolder holder) {
        CompanyService companyService = vendorCtx.getCompanyService();
        Vendor vendor = entity.getVendor();
        if (vendor == null) {
            return;
        }
        if (!Hibernate.isInitialized(vendor)) {
            vendor = getVendorService().findById(vendor.getId());
        }
        Company company = vendor.getCompany();
        if (company == null) {
            return;
        }
        if (!Hibernate.isInitialized(company)) {
            company = companyService.findById(company.getId());
        }
        boolean modified = false;
        CompanyCtx companyCtx = vendorCtx.getCompanyCtx();
        if (companyCtx.updateCompanyNameIfAbsent(company, entity.getName(), holder)) {
            modified = true;
        }
        if (companyCtx.updateCompanyAbbNameIfAbsent(company, entity.getAbbName(), holder)) {
            modified = true;
        }
        if (modified) {
            companyService.save(company);
        }
    }

}
