<script setup lang="tsx">
import { ref, watch } from 'vue';
import { ElTag } from 'element-plus';
import { fetchGetOvertimeApplicationStatusLogs } from '@/service/api';
import BusinessFormDialog from '@/components/custom/business-form-dialog.vue';
import {
  formatEmptyText,
  formatOvertimeDate,
  formatOvertimeDateTime,
  getOvertimeApplicationActionLabel,
  getOvertimeApplicationStatusLabel,
  resolveOvertimeApplicationStatusTagType
} from './overtime-application-shared';

defineOptions({ name: 'OvertimeApplicationStatusLogDialog' });

interface Props {
  rowData?: Api.OvertimeApplication.OvertimeApplication | null;
}

const props = defineProps<Props>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const loading = ref(false);
const logs = ref<Api.OvertimeApplication.OvertimeApplicationStatusLog[]>([]);

async function loadLogs() {
  if (!props.rowData?.id) {
    logs.value = [];
    return;
  }

  loading.value = true;
  const { error, data } = await fetchGetOvertimeApplicationStatusLogs(props.rowData.id);
  loading.value = false;

  logs.value = error || !data ? [] : data;
}

function renderStatus(code?: string | null) {
  if (!code) {
    return '--';
  }

  return <ElTag type={resolveOvertimeApplicationStatusTagType(code)}>{getOvertimeApplicationStatusLabel(code)}</ElTag>;
}

watch(
  () => visible.value,
  value => {
    if (value) {
      loadLogs();
    }
  }
);
</script>

<template>
  <BusinessFormDialog
    v-model="visible"
    title="状态日志"
    width="920px"
    :loading="loading"
    :show-footer="false"
    max-body-height="72vh"
  >
    <ElTable border :data="logs">
      <ElTableColumn prop="createTime" label="操作时间" width="170">
        <template #default="{ row }">{{ formatOvertimeDateTime(row.createTime) }}</template>
      </ElTableColumn>
      <ElTableColumn prop="actionType" label="动作" width="110">
        <template #default="{ row }">{{ getOvertimeApplicationActionLabel(row.actionType) }}</template>
      </ElTableColumn>
      <ElTableColumn prop="operatorName" label="操作人" width="120" show-overflow-tooltip />
      <ElTableColumn prop="fromStatus" label="原状态" width="110" :formatter="row => renderStatus(row.fromStatus)" />
      <ElTableColumn prop="toStatus" label="新状态" width="110" :formatter="row => renderStatus(row.toStatus)" />
      <ElTableColumn prop="reason" label="原因/意见" min-width="180" show-overflow-tooltip>
        <template #default="{ row }">{{ formatEmptyText(row.reason) }}</template>
      </ElTableColumn>
      <ElTableColumn prop="overtimeDateSnapshot" label="加班日期" width="120">
        <template #default="{ row }">{{ formatOvertimeDate(row.overtimeDateSnapshot) }}</template>
      </ElTableColumn>
      <ElTableColumn prop="overtimeDurationSnapshot" label="时长" width="90" show-overflow-tooltip />
    </ElTable>
  </BusinessFormDialog>
</template>
