<script lang="ts" setup>
/**
 * 仓库药品修改记录列表（日志审计）
 * 查看单个/批量/同步到门店的前后快照
 */
import { onMounted } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { Tag } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { TableAction } from '#/components/table-action';

import {
  getWarehouseDrugChangeTypeOption,
  getWarehouseDrugUserTypeOption,
} from './api';
import DetailModal from './components/detail-modal.vue';
import { formOptions } from './config/search';
import { gridOptions } from './config/table';

defineOptions({ name: 'WarehouseDrugChangeLog' });

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [DetailModalComp, detailModalApi] = useVbenModal({
  connectedComponent: DetailModal,
});

function openDetail(row: Record<string, any>) {
  detailModalApi.setData({ id: Number(row?.id || 0), values: row });
  detailModalApi.open();
}

function changeTypeColor(type: number) {
  if (type === 2) return 'orange';
  if (type === 3) return 'purple';
  return 'blue';
}

onMounted(async () => {
  try {
    const [changeOpts, userOpts] = await Promise.all([
      getWarehouseDrugChangeTypeOption(),
      getWarehouseDrugUserTypeOption(),
    ]);
    const changeOptions = Array.isArray(changeOpts)
      ? changeOpts
      : changeOpts?.data || [];
    const userOptions = Array.isArray(userOpts) ? userOpts : userOpts?.data || [];
    gridApi.formApi?.updateSchema?.([
      {
        fieldName: 'change_type',
        componentProps: {
          allowClear: true,
          options: changeOptions,
          placeholder: '全部',
        },
      },
      {
        fieldName: 'user_type',
        componentProps: {
          allowClear: true,
          options: userOptions,
          placeholder: '全部',
        },
      },
    ]);
  } catch {
    // 接口失败时沿用 constants 兜底
  }
});
</script>

<template>
  <Page auto-content-height title="仓库修改记录">
    <DetailModalComp />
    <Grid>
      <template #toolbar-actions />
      <template #user_type="{ row }">
        <Tag :color="Number(row.user_type) === 2 ? 'geekblue' : 'green'">
          {{ row.user_type_txt || row.user_type }}
        </Tag>
      </template>
      <template #change_type="{ row }">
        <Tag :color="changeTypeColor(Number(row.change_type))">
          {{ row.change_type_txt || row.change_type }}
        </Tag>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '详情',
              type: 'link',
              size: 'small',
              onClick: () => openDetail(row),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
