package com.ecep.contract.controller.customer;

import java.io.File;
import java.time.LocalDate;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import com.ecep.contract.MyDateTimeUtils;
import com.ecep.contract.controller.AbstManagerWindowController;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.CompanyCustomer;
import com.ecep.contract.service.CompanyCustomerService;
import com.ecep.contract.service.CompanyService;
import com.ecep.contract.util.FxmlPath;
import com.ecep.contract.util.ProxyUtils;
import com.ecep.contract.util.UITools;
import com.ecep.contract.vm.CompanyCustomerViewModel;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.TableColumn;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

@Lazy
@Scope("prototype")
@Component
@FxmlPath("/ui/company/customer/customer_manager.fxml")
public class CompanyCustomerManagerWindowController
        extends AbstManagerWindowController<CompanyCustomer, CompanyCustomerViewModel, CompanyCustomerManagerSkin> {

    // columns
    public TableColumn<CompanyCustomerViewModel, Number> idColumn;
    public TableColumn<CompanyCustomerViewModel, Company> companyColumn;
    public TableColumn<CompanyCustomerViewModel, String> catalogColumn;
    public TableColumn<CompanyCustomerViewModel, LocalDate> developDateColumn;
    public TableColumn<CompanyCustomerViewModel, String> pathColumn;
    public TableColumn<CompanyCustomerViewModel, String> createdColumn;


    @Override
    public CompanyCustomerService getViewModelService() {
        return getCachedBean(CompanyCustomerService.class);
    }

    @Autowired
    private CompanyService getCompanyService() {
        return getCachedBean(CompanyService.class);
    }

    @Override
    public void show(Stage stage) {
        super.show(stage);
        getTitle().set("客户管理");
    }

    @Override
    protected CompanyCustomerManagerSkin createDefaultSkin() {
        CompanyCustomerManagerSkin skin = new CompanyCustomerManagerSkin(this);
        return skin;
    }

    /**
     * 对所有客户的文件进行重置
     * <p>
     * 弹出对话框模式，对话框中有进度条和重置的消息
     *
     * @param event 事件
     */
    public void onReBuildFilesAction(ActionEvent event) {
        Dialog<String> dialog = new Dialog<>();
        dialog.setTitle("客户文件重置");
        AtomicBoolean canceled = new AtomicBoolean(false);
        VBox box = new VBox();
        Label header = new Label("遍历所有客户，对每个可以客户的文件进行“重置”操作");

        ProgressBar progressBar = new ProgressBar();
        progressBar.setPrefWidth(300);
        progressBar.setMinHeight(18);
        VBox.setMargin(progressBar, new Insets(8, 0, 8, 0));

        ListView<String> listView = new ListView<>();
        ObservableList<String> listViewDataSet = FXCollections.observableArrayList();
        listView.setItems(listViewDataSet);
        VBox.setVgrow(listView, Priority.ALWAYS);
        box.getChildren().setAll(header, progressBar, listView);

        dialog.getDialogPane().setContent(box);

        dialog.getDialogPane().getButtonTypes().add(ButtonType.OK);
        dialog.setResizable(true);
        dialog.setWidth(600);
        dialog.setHeight(500);
        dialog.setOnCloseRequest(v -> canceled.set(true));
        dialog.initOwner(table.getScene().getWindow());
        dialog.show();

        CompletableFuture.runAsync(() -> {
            Pageable pageRequest = PageRequest.ofSize(50);
            while (!canceled.get()) {
                Page<CompanyCustomer> page = getViewModelService().findAll(null, pageRequest);
                int index = page.getNumber() * page.getSize();

                int i = 1;
                for (CompanyCustomer companyCustomer : page) {
                    if (canceled.get()) {
                        return;
                    }
                    Company company = companyCustomer.getCompany();
                    if (!ProxyUtils.isInitialized(company)) {
                        company = getCompanyService().findById(company.getId());
                    }

                    String prefix = (index + i) + "/" + page.getTotalElements() + ", " + company.getName() + "> ";
                    getViewModelService().reBuildingFiles(companyCustomer, (level, msg) -> {
                        Platform.runLater(() -> {
                            listViewDataSet.add(prefix + msg);
                            listView.scrollTo(listViewDataSet.size() - 1);
                        });
                    });

                    double progress = (double) (index + i) / page.getTotalElements();
                    Platform.runLater(() -> {
                        progressBar.setProgress(progress);
                    });
                    i++;
                }
                if (!page.hasNext()) {
                    break;
                }
                pageRequest = page.nextPageable();
            }
        });
    }

    public void onCreateNewCustomerAction(ActionEvent event) {

    }

    public void onBaseTableRefreshAction(ActionEvent event) {
        getSkin().loadTableDataSet(true);
    }

    public void onExportAction(ActionEvent event) {
        CompanyCustomerExportExcelTasker tasker = new CompanyCustomerExportExcelTasker();
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("导出");
        fileChooser.setInitialFileName("客户资信台账-" + MyDateTimeUtils.format(LocalDate.now()) + ".xlsx");
        fileChooser.setInitialDirectory(getViewModelService().getBasePath());
        File destFile = fileChooser.showSaveDialog(table.getScene().getWindow());
        tasker.setDestFile(destFile);
        UITools.showTaskDialogAndWait("导出Excel", tasker, null);
    }

}
