package com.ecep.contract.controller.customer;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.springframework.util.StringUtils;

import com.ecep.contract.MyDateTimeUtils;
import com.ecep.contract.controller.company.CompanyWindowController;
import com.ecep.contract.controller.tab.AbstEntityBasedTabSkin;
import com.ecep.contract.controller.tab.TabSkin;
import com.ecep.contract.service.CompanyContactService;
import com.ecep.contract.service.CompanyCustomerService;
import com.ecep.contract.service.CompanyService;
import com.ecep.contract.util.UITools;
import com.ecep.contract.vm.CompanyCustomerViewModel;
import com.ecep.contract.vo.CompanyCustomerVo;
import com.ecep.contract.vo.CompanyVo;

import javafx.beans.binding.Bindings;
import javafx.beans.property.SimpleObjectProperty;
import javafx.event.ActionEvent;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import javafx.stage.DirectoryChooser;
import javafx.util.converter.LocalDateStringConverter;

public class CompanyCustomerTabSkinBase
        extends AbstEntityBasedTabSkin<CompanyCustomerWindowController, CompanyCustomerVo, CompanyCustomerViewModel>
        implements TabSkin {

    public CompanyCustomerTabSkinBase(CompanyCustomerWindowController controller) {
        super(controller);
    }

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

    @Override
    public void initializeTab() {
        initializeCompanyFieldAutoCompletion(controller.companyField);
        initializeContactFieldAutoCompletion(controller.contactField);

        UITools.autoCompletion(controller.contactField, viewModel.getContact(), getCompanyContactService());

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

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

        controller.pathField.textProperty().bind(viewModel.getPath());
        controller.descriptionField.textProperty().bindBidirectional(viewModel.getDescription());
        controller.createdField.textProperty().bind(
                Bindings.createStringBinding(
                        () -> localDateTimeFormatter(viewModel.getCreated()),
                        viewModel.getCreated()));
        controller.versionLabel.textProperty().bind(viewModel.getVersion().asString());

        controller.relativeCompanyBtn.disableProperty().bind(viewModel.getCompany().isNull());
        controller.relativeCompanyBtn.setOnAction(event -> {
            Integer companyId = viewModel.getCompany().get();
            if (companyId != null) {
                CompanyVo company = getCompanyService().findById(companyId);
                if (company != null) {
                    CompanyWindowController.show(company, controller.root.getScene().getWindow());
                }
            }
        });

        controller.createPathBtn.setOnAction(this::onCompanyCustomerCreatePathAction);
        controller.changePathBtn.setOnAction(this::onCompanyCustomerChangePathAction);
        controller.pathAsNameBtn.setOnAction(this::onCompanyCustomerPathSameAsNameAction);
    }

    protected String localDateTimeFormatter(SimpleObjectProperty<LocalDateTime> property) {
        LocalDateTime dateTime = property.get();
        if (dateTime == null) {
            return "";
        }
        return MyDateTimeUtils.format(dateTime);
    }

    private void initializeContactFieldAutoCompletion(TextField textField) {
        UITools.autoCompletion(textField, viewModel.getContact(), getCompanyContactService());
    }

    private void initializeCompanyFieldAutoCompletion(TextField textField) {
        UITools.autoCompletion(textField, viewModel.getCompany(), getCompanyService());
    }

    public void onCompanyCustomerCreatePathAction(ActionEvent event) {
        CompanyCustomerVo companyCustomer = getCompanyCustomerService().findById(viewModel.getId().get());
        if (getCompanyCustomerService().makePathAbsent(companyCustomer)) {
            companyCustomer = getCompanyCustomerService().save(companyCustomer);
            viewModel.update(companyCustomer);
        } else {
            setStatus("目录存在或创建失败");
        }
    }

    public void onCompanyCustomerChangePathAction(ActionEvent event) {
        DirectoryChooser chooser = new DirectoryChooser();
        CompanyCustomerVo 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 = getCompanyCustomerService().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 onCompanyCustomerPathSameAsNameAction(ActionEvent event) {
        setStatus("未实现");
    }

    public CompanyCustomerService getCompanyCustomerService() {
        return controller.getCachedBean(CompanyCustomerService.class);
    }

    public CompanyContactService getCompanyContactService() {
        return controller.getCachedBean(CompanyContactService.class);
    }

    public CompanyService getCompanyService() {
        return controller.getCachedBean(CompanyService.class);
    }
}
