package com.ecep.contract.controller.tab;

import java.util.List;

import org.controlsfx.control.textfield.TextFields;

import com.ecep.contract.ContractPayWay;
import com.ecep.contract.SpringApp;
import com.ecep.contract.controller.contract.AbstContractTableTabSkin;
import com.ecep.contract.controller.contract.ContractWindowController;
import com.ecep.contract.controller.table.EditableEntityTableTabSkin;
import com.ecep.contract.controller.vendor.VendorBidWindowController;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.Contract;
import com.ecep.contract.model.ContractBidVendor;
import com.ecep.contract.model.ContractFile;
import com.ecep.contract.service.CompanyService;
import com.ecep.contract.service.ContractBidVendorService;
import com.ecep.contract.service.ContractFileService;
import com.ecep.contract.util.FxmlPath;
import com.ecep.contract.util.ProxyUtils;
import com.ecep.contract.vm.CompanyViewModel;
import com.ecep.contract.vm.ContractBidVendorViewModel;

import javafx.event.ActionEvent;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceDialog;
import javafx.scene.control.ComboBox;
import javafx.scene.control.MenuItem;
import javafx.scene.control.Tab;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.util.StringConverter;
import lombok.Setter;

/**
 * 以下是比价供应商
 */
@FxmlPath("/ui/contract/contract-tab-bid.fxml")
public class ContractTabSkinVendorBid
        extends AbstContractTableTabSkin<ContractBidVendor, ContractBidVendorViewModel>
        implements TabSkin, EditableEntityTableTabSkin<ContractBidVendor, ContractBidVendorViewModel> {
    @Setter
    private ContractBidVendorService service;
    public TableColumn<ContractBidVendorViewModel, Number> bidVendorTable_idColumn;
    public TableColumn<ContractBidVendorViewModel, String> bidVendorTable_companyColumn;
    public TableColumn<ContractBidVendorViewModel, ContractFile> bidVendorTable_quotationSheetColumn;

    public Button bidVendorCreateBtn;
    public MenuItem bidVendorTable_menu_refresh;
    public MenuItem bidVendorTable_menu_delete;
    public MenuItem bidVendorTable_menu_chose_sheet;

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

    @Override
    protected ContractBidVendorService getViewModelService() {
        return getService();
    }

    @Override
    public void initializeUIComponents() {
        super.initializeUIComponents();
        // 合同是收时，有关联子合同
        getTab().disableProperty().bind(viewModel.getPayWay().isEqualTo(ContractPayWay.PAY).not());
    }

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

    static class QuotationSheetColumnTableCell extends TableCell<ContractBidVendorViewModel, ContractFile> {
        private ContractFileService contractFileService;

        public ContractFileService getContractFileService() {
            if (contractFileService == null) {
                contractFileService = SpringApp.getBean(ContractFileService.class);
            }
            return contractFileService;
        }

        @Override
        protected void updateItem(ContractFile item, boolean empty) {
            super.updateItem(item, empty);
            if (empty || item == null) {
                setText(null);
            } else {
                if (!ProxyUtils.isInitialized(item)) {
                    item = getContractFileService().findById(item.getId());
                    ContractBidVendorViewModel viewModel = getTableRow().getItem();
                    viewModel.getQuotationSheet().set(item);
                }
                setText(item.getFileName());
            }
        }
    }

    @Override
    public void initializeTab() {
        bidVendorCreateBtn.setOnAction(this::onBidVendorTableCreateAction);
        bidVendorTable_menu_refresh.setOnAction(this::onTableRefreshAction);
        bidVendorTable_menu_delete.setOnAction(this::onTableDeleteAction);
        bidVendorTable_menu_chose_sheet.setOnAction(this::onBidVendorTableChoseQuotationSheetAction);

        bidVendorTable_idColumn.setCellValueFactory(param -> param.getValue().getId());
        bidVendorTable_companyColumn.setCellValueFactory(param -> param.getValue().getCompany().map(c -> {
            if (c == null) {
                return null;
            } else {
                return c.getName();
            }
        }));
        bidVendorTable_quotationSheetColumn.setCellValueFactory(param -> param.getValue().getQuotationSheet());
        bidVendorTable_quotationSheetColumn.setCellFactory(param -> new QuotationSheetColumnTableCell());

        super.initializeTab();
    }

    @Override
    protected void onTableRowDoubleClickedAction(ContractBidVendorViewModel item) {
        showInOwner(VendorBidWindowController.class, item);
    }

    public void onBidVendorTableCreateAction(ActionEvent event) {
        Contract contract = getParent();


        ChoiceDialog<String> dialog = new ChoiceDialog<>();
        dialog.setTitle("添加比价供应商");
        dialog.setHeaderText("请输入比价的供应商公司名称，支持模糊搜索功能");
        dialog.setWidth(400);
        ComboBox<String> comboBox = (ComboBox<String>) dialog.getDialogPane().getContent().lookup("ComboBox");
        TextFields.bindAutoCompletion(comboBox.getEditor(), p -> {
            if (p.isCancelled()) {
                return null;
            }
            return getCompanyService().search(p.getUserText()).stream().map(CompanyViewModel::from).toList();
        }, new StringConverter<>() {
            @Override
            public String toString(CompanyViewModel viewModel) {
                return viewModel.getName().get();
            }

            @Override
            public CompanyViewModel fromString(String string) {
                return null;
            }
        });

        comboBox.setEditable(true);
        dialog.showAndWait().ifPresent(selectedItem -> {

            Company company = getCompanyService().findAllByName(selectedItem).getFirst();

            List<ContractBidVendor> list = getService().findByContractAndCompany(contract, company);
            if (list == null || list.isEmpty()) {
                ContractBidVendor bidVendor = new ContractBidVendor();
                bidVendor.setContract(contract);
                bidVendor.setCompany(company);
                getService().save(bidVendor);
                loadTableDataSet();
            } else {
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setTitle("添加比价供应商");
                alert.setHeaderText("添加的供应商：" + company.getName() + " 已经存在。");
                alert.showAndWait();
            }
        });
    }


    /**
     * 匹配报价表
     *
     * @param event event
     */
    public void onBidVendorTableChoseQuotationSheetAction(ActionEvent event) {
        ContractBidVendorViewModel selectedItem = getSelectedItem();
        if (selectedItem == null) {
            return;
        }

        // TODO xx
    }

    private ContractBidVendorService getService() {
        if (service == null) {
            service = SpringApp.getBean(ContractBidVendorService.class);
        }
        return service;
    }

    private CompanyService getCompanyService() {
        return controller.getCompanyService();
    }


}
