<script setup lang="ts">
import { computed, ref } from 'vue'
import type { KbxLookupItem } from '@kbx/contracts'
import { KbxDataGrid, KbxFastEntryPage, KbxLookupDialog, useKbxPageShortcuts } from '@kbx/ui'
import { itemPriceColumns, itemPriceScreen, type ItemPriceRow } from './item-price.definition'
import { useItemPriceFastEntry } from './useItemPriceFastEntry'
import { useKbxWorkspaceBinding } from '../../../shell/useKbxWorkspaceBinding'

const vm=useItemPriceFastEntry()
useKbxWorkspaceBinding(vm.dirty, async()=>await vm.save())
const lookupOpen=ref(false); const activeRow=ref<ItemPriceRow|null>(null)
function openLookup(event:{row:ItemPriceRow;entity:string}){ if(event.entity!=='item')return;activeRow.value=event.row;lookupOpen.value=true }
function selectItem(item:KbxLookupItem<string>){ if(activeRow.value)vm.applyItemLookup(activeRow.value,item) }
const pageContext=computed(()=>({label:'품목 단가 입력',hint:'저장 전 오류를 모두 해소한 뒤 F8로 일괄 저장합니다.',metrics:[{key:'rows',label:'입력',value:vm.enteredCount.value},{key:'errors',label:'오류',value:vm.errors.value.length,tone:vm.errors.value.length?'danger' as const:'default' as const,emphasis:vm.errors.value.length>0}]}))
const summary=computed(()=>[
  {key:'rows',label:'입력',value:`${vm.enteredCount.value.toLocaleString('ko-KR')}건`},
  {key:'errors',label:'오류',value:`${vm.errors.value.length.toLocaleString('ko-KR')}건`},
  ...(vm.lastResult.value?[{key:'saved',label:'최근 저장',value:`${vm.lastResult.value.saved.toLocaleString('ko-KR')}건`,emphasis:true}]:[]),
])
useKbxPageShortcuts([{key:'F8',execute:()=>vm.save()}])
async function command(id:string){ if(id==='save')await vm.save(); if(id==='new')vm.clear() }
</script>

<template>
  <KbxFastEntryPage :screen="itemPriceScreen" :selection-count="0" :dirty="vm.dirty.value" :context="pageContext" :errors="vm.errors.value" :summary-items="summary" :problem="vm.problem.value" grid-title="품목 단가 입력" grid-description="품목·단가를 연속 입력하고 오류 셀을 해소한 뒤 F8로 저장합니다." :row-count="vm.enteredCount.value" row-count-unit="건" breadcrumb="ERP > 기준정보" @command="command" @retry-problem="vm.retryProblem" @dismiss-problem="vm.dismissProblem">
    <template #guide>
      <span><kbd>Enter</kbd> 다음 셀</span><span><kbd>F2</kbd> 품목 조회</span><span><kbd>Ctrl+V</kbd> Excel 붙여넣기</span><span>행 선택 후 아래 채우기/복제</span>
    </template>
    <template #notice>
      <div v-if="vm.lastResult.value" class="price-save-result" role="status">저장 {{vm.lastResult.value.saved.toLocaleString('ko-KR')}}건 · 신규 {{vm.lastResult.value.created.toLocaleString('ko-KR')}} · 수정 {{vm.lastResult.value.updated.toLocaleString('ko-KR')}}</div>
    </template>
    <template #grid-actions><span class="grid-action-status">오류 {{vm.errors.value.length.toLocaleString('ko-KR')}}건</span></template>
    <template #content>
      <KbxDataGrid
        :rows="vm.rows.value" :columns="itemPriceColumns" row-key="clientId" selection="multiple"
        :errors="vm.errors.value" editable clipboard
        :editing-policy="{allowRowAdd:true,allowRowDuplicate:true,fillDown:true,paste:true,errorNavigation:true}"
        @row-add-requested="vm.addRow" @row-duplicate-requested="vm.duplicateRows" @cell-changed="vm.onCellChanged" @lookup-requested="openLookup"
      />
    </template>
  </KbxFastEntryPage>
  <KbxLookupDialog v-model:visible="lookupOpen" entity="item" title="품목" @select="selectItem" />
</template>

<style scoped>
.grid-action-status{font-size:var(--kbx-font-xs);color:var(--kbx-color-text-muted);white-space:nowrap}.price-save-result{min-height:var(--kbx-control-sm);display:flex;align-items:center;padding:0 var(--kbx-space-2);border:var(--kbx-border-width) solid var(--kbx-color-success-border);background:var(--kbx-color-success-surface);color:var(--kbx-color-success-text);font-size:var(--kbx-font-sm)}
</style>
