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

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

// 定义props
const props = withDefaults(
  defineProps<{
    item?: ItemProps;
  }>(),
  {
    item: () => ({})
  }
);
// 主体框架内置的第三方方法通过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 loading = ref(false);

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

// 存储原始数据，用于比较是否有变化
const originalData = ref<ItemProps>({});


// 创建一个通用的日期处理函数
const createDateComputed = (getter: () => string | null, setter: (val: string | null) => void) => {
  return computed({
    get: () => {
      const value = getter();
      return value ? new Date(value).getTime() : null;
    },
    set: (val: any) => {
      if (!val) {
        setter(null);
        return;
      }

      try {
        // 确保val是数字时间戳或Date对象
        let dateVal: Date;
        if (typeof val === 'number') {
          dateVal = new Date(val);
        } else if (val instanceof Date) {
          dateVal = val;
        } else {
          dateVal = 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);
      }
    }
  });
};



// 创建处理后的DealDate计算属性
const formattedDealDate = createDateComputed(
  () => detailedData.DealDate,
  val => (detailedData.DealDate = val)
);

// 比较数据是否有变化的辅助函数
const hasDataChanged = (): { changed: boolean; changedFields: Partial<ItemProps> } => {
  const changedFields: Partial<ItemProps> = {};
  let changed = false;

  // 比较关键字段
  const fieldsToCheck = [
    'SampleName',
    'SampleManufacturerAddress',
    'SampleManufacturerContactName',
    'SampleManufacturerContactNumber',
    'DealDate',
    'Remark'
  ];

  fieldsToCheck.forEach(field => {
    const currentValue = detailedData[field];
    const originalValue = originalData.value[field];

    if (currentValue !== originalValue) {
      changedFields[field] = currentValue;
      changed = true;
    }
  });

  return { changed, changedFields };
};

// 获取详情数据
const fetchDetail = async (kvid: string) => {
  if (!kvid) return;

  // console.log(`准备获取详情数据，Kvid: ${kvid}，当前loadedKvid: ${detailedData.Kvid}`);
  if (kvid === detailedData.Kvid && Object.keys(detailedData).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
      Object.assign(detailedData, response.data.Result || {});
      // 同时更新原始数据副本
      originalData.value = JSON.parse(JSON.stringify(response.data.Result || {}));
      // console.log('获取到详情数据:', response.data.Result);

      message.success('详情数据加载成功');
    } else {
      message.error('获取详情数据失败');
    }
  } catch (error) {
    // console.error('获取详情数据失败:', error);
    message.error('获取详情数据失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};



// 监听props.item变化，同步到detailedData
watch(
  () => props.item,
  newItem => {
    if (newItem && newItem.Kvid && newItem.Kvid !== detailedData.Kvid) {
      fetchDetail(newItem.Kvid);
    }
    // 保持detailedData为props.item的响应式副本
    Object.assign(detailedData, newItem || {});
    // 同时更新原始数据副本
    originalData.value = JSON.parse(JSON.stringify(newItem || {}));
  },
  { immediate: true, deep: true }
);





// 组件加载时初始化
onMounted(() => {
  // console.log('applicationInformation组件已挂载');
  // 确保detailedData对象已正确初始化
  if (Object.keys(detailedData).length === 0) {
    Object.assign(detailedData, {});
  }
  // 如果已有选择的实验室名称，确保它被设置
  if (detailedData.SampleName) {
    // console.log('已有实验室名称:', detailedData.SampleName);
  }
});

// 创建实体方法
const createEntity = async () => {
  // 验证：Kvid不存在时才创建
  if (detailedData.Kvid) {
    // console.log('实体已存在，无需创建');
    return { success: true, data: detailedData };
  }

  try {
    loading.value = true;

    // 构建全量数据的请求参数
    // 先用detailedData的数据作为基础
    const Item = { ...detailedData };

    // 然后检查特定字段，如果为空则使用默认值
    if (!Item.SupplierName) {
      Item.SupplierName = '江苏省纺织产品质量监督检验研究院';
    }
    if (!Item.PayeeName) {
      Item.PayeeName = '江苏省纺织产品质量监督检验研究院';
    }
    if (!Item.DemanderName) {
      Item.DemanderName = (window as any).$KiviiContext?.CurrentMember?.OrganizationName || '默认组织名称';
    }
    if (!Item.DemanderKvid) {
      Item.DemanderKvid = (window as any).$KiviiContext?.CurrentMember?.OrganizationKvid || '';
    }
    if (!Item.OperatorName) {
      Item.OperatorName = (window as any).$KiviiContext?.CurrentMember?.FullName || '默认用户';
    }
    if (!Item.OperatorKvid) {
      Item.OperatorKvid = (window as any).$KiviiContext?.CurrentMember?.Kvid || '';
    }
    if (Item.TestNeedJudge === undefined || Item.TestNeedJudge === null) {
      Item.TestNeedJudge = true;
    }
    if (!Item.Quantity) {
      Item.Quantity = '1';
    }
    if (Item.Status === undefined || Item.Status === null) {
      Item.Status = 0;
    }
    if (!Item.SampleManufacturerName) {
      Item.SampleManufacturerName = (window as any).$KiviiContext?.CurrentMember?.DepartmentName || '默认部门';
    }
    if (!Item.SampleManufacturerKvid) {
      Item.SampleManufacturerKvid = (window as any).$KiviiContext?.CurrentMember?.DepartmentKvid || '';
    }
    if (!Item.TemplateName) {
      Item.TemplateName = '默认模板';
    }

    const requestData = { Item };

    // console.log('创建实体请求数据:', requestData);

    // 调用创建接口
    const response = await axios.post('/Restful/Kivii.Lims.Entities.Report/Create.json', requestData);

    if (response.data.Results.length > 0) {
      // 保存返回的Kvid
      if (response.data.Results[0].Kvid) {
        Object.assign(detailedData, response.data.Results[0]);
      }

      // console.log('实体创建成功:', response.data);
      message.success('实体创建成功');
      return { success: true, data: response.data };
    }

    // 处理错误情况
    // console.error('创建失败:', response.data);
    message.error(response.data?.Message || '创建失败，请重试');
    return { success: false, error: response.data?.Message || '创建失败' };

  } catch (error) {
    // console.error('创建实体失败:', error);
    message.error('系统错误，请稍后重试');
    return { success: false, error: '系统错误' };
  } finally {
    loading.value = false;
  }
};

// 更新实体方法
const updateEntity = async (changedFields: Partial<ItemProps> = {}) => {
  // 验证：Kvid存在时才更新
  if (!detailedData.Kvid) {
    // console.log('实体不存在，无法更新');
    message.error('实体不存在，请先创建');
    return { success: false, error: '实体不存在' };
  }

  try {
    loading.value = true;

    // 构建只包含更改字段和Kvid的请求参数
    const requestData = {
      Item: {
        Kvid: detailedData.Kvid,
        ...changedFields
      }
    };

    // console.log('更新实体请求数据:', requestData);

    // 调用更新接口
    const response = await axios.post('/Restful/Kivii.Lims.Entities.Report/Update.json', requestData);

    if (response.data.Results.length > 0) {
      // 保存返回的Kvid
      if (response.data.Results[0].Kvid) {
        // 更新本地数据
        Object.assign(detailedData, response.data.Results[0]);
      }

      // console.log('实体更新成功:', response.data);
      message.success('实体更新成功');
      return { success: true, data: response.data };
    }

    // 处理错误情况
    // console.error('更新失败:', response.data);
    message.error(response.data?.Message || '更新失败，请重试');
    return { success: false, error: response.data?.Message || '更新失败' };

  } catch (error) {
    // console.error('更新实体失败:', error);
    message.error('系统错误，请稍后重试');
    return { success: false, error: '系统错误' };
  } finally {
    loading.value = false;
  }
};

// 智能验证和保存方法（统一入口）
const validateAndSave = async () => {
  // console.log('开始验证和保存数据...');

  // 1. 验证必填字段
  // console.log('验证实验室名称:', detailedData.SampleName);
  if (!detailedData.SampleName) {
    message.error('请输入实验室名称');
    return false;
  }

  // 2. 判断操作类型
  const hasKvid = Boolean(detailedData.Kvid);

  if (!hasKvid) {
    // 没有Kvid，需要创建
    // console.log('检测到无Kvid，执行创建操作');
    const result = await createEntity();
    if (result.success) {
      // 创建成功后更新原始数据副本
      originalData.value = JSON.parse(JSON.stringify(detailedData));
    }
    return result.success;
  } else {
    // 有Kvid，检查是否有数据变化
    const { changed, changedFields } = hasDataChanged();

    if (!changed) {
      // 没有变化，直接返回成功
      // console.log('数据没有变化，无需更新');
      message.success('数据已是最新，无需保存');
      return true;
    } else {
      // 有变化，需要更新
      // console.log('检测到数据变化，执行更新操作，变更字段:', changedFields);
      const result = await updateEntity(changedFields);
      if (result.success) {
        // 更新成功后更新原始数据副本
        originalData.value = JSON.parse(JSON.stringify(detailedData));
      }
      return result.success;
    }
  }
};

// 导出方法供父组件调用
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%">
      <NFormItem path="SampleName" label="实验室名称" style="width: 50%">
        <NInput
          v-model:value="detailedData.SampleName"
          placeholder="请输入实验室名称"
          clearable
          size="medium"
        />
      </NFormItem>

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

      <NFormItem path="contactPhone" label="联系电话" style="width: 50%">
        <NInput v-model:value="detailedData.SampleManufacturerContactNumber" 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="formattedDealDate"
        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="detailedData.Remark"
        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>
