<script setup lang="ts">
import { reactive, ref } from 'vue';
import { request } from '@/service/request';
import ApplicationInformation from './applicationInformation.vue';
import FileReview from './fileReview.vue';
import ComparisonTest from './comparisonTest.vue';

// 定义文件项接口
interface FileItem {
  id: number;
  name: string;
  type: string;
  status: string;
  size?: string;
  StandardKvid: string;
  Kvid: string;
}

// 定义测试项接口
interface TestItem {
  id: number;
  name: string;
  selected: boolean;
}

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

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

// 主体框架内置的第三方方法通过window对象暴露、供外部组件使用
// 获取消息提示
const message = (window as any).$message;

// 当前步骤
const currentStep = ref(0);

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

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

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

// 测试项目
const testItems = ref<TestItem[]>([
  { 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 saveAsDraft = ref(false);

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

// 表单引用
const formRef = ref<any>(null);

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

// 提取复杂的创建申请逻辑到单独函数
const createApplication = async () => {
  try {
    // 显示加载状态
    loading.value = true;

    // 构建请求参数
    const requestData = {
      // 这里是Item参数内容，用户可以自定义
      Item: {
        SupplierName: '江苏省纺织产品质量监督检验研究院',
        PayeeName: '江苏省纺织产品质量监督检验研究院',
        DemanderName: (window as any).$KiviiContext?.CurrentMember?.OrganizationName || '默认组织名称',
        DemanderKvid: (window as any).$KiviiContext?.CurrentMember?.OrganizationKvid || '',
        OperatorName: (window as any).$KiviiContext?.CurrentMember?.FullName || '默认用户',
        OperatorKvid: (window as any).$KiviiContext?.CurrentMember?.Kvid || '',
        TestNeedJudge: true,
        Quantity: '1',
        DealDate: formModel.applyDate,
        Status: 0,
        SampleManufacturerName: (window as any).$KiviiContext?.CurrentMember?.DepartmentName || '默认部门',
        SampleManufacturerKvid: (window as any).$KiviiContext?.CurrentMember?.DepartmentKvid || '',
        SampleManufacturerContactName: formModel.contactName,
        SampleManufacturerContactNumber: formModel.contactPhone,
        SampleManufacturerAddress: formModel.labAddress,
        SampleName: formModel.labName,
        TemplateName: '默认模板',
        Remark: formModel.remarks
      }
    };

    // 调用创建接口
    const { data, error } = await request({
      url: '/Restful/Kivii.Lims.Entities.Report/Create.json',
      method: 'post',
      data: requestData
    });

    if (error) {
      console.error('保存申请信息失败:', error);
      message.error('保存失败，请重试');
      return;
    }

    if (data.Results.length > 0) {
      // 保留完整的原始数据结构，同时保持展示字段的兼容性
      Object.assign(formModel, {
        ...data.Results[0], // 保留所有原始字段
        kvid: data.Results[0].Kvid, // 保持kvid字段兼容性
        labName: formModel.labName, // 保持表单字段
        labAddress: formModel.labAddress,
        contactName: formModel.contactName,
        contactPhone: formModel.contactPhone,
        applyDate: formModel.applyDate,
        remarks: formModel.remarks
      });

      message.success('申请信息保存成功');
      // 保存成功后进入下一步
      currentStep.value += 1;
    } else {
      message.error('保存失败，请重试');
    }
  } catch (error) {
    console.error('保存申请信息失败:', error);
    message.error('系统错误，请稍后重试');
  } finally {
    // 隐藏加载状态
    loading.value = false;
  }
};

// 提取复杂的创建申请逻辑到单独函数
const updateApplication = async () => {
  try {
    // 显示加载状态
    loading.value = true;

    // 构建请求参数
    const requestData = {
      // 这里是Item参数内容，用户可以自定义
      Item: {
        DealDate: formModel.applyDate,
        SampleManufacturerContactName: formModel.contactName,
        SampleManufacturerContactNumber: formModel.contactPhone,
        SampleManufacturerAddress: formModel.labAddress,
        SampleName: formModel.labName,
        Remark: formModel.remarks,
        Kvid: formModel.kvid
      }
    };

    // 调用创建接口
    const { data, error } = await request({
      url: '/Restful/Kivii.Lims.Entities.Report/Update.json',
      method: 'post',
      data: requestData
    });

    if (error) {
      console.error('保存申请信息失败:', error);
      message.error('保存失败，请重试');
      return;
    }

    if (data.Results.length > 0) {
      // 保留完整的原始数据结构，同时保持展示字段的兼容性
      Object.assign(formModel, {
        ...data.Results[0], // 保留所有原始字段
        kvid: data.Results[0].Kvid, // 保持kvid字段兼容性
        labName: formModel.labName, // 保持表单字段
        labAddress: formModel.labAddress,
        contactName: formModel.contactName,
        contactPhone: formModel.contactPhone,
        applyDate: formModel.applyDate,
        remarks: formModel.remarks
      });

      message.success('申请信息保存成功');
      // 保存成功后进入下一步
      currentStep.value += 1;
    } else {
      message.error('保存失败，请重试');
    }
  } catch (error) {
    console.error('保存申请信息失败:', error);
    message.error('系统错误，请稍后重试');
  } finally {
    // 隐藏加载状态
    loading.value = false;
  }
};

// 下一步
function nextStep() {
  if (currentStep.value < 2) {
    // 如果当前是第一步（申请信息填写），则调用创建接口
    if (currentStep.value === 0) {
      // 如果已经存在Kvid，则直接进入下一步
      if (formModel.kvid) {
        updateApplication();
        return;
      }

      // 验证表单
      formRef.value?.validate(async (errors: any) => {
        if (errors) {
          message.error('请完善必填信息');
          return;
        }

        await createApplication();
      });
    } else {
      // 不是第一步，直接进入下一步
      currentStep.value += 1;
    }
  }
}

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

// 保存申请
function saveApplication() {
  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' : '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"
          :form-model="formModel"
          :availability-data="availabilityData"
        ></ApplicationInformation>

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

        <!-- 步骤3: 比对测试选择 -->
        <ComparisonTest
          v-if="currentStep === 2"
          :test-items="testItems"
          :save-as-draft="saveAsDraft"
          @update:test-items="(newItems: TestItem[]) => (testItems = newItems)"
          @update:save-as-draft="(value: boolean) => (saveAsDraft = value)"
        ></ComparisonTest>
      </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">
            <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;
}

.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: fit-content;
  margin: 0 auto;
}

/* 确保步骤之间的连接线正常显示 */
:deep(.n-step-splitor) {
  display: block !important;
  width: 560px !important;
}

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

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

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