<script setup lang="ts">
import { computed, defineEmits, defineProps, h, onMounted, ref, resolveComponent } from 'vue';
import TestPlanDetailSelector from './TestPlanDetailSelector.vue'; // '/codes/TestPlanDetailSelector.vue';

interface TestItem {
  id: number;
  name: string;
  selected: boolean;
}

interface TestDataItem {
  key: string;
  testItem: string;
  standardValue: string;
  allowableRange: string;
  measuredValue: string | null;
  verifier: string | null;
  result: string;
  children?: TestDataItem[];
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const props = defineProps({
  testItems: {
    type: Array as () => TestItem[],
    required: true
  },
  saveAsDraft: {
    type: Boolean,
    required: true
  }
});

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const emit = defineEmits(['update:testItems', 'update:saveAsDraft']);

// 主体框架内置的第三方方法通过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 testPlan = ref('');
const testDate = ref(null);
const sampleCode = ref('');
const testResult = ref('');
const testComment = ref('');
const showDetailSelector = ref(false);

// 状态变量
const loading = ref<boolean>(false);
const titleOptions = ref<Array<{ label: string; value: string }>>([]);

// 获取测试方案选项
async function fetchTestPlanOptions() {
  try {
    loading.value = true;

    // 调用标准实体查询接口
    const response = await axios.post('/Restful/Kivii.Standards.Entities.Standard/Query.json?Type=比对测试');
          // console.log('测试方案响应数据:', response.data);

    // 添加数据存在性检查
    if (response.data && response.data.Results) {
      // 直接使用Results数组
      titleOptions.value = response.data.Results.map((item: any) => ({
        label: item.Title,
        value: item.Kvid
      }));
    } else {
              // console.error('无效的数据格式:', response.data);
      message.error('数据格式不正确');
    }
  } catch (error) {
    message.error('获取测试方案失败');
          // console.error('获取测试方案失败:', error);
  } finally {
    loading.value = false;
  }
}

// 表格列定义
const columns = [
  { title: '测试项目', key: 'testItem' },
  { title: '标准值', key: 'standardValue', align: 'center' as const },
  { title: '允许偏差范围', key: 'allowableRange', align: 'center' as const },
  {
    title: '实测值',
    key: 'measuredValue',
    align: 'center' as const,
    render: (row: TestDataItem) => {
      return h(resolveComponent('n-input'), {
        value: row.measuredValue,
        placeholder: '请输入测试值',
        onUpdateValue: (value: string) => {
          row.measuredValue = value;
          checkTestResult(row);
        }
      });
    }
  },
  {
    title: '授信人',
    key: 'verifier',
    align: 'center' as const,
    render: (row: TestDataItem) => {
      return h(resolveComponent('n-input'), {
        value: row.verifier,
        placeholder: '请输入授信人',
        onUpdateValue: (value: string) => {
          row.verifier = value;
        }
      });
    }
  },
  {
    title: '结果',
    key: 'result',
    align: 'center' as const,
    render: (_row: TestDataItem) => {
      return h(resolveComponent('n-tag'), { type: 'default' }, { default: () => '待测试' });
    }
  },
  {
    title: '操作',
    key: 'actions',
    width: 200,
    align: 'center',
    render(row: any) {
      return h('div', { style: 'display: flex; gap: 8px; justify-content: center;' }, [
        h(
          resolveComponent('n-button'),
          {
            size: 'small',
            type: 'error',
            onClick: () => deleteTestPlanDetail(row)
          },
          { default: () => '删除' }
        )
      ]);
    }
  }
];

function deleteTestPlanDetail(row: TestDataItem) {
  dialog.warning({
    title: '确认删除',
    content: `是否确认删除测试项"${row.testItem}"？`,
    positiveText: '确认',
    negativeText: '取消',
    onPositiveClick: () => {
      // 递归查找并删除行项目
      const removeItem = (items: TestDataItem[], key: string): boolean => {
        for (let i = 0; i < items.length; i++) {
          if (items[i].key === key) {
            items.splice(i, 1);
            return true;
          }
          if (items[i].children && items[i].children.length > 0) {
            if (removeItem(items[i].children, key)) {
              return true;
            }
          }
        }
        return false;
      };

      if (removeItem(testData.value, row.key)) {
        message.success('删除成功');
      }
    }
  });
}

// 测试数据
const testData = ref<TestDataItem[]>([]);

// 处理测试方案变化
function handlePlanChange(value: string) {
  if (value) {
    // 打开明细选择弹窗
    showDetailSelector.value = true;
  }
}

// 处理方案明细确认事件
function handlePlanDetailsConfirm(selectedItems: any[]) {
  // 获取当前最大测试项索引，用于生成唯一key
  let maxIndex = 0;
  if (testData.value.length > 0) {
    // 从现有key中提取数字部分
    const keyNumbers = testData.value.map(item => {
      const matches = item.key.match(/test-(\d+)/);
      return matches ? Number.parseInt(matches[1], 10) : 0;
    });
    maxIndex = Math.max(...keyNumbers);
  }

  // 处理新选择的测试项，添加正确的key
  const processedItems = processTestItems(selectedItems, maxIndex);

  // 将处理后的数据添加到现有数据中
  testData.value = [...testData.value, ...processedItems];

  showDetailSelector.value = false;
  message.success(`已添加${selectedItems.length}个测试项目`);
}

// 处理测试项目数据，添加必要的字段并构建树形结构
function processTestItems(items: any[], startId = 0) {
  // 创建一个新的数组来存储处理后的数据
  return items.map((item, index) => {
    const newId = startId + index + 1;
    return {
      key: `test-${newId}`,
      testItem: item.testItem,
      standardValue: item.standardValue,
      allowableRange: item.allowableRange,
      measuredValue: null,
      verifier: null,
      result: '待测试',
      // 如果原数据中有children，也需要递归处理
      ...(item.children
        ? {
            children: processTestItems(item.children, startId + items.length)
          }
        : {})
    };
  });
}

// 页面加载时获取测试方案选项
onMounted(() => {
  fetchTestPlanOptions();
});

// 检查测试结果
function checkTestResult(row: TestDataItem) {
  // 这里可以添加逻辑来判断测试结果是否在允许范围内
  // 现在只是占位，实际应用中应根据实测值和标准值+允许偏差范围判断
  if (row.measuredValue) {
    row.result = '待评估';
  } else {
    row.result = '待测试';
  }
}
</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="M6,22A3,3 0 0,1 3,19C3,18.4 3.18,17.84 3.5,17.37L9,7.81V6A1,1 0 0,1 8,5V4A2,2 0 0,1 10,2H14A2,2 0 0,1 16,4V5A1,1 0 0,1 15,6V7.81L20.5,17.37C20.82,17.84 21,18.4 21,19A3,3 0 0,1 18,22H6M5,19A1,1 0 0,0 6,20H18A1,1 0 0,0 19,19C19,18.79 18.93,18.59 18.82,18.43L16.53,14.47L14,17L8.93,11.93L5.18,18.43C5.07,18.59 5,18.79 5,19M13,10A1,1 0 0,0 12,11A1,1 0 0,0 13,12A1,1 0 0,0 14,11A1,1 0 0,0 13,10Z"
        ></path>
      </svg>
      <span>测试方案选择</span>
    </div>

    <NFormItem label="测试方案" required>
      <NSelect
        v-model:value="testPlan"
        :options="titleOptions"
        placeholder="请选择测试方案"
        style="width: 100%"
        @update:value="handlePlanChange"
      ></NSelect>
    </NFormItem>

    <NFormItem label="测试日期" required>
      <NDatePicker v-model:value="testDate" type="date" clearable style="width: 100%" format="yyyy/MM/dd"></NDatePicker>
    </NFormItem>

    <NFormItem label="测试样品编号" class="last-form-item" required>
      <NInput v-model:value="sampleCode" placeholder="请输入测试样品编号"></NInput>
    </NFormItem>

    <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="M10,17L6,13L7.41,11.59L10,14.17L16.59,7.58L18,9M12,3A1,1 0 0,1 13,4A1,1 0 0,1 12,5A1,1 0 0,1 11,4A1,1 0 0,1 12,3M19,3H14.82C14.4,1.84 13.3,1 12,1C10.7,1 9.6,1.84 9.18,3H5A2,2 0 0,0 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5A2,2 0 0,0 19,3Z"
        ></path>
      </svg>
      <span>比对测试数据</span>
    </div>

    <NDataTable
      :columns="columns"
      :data="testData"
      :bordered="false"
      :max-height="300"
      :loading="loading"
      :row-key="row => row.key"
      children-key="children"
      :indent="20"
      :default-expand-all="true"
      striped
    ></NDataTable>

    <div class="result-summary">
      <span class="result-label">总体结果：</span>
      <NTag type="warning">未完成</NTag>
    </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="M6,2C4.89,2 4,2.89 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2H6M6,4H13V9H18V20H6V4M8,12V14H16V12H8M8,16V18H13V16H8Z"
        ></path>
      </svg>
      <span>测试结论</span>
    </div>

    <NFormItem label="测试结论">
      <NRadioGroup v-model:value="testResult">
        <NSpace>
          <NRadio value="pass">通过</NRadio>
          <NRadio value="fail">不通过</NRadio>
          <NRadio value="partial">部分通过</NRadio>
        </NSpace>
      </NRadioGroup>
    </NFormItem>

    <NFormItem label="测试意见" class="last-form-item">
      <NInput v-model:value="testComment" type="textarea" placeholder="请输入测试意见" :rows="4"></NInput>
    </NFormItem>

    <!-- 测试方案明细选择弹窗 -->
    <NModal
      v-model:show="showDetailSelector"
      style="width: 800px"
      preset="card"
      :bordered="false"
      :show-icon="false"
      title="测试方案明细选择"
    >
      <TestPlanDetailSelector
        :standard-kvid="testPlan"
        @cancel="showDetailSelector = false"
        @confirm="handlePlanDetailsConfirm"
      ></TestPlanDetailSelector>
    </NModal>
  </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;
}

.test-item {
  padding: 8px 0;
}

.text-sm {
  font-size: 14px;
}

.text-gray-400 {
  color: #9ca3af;
}

.result-summary {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding-top: 24px;
  /* padding-bottom: 16px; */
}

.result-label {
  font-size: 16px;
  font-weight: bold;
  margin-right: 8px;
}

:deep(.n-form-item-label) {
  text-align: justify;
  text-align-last: justify;
}

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