<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch, withDefaults } from 'vue';
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(3);

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

// 表单数据
const formModel = reactive({
  labName: '',
  labAddress: '',
  contactName: '',
  contactPhone: '',
  contactEmail: '',
  applyDate: null as number | null,
  applyTime: null as number | null,
  remarks: '',
  Kvid: ''
});

// 监听传入的Item变化
watch(
  () => props.Item,
  newItem => {
    if (newItem && newItem.Kvid) {
      // 将传入的Item中的Kvid设置到formModel中
      formModel.Kvid = newItem.Kvid;
    }
  },
  { immediate: true, deep: true }
);

// 文件列表
const fileList = ref<
  Array<{
    id: number;
    name: string;
    type: string;
    status: string;
    size?: string;
  }>
>([]);

// 测试项目
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 = {
  labName: {
    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 < 4) {
    // 如果当前是第一步（申请信息填写），则调用子组件的创建接口
    if (currentStep.value === 0) {
      // 如果已经存在Kvid（从props的Item或formModel中），则直接进入下一步
      if ((props.Item && props.Item.Kvid) || formModel.Kvid) {
        console.log('已存在Kvid，直接进入下一步');
        currentStep.value += 1;
        return;
      }

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

// 上一步
function prevStep() {
  if (currentStep.value > 0) {
    currentStep.value -= 1;
  }
}

// 保存申请
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">
        <NSteps :current="currentStep" class="mt-8">
          <NStep title="申请信息填写" :status="currentStep === 0 ? 'process' : 'finish'"></NStep>
          <NStep
            title="审核文件提交"
            :status="currentStep === 1 ? 'process' : currentStep > 1 ? 'finish' : 'wait'"
          ></NStep>
          <NStep
            title="比对测试选择"
            :status="currentStep === 2 ? 'process' : currentStep > 2 ? 'finish' : 'wait'"
          ></NStep>
          <NStep
            title="现场审核规划"
            :status="currentStep === 3 ? 'process' : currentStep > 3 ? 'finish' : 'wait'"
          ></NStep>
          <NStep title="现场审核执行" :status="currentStep === 4 ? 'process' : 'wait'"></NStep>
        </NSteps>
      </div>
    </NCard>

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

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

        <!-- 步骤3: 比对测试选择 -->
        <ComparisonTest
          v-if="currentStep === 2"
          :test-items="testItems"
          :save-as-draft="false"
          @update:test-items="newItems => (testItems = newItems)"
        ></ComparisonTest>

        <!-- 步骤4: 现场审核规划 -->
        <FieldReviewPlanning v-if="currentStep === 3"></FieldReviewPlanning>

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

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

          <NPopconfirm v-if="currentStep === 4" @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: 24px;
  min-height: 100vh;
  width: 100%;
}

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

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

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

/* 强制设置当前步骤样式 */
:deep(.n-step--process .n-step-indicator) {
  background-color: #2080f0 !important;
  color: white !important;
}

:deep(.n-step--process .n-step-header__title) {
  color: #2080f0 !important;
  font-weight: bold !important;
}

:deep(.n-step--process .n-step-header__description) {
  color: #2080f0 !important;
}

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

/* 隐藏最后一个步骤的横线 */
:deep(.n-steps .n-step:last-child .n-step-splitor) {
  display: none;
}

/* 调整步骤组件布局，去除右侧空白 */
:deep(.n-steps) {
  width: 100%;
  margin: 0 auto;
}

/* 确保步骤之间的连接线自适应显示 */
:deep(.n-step-splitor) {
  display: block !important;
  width: auto !important;
  flex: 1 !important;
}

/* 只隐藏最后一个步骤的连接线 */
:deep(.n-steps .n-step:last-child .n-step-splitor) {
  display: none !important;
}

/* 步骤在小屏幕上的响应式处理 */
@media (max-width: 768px) {
  :deep(.n-steps) {
    max-width: 100%;
  }

  :deep(.n-step-header__title) {
    font-size: 14px !important;
  }
}

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

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