<template>
  <div class="today-notes">
    <a-tabs v-model:activeKey="activeTab" @change="handleTabChange">
      <a-tab-pane v-for="type in noteTypes" :key="type.key" :tab="type.label">
        <a-table :columns="getColumns(type.key)" :data-source="filteredData" :rowKey="record => record.recordId">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'scheduleJson'">
              <span v-if="record.classify !== 8 && record.classify !== 9">
                {{ formatScheduleJson(record.scheduleJson) }}
              </span>
            </template>
            <template v-if="column.key === 'today'">
              <span>{{ record.today }}</span>
            </template>
            <template v-if="column.key === 'action'">
              <a-space>
                <a-button type="link" @click="editItem(record)">编辑</a-button>
                <a-button type="link" @click="deleteItem(record)">删除</a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </a-tab-pane>
      <template #rightExtra>
        <a-button type="primary" @click="showAddModal">新增</a-button>
      </template>
    </a-tabs>

    <a-modal
      v-model:visible="modalVisible"
      :title="(modalMode === 'add' ? '新增' : '编辑') + currentNoteTypeLabel"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      width="800px"
    >
      <a-form :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="日期" name="todayStr" :rules="[{ required: true, message: '请选择日期' }]">
          <a-date-picker v-model:value="formState.todayStr" style="width: 100%" format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="类型" name="classify" :rules="[{ required: true, message: '请选择类型' }]">
          <a-select v-model:value="formState.classify">
            <a-select-option v-for="type in noteTypes" :key="type.key" :value="type.key">
              {{ type.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <template v-if="formState.classify !== 8 && formState.classify !== 9">
          <a-form-item label="比赛" name="match" :rules="[{ required: true, message: '请输入比赛' }]">
            <a-input v-model:value="formState.match" />
          </a-form-item>
          <a-form-item label="球队1" name="team1" :rules="[{ required: true, message: '请输入球队1' }]">
            <a-input v-model:value="formState.team1" />
          </a-form-item>
          <a-form-item label="球队2" name="team2" :rules="[{ required: true, message: '请输入球队2' }]">
            <a-input v-model:value="formState.team2" />
          </a-form-item>
          <a-form-item label="比分结果" name="result" :rules="[{ required: true, message: '请输入结果' }]">
            <a-input v-model:value="formState.result" />
          </a-form-item>
        </template>
        <a-form-item label="赔率" name="odds">
          <a-input v-model:value="formState.odds" />
        </a-form-item>
        <a-form-item label="中否" name="fruit">
          <a-input v-model:value="formState.fruit" />
        </a-form-item>
        <a-form-item v-if="formState.classify === 9" label="开奖号" name="winNo">
          <a-input v-model:value="formState.winNo" />
        </a-form-item>
        <a-form-item v-if="formState.classify === 8 || formState.classify === 9" label="推荐号" name="recommendNo">
          <a-input v-model:value="formState.recommendNo" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';
import { getScheduleListApi, deleteScheduleApi, saveScheduleApi, updateScheduleApi } from '../../api/scheduleConfig';

const noteTypes = [
  { key: 1, label: '总进球' },
  { key: 2, label: '2.0' },
  { key: 3, label: '3.0' },
  { key: 4, label: '中高倍' },
  { key: 5, label: '高倍' },
  { key: 6, label: '十倍' },
  { key: 7, label: '篮球' },
  { key: 8, label: '排列三' },
  { key: 9, label: '快乐八' },
];

const activeTab = ref(noteTypes[0].key);
const modalVisible = ref(false);
const modalMode = ref('add');

const data = reactive([]);

const formState = reactive({
  recordId: null,
  todayStr: '',
  classify: 1,
  match: '',
  team1: '',
  team2: '',
  result: '',
  odds: '',
  fruit: '',
  winNo: '',
  recommendNo: '',
});

const filteredData = computed(() => {
  return data.map(item => ({
    ...item,
    today: dayjs(item.todayStr).format('YYYY-MM-DD')
  })).filter(item => item.classify === activeTab.value);
});

const currentNoteType = computed(() => {
  return noteTypes.find(type => type.key === activeTab.value) || noteTypes[0];
});

const currentNoteTypeLabel = computed(() => {
  return currentNoteType.value.label;
});

const formatScheduleJson = (scheduleJson) => {
  try {
    const parsed = JSON.parse(scheduleJson);
    return `${parsed.match} ${parsed.team1} vs ${parsed.team2} ${parsed.result}`;
  } catch (error) {
    return scheduleJson;
  }
};

const showAddModal = () => {
  modalMode.value = 'add';
  Object.assign(formState, {
    recordId: null,
    todayStr: dayjs(),
    classify: activeTab.value,
    match: '',
    team1: '',
    team2: '',
    result: '',
    odds: '',
    fruit: '',
    winNo: '',
    recommendNo: '',
  });
  modalVisible.value = true;
};

const editItem = (record) => {
  modalMode.value = 'edit';
  Object.assign(formState, {
    ...record,
    todayStr: dayjs(record.todayStr),
  });
  if (record.scheduleJson) {
    try {
      const parsed = JSON.parse(record.scheduleJson);
      formState.match = parsed.match;
      formState.team1 = parsed.team1;
      formState.team2 = parsed.team2;
      formState.result = parsed.result;
    } catch (error) {
      console.error('Error parsing scheduleJson:', error);
    }
  }
  modalVisible.value = true;
};

const deleteItem = async (record) => {
  try {
    await deleteScheduleApi(record.id);
    message.success('删除成功');
    fetchData();
  } catch (error) {
    message.error('删除失败');
  }
};

const handleModalOk = async () => {
  try {
    let payload = {
      ...formState,
      recordId: formState.id,
      todayStr: formState.todayStr.format('YYYY-MM-DD'),
    };
    
    if (payload.classify !== 8 && payload.classify !== 9) {
      payload.scheduleJson = JSON.stringify({
        match: payload.match,
        team1: payload.team1,
        team2: payload.team2,
        result: payload.result,
      });
      
      // 清除不需要的字段
      delete payload.match;
      delete payload.team1;
      delete payload.team2;
      delete payload.result;
    }
    
    if (modalMode.value === 'add') {
      await saveScheduleApi(payload);
    } else {
      await updateScheduleApi(payload);
    }
    
    message.success(modalMode.value === 'add' ? '添加成功' : '编辑成功');
    modalVisible.value = false;
    fetchData();
  } catch (error) {
    message.error(modalMode.value === 'add' ? '添加失败' : '编辑失败');
  }
};

const handleModalCancel = () => {
  modalVisible.value = false;
};

const fetchData = async () => {
  try {
    const response = await getScheduleListApi(1, 100, activeTab.value);
    data.splice(0, data.length, ...response.data.records);
  } catch (error) {
    message.error('获取数据失败');
  }
};

const handleTabChange = (newActiveKey) => {
  activeTab.value = newActiveKey;
  fetchData();
};

const getColumns = (classify) => {
  const baseColumns = [
    { title: '日期', dataIndex: 'today', key: 'today' },
    { title: '赔率', dataIndex: 'odds', key: 'odds' },
    { title: '结果', dataIndex: 'fruit', key: 'fruit' },
    { title: '操作', key: 'action' },
  ];

  if (classify === 8) {
    baseColumns.splice(1, 0, { title: '开奖号', dataIndex: 'winNo', key: 'winNo' });
    baseColumns.splice(2, 0, { title: '推荐号', dataIndex: 'recommendNo', key: 'recommendNo' });
  } else if (classify === 9) {
    baseColumns.splice(1, 0, { title: '推荐号', dataIndex: 'recommendNo', key: 'recommendNo' });
  } else {
    baseColumns.splice(1, 0, { title: '比赛内容', key: 'scheduleJson' });
  }

  return baseColumns;
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.today-notes {
  padding: 24px;
}
</style>