package com.ecep.contract.controller.contract;

import java.util.List;
import java.util.concurrent.CompletableFuture;

import com.ecep.contract.SpringApp;
import com.ecep.contract.controller.ComboBoxUtils;
import com.ecep.contract.model.VendorGroup;
import com.ecep.contract.service.ExtendVendorInfoService;
import com.ecep.contract.service.VendorGroupService;
import com.ecep.contract.util.FxmlPath;
import com.ecep.contract.util.UITools;
import com.ecep.contract.vm.ExtendVendorInfoViewModel;
import com.ecep.contract.vo.ContractVo;
import com.ecep.contract.vo.ExtendVendorInfoVo;
import com.ecep.contract.vo.VendorGroupVo;

import javafx.application.Platform;
import javafx.beans.binding.Bindings;
import javafx.beans.property.BooleanProperty;
import javafx.fxml.FXML;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import javafx.util.converter.NumberStringConverter;
import lombok.Setter;

@FxmlPath("/ui/contract/contract-tab-ext-vendor-info.fxml")
public class ContractTabSkinExtendVendorInfo extends AbstContractBasedTabSkin {

    /**
     * VendorGroup
     */
    @FXML
    public ComboBox<VendorGroupVo> vendorGroupField;
    @FXML
    public Label vendorGroupLabel;
    @FXML
    public TextField sequenceNumberField;
    @FXML
    public CheckBox assignedProviderField;
    @FXML
    public CheckBox prePurchaseField;

    CompletableFuture<ExtendVendorInfoVo> loadedFuture;
    private ExtendVendorInfoViewModel viewModel = new ExtendVendorInfoViewModel();

    public ContractTabSkinExtendVendorInfo(ContractWindowController controller) {
        super(controller);
    }

    @Override
    public Tab getTab() {
        return controller.extendVendorInfo;
    }

    @Override
    public void initializeUIComponents() {
        super.initializeUIComponents();
        listenTabSelectionChanged();
    }

    @Override
    public BooleanProperty changeProperty() {
        return viewModel.getChanged();
    }

    @Override
    public void onTabShown() {
        if (loadedFuture == null) {
            loadedFuture = CompletableFuture.supplyAsync(() -> {
                initializeTab();
                ContractVo contract = getEntity();
                return loadExtendVendorInfo(contract);
            });
        }
    }

    void updateViewModel(ExtendVendorInfoVo info) {
        if (Platform.isFxApplicationThread()) {
            viewModel.update(info);
        } else {
            Platform.runLater(() -> viewModel.update(info));
        }
    }

    private ExtendVendorInfoVo loadExtendVendorInfo(ContractVo contract) {
        ExtendVendorInfoService service = getExtendVendorInfoService();
        try {
            ExtendVendorInfoVo info = service.findByContract(contract);
            if (info == null) {
                info = new ExtendVendorInfoVo();
                info.setContractId(contract.getId());
                // 注意：这里可能需要调整，取决于service接口的实现
            }
            updateViewModel(info);
            viewModel.bindListener();
            return info;
        } catch (Exception e) {
            UITools.showExceptionAndWait("加载成本时发生错误", e);
            throw e;
        }
    }

    @Override
    public void initializeTab() {
        ComboBoxUtils.initialComboBox(vendorGroupField, viewModel.getGroup(), getVendorGroupService(), true);
        vendorGroupLabel.textProperty().bind(vendorGroupField.valueProperty().map(v -> {
            if (v == null) {
                return "-";
            }
            return v.getDescription();
        }));

        sequenceNumberField.textProperty().bindBidirectional(viewModel.getCodeSequenceNumber(),
                new NumberStringConverter());
        assignedProviderField.selectedProperty().bindBidirectional(viewModel.getAssignedProvider());
        assignedProviderField.disableProperty().bind(Bindings.createBooleanBinding(() -> {
            Integer groupId = viewModel.getGroup().get();
            VendorGroupVo group = getVendorGroupService().findById(groupId);
            if (group == null) {
                return false;
            }
            return !group.isPriceComparison();
        }, viewModel.getGroup()));

        prePurchaseField.selectedProperty().bindBidirectional(viewModel.getPrePurchase());
    }

    @Override
    public void save() {
        if (loadedFuture != null) {
            ExtendVendorInfoVo vendorInfo = loadedFuture.join();
            if (viewModel.copyTo(vendorInfo)) {
                // 注意：这里需要根据实际service接口实现调整，可能需要调用不同的方法
                // ExtendVendorInfoVo saved = getExtendVendorInfoService().saveVo(vendorInfo);
                // updateViewModel(saved);
                // loadedFuture = CompletableFuture.completedFuture(saved);
            }
        }
    }

    public ExtendVendorInfoService getExtendVendorInfoService() {
        return getCachedBean(ExtendVendorInfoService.class);
    }

    public VendorGroupService getVendorGroupService() {
        return getCachedBean(VendorGroupService.class);
    }
}
