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

interface AuditScheme {
  id: string;
  name: string;
  labType: string;
  level: string;
  description: string;
  items: Array<{
    id: string;
    name: string;
    category: string;
    weight: number;
  }>;
}

interface AuditTeamMember {
  id: string;
  name: string;
  profession: string;
  level: string;
  phone: string;
  email: string;
  available: boolean;
}

// 主体框架内置的第三方方法通过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 labType = ref('');
const labLevel = ref('');
const selectedScheme = ref('');
const customSchemeItems = ref<Array<any>>([]);
const selectedTeamMembers = ref<string[]>([]);
const auditDate = ref<number | null>(null);
const auditDuration = ref(1);

// 状态变量
const loading = ref<boolean>(false);
const schemesLoading = ref<boolean>(false);
const teamLoading = ref<boolean>(false);

// 审核方案库
const auditSchemes = ref<AuditScheme[]>([]);
const auditTeam = ref<AuditTeamMember[]>([]);

// 实验室类型选项
const labTypeOptions = [
  { label: '检测实验室', value: 'testing' },
  { label: '校准实验室', value: 'calibration' },
  { label: '医学实验室', value: 'medical' },
  { label: '司法鉴定实验室', value: 'forensic' }
];

// 实验室级别选项
const labLevelOptions = [
  { label: '国家级', value: 'national' },
  { label: '省级', value: 'provincial' },
  { label: '市级', value: 'municipal' },
  { label: '县级', value: 'county' }
];

// 审核时长选项
const durationOptions = [
  { label: '1天', value: 1 },
  { label: '2天', value: 2 },
  { label: '3天', value: 3 },
  { label: '5天', value: 5 }
];

// 审核方案表格列定义
const schemeColumns = [
  { title: '方案名称', key: 'name' },
  { title: '适用类型', key: 'labType', align: 'center' as const },
  { title: '适用级别', key: 'level', align: 'center' as const },
  { title: '描述', key: 'description' },
  {
    title: '操作',
    key: 'actions',
    width: 150,
    align: 'center' as const,
    render(row: AuditScheme) {
      return h('div', { style: 'display: flex; gap: 8px; justify-content: center;' }, [
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            type: 'primary',
            onClick: () => selectScheme(row)
          },
          { default: () => '选择' }
        ),
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            onClick: () => previewScheme(row)
          },
          { default: () => '预览' }
        )
      ]);
    }
  }
];

// 审核团队表格列定义
const teamColumns = [
  {
    title: '选择',
    key: 'select',
    width: 60,
    align: 'center' as const,
    render(row: AuditTeamMember) {
      return h(resolveComponent('n-checkbox'), {
        checked: selectedTeamMembers.value.includes(row.id),
        onUpdateChecked: (checked: boolean) => {
          if (checked) {
            selectedTeamMembers.value.push(row.id);
          } else {
            const index = selectedTeamMembers.value.indexOf(row.id);
            if (index > -1) {
              selectedTeamMembers.value.splice(index, 1);
            }
          }
        }
      });
    }
  },
  { title: '姓名', key: 'name' },
  { title: '专业', key: 'profession' },
  { title: '级别', key: 'level', align: 'center' as const },
  { title: '电话', key: 'phone' },
  { title: '邮箱', key: 'email' },
  {
    title: '状态',
    key: 'available',
    align: 'center' as const,
    render(row: AuditTeamMember) {
      return h(
        resolveComponent('n-tag'),
        { type: row.available ? 'success' : 'warning' },
        { default: () => (row.available ? '可用' : '忙碌') }
      );
    }
  }
];

// 定制方案项目表格列定义
const customItemColumns = [
  { title: '审核项目', key: 'name' },
  { title: '类别', key: 'category', align: 'center' as const },
  { title: '权重', key: 'weight', align: 'center' as const },
  {
    title: '操作',
    key: 'actions',
    width: 120,
    align: 'center' as const,
    render(row: any, index: number) {
      return h('div', { style: 'display: flex; gap: 8px; justify-content: center;' }, [
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            type: 'error',
            onClick: () => removeCustomItem(index)
          },
          { default: () => '删除' }
        )
      ]);
    }
  }
];

// 获取审核方案库
async function fetchAuditSchemes() {
  try {
    schemesLoading.value = true;

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

    auditSchemes.value = [
      {
        id: '1',
        name: 'ISO/IEC 17025 检测实验室标准方案',
        labType: '检测实验室',
        level: '国家级',
        description: '适用于ISO/IEC 17025标准的检测实验室审核',
        items: [
          { id: '1-1', name: '管理体系', category: '管理要求', weight: 30 },
          { id: '1-2', name: '技术要求', category: '技术要求', weight: 40 },
          { id: '1-3', name: '设备设施', category: '技术要求', weight: 20 },
          { id: '1-4', name: '人员资质', category: '管理要求', weight: 10 }
        ]
      },
      {
        id: '2',
        name: 'ISO 15189 医学实验室标准方案',
        labType: '医学实验室',
        level: '省级',
        description: '适用于ISO 15189标准的医学实验室审核',
        items: [
          { id: '2-1', name: '质量管理', category: '管理要求', weight: 25 },
          { id: '2-2', name: '检验前过程', category: '技术要求', weight: 25 },
          { id: '2-3', name: '检验过程', category: '技术要求', weight: 30 },
          { id: '2-4', name: '检验后过程', category: '技术要求', weight: 20 }
        ]
      }
    ];

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

// 获取审核团队
async function fetchAuditTeam() {
  try {
    teamLoading.value = true;

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

    auditTeam.value = [
      {
        id: '1',
        name: '张专家',
        profession: '化学分析',
        level: '高级审核员',
        phone: '13800138001',
        email: 'zhang@example.com',
        available: true
      },
      {
        id: '2',
        name: '李教授',
        profession: '物理检测',
        level: '主任审核员',
        phone: '13800138002',
        email: 'li@example.com',
        available: true
      },
      {
        id: '3',
        name: '王工程师',
        profession: '微生物',
        level: '审核员',
        phone: '13800138003',
        email: 'wang@example.com',
        available: false
      },
      {
        id: '4',
        name: '赵博士',
        profession: '环境监测',
        level: '高级审核员',
        phone: '13800138004',
        email: 'zhao@example.com',
        available: true
      }
    ];

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

// 根据类型和级别筛选方案
const filteredSchemes = computed(() => {
  return auditSchemes.value.filter(scheme => {
    const typeMatch = !labType.value || scheme.labType === labType.value;
    const levelMatch = !labLevel.value || scheme.level === labLevel.value;
    return typeMatch && levelMatch;
  });
});

// 选择方案
function selectScheme(scheme: AuditScheme) {
  selectedScheme.value = scheme.id;
  customSchemeItems.value = [...scheme.items];
  message.success(`已选择方案：${scheme.name}`);
}

// 预览方案
function previewScheme(scheme: AuditScheme) {
  dialog.info({
    title: `方案预览：${scheme.name}`,
    content: () => {
      const itemList = scheme.items.map(item => `• ${item.name} (${item.category}, 权重: ${item.weight}%)`).join('\n');
      return `描述：${scheme.description}\n\n审核项目：\n${itemList}`;
    },
    positiveText: '确认'
  });
}

// 添加自定义项目
function addCustomItem() {
  customSchemeItems.value.push({
    id: `custom-${Date.now()}`,
    name: '',
    category: '管理要求',
    weight: 0
  });
}

// 删除自定义项目
function removeCustomItem(index: number) {
  customSchemeItems.value.splice(index, 1);
}

// 查询方案
function searchSchemes() {
  fetchAuditSchemes();
}

// 页面加载时获取数据
onMounted(() => {
  fetchAuditSchemes();
  fetchAuditTeam();
});
</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="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z"
        ></path>
      </svg>
      <span>现场审核方案库</span>
    </div>

    <NFormItem label="实验室类型">
      <NSelect
        v-model:value="labType"
        :options="labTypeOptions"
        placeholder="请选择实验室类型"
        class="responsive-select"
        clearable
      ></NSelect>
    </NFormItem>

    <NFormItem label="实验室级别">
      <NSelect
        v-model:value="labLevel"
        :options="labLevelOptions"
        placeholder="请选择实验室级别"
        class="responsive-select"
        clearable
      ></NSelect>
    </NFormItem>

    <NFormItem label="" class="last-form-item">
      <NButton type="primary" :loading="schemesLoading" @click="searchSchemes">
        <template #icon>
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16">
            <path
              fill="currentColor"
              d="M9.5,3A6.5,6.5 0 0,1 16,9.5C16,11.11 15.41,12.59 14.44,13.73L14.71,14H15.5L20.5,19L19,20.5L14,15.5V14.71L13.73,14.44C12.59,15.41 11.11,16 9.5,16A6.5,6.5 0 0,1 3,9.5A6.5,6.5 0 0,1 9.5,3M9.5,5C7,5 5,7 5,9.5C5,12 7,14 9.5,14C12,14 14,12 14,9.5C14,7 12,5 9.5,5Z"
            ></path>
          </svg>
        </template>
        查询方案
      </NButton>
    </NFormItem>

    <NDataTable
      :columns="schemeColumns"
      :data="filteredSchemes"
      :bordered="false"
      :max-height="250"
      :loading="schemesLoading"
      :row-key="row => row.id"
      striped
    ></NDataTable>

    <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="M20.71,7.04C21.1,6.65 21.1,6 20.71,5.63L18.37,3.29C18,2.9 17.35,2.9 16.96,3.29L15.12,5.12L18.87,8.87M3,17.25V21H6.75L17.81,9.93L14.06,6.18L3,17.25Z"
        ></path>
      </svg>
      <span>审核方案定制</span>
    </div>

    <div style="margin-bottom: 16px">
      <NButton type="primary" @click="addCustomItem">
        <template #icon>
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16">
            <path fill="currentColor" d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z"></path>
          </svg>
        </template>
        添加审核项目
      </NButton>
    </div>

    <NDataTable
      :columns="customItemColumns"
      :data="customSchemeItems"
      :bordered="false"
      :max-height="200"
      :row-key="row => row.id"
      striped
    ></NDataTable>

    <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="M16,4C18.21,4 20,5.79 20,8C20,10.21 18.21,12 16,12C13.79,12 12,10.21 12,8C12,5.79 13.79,4 16,4M16,5.9A2.1,2.1 0 0,0 13.9,8A2.1,2.1 0 0,0 16,10.1A2.1,2.1 0 0,0 18.1,8A2.1,2.1 0 0,0 16,5.9M16,13C18.67,13 22,14.33 22,17V20H10V17C10,14.33 13.33,13 16,13M8,12C10.21,12 12,10.21 12,8C12,5.79 10.21,4 8,4C5.79,4 4,5.79 4,8C4,10.21 5.79,12 8,12M8,13C5.33,13 0,14.33 0,17V20H8V17C8,15.9 8.6,14.93 9.5,14.3C8.61,14.11 7.8,14 7,14H9C8.39,14.39 8,15.14 8,16V20H2V17C2,16.36 4.77,15 8,15C9.83,15 10.54,15.2 11.78,15.61C14.09,14.75 16,14.42 16,15.61V20H22V17C22,14.33 18.67,13 16,13Z"
        ></path>
      </svg>
      <span>审核团队组建 (已选择 {{ selectedTeamMembers.length }} 人)</span>
    </div>

    <NDataTable
      :columns="teamColumns"
      :data="auditTeam"
      :bordered="false"
      :max-height="250"
      :loading="teamLoading"
      :row-key="row => row.id"
      striped
    ></NDataTable>

    <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="M9,10V12H7V10H9M13,10V12H11V10H13M17,10V12H15V10H17M19,3A2,2 0 0,1 21,5V19A2,2 0 0,1 19,21H5C3.89,21 3,20.1 3,19V5A2,2 0 0,1 5,3H6V1H8V3H16V1H18V3H19M19,19V8H5V19H19M9,14V16H7V14H9M13,14V16H11V14H13M17,14V16H15V14H17Z"
        ></path>
      </svg>
      <span>审核行程规划</span>
    </div>

    <NFormItem label="审核日期" required>
      <NDatePicker
        v-model:value="auditDate"
        type="date"
        clearable
        class="responsive-date-picker"
        format="yyyy/MM/dd"
      ></NDatePicker>
    </NFormItem>

    <NFormItem label="审核时长" class="last-form-item" required>
      <NSelect
        v-model:value="auditDuration"
        :options="durationOptions"
        placeholder="请选择审核时长"
        class="responsive-select"
      ></NSelect>
    </NFormItem>

    <div class="result-summary">
      <span class="result-label">规划状态：</span>
      <NTag type="info">{{ selectedScheme ? '已制定方案' : '待制定方案' }}</NTag>
    </div>
  </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;
}

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

/* 响应式表单元素 */
.responsive-select {
  width: 300px;
  min-width: 200px;
}

.responsive-date-picker {
  width: 400px;
  min-width: 300px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .responsive-select,
  .responsive-date-picker {
    width: 100%;
    min-width: auto;
  }

  .section-title {
    font-size: 16px;
  }

  .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;
  }
}
</style>
