<script setup lang="ts">
import { computed, h, onMounted, ref, resolveComponent } from 'vue';

interface AuditItem {
  id: string;
  name: string;
  category: string;
  weight: number;
  score: number | null;
  status: 'pending' | 'completed' | 'in-progress';
  photos: Array<{
    id: string;
    url: string;
    description: string;
    timestamp: string;
  }>;
  evidences: Array<{
    id: string;
    type: 'photo' | 'audio' | 'video' | 'document';
    url: string;
    description: string;
    timestamp: string;
  }>;
  issues: Array<{
    id: string;
    description: string;
    severity: 'low' | 'medium' | 'high' | 'critical';
    category: string;
    timestamp: string;
  }>;
  communications: Array<{
    id: string;
    content: string;
    participantName: string;
    timestamp: string;
    result: string;
  }>;
}

// 主体框架内置的第三方方法通过window对象暴露、供外部组件使用
const axios = (window as any).$axios;
// 获取主题状态
const themeStore = (window as any).$themeStore;
// 获取消息提示
const message = (window as any).$message;
const dialog = (window as any).$dialog;
// 通过计算属性确定当前的主体色
const isDarkMode = computed(() => themeStore?.darkMode || false);
// 根据主题计算文字颜色
const textColor = computed(() => (isDarkMode.value ? 'rgba(255, 255, 255, 0.85)' : 'rgba(0, 0, 0, 0.85)'));
const legendTextColor = computed(() => (isDarkMode.value ? 'rgba(255, 255, 255, 0.65)' : 'rgba(0, 0, 0, 0.65)'));
const borderColor = computed(() => (isDarkMode.value ? '#303030' : '#ffffff'));
// CSS变量
const cssVars = computed(() => ({
  '--text-color': textColor.value,
  '--bg-color': isDarkMode.value ? '#1f1f1f' : '#f5f5f5',
  '--panel-bg': isDarkMode.value ? '#262626' : '#ffffff',
  '--card-bg': isDarkMode.value ? '#303030' : '#ffffff',
  '--border-color': isDarkMode.value ? '#434343' : '#e8e8e8'
}));

// 状态变量
const loading = ref<boolean>(false);
const currentItem = ref<AuditItem | null>(null);
const showPhotoDialog = ref(false);
const showEvidenceDialog = ref(false);
const showIssueDialog = ref(false);
const showCommunicationDialog = ref(false);

// 表单数据
const photoDescription = ref('');
const issueForm = ref({
  description: '',
  severity: 'medium',
  category: '管理要求'
});
const communicationForm = ref({
  content: '',
  participantName: '',
  result: ''
});

// 审核项目数据
const auditItems = ref<AuditItem[]>([]);

// 严重程度选项
const severityOptions = [
  { label: '轻微', value: 'low' },
  { label: '一般', value: 'medium' },
  { label: '严重', value: 'high' },
  { label: '致命', value: 'critical' }
];

// 问题类别选项
const issueCategoryOptions = [
  { label: '管理要求', value: '管理要求' },
  { label: '技术要求', value: '技术要求' },
  { label: '设备设施', value: '设备设施' },
  { label: '人员资质', value: '人员资质' }
];

// 审核项目表格列定义
const auditColumns = [
  { title: '审核项目', key: 'name', width: 200 },
  { title: '类别', key: 'category', align: 'center' as const, width: 120 },
  { title: '权重', key: 'weight', align: 'center' as const, width: 80 },
  {
    title: '评分',
    key: 'score',
    align: 'center' as const,
    width: 120,
    render: (row: AuditItem) => {
      return h(resolveComponent('n-input-number'), {
        value: row.score,
        min: 0,
        max: 100,
        placeholder: '0-100',
        onUpdateValue: (value: number | null) => {
          row.score = value;
          updateItemStatus(row);
        }
      });
    }
  },
  {
    title: '状态',
    key: 'status',
    align: 'center' as const,
    width: 100,
    render: (row: AuditItem) => {
      const statusMap = {
        pending: { type: 'default', text: '待审核' },
        'in-progress': { type: 'warning', text: '进行中' },
        completed: { type: 'success', text: '已完成' }
      };
      const status = statusMap[row.status];
      return h(resolveComponent('n-tag'), { type: status.type }, { default: () => status.text });
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 250,
    align: 'center' as const,
    render(row: AuditItem) {
      return h('div', { style: 'display: flex; gap: 4px; justify-content: center; flex-wrap: wrap;' }, [
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            type: 'info',
            onClick: () => openPhotoDialog(row)
          },
          { default: () => '拍照' }
        ),
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            type: 'primary',
            onClick: () => openEvidenceDialog(row)
          },
          { default: () => '证据' }
        ),
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            type: 'warning',
            onClick: () => openIssueDialog(row)
          },
          { default: () => '问题' }
        ),
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            type: 'success',
            onClick: () => openCommunicationDialog(row)
          },
          { default: () => '沟通' }
        )
      ]);
    }
  }
];

// 获取审核项目数据
async function fetchAuditItems() {
  try {
    loading.value = true;

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500));

    auditItems.value = [
      {
        id: '1',
        name: '管理体系文件',
        category: '管理要求',
        weight: 15,
        score: null,
        status: 'pending',
        photos: [],
        evidences: [],
        issues: [],
        communications: []
      },
      {
        id: '2',
        name: '人员资质证书',
        category: '管理要求',
        weight: 10,
        score: null,
        status: 'pending',
        photos: [],
        evidences: [],
        issues: [],
        communications: []
      },
      {
        id: '3',
        name: '检测设备校准',
        category: '技术要求',
        weight: 20,
        score: null,
        status: 'pending',
        photos: [],
        evidences: [],
        issues: [],
        communications: []
      },
      {
        id: '4',
        name: '环境条件控制',
        category: '技术要求',
        weight: 15,
        score: null,
        status: 'pending',
        photos: [],
        evidences: [],
        issues: [],
        communications: []
      },
      {
        id: '5',
        name: '检测方法验证',
        category: '技术要求',
        weight: 25,
        score: null,
        status: 'pending',
        photos: [],
        evidences: [],
        issues: [],
        communications: []
      },
      {
        id: '6',
        name: '质量控制记录',
        category: '管理要求',
        weight: 15,
        score: null,
        status: 'pending',
        photos: [],
        evidences: [],
        issues: [],
        communications: []
      }
    ];

    message.success('审核项目加载成功');
  } catch (error) {
    message.error('获取审核项目失败');
    // console.error('获取审核项目失败:', error);
  } finally {
    loading.value = false;
  }
}

// 更新项目状态
function updateItemStatus(item: AuditItem) {
  if (item.score !== null) {
    item.status = 'completed';
  } else {
    item.status = 'pending';
  }
}

// 打开拍照对话框
function openPhotoDialog(item: AuditItem) {
  currentItem.value = item;
  photoDescription.value = '';
  showPhotoDialog.value = true;
}

// 拍照功能（模拟）
function takePhoto() {
  if (!currentItem.value) return;

  const photo = {
    id: `photo-${Date.now()}`,
    url: `https://via.placeholder.com/300x200?text=${encodeURIComponent(currentItem.value.name)}`,
    description: photoDescription.value || '现场照片',
    timestamp: new Date().toLocaleString()
  };

  currentItem.value.photos.push(photo);

  // 同时添加到证据中
  currentItem.value.evidences.push({
    id: photo.id,
    type: 'photo',
    url: photo.url,
    description: photo.description,
    timestamp: photo.timestamp
  });

  currentItem.value.status = 'in-progress';
  photoDescription.value = '';
  showPhotoDialog.value = false;
  message.success('照片已保存');
}

// 打开证据对话框
function openEvidenceDialog(item: AuditItem) {
  currentItem.value = item;
  showEvidenceDialog.value = true;
}

// 添加其他证据（模拟）
function addEvidence(type: 'audio' | 'video' | 'document') {
  if (!currentItem.value) return;

  const evidence = {
    id: `evidence-${Date.now()}`,
    type,
    url: `#${type}-placeholder`,
    description: `${getEvidenceTypeName(type)}证据`,
    timestamp: new Date().toLocaleString()
  };

  currentItem.value.evidences.push(evidence);
  currentItem.value.status = 'in-progress';
  message.success(`${getEvidenceTypeName(type)}证据已添加`);
}

// 获取证据类型名称
function getEvidenceTypeName(type: string) {
  const typeMap: { [key: string]: string } = {
    photo: '照片',
    audio: '录音',
    video: '录像',
    document: '文档'
  };
  return typeMap[type] || type;
}

// 打开问题记录对话框
function openIssueDialog(item: AuditItem) {
  currentItem.value = item;
  issueForm.value = {
    description: '',
    severity: 'medium',
    category: '管理要求'
  };
  showIssueDialog.value = true;
}

// 记录问题
function recordIssue() {
  if (!currentItem.value || !issueForm.value.description.trim()) {
    message.error('请填写问题描述');
    return;
  }

  const issue = {
    id: `issue-${Date.now()}`,
    description: issueForm.value.description,
    severity: issueForm.value.severity as 'low' | 'medium' | 'high' | 'critical',
    category: issueForm.value.category,
    timestamp: new Date().toLocaleString()
  };

  currentItem.value.issues.push(issue);
  currentItem.value.status = 'in-progress';
  showIssueDialog.value = false;
  message.success('问题已记录');
}

// 打开沟通记录对话框
function openCommunicationDialog(item: AuditItem) {
  currentItem.value = item;
  communicationForm.value = {
    content: '',
    participantName: '',
    result: ''
  };
  showCommunicationDialog.value = true;
}

// 记录沟通
function recordCommunication() {
  if (!currentItem.value || !communicationForm.value.content.trim()) {
    message.error('请填写沟通内容');
    return;
  }

  const communication = {
    id: `comm-${Date.now()}`,
    content: communicationForm.value.content,
    participantName: communicationForm.value.participantName,
    timestamp: new Date().toLocaleString(),
    result: communicationForm.value.result
  };

  currentItem.value.communications.push(communication);
  currentItem.value.status = 'in-progress';
  showCommunicationDialog.value = false;
  message.success('沟通记录已保存');
}

// 计算审核进度
const auditProgress = computed(() => {
  const total = auditItems.value.length;
  const completed = auditItems.value.filter(item => item.status === 'completed').length;
  const inProgress = auditItems.value.filter(item => item.status === 'in-progress').length;

  return {
    total,
    completed,
    inProgress,
    pending: total - completed - inProgress,
    completionRate: total > 0 ? Math.round((completed / total) * 100) : 0,
    progressRate: total > 0 ? Math.round(((completed + inProgress) / total) * 100) : 0
  };
});

// 计算总体评分
const overallScore = computed(() => {
  const scoredItems = auditItems.value.filter(item => item.score !== null);
  if (scoredItems.length === 0) return null;

  const totalWeight = scoredItems.reduce((sum, item) => sum + item.weight, 0);
  const weightedScore = scoredItems.reduce((sum, item) => sum + item.score! * item.weight, 0);

  return totalWeight > 0 ? Math.round(weightedScore / totalWeight) : 0;
});

// 页面加载时获取数据
onMounted(() => {
  fetchAuditItems();
});
</script>

<template>
  <div>
    <!-- 审核进度跟踪 -->
    <div class="section-title">
      <svg class="section-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
        <path
          fill="currentColor"
          d="M13,9H11V7H13M13,17H11V11H13M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z"
        ></path>
      </svg>
      <span>审核进度跟踪</span>
    </div>

    <div class="progress-cards">
      <NCard class="progress-card">
        <div class="progress-item">
          <div class="progress-number">{{ auditProgress.total }}</div>
          <div class="progress-label">总项目</div>
        </div>
      </NCard>
      <NCard class="progress-card">
        <div class="progress-item">
          <div class="progress-number">{{ auditProgress.completed }}</div>
          <div class="progress-label">已完成</div>
        </div>
      </NCard>
      <NCard class="progress-card">
        <div class="progress-item">
          <div class="progress-number">{{ auditProgress.inProgress }}</div>
          <div class="progress-label">进行中</div>
        </div>
      </NCard>
      <NCard class="progress-card">
        <div class="progress-item">
          <div class="progress-number">{{ auditProgress.completionRate }}%</div>
          <div class="progress-label">完成率</div>
        </div>
      </NCard>
    </div>

    <NProgress type="line" :percentage="auditProgress.progressRate" :height="20" :border-radius="10">
      <span style="color: white; font-weight: bold">{{ auditProgress.progressRate }}%</span>
    </NProgress>

    <NDivider></NDivider>

    <!-- 审核项目打分 -->
    <div class="section-title">
      <svg class="section-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24">
        <path
          fill="currentColor"
          d="M12,17.27L18.18,21L16.54,13.97L22,9.24L14.81,8.62L12,2L9.19,8.62L2,9.24L7.46,13.97L5.82,21L12,17.27Z"
        ></path>
      </svg>
      <span>审核项目打分</span>
    </div>

    <NDataTable
      :columns="auditColumns"
      :data="auditItems"
      :bordered="false"
      :max-height="400"
      :loading="loading"
      :row-key="row => row.id"
      striped
    ></NDataTable>

    <div class="result-summary">
      <span class="result-label">总体评分：</span>
      <NTag
        :type="
          overallScore !== null
            ? overallScore >= 80
              ? 'success'
              : overallScore >= 60
                ? 'warning'
                : 'error'
            : 'default'
        "
      >
        {{ overallScore !== null ? `${overallScore}分` : '未完成' }}
      </NTag>
    </div>

    <!-- 拍照对话框 -->
    <NModal
      v-model:show="showPhotoDialog"
      style="width: 500px"
      preset="card"
      title="现场拍照"
      :bordered="false"
      :show-icon="false"
    >
      <div style="text-align: center">
        <div style="margin-bottom: 16px">
          <div
            style="
              width: 100%;
              height: 200px;
              background: #f5f5f5;
              border: 2px dashed #ccc;
              display: flex;
              align-items: center;
              justify-content: center;
              margin-bottom: 16px;
            "
          >
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="48" height="48" style="color: #ccc">
              <path
                fill="currentColor"
                d="M4,4H7L9,2H15L17,4H20A2,2 0 0,1 22,6V18A2,2 0 0,1 20,20H4A2,2 0 0,1 2,18V6A2,2 0 0,1 4,4M12,7A5,5 0 0,0 7,12A5,5 0 0,0 12,17A5,5 0 0,0 17,12A5,5 0 0,0 12,7M12,9A3,3 0 0,1 15,12A3,3 0 0,1 12,15A3,3 0 0,1 9,12A3,3 0 0,1 12,9Z"
              ></path>
            </svg>
          </div>
          <NInput v-model:value="photoDescription" placeholder="请输入照片描述" style="margin-bottom: 16px"></NInput>
        </div>
        <NSpace justify="center">
          <NButton @click="showPhotoDialog = false">取消</NButton>
          <NButton type="primary" @click="takePhoto">拍照保存</NButton>
        </NSpace>
      </div>
    </NModal>

    <!-- 证据管理对话框 -->
    <NModal
      v-model:show="showEvidenceDialog"
      style="width: 600px"
      preset="card"
      title="多媒体证据采集"
      :bordered="false"
      :show-icon="false"
    >
      <div>
        <div style="margin-bottom: 16px">
          <NSpace>
            <NButton type="info" @click="addEvidence('audio')">
              <template #icon>
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16">
                  <path
                    fill="currentColor"
                    d="M12,2A3,3 0 0,1 15,5V11A3,3 0 0,1 12,14A3,3 0 0,1 9,11V5A3,3 0 0,1 12,2M19,11C19,14.53 16.39,17.44 13,17.93V21H11V17.93C7.61,17.44 5,14.53 5,11H7A5,5 0 0,0 12,16A5,5 0 0,0 17,11H19Z"
                  ></path>
                </svg>
              </template>
              录音
            </NButton>
            <NButton type="success" @click="addEvidence('video')">
              <template #icon>
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16">
                  <path
                    fill="currentColor"
                    d="M17,10.5V7A1,1 0 0,0 16,6H4A1,1 0 0,0 3,7V17A1,1 0 0,0 4,18H16A1,1 0 0,0 17,17V13.5L21,17.5V6.5L17,10.5Z"
                  ></path>
                </svg>
              </template>
              录像
            </NButton>
            <NButton type="warning" @click="addEvidence('document')">
              <template #icon>
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16">
                  <path
                    fill="currentColor"
                    d="M6,2C4.89,2 4,2.89 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2H6M6,4H13V9H18V20H6V4Z"
                  ></path>
                </svg>
              </template>
              文档
            </NButton>
          </NSpace>
        </div>

        <div v-if="currentItem && currentItem.evidences.length > 0">
          <h4>已采集证据：</h4>
          <div
            v-for="evidence in currentItem.evidences"
            :key="evidence.id"
            style="margin-bottom: 8px; padding: 8px; background: #f5f5f5; border-radius: 4px"
          >
            <div>
              <strong>{{ getEvidenceTypeName(evidence.type) }}</strong>
              - {{ evidence.description }}
            </div>
            <div style="font-size: 12px; color: #666">{{ evidence.timestamp }}</div>
          </div>
        </div>
      </div>
    </NModal>

    <!-- 问题记录对话框 -->
    <NModal
      v-model:show="showIssueDialog"
      style="width: 500px"
      preset="card"
      title="问题记录与分类"
      :bordered="false"
      :show-icon="false"
    >
      <NForm>
        <NFormItem label="问题描述" required>
          <NInput
            v-model:value="issueForm.description"
            type="textarea"
            placeholder="请详细描述发现的问题"
            :rows="4"
          ></NInput>
        </NFormItem>
        <NFormItem label="严重程度" required>
          <NSelect v-model:value="issueForm.severity" :options="severityOptions" placeholder="请选择严重程度"></NSelect>
        </NFormItem>
        <NFormItem label="问题类别" required>
          <NSelect
            v-model:value="issueForm.category"
            :options="issueCategoryOptions"
            placeholder="请选择问题类别"
          ></NSelect>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="showIssueDialog = false">取消</NButton>
          <NButton type="primary" @click="recordIssue">保存问题</NButton>
        </NSpace>
      </template>
    </NModal>

    <!-- 沟通记录对话框 -->
    <NModal
      v-model:show="showCommunicationDialog"
      style="width: 500px"
      preset="card"
      title="现场沟通记录"
      :bordered="false"
      :show-icon="false"
    >
      <NForm>
        <NFormItem label="沟通内容" required>
          <NInput
            v-model:value="communicationForm.content"
            type="textarea"
            placeholder="请记录沟通的具体内容"
            :rows="4"
          ></NInput>
        </NFormItem>
        <NFormItem label="参与人员">
          <NInput v-model:value="communicationForm.participantName" placeholder="请输入参与沟通的人员姓名"></NInput>
        </NFormItem>
        <NFormItem label="沟通结果">
          <NInput v-model:value="communicationForm.result" placeholder="请记录沟通达成的结果或共识"></NInput>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="showCommunicationDialog = false">取消</NButton>
          <NButton type="primary" @click="recordCommunication">保存记录</NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<style scoped>
.section-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 16px;
  color: #333;
}

.section-icon {
  margin-right: 8px;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;
}

.progress-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  margin-bottom: 16px;
}

/* 响应式网格布局 */
@media (max-width: 1024px) {
  .progress-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 14px;
  }
}

@media (max-width: 480px) {
  .progress-cards {
    grid-template-columns: 1fr;
    gap: 12px;
  }
}

.progress-card {
  text-align: center;
}

.progress-item {
  padding: 8px;
}

.progress-number {
  font-size: 28px;
  font-weight: bold;
  color: #2080f0;
  margin-bottom: 8px;
}

.progress-label {
  font-size: 14px;
  color: #666;
}

.result-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-top: 24px;
}

.result-label {
  font-size: 16px;
  font-weight: bold;
  margin-right: 8px;
}

:deep(.n-form-item-label) {
  text-align: justify;
  text-align-last: justify;
}

:deep(.last-form-item .n-form-item-feedback-wrapper) {
  display: none;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .section-title {
    font-size: 16px;
  }

  .progress-number {
    font-size: 24px;
  }

  .result-summary {
    justify-content: center;
    flex-direction: column;
    gap: 8px;
  }
}

/* 表格响应式处理 */
:deep(.n-data-table) {
  width: 100%;
}

@media (max-width: 768px) {
  :deep(.n-data-table-wrapper) {
    overflow-x: auto;
  }

  :deep(.n-data-table th),
  :deep(.n-data-table td) {
    min-width: 80px;
  }
}
</style>
