<script setup lang="ts">
import apiAssetDevice from '@/api/modules/assetDevice'
import apiBaseModel from '@/api/modules/baseModel'
import apiBaseCategory from '@/api/modules/baseCategory'
import apiBaseLocation from '@/api/modules/baseLocation'
import apiBaseSupplier from '@/api/modules/baseSupplier'
import DetailForm from './components/DetailForm/index.vue'

defineOptions({ name: 'AssetDeviceList' })

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

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

const searchDefault = {
  keyword: '', assets_status: undefined as string | undefined,
  category_id: undefined as number | undefined, location_id: undefined as number | undefined,
  model_id: undefined as number | undefined, supplier_id: undefined as number | undefined,
}
const search = ref({ ...searchDefault })
function searchReset() {
  Object.assign(search.value, searchDefault)
  getDataList()
}

const loading = ref(false)
const dataList = ref<any[]>([])
const categoryOptions = ref<{ value: number; label: string }[]>([])
const locationOptions = ref<{ value: number; label: string }[]>([])
const modelOptions = ref<{ value: number; label: string }[]>([])
const supplierOptions = ref<{ value: number; label: string }[]>([])

const statusMap: Record<string, string> = { '1': '在库', '2': '在用', '3': '维修', '4': '报废' }

const columns = [
  { title: '设备名称', dataIndex: 'name', key: 'name', ellipsis: true },
  { title: '序列号', dataIndex: 'serial', key: 'serial', width: 140, ellipsis: true },
  { title: '设备编号', dataIndex: 'device_no', key: 'device_no', width: 120, ellipsis: true },
  { title: '型号', dataIndex: 'model_name', key: 'model_name', width: 140, ellipsis: true },
  { title: '分类', dataIndex: 'category_name', key: 'category_name', width: 120, ellipsis: true },
  { title: '状态', dataIndex: 'assets_status', key: 'assets_status', width: 80, align: 'center' as const },
  { title: '位置', dataIndex: 'location_name', key: 'location_name', width: 120, ellipsis: true },
  { title: '供应商', dataIndex: 'supplier_name', key: 'supplier_name', width: 140, ellipsis: true },
  { title: '操作', key: 'action', width: 100, align: 'center' as const },
]

onMounted(() => {
  getDataList()
  apiBaseCategory.list().then((res: any) => { categoryOptions.value = res.data.map((i: any) => ({ value: i.id, label: i.name })) })
  apiBaseLocation.list().then((res: any) => { locationOptions.value = res.data.map((i: any) => ({ value: i.id, label: i.name })) })
  apiBaseModel.list().then((res: any) => { modelOptions.value = res.data.map((i: any) => ({ value: i.id, label: i.name })) })
  apiBaseSupplier.list().then((res: any) => { supplierOptions.value = res.data.map((i: any) => ({ value: i.id, label: i.name })) })
})

function getDataList() {
  loading.value = true
  const params = { ...getParams(), ...search.value }
  apiAssetDevice.page(params).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 onCreate() { formModeProps.value.id = ''; updateDrawer({ title: '新增设备' }); openDrawer() }
function onEdit(row: any) { formModeProps.value.id = row.id; updateDrawer({ title: '编辑设备' }); openDrawer() }
function onDel(row: any) {
  useFaModal().confirm({
    title: '确认删除',
    content: `确认删除「${row.name}」吗？`,
    onConfirm: () => apiAssetDevice.delete(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.assets_status" placeholder="全部" allow-clear :options="[
                { value: '1', label: '在库' }, { value: '2', label: '在用' },
                { value: '3', label: '维修' }, { value: '4', label: '报废' },
              ]" />
            </FaLabel>
            <FaLabel label="分类" v-show="!fold">
              <ASelect v-model:value="search.category_id" placeholder="全部" allow-clear show-search :filter-option="(input: string, option: any) => option.label?.toLowerCase().includes(input.toLowerCase())" :options="categoryOptions" />
            </FaLabel>
            <FaLabel label="位置" v-show="!fold">
              <ASelect v-model:value="search.location_id" placeholder="全部" allow-clear show-search :filter-option="(input: string, option: any) => option.label?.toLowerCase().includes(input.toLowerCase())" :options="locationOptions" />
            </FaLabel>
            <FaLabel label="型号" v-show="!fold">
              <ASelect v-model:value="search.model_id" placeholder="全部" allow-clear show-search :filter-option="(input: string, option: any) => option.label?.toLowerCase().includes(input.toLowerCase())" :options="modelOptions" />
            </FaLabel>
            <FaLabel label="供应商" v-show="!fold">
              <ASelect v-model:value="search.supplier_id" placeholder="全部" allow-clear show-search :filter-option="(input: string, option: any) => option.label?.toLowerCase().includes(input.toLowerCase())" :options="supplierOptions" />
            </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="onCreate"><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: 1200 }">
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'assets_status'">
            <ATag :color="record.assets_status === '2' ? 'blue' : record.assets_status === '3' ? 'orange' : record.assets_status === '4' ? 'red' : 'default'">{{ statusMap[record.assets_status] || record.assets_status }}</ATag>
          </template>
          <template v-else-if="column.key === 'action'">
            <ASpace :size="4">
              <FaTooltip text="编辑">
                <FaButton variant="outline" size="icon-sm" @click="onEdit(record)"><FaIcon name="i-ri:edit-line" /></FaButton>
              </FaTooltip>
              <FaDropdown :items="[[{ label: '删除', variant: 'destructive', handle: () => onDel(record) }]]">
                <FaTooltip text="更多">
                  <FaButton variant="outline" size="icon-sm"><FaIcon name="i-ri:more-line" /></FaButton>
                </FaTooltip>
              </FaDropdown>
            </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>
