<template>
  <el-dialog v-model="visible" :title="title" width="1200px" append-to-body @close="handleClose">
    <div class="qc-audit-container">
      <!-- 左侧：PDF 预览 -->
      <div class="qc-preview-section">
        <div v-if="previewLoading" v-loading="true" class="preview-loading">
          {{ t('qc.task.auditDialog.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('qc.task.auditDialog.noDocument')" />
        </div>
      </div>

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

        <div class="qc-form-body">
          <el-form ref="formRef" :model="form" :rules="rules" label-position="top">
            <el-form-item :label="t('qc.task.auditDialog.result')" prop="result" class="result-item">
              <el-radio-group v-model="form.result" class="result-radio-group">
                <el-radio :value="1" class="result-radio result-radio-pass" border>
                  <div class="radio-content">
                    <el-icon :size="20"><CircleCheck /></el-icon>
                    <span>{{ t('qc.task.auditDialog.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('qc.task.auditDialog.reject') }}</span>
                  </div>
                </el-radio>
              </el-radio-group>
            </el-form-item>

            <transition name="el-fade-in">
              <div v-if="form.result === 2" class="reject-form-items">
                <el-form-item :label="t('qc.task.auditDialog.rejectionType')" prop="rejectionType">
                  <el-select v-model="form.rejectionType" :placeholder="t('qc.task.auditDialog.rejectionTypePlaceholder')" style="width: 100%">
                    <el-option v-for="dict in qcQuestionType" :key="dict.value" :label="parseI18nName(dict.label)"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>

                <el-form-item :label="t('qc.task.auditDialog.opinion')" prop="opinion">
                  <el-input v-model="form.opinion" type="textarea" :rows="3" :placeholder="t('qc.task.auditDialog.opinionPlaceholder')" />
                </el-form-item>

                <el-form-item :label="t('qc.task.auditDialog.designatedDealer')" prop="designatedDealer">
                  <el-select v-model="form.designatedDealer" filterable remote reserve-keyword :placeholder="t('qc.task.auditDialog.designatedDealerPlaceholder')"
                    :remote-method="searchDealers" :loading="dealerSearchLoading" style="width: 100%">
                    <el-option v-for="dealer in dealerOptions" :key="dealer.id"
                      :label="`${dealer.name} / ${dealer.dept} --- ${dealer.phoneNumber}`" :value="dealer.id" />
                  </el-select>
                </el-form-item>

                <el-form-item :label="t('qc.task.auditDialog.deadline')" prop="deadline">
                  <el-date-picker v-model="form.deadline" type="date" value-format="YYYY-MM-DD" :placeholder="t('qc.task.auditDialog.deadlinePlaceholder')"
                    style="width: 100%" />
                </el-form-item>
              </div>
            </transition>
          </el-form>
        </div>

        <div class="qc-form-footer">
          <el-button size="large" @click="handleClose" class="footer-btn">
            <el-icon><Close /></el-icon>
            <span>{{ t('qc.task.auditDialog.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('qc.task.auditDialog.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 { parseI18nName } from '@/utils/i18n';
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 TaskDetail {
  id?: number;
  documentName?: string;
  executorName?: string;
  executionTime?: string;
  finishTime?: string;
  note?: string;
  actualDocument?: string | number;
  [key: string]: any;
}

interface AuditFormData {
  result: number;
  rejectionType?: string;
  opinion?: string;
  designatedDealer?: number;
  deadline?: string;
}

interface Dealer {
  id: number;
  name: string;
  dept: string;
  phoneNumber: string;
}

interface Props {
  modelValue: boolean;
  taskDetail: TaskDetail | null;
  title?: string;
  qcQuestionType?: any[];
  dealerSearchMethod?: (query: string) => Promise<Dealer[]>;
}

const props = withDefaults(defineProps<Props>(), {
  title: '',
  qcQuestionType: () => [],
  dealerSearchMethod: undefined
});

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

const { t } = useI18n();
const formRef = ref<FormInstance>();
const loading = ref(false);
const dealerSearchLoading = ref(false);
const dealerOptions = ref<Dealer[]>([]);
const previewLoading = ref(false);
const previewError = ref('');
const pdfBlob = ref<ArrayBuffer | null>(null);
let dealerSearchTimer: NodeJS.Timeout | null = null;

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

const title = computed(() => props.title || t('qc.task.auditDialog.title'));

const form = ref<AuditFormData>({
  result: 1,
  rejectionType: undefined,
  opinion: undefined,
  designatedDealer: undefined,
  deadline: undefined
});

const rules = reactive({
  result: [
    {
      required: true,
      message: t('qc.task.auditRule.resultRequired'),
      trigger: 'change'
    }
  ],
  rejectionType: [
    {
      required: true,
      message: t('qc.task.auditRule.rejectionTypeRequired'),
      trigger: 'change'
    }
  ],
  opinion: [
    {
      required: true,
      message: t('qc.task.auditRule.opinionRequired'),
      trigger: 'blur'
    }
  ],
  designatedDealer: [
    {
      required: true,
      message: t('qc.task.auditRule.designatedDealerRequired'),
      trigger: 'change'
    }
  ],
  deadline: [
    {
      required: true,
      message: t('qc.task.auditRule.deadlineRequired'),
      trigger: 'change'
    }
  ]
});

// 监听对话框打开和 taskDetail 变化
watch(
  [() => props.modelValue, () => props.taskDetail],
  ([isVisible, newDetail]) => {
    if (isVisible && newDetail) {
      form.value = {
        result: 1,
        rejectionType: undefined,
        opinion: undefined,
        designatedDealer: undefined,
        deadline: undefined
      };
      dealerOptions.value = [];
      nextTick(() => {
        formRef.value?.clearValidate();
      });
      
      // 加载 PDF 预览
      loadPdfPreview(newDetail);
    } else if (!isVisible) {
      // 对话框关闭时清理状态
      dealerOptions.value = [];
      dealerSearchLoading.value = false;
      pdfBlob.value = null;
      previewError.value = '';
      previewLoading.value = false;
      if (dealerSearchTimer) {
        clearTimeout(dealerSearchTimer);
      }
    }
  },
  { immediate: true }
);

// 搜索处理人
const searchDealers = async (query: string) => {
  if (!query || query.trim() === '') {
    dealerOptions.value = [];
    return;
  }

  if (dealerSearchTimer) {
    clearTimeout(dealerSearchTimer);
  }

  dealerSearchTimer = setTimeout(async () => {
    if (!props.dealerSearchMethod) {
      return;
    }

    dealerSearchLoading.value = true;
    try {
      dealerOptions.value = await props.dealerSearchMethod(query);
    } catch (error) {
      console.error('搜索处理人失败:', error);
      dealerOptions.value = [];
    } finally {
      dealerSearchLoading.value = false;
    }
  }, 300);
};

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

  if (!detail.actualDocument) {
    previewError.value = t('qc.task.auditDialog.documentNotExist');
    previewLoading.value = false;
    return;
  }

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

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

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

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

const handleClose = () => {
  visible.value = false;
  formRef.value?.resetFields();
  form.value = {
    result: 1,
    rejectionType: undefined,
    opinion: undefined,
    designatedDealer: undefined,
    deadline: undefined
  };
  dealerOptions.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 = {
      result: form.value.result
    };

    // 驳回时添加额外字段
    if (form.value.result === 2) {
      submitData.rejectionType = form.value.rejectionType;
      submitData.opinion = form.value.opinion;
      submitData.designatedDealer = form.value.designatedDealer;
      submitData.deadline = form.value.deadline;
    }

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

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

defineExpose({
  closeDialog
});
</script>

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

  .qc-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%;
      }
    }
  }

  .qc-info-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);
    display: flex;
    flex-direction: column;

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

      .qc-info-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);
      }

      .qc-info-content {
        flex: 1;

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

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

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

      .info-item {
        display: flex;
        margin-bottom: 16px;
        padding-bottom: 12px;
        border-bottom: 1px solid #e4e7ed;

        &:last-child {
          border-bottom: none;
          margin-bottom: 0;
          padding-bottom: 0;
        }

        .info-label {
          font-weight: 600;
          color: #606266;
          min-width: 120px;
          flex-shrink: 0;
        }

        .info-value {
          color: #303133;
          flex: 1;
          word-break: break-all;
        }
      }
    }
  }

  .qc-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;

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

      .qc-form-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);
      }

      .qc-form-content {
        flex: 1;

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

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

    .qc-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;
                  }
                }
              }
            }
          }
        }

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

          :deep(.el-input__inner),
          :deep(.el-textarea__inner) {
            border-radius: 8px;
            border: 2px solid #e4e7ed;
            transition: all 0.3s ease;

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

          :deep(.el-select__wrapper) {
            border-radius: 8px;
          }
        }
      }
    }

    .qc-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>
