<script setup lang="ts">
import apiBizAllocation from '@/api/modules/bizAllocation'
import DetailForm from './components/DetailForm/index.vue'

defineOptions({ name: 'BizAllocationList' })

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

const formModeProps = ref({ id: '' as number | string })

const searchDefault = { keyword: '', item_type: undefined as string | undefined, status: 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 itemTypeMap: Record<string, string> = { device: '设备', license: '许可', accessory: '配件' }
const statusMap: Record<string, string> = { reserved: '预约', active: '占用', returned: '已归还' }

const columns = [
  { title: '资源类型', dataIndex: 'item_type', key: 'item_type', width: 80, align: 'center' as const },
  { title: '资源ID', dataIndex: 'item_id', key: 'item_id', width: 80 },
  { title: '归属者', dataIndex: 'assignee_name', key: 'assignee_name', width: 120, ellipsis: true },
  { title: '位置', dataIndex: 'location_name', key: 'location_name', width: 140, ellipsis: true },
  { title: '数量', dataIndex: 'quantity', key: 'quantity', width: 60 },
  { title: '状态', dataIndex: 'status', key: 'status', width: 80, align: 'center' as const },
  { title: '分配时间', dataIndex: 'assign_date', key: 'assign_date', width: 170 },
  { title: '预计归还', dataIndex: 'expected_return_date', key: 'expected_return_date', width: 170 },
  { title: '操作', key: 'action', width: 100, align: 'center' as const },
]

onMounted(() => getDataList())

function getDataList() {
  loading.value = true
  apiBizAllocation.page({ ...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, id: formModeProps.value.id }),
})

function onAssign() { formModeProps.value.id = ''; updateDrawer({ title: '新增分配' }); openDrawer() }
function onDetail(row: any) { formModeProps.value.id = row.id; updateDrawer({ title: '分配详情' }); openDrawer() }

function onReturn(row: any) {
  useFaModal().confirm({
    title: '确认归还', content: `确认将「${row.item_type}-${row.item_id}」归还吗？`,
    onConfirm: () => apiBizAllocation.return(row.id).then(() => { getDataList(); faToast.success('归还成功') }),
  })
}
</script>

<template>
  <div class="flex flex-col size-full">
    <FaPageHeader title="资产分配管理" class="mb-0" />
    <FaPageMain class="flex-1 flex flex-col overflow-auto">
      <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.item_type" placeholder="全部" allow-clear :options="[
                { value: 'device', label: '设备' }, { value: 'license', label: '许可' }, { value: 'accessory', label: '配件' },
              ]" />
            </FaLabel>
            <FaLabel label="状态" v-show="!fold">
              <ASelect v-model:value="search.status" placeholder="全部" allow-clear :options="[
                { value: 'active', label: '占用' }, { value: 'returned', label: '已归还' }, { value: 'reserved', 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="onAssign"><FaIcon name="i-ri:add-line" />新增分配</FaButton>
            </div>
          </div>
        </template>
      </FaSearchBar>
      <ATable :loading="loading" :columns="columns" :data-source="dataList" :pagination="false" size="middle" row-key="id" :scroll="{ x: 1100 }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'item_type'">
            <ATag>{{ itemTypeMap[record.item_type] || record.item_type }}</ATag>
          </template>
          <template v-else-if="column.key === 'status'">
            <ATag :color="record.status === 'active' ? 'blue' : record.status === 'returned' ? 'default' : 'orange'">
              {{ statusMap[record.status] || record.status }}
            </ATag>
          </template>
          <template v-else-if="column.key === 'action'">
            <ASpace :size="4">
              <FaButton variant="outline" size="sm" @click="onDetail(record)">详情</FaButton>
              <FaButton v-if="record.status === 'active'" variant="outline" size="sm" @click="onReturn(record)">归还</FaButton>
            </ASpace>
          </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>
