<template>
  <el-dialog v-model="visible" :title="title" width="1200px" @close="handleClose">
    <div class="audit-container">
      <!-- 左侧：PDF 预览 -->
      <div class="preview-section">
        <div v-if="previewLoading" v-loading="true" class="preview-loading">
          {{ t('document.document.auditForm.loading') }}
        </div>
        <div v-else-if="previewError" class="preview-error">
          <el-alert :title="previewError" type="error" :closable="false" />
        </div>
        <div v-else-if="pdfBlob" class="preview-content">
          <VueOfficePdf :src="pdfBlob" @rendered="handleRendered" @error="handlePreviewError" />
        </div>
        <div v-else class="preview-empty">
          <el-empty :description="t('document.document.auditForm.noDocument')" />
        </div>
      </div>

      <!-- 右侧：审核表单 -->
      <div class="form-section">
        <div class="form-header">
          <div class="header-icon">
            <el-icon :size="24"><DocumentChecked /></el-icon>
          </div>
          <div class="header-content">
            <h3 class="header-title">{{ t('document.document.auditForm.title') }}</h3>
            <p class="header-subtitle">{{ t('document.document.auditForm.subtitle') }}</p>
          </div>
        </div>

        <div class="form-body">
          <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
            <el-form-item :label="t('document.document.auditForm.result')" prop="result" class="result-item">
              <el-radio-group v-model="form.result" class="result-radio-group">
                <el-radio :value="3" class="result-radio result-radio-pass" border>
                  <div class="radio-content">
                    <el-icon :size="20"><CircleCheck /></el-icon>
                    <span>{{ t('document.document.auditForm.pass') }}</span>
                  </div>
                </el-radio>
                <el-radio :value="2" class="result-radio result-radio-reject" border>
                  <div class="radio-content">
                    <el-icon :size="20"><CircleClose /></el-icon>
                    <span>{{ t('document.document.auditForm.reject') }}</span>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <transition name="el-fade-in">
              <el-form-item
                v-if="form.result === 2"
                :label="t('document.document.auditForm.reason')"
                prop="rejectReason"
                class="reason-item"
              >
                <el-input
                  v-model="form.rejectReason"
                  type="textarea"
                  :rows="6"
                  :placeholder="t('document.document.auditForm.reasonPlaceholder')"
                  maxlength="500"
                  show-word-limit
                  class="reason-textarea"
                />
              </el-form-item>
            </transition>
          </el-form>
        </div>

        <div class="form-footer">
          <el-button size="large" @click="handleClose" class="footer-btn">
            <el-icon><Close /></el-icon>
            <span>{{ t('document.document.button.cancel') }}</span>
          </el-button>
          <el-button
            type="primary"
            size="large"
            :loading="loading"
            @click="handleSubmit"
            class="footer-btn footer-btn-primary"
          >
            <el-icon v-if="!loading"><Check /></el-icon>
            <span>{{ t('document.document.button.confirm') }}</span>
          </el-button>
        </div>
      </div>
    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, nextTick, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { DocumentChecked, CircleCheck, CircleClose, Check, Close } from '@element-plus/icons-vue';
import type { FormInstance } from 'element-plus';
import VueOfficePdf from '@vue-office/pdf';
import axios from 'axios';
import { globalHeaders } from '@/utils/request';

const baseURL = import.meta.env.VITE_APP_BASE_API;

interface DocumentInfo {
  id: string | number;
  actualDocument?: string | number;
  [key: string]: any;
}

interface AuditFormData {
  documentId: string | number;
  result: number;
  rejectReason?: string;
}

interface Props {
  modelValue: boolean;
  document: DocumentInfo | null;
  title?: string;
}

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

const emit = defineEmits<{
  'update:modelValue': [value: boolean];
  submit: [data: AuditFormData];
}>();

const { t } = useI18n();
const formRef = ref<FormInstance>();
const loading = ref(false);
const previewLoading = ref(false);
const previewError = ref('');
const pdfBlob = ref<ArrayBuffer | null>(null);

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

const title = computed(() => props.title || t('document.document.dialog.auditDocument'));

const form = ref<AuditFormData>({
  documentId: 0,
  result: 3,
  rejectReason: ''
});

const rules = reactive({
  result: [
    {
      required: true,
      message: t('document.document.auditRule.resultRequired'),
      trigger: 'change'
    }
  ],
  rejectReason: [
    {
      required: true,
      message: t('document.document.auditRule.reasonRequired'),
      trigger: 'blur'
    }
  ]
});

// 监听对话框打开和 document 变化，初始化表单和加载预览
watch(
  [() => props.modelValue, () => props.document],
  ([isVisible, newDoc]) => {
    // 只有在对话框打开且有文档时才加载
    if (isVisible && newDoc) {
      form.value = {
        documentId: newDoc.id as number,
        result: 3,
        rejectReason: ''
      };
      nextTick(() => {
        formRef.value?.clearValidate();
      });

      // 加载 PDF 预览
      loadPdfPreview(newDoc);
    } else if (!isVisible) {
      // 对话框关闭时清理状态
      pdfBlob.value = null;
      previewError.value = '';
      previewLoading.value = false;
    }
  },
  { immediate: true }
);

// 加载 PDF 预览
const loadPdfPreview = async (doc: DocumentInfo) => {
  previewLoading.value = true;
  previewError.value = '';
  pdfBlob.value = null;

  if (!doc.actualDocument) {
    previewError.value = t('document.document.auditForm.documentNotExist');
    previewLoading.value = false;
    return;
  }

  try {
    // 使用统一的文件下载接口获取 PDF 文件
    const response = await axios({
      method: 'post',
      url: `${baseURL}/document/document/download/${doc.actualDocument}`,
      responseType: 'arraybuffer',
      headers: globalHeaders()
    });

    pdfBlob.value = response.data;
    previewLoading.value = false;
  } catch (error) {
    console.error('下载PDF文件失败:', error);
    previewError.value = t('document.document.auditForm.loadFailed');
    previewLoading.value = false;
  }
};

// PDF 渲染完成
const handleRendered = () => {
  previewLoading.value = false;
};

// PDF 预览错误
const handlePreviewError = (error: any) => {
  previewLoading.value = false;
  previewError.value = t('document.document.auditForm.previewError');
  console.error('PDF预览错误:', error);
};

const handleClose = () => {
  visible.value = false;
  formRef.value?.resetFields();
  form.value = {
    documentId: 0,
    result: 3,
    rejectReason: ''
  };
  pdfBlob.value = null;
  previewError.value = '';
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  // 如果选择驳回，需要验证驳回理由
  if (form.value.result === 2) {
    try {
      await formRef.value.validate();
    } catch (error) {
      return;
    }
  }

  loading.value = true;
  try {
    const submitData: AuditFormData = {
      documentId: form.value.documentId,
      result: form.value.result,
      rejectReason: form.value.result === 2 ? form.value.rejectReason : undefined
    };

    // 触发提交事件，由父组件处理实际的审核请求
    emit('submit', submitData);
  } finally {
    loading.value = false;
  }
};

// 暴露方法供父组件调用
const closeDialog = () => {
  handleClose();
};

defineExpose({
  closeDialog
});
</script>

<style scoped lang="scss">
.audit-container {
  display: flex;
  gap: 20px;
  height: 70vh;
  min-height: 500px;

  .preview-section {
    flex: 1;
    border: 1px solid #dcdfe6;
    border-radius: 8px;
    overflow: hidden;
    background-color: #f5f7fa;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .preview-loading,
    .preview-error,
    .preview-empty {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
    }

    .preview-content {
      height: 100%;
      overflow: auto;
      background-color: #fff;

      :deep(.vue-office-pdf) {
        height: 100%;
      }
    }
  }

  .form-section {
    width: 420px;
    display: flex;
    flex-direction: column;
    background: linear-gradient(to bottom, #ffffff 0%, #fafbfc 100%);
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    overflow: hidden;

    .form-header {
      display: flex;
      align-items: center;
      gap: 16px;
      padding: 24px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #fff;

      .header-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 48px;
        height: 48px;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 12px;
        backdrop-filter: blur(10px);
      }

      .header-content {
        flex: 1;

        .header-title {
          margin: 0;
          font-size: 18px;
          font-weight: 600;
          line-height: 1.4;
        }

        .header-subtitle {
          margin: 4px 0 0;
          font-size: 13px;
          opacity: 0.9;
          line-height: 1.4;
        }
      }
    }

    .form-body {
      flex: 1;
      padding: 24px;
      overflow-y: auto;

      .el-form {
        height: 100%;

        .result-item {
          margin-bottom: 24px;

          :deep(.el-form-item__label) {
            font-weight: 600;
            font-size: 14px;
            color: #303133;
            margin-bottom: 12px;
          }

          .result-radio-group {
            display: flex;
            flex-direction: column;
            gap: 12px;
            width: 100%;

            .result-radio {
              width: 100%;
              margin: 0;
              padding: 0;
              border-radius: 8px;
              transition: all 0.3s ease;

              :deep(.el-radio__input) {
                display: none;
              }

              :deep(.el-radio__label) {
                width: 100%;
                padding: 16px 20px;
                display: flex;
                align-items: center;
                justify-content: center;
              }

              .radio-content {
                display: flex;
                align-items: center;
                gap: 10px;
                font-size: 15px;
                font-weight: 500;
              }

              &.result-radio-pass {
                border-color: #e8f4ea;
                background-color: #f0f9f1;

                &:hover {
                  border-color: #67c23a;
                  background-color: #e8f4ea;
                  transform: translateY(-2px);
                  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.2);
                }

                &.is-checked {
                  border-color: #67c23a;
                  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
                  box-shadow: 0 4px 12px rgba(103, 194, 58, 0.3);

                  :deep(.el-radio__label) {
                    color: #fff;
                  }

                  .radio-content {
                    color: #fff;
                  }
                }
              }

              &.result-radio-reject {
                border-color: #fde8e8;
                background-color: #fef0f0;

                &:hover {
                  border-color: #f56c6c;
                  background-color: #fde8e8;
                  transform: translateY(-2px);
                  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.2);
                }

                &.is-checked {
                  border-color: #f56c6c;
                  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
                  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.3);

                  :deep(.el-radio__label) {
                    color: #fff;
                  }

                  .radio-content {
                    color: #fff;
                  }
                }
              }
            }
          }
        }

        .reason-item {
          :deep(.el-form-item__label) {
            font-weight: 600;
            font-size: 14px;
            color: #303133;
            margin-bottom: 12px;
          }

          .reason-textarea {
            :deep(.el-textarea__inner) {
              border-radius: 8px;
              border: 2px solid #e4e7ed;
              padding: 12px;
              font-size: 14px;
              line-height: 1.6;
              transition: all 0.3s ease;

              &:focus {
                border-color: #667eea;
                box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
              }
            }

            :deep(.el-input__count) {
              background-color: transparent;
              font-size: 12px;
            }
          }
        }
      }
    }

    .form-footer {
      display: flex;
      gap: 12px;
      padding: 20px 24px;
      background-color: #fff;
      border-top: 1px solid #e4e7ed;
      box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.04);

      .footer-btn {
        flex: 1;
        height: 44px;
        font-size: 15px;
        font-weight: 500;
        border-radius: 8px;
        transition: all 0.3s ease;

        .el-icon {
          margin-right: 6px;
        }

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        &.footer-btn-primary {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          border: none;

          &:hover {
            background: linear-gradient(135deg, #5568d3 0%, #6a3f8f 100%);
          }
        }
      }
    }
  }
}

// 过渡动画
.el-fade-in-enter-active,
.el-fade-in-leave-active {
  transition: all 0.3s ease;
}

.el-fade-in-enter-from {
  opacity: 0;
  transform: translateY(-10px);
}

.el-fade-in-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}
</style>
