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

// 只保留kvid的prop，移除formModel和availabilityData
const props = defineProps({
  kvid: {
    type: String,
    default: ''
  }
});

// 主体框架内置的第三方方法通过window对象暴露、供外部组件使用
const axios = (window as any).$axios;
// 获取主题状态
const themeStore = (window as any).$themeStore;
// 获取消息提示
const message = (window as any).$message;
// 通过计算属性确定当前的主体色
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 labNameOptions = ref<Array<{ label: string; value: string }>>([]);
// 存储 API 获取的实验室完整数据（包含地址等信息）
const apiLabOptions = ref<Array<{
  label: string;
  value: string;
  address?: string;
  kvid?: string;
}>>([]);
const searchInputValue = ref('');
const loading = ref(false);

// 后缀列表，用于生成模糊匹配选项
const suffixList = ['实验室', '研究中心', '技术研究所'];

// 存储API返回的详细数据
const detailedData = ref<any>({});

// 记录当前已加载的kvid，避免重复请求
const loadedKvid = ref('');

// 创建一个通用的日期处理函数
const createDateComputed = (getter: () => string | null, setter: (val: string | null) => void) => {
  return computed({
    get: () => {
      const value = getter()
      return value ? new Date(value) : null
    },
    set: (val: any) => {
      if (!val) {
        setter(null)
        return
      }
      
      try {
        // 确保val是Date对象
        const dateVal = val instanceof Date ? val : new Date(val)
        // 检查是否是有效日期
        if (!isNaN(dateVal.getTime())) {
          // 格式化为ISO字符串
          const formattedDate = dateVal.toISOString()
          setter(formattedDate)
        } else {
          console.warn('无效的日期值:', val)
          setter(null)
        }
      } catch (err) {
        console.error('日期处理错误:', err)
        setter(null)
      }
    }
  })
}

// 创建处理后的CreateTime计算属性
const formattedCreateTime = createDateComputed(
  () => detailedData.value.CreateTime,
  (val) => detailedData.value.CreateTime = val
)

// 获取详情数据
const fetchDetail = async (kvid: string) => {
  if (!kvid) return;
  
  console.log(`准备获取详情数据，Kvid: ${kvid}，当前loadedKvid: ${loadedKvid.value}`);
  if (kvid === loadedKvid.value && Object.keys(detailedData.value).length > 0) {
    console.log('跳过重复请求，使用已缓存的数据');
    return;
  }
  
  loading.value = true;
  try {
    console.log('开始获取详情数据，Kvid:', kvid);
    // 调用接口获取详情数据
    const response = await axios.get(`/Restful/Kivii.Lims.Entities.Report/Read.json?Kvid=${kvid}`);
    
    if (response.data) {
      // 直接赋值给detailedData
      detailedData.value = response.data.Result || {};
      console.log('获取到详情数据:', response.data.Result);
      
      // 更新已加载的kvid
      loadedKvid.value = kvid;
      
      message.success('详情数据加载成功');
    } else {
      message.error('获取详情数据失败');
    }
  } catch (error) {
    console.error('获取详情数据失败:', error);
    message.error('获取详情数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};

// 监听输入值变化，实时更新选项
watch(searchInputValue, (newVal) => {
  if (newVal) {
    updateOptions(newVal);
  }
});

// 监听kvid的变化，如果有值则获取详情数据
watch(() => props.kvid, (newKvid) => {
  if (newKvid && newKvid !== loadedKvid.value) {
    loadedKvid.value = newKvid;
    fetchDetail(newKvid);
  }
}, { immediate: true });

// 更新选项列表，包括API数据和模糊匹配
const updateOptions = (query: any) => {
  console.log('更新选项:', query);
  
  // 确保 query 是字符串类型
  const queryStr = typeof query === 'string' ? query : '';
  
  // 首先基于API获取的数据进行过滤
  const filteredApiOptions = apiLabOptions.value.filter(item => 
    !queryStr || item.label.toLowerCase().includes(queryStr.toLowerCase())
  );
    
  // 创建带后缀的选项列表
  const combinedOptions: Array<{ label: string; value: string }> = [];
  
  // 对于每个过滤后的API选项，生成带有不同后缀的选项
  filteredApiOptions.forEach(item => {
    // 添加原始选项
    combinedOptions.push({
      label: item.label,
      value: item.value
    });
    
    // 为每个选项添加后缀变体
    suffixList.forEach(suffix => {
      const newLabel = `${item.label}${suffix}`;
      combinedOptions.push({
        label: newLabel,
        value: newLabel
      });
    });
  });
  
  console.log('更新后的选项:', combinedOptions);
  labNameOptions.value = combinedOptions;
};

// 获取实验室数据
const fetchLabData = async () => {
  loading.value = true;
  try {
    console.log('开始获取检测机构数据');
    // 第一步：获取检测机构数据
    const orgResponse = await axios.post(
      '/Restful/Kivii.Organizations.Entities.Organization/Query.json', 
      { InternalCode: "检测机构" }
    );
    
    console.log('检测机构数据响应:', orgResponse.data);

    if (!orgResponse.data?.Results || orgResponse.data.Results.length === 0) {
      message.error('未找到检测机构数据');
      loading.value = false;
      return;
    }

    const orgKvid = orgResponse.data.Results[0].Kvid;
    console.log('获取到检测机构Kvid:', orgKvid);

    // 第二步：根据ParentKvid获取实验室列表
    const labResponse = await axios.post(
      '/Restful/Kivii.Organizations.Entities.Organization/Query.json',
      { ParentKvid: orgKvid }
    );
    
    console.log('实验室数据响应:', labResponse.data);

    if (!labResponse.data?.Results) {
      message.error('获取实验室列表失败');
      loading.value = false;
      return;
    }

    // 转换为下拉框数据格式，同时保存更多信息用于自动填充
    const results = labResponse.data.Results || [];
    apiLabOptions.value = results.map((item: any) => ({
      label: item.Name,
      value: item.Name,
      address: item.Address || '',
      kvid: item.Kvid
    }));
    
    // 初始化选项列表
    updateOptions('');
    
    // 如果没有数据，显示提示
    if (apiLabOptions.value.length === 0) {
      message.info('暂无实验室数据');
    } else {
      message.success(`成功获取${apiLabOptions.value.length}个实验室数据`);
    }
    
  } catch (error) {
    console.error('获取实验室数据失败', error);
    message.error('获取实验室数据失败');
  } finally {
    loading.value = false;
  }
};

// 实验室名称搜索处理
const handleLabSearch = (query: any) => {
  console.log('搜索实验室:', query);
  // 无论输入是什么，都更新searchInputValue
  searchInputValue.value = typeof query === 'string' ? query : '';
  // 即使输入为空也更新选项
  updateOptions(searchInputValue.value);
};

// 实验室名称选择处理
const handleLabSelect = (value: string) => {
  console.log('选择实验室:', value);
  
  if (!value) {
    // 如果清空选择，则清空地址
    detailedData.value.SampleManufacturerAddress = '';
    // 清空时重置选项列表，显示所有可用选项
    updateOptions('');
    return;
  }
  
  // 确保通过多种方式设置实验室名称
  detailedData.value.SampleName = value;
  // 使用nextTick确保值更新
  (window as any).$nextTick && (window as any).$nextTick(() => {
    // 再次确认值已设置
    console.log('nextTick后检查实验室名称:', detailedData.value.SampleName);
  });
  
  // 首先尝试查找完全匹配的实验室
  let selected = apiLabOptions.value.find(item => item.value === value);
  
  // 如果没有找到完全匹配的，可能是带后缀的选项
  if (!selected) {
    // 检查是否是带后缀的选项
    for (const item of apiLabOptions.value) {
      for (const suffix of suffixList) {
        if (value === `${item.label}${suffix}`) {
          selected = item;
          break;
        }
      }
      if (selected) break;
    }
  }
  
  // 如果找到匹配的实验室数据且有地址信息，则自动填充地址
  if (selected && selected.address) {
    console.log('自动填充地址:', selected.address);
    detailedData.value.SampleManufacturerAddress = selected.address;
    message.success('已自动填充实验室地址');
  }
};

// 组件加载时获取实验室数据
onMounted(() => {
  console.log('applicationInformation组件已挂载，开始获取实验室数据');
  
  // 确保detailedData对象已正确初始化
  if (!detailedData.value) {
    detailedData.value = {};
  }
  
  // 如果已有选择的实验室名称，确保它被设置
  if (detailedData.value.SampleName) {
    console.log('已有实验室名称:', detailedData.value.SampleName);
  }
  
  fetchLabData().then(() => {
    // 初始化时更新一次选项列表，显示所有可用选项
    updateOptions('');
  });
});

// 创建接口验证和提交方法
const validateAndSave = async () => {
  // 验证必填字段
  console.log('验证实验室名称:', detailedData.value.SampleName);
  
  // 尝试从DOM中获取实验室名称的值
  const selectElement = document.querySelector('input[placeholder="请输入或选择实验室名称"]');
  if (selectElement && (selectElement as HTMLInputElement).value && !detailedData.value.SampleName) {
    // 如果DOM中有值但detailedData中没有，则手动设置
    detailedData.value.SampleName = (selectElement as HTMLInputElement).value;
    console.log('从DOM获取并设置实验室名称:', detailedData.value.SampleName);
  }
  
  if (!detailedData.value.SampleName) {
    message.error('请输入实验室名称');
    return false;
  }
  
  // 如果已经有Kvid，直接返回成功，不需要调用Create接口
  if (detailedData.value.Kvid || props.kvid) {
    console.log('已存在Kvid，无需创建新记录');
    return true;
  }
  
  try {
    // 显示加载状态
    loading.value = true;
    
    // 构建请求参数
    const requestData = {
      // 这里是Item参数内容，直接使用detailedData中的数据
      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": detailedData.value.CreateTime,
        "Status": 0,
        "SampleManufacturerName": (window as any).$KiviiContext?.CurrentMember?.DepartmentName || "默认部门",
        "SampleManufacturerKvid": (window as any).$KiviiContext?.CurrentMember?.DepartmentKvid || "",
        "SampleManufacturerContactName": detailedData.value.SampleManufacturerContactName,
        "SampleManufacturerContactNumber": detailedData.value.SampleManufacturerContactNumber,
        "SampleManufacturerAddress": detailedData.value.SampleManufacturerAddress,
        "SampleName": detailedData.value.SampleName,
        "TemplateName": "默认模板",
        "Remark": detailedData.value.Remark
      }
    };
    
    // 调用创建接口
    const response = await axios.post('/Restful/Kivii.Lims.Entities.Report/Create.json', requestData);
    
    if (response.data) {
      // 保存返回的Kvid
      if (response.data.Kvid) {
        detailedData.value.Kvid = response.data.Kvid;
        // 更新已加载的kvid，避免重复请求
        loadedKvid.value = response.data.Kvid;
      }
      
      message.success('申请信息保存成功');
      return true;
    } else {
      // 处理错误情况
      message.error(response.data?.Message || '保存失败，请重试');
      return false;
    }
  } catch (error) {
    console.error('保存申请信息失败:', error);
    message.error('系统错误，请稍后重试');
    return false;
  } finally {
    // 隐藏加载状态
    loading.value = false;
  }
};

// 导出方法供父组件调用
defineExpose({
  validateAndSave,
  detailedData
});
</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="M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z"></path>
      </svg>
      <span>实验室信息</span>
    </div>
    <div style="display: flex; width: 100%;">
    <n-form-item path="labName" label="实验室名称" style="width: 50%;" >
      <n-select
        v-model:value="detailedData.SampleName"
        :options="labNameOptions"
        :loading="loading"
        placeholder="请输入或选择实验室名称"
        clearable
        filterable
        @update:value="handleLabSelect"
        @search="handleLabSearch"
        @clear="() => updateOptions('')"
        remote
        :remote-props="{ loading }"
        size="medium"
      >
        <template #empty>
          <n-empty description="暂无实验室数据" size="small" ></n-empty>
        </template>
      </n-select>
      <!-- 添加一个隐藏的输入框，确保数据绑定 -->
      <input type="hidden" :value="detailedData.SampleName" />
    </n-form-item>

    <n-form-item path="labAddress" label="实验室地址" style="width: 50%;">
      <n-input
        v-model:value="detailedData.SampleManufacturerAddress"
        placeholder="请输入实验室详细地址"
      ></n-input>
    </n-form-item>
  </div>
    <n-divider ></n-divider>

    <!-- 联系人信息 -->
    <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,4A4,4 0 0,1 16,8A4,4 0 0,1 12,12A4,4 0 0,1 8,8A4,4 0 0,1 12,4M12,14C16.42,14 20,15.79 20,18V20H4V18C4,15.79 7.58,14 12,14Z"></path>
      </svg>
      <span>联系人信息</span>
    </div>
    <div style="display: flex; width: 100%;">
      <n-form-item path="contactName" label="联系人姓名" style="width: 50%;">
        <n-input
          v-model:value="detailedData.SampleManufacturerContactName"
          placeholder="请输入联系人姓名"
        ></n-input>
      </n-form-item>

      <n-form-item path="contactPhone" label="联系电话" style="width: 50%;">
        <n-input
          v-model:value="detailedData.SampleManufacturerContactNumber"
          placeholder="请输入联系电话"
        ></n-input>
      </n-form-item>
    </div>

    <n-divider ></n-divider>

    <!-- 申请时间 -->
    <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="M19,19H5V8H19M16,1V3H8V1H6V3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3H18V1M17,12H12V17H17V12Z"></path>
      </svg>
      <span>申请时间设置</span>
    </div>

    <n-form-item path="applyDate" label="申请时间">
      <n-date-picker
        v-model:value="formattedCreateTime"
        type="datetime"
        clearable
        style="width: 100%"
        format="yyyy-MM-dd HH:mm"
        :disabled-date="(ts: number) => ts < Date.now() - 86400000"
      ></n-date-picker>
    </n-form-item>

    <n-form-item path="remarks" label="备注说明" class="last-form-item">
      <n-input
        v-model:value="detailedData.Remark"
        type="textarea"
        placeholder="如有特殊需求，请在此说明"
        :autosize="{ minRows: 3, maxRows: 5 }"
      ></n-input>
    </n-form-item>
  </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;
}

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

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

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