<script lang="ts" setup>
/**
 * 身份证实名核验日志（name 存 MD5 摘要；超管可回填旧明文）
 */
import { computed, ref } from 'vue';

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

import { Button, Modal, Tag, message } from 'ant-design-vue';

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

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

defineOptions({ name: 'IdcardVerifyLog' });

const userStore = useUserStore();
/** 仅超管 role_id=1 可见回填按钮，与后端 SUPPER_ADMIN 一致 */
const isSuperAdmin = computed(() => {
  const roleId = Number(
    userStore.userInfo?.role_id ?? userStore.userInfo?.roles?.id,
  );
  return roleId === 1;
});

const backfilling = ref(false);
const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
const [DetailModalComp, detailModalApi] = useVbenModal({
  connectedComponent: DetailModal,
});

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

/** 超管确认后把历史明文 name 刷成 MD5 摘要 */
function handleBackfillNameHash() {
  Modal.confirm({
    title: '回填姓名 MD5',
    content:
      '将把尚未哈希的明文姓名批量更新为 MD5 摘要。已是 32 位摘要的行会跳过，可重复执行。是否继续？',
    okText: '开始回填',
    cancelText: '取消',
    onOk: async () => {
      backfilling.value = true;
      try {
        const res = await backfillIdcardVerifyNameHash();
        const data = res?.data || res || {};
        message.success(
          `回填完成：更新 ${Number(data.updated || 0)} 条，跳过 ${Number(data.skipped || 0)} 条`,
        );
        await gridApi.query();
      } finally {
        backfilling.value = false;
      }
    },
  });
}
</script>

<template>
  <Page auto-content-height title="身份证实名核验日志">
    <DetailModalComp />
    <Grid>
      <template #toolbar-tools>
        <Button
          v-if="isSuperAdmin"
          type="primary"
          danger
          :loading="backfilling"
          class="mr-2"
          @click="handleBackfillNameHash"
        >
          回填姓名MD5
        </Button>
      </template>
      <template #is_match="{ row }">
        <Tag :color="Number(row.is_match) === 1 ? 'success' : 'error'">
          {{ row.is_match_txt }}
        </Tag>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            { label: '详情', type: 'link', size: 'small', onClick: () => openDetail(row) },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
