import { defineKbxScreen, type KbxGridColumn, type KbxRecordStatePolicy, type KbxWorkflowDefinition } from '@kbx/ui'
import { kbxStatusCatalog } from '../../../../registry/statusCatalog'

export interface OrderLineForm { clientId:string; itemId:string|null; itemCode:string; itemName:string; availableQty:number|null; orderQty:number; unitPrice:number; amount:number; remark:string }

export const orderWorkflow:KbxWorkflowDefinition={id:'oms.order.lifecycle',version:'2.0.0',states:
  kbxStatusCatalog.orderLifecycle
    .filter(state => ['NEW','DRAFT','CONFIRMED','ALLOCATED','PICKING','CHECKED','SHIPPED'].includes(state.value))
    .map(state => ({...state,terminal:state.value==='SHIPPED'})),
 transitions:[{id:'confirm',from:['DRAFT'],to:'CONFIRMED',label:'주문확정',permission:'oms.order.confirm',confirm:true}]}
export const orderStatePolicies:KbxRecordStatePolicy[]=[
  {status:'NEW',editability:'editable'},
  {status:'DRAFT',editability:'editable'},
  {status:'CONFIRMED',editability:'readonly',message:'확정된 주문은 직접 수정할 수 없습니다.'},
  {status:'ALLOCATED',editability:'readonly'},
  {status:'PICKING',editability:'readonly'},
  {status:'CHECKED',editability:'readonly'},
  {status:'SHIPPED',editability:'readonly'},
]

export const orderRegisterScreen = defineKbxScreen({
  id:'OMS-ORD-002',version:'1.4.0',module:'OMS',type:'transaction', templateCode:'T03',title:'주문등록',helpKey:'OMS-ORD-002',permissions:['oms.order.read','erp.item.read'],
  commands:[
    {id:'new',label:'신규',group:'edit'},
    {id:'save',label:'저장',group:'edit',variant:'primary',shortcut:'F8',permissionByStatus:{NEW:'oms.order.create',DRAFT:'oms.order.write'},allowedStatuses:['NEW','DRAFT'],requiresDirty:true},
    {id:'confirm',label:'주문확정',group:'workflow',permission:'oms.order.confirm',allowedStatuses:['DRAFT'],requiresClean:true,disabledReason:'변경사항을 저장한 뒤 주문을 확정하세요.',confirm:{title:'주문을 확정하시겠습니까?',detail:'확정 후 주문의 일반 입력 필드는 직접 수정할 수 없습니다.',level:'high',confirmLabel:'주문확정'}},
    {id:'copy',label:'주문복사',group:'edit'},
    {id:'excel',label:'엑셀',group:'output'},
  ],telemetry:{enabled:true},
})
export const orderLineColumns:KbxGridColumn<OrderLineForm>[]=[
 {field:'itemCode',header:'품목코드',type:'lookup',width:130,editable:true,pinned:'left',lookup:{entity:'item'}},{field:'itemName',header:'품목명',width:220},{field:'availableQty',header:'가용재고',type:'quantity',width:100},{field:'orderQty',header:'수량',type:'quantity',width:95,editable:true},{field:'unitPrice',header:'단가',type:'money',width:120,editable:true},{field:'amount',header:'금액',type:'money',width:130},{field:'remark',header:'비고',width:220,editable:true},
]
