<script lang="ts" setup>
// 导入部分
import { ref, computed, onMounted } from 'vue';
import { Page } from '@vben/common-ui';
import { ElTable, ElTableColumn, ElButton, ElInput, ElTabs, ElTabPane, ElSelect, ElOption } from 'element-plus';

// API 导入
import { scoreEntryList, updateScoreEntry } from '#/api/system/infoEntry/scoreEntry/scoreEntry';
// 数据字典导入
import { getDictOptions } from '#/utils/dict';

// 类型定义
interface TabOption {
  label: string;
  value: string;
  typeValue: string;
}

interface StandardItem {
  score: number;
  condition: string;
  max_value?: number;
  min_value?: number;
}

interface ScoreItem {
  id: string;
  type: string;
  typeName: string;
  dimension: string;
  dimensionName: string;
  indicator: string;
  indicatorName: string;
  standardJson: string;
  standards: StandardItem[];
  isEditing?: boolean;
  // 拆分后的标准字段
  threshold1: number;
  score1: number;
  threshold2: number;
  threshold3: number;
  score2: number;
  threshold4: number;
  threshold5: number;
  score3: number;
  threshold6: number;
  threshold7: number;
  score4: number;
  // API 响应中的其他字段
  createBy?: string;
  createTime?: string;
  updateBy?: string;
  updateTime?: string;
  remark?: string;
}

// 数据字典选项
const typeOptions = ref<any[]>([]);
const dimensionOptions = ref<any[]>([]);
const indicatorOptions = ref<any[]>([]);

// 响应式数据
// Tab切换数据
const activeTab = ref<string>('stationManager');
const tabOptions: TabOption[] = [
  { label: '油站管理人员', value: 'stationManager', typeValue: 'oil_station_manager' },
  { label: '油站员工', value: 'stationStaff', typeValue: 'oil_station_employee' },
  { label: '片区人员', value: 'areaStaff', typeValue: 'region_personnel' },
  { label: '总部人员', value: 'headquarters', typeValue: 'headquarters_personnel' },
  { label: '油站', value: 'station', typeValue: 'oil_station' },
  { label: '片区', value: 'area', typeValue: 'region' },
];

// 评分数据
const scoreData = ref<ScoreItem[]>([]);
const loading = ref<boolean>(false);

// 获取当前选中tab对应的typeValue
const getCurrentTypeValue = () => {
  const tab = tabOptions.find(tab => tab.value === activeTab.value);
  return tab ? tab.typeValue : '';
};

// 解析standardJson字段
const parseStandardJson = (standardJson: string): StandardItem[] => {
  try {
    const parsed = JSON.parse(standardJson);
    return parsed.standards || [];
  } catch (error) {
    console.error('解析standardJson失败:', error);
    return [];
  }
};

// 格式化标准项为阈值和分数
const formatStandardsToThresholds = (standards: StandardItem[]): Partial<ScoreItem> => {
  // 默认值
  const defaults = {
    threshold1: 0,
    score1: 0,
    threshold2: 0,
    threshold3: 0,
    score2: 0,
    threshold4: 0,
    threshold5: 0,
    score3: 0,
    threshold6: 0,
    threshold7: 0,
    score4: 0,
  };
  
  if (!standards || standards.length === 0) {
    return defaults;
  }
  
  // 按min_value降序排序
  const sortedStandards = [...standards].sort((a, b) => (b.min_value || 0) - (a.min_value || 0));
  
  // 填充阈值和分数
  return {
    threshold1: sortedStandards[0]?.min_value || 0,
    score1: sortedStandards[0]?.score || 0,
    threshold2: sortedStandards[1]?.min_value || 0,
    threshold3: sortedStandards[1]?.max_value || 0,
    score2: sortedStandards[1]?.score || 0,
    threshold4: sortedStandards[2]?.min_value || 0,
    threshold5: sortedStandards[2]?.max_value || 0,
    score3: sortedStandards[2]?.score || 0,
    threshold6: sortedStandards[3]?.min_value || 0,
    threshold7: sortedStandards[3]?.max_value || 0,
    score4: sortedStandards[3]?.score || 0,
  };
};

// 加载评分数据
const loadScoreData = async () => {
  const typeValue = getCurrentTypeValue();
  if (!typeValue) return;
  
  loading.value = true;
  try {
    const response = await scoreEntryList({ type: typeValue });
    console.log('原始响应:', response);
    if (response.rows) {
      scoreData.value = response.rows.map((item: any) => {
        const standards = parseStandardJson(item.standardJson);
        const thresholds = formatStandardsToThresholds(standards);
        return {
          ...item,
          standards,
          isEditing: false,
          ...thresholds,
        };
      });
    }
  } catch (error) {
    console.error('加载评分数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 监听tab切换，重新加载数据
const handleTabChange = () => {
  loadScoreData();
};

// 计算当前选中的评分数据
const currentScores = computed(() => {
  return scoreData.value;
});

// 初始化数据
onMounted(async () => {
  // 加载数据字典
  typeOptions.value = getDictOptions("score_standard_type");
  dimensionOptions.value = getDictOptions("score_standard_dimension");
  indicatorOptions.value = getDictOptions("score_standard_indicator");
  
  // 加载初始数据
  await loadScoreData();
});















// 计算需要合并的行
const getRowspan = (scores: ScoreItem[], index: number): number => {
  const currentDimension = scores[index].dimensionName;
  let rowspan = 1;
  for (let i = index + 1; i < scores.length; i++) {
    if (scores[i].dimensionName === currentDimension) {
      rowspan++;
    } else {
      break;
    }
  }
  return rowspan;
};

// 表格行合并方法
const tableSpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  // 只处理维度列的合并
  if (columnIndex === 0) {
    const scores = currentScores.value;
    const currentDimension = scores[rowIndex].dimensionName;
    
    // 检查当前行是否是连续相同维度行的第一行
    if (rowIndex === 0 || scores[rowIndex - 1].dimensionName !== currentDimension) {
      const rowspan = getRowspan(scores, rowIndex);
      return [rowspan, 1];
    } else {
      // 如果不是第一行，返回[0, 0]隐藏该单元格
      return [0, 0];
    }
  }
  return [1, 1];
};

// 事件处理函数
// 编辑按钮点击事件
const handleEdit = (id: string) => {
  const scores = currentScores.value;
  const item = scores.find(item => item.id === id);
  if (item) {
    item.isEditing = true;
  }
};

// 保存按钮点击事件
const handleSave = async (id: string) => {
  const scores = currentScores.value;
  const item = scores.find(item => item.id === id);
  if (item) {
    // 生成新的standardJson
    const standards = [
      {
        score: item.score1,
        condition: `≥${item.threshold1}%`,
        min_value: item.threshold1,
        max_value: null
      },
      {
        score: item.score2,
        condition: `${item.threshold2}%—${item.threshold3}%`,
        min_value: item.threshold2,
        max_value: item.threshold3
      },
      {
        score: item.score3,
        condition: `${item.threshold4}%—${item.threshold5}%`,
        min_value: item.threshold4,
        max_value: item.threshold5
      },
      {
        score: item.score4,
        condition: `${item.threshold6}%—${item.threshold7}%`,
        min_value: item.threshold6,
        max_value: item.threshold7
      }
    ];
    
    const updatedItem = {
      id: item.id,
      type: item.type,
      dimension: item.dimension,
      indicator: item.indicator,
      standardJson: JSON.stringify({ standards })
    };
    
    try {
      const response = await updateScoreEntry(updatedItem);
      console.log('更新响应:', response);
      item.isEditing = false;
      // 重新加载数据以确保一致性
      await loadScoreData();
    } catch (error) {
      console.error('保存失败:', error);
    }
  }
};

</script>

<template>
  <Page :auto-content-height="true">
    <div class="score-entry">
      <!-- Tab切换区域 -->
      <div class="tab-container">
        <ElTabs v-model="activeTab" @tab-click="handleTabChange">
          <ElTabPane v-for="tab in tabOptions" :key="tab.value" :label="tab.label" :name="tab.value">
            <!-- 评分表格 -->
            <div class="score-table-container">
              <ElTable :data="currentScores" border stripe style="width: 100%" :span-method="tableSpanMethod">
                <ElTableColumn prop="dimensionName" label="维度" width="150" />
                <ElTableColumn prop="indicatorName" label="指标" width="180" />
                <ElTableColumn label="标准及分值">
                  <template #default="scope">
                    <div v-if="scope.row.isEditing" class="standard-edit">
                      <div class="standard-item">
                        <span>≥ </span>
                        <ElInput v-model.number="scope.row.threshold1" type="number" size="small" />
                        <span>% ：</span>
                        <ElInput v-model.number="scope.row.score1" type="number" size="small" />
                        <span>分</span>
                      </div>
                      <div class="standard-item">
                        <span>区间 </span>
                        <ElInput v-model.number="scope.row.threshold2" type="number" size="small" />
                        <span>% — </span>
                        <ElInput v-model.number="scope.row.threshold3" type="number" size="small" />
                        <span>% ：</span>
                        <ElInput v-model.number="scope.row.score2" type="number" size="small" />
                        <span>分</span>
                      </div>
                      <div class="standard-item">
                        <span>区间 </span>
                        <ElInput v-model.number="scope.row.threshold4" type="number" size="small" />
                        <span>% — </span>
                        <ElInput v-model.number="scope.row.threshold5" type="number" size="small" />
                        <span>% ：</span>
                        <ElInput v-model.number="scope.row.score3" type="number" size="small" />
                        <span>分</span>
                      </div>
                      <div class="standard-item">
                        <span>区间 </span>
                        <ElInput v-model.number="scope.row.threshold6" type="number" size="small" />
                        <span>% — </span>
                        <ElInput v-model.number="scope.row.threshold7" type="number" size="small" />
                        <span>% ：</span>
                        <ElInput v-model.number="scope.row.score4" type="number" size="small" />
                        <span>分</span>
                      </div>
                    </div>
                    <div v-else class="standard-display">
                      <div class="standard-item">≥ {{ scope.row.threshold1 }}% ：{{ scope.row.score1 }}分</div>
                      <div class="standard-item">区间 {{ scope.row.threshold2 }}% — {{ scope.row.threshold3 }}% ：{{ scope.row.score2 }}分</div>
                      <div class="standard-item">区间 {{ scope.row.threshold4 }}% — {{ scope.row.threshold5 }}% ：{{ scope.row.score3 }}分</div>
                      <div class="standard-item">区间 {{ scope.row.threshold6 }}% — {{ scope.row.threshold7 }}% ：{{ scope.row.score4 }}分</div>
                    </div>
                  </template>
                </ElTableColumn>
                <ElTableColumn label="操作" width="150">
                  <template #default="scope">
                    <ElButton 
                      v-if="!scope.row.isEditing"
                      type="primary" 
                      size="small" 
                      @click="handleEdit(scope.row.id)"
                    >
                      编辑
                    </ElButton>
                    <ElButton 
                      v-else
                      type="success" 
                      size="small" 
                      @click="handleSave(scope.row.id)"
                    >
                      保存
                    </ElButton>
                  </template>
                </ElTableColumn>
              </ElTable>
            </div>
          </ElTabPane>
        </ElTabs>
      </div>
    </div>
  </Page>
</template>

<style scoped lang="scss">
.score-entry {
  min-height: 100vh;
  padding: 16px;
  background-color: #fff;

  .tab-container {
    margin-bottom: 16px;

    :deep(.el-tabs__header) {
      margin-bottom: 20px;
    }

    :deep(.el-tabs__content) {
      padding: 0;
    }
  }

  .score-table-container {
    padding: 16px;
    background-color: #fff;
    border-radius: 6px;

    :deep(.el-table) {
      width: 100%;
    }

    :deep(.el-table__cell),
    :deep(.el-table__header-cell) {
      padding: 12px;
      line-height: 2;
      text-align: center;
      vertical-align: middle;
    }

    /* 确保表格内容容器也上下居中 */
    .standard-edit,
    .standard-display {
      display: flex;
      flex-direction: column;
      justify-content: center;
      height: 100%;
    }

    .score-value {
      margin-top: 8px;
      font-weight: bold;
      color: #409EFF;
    }

    .standard-edit {
      padding: 8px;
      background-color: #f5f7fa;
      border-radius: 4px;
    }

    .standard-item {
      display: flex;
      flex-wrap: wrap;
      align-items: center;
      margin-bottom: 8px;
    }

    .standard-item:last-child {
      margin-bottom: 0;
    }

    .standard-item span {
      margin: 0 4px;
    }

    .standard-item .el-input {
      width: 60px;
      margin: 0 2px;
    }

    .score-input {
      display: flex;
      align-items: center;
      margin-top: 12px;
    }

    .score-input span {
      margin-right: 8px;
    }

    .score-input .el-input {
      width: 80px;
    }

    .standard-display {
      padding: 4px;
    }

    .standard-display .standard-item {
      line-height: 1.5;
    }
  }
}
</style>
