package com.ecep.contract.controller.tab;

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

import org.springframework.util.StringUtils;

import com.ecep.contract.controller.company.AbstCompanyBasedTabSkin;
import com.ecep.contract.controller.company.CompanyWindowController;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.CompanyOldName;
import com.ecep.contract.service.CompanyOldNameService;

import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Modality;
import javafx.util.converter.LocalDateStringConverter;
import lombok.Setter;

/**
 *
 */

public class CompanyTabSkinBase
        extends AbstCompanyBasedTabSkin
        implements TabSkin {
    @Setter
    private CompanyOldNameService companyOldNameService;

    public CompanyTabSkinBase(CompanyWindowController controller) {
        super(controller);
    }

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

    @Override
    public void initializeTab() {

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

        controller.nameField.textProperty().bind(viewModel.getName());
        controller.shortNameField.textProperty().bindBidirectional(viewModel.getShortName());
        controller.entStatusField.textProperty().bindBidirectional(viewModel.getEntStatus());

        controller.uidField.textProperty().bindBidirectional(viewModel.getUid());
        controller.setupDateField.setConverter(localDateStringConverter);
        controller.setupDateField.valueProperty().bindBidirectional(viewModel.getSetupDate());
        controller.entTypeField.textProperty().bindBidirectional(viewModel.getEntType());
        controller.industryField.textProperty().bindBidirectional(viewModel.getIndustry());
        controller.districtField.textProperty().bindBidirectional(viewModel.getDistrict());
        controller.pathExistField.selectedProperty().bind(viewModel.getPathExist());
        controller.pathField.textProperty().bind(viewModel.getPath());
        controller.createdDateField.setConverter(localDateStringConverter);
        controller.createdDateField.valueProperty().bindBidirectional(viewModel.getCreated());

        controller.telephoneField.textProperty().bindBidirectional(viewModel.getTelephone());
        controller.regAddressField.textProperty().bindBidirectional(viewModel.getRegAddress());
        controller.addressField.textProperty().bindBidirectional(viewModel.getAddress());
        controller.registeredCapitalField.textProperty().bindBidirectional(viewModel.getRegisteredCapital());
        controller.registeredCapitalCurrencyField.textProperty().bindBidirectional(viewModel.getRegisteredCapitalCurrency());
        controller.legalRepresentativeField.textProperty().bindBidirectional(viewModel.getLegalRepresentative());

        controller.operationPeriodBeginField.setConverter(localDateStringConverter);
        controller.operationPeriodBeginField.valueProperty().bindBidirectional(viewModel.getOperationPeriodBegin());
        controller.operationPeriodEndField.setConverter(localDateStringConverter);
        controller.operationPeriodEndField.valueProperty().bindBidirectional(viewModel.getOperationPeriodEnd());

        controller.memoField.textProperty().bindBidirectional(viewModel.getMemo());
        controller.versionLabel.textProperty().bind(viewModel.getVersion().asString());

        controller.companyRenameBtn.setOnAction(this::onCompanyRenameAction);
        controller.companyPathCreateBtn.setOnAction(this::onCompanyPathCreatePathAction);
        controller.companyPathChangeBtn.setOnAction(this::onCompanyPathChangePathAction);
        controller.companyPathSameAsNameBtn.setOnAction(this::onCompanyPathSameAsNameAction);
    }

    private void onCompanyPathCreatePathAction(ActionEvent event) {
        Company company = getEntity();
        if (getCompanyService().makePathAbsent(company)) {
            save(company);
        } else {
            setStatus("目录存在或创建失败");
        }
    }

    private void onCompanyPathChangePathAction(ActionEvent event) {
    }

    private void onCompanyPathSameAsNameAction(ActionEvent event) {
        Company company = getEntity();
        String path = company.getPath();
        if (!StringUtils.hasText(path)) {
            return;
        }
        File file = new File(path);
        if (!file.exists()) {
            return;
        }

        if (file.getName().equals(company.getName())) {
            return;
        }
        File dest = new File(file.getParent(), company.getName());
        if (file.renameTo(dest)) {
            company.setPath(dest.getAbsolutePath());
            save(company);
            setStatus("目录变更为" + dest.getName());
        }
    }

    private void onCompanyRenameAction(ActionEvent event) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.initOwner(controller.root.getScene().getWindow());
        alert.initModality(Modality.WINDOW_MODAL);
        VBox layout = new VBox();

        TextField nameField = new TextField();
        Label nameLabel = new Label("");

        CheckBox saveAsOldName = new CheckBox();
        CheckBox ambiguity = new CheckBox();
        Label ambiguityLabel = new Label("当曾用名不是工商注册过的名字时，请勾选 歧义 标记");
        layout.setPadding(new Insets(12));
        layout.setSpacing(8);

        nameField.setPromptText("新的公司名称");
        nameField.setText(viewModel.getName().get());
        nameField.setEditable(true);
        nameLabel.setTextFill(Color.GRAY);

        saveAsOldName.setText("旧名称是否设置为曾用名");
        ambiguity.setText("是否标记为歧义");
        ambiguity.visibleProperty().bind(saveAsOldName.selectedProperty());
        ambiguityLabel.setTextFill(Color.GRAY);
        ambiguityLabel.visibleProperty().bind(saveAsOldName.selectedProperty());

        layout.getChildren().addAll(nameField, nameLabel, saveAsOldName, ambiguity, ambiguityLabel);


        alert.setContentText("context");
        alert.setHeaderText(null);
        alert.setTitle("企业更名");

        alert.getDialogPane().setContent(layout);

//        alert.setResultConverter(param -> {
//
//            return null;
//        });


        alert.setOnCloseRequest(dialogEvent -> {
            ButtonType buttonType = alert.getResult();
            if (buttonType != ButtonType.OK) {
                return;
            }
            String newName = nameField.getText();
            String oldName = viewModel.getName().get();
            if (oldName.equals(newName)) {
                nameLabel.setText("名称没有修改");
                nameLabel.setTextFill(Color.PERU);
                dialogEvent.consume();
                return;
            }

            viewModel.getName().set(newName);
            save();

            // TODO 修改文件夹
            if (!saveAsOldName.isSelected()) {
                return;
            }

            Company company = getEntity();
            List<CompanyOldName> oldNames = getCompanyOldNameService().findAllByCompanyAndName(company, oldName);
            if (oldNames.isEmpty()) {
                CompanyOldName companyOldName = new CompanyOldName();
                companyOldName.setCompanyId(company.getId());
                companyOldName.setName(oldName);
                companyOldName.setAmbiguity(ambiguity.isSelected());
                companyOldName.setMemo("名称更名 " + oldName + " -> " + newName);
                getCompanyOldNameService().save(companyOldName);

                CompanyTabSkinOldName tabSkin = controller.getTabSkin(CompanyTabSkinOldName.class);
                if (tabSkin != null) {
                    tabSkin.loadTableDataSet();
                }
            }
        });

        alert.showAndWait();
    }

    private CompanyOldNameService getCompanyOldNameService() {
        if (companyOldNameService == null) {
            companyOldNameService = getBean(CompanyOldNameService.class);
        }
        return companyOldNameService;
    }
}
