<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch, withDefaults } from 'vue';
import { number } from 'echarts';
import ApplicationInformation from './applicationInformation.vue'; // '/codes/applicationInformation.vue';
import FileReview from './fileReview.vue'; // '/codes/fileReview.vue';
import ComparisonTest from './comparisonTest.vue'; // '/codes/comparisonTest.vue';
// import FieldReviewPlanning from './fieldReviewPlanning.vue'; // '/codes/fieldReviewPlanning.vue';
// import FieldReviewExecution from './fieldReviewExecution.vue'; // '/codes/fieldReviewExecution.vue';

// 定义Item对象的接口
interface ItemProps {
  Kvid?: string;
  [key: string]: any;
}

// 定义props
const props = withDefaults(
  defineProps<{
    item?: ItemProps;
  }>(),
  {
    item: () => ({})
  }
);

// 定义emit事件
const emit = defineEmits(['close-and-refresh']);

// 返回列表并刷新数据
const handleClose = () => {
  // console.log('返回列表并刷新数据');
  // 发送关闭并刷新数据的信号
  emit('close-and-refresh');
};

// 主体框架内置的第三方方法通过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 currentStep = ref(0);

// 记录已访问过的步骤（用于优化数据加载）
const visitedSteps = ref(new Set([0])); // 默认第一步已访问

// 加载状态
const loading = ref(false);

// 表单数据 - 直接使用props.item作为formModel
const formModel = reactive<ItemProps>({});

// 监听props.item变化，同步到formModel
watch(
  () => props.item,
  newItem => {
    // 保持formModel为props.item的响应式副本
    Object.assign(formModel, newItem || {});
  },
  { immediate: true, deep: true }
);

// 定义FileItem接口，与FileReview组件保持一致
interface FileItem {
  id?: number;
  Kvid: string;
  StandardKvid: string;
  Title?: string;
  Code?: string;
  Unit?: string;
  QualifiedValue?: string;
  Description?: string;
  StatusType?: string;
  ReportKvid?: string;
  // 兼容原有字段
  name?: string;
  type?: string;
  status?: string;
  size?: string;
  [key: string]: any;
}

// 文件列表
const fileList = ref<FileItem[]>([]);

// 测试项目
const testItems = ref([
  { id: 1, name: '化学成分分析', selected: false },
  { id: 2, name: '物理性能测试', selected: false },
  { id: 3, name: '微生物检测', selected: false },
  { id: 4, name: '无损检测', selected: false },
  { id: 5, name: '电气安全测试', selected: false },
  { id: 6, name: '环境模拟测试', selected: false }
]);

// 验证规则
const rules = {
  SampleName: {
    required: true,
    trigger: ['blur', 'input'],
    message: '请输入实验室名称'
  }
};

// 表单引用
const formRef = ref<any>(null);
// 添加applicationInformation组件引用
const appInfoRef = ref<any>(null);

// 评审资源可用性数据
const availabilityData = reactive({
  morning: { total: 5, booked: 2 },
  afternoon: { total: 5, booked: 1 },
  evening: { total: 3, booked: 3 }
});

// 下一步
function nextStep() {
  if (currentStep.value < 2) {
    // 修改为2，因为只有3个步骤
    // 如果当前是第一步（申请信息填写），则调用子组件的创建接口
    if (currentStep.value === 0) {
      // // 如果已经存在Kvid（从props的Item或formModel中），则直接进入下一步
      // if ((props.item && props.item.Kvid) || formModel.Kvid) {
      //   console.log('已存在Kvid，直接进入下一步');
      //   currentStep.value += 1;
      //   visitedSteps.value.add(currentStep.value);
      //   return;
      // }

      // 使用ref获取到的组件实例
      if (appInfoRef.value && typeof appInfoRef.value.validateAndSave === 'function') {
        // 调用子组件的验证和保存方法
        appInfoRef.value.validateAndSave().then((success: boolean) => {
          if (success) {
            // 保存成功后进入下一步，并获取返回的Kvid
            Object.assign(formModel, appInfoRef.value.detailedData);
            currentStep.value += 1;
            // 记录新访问的步骤
            visitedSteps.value.add(currentStep.value);
          }
        });
      } else {
        message.error('组件引用获取失败，请刷新页面重试');
      }
    } else {
      // 不是第一步，直接进入下一步
      currentStep.value += 1;
      // 记录新访问的步骤
      visitedSteps.value.add(currentStep.value);
    }
  }
}

// 上一步
function prevStep() {
  if (currentStep.value > 0) {
    currentStep.value -= 1;
    // 上一步时不需要添加到visitedSteps，因为已经访问过了
  }
}

// 保存申请
function saveApplication(submit = true) {
  formRef.value?.validate((errors: any) => {
    if (errors) {
      message.error('请完善必填信息');
      return;
    }

    message.success('申请提交成功');
    /* console.log('Submit application:', {
      form: formModel,
      files: fileList.value,
      tests: testItems.value.filter(item => item.selected)
    }); */
  });
}
</script>

<template>
  <div class="apply-page-container">
    <!-- 添加顶部导航栏 -->
    <div class="header">
      <NButton quaternary class="back-button" @click="handleClose">
        <template #icon>
          <NIcon>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
              <path fill="currentColor" d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z" />
            </svg>
          </NIcon>
        </template>
        返回
      </NButton>
    </div>

    <NCard style="margin-bottom: 10px">
      <div class="page-header">
        <div style="width: 100%; display: flex; align-items: center">
          <!-- 第一步 -->
          <div style="flex: 1; text-align: center; position: relative">
            <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 12px">
              <div
                :style="{
                  width: '32px',
                  height: '32px',
                  borderRadius: '50%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '14px',
                  fontWeight: 'bold',
                  backgroundColor: currentStep >= 0 ? '#2080f0' : '#f0f0f0',
                  color: currentStep >= 0 ? 'white' : '#999',
                  border: currentStep === 0 ? '2px solid #2080f0' : 'none'
                }"
              >
                {{ currentStep > 0 ? '✓' : '1' }}
              </div>
            </div>
            <div
              :style="{
                fontSize: '14px',
                color: currentStep === 0 ? '#2080f0' : '#333',
                fontWeight: currentStep === 0 ? 'bold' : 'normal'
              }"
            >
              申请信息填写
            </div>
          </div>

          <!-- 连接线1 -->
          <div style="flex: 0 0 80px; height: 2px; background: #e0e0e0; margin: 0 20px; margin-bottom: 30px"></div>

          <!-- 第二步 -->
          <div style="flex: 1; text-align: center; position: relative">
            <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 12px">
              <div
                :style="{
                  width: '32px',
                  height: '32px',
                  borderRadius: '50%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '14px',
                  fontWeight: 'bold',
                  backgroundColor: currentStep >= 1 ? '#2080f0' : '#f0f0f0',
                  color: currentStep >= 1 ? 'white' : '#999',
                  border: currentStep === 1 ? '2px solid #2080f0' : 'none'
                }"
              >
                {{ currentStep > 1 ? '✓' : '2' }}
              </div>
            </div>
            <div
              :style="{
                fontSize: '14px',
                color: currentStep === 1 ? '#2080f0' : '#333',
                fontWeight: currentStep === 1 ? 'bold' : 'normal'
              }"
            >
              审核文件提交
            </div>
          </div>

          <!-- 连接线2 -->
          <div style="flex: 0 0 80px; height: 2px; background: #e0e0e0; margin: 0 20px; margin-bottom: 30px"></div>

          <!-- 第三步 -->
          <div style="flex: 1; text-align: center; position: relative">
            <div style="display: flex; align-items: center; justify-content: center; margin-bottom: 12px">
              <div
                :style="{
                  width: '32px',
                  height: '32px',
                  borderRadius: '50%',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  fontSize: '14px',
                  fontWeight: 'bold',
                  backgroundColor: currentStep >= 2 ? '#2080f0' : '#f0f0f0',
                  color: currentStep >= 2 ? 'white' : '#999',
                  border: currentStep === 2 ? '2px solid #2080f0' : 'none'
                }"
              >
                {{ currentStep > 2 ? '✓' : '3' }}
              </div>
            </div>
            <div
              :style="{
                fontSize: '14px',
                color: currentStep === 2 ? '#2080f0' : '#333',
                fontWeight: currentStep === 2 ? 'bold' : 'normal'
              }"
            >
              比对测试选择
            </div>
          </div>
        </div>
      </div>
    </NCard>

    <NCard :bordered="false" class="form-card" size="huge">
      <NForm
        ref="formRef"
        :model="formModel"
        label-placement="left"
        label-width="120px"
        require-mark-placement="right-hanging"
        size="medium"
      >
        <!-- 步骤1: 申请信息填写 -->
        <ApplicationInformation
          v-if="visitedSteps.has(0) && currentStep === 0"
          ref="appInfoRef"
          :item="formModel"
          :active="currentStep === 0"
        ></ApplicationInformation>

        <!-- 步骤2: 审核文件提交 -->
        <FileReview
          v-if="visitedSteps.has(1) && currentStep === 1"
          :item="formModel"
          :active="currentStep === 1"
          @update:file-list="newList => (fileList = newList)"
        ></FileReview>

        <!-- 步骤3: 比对测试选择 -->
        <ComparisonTest
          v-if="visitedSteps.has(2) && currentStep === 2"
          :test-items="testItems"
          :save-as-draft="false"
          :active="currentStep === 2"
          @update:test-items="newItems => (testItems = newItems)"
        ></ComparisonTest>
        <!--
        步骤4: 现场审核规划
        <FieldReviewPlanning v-show="currentStep === 3"></FieldReviewPlanning>

        步骤5: 现场审核执行
        <FieldReviewExecution v-show="currentStep === 4"></FieldReviewExecution> 
-->
      </NForm>
      <NDivider></NDivider>
      <div>
        <NSpace justify="center">
          <NButton v-if="currentStep > 0" round @click="prevStep">上一步</NButton>

          <NButton v-if="currentStep < 2" type="primary" round @click="nextStep">下一步</NButton>

          <NPopconfirm v-if="currentStep == 2" @positive-click="saveApplication(true)">
            <template #trigger>
              <NButton type="primary" round>
                <template #icon>
                  <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16">
                    <path fill="currentColor" d="M2,21L23,12L2,3V10L17,12L2,14V21Z"></path>
                  </svg>
                </template>
                保存申请
              </NButton>
            </template>
            确认保存此申请吗？
          </NPopconfirm>
        </NSpace>
      </div>
    </NCard>
  </div>
</template>

<style scoped>
.apply-page-container {
  /* padding: 14px; */
  /* min-height: 100vh; */
  width: 100%;
}

/* 响应式容器 */
@media (max-width: 768px) {
  .apply-page-container {
    padding: 5px;
  }
}

@media (max-width: 480px) {
  .apply-page-container {
    padding: 5px;
  }
}

.page-header {
  text-align: center;
  justify-content: center;
  align-items: center;
  /* margin-bottom: 0px; */
}

.form-card {
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

/* 自定义步骤条样式已移至内联样式 */

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

.contact-tags {
  min-height: 32px;
}

.empty-tip {
  color: #999;
  font-size: 13px;
  font-style: italic;
}

.time-slot-card {
  transition: all 0.3s;
  border: 1px solid #eaeaea;
}

.time-slot-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
}

.time-slot-full {
  opacity: 0.6;
}

.time-slot-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.availability {
  font-size: 24px;
  font-weight: bold;
  color: #0072ff;
}

.summary-card {
  background-color: #f9fbff;
}

.summary-item {
  margin-bottom: 16px;
}

.summary-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.summary-value {
  font-size: 15px;
  color: #333;
}

.upload-hint {
  color: #999;
  font-size: 13px;
  margin-top: 8px;
}

.mt-4 {
  margin-top: 16px;
}

.mt-6 {
  margin-top: 24px;
}

/* .mt-8 {
  margin-top: 20px;
} */

.text-sm {
  font-size: 14px;
}

.text-gray-400 {
  color: #9ca3af;
}

/* 步骤在小屏幕上的响应式处理 */
@media (max-width: 768px) {
  .page-header > div {
    flex-direction: column;
    gap: 20px;
  }

  .page-header > div > div[style*='flex: 0 0 80px'] {
    display: none;
  }
}

/* 添加顶部导航栏样式 */
.header {
  display: flex;
  align-items: center;
  /* margin-bottom: 20px; */
  gap: 16px;
}

.back-button {
  font-size: 14px;
}
</style>
