
from .commons.dialogs import HelpDialog, QuickDialog
from PyQt5.QtCore import QRect, Qt
from PyQt5.QtWidgets import (
    QWidget, QLabel, QTextEdit, QVBoxLayout, QGridLayout, QLineEdit,
    QScrollArea, QHBoxLayout, QDoubleSpinBox, QDateEdit, QDesktopWidget,
    QPlainTextEdit, QCheckBox
)
from .constants import alignCenter, alignLeft, FRACTIONS
from .commons.forms import FieldMoney, ComboBox
from .commons.search_window import SearchWindow
from collections import OrderedDict
from .manage_tables import ManageTables
from app.commons.menu_buttons import GridButtons
from app.commons.table import TableView
from .commons.custom_button import CustomButton
from .tools import get_icon

__all__ = [
    'ControlPanel', 'SearchSale', 'SearchParty', 'SearchProduct', 'EditLine',
    'Comment', 'Position', 'DialogPayment', 'DialogTaxes', 'DialogChannel',
    'DialogTableMoneyCount', 'DialogTableDeliveryParty', 'DialogDeliveryParty',
    'Help', 'DeliveryPartySelected', 'DialogPrintInvoice', 'DialogStock',
    'DialogGlobalDiscountTable', 'DialogSalesman', 'DialogAgent',
    'DialogOrder', 'DialogGlobalDiscount', 'DialogVoucher', 'DialogConsumer',
    'DialogManageTables', 'DialogTableSaleConsumer', 'SaleConsumerSelected',
    'DialogCancelInvoice', 'DialogForceAssign', 'AdditionProduct'
]


TYPE_VEHICLE = [
    ('', ''),
    ('motorcycle', 'Motorcycle'),
    ('bicycle', 'Bicycle'),
    ('car', 'Car'),
]


def get_screen():
    screen = QDesktopWidget().screenGeometry()
    width = screen.width()
    height = screen.height()
    return width, height


def create_vbox(parent, values, method, columns=4, dimension=None):
    vbox_ = QVBoxLayout()
    grid = QGridLayout()
    grid.setSpacing(2)
    if isinstance(method, str):
        method = getattr(parent, method)
    grid_buttons = GridButtons(parent, values, columns, action=method,
        style='standard_button')

    vbox_.setObjectName('grid_buttons')
    scroll_area = QScrollArea()
    scroll_area.setWidgetResizable(True)
    scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
    scroll_area.setWidget(grid_buttons)
    width, height = get_screen()
    if dimension:
        width = width / dimension[0]
        height = height / dimension[0]
        scroll_area.setFixedSize(width, height)
    grid.addWidget(scroll_area)
    vbox_.addLayout(grid)
    return vbox_


class ControlPanel(QWidget):
    def __init__(self, parent):
        super(ControlPanel, self).__init__(parent)
        self._parent = parent

    def get(self, menu_dash):
        string_ = self.tr('CONTROL PANEL')

        vbox_ = QVBoxLayout()
        grid = QGridLayout()
        scroll_area = QScrollArea()
        scroll_area.setLayout(menu_dash)
        grid.addWidget(scroll_area)
        vbox_.addLayout(grid)
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_])
        width, height = get_screen()
        dialog.setFixedSize(width/2, height/1.2)
        dialog.setWindowTitle(string_)
        return dialog


class SearchSale(QWidget):
    def __init__(self, parent):
        super(SearchSale, self).__init__(parent)
        self._parent = parent

    def get(self):
        headers = OrderedDict()
        headers['id'] = {'desc': self.tr('ID'), 'type': 'char'}
        headers['number'] = {'desc': self.tr('NUMBER'), 'type': 'char'}
        headers['invoice_number'] = {'desc': self.tr('INVOICE'), 'type': 'char'}
        headers['party.name'] = {'desc': self.tr('PARTY'), 'type': 'char'}
        headers['sale_date'] = {'desc': self.tr('DATE'), 'type': 'char'}
        headers['salesman.rec_name'] = {'desc': self.tr('SALESMAN'), 'type': 'char'}
        widths = [20, 120, 100, 180, 110, 260]

        if self._parent._sale_pos_restaurant:
            headers['consumer.rec_name'] = {'desc': self.tr('CONSUMER'), 'type': 'char'}
            widths.append(310)

        headers['position'] = {'desc': self.tr('POSITION'), 'type': 'char'}
        widths.append(100)
        headers['total_amount_cache'] = {'desc': self.tr('TOTAL AMOUNT'), 'type': 'number'}
        widths.append(80)

        title = self.tr('SEARCH SALES...')
        methods = {
            'on_selected_method': 'on_selected_sale',
            'on_return_method': 'on_selected_sale'
        }
        return SearchWindow(self._parent, headers, None, methods,
            filter_column=[2, 3, 4, 6, 7], cols_width=widths,
            title=title, fill=True)


class SearchParty(QWidget):
    def __init__(self, parent):
        super(SearchParty, self).__init__(parent)
        self._parent = parent

    def get(self):
        headers = OrderedDict()
        headers['id'] = {'desc': self.tr('ID'), 'type': 'char'}
        headers['id_number'] = {'desc': self.tr('ID NUMBER'), 'type': 'char'}
        headers['name'] = {'desc': self.tr('NAME'), 'type': 'char'}
        headers['street'] = {'desc': self.tr('ADDRESS'), 'type': 'char'}
        headers['phone'] = {'desc': self.tr('PHONE'), 'type': 'char'}

        title = self.tr('SEARCH CUSTOMER')
        methods = {
            'on_selected_method': 'on_selected_party',
            'on_return_method': 'on_search_party',
        }
        return SearchWindow(self._parent, headers, None, methods,
              filter_column=[], cols_width=[60, 120, 270, 190, 90],
              title=title, fill=True)


class SearchProduct(QWidget):
    def __init__(self, parent):
        super(SearchProduct, self).__init__(parent)
        self._parent = parent

    def get(self):
        _cols_width = [10, 80]
        headers = OrderedDict()
        self.prueba = 5
        headers['id'] = {'desc': self.tr('ID'), 'type': 'char'}
        headers['code'] = {'desc': self.tr('CODE'), 'type': 'char'}
        if self._parent._config.get('show_stock_pos') in ['icon', 'value']:
            headers['quantity'] = {'desc': self.tr('STOCK'), 'type': 'char'}
            if self._parent._config['show_stock_pos'] == 'icon':
                headers['quantity']['icon'] = 'stock'
                headers['quantity']['type'] = 'icon'
            _cols_width.append(60)

        if not self._parent.cache_local:
            headers['name'] = {'desc': self.tr('NAME'), 'type': 'char'}
        else:
            headers['template.name'] = {'desc': self.tr('NAME'), 'type': 'char'}

        _cols_width.append(350)

        if self._parent._config.get('show_description_pos'):
            headers['description'] = {'desc': self.tr('DESCRIPTION'), 'type': 'char'}
            _cols_width.append(300)

        if self._parent._config.get('show_brand'):
            headers['template.brand'] = {'desc': self.tr('BRAND'), 'type': 'char'}
            _cols_width.append(100)

        price = {'desc': self.tr('PRICE'), 'type': 'number'}
        if not self._parent._config.get('encoded_sale_price'):
            headers['template.sale_price_w_tax'] = price
        else:
            price['type'] = 'char'
            headers['encoded_sale_price'] = price

        _cols_width.append(100)

        if self._parent._config.get('show_location_pos'):
            headers['location.name'] = {'desc': self.tr('LOCATION'), 'type': 'char'}
        _cols_width.append(100)

        if self._parent._config['show_product_image']:
            headers['image'] = {'desc': self.tr('IMAGE'), 'icon': 'image', 'type': 'icon'}
            _cols_width.append(30)

        methods = {
            'on_selected_method': 'on_selected_product',
            'on_return_method': 'on_search_product',
            'image': self._parent.on_selected_icon_product,
            'quantity': self._parent.on_selected_stock_product
        }
        search_window = SearchWindow(self._parent, headers, None, methods,
            cols_width=_cols_width, fill=True)
        fields_names = list(headers.keys())
        try:
            fields_names.remove('image')
        except:
            pass
        search_window.fields_names = fields_names
        return search_window


class DialogManageTables(QWidget):
    def __init__(self, parent):
        super(DialogManageTables, self).__init__(parent)
        self._parent = parent

    def exec_(self):
        self.open_tables()
        super(DialogManageTables, self).exec_()

    def open_tables(self):
        tables = self._parent.RestTables.find([
            ('shop', '=', self._parent.shop['id'])
        ])
        self.manager.update_records(tables)

    def get(self):
        if not self._parent._sale_pos_restaurant:
            return
        tables = self._parent.RestTables.find([
            ('shop', '=', self._parent.shop['id'])
        ])
        activate_method = self._parent.action_table_assigned
        see_sale_method = self._parent.action_see_table_sale
        self.manager = ManageTables(self._parent, tables, activate_method, see_sale_method)
        dialog = QuickDialog(self._parent, 'action', widgets=[self.manager])
        width, height = get_screen()
        dialog.setFixedSize(width/1.5, height/1.5)
        return dialog


class DialogConsumer(QWidget):
    def __init__(self, parent):
        super(DialogConsumer, self).__init__(parent)
        self._parent = parent

    def get(self):
        self._parent.state_consumer = {}
        self._parent._consumer = None
        vbox_consumer = QVBoxLayout()
        grid = QGridLayout()

        label_phone = QLabel(self.tr('PHONE:'))
        label_phone.setObjectName('label_phone')
        grid.addWidget(label_phone, 1, 1)
        self._parent.row_field_phone = QLineEdit()
        self._parent.row_field_phone.setObjectName('row_field_phone')
        self._parent.row_field_phone.editingFinished.connect(
            lambda: self._parent.update_consumer_data('phone'))
        grid.addWidget(self._parent.row_field_phone, 1, 2)

        label_consumer = QLabel(self.tr('CONSUMER:'))
        label_consumer.setObjectName('label_consumer')
        grid.addWidget(label_consumer, 2, 1)
        self._parent.row_field_consumer = QLineEdit()
        self._parent.row_field_consumer.setObjectName('row_field_consumer')
        self._parent.row_field_consumer.textChanged.connect(
            lambda: self._parent.update_consumer_data('name'))
        grid.addWidget(self._parent.row_field_consumer, 2, 2)

        label_address = QLabel(self.tr('ADDRESS:'))
        label_address.setObjectName('label_address')
        grid.addWidget(label_address, 3, 1)
        self._parent.row_field_address = QLineEdit()
        self._parent.row_field_address.setObjectName('row_field_address')
        self._parent.row_field_address.textChanged.connect(
            lambda: self._parent.update_consumer_data('address'))
        grid.addWidget(self._parent.row_field_address, 3, 2)

        label_id_number = QLabel(self.tr('ID NUMBER:'))
        label_id_number.setObjectName('label_id_number')
        grid.addWidget(label_id_number, 4, 1)
        self._parent.row_field_id_number = QLineEdit()
        self._parent.row_field_id_number.setObjectName('row_field_id_number')
        self._parent.row_field_id_number.textChanged.connect(
            lambda: self._parent.update_consumer_data('id_number'))
        grid.addWidget(self._parent.row_field_id_number, 4, 2)

        label_birthday = QLabel(self.tr('BIRTHDAY:'))
        label_birthday.setObjectName('label_birthday')
        grid.addWidget(label_birthday, 5, 1)
        item_date = QDateEdit()
        item_date.setGeometry(QRect(120, 18, 140, 18))
        item_date.setDisplayFormat('dd/MM/yyyy')
        # item_date.setCalendarPopup(True)
        self._parent.row_field_birthday = item_date
        self._parent.row_field_birthday.setObjectName('row_field_birthday')
        self._parent.row_field_birthday.dateTimeChanged.connect(
            lambda: self._parent.update_consumer_data('birthday'))
        grid.addWidget(self._parent.row_field_birthday, 5, 2)

        label_notes = QLabel(self.tr('NOTES:'))
        label_notes.setObjectName('label_notes')
        grid.addWidget(label_notes, 6, 1)
        self._parent.row_field_consumer_notes = QPlainTextEdit()
        self._parent.row_field_consumer_notes.setObjectName('row_field_id_number')
        self._parent.row_field_consumer_notes.textChanged.connect(
            lambda: self._parent.update_consumer_data('notes')
        )
        grid.addWidget(self._parent.row_field_consumer_notes, 6, 2)
        grid.setVerticalSpacing(15)
        grid.addWidget(self.get_button(), 7, 1, 1, 2)

        vbox_consumer.addLayout(grid)
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_consumer])
        dialog.setWindowTitle('CONSUMER')
        width, height = get_screen()
        dialog.setGeometry(0, 0, width/2.7, height/1.8)
        dialog.accepted.connect(self._parent.dialog_search_consumer_accepted)
        return dialog

    def get_button(self):
        self._parent.button_history_customer = CustomButton(
            id='button_history_customer',
            parent=self._parent,
            icon=get_icon('history'),
            title=self.tr('SALES HISTORY'),
            name_style='toolbar',
            method='button_sale_consumer_history'
        )
        self._parent.button_history_customer.setVisible(False)
        return self._parent.button_history_customer


class DialogTableSaleConsumer(QWidget):
    def __init__(self, parent):
        super(DialogTableSaleConsumer, self).__init__(parent)
        self._parent = parent

    def get(self):
        string_ = self.tr('SALES')
        width, height = get_screen()
        col_sizes_tlines = [
            field['width'] for field in self._parent.fields_sale_consumer
        ]
        table = TableView('model_sale_consumer',
            self._parent.model_sale_consumer, col_sizes_tlines,
            method_selected_row=self._parent.sale_consumer_selected
        )

        table.setFixedSize(width/1.5, height/2)
        vbox_ = QVBoxLayout()

        layout = QVBoxLayout()
        layout.addWidget(table)
        layout.setAlignment(alignCenter)

        vbox_.addLayout(layout)
        vbox_.addSpacing(10)
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_])
        dialog.setFixedSize(width/1.3, height/1.7)
        dialog.setWindowTitle(string_)
        return dialog


class SaleConsumerSelected(QWidget):
    def __init__(self, parent):
        super(SaleConsumerSelected, self).__init__(parent)
        self._parent = parent

    def get(self):
        vbox_ = QVBoxLayout()
        grid = QGridLayout()

        label_party = QLabel(self.tr('PARTY:'))
        label_party.setAlignment(alignLeft)
        label_party.setObjectName('label_party')
        grid.addWidget(label_party, 1, 1)
        self._parent.row_sale_party = QLineEdit()
        self._parent.row_sale_party.setObjectName('row_sale_party')
        grid.addWidget(self._parent.row_sale_party, 1, 2)

        label_number = QLabel(self.tr('NUMBER:'))
        label_number.setAlignment(alignLeft)
        label_number.setObjectName('label_number')
        grid.addWidget(label_number, 1, 3)
        self._parent.row_sale_number = QLineEdit()
        self._parent.row_sale_number.setObjectName('row_sale_number')
        grid.addWidget(self._parent.row_sale_number, 1, 4)

        label_date = QLabel(self.tr('DATE:'))
        label_date.setAlignment(alignLeft)
        label_date.setObjectName('label_date')
        grid.addWidget(label_date, 2, 1)
        self._parent.row_sale_date = QLineEdit()
        self._parent.row_sale_date.setObjectName('row_sale_date')
        grid.addWidget(self._parent.row_sale_date, 2, 2)

        label_salesman = QLabel(self.tr('SALESMAN:'))
        label_salesman.setAlignment(alignLeft)
        label_salesman.setObjectName('label_salesman')
        grid.addWidget(label_salesman, 2, 3)
        self._parent.row_sale_salesman = QLineEdit()
        self._parent.row_sale_salesman.setObjectName('row_sale_salesman')
        grid.addWidget(self._parent.row_sale_salesman, 2, 4)

        label_lines = QLabel(self.tr('LINES:'))
        label_lines.setAlignment(alignLeft)
        label_lines.setObjectName('label_lines')
        grid.addWidget(label_lines, 3, 1, 1, 4)
        col_sizes_tlines = [field['width'] for field in self._parent.fields_sale_line]
        table = TableView('model_sale_lines',
            self._parent.model_sale_customer_lines, col_sizes_tlines
        )
        grid.addWidget(table, 4, 1, 1, 4)

        label_untaxed = QLabel(self.tr('UNTAXED AMOUNT:'))
        label_untaxed.setAlignment(alignCenter)
        label_untaxed.setObjectName('label_untaxed')
        grid.addWidget(label_untaxed, 5, 1)
        self._parent.row_sale_untaxed = QLineEdit()
        self._parent.row_sale_untaxed.setObjectName('row_sale_untaxed')
        grid.addWidget(self._parent.row_sale_untaxed, 5, 2)

        label_tax_amount = QLabel(self.tr('TAX AMOUNT:'))
        label_tax_amount.setAlignment(alignCenter)
        label_tax_amount.setObjectName('label_tax_amount')
        grid.addWidget(label_tax_amount, 6, 1)
        self._parent.row_sale_tax_amount = QLineEdit()
        self._parent.row_sale_tax_amount.setObjectName('row_sale_tax_amount')
        grid.addWidget(self._parent.row_sale_tax_amount, 6, 2)

        label_total = QLabel(self.tr('TOTAL AMOUNT:'))
        label_total.setAlignment(alignCenter)
        label_total.setObjectName('label_total')
        grid.addWidget(label_total, 7, 1)
        self._parent.row_sale_total = QLineEdit()
        self._parent.row_sale_total.setObjectName('row_sale_total')
        grid.addWidget(self._parent.row_sale_total, 7, 2)

        grid.setVerticalSpacing(15)
        grid.addWidget(self.get_button(), 5, 3, 3, 4)

        vbox_.addLayout(grid)
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_])
        width, height = get_screen()
        dialog.setFixedSize(width/1.2, height/1.2)
        return dialog

    def get_button(self):
        self._parent.button_duplicate_sale = CustomButton(
            id='button_duplicate_sale',
            parent=self._parent,
            icon=get_icon('duplicate_sale'),
            title=self.tr('DUPLICATE SALE'),
            name_style='toolbar',
            method='button_duplicate_sale'
        )
        return self._parent.button_duplicate_sale


class DialogAgent(QWidget):
    def __init__(self, parent):
        super(DialogAgent, self).__init__(parent)
        self._parent = parent

    def get(self):
        view = [
            ('agent_ask', {
                'name': self.tr('AGENT'),
                'type': 'relation',
                'model': self._parent.Agent,
                'domain': [],
                'fields': [
                    ('id', self.tr('ID')),
                    ('party.rec_name', self.tr('NAME')),
                    ('party.id_number', self.tr('ID NUMBER')),
                ]}),
            ('commission_ask', {'name': self.tr('COMMISSION')}),
            ('commission_amount', {'name': self.tr('AMOUNT'), 'readonly': True}),
        ]
        return QuickDialog(self._parent, 'action', data=view)


class DialogCancelInvoice(QWidget):
    def __init__(self, parent):
        super(DialogCancelInvoice, self).__init__(parent)
        self._parent = parent

    def get(self):
        view = [
            ('password_for_cancel_ask', {
                'name': self.tr('INSERT PASSWORD FOR CANCEL'),
                'password': True
            }),
        ]
        return QuickDialog(self._parent, 'action', data=view)


class DialogForceAssign(QWidget):
    def __init__(self, parent):
        super(DialogForceAssign, self).__init__(parent)
        self._parent = parent

    def get(self):
        field = 'password_force_assign_ask'
        data = {'name': self.tr('PASSWORD FORCE ASSIGN')}
        return QuickDialog(self._parent, 'action', data=[(field, data)])


class DialogOrder(QWidget):
    def __init__(self, parent):
        super(DialogOrder, self).__init__(parent)
        self._parent = parent

    def get(self):
        string = self.tr('DO YOU WANT TO CONFIRM THE SEND ORDER?')
        return QuickDialog(self._parent, 'action', string, data=[])


class DialogStock(QWidget):
    def __init__(self, parent):
        super(DialogStock, self).__init__(parent)
        self._parent = parent

    def get(self):
        data = {
            'name': 'stock',
            'values': [],
            'heads': [self.tr('WAREHOUSE'), self.tr('QUANTITY')],
        }
        label = self.tr('STOCK BY PRODUCT:')
        return QuickDialog(self._parent, 'selection', label, data, readonly=True)


class DialogGlobalDiscount(QWidget):
    def __init__(self, parent):
        super(DialogGlobalDiscount, self).__init__(parent)
        self._parent = parent

    def get(self):
        field = 'global_discount_ask'
        data = {'name': self.tr('GLOBAL DISCOUNT')}
        return QuickDialog(self._parent, 'action', data=[(field, data)])


class DialogPrintInvoice(QWidget):
    def __init__(self, parent):
        super(DialogPrintInvoice, self).__init__(parent)
        self._parent = parent

    def get(self):
        view = [
            ('invoice_number_ask', {'name': self.tr('ORDER / INVOICE NUMBER')}),
            ('type_ask', {
                'name': self.tr('TYPE'),
                'type': 'selection',
                'values': [
                    ('invoice', self.tr('INVOICE')),
                    ('order', self.tr('ORDER')),
                    ('delivery', self.tr('DELIVERY'))
                ],
            }),
            ('printer_ask', {
                'name': self.tr('PRINTER'),
                'type': 'selection',
                'values': [
                    (1, 'POS'),
                    (2, 'LASER')
                ],
            }),
        ]
        return QuickDialog(self._parent, 'action', data=view)


class DialogVoucher(QWidget):
    def __init__(self, parent):
        super(DialogVoucher, self).__init__(parent)
        self._parent = parent

    def get(self):
        field = 'voucher_ask'
        data = {'name': self.tr('VOUCHER NUMBER')}
        return QuickDialog(self._parent, 'action', data=[(field, data)])


class DialogSalesman(QWidget):
    def __init__(self, parent):
        super(DialogSalesman, self).__init__(parent)
        self._parent = parent

    def get(self):
        string_ = self.tr('CHOOSE SALESMAN')
        vbox_salesman = create_vbox(
            self._parent,
            self._parent.employees,
            self._parent.on_selected_salesman,
            dimension=[1.7, 1.8]
        )

        dialog = QuickDialog(self._parent, 'action', size=(800, 500), widgets=[vbox_salesman])
        dialog.setWindowTitle(string_)
        width, height = get_screen()
        dialog.setFixedSize(width/1.5, height/1.5)
        return dialog


class DialogGlobalDiscountTable(QWidget):
    def __init__(self, parent):
        super(DialogGlobalDiscountTable, self).__init__(parent)
        self._parent = parent

    def get(self):
        string_ = self.tr('CHOOSE DISCOUNT')
        vbox_discounts = create_vbox(
            self._parent,
            self._parent.discounts,
            self._parent.on_selected_discount
        )

        dialog = QuickDialog(self._parent, 'action', size=(800, 500),
                             widgets=[vbox_discounts])
        dialog.setWindowTitle(string_)
        return dialog


class DialogDeliveryParty(QWidget):
    def __init__(self, parent):
        super(DialogDeliveryParty, self).__init__(parent)
        self._parent = parent

    def get(self):
        string_ = self.tr('CHOOSE DELIVERY MAN')
        vbox_salesman = create_vbox(
            self._parent,
            self._parent.delivery_parties,
            self._parent.on_selected_delivery_party,
            dimension=[1.7, 1.8]
        )
        dialog = QuickDialog(self._parent, 'action', size=(800, 500),
                             widgets=[vbox_salesman])
        dialog.setWindowTitle(string_)
        width, height = get_screen()
        dialog.setFixedSize(width / 1.5, height / 1.5)
        return dialog


class DeliveryPartySelected(QWidget):
    def __init__(self, parent):
        super(DeliveryPartySelected, self).__init__(parent)
        self._parent = parent

    def get(self):
        self._parent.state_delivery_party = {}
        vbox_ = QVBoxLayout()
        grid = QGridLayout()

        label_delivery_party = QLabel(self.tr('DELIVERY PARTY:'))
        label_delivery_party.setAlignment(alignCenter)
        label_delivery_party.setObjectName('label_delivery_party')
        grid.addWidget(label_delivery_party, 1, 1)
        self._parent.row_delivery_party = QLineEdit()
        self._parent.row_delivery_party.setObjectName('row_delivery_party')
        self._parent.row_delivery_party.textChanged.connect(
            lambda: self._parent.update_delivery_party('delivery_party'))
        grid.addWidget(self._parent.row_delivery_party, 1, 2)

        label_id_number = QLabel(self.tr('ID NUMBER:'))
        label_id_number.setAlignment(alignCenter)
        label_id_number.setObjectName('label_id_number')
        grid.addWidget(label_id_number, 2, 1)
        self._parent.row_id_number = QLineEdit()
        self._parent.row_id_number.setObjectName('row_id_number')
        self._parent.row_id_number.textChanged.connect(
            lambda: self._parent.update_delivery_party('id_number'))
        grid.addWidget(self._parent.row_id_number, 2, 2)

        label_number_plate = QLabel(self.tr('NUMBER PLATE:'))
        label_number_plate.setAlignment(alignCenter)
        label_number_plate.setObjectName('label_number_plate')
        grid.addWidget(label_number_plate, 3, 1)
        self._parent.row_number_plate = QLineEdit()
        self._parent.row_number_plate.setObjectName('row_number_plate')
        self._parent.row_number_plate.textChanged.connect(
            lambda: self._parent.update_delivery_party('number_plate'))
        grid.addWidget(self._parent.row_number_plate, 3, 2)

        label_phone = QLabel(self.tr('PHONE:'))
        label_phone.setAlignment(alignCenter)
        label_phone.setObjectName('label_phone')
        grid.addWidget(label_phone, 4, 1)
        self._parent.row_phone = QLineEdit()
        self._parent.row_phone.setObjectName('row_phone')
        self._parent.row_phone.textChanged.connect(
            lambda: self._parent.update_delivery_party('row_phone'))
        grid.addWidget(self._parent.row_phone, 4, 2)

        label_type_vehicle = QLabel(self.tr('TYPE VEHICLE:'))
        label_type_vehicle.setAlignment(alignCenter)
        label_type_vehicle.setObjectName('label_type_vehicle')
        grid.addWidget(label_type_vehicle, 5, 1)
        self._parent.row_type_vehicle = ComboBox(self._parent, 'TYPE VEHICLE',
                                                 {'values': TYPE_VEHICLE})
        self._parent.row_type_vehicle.setObjectName('row_type_vehicle')
        self._parent.row_type_vehicle.currentIndexChanged.connect(
            lambda: self._parent.update_delivery_party('type_vehicle'))
        grid.addWidget(self._parent.row_type_vehicle, 5, 2)

        label_delivery_party_active = QLabel(self.tr('ACTIVE:'))
        label_delivery_party_active.setAlignment(alignCenter)
        label_delivery_party_active.setObjectName('label_delivery_party_active')
        grid.addWidget(label_delivery_party_active, 6, 1)
        self._parent.row_delivery_party_active = QCheckBox()
        self._parent.row_delivery_party_active.setObjectName('row_delivery_party_active')
        self._parent.row_delivery_party_active.stateChanged.connect(
            lambda: self._parent.update_delivery_party('delivery_party_active'))
        grid.addWidget(self._parent.row_delivery_party_active, 6, 2)

        vbox_.addLayout(grid)
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_])
        dialog.accepted.connect(self._parent.dialog_delivery_party_accepted)
        return dialog


class DialogTableDeliveryParty(QWidget):
    def __init__(self, parent):
        super(DialogTableDeliveryParty, self).__init__(parent)
        self._parent = parent

    def get(self):
        string_ = self.tr('DELIVERY MAN')

        col_sizes_tlines = [field['width'] for field in self._parent.fields_delivery_party]
        table = TableView('model_delivery_party',
          self._parent.model_delivery_party, col_sizes_tlines,
          method_selected_row=self._parent.delivery_party_selected
        )
        width, height = get_screen()
        table.setFixedSize(width/2.2, height/2.2)
        vbox_ = QVBoxLayout()

        grid = QGridLayout()
        grid.addWidget(table, 1, 1, 1, 2)
        grid.setVerticalSpacing(20)
        grid.addWidget(self.get_button(), 2, 1, 1, 2)
        grid.setAlignment(alignCenter)

        vbox_.addLayout(grid)
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_])
        width, height = get_screen()
        dialog.setGeometry(0, 0, width/1.8, height/1.5)
        dialog.setWindowTitle(string_)
        return dialog

    def get_button(self):
        self._parent.button_create_delivery_party = CustomButton(
            id='button_create_delivery_party',
            parent=self._parent,
            icon=get_icon('delivery_party'),
            title=self.tr('CREATE NEW DELIVERY MEN'),
            name_style='toolbar',
            method='button_create_delivery_party'
        )
        return self._parent.button_create_delivery_party


class DialogTableMoneyCount(QWidget):
    def __init__(self, parent):
        super(DialogTableMoneyCount, self).__init__(parent)
        self._parent = parent

    def get(self):
        string_ = self.tr('MONEY COUNT')

        col_sizes_tlines = [200, 160, 210]
        table = TableView('model_money_count', self._parent.model_money_count,
                          col_sizes_tlines, selection_edit=True)

        width, height = get_screen()
        table.setFixedSize(width/3.3, height/3)
        vbox_ = QVBoxLayout()
        label, field = self.get_fields()

        layout1 = QVBoxLayout()
        layout1.addWidget(table)
        layout1.setAlignment(alignCenter)
        layout2 = QHBoxLayout()
        label.setAlignment(alignCenter)
        field.setAlignment(alignLeft)
        layout2.addWidget(label)
        layout2.addWidget(field)
        layout2.setAlignment(alignCenter)

        vbox_.addLayout(layout1)
        vbox_.addSpacing(20)
        vbox_.addLayout(layout2)
        vbox_.addSpacing(20)
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_])
        width, height = get_screen()
        dialog.setGeometry(0, 0, width/3, height/1.8)
        dialog.setWindowTitle(string_)
        dialog.accepted.connect(self._parent.dialog_money_count_accepted)
        return dialog

    def get_fields(self):
        label_amount = QLabel(self.tr('TOTAL MONEY:'))
        label_amount.setObjectName('label_price')
        self._parent.row_field_total_money = FieldMoney(self, 'row_field_total_money',
                                                        {}, readonly=True)
        self._parent.row_field_total_money.setObjectName('row_field_total_money')
        self._parent.row_field_total_money.textChanged.connect(
            lambda: self._parent.update_sale_line('unit_price')
        )
        self._parent.row_field_total_money.setAlignment(alignLeft)
        return label_amount, self._parent.row_field_total_money


class DialogTaxes(QWidget):
    def __init__(self, parent):
        super(DialogTaxes, self).__init__(parent)
        self._parent = parent

    def get(self):
        if self._parent.shop_taxes:
            taxes = [(str(e['id']), e['name']) for e in self._parent.shop_taxes]
        else:
            taxes = []
        data = {
            'name': 'tax',
            'values': taxes,
            'heads': [self.tr('Id'), self.tr('Salesman')],
        }
        string = self.tr('CHOOSE TAX')
        return QuickDialog(self._parent, 'selection', string, data)


class DialogChannel(QWidget):
    def __init__(self, parent):
        super(DialogChannel, self).__init__(parent)
        self._parent = parent

    def get(self):
        string_ = self.tr('SELECT CHANNEL')
        vbox_ = create_vbox(self._parent, self._parent.channels,
                            self._parent.on_selected_channel)
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_])
        dialog.setWindowTitle(string_)
        return dialog


class DialogPaymentTerm(QWidget):
    def __init__(self, parent):
        super(DialogPaymentTerm, self).__init__(parent)
        self._parent = parent

    def get(self):
        string_ = self.tr('SELECT PAYMENT TERM')
        vbox_ = create_vbox(self._parent, self._parent._payment_terms,
                            self._parent.on_selected_payment_term)
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_])
        dialog.setWindowTitle(string_)
        return dialog


class DialogPayment(QWidget):
    def __init__(self, parent):
        super(DialogPayment, self).__init__(parent)
        self._parent = parent

    def get(self):
        string_ = self.tr('SELECT PAYMENT MODE:')
        vbox_ = create_vbox(
            self._parent,
            self._parent._journals,
            self._parent.on_selected_payment
        )
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_])
        dialog.setWindowTitle(string_)
        return dialog


class Position(QWidget):
    def __init__(self, parent):
        super(Position, self).__init__(parent)
        self._parent = parent

    def get(self):
        _field = 'position'
        _data = {'name': self.tr('POSITION')}
        return QuickDialog(self._parent, 'action', data=[(_field, _data)])


class Comment(QWidget):
    def __init__(self, parent):
        super(Comment, self).__init__(parent)
        self._parent = parent

    def get(self):
        _field = 'comment'
        _data = {'name': self.tr('COMMENTS'), 'type': 'text'}
        return QuickDialog(self._parent, 'action', data=[(_field, _data)])


class TipAmount(QWidget):
    def __init__(self, parent):
        super(TipAmount, self).__init__(parent)
        self._parent = parent

    def get(self):
        _field = 'tip_amount_ask'
        _data = {'name': self.tr('TIP AMOUNT')}
        return QuickDialog(self._parent, 'action', data=[(_field, _data)])


class DeliveryAmount(QWidget):
    def __init__(self, parent):
        super(DeliveryAmount, self).__init__(parent)
        self._parent = parent

    def get(self):
        _field = 'delivery_amount_ask'
        _data = {'name': self.tr('DELIVERY AMOUNT')}
        return QuickDialog(self._parent, 'action', data=[(_field, _data)])


class EditLine(QWidget):
    def __init__(self, parent):
        super(EditLine, self).__init__(parent)
        self._parent = parent

    def get(self):
        self._parent.state_line = {}
        vbox_product = QVBoxLayout()
        grid = QGridLayout()
        qty = 2

        self._parent.label_product = QLabel()
        self._parent.label_product.setAlignment(alignCenter)
        self._parent.label_product.setObjectName('label_product')
        vbox_product.addWidget(self._parent.label_product)
        self._parent.row_field_description = QLineEdit()
        self._parent.row_field_description.setObjectName('row_field_description')
        self._parent.row_field_description.textChanged.connect(
            lambda: self._parent.update_sale_line('description')
        )
        grid.addWidget(self._parent.row_field_description, 1, 1, 1, 2)

        if self._parent._config.get('show_fractions'):
            label_fraction = QLabel(self.tr('FRACTION:'))
            label_fraction.setObjectName('label_fraction')
            grid.addWidget(label_fraction, 2, 1)
            self._parent.field_combobox_fraction = ComboBox(self._parent, 'fraction',
                                                      {'values': FRACTIONS})
            grid.addWidget(self._parent.field_combobox_fraction, 2, 2)
            self._parent.field_combobox_fraction.currentIndexChanged.connect(
                lambda: self._parent.update_sale_line('qty_fraction')
            )

        label_qty = QLabel(self.tr('QUANTITY:'))
        label_qty.setObjectName('label_qty')
        grid.addWidget(label_qty, 3, 1)
        self._parent.row_field_qty = QDoubleSpinBox()
        self._parent.row_field_qty.setObjectName('row_field_qty')
        self._parent.row_field_qty.setMinimum(0)
        self._parent.row_field_qty.setMaximum(100000)
        if self._parent._config.get('decimals_digits_quantity'):
            qty = self._parent._config['decimals_digits_quantity']

        self._parent.row_field_qty.setDecimals(qty)
        self._parent.row_field_qty.setAlignment(alignCenter)
        grid.addWidget(self._parent.row_field_qty, 3, 2)
        self._parent.row_field_qty.valueChanged.connect(
            lambda: self._parent.update_sale_line('quantity')
        )

        label_price = QLabel(self.tr('UNIT PRICE:'))
        label_price.setObjectName('label_price')
        grid.addWidget(label_price, 4, 1)
        self._parent.row_field_price = FieldMoney(self, 'row_field_price', {}, readonly=False)
        self._parent.row_field_price.setObjectName('row_field_price')
        grid.addWidget(self._parent.row_field_price, 4, 2)
        self._parent.row_field_price.textChanged.connect(
            lambda: self._parent.update_sale_line('unit_price')
        )

        self._parent.row_field_note = QTextEdit('')
        self._parent.row_field_note.setObjectName('row_field_note')
        grid.addWidget(self._parent.row_field_note, 5, 1, 5, 2)
        self._parent.row_field_note.textChanged.connect(
            lambda: self._parent.update_sale_line('note')
        )
        button_delete = CustomButton(
            self._parent,
            id='button_delete',
            size='small',
            icon=get_icon('delete_line'),
            title=self.tr('DELETE'),
            method='action_delete_line',
            name_style='mini_button',
        )
        button_addition = CustomButton(
            self._parent,
            id='button_addition',
            size='small',
            icon=get_icon('addition-product'),
            title=self.tr('ADDITION'),
            method='action_addition_line',
            name_style='mini_button',
        )
        hbox = QHBoxLayout()
        vbox_product.addLayout(grid, 1)
        vbox_product.addLayout(hbox, 0)
        hbox.addWidget(button_delete, 0)

        if self._parent.enviroment == 'restaurant':
            hbox.addWidget(button_addition, 0)
        dialog = QuickDialog(self._parent, 'action', widgets=[vbox_product], size=[600, 900])
        dialog.accepted.connect(self._parent.dialog_product_edit_accepted)
        return dialog


class AdditionProduct(QuickDialog):
    def __init__(self, parent):
        super(AdditionProduct, self).__init__(parent, 'action')
        self.setWindowTitle(self.tr('SELECT ADDITIONAL'))
        self._parent = parent

    def set_products(self, products):
        vbox_ = create_vbox(self._parent, products, 'on_selected_item_mix')
        self.add_widget(vbox_)


class Help(HelpDialog):

    def __init__(self, parent):
        super(Help, self).__init__(parent)
        shortcuts = [
            (self.tr('PANEL'), 'F1'),
            (self.tr('SEARCH PRODUCT'), 'F2'),
            (self.tr('PAYMENT MODE'), 'F3'),
            (self.tr('SEARCH CUSTOMER'), 'F4'),
            (self.tr('GLOBAL DISCOUNT'), 'F5'),
            (self.tr('PRINT ORDER'), 'F6'),
            (self.tr('PRINT INVOICE'), 'F7'),
            (self.tr('PAYMENT TERM'), 'F8'),
            (self.tr('SEARCH SALES'), 'F9'),
            (self.tr('ACTIVATE TABLE'), 'F10'),
            (self.tr('NEW SALE'), 'F11'),
            (self.tr('CONTROL PANEL'), 'F12'),
            (self.tr('SALESMAN'), 'Home'),
            (self.tr('POSITION'), 'Insert'),
            (self.tr('CASH'), 'End'),
            (self.tr('COMMENT'), 'Quotation Marks'),
        ]

        self.set_shortcuts(shortcuts)
