package com.ecep.contract.controller.vendor;

import java.io.File;
import java.time.format.DateTimeFormatter;
import java.util.List;

import org.springframework.util.StringUtils;

import com.ecep.contract.MyDateTimeUtils;
import com.ecep.contract.SpringApp;
import com.ecep.contract.VendorType;
import com.ecep.contract.controller.company.CompanyWindowController;
import com.ecep.contract.controller.tab.AbstEntityBasedTabSkin;
import com.ecep.contract.service.CompanyContactService;
import com.ecep.contract.service.QueryService;
import com.ecep.contract.service.VendorCatalogService;
import com.ecep.contract.service.VendorService;
import com.ecep.contract.service.VendorTypeService;
import com.ecep.contract.util.ComboBoxUtils;
import com.ecep.contract.util.UITools;
import com.ecep.contract.vm.CompanyContactViewModel;
import com.ecep.contract.vm.CompanyVendorViewModel;
import com.ecep.contract.vm.CompanyViewModel;
import com.ecep.contract.vo.CompanyContactVo;
import com.ecep.contract.vo.CompanyVo;
import com.ecep.contract.vo.VendorVo;

import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Tab;
import javafx.stage.DirectoryChooser;
import javafx.util.StringConverter;
import javafx.util.converter.LocalDateStringConverter;
import javafx.util.converter.LocalDateTimeStringConverter;

public class VendorTabSkinBase
        extends AbstEntityBasedTabSkin<VendorWindowController, VendorVo, CompanyVendorViewModel> {
    public VendorTabSkinBase(VendorWindowController controller) {
        super(controller);
    }

    CompanyContactService companyContactService;

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

    CompanyContactService getCompanyContactService() {
        if (companyContactService == null) {
            companyContactService = SpringApp.getBean(CompanyContactService.class);
        }
        return companyContactService;
    }

    @Override
    public void initializeTab() {
        // initializeBaseTabCompanyFieldAutoCompletion(controller.companyField);

        LocalDateStringConverter converter = new LocalDateStringConverter(DateTimeFormatter.ISO_LOCAL_DATE, null);

        controller.developDateField.setConverter(converter);
        controller.developDateField.valueProperty().bindBidirectional(viewModel.getDevelopDate());

        ComboBoxUtils.initialComboBox(controller.catalogField, viewModel.getCatalog(),
                getCachedBean(VendorCatalogService.class), true);

        initialTypeComboBox();

        controller.protocolProviderField.selectedProperty().bindBidirectional(viewModel.getProtocolProvider());
        UITools.autoCompletion(controller.contactField, viewModel.getContact(),
                new QueryService<CompanyContactVo, CompanyContactViewModel>() {
                    @Override
                    public CompanyContactVo findById(Integer id) {
                        return getCompanyContactService().findById(id);
                    }

                    @Override
                    public List<CompanyContactVo> search(String searchText) {
                        VendorVo vendor = getEntity();
                        CompanyVo company = controller.getCompanyService().findById(vendor.getCompanyId());
                        return getCompanyContactService().searchByCompany(company, searchText);
                    }

                    @Override
                    public StringConverter<CompanyContactVo> getStringConverter() {
                        return getCompanyContactService().getStringConverter();
                    }
                });
        controller.purchaseField.textProperty().bindBidirectional(viewModel.getPurchase());

        controller.pathField.textProperty().bind(viewModel.getPath());
        controller.descriptionField.textProperty().bindBidirectional(viewModel.getDescription());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter
                .ofPattern(MyDateTimeUtils.DEFAULT_DATETIME_FORMAT_PATTERN);
        controller.createdField.textProperty().bindBidirectional(viewModel.getCreated(),
                new LocalDateTimeStringConverter(dateTimeFormatter, null));
        controller.versionLabel.textProperty().bind(viewModel.getVersion().asString());

        controller.relativeCompanyBtn.disableProperty().bind(viewModel.getCompany().isNull());
        controller.relativeCompanyBtn.setOnAction(event -> {
            Integer companyId = viewModel.getCompany().get();
            ;
            CompanyVo company = controller.getCompanyService().findById(companyId);
            if (company != null) {
                showInOwner(CompanyWindowController.class, CompanyViewModel.from(company));
            }
        });

        controller.createPathBtn.setOnAction(this::onCreatePathAction);
        controller.changePathBtn.setOnAction(this::onChangePathAction);
        controller.pathAsNameBtn.setOnAction(this::onPathSameAsNameAction);
    }

    private void initialTypeComboBox() {
        VendorTypeService typeService = getCachedBean(VendorTypeService.class);
        ObservableList<VendorType> list = FXCollections.observableArrayList();
        ComboBox<VendorType> comboBox = controller.typeField;
        list.add(null);
        list.addAll(VendorType.values());
        comboBox.setItems(list);
        comboBox.setConverter(typeService.getTypeStringConverter());
        comboBox.valueProperty().bindBidirectional(viewModel.getType());
    }

    public void onCreatePathAction(ActionEvent event) {
        VendorVo companyVendor = getEntity();
        if (getCompanyVendorService().makePathAbsent(companyVendor)) {
            save(companyVendor);
        } else {
            setStatus("目录存在或创建失败");
        }
    }

    public void onChangePathAction(ActionEvent event) {
        DirectoryChooser chooser = new DirectoryChooser();
        VendorVo entity = getEntity();
        String path = entity.getPath();
        File initialDirectory = null;

        // 如果当前已经设置了目录并且路径有效，则设置初始目录为该目录
        if (StringUtils.hasText(path)) {
            File dir = new File(path);
            if (dir.exists()) {
                initialDirectory = dir;
            }
        }

        // 如果没有有效的初始目录，则使用基础路径
        if (initialDirectory == null) {
            initialDirectory = getCompanyVendorService().getBasePath();
        }

        if (initialDirectory != null) {
            chooser.setInitialDirectory(initialDirectory);
        }

        File newDirectory = chooser.showDialog(getTab().getContent().getScene().getWindow());
        if (newDirectory != null) {
            entity.setPath(newDirectory.getAbsolutePath());
            save(entity);
        }
    }

    public void onPathSameAsNameAction(ActionEvent event) {
        setStatus("未实现");
    }

    public VendorService getCompanyVendorService() {
        return controller.getViewModelService();
    }
}
