{# To include this widget, make sure to pass: `manufacturer_parts`, `profile`, (optional, for mouser) `part_revision` variables  #}
{% load static %}

{% block head %}
    <link rel="stylesheet" type="text/css" href="{% static 'bom/css/treetable-theme.css' %}"/>
    <link rel="stylesheet" type="text/css" href="{% static 'bom/css/jquery.treetable.css' %}"/>
{% endblock %}

<div class="responsive-table-wrapper">
    <table id="manufacturer-parts" class="highlight tight treetable">
        <thead>
        <tr>
            <th>MPN</th>
            <th>Manufacturer</th>
            {% if show_part %}<th>Part</th>{% endif %}
            <th>Seller</th>
            <th>PN</th>
            <th>MOQ</th>
            <th>MPQ</th>
            <th>Price</th>
            <th>Lead Time (days)</th>
            <th>NRE</th>
            <th>NCNR</th>
            <th colspan="2">Manage</th>
        </tr>
        </thead>
        <tbody>
        {% for manufacturer_part in manufacturer_parts %}
            <tr id="sourcing-mp-{{ manufacturer_part.id }}" data-tt-id="{{ manufacturer_part.id }}">
                <td>{% if manufacturer_part.link %}<a href="{{ manufacturer_part.link }}" target="_blank">{% endif %}{{ manufacturer_part.manufacturer_part_number }}{% if manufacturer_part.link %}&nbsp;<i class="material-icons" style="font-size: 14px;">open_in_new</i></a>{% endif %}</td>
                <td>{% if manufacturer_part.manufacturer %}<a href="{% url 'bom:manufacturer-info' manufacturer_id=manufacturer_part.manufacturer_id %}">{% endif %}{{ manufacturer_part.manufacturer }}{% if manufacturer_part.manufacturer %}</a>{% endif %}</td>
                {% if show_part %}<td><a href="{% url 'bom:part-info' part_id=manufacturer_part.part_id %}">{{ manufacturer_part.part }}</a></td>{% endif %}
                <td id="sourcing-mp-{{ manufacturer_part.id }}-name">{% if manufacturer_part.optimal_seller.link %}<a href="{{ manufacturer_part.optimal_seller.link }}" target="_blank">{% endif %}{{ manufacturer_part.optimal_seller.seller.name }}{% if manufacturer_part.optimal_seller.link %}&nbsp;<i class="material-icons" style="font-size: 14px;">open_in_new</i></a>{% endif %}</td>
                <td id="sourcing-mp-{{ manufacturer_part.id }}-pn">{{ manufacturer_part.optimal_seller.seller_part_number }}</td>
                <td id="sourcing-mp-{{ manufacturer_part.id }}-moq">{{ manufacturer_part.optimal_seller.minimum_order_quantity }}</td>
                <td id="sourcing-mp-{{ manufacturer_part.id }}-mpq">{{ manufacturer_part.optimal_seller.minimum_pack_quantity }}</td>
                <td id="sourcing-mp-{{ manufacturer_part.id }}-cost">{{ manufacturer_part.optimal_seller.unit_cost }}</td>
                <td id="sourcing-mp-{{ manufacturer_part.id }}-lt">{{ manufacturer_part.optimal_seller.lead_time_days }}</td>
                <td id="sourcing-mp-{{ manufacturer_part.id }}-nre">{{ manufacturer_part.optimal_seller.nre_cost }}</td>
                <td id="sourcing-mp-{{ manufacturer_part.id }}-ncnr">{{ manufacturer_part.optimal_seller.ncnr }}</td>
                {#                                    <td style="min-width: 0px;"></td>#}
                <td>
                    {% if profile.role == 'A' %}
                        <!-- Dropdown Trigger -->
                        <a class='dropdown-trigger' href='#' data-target='dropdown{{ manufacturer_part.id }}'><i
                                class="material-icons right green-text lighten-1">more_horiz</i></a>
                        <!-- Dropdown Structure -->
                        <ul id='dropdown{{ manufacturer_part.id }}' class='dropdown-content'>
                            <li><a class="green-text text-lighten-1"
                                   href="{% url 'bom:manufacturer-part-edit' manufacturer_part_id=manufacturer_part.id %}"><i
                                    class="material-icons green-text text-lighten-1">edit</i>edit</a></li>
                            <li><a class="green-text text-lighten-1"
                                   href="{% url 'bom:manufacturer-part-add-sellerpart' manufacturer_part_id=manufacturer_part.id %}"><i
                                    class="material-icons green-text text-lighten-1">add</i>add seller part</a>
                            </li>
                            <li class="divider" tabindex="-1"></li>
                            <li><a class="red-text text-lighten-1"
                                   href="{% url 'bom:manufacturer-part-delete' manufacturer_part_id=manufacturer_part.id %}"><i
                                    class="material-icons red-text text-lighten-1">delete_forever</i>delete</a>
                            </li>
                        </ul>
                    {% endif %}
                </td>
            </tr>
            {% for seller_part in manufacturer_part.seller_parts %}
                <tr data-tt-id="0" data-tt-parent-id="{{ manufacturer_part.id }}" {% if forloop.last %}id="sourcing-{{ manufacturer_part.id }}-last"{% endif %}>
                    <td></td>
                    <td></td>
                    <td>{% if seller_part.link %}<a href="{{ seller_part.link }}" target="_blank">{% endif %}{{ seller_part.seller.name }}{% if seller_part.link %}&nbsp;<i class="material-icons" style="font-size: 14px;">open_in_new</i></a>{% endif %}</td>
                    <td>{{ seller_part.seller_part_number }}</td>
                    <td>{{ seller_part.minimum_order_quantity }}</td>
                    <td>{{ seller_part.minimum_pack_quantity }}</td>
                    <td>{{ seller_part.unit_cost }}</td>
                    <td>{{ seller_part.lead_time_days }}</td>
                    <td>{{ seller_part.nre_cost }}</td>
                    <td>{{ seller_part.ncnr }}</td>
                    <td>{% if profile.role == 'A' %}
                        <a href="{% url 'bom:sellerpart-edit' sellerpart_id=seller_part.id %}">edit</a> |
                        <a href="{% url 'bom:sellerpart-delete' sellerpart_id=seller_part.id %}">delete</a>
                    {% endif %}</td>
                </tr>
            {% empty %}
                <tr data-tt-id="0" data-tt-parent-id="{{ manufacturer_part.id }}">
                    <td colspan="99" style="text-align: center;"><i>This manufacturer part has no sellers entered yet.</i></td>
                </tr>
            {% endfor %}
        {% empty %}
            <tr>
                <td colspan="99" style="text-align: center; height: 20vh;"><i>None found.</i></td>
            </tr>
        {% endfor %}
        </tbody>
    </table>
</div>

<script src="{% static 'bom/js/jquery.treetable.js' %}"></script>
<script>
    $("#manufacturer-parts").treetable({
        expandable: true,
        indent: 2,
        initialState: 'collapsed',
    });
</script>

<!-- Floating Horizontal Scrollbar -->
<script type="text/javascript" src="{% static 'bom/js/jquery.ba-floatingscrollbar.min.js' %}"></script>
<script>
    $(function () {
        $('.responsive-table-wrapper').floatingScrollbar();
    });
</script>

<!-- Match Seller Parts -->
<script>
    let partMatchData = {};
    const mouserImage = '<img height="18" style="padding: 4px 4px 0 4px;" alt="Mouser" title="Via Mouser.com" src="{% static 'bom/img/mouser.png' %}">';
    let specsUnitCost;
    let specsEstCostPerOrder;
    let specsMissingParts;
    let dataSheet;
    $(document).ready(function () {
        {% if part_revision.id and mouser_parts %}
            $.get("{% url 'json:mouser-part-match-bom' part_revision_id=part_revision.id %}",
                function (response) {
                    partMatchData = response['content'];
                    const errors = response['errors'];
                    if (errors.length > 0) {
                        console.error(errors);
                    } else {
                        const flatBom = partMatchData['flat_bom'];
                        const bomParts = flatBom['parts'];
                        const mouserInfo = flatBom['parts']['{{ part_revision.id }}']['api_info'];
                        const sourcingParts = mouserInfo['seller_parts'];
                        const stockParsed = mouserInfo['stock_parsed'];
                        const optimalSellerPart = flatBom['parts']['{{ part_revision.id }}']['seller_part'];
                        specsUnitCost = parseFloat(flatBom['unit_cost']).toFixed(4);
                        specsEstCostPerOrder = parseFloat(flatBom['out_of_pocket_cost']).toFixed(2);
                        specsMissingParts = flatBom['missing_item_costs'];
                        dataSheet = mouserInfo['data_sheet'];
                        mouserStock = mouserInfo['stock'];
                        const sellerLink = mouserInfo['product_detail_url'];
                        updateSpecs(specsUnitCost, specsEstCostPerOrder, specsMissingParts, dataSheet, mouserStock, sellerLink);
                        updateFlat(bomParts);
                        updateIndented(bomParts);
                        updateSourcing(sourcingParts, optimalSellerPart, stockParsed);
                        $("#indented-bom").trigger('update');
                        $("#flat-bom").trigger('update');
                    }
                }
            );
        {% endif %}
    });

    function updateSourcing(sellerParts, optimalSellerPart, stock) {
        let lastRowDict = {};
        let mouserOptimizations = 0;
        if (sellerParts) {
            sellerParts.forEach((sellerPart, index) => {
                if (sellerPart['data_source'] === 'Mouser') mouserOptimizations += 1;
                const manufacturerPartId = parseInt(sellerPart['manufacturer_part']);
                if (!(manufacturerPartId in lastRowDict)) {
                    const lastRow = $(`#sourcing-${manufacturerPartId}-last`);
                    if (lastRow.length === 0) {
                        lastRowDict[manufacturerPartId] = $(`#sourcing-mp-${manufacturerPartId}`);
                    } else {
                        lastRowDict[manufacturerPartId] = lastRow;
                    }
                }
                if (lastRowDict[manufacturerPartId]) {
                    const pn = sellerPart['seller_part_number'];
                    const moq = sellerPart['minimum_order_quantity'];
                    const mpq = sellerPart['minimum_pack_quantity'];
                    const price = parseFloat(sellerPart['unit_cost']).toFixed(4);
                    const leadTime = `${sellerPart['lead_time_days']}`;
                    const nre = parseFloat(sellerPart['nre_cost']).toFixed(4);
                    const ncnr = "True";
                    lastRowDict[manufacturerPartId].after(`<tr data-tt-id="${index + 1}" data-tt-parent-id="${manufacturerPartId}"><td></td><td></td><td>${mouserImage} Mouser</td><td>${pn}</td><td>${moq}</td><td>${mpq}</td><td>${price}</td><td>${leadTime}</td><td>${nre}</td><td>${ncnr}</td><td>(${stock} in stock)</td></tr>`)
                    const lastRow = lastRowDict[manufacturerPartId].closest('tr').next('tr');
                    lastRowDict[manufacturerPartId] = lastRow;
                    const parentNode = $("#manufacturer-parts").treetable("node", manufacturerPartId);
                    $("#manufacturer-parts").treetable("loadBranch", parentNode, lastRow);
                    $("#manufacturer-parts").treetable("collapseAll");
                }
            });
        }
        if (optimalSellerPart && optimalSellerPart !== "None") {
            const mpBaseId = `#sourcing-mp-${optimalSellerPart['manufacturer_part']}`;
            if (optimalSellerPart['seller'] === null) { // TODO need to fix this to get the seller name via the API
                $(`${mpBaseId}-name`).text(optimalSellerPart['data_source']).prepend(mouserImage);
            }
            $(`${mpBaseId}-pn`).text(optimalSellerPart['seller_part_number']);
            $(`${mpBaseId}-moq`).text(optimalSellerPart['minimum_order_quantity']);
            $(`${mpBaseId}-mpq`).text(optimalSellerPart['minimum_pack_quantity']);
            $(`${mpBaseId}-cost`).text(optimalSellerPart['unit_cost']);
            $(`${mpBaseId}-lt`).text(optimalSellerPart['lead_time_days']);
            $(`${mpBaseId}-nre`).text(optimalSellerPart['nre_cost']);
            $(`${mpBaseId}-ncnr`).text(optimalSellerPart['ncnr']);
        }
    }

    function updateSpecs(unitCost, estCostPerOrder, specsMissingParts, dataSheet, mouserStock, sellerLink) {
        const mouserEstCost = $("#mouser-est-cost");
        const mouserEstCostPerOrder = $("#mouser-est-cost-per-order");
        const mouserMissingCosts = $("#mouser-missing-item-costs");
        const mouserDataSheetWrapperElement = $("#mouser-data-sheet-wrapper");
        const mouserDataSheetElement = $("#mouser-data-sheet");
        const mouserStockWrapperElement = $("#mouser-stock-wrapper");
        const mouserStockElement = $("#mouser-stock");
        const currencyUnit = "{{ organization.currency }}" === "USD" ? "$" : ""; // Do this right some day...
        updateSpecElement(mouserEstCost, unitCost, `${currencyUnit}${unitCost}`);
        updateSpecElement(mouserEstCostPerOrder, estCostPerOrder, `${currencyUnit}${estCostPerOrder}`);
        updateSpecElement(mouserMissingCosts, specsMissingParts, `${specsMissingParts}`);
        updateSpecElement(mouserStockElement, mouserStock, `${mouserStock}`, mouserStockWrapperElement, false);
        mouserStockElement.append(` (<a href="${sellerLink}" target="_blank">view</a>)`)

        if (dataSheet) {
            mouserDataSheetElement.attr("href", `${dataSheet}`);
            mouserDataSheetWrapperElement.show();
        }
    }

    function updateSpecElement(element, property, text, wrapper = null, hasDefault = true) {
        if (property != null) {
            if (hasDefault) {
                element.text(text + ' ').prepend(mouserImage).next().css('color', '#bdbdbd').prepend('(').append(' without Mouser)');
            } else {
                element.text(text).prepend(mouserImage);
                if (wrapper) {
                    wrapper.show();
                }
            }
        }
    }

    function updateIndented(indentedBomParts) {
        const baseUnitCostId = "#bom-indented-unit-cost-";
        const baseSellerNameId = "#bom-indented-seller-name-";
        updateBom(indentedBomParts, baseUnitCostId, baseSellerNameId);
    }

    function updateFlat(flatBomParts) {
        const baseUnitCostId = "#bom-flat-unit-cost-";
        const baseSellerNameId = "#bom-flat-seller-name-";
        updateBom(flatBomParts, baseUnitCostId, baseSellerNameId);
    }

    function updateBom(bomParts, baseUnitCostId, baseSellerNameId) {
        for (const partRevId in bomParts) {
            if (bomParts.hasOwnProperty(partRevId) && bomParts[partRevId].hasOwnProperty('seller_part') && bomParts[partRevId].hasOwnProperty('api_info')) {
                const unitCost = parseFloat(bomParts[partRevId]['seller_part']['unit_cost']);
                const sellerName = bomParts[partRevId]['seller_part']['data_source'];
                const isMouser = bomParts[partRevId]['seller_part']['seller'] === 'None' || bomParts[partRevId]['seller_part']['seller'] === null;
                const sellerLink = bomParts[partRevId]['api_info']['product_detail_url'];
                const sourcingInfo = bomParts[partRevId]['api_info'] !== 'None';
                const unitCostId = `${baseUnitCostId}${partRevId}`;
                const unitCostElement = $(unitCostId);
                const sellerNameId = `${baseSellerNameId}${partRevId}`;
                const sellerNameElement = $(sellerNameId);
                if (unitCost && sourcingInfo && sellerLink) {
                    unitCostElement.text('');
                    unitCostElement.html(`<a href="${sellerLink}" target="_blank">${unitCost.toFixed(4)}</a>`);
                } else if (unitCost && sourcingInfo) {
                    unitCostElement.text(`${unitCost.toFixed(4)}`);
                }
                if (unitCost && sourcingInfo && bomParts[partRevId]['seller_part']['data_source'] === 'Mouser') unitCostElement.append(mouserImage);
                if (isMouser && sellerName) sellerNameElement.text('Mouser');
            }
        }
    }
</script>