package com.ecep.contract.controller.project;

import com.ecep.contract.controller.company.CompanyWindowController;
import com.ecep.contract.controller.tab.TabSkin;
import com.ecep.contract.converter.EntityStringConverter;
import com.ecep.contract.service.*;
import com.ecep.contract.util.FxmlPath;
import com.ecep.contract.util.UITools;
import com.ecep.contract.vo.*;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.StringProperty;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import org.controlsfx.control.textfield.AutoCompletionBinding;
import org.springframework.util.StringUtils;

@FxmlPath("/ui/project/project-tab-customer.fxml")
public class ProjectTabSkinCustomerInfo
        extends AbstProjectBasedTabSkin
        implements TabSkin {
    @FXML
    public TextField companyField;
    @FXML
    public Button companyDetailBtn;
    @FXML
    public Label companyLabel;
    @FXML
    public TextField bankAccountField;
    @FXML
    public Label bankAccountLabel;
    @FXML
    public TextField invoiceInfoField;
    @FXML
    public Label invoiceInfoLabel;
    @FXML
    public TextField mainContactField;
    @FXML
    public Label mainContactLabel;
    @FXML
    public TextField subContactField;
    @FXML
    public Label subContactLabel;

    public ProjectTabSkinCustomerInfo(ProjectWindowController controller) {
        super(controller);
    }

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

    @Override
    public void initializeTab() {
        initCompanyField();
        initBankAccountField();
        initInvoiceInfoField();
        initMainContactField();
        initSubContactField();
    }

    private void initCompanyField() {
        companyAutoCompletion(companyField, companyLabel, viewModel.getCustomer()).setOnAutoCompleted(event -> {
            CompanyVo company = event.getCompletion();
            viewModel.getCustomer().set(company.getId());

        });

        companyDetailBtn.setOnAction(event -> {
            Integer companyId = viewModel.getCustomer().get();
            CompanyVo company = getCompanyService().findById(companyId);
            if (company == null) {
                return;
            }
            CompanyWindowController.show(company, controller.root.getScene().getWindow());
        });
    }

    private void initBankAccountField() {
        bankAccountAutoCompletion(bankAccountField, bankAccountLabel, viewModel.getBankAccount())
                .setOnAutoCompleted(event -> {
                    CompanyBankAccountVo account = event.getCompletion();
                    viewModel.getBankAccount().set(account.getId());
                });
    }

    private void initInvoiceInfoField() {
        invoiceInfoAutoCompletion(invoiceInfoField, invoiceInfoLabel, viewModel.getInvoiceInfo())
                .setOnAutoCompleted(event -> {
                    CompanyInvoiceInfoVo invoiceInfo = event.getCompletion();
                    viewModel.getInvoiceInfo().set(invoiceInfo.getId());
                });
    }

    private void initMainContactField() {
        contactAutoCompletion(mainContactField, mainContactLabel, viewModel.getMainContact())
                .setOnAutoCompleted(event -> {
                    CompanyContactVo contact = event.getCompletion();
                    viewModel.getMainContact().set(contact.getId());
                });
    }

    private void initSubContactField() {
        contactAutoCompletion(subContactField, subContactLabel, viewModel.getSubContact()).setOnAutoCompleted(event -> {
            CompanyContactVo contact = event.getCompletion();
            viewModel.getSubContact().set(contact.getId());
        });
    }

    /**
     * 更新 property 未为空时
     *
     * @param value    要设置的值
     * @param property 要设置的 property
     */
    private void updateAbsent(String value, StringProperty property) {
        if (!StringUtils.hasText(value)) {
            return;
        }
        if (StringUtils.hasText(property.get())) {
            return;
        }
        property.set(value);
    }

    private AutoCompletionBinding<CompanyVo> companyAutoCompletion(TextField textField, Label label,
            SimpleObjectProperty<Integer> property) {

        label.textProperty().bind(property.map(companyId -> {
            if (companyId == null) {
                return "未选择";
            }

            CompanyVo company = getCompanyService().findById(companyId);
            if (company == null) {
                return "#" + companyId;
            }
            StringBuilder sb = new StringBuilder();
            sb.append("经营状态：");
            sb.append(company.getEntStatus());
            sb.append("\n");

            sb.append("统一社会信用代码：");
            sb.append(company.getUniscid());
            sb.append("\n");

            sb.append("注册电话：");
            sb.append(company.getTelephone());
            sb.append("\n");

            sb.append("注册地址：");
            sb.append(company.getRegAddr());
            return sb.toString();
        }));

        return UITools.autoCompletion(textField, property, getCompanyService());
    }

    private AutoCompletionBinding<CompanyBankAccountVo> bankAccountAutoCompletion(TextField textField, Label label,
            SimpleObjectProperty<Integer> property) {

        label.textProperty().bind(property.map(accountId -> {
            if (accountId == null) {
                return "未选择";
            }
            CompanyBankAccountVo account = getBankAccountService().findById(accountId);
            if (account == null) {
                return "#" + accountId;
            }
            StringBuilder sb = new StringBuilder();
            Integer bankId = account.getBankId();
            BankVo bank = getBankService().findById(bankId);
            sb.append("开户行：");
            if (bank != null) {
                sb.append(getBankService().getStringConverter().toString(bank));
                sb.append(" ");
            }
            sb.append(account.getOpeningBank());
            sb.append("\n");

            sb.append("开户账号：");
            sb.append(account.getAccount());
            return sb.toString();
        }));
        return UITools.autoCompletion(textField, property, getBankAccountService());
    }

    private AutoCompletionBinding<CompanyInvoiceInfoVo> invoiceInfoAutoCompletion(TextField textField, Label label,
                                                                                  SimpleObjectProperty<Integer> property) {
        EntityStringConverter<CompanyInvoiceInfoVo> converter = new EntityStringConverter<>();
        converter.setInitialized(info -> getInvoiceInfoService().findById(info.getId()));

        label.textProperty().bind(property.map(infoId -> {
            if (infoId == null) {
                return "未选择";
            }
            CompanyInvoiceInfoVo info = getInvoiceInfoService().findById(infoId);
            if (info == null) {
                return "#" + infoId;
            }
            StringBuilder sb = new StringBuilder();
            sb.append("发票抬头：");
            sb.append(info.getName());
            sb.append("\n");

            sb.append("纳税人识别号：");
            sb.append(info.getTaxId());
            sb.append("\n");

            sb.append("地址：");
            sb.append(info.getAddress());
            sb.append("\n");

            sb.append("电话：");
            sb.append(info.getPhone());
            return sb.toString();
        }));
        return UITools.autoCompletion(textField, property, getInvoiceInfoService());
    }

    private AutoCompletionBinding<CompanyContactVo> contactAutoCompletion(TextField textField, Label label,
            SimpleObjectProperty<Integer> property) {

        label.textProperty().bind(property.map(contactId -> {
            if (contactId == null) {
                return "未选择";
            }
            CompanyContactVo contact = getContactService().findById(contactId);
            if (contact == null) {
                return "#" + contactId;
            }
            StringBuilder sb = new StringBuilder();
            sb.append("联系人：");
            sb.append(contact.getName());

            sb.append("\n");
            sb.append("职位：");
            sb.append(contact.getPosition());

            sb.append("\n");
            sb.append("电话：");
            sb.append(contact.getPhone());

            sb.append("\n");
            sb.append("邮箱：");
            sb.append(contact.getEmail());

            return sb.toString();
        }));
        return UITools.autoCompletion(textField, property, getContactService());
    }

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

    public BankService getBankService() {
        return getCachedBean(BankService.class);
    }

    public CompanyInvoiceInfoService getInvoiceInfoService() {
        return getCachedBean(CompanyInvoiceInfoService.class);
    }

    public CompanyBankAccountService getBankAccountService() {
        return getCachedBean(CompanyBankAccountService.class);
    }

    public CompanyContactService getContactService() {
        return getCachedBean(CompanyContactService.class);
    }
}
