<template>
  <div>
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="1000px" append-to-body>
      <!-- 搜索栏 -->
      <el-form :model="queryParams" :inline="true" class="search-form mb-4">
        <el-form-item :label="resultLabel">
          <el-select v-model="queryParams.result" :placeholder="selectResultPlaceholder" clearable>
            <el-option :label="passLabel" value="3" />
            <el-option :label="rejectLabel" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item :label="auditTimeLabel">
          <el-date-picker v-model="auditTimeRange" type="daterange" range-separator="-"
            :start-placeholder="startTimePlaceholder" :end-placeholder="endTimePlaceholder"
            value-format="YYYY-MM-DD HH:mm:ss" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">{{ searchButtonText }}</el-button>
          <el-button icon="Refresh" @click="handleReset">{{ resetButtonText }}</el-button>
        </el-form-item>
      </el-form>

      <!-- 审核记录列表 -->
      <el-table v-loading="loading" :data="auditLogList" border>
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="documentName" :label="documentNameLabel" min-width="150" show-overflow-tooltip />
        <el-table-column prop="auditorType" :label="auditorTypeLabel" width="120" align="center">
          <template #default="scope">
            <dict-tag v-if="scope.row.auditorType" :options="auditor_type" :value="scope.row.auditorType" />
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="auditorName" :label="auditorNameLabel" width="120" align="center" />
        <el-table-column prop="result" :label="resultLabel" width="100" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.result === 3" size="small" type="success">
              {{ passLabel }}
            </el-tag>
            <el-tag v-else-if="scope.row.result === 2" size="small" type="danger">
              {{ rejectLabel }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="rejectReason" :label="rejectReasonLabel" min-width="180" show-overflow-tooltip />
        <el-table-column prop="auditTime" :label="auditTimeLabel" width="180" align="center">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditTime) }}</span>
          </template>
        </el-table-column>
        <!-- 操作栏 -->
        <el-table-column :label="operationLabel" width="120" align="center" fixed="right">
          <template #default="scope">
            <el-button v-if="scope.row.ossId" type="primary" link icon="Download"
              @click="handleDownload(scope.row.ossId, scope.row.documentName)" :title="downloadButtonText" />
            <span v-else>-</span>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
        :total="total" @pagination="getList" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, getCurrentInstance, toRefs } from 'vue';
import { useI18n } from 'vue-i18n';
import { parseTime } from '@/utils/ruoyi';
import { downloadDocumentFile } from '@/api/document/document';
import type { ComponentInternalInstance } from 'vue';

interface Props {
  documentId: number | string;
  visible: boolean;
  apiFunction: (params: any) => Promise<any>;
  i18nPrefix?: string; // 国际化前缀，如 'document.document' 或 'home.taskCenter'
}

const props = withDefaults(defineProps<Props>(), {
  i18nPrefix: 'document.document'
});

const emit = defineEmits(['update:visible']);

const { t } = useI18n();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

// 获取审核人类型字典
const { auditor_type } = toRefs<any>(proxy?.useDict('auditor_type'));

const dialogVisible = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// 国际化文本计算属性
const dialogTitle = computed(() => t(`${props.i18nPrefix}.dialog.auditLog`));
const resultLabel = computed(() => t(`${props.i18nPrefix}.auditLog.result`));
const selectResultPlaceholder = computed(() => t(`${props.i18nPrefix}.auditLog.selectResult`));
const passLabel = computed(() => t(`${props.i18nPrefix}.auditLog.pass`));
const rejectLabel = computed(() => t(`${props.i18nPrefix}.auditLog.reject`));
const auditTimeLabel = computed(() => t(`${props.i18nPrefix}.auditLog.auditTime`));
const startTimePlaceholder = computed(() => t(`${props.i18nPrefix}.auditLog.startTime`));
const endTimePlaceholder = computed(() => t(`${props.i18nPrefix}.auditLog.endTime`));
const searchButtonText = computed(() => t(`${props.i18nPrefix}.button.search`));
const resetButtonText = computed(() => t(`${props.i18nPrefix}.button.reset`));
const documentNameLabel = computed(() => t(`${props.i18nPrefix}.auditLog.documentName`));
const auditorTypeLabel = computed(() => t(`${props.i18nPrefix}.auditLog.auditorType`));
const auditorNameLabel = computed(() => t(`${props.i18nPrefix}.auditLog.auditorName`));
const rejectReasonLabel = computed(() => t(`${props.i18nPrefix}.auditLog.rejectReason`));
const operationLabel = computed(() => t(`${props.i18nPrefix}.auditLog.operation`));
const downloadButtonText = computed(() => t(`${props.i18nPrefix}.button.download`));

const loading = ref(false);
const total = ref(0);
const auditLogList = ref<any[]>([]);
const auditTimeRange = ref<[string, string]>(['', '']);

const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  documentId: props.documentId,
  result: undefined,
  params: {}
});

/** 查询审核记录列表 */
const getList = async () => {
  loading.value = true;
  // 更新documentId
  queryParams.value.documentId = props.documentId;
  // 处理时间范围
  queryParams.value.params = {};
  proxy?.addDateRange(queryParams.value, auditTimeRange.value, 'AuditTime', 'earliestTime', 'latestTime');

  try {
    const res = await props.apiFunction(queryParams.value);
    auditLogList.value = res.rows;
    total.value = res.total;
  } catch (error) {
    console.error('获取审核记录失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const handleReset = () => {
  queryParams.value.result = undefined;
  auditTimeRange.value = ['', ''];
  handleQuery();
};

/** 监听文档ID变化，重新查询 */
watch(() => props.documentId, (newVal) => {
  if (newVal && dialogVisible.value) {
    getList();
  }
});

/** 监听可见性变化，打开时重新查询 */
watch(() => props.visible, (newVal) => {
  if (newVal) {
    getList();
  }
});

/** 下载历史文件 */
const handleDownload = async (ossId: number, fileName: string) => {
  if (!ossId) return;
  await downloadDocumentFile(ossId, fileName);
};
</script>

<style scoped>
.search-form {
  margin-bottom: 16px;
}
</style>
