<script setup lang="ts">
import apiBizTransaction from '@/api/modules/bizTransaction'
import apiAssetConsumable from '@/api/modules/assetConsumable'
import DetailForm from './components/DetailForm/index.vue'

defineOptions({ name: 'BizTransactionList' })

const { pagination, getParams, onSizeChange, onCurrentChange } = usePagination()

const formModeProps = ref({ consumable_id: undefined as number | undefined, consumable_name: '' })

const selectedConsumableId = ref<number | undefined>()
const selectedConsumableName = ref('')
const consumableOptions = ref<{ value: number; label: string }[]>([])

const searchDefault = { keyword: '', action_type: undefined as string | undefined }
const search = ref({ ...searchDefault })
function searchReset() { Object.assign(search.value, searchDefault); getDataList() }

const loading = ref(false)
const dataList = ref<any[]>([])

const actionTypeMap: Record<string, string> = { STOCK_IN: '入库', STOCK_OUT: '出库', ADJUST: '调整' }

const columns = [
  { title: '变动类型', dataIndex: 'action_type', key: 'action_type', width: 80, align: 'center' as const },
  { title: '变动数量', dataIndex: 'quantity', key: 'quantity', width: 90 },
  { title: '结存', dataIndex: 'remaining_quantity', key: 'remaining_quantity', width: 80 },
  { title: '操作人', dataIndex: 'operator_name', key: 'operator_name', width: 120, ellipsis: true },
  { title: '备注', dataIndex: 'note', key: 'note', ellipsis: true },
  { title: '时间', dataIndex: 'create_time', key: 'create_time', width: 170 },
]

onMounted(() => {
  apiAssetConsumable.page({ size: 999 }).then((res: any) => {
    consumableOptions.value = (res.data.list || []).map((i: any) => ({ value: i.id, label: `${i.name}(${i.item_no || i.id})` }))
  })
})

function onSelectConsumable(id: number, name: string) {
  selectedConsumableId.value = id
  selectedConsumableName.value = name
  getDataList()
}

function getDataList() {
  if (!selectedConsumableId.value) return
  loading.value = true
  apiBizTransaction.page({ consumable_id: selectedConsumableId.value, ...getParams(), ...search.value }).then((res: any) => {
    loading.value = false; dataList.value = res.data.list; pagination.value.total = res.data.total
  }).catch(() => { loading.value = false })
}

function sizeChange(size: number) { onSizeChange(size).then(() => getDataList()) }
function currentChange(page = 1) { onCurrentChange(page).then(() => getDataList()) }

const formRef = ref<InstanceType<typeof DetailForm>>()
const { open: openDrawer, update: updateDrawer } = useFaDrawer().create({
  destroyOnClose: true, closeOnClickOverlay: false, closeOnPressEscape: false,
  beforeClose(action, done) {
    if (action === 'confirm') { formRef.value?.submit().then(() => { getDataList(); done() }) } else { done() }
  },
  content: () => h(DetailForm, { ref: formRef, ...formModeProps.value }),
})

function onInOut() {
  if (!selectedConsumableId.value) { faToast.warning('请先选择耗材'); return }
  formModeProps.value = { consumable_id: selectedConsumableId.value, consumable_name: selectedConsumableName.value }
  updateDrawer({ title: '出入库操作' })
  openDrawer()
}
</script>

<template>
  <div class="flex flex-col size-full">
    <FaPageHeader title="出入库记录" class="mb-0" />
    <FaPageMain class="flex-1 flex flex-col overflow-auto">
      <div class="mb-4">
        <FaLabel label="选择耗材">
          <ASelect v-model:value="selectedConsumableId" placeholder="请先选择耗材" show-search allow-clear class="w-80" :filter-option="(input: string, option: any) => option.label?.toLowerCase().includes(input.toLowerCase())" :options="consumableOptions" @change="(val: number, option: any) => { if (val) onSelectConsumable(val, option.label) }" />
        </FaLabel>
      </div>
      <FaSearchBar :show-toggle="false">
        <template #default="{ fold, toggle }">
          <div class="gap-x-8 gap-y-2 grid grid-cols-[repeat(auto-fit,minmax(300px,1fr))]">
            <FaLabel label="关键词">
              <AInput v-model:value="search.keyword" placeholder="备注" allow-clear />
            </FaLabel>
            <FaLabel label="变动类型">
              <ASelect v-model:value="search.action_type" placeholder="全部" allow-clear :options="[
                { value: 'STOCK_IN', label: '入库' }, { value: 'STOCK_OUT', label: '出库' }, { value: 'ADJUST', label: '调整' },
              ]" />
            </FaLabel>
            <div class="flex gap-2 col-end--1 justify-end">
              <FaButton variant="outline" @click="searchReset()">重置</FaButton>
              <FaButton type="primary" @click="currentChange()"><FaIcon name="i-ri:search-line" />筛选</FaButton>
              <FaButton variant="ghost" @click="toggle">{{ fold ? '展开' : '收起' }}<FaIcon :name="fold ? 'i-ep:caret-bottom' : 'i-ep:caret-top'" /></FaButton>
              <FaButton @click="onInOut"><FaIcon name="i-ri:add-line" />出入库</FaButton>
            </div>
          </div>
        </template>
      </FaSearchBar>
      <div v-if="selectedConsumableId" class="text-sm text-gray-500 my-4">当前耗材：{{ selectedConsumableName }}</div>
      <ATable :loading="loading" :columns="columns" :data-source="dataList" :pagination="false" size="middle" row-key="id">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'action_type'">
            <ATag :color="record.action_type === 'STOCK_IN' ? 'green' : record.action_type === 'STOCK_OUT' ? 'red' : 'default'">{{ actionTypeMap[record.action_type] || record.action_type }}</ATag>
          </template>
        </template>
      </ATable>
      <div class="flex-center mt-4 rounded-lg border bg-background px-4 py-3">
        <FaPagination :page="pagination.page" :size="pagination.size" :total="pagination.total" @page-change="currentChange" @size-change="sizeChange" />
      </div>
    </FaPageMain>
  </div>
</template>
