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

const props = defineProps({
  formModel: {
    type: Object,
    required: true
  },
  availabilityData: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update:formModel']);

// 主体框架内置的第三方方法通过window对象暴露、供外部组件使用
// 获取主题状态
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 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 = ['实验室', '研究中心', '技术研究所', '检测中心', '认证中心'];

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

// 更新选项列表，包括API数据和模糊匹配
const updateOptions = (query: string) => {
  console.log('更新选项:', query);

  // 首先基于API获取的数据进行过滤
  const filteredApiOptions = query
    ? apiLabOptions.value.filter(item => item.label.toLowerCase().includes(query.toLowerCase()))
    : [...apiLabOptions.value];

  // 添加带后缀的动态选项
  const dynamicOptions = query
    ? suffixList.map(suffix => ({
        label: `${query}${suffix}`,
        value: `${query}${suffix}`
      }))
    : [];

  // 合并去重，优先显示API数据
  const combinedOptions = [...filteredApiOptions];

  // 仅添加不在API过滤结果中的动态选项
  dynamicOptions.forEach(option => {
    if (!combinedOptions.some(item => item.value === option.value)) {
      combinedOptions.push(option);
    }
  });

  console.log('更新后的选项:', combinedOptions);
  labNameOptions.value = combinedOptions;
};

// 获取实验室数据
const fetchLabData = async () => {
  loading.value = true;
  try {
    console.log('开始获取检测机构数据');
    // 第一步：获取检测机构数据
    const { data: orgData, error: orgError } = await request({
      url: '/Restful/Kivii.Organizations.Entities.Organization/Query.json',
      method: 'get',
      params: { InternalCode: '检测机构' }
    });

    console.log('检测机构数据响应:', orgData);

    if (orgError) {
      console.error('获取检测机构数据失败:', orgError);
      message.error('获取检测机构数据失败');
      return;
    }

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

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

    // 第二步：根据ParentKvid获取实验室列表
    const { data: labData, error: labError } = await request({
      url: '/Restful/Kivii.Organizations.Entities.Organization/Query.json',
      method: 'get',
      params: { ParentKvid: orgKvid }
    });

    console.log('实验室数据响应:', labData);

    if (labError) {
      console.error('获取实验室列表失败:', labError);
      message.error('获取实验室列表失败');
      return;
    }

    if (!labData?.Results) {
      message.error('获取实验室列表失败：响应格式错误');
      return;
    }

    // 转换为下拉框数据格式，同时保存更多信息用于自动填充
    const results = labData.Results || [];
    apiLabOptions.value = results.map((item: any) => ({
      label: item.Name,
      value: item.Name,
      address: item.Address || '',
      kvid: item.Kvid
    }));

    // 初始化选项列表
    labNameOptions.value = [...apiLabOptions.value];

    console.log('转换后的实验室列表(包含地址):', apiLabOptions.value);

    // 如果没有数据，显示提示
    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: string) => {
  console.log('搜索实验室:', query);
  searchInputValue.value = query;
  updateOptions(query);
};

// 实验室名称选择处理
const handleLabSelect = (value: string) => {
  console.log('选择实验室:', value);

  if (value) {
    // 设置实验室名称
    props.formModel.labName = value;

    // 查找是否有匹配的实验室数据（来自API）
    const selected = apiLabOptions.value.find(item => item.value === value);

    // 如果找到匹配的实验室数据且有地址信息，则自动填充地址
    if (selected && selected.address) {
      console.log('自动填充地址:', selected.address);
      props.formModel.labAddress = selected.address;
      message.success('已自动填充实验室地址');
    }
  }
};

// 组件加载时获取实验室数据
onMounted(() => {
  console.log('applicationInformation组件已挂载，开始获取实验室数据');
  fetchLabData();
});
</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%">
      <NFormItem path="labName" label="实验室名称" style="width: 50%">
        <NSelect
          v-model:value="formModel.labName"
          :options="labNameOptions"
          :loading="loading"
          placeholder="请输入或选择实验室名称"
          clearable
          filterable
          remote
          size="medium"
          @update:value="handleLabSelect"
          @input="handleLabSearch"
        >
          <template #empty>
            <NEmpty description="暂无实验室数据" size="small" />
          </template>
        </NSelect>
      </NFormItem>

      <NFormItem path="labAddress" label="实验室地址" style="width: 50%">
        <NInput v-model:value="formModel.labAddress" placeholder="请输入实验室详细地址"></NInput>
      </NFormItem>
    </div>
    <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="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%">
      <NFormItem path="contactName" label="联系人姓名" style="width: 33%">
        <NInput v-model:value="formModel.contactName" placeholder="请输入联系人姓名"></NInput>
      </NFormItem>

      <NFormItem path="contactPhone" label="联系电话" style="width: 33%">
        <NInput v-model:value="formModel.contactPhone" placeholder="请输入联系电话"></NInput>
      </NFormItem>
    </div>

    <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="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>

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

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