<global-bar></global-bar>

@if (items$ | async) {}
@if (requiredData$ | async) {}
@if (gridLoading$ | async) {}
@if (refreshCounterpartyForPipeline$ | async) {}
@if (refreshContractForPipeline$ | async) {}
@if (refreshMeterForPipeline$ | async) {}
@if (refreshHistory$ | async) {}
@if (historyItems$ | async) {}
@if (pipelineChanged$ | async) {}
@if (pipeContractChanged$ | async) {}
@if (productionPeriodChanged$ | async) {}
@if (actualTypeChanged$ | async) {}
@if (saveResult$ | async) {}
@if (toggleTneMeterResult$ | async) {}
@if (meterChanged$ | async) {}
@if (counterpartyChanged$ | async) {}
@if (exportAction$ | async) {}
@if (saveGridSettingsAction$ | async) {}
@if (isActualizeNomsActive$ | async) {}
@if (gridSettings$ | async) {}
@if (screenPathsResult$ | async) {}
@if (setTneMeterResult$ | async) {}
@if (refreshContextMenuFilter$ | async) {}

<div class="flex flex-col h-full overflow-hidden">
  <ng-template #actualizeToNomsTemplate let-anchor>
    Actualize to Noms sets any empty Actual volume to the corresponding Nominated volume, this is enabled when ALL of the following conditions are met:
    <br>
    <b> For Buy Deals:</b>
    <ol class="list-disc pl-6">
      <li>A specific counterparty is selected
      <li>Either a pipeline or meter are selected</li>
      <li>Items are present</li>
    </ol>
    <b> For Sell or Transfer Deals:</b>
    <ol class="list-disc pl-6">
      <li>A specific pipeline is selected
      <li>Either a pipe contract or a meter is selected
      <li>Items are present</li>
    </ol>
  </ng-template>
  <fast-header>
    <form class="flex flex-col grow items-start justify-start basis-3/10 mt-px mb-0.5 w-full" id="header" [formGroup]="userSelectionsForm">
      <div class="flex flex-row w-full">
        <div class="flex flex-row grow-0 items-center justify-start mt-px mr-0 mb-0.5 ml-2.5">
          <h1 class="mr-1 text-xl whitespace-nowrap items-center text-base-black-250 dark:text-base-white-1000">{{title$ | async}}</h1>
        </div>
        <div class="flex flex-row grow-0 items-center justify-start mt-px mr-0 mb-0.5 ml-2.5">
          <fast-label class="whitespace-nowrap">Production Period&nbsp;</fast-label>
          <fast-datepicker type="date-month" class="w-38" formControlName="productionPeriod" bottomView="year" [min]="util.minDate"
            [max]="util.maxDate"></fast-datepicker>
        </div>
        <div class="flex flex-row grow-0 items-center justify-start mt-px mr-0 mb-0.5 ml-2.5">
          <fast-label class="whitespace-nowrap">Type&nbsp;</fast-label>
          <fast-combobox class="min-w-37.5 w-37.5" formControlName="actualTypeId" [data]="ActualTypes$ | async" [textField]="'actualTypeName'"
            [valueField]="'actualTypeId'" [valuePrimitive]="true" (filterChange)="filterActualTypes$.next($event)"></fast-combobox>
        </div>
        <div class="flex flex-row grow-0 items-center justify-start mt-px mr-0 mb-0.5 ml-2.5" fast-tip [tipContent]="actualizeToNomsTemplate"
          tipPosition="bottom">
          <fast-button class="w-40" [disabled]="(isActualizeNomsActive$ | async) === false" (click)="onActualizeNomsClicked()"><fast-svg
              icon="chevronRight" />Actualize to Noms</fast-button>
        </div>
        <div class="flex flex-row grow-0 items-center justify-start mt-px mr-0 mb-0.5 ml-2.5">
          @if ((requiredData$ | async)?.hasModifyPermission) {
          <fast-button (click)="openSaveWindow()"><fast-svg icon="save" />Save</fast-button>
          }
        </div>
        <div class="flex flex-row grow items-center justify-center mt-px mx-2.5 mb-0.5"></div>
        <div class="flex flex-row grow-0 items-center justify-end mt-px mr-2.5 mb-0.5 ml-0">
          <fast-button type="export" [exporting]="exporting$ |  async" (click)="export()" tabindex="-1">
            <fast-svg icon="excelFile" /> Export
          </fast-button>
        </div>
      </div>
      <div class="flex flex-row min-w-175 w-full max-w-300">
        <div class="flex flex-col grow items-stretch justify-center mt-0.5 mx-2.5 mb-2">
          <fast-label>Counterparty</fast-label>
          <fast-combobox class="min-w-35 max-w-70" formControlName="counterpartyId" [data]="Counterparties$ | async" [textField]="'counterpartyName'"
            [valueField]="'counterpartyId'" [valuePrimitive]="true" (filterChange)="filterCounterparties$.next($event)" [dropdownWidth]="400"
            [listHeight]="400" />
        </div>
        <div class="flex flex-col grow items-stretch justify-center mt-0.5 mx-2.5 mb-2">
          <fast-label>Pipeline</fast-label>
          <fast-combobox class="min-w-35 max-w-70" formControlName="pipelineId" [data]="Pipelines$ | async" [textField]="'pipelineName'"
            [valueField]="'pipelineId'" [valuePrimitive]="true" (filterChange)="filterPipelines$.next($event)" [dropdownWidth]="400" [listHeight]="400" />
        </div>
        <div class="flex flex-col grow items-stretch justify-center mt-0.5 mx-2.5 mb-2">
          <fast-label>P/L Contract</fast-label>
          <fast-combobox class="min-w-35 max-w-70" formControlName="pipeContractId" [data]="PipeContracts$ | async" [textField]="'pipeContractName'"
            [valueField]="'pipeContractId'" [valuePrimitive]="true" (filterChange)="filterPipeContracts$.next($event)" [dropdownWidth]="350"
            [listHeight]="400" />
        </div>
        <div class="flex flex-col grow items-stretch justify-center mt-0.5 mx-2.5 mb-2">
          <fast-label>Meter</fast-label>
          <fast-combobox class="min-w-35 max-w-70" formControlName="meterId" [data]="Meters$ | async" [textField]="'meterName'" [valueField]="'meterId'"
            [valuePrimitive]="true" (filterChange)="filterMeters$.next($event)" [dropdownWidth]="400" [listHeight]="400" />
        </div>
      </div>
    </form>
  </fast-header>

  <ng-template #tooltipHistoryTemplate let-anchor>
    @if (historyLoading$ | async) {
    <span>Loading...</span>
    }
    @if ((historyLoading$ | async) === false) {
    <div>
      @if ((historyItems$ | async)?.length && this.userSelectionsForm.controls['actualTypeId'].value === 1) {
      <div>
        @for (item of (historyItems$ | async); track item) {
        <div>
          Changed : <span>{{ item.saveDate }}</span> <br />
          Actual Volume : <span>{{ item.actualVolume }}</span> <br />
          Price : <span>{{ item.price }}</span> <br />
          Price Adj. : <span>{{ item.priceAdj }}</span> <br />
          Fees : <span>{{ item.actualFee }}</span> <br />
          Adj. : <span>{{ item.adjustment }}</span> <br />
          T&E : <span>{{ item.transportRate }}</span>
        </div>
        }
      </div>
      }
      @if ((historyItems$ | async)?.length && this.userSelectionsForm.controls['actualTypeId'].value === -1) {
      <div>
        @for (item of (historyItems$ | async); track item) {
        <div>
          Changed : <span>{{ item.saveDate }}</span> <br />
          Actual Volume : <span>{{ item.actualVolume }}</span> <br />
          Price : <span>{{ item.price }}</span> <br />
          Price Adj. : <span>{{ item.priceAdj }}</span> <br />
          Fees : <span>{{ item.actualFee }}</span> <br />
          Adj. : <span>{{ item.adjustment }}</span> <br />
        </div>
        }
      </div>
      }
      @if ((historyItems$ | async)?.length && this.userSelectionsForm.controls['actualTypeId'].value === 0) {
      <div>
        @for (item of (historyItems$ | async); track item) {
        <div>
          Changed : <span>{{ item.saveDate }}</span> <br />
          Actual Volume : <span>{{ item.actualVolume }}</span>
        </div>
        }
      </div>
      }
      @if ((!(historyItems$ | async)?.length)) {
      <div [ngTemplateOutlet]="noHistoryTemplate"></div>
      }
      <ng-template #noHistoryTemplate>
        <span>No history available</span>
      </ng-template>
    </div>
    }
  </ng-template>

  <ng-template #tooltipGridTemplate let-anchor>
    @for (text of util.getTableCellTooltipText(anchor.nativeElement); track text) {
    <div>
      <div>{{text}}</div>
    </div>
    }
  </ng-template>

  <ng-template #tooltipCalcTextTemplate let-anchor>
    @for (text of getTitleSplit(anchor); track text) {
    <div>
      {{text}}
    </div>
    }
  </ng-template>

  <ng-template #ticketNumTemplate let-dataItem="dataItem">
    <div class="underline cursor-pointer" (click)="openSupplyDealOrTransfer(dataItem, dataItem.ticketNum)">{{dataItem.ticketNum}}</div>
  </ng-template>
  <ng-template #deliveryDealNumTemplate let-dataItem="dataItem">
    <div class="underline cursor-pointer" (click)="openSupplyDealOrTransfer(dataItem, dataItem.deliveryDealNum)">{{dataItem.deliveryDealNum}}</div>
  </ng-template>
  <ng-template #receiptDealNumTemplate let-dataItem="dataItem">
    <div class="underline cursor-pointer" (click)="openSupplyDealOrTransfer(dataItem, dataItem.receiptDealNum)">{{dataItem.receiptDealNum}}</div>
  </ng-template>
  <ng-template #deliveryTooltip let-dataItem="dataItem">
    <div>
      For Delivery Deal:
      {{dataItem.counterpartyShort}}
      Delivery Volume: {{dataItem.nomVolume | number:'1.0-0'}}
    </div>
  </ng-template>
  <ng-template #receiptTooltip let-dataItem="dataItem">
    <div>
      For Receipt Deal:
      {{dataItem.counterpartyShort}}
      Receipt Volume: {{dataItem.nomVolume | number:'1.0-0'}}
    </div>
  </ng-template>

  <div #gridElement class="flex flex-row grow overflow-auto">
    <fast-grid #grid [scrollable]="'virtual'" [pageSize]="state.take" (cellClick)="onCellClick($event)" (keyDown)="onKeyDown($event)"
      [loading]="gridLoading$ | async" [gridBinding]="gridItems()" [resizable]="true" [navigable]="false" [skip]="state.skip" [sort]="state.sort"
      [filter]="state.filter" (GridNavigableSection)="true" [sortable]="{mode: 'multiple'}" [filterable]="'menu, row'"
      (dataStateChange)="onGridStateChange($event)" (cellClose)="onCellClose($event)" [rowClass]="rowCallback" [rowHeight]="33">
      <fast-grid-col type="text" field="counterpartyName" [width]="200" [title]="'Counterparty'">
      </fast-grid-col>
      <fast-grid-col type="text" field="receiptDealNum" [width]="130" [title]="'Rec. Deal #'" [cellTemplate]="receiptDealNumTemplate"
        [hidden]="this.userSelectionsForm.controls['actualTypeId'].value !== 1">
      </fast-grid-col>
      <fast-grid-col type="text" field="deliveryDealNum" [width]="130" [title]="'Del. Deal #'" [cellTemplate]="deliveryDealNumTemplate"
        [hidden]="this.userSelectionsForm.controls['actualTypeId'].value !== -1">
      </fast-grid-col>
      <fast-grid-col type="text" field="ticketNum" [width]="130" [title]="'Deal #'" [cellTemplate]="ticketNumTemplate"
        [hidden]="this.userSelectionsForm.controls['actualTypeId'].value !== 0">
      </fast-grid-col>
      <fast-grid-col type="text" field="pipeName" [width]="110" [title]="'Pipeline'">
      </fast-grid-col>
      <fast-grid-col type="text" [hidden]="this.userSelectionsForm.controls['actualTypeId'].value === 0" field="pointName" [width]="210" [title]="'Point'">
      </fast-grid-col>
      <fast-grid-col type="text" field="receiptDealNum" [width]="130" [title]="'Rec. Deal #'"
        [hidden]="this.userSelectionsForm.controls['actualTypeId'].value !== -1" [cellTemplate]="receiptCellTemplate">
        <ng-template #receiptCellTemplate let-dataItem="dataItem" let-column="column">
          <ng-template #receiptTooltip let-item="item">
            <div>
              {{item.receiptCounterpartyShort}} <br />
              Receipt Volume: {{item.nomVolume | number:'1.0-0'}}
            </div>
          </ng-template>
          <div class="underline cursor-pointer" fast-tip #receiptTooltipDirective="fast-tip" [tipContent]="receiptTooltip" [tipContext]="{item: dataItem}"
            (mouseover)="onDealMouseover($event, receiptTooltipDirective)" (click)="openSupplyDealOrTransfer(dataItem, dataItem.receiptDealNum)">
            {{dataItem.receiptDealNum}}
          </div>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="text" field="receiptMeterName" [width]="210" [title]="'Receipt Meter'"></fast-grid-col>
      <fast-grid-col type="text" field="deliveryMeterName" [width]="210" [title]="'Delivery Meter'"></fast-grid-col>
      <fast-grid-col type="text" field="deliveryDealNum" [width]="130" [title]="'Del. Deal #'"
        [hidden]="this.userSelectionsForm.controls['actualTypeId'].value !== 1" [cellTemplate]="deliveryCellTemplate">
        <ng-template #deliveryCellTemplate let-dataItem="dataItem" let-column="column">
          <ng-template #deliveryTooltip let-item="item">
            <div>
              {{item.deliveryCounterpartyShort}} <br />
              Delivery Volume: {{item.nomVolume | number:'1.0-0'}}
            </div>
          </ng-template>
          <div class="underline cursor-pointer" fast-tip #deliveryTooltipDirective="fast-tip" [tipContent]="deliveryTooltip" [tipContext]="{item: dataItem}"
            (mouseover)="onDealMouseover($event, deliveryTooltipDirective)" (click)="openSupplyDealOrTransfer(dataItem, dataItem.deliveryDealNum)">
            {{dataItem.deliveryDealNum}}
          </div>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="text" [hidden]="this.userSelectionsForm.controls['actualTypeId'].value !== 1" field="tneMeterName" [width]="75"
        [cellTemplate]="tneMeterCellTemplate" class="p-0!" [headerTemplate]="tneMeterHeaderTemplate">
        <ng-template #tneMeterHeaderTemplate let-column>
          T&E<br>Meter
        </ng-template>>
        <ng-template #tneMeterCellTemplate let-dataItem="dataItem">
          <div class="flex items-center justify-center w-full h-full cursor-pointer" [fast-tip]="dataItem.tneMeterName">
            <pipe-icon class="pointer-events-none" [pipeCount]="dataItem.transferCount" [highlightLeg]="dataItem.tneMeterDeductLegNum" [size]="34" />
          </div>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="text" field="pipeContractName" [width]="115" [title]="'P/L Contract'"></fast-grid-col>
      <fast-grid-col type="num-d2" field="nomVolume" [width]="120" [title]="'Nom Vol'" [cellTemplate]="nomVolumeCellTemplate"
        [headerTemplate]="nomVolumeHeaderTemplate">
        <ng-template #nomVolumeHeaderTemplate let-column>
          <p>
            {{ column.title }}
            <br>
            <b> {{ nomVolTotal() | number:'1.2-2' }} </b>
          </p>
        </ng-template>
        <ng-template #nomVolumeCellTemplate let-dataItem="dataItem">
          @if (dataItem.lastTransferId) {
          <div [fast-tip]="dataItem.lastTransferNum" class="underline cursor-pointer" (click)="openLastTransfer(dataItem)" [tipPosition]="'left'">
            {{dataItem.nomVolume | number:'1.2-2'}}</div>
          } @else {
          <div>{{dataItem.nomVolume | number:'1.2-2'}}</div>
          }
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="num-d2-edit" editor="numeric" field="actualVolume" [width]="120" [title]="'Actual Vol'" [class]="{'editedVolumeCell': true}"
        editFormControlName="actualVolume" [headerTemplate]="actualVolumeHeaderTemplate">
        <ng-template #actualVolumeHeaderTemplate let-column="column">
          <p>
            {{ column.title }}
            <br>
            <b> {{ actualVolTotal() | number:'1.2-2' }} </b>
          </p>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="num-c5-edit" editor="numeric" [hidden]="this.userSelectionsForm.controls['actualTypeId'].value === 0" field="price" [width]="100"
        [title]="'Price'" [class]="{'editedPriceCell': true}" editFormControlName="price" [cellTemplate]="priceCellTemplate">
        <ng-template #priceCellTemplate let-dataItem="dataItem">
          <div fast-tip tipPosition="left" [tipContext]="dataItem.priceCalcText" [tipContent]="tooltipCalcTextTemplate">
            ${{ dataItem.price | number: '1.5-5' }}
          </div>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="num-c5-edit" editor="numeric" [hidden]="this.userSelectionsForm.controls['actualTypeId'].value === 0" field="priceAdj" [width]="100"
        [title]="'Price Adj.'" [class]="{'editedPriceAdjCell': true}" editFormControlName="priceAdj" [cellTemplate]="priceAdjCellTemplate">
        <ng-template #priceAdjCellTemplate let-dataItem="dataItem">
          <div fast-tip tipPosition="left" [tipContext]="dataItem.priceAdjCalcText" [tipContent]="tooltipCalcTextTemplate">
            ${{ dataItem.priceAdj | number: '1.5-5' }}
          </div>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="num-c2-edit" editor="numeric" [hidden]="this.userSelectionsForm.controls['actualTypeId'].value === 0" field="actualFee" [width]="100"
        [title]="'Fees.'" [class]="{'editedActualFeeCell': true}" editFormControlName="actualFee">
      </fast-grid-col>
      <fast-grid-col type="num-c2-edit" editor="numeric" [hidden]="this.userSelectionsForm.controls['actualTypeId'].value === 0" field="adjustment"
        [width]="100" [title]="'Adj.'" [class]="{'editedAdjustmentCell': true}" editFormControlName="adjustment">
      </fast-grid-col>
      <fast-grid-col type="num-c5-edit" editor="numeric" [hidden]="this.userSelectionsForm.controls['actualTypeId'].value === -1" field="transportRate"
        [width]="100" [title]="'T&E'" [class]="{'editedTransportRateCell': true}" editFormControlName="transportRate" [cellTemplate]="TandECellTemplate">
        <ng-template #TandECellTemplate let-dataItem="dataItem">
          <div fast-tip tipPosition="left" [tipContext]="dataItem.transportCalcText" [tipContent]="tooltipCalcTextTemplate">
            ${{ dataItem.transportRate | number: '1.5-5' }}
          </div>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="num-c5" [hidden]="this.userSelectionsForm.controls['actualTypeId'].value === 0" field="invoicePrice" [width]="120"
        [title]="'Invoice Price'">
      </fast-grid-col>
      <fast-grid-col type="num-c2" [hidden]="this.userSelectionsForm.controls['actualTypeId'].value === 0" field="amount" [width]="150" [title]="'Amount'"
        [headerTemplate]="amountHeaderTemplate">
        <ng-template #amountHeaderTemplate let-column>
          <p>
            {{ column.title }}
            <br>
            <b> {{ amountTotal() | number:'1.2-2'}} </b>
          </p>
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="text" editor="boolean" [hidden]="this.userSelectionsForm.controls['actualTypeId'].value !== 0" field="isLinked" [width]="55"
        [title]="'Link'" [class]="{'editedLinkedCell': true}" [cellTemplate]="linkCellTemplate">
        <ng-template #linkCellTemplate let-dataItem="dataItem">
          {{ dataItem.isLinked ? 'Yes' : 'No' }}
        </ng-template>
      </fast-grid-col>
      <fast-grid-col type="text" [width]="60" field="historyItems" [title]="'History'" [class]="'historyCell'" [cellTemplate]="historyCellTemplate"
        [filterable]="false">
        <ng-template #historyCellTemplate let-dataItem="dataItem" let-column="column">
          <div class="hover:cursor-pointer hover:text-base-yellow-250" fast-tip #historyTooltipDirective="fast-tip" (click)="openHistory(dataItem)"
            [tipContent]="tooltipHistoryTemplate" (mouseover)="onHistoryMouseOver($event, dataItem, historyTooltipDirective)">
            <fast-svg size="15" icon="calendarDate" />
          </div>
        </ng-template>
      </fast-grid-col>
    </fast-grid>
  </div>
  <fast-contextmenu [target]="gridElement" [items]="contextMenuItems" (select)="onContextMenuSelect($event)"
    [filter]="contextMenuFilter$ | async"></fast-contextmenu>
</div>

@if (historyOpened$ | async) {
<fast-overlay />
}
@if (historyOpened$ | async) {
<fast-window title="Item History" (close)="closeHistory()" [height]="250 | winHeight" [width]="1060 | winWidth" [minWidth]="300" [minHeight]="200">
  <div class="flex flex-col grow p-5 overflow-auto">
    <app-actuals-crude-history #history [actualTypeId]="historyItem.actualTypeId" [supplyNomId]="historyItem.supplyNomId"
      [marketNomId]="historyItem.marketNomId" [lastTransferId]="historyItem.lastTransferId" (refreshGridItems)="this.refreshItems$.next(null)"
      (closeClicked)="closeHistory()"></app-actuals-crude-history>
  </div>
  <fast-hr />
  <div class="flex flex-row bottomSection">
    <div class="flex flex-col grow items-stretch justify-center basis-3/10 mt-0.5 mx-2.5 mb-2"></div>
    <div class="flex flex-col grow-0 items-stretch justify-end mt-1 mr-2.5 mb-2 ml-0">
      <fast-button type="primary" (click)="saveHistory()"><fast-svg icon="save" />Save</fast-button>
    </div>
    <div class="flex flex-col grow-0 items-stretch justify-end mt-1 mr-2.5 mb-2 ml-0">
      <fast-button type="basic" [disabled]="historyLoading$ | async" (click)="closeHistory()"><fast-svg icon="cancel" />Cancel</fast-button>
    </div>
  </div>
</fast-window>
}

@if (dateSaveOpened$ | async) {
<fast-overlay />
@if (gridLoading$ | async) {
<fast-spinner></fast-spinner>
}
<fast-window [height]="150" [width]="300" [minWidth]="300" [minHeight]="150" [title]="'Save Date'" (close)="closeSaveWindow()">
  <div class="flex flex-row grow">
    <div class="flex flex-col grow mx-2.5">
      <fast-datepicker [(ngModel)]="gridSaveDate"></fast-datepicker>
    </div>
    <div class="flex flex-col grow mx-2.5">
    </div>
  </div>
  <fast-hr />
  <div class="flex flex-row bottomSection">
    <div class="flex flex-col grow items-stretch justify-center basis-3/10 mt-0.5 mx-2.5 mb-2"></div>
    <div class="flex flex-col grow-0 items-stretch justify-end mt-1 mr-2.5 mb-2 ml-0">
      <fast-button type="primary" (click)="save(util.SaveType.New)"><fast-svg icon="save" />Save</fast-button>
    </div>
    <div class="flex flex-col grow-0 items-stretch justify-end mt-1 mr-2.5 mb-2 ml-0">
      <fast-button type="basic" [disabled]="historyLoading$ | async" (click)="closeSaveWindow()"><fast-svg icon="cancel" />Cancel</fast-button>
    </div>
  </div>
</fast-window>
}

@if (dealsOpened$ | async) {
<fast-frame title="Deals" [src]="dealUrl" [externalParams]="externalParams" (closed)="dealsOpened$.next(false)" />
}

@if (transfersOpened$ | async) {
<fast-frame title="Scheduling" [src]="getSchedulingUrl()" (closed)="transfersOpened$.next(false)" [isCloseVisible]="false" />
}

@if (tneMeterOpened$ | async) {
<fast-frame title="Scheduling" [src]="getTneMeterUrl()" (closed)="closeTneMeter()" [isCloseVisible]="false" />
}