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.table.cell.CompanyTableCell;
import com.ecep.contract.controller.table.cell.ContractFileTableCell;
import com.ecep.contract.controller.vendor.bid.VendorBidWindowController;
import com.ecep.contract.service.CompanyService;
import com.ecep.contract.service.ContractBidVendorService;
import com.ecep.contract.util.FxmlPath;
import com.ecep.contract.vm.CompanyViewModel;
import com.ecep.contract.vm.ContractBidVendorViewModel;
import com.ecep.contract.vo.CompanyVo;
import com.ecep.contract.vo.ContractBidVendorVo;
import com.ecep.contract.vo.ContractVo;

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.TableColumn;
import javafx.util.StringConverter;
import lombok.Setter;

/**
 * 以下是比价供应商
 */
@FxmlPath("/ui/contract/contract-tab-bid.fxml")
public class ContractTabSkinVendorBid
        extends AbstContractTableTabSkin<ContractBidVendorVo, ContractBidVendorViewModel>
        implements TabSkin, EditableEntityTableTabSkin<ContractBidVendorVo, ContractBidVendorViewModel> {
    @Setter
    private ContractBidVendorService service;
    public TableColumn<ContractBidVendorViewModel, Number> bidVendorTable_idColumn;
    public TableColumn<ContractBidVendorViewModel, Integer> bidVendorTable_companyColumn;
    /**
     * 报价单, 合同文件， ContractFile
     */
    public TableColumn<ContractBidVendorViewModel, Integer> 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;
    }

    @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().getCompanyId());
        bidVendorTable_companyColumn.setCellFactory(CompanyTableCell.forTableColumn(getCompanyService()));
        bidVendorTable_quotationSheetColumn.setCellValueFactory(param -> param.getValue().getQuotationSheetFileId());
        bidVendorTable_quotationSheetColumn.setCellFactory(ContractFileTableCell.forTableColumn(getContractService()));

        super.initializeTab();
    }

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

    public void onBidVendorTableCreateAction(ActionEvent event) {
        ContractVo 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 -> {

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

            List<ContractBidVendorVo> list = getService().findByContractAndCompany(contract, company);
            if (list == null || list.isEmpty()) {
                ContractBidVendorVo bidVendor = new ContractBidVendorVo();
                bidVendor.setContractId(contract.getId());
                bidVendor.setCompanyId(company.getId());
                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();
    }

}
