{% extends 'bom/bom-base.html' %}

{% load static %}

{% block head-title %}{{ part.full_part_number }}{% if part_revision %} {{ part_revision.synopsis }}{% endif %}{% endblock %}

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

{% block content %}
    {% include 'bom/bom-action-btn.html' with profile=profile %}
    <div class="container-app">
        <div class="part-info">
            <div class="row" style="margin-bottom: 5px;">
                <div class="col m8 hide-on-small-and-down">
                    <h3 class="light">{{ part.full_part_number }}</h3>
                    {% if profile.role == 'A' %}
                        <p>Select latest revision to edit, add a new revision, etc., or select an earlier revision for viewing only</p>
                    {% else %}
                        <p>Select a revision for viewing</p>
                    {% endif %}
                </div>
            </div>

            <div class="row">
                {% if part_revision %}
                    <div class="col l2 m3 s5">
                        <div class="input-field">
                            <select id="select-revision">
                                {% for r in revisions.all %}
                                    <option {% if part_revision.id == r.id %}selected{% endif %}
                                            value="{% if r == part.latest %}{% url 'bom:part-info' part_id=part.id %}
                                                    {% else %}{% url 'bom:part-info-history' part_id=part.id part_revision_id=r.id %}
                                                    {% endif %}">Rev {{ r.revision }}{% if r.configuration == 'W' %} (working){% endif %}</option>
                                {% endfor %}
                            </select>
                        </div>
                    </div>
                {% endif %}
                <div class="col {% if part_revision %}m3 s1{% else %}m3 s12 center{% endif %}">
                    {% if profile.role == 'A' and part_revision %}
                        <div style="margin-top: 1.5rem;">
                            <!-- Dropdown Trigger -->
                            <button class='dropdown-trigger hide-on-small-and-down waves-effect waves-light grey lighten-4 btn-flat'
                                    href='#' data-target='dropdown-revision'><i class="material-icons right">arrow_drop_down</i>Manage
                            </button>
                            <a class='dropdown-trigger hide-on-med-and-up' href='#' data-target='dropdown-revision'><i
                                    class="material-icons green-text text-lighten-1">more_vert</i></a>
                            <!-- Dropdown Structure -->
                            <ul id='dropdown-revision' class='dropdown-content'>
                                {% if part_revision.configuration == 'W' %}
                                    <li>
                                        <a class="green-text text-lighten-1"
                                           href="{% url 'bom:part-revision-edit' part_id=part.id part_revision_id=part_revision.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:part-revision-release' part_id=part.id part_revision_id=part_revision.id %}">
                                            <i class="material-icons green-text text-lighten-1">check</i>Release</a>
                                    </li>
                                {% endif %}
                                <li>
                                    <a class="green-text text-lighten-1" href="{% url 'bom:part-revision-new' part_id=part.id %}">
                                        <i class="material-icons green-text text-lighten-1">add</i>New revision</a>
                                </li>
                                {% if part_revision.configuration == 'R' %}
                                    <li>
                                        <a class="green-text text-lighten-1 disabled" onclick="revertPartRevision()">
                                            <i class="material-icons green-text text-lighten-1">undo</i>Revert to working</a>
                                    </li>
                                {% endif %}
                                <li class="divider" tabindex="-1"></li>
                                <li>
                                    <a class="red-text text-lighten-1" onclick="deletePartRevision()">
                                        <i class="material-icons red-text text-lighten-1">delete</i>Delete</a>
                                </li>
                            </ul>
                        </div>
                    {% elif profile.role == 'A' and not part_revision %}
                        <a class='waves-effect waves-light grey lighten-4 btn-flat'
                           href='{% url 'bom:part-revision-new' part_id=part.id %}'><i class="material-icons left">add</i>Create Revision</a>
                    {% endif %}
                </div>
                {% if part_revision %}
                    <div class="col m2 push-l5 push-m4 s6 right-align part-info-form">
                        <form action="{% url 'bom:part-info' part_id=part.id %}" method="post">
                            {% csrf_token %}
                            <div class="row">
                                <div class="col s9" style="padding-right: 0;">
                                    {{ part_info_form }}
                                </div>
                                <div class="col s3">
                                    <button type="submit" class="waves-effect waves-green btn-flat input-field btn-icon-round"><i class="material-icons green-text">send</i></button>
                                </div>
                            </div>
                        </form>
                    </div>
                {% endif %}
            </div>

            <div class="row">
                <div class="col s12">
                    <ul id="tabs" class="tabs tabs-fixed-width">
                        <li class="tab"><a id="specs-tab" href="#specs">Specifications</a></li>
                        <li class="tab"><a id="bom-tab" href="#bom">Bill of Materials</a></li>
                        <li class="tab"><a id="used-tab" href="#used">Where Used</a></li>
                        <li class="tab"><a id="sourcing-tab" href="#sourcing">Sourcing</a></li>
                    </ul>
                </div>

                <div id="specs" class="col s12">
                    <br>
                    <ul class="collection with-header">
                        <li class="collection-header"><h5>Item Details</h5></li>
                        <li class="collection-item">
                            {% if organization.number_scheme == 'S' %}
                                <div class="row">
                                    <div class="col s4 l2 text-right" style="padding-left: 0px;">Item Class:</div>
                                    <div class="col s8 l10">{{ part.number_class }}</div>
                                </div>
                            {% endif %}
                            <div class="row">
                                <div class="col s4 l2 text-right" style="padding-left: 0px;">Number:</div>
                                <div class="col s8 l10">{{ part.full_part_number }}
                                    {% if profile.role == 'A' %}
                                        <a href="{% url 'bom:part-edit' part_id=part.id %}">&nbsp;[edit]</a>
                                    {% endif %}
                                </div>
                            </div>
                            <div class="row">
                                <div class="col s4 l2 text-right" style="padding-left: 0px;">Synopsis:</div>
                                <div class="col s8 l10">{{ part_revision.synopsis }}</div>
                            </div>
                            <div class="row">
                                <div class="col s4 l2 text-right" style="padding-left: 0px;">Configuration:</div>
                                <div class="col s8 l10">{{ part_revision.get_configuration_display|default:'n/a' }}&nbsp;<i>{% if part_revision %}(as of <span id="specs-revision-timestamp"></span>
                                    ){% endif %}
                                </i></div>
                            </div>
                            <div class="row">
                                <div class="col s4 l2 text-right" style="padding-left: 0;">
                                    <img title="Via Google Drive" style="width: 16px;" src="{% static 'bom/img/google_drive_logo.svg' %}">&nbsp;Files:
                                </div>
                                <div class="col s8 l10"><a href="{% url 'google-drive:add-folder' part_id=part.id %}" target="_blank">Open Folder</a></div>
                            </div>
                            <div class="row">
                                <div id="mouser-data-sheet-wrapper" style="display: none; min-height: 22px;">
                                    <div class="col s4 l2 text-right" style="padding-left: 0;">
                                        <img title="Via Mouser.com" style="width: 16px;" src="{% static 'bom/img/mouser.png' %}">&nbsp;Datasheets
                                    </div>
                                    <div class="col s8 l10"><a id="mouser-data-sheet" target="_blank">View datasheet</a></div>
                                </div>
                            </div>
                        </li>
                        <li class="collection-header">
                            <h5><h5 class="title">Manufacturer & Sourcing</h5></h5>
                        </li>
                        <li class="collection-item">
                            <div class="row">
                                <div class="col s4 l2 text-right" style="padding-left: 0px;">Primary Manufacturer Part:</div>
                                <div class="col s8 l10">{{ part.primary_manufacturer_part.manufacturer.name }} - {{ part.primary_manufacturer_part.manufacturer_part_number }}
                                    {% if profile.role == 'A' %}
                                        <a href="{% url 'bom:part-edit' part_id=part.id %}">&nbsp;[change]</a>
                                    {% endif %}
                                </div>
                            </div>
                            <div class="row">
                                <div class="col s4 l2 text-right" style="padding-left: 0px;">Est. Cost:</div>
                                <div id="specs-unit-cost" class="col s8 l10"><span id="mouser-est-cost"></span><span>${{ indented_bom.unit_cost|floatformat:4 }}</span></div>
                            </div>
                            <div class="row">
                                <div class="col s4 l2 text-right" style="padding-left: 0px;">Subparts without costs:</div>
                                <div class="col s8 l10"><span id="mouser-missing-item-costs"></span><span>{{ indented_bom.missing_item_costs }}</span></div>
                            </div>
                            <div class="row">
                                <div class="col s4 l2 text-right" style="padding-left: 0px;">Est. Total NRE:</div>
                                <div class="col s8 l10"><span id="mouser-est-nre"></span><span>${{ indented_bom.nre|floatformat:2 }}</span></div>
                            </div>
                            <div class="row">
                                <div class="col s4 l2 text-right" style="padding-left: 0px;">Est. Cost per {{ qty }} Unit Order (Including MOQs):</div>
                                <div class="col s8 l10"><span id="mouser-est-cost-per-order"></span><span>${{ indented_bom.out_of_pocket_cost|floatformat:2 }}</span></div>
                            </div>
                            <div class="row" id="mouser-stock-wrapper" style="display: none;">
                                <div class="col s4 l2 text-right" style="padding-left: 0px;">Mouser stock:</div>
                                <div class="col s8 l10"><span id="mouser-stock"></span></div>
                            </div>
                        </li>
                    </ul>
                </div>

                <div id="bom" class="col s12">
                    <div id="bom-indented">
                        <div class="text-center" style="padding-top: 8px;">
                            <span>Indented</span> | <a onclick="showFlatBOM()" href="#">Flat</a>
                        </div>
                        {% include 'bom/bom-indented.html' with order_by=order_by bom_items=indented_bom.parts part=part part_revision=part_revision profile=profile %}
                    </div>
                    <div id="bom-flat" style="display: none;">
                        <div class="text-center" style="padding-top: 8px;">
                            <a onclick="showIndentedBOM()" href="#">Indented</a> | <span>Flat</span>
                        </div>
                        {% include 'bom/bom-flat.html' with order_by=order_by bom_items=flat_bom.parts part=part part_revision=part_revision profile=profile %}
                    </div>
                </div>

                <div id="used" class="col s12">
                    <br>
                    <div class="responsive-table-wrapper">
                        <ul class="collapsible" data-collapsible="expandable" style="overflow: scroll;">
                            <li class="active">
                                <div class="collapsible-header"><i class="material-icons">my_location</i>Where this revision is used</div>
                                <div class="collapsible-body">
                                    <table class="highlight tight">
                                        <thead>
                                        <tr>
                                            <th>Part Number</th>
                                            <th>Synopsis</th>
                                            <th>Rev</th>
                                            <th>Manufacturer</th>
                                            <th>MPN</th>
                                        </tr>
                                        </thead>

                                        <tbody>
                                        {% for used_part in where_used %}
                                            <tr>
                                                <td>
                                                    <a href="{% url 'bom:part-info-history' part_id=used_part.part.id part_revision_id=used_part.id %}">{{ used_part.part.full_part_number }}</a>
                                                </td>
                                                <td>{{ used_part.synopsis }}</td>
                                                <td>{{ used_part.revision }}</td>
                                                <td>{{ used_part.part.primary_manufacturer_part.manufacturer.name }}</td>
                                                <td>{{ used_part.part.primary_manufacturer_part.manufacturer_part_number }}</td>
                                            </tr>
                                        {% empty %}
                                            <tr>
                                                <td colspan="99" style="text-align: left; height: 20vh;"><i>This part is not currently
                                                    used in any of your other parts. To add a part to a subassembly or assembly, go to the
                                                    parent part's Bill of Materials, and click "Manage", then "Edit".</i></td>
                                            </tr>
                                        {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            </li>
                            <li>
                                <div class="collapsible-header"><i class="material-icons">location_searching</i>All part usages</div>
                                <div class="collapsible-body">
                                    <table class="highlight tight">
                                        <thead>
                                        <tr>
                                            <th>Part Number</th>
                                            <th>Synopsis</th>
                                            <th>Rev</th>
                                            <th>Manufacturer</th>
                                            <th>MPN</th>
                                        </tr>
                                        </thead>

                                        <tbody>
                                        {% for used_part in where_used_part %}
                                            <tr>
                                                <td>
                                                    <a href="{% url 'bom:part-info-history' part_id=used_part.part.id part_revision_id=used_part.id %}">{{ used_part.part.full_part_number }}</a>
                                                </td>
                                                <td>{{ used_part.synopsis }}</td>
                                                <td>{{ used_part.revision }}</td>
                                                <td>{{ used_part.part.primary_manufacturer_part.manufacturer.name }}</td>
                                                <td>{{ used_part.part.primary_manufacturer_part.manufacturer_part_number }}</td>
                                            </tr>
                                        {% empty %}
                                            <tr>
                                                <td colspan="99" style="text-align: center; height: 20vh;"><i>This part is not currently
                                                    used in any of your other parts.
                                                    {% if profile.role == 'A' %}
                                                        To add a part to a subassembly or assembly, go to the
                                                        parent part's Bill of Materials, and click "Manage", then "Edit".
                                                    {% endif %}
                                                </i></td>
                                            </tr>
                                        {% endfor %}
                                        </tbody>
                                    </table>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>

                <div id="sourcing" class="col s12">
                    <div class="responsive-table-wrapper">
                        <table id="manufacturer-parts" class="highlight tight treetable">
                            <thead>
                            <tr>
                                <th>MPN</th>
                                <th>Manufacturer</th>
                                <th>Seller</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 part.manufacturer_parts %}
                                <tr id="sourcing-mp-{{ manufacturer_part.id }}" data-tt-id="{{ manufacturer_part.id }}">
                                    <td>{{ manufacturer_part.manufacturer_part_number }}</td>
                                    <td>{{ manufacturer_part.manufacturer }}</td>
                                    <td id="sourcing-mp-{{ manufacturer_part.id }}-name">{{ manufacturer_part.optimal_seller.seller.name }}</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>{{ seller_part.seller.name }}</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>This part has no manufacturer parts.</i></td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    {% if profile.role == 'A' %}
                        <div class="row" style="padding-top: 16px;">
                            <div class="col s12 center-align">
                                <a class="waves-effect waves-green grey lighten-4 btn-flat"
                                   href="{% url 'bom:part-add-manufacturer-part' part_id=part.id %}" style="margin: 10px;">Add Manufacturer Part</a>
                            </div>
                        </div>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
{% endblock %}
{% block bom-script %}
    <!-- Materialize initializer -->
    <script>
        $(document).ready(function () {
            $('.collapsible').collapsible({
                accordion: false
            });
        });
        var elem = document.querySelector('.collapsible.expandable');
        var instance = M.Collapsible.init(elem, {
            accordion: false
        });
    </script>

    <!-- Handle if there's an anchor, select tab -->
    <script type='text/javascript'>
        var tabsElem = document.querySelector('.tabs');

        {% if tab_anchor %}
            $('#{{ tab_anchor }}-tab').addClass('active');
        {% endif %}

        var tabs = M.Tabs.init(tabsElem);

        // For dropdown menu
        $(document).ready(function () {
            $('.dropdown-trigger').dropdown({
                    inDuration: 300,
                    outDuration: 225,
                    constrainWidth: false, // Does not change width of dropdown to that of the activator
                    hover: false, // Activate on hover
                    gutter: 0, // Spacing from edge
                    alignment: 'left', // Displays dropdown with edge aligned to the left of button
                    stopPropagation: false, // Stops event propagation
                    coverTrigger: false
                }
            );

            {% if not tab_anchor %}
                if (window.localStorage['part-info-last-anchor']) {
                    {#tabs.select(window.localStorage['part-info-last-anchor']);#}
                }
            {% endif %}
        });
    </script>

    <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>

    <!-- For revision selector logic -->
    <script>
        var selectRevisionSelectedIndex = 1;
        $(document).ready(function () {
            selectRevisionSelectedIndex = $("#select-revision")[0].selectedIndex;
        });

        $("#select-revision").on('change', function () {
            var url = $(this)[0].value;
            var selectedIndex = $(this)[0].selectedIndex;
            if (selectedIndex === 0) {
                var value = "{% if revision == part.latest %}{% url 'bom:part-info' part_id=part.id %}{% else %}{% url 'bom:part-info-history' part_id=part.id part_revision_id=part_revision.id %}{% endif %}";
                $("#select-revision")[0].selectedIndex = selectRevisionSelectedIndex;
                $("#select-revision").formSelect();
            }
            window.location.href = url;
        });
    </script>

    <!-- Revision timestamp to local time -->
    <script>
        $(document).ready(function () {
            let revision_configuration_date = new Date("{{ part_revision.timestamp.isoformat }}")
            $("#specs-revision-timestamp").text(revision_configuration_date.toLocaleString());
        })
    </script>

    <!-- Confirmation popups?  -->
    <script>
        function deletePartRevision() {
            {% if part_revision is not None %}
                let url = "{% url 'bom:part-revision-delete' part_id=part.id part_revision_id=part_revision.id %}";
                if (confirm("Are you sure you want to delete this revision?\n\nIt will be deleted permanently.")) {
                    window.location.href = url;
                }
            {% else %}
                confirm("No part revisions to delete!");
            {% endif %}
        }

        function revertPartRevision() {
            {% if part_revision is not None %}
                let url = "{% url 'bom:part-revision-revert' part_id=part.id part_revision_id=part_revision.id %}";
                if (confirm("Are you sure you want to revert this revision?\n\n")) {
                    window.location.href = url;
                }
            {% else %}
                confirm("No part revisions to revert!");
            {% endif %}
        }
    </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'];
                            updateSpecs(specsUnitCost, specsEstCostPerOrder, specsMissingParts, dataSheet, mouserStock);
                            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 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>${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}-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) {
            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");
            updateSpecElement(mouserEstCost, unitCost, `$${unitCost}`);
            updateSpecElement(mouserEstCostPerOrder, estCostPerOrder, `$${estCostPerOrder}`);
            updateSpecElement(mouserMissingCosts, specsMissingParts, `${specsMissingParts}`);
            updateSpecElement(mouserStockElement, mouserStock, `${mouserStock}`, mouserStockWrapperElement, false);

            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';
                    const sourcingInfo = bomParts[partRevId]['api_info'] !== 'None';
                    const unitCostId = `${baseUnitCostId}${partRevId}`;
                    const unitCostElement = $(unitCostId);
                    const sellerNameId = `${baseSellerNameId}${partRevId}`;
                    const sellerNameElement = $(sellerNameId);
                    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(`${sellerName}`);
                }
            }
        }
    </script>
    <script>
        function showFlatBOM() {
            $('#bom-indented').hide();
            $('#bom-flat').show();
        }

        function showIndentedBOM() {
            $('#bom-flat').hide();
            $('#bom-indented').show();
        }
    </script>
{% endblock bom-script %}