<template>
  <a-card title="" :bordered="false">
    <!-- 查询区域 -->
    <a-form ref="formRef" @keyup.enter.native="searchQuery" :model="queryParam"
            :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-row>
        <a-col :span="6">
          <a-form-item label="手机号">
            <a-input v-model:value="queryParam.phone" placeholder="请输入手机号" allowClear/>
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-button type="primary" preIcon="ant-design:search-outlined" @click="searchQuery">查询</a-button>
          <a-button type="primary" preIcon="ant-design:reload-outlined" @click="searchReset" style="margin-left: 8px">重置</a-button>
        </a-col>
      </a-row>
    </a-form>

    <!-- JVxeTable 表格区域 -->
    <JVxeTable
      toolbar
      :toolbarConfig="toolbarConfig"
      rowNumber
      rowSelection
      keepSource
      asyncRemove
      :height="600"
      :loading="loading"
      :columns="columns"
      :dataSource="dataSource"
      :pagination="pagination"
      @removed="handleTableRemove"
      @edit-closed="handleEditClosed"
      @pageChange="handlePageChange"
      @selectRowChange="handleSelectRowChange"
    />
  </a-card>
</template>

<script lang="ts" setup>
import {reactive, ref} from 'vue';
import {defHttp} from '/@/utils/http/axios';
import {JVxeColumn, JVxeTypes} from '/@/components/jeecg/JVxeTable/types';
import {useMessage} from '/@/hooks/web/useMessage';
// 引入你的API
import {list, deleteOne, batchDelete} from './YxUserScore.api';

const { createMessage } = useMessage();

// API Endpoints
enum Api {
  getData = '/yx/yxUserScore/userScoreList_q23f', // 使用导入的list函数，这里仅作示例
  saveRow = '/yx/yxUserScore/userScoreSave_5rew', // 假设的行编辑保存接口
  deleteBatch = '/yx/yxUserScore/deleteBatch', // 使用导入的batchDelete函数，这里仅作示例
}

// antd组件的布局设置
const labelCol = reactive({ xs: {span: 24}, sm: {span: 7} });
const wrapperCol = reactive({ xs: {span: 24}, sm: {span: 16} });

// JVxeTable的工具栏配置, 这里设置为空，不显示内部按钮
const toolbarConfig = reactive({
  btn: [],
});

// 表格加载状态
const loading = ref(false);
// 查询参数
const queryParam = reactive({ phone: '' });
// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  pageSizeOptions: ['10', '20', '50', '100'],
  total: 0,
});
// 表格数据源
const dataSource = ref<Recordable[]>([]);
// 已选择的行
const selectedRows = ref<Recordable[]>([]);

// 【核心修改】列定义：从YxUserScore.data.ts迁移并改造为JVxeColumn格式
const columns = ref<JVxeColumn[]>([
  { title: '手机号', key: 'phone', width: 120, type: JVxeTypes.input },
  { title: '用户名', key: 'username', width: 120, type: JVxeTypes.input },
  { title: '专业类别', key: 'professionalCategory', width: 120, type: JVxeTypes.input },
  { title: '子级专业类别', key: 'professionalCategoryChildren', width: 150, type: JVxeTypes.input },
  { title: '文理分班', key: 'cognitioPolyclinic', width: 100, type: JVxeTypes.input },
  { title: '统考成绩', key: 'professionalScore', width: 100, type: JVxeTypes.inputNumber },
  { title: '文化成绩', key: 'culturalScore', width: 100, type: JVxeTypes.inputNumber },
  { title: '创建时间', key: 'createTime', width: 180, type: JVxeTypes.normal }, // 不可编辑
  { title: '高考省份', key: 'province', width: 100, type: JVxeTypes.input },
  { title: '语文成绩', key: 'chineseScore', width: 100, type: JVxeTypes.inputNumber },
  { title: '英语成绩', key: 'englishScore', width: 100, type: JVxeTypes.inputNumber },
  { title: '音乐表演声乐', key: 'yybysy', width: 120, type: JVxeTypes.inputNumber },
  { title: '音乐表演器乐', key: 'yybyqy', width: 120, type: JVxeTypes.inputNumber },
  { title: '音乐教育', key: 'yyjy', width: 100, type: JVxeTypes.inputNumber },
  { title: '服装表演', key: 'fzby', width: 100, type: JVxeTypes.inputNumber },
  { title: '戏剧影视导演', key: 'xjysdy', width: 130, type: JVxeTypes.inputNumber },
  { title: '戏剧影视表演', key: 'xjysby', width: 130, type: JVxeTypes.inputNumber },
  { title: '可冲击专业数量', key: 'kcjNum', width: 130, type: JVxeTypes.inputNumber },
  { title: '较稳妥专业数量', key: 'jwtNum', width: 130, type: JVxeTypes.inputNumber },
  { title: '可保底专业数量', key: 'kbdNum', width: 130, type: JVxeTypes.inputNumber },
  { title: '难录取专业数量', key: 'nlqNum', width: 130, type: JVxeTypes.inputNumber },
  { title: '记录结果表名', key: 'calculationTableName', width: 150, type: JVxeTypes.input },
]);

// 初始加载数据
loadData();

/**
 * 加载数据
 */
async function loadData() {
  loading.value = true;
  const params = {
    ...queryParam,
    pageNo: pagination.current,
    pageSize: pagination.pageSize,
  };
  try {
    const result = await list(params); // 使用导入的list API
    pagination.total = result.total;
    dataSource.value = result.records;
    selectedRows.value = []; // 重置选择
  } catch (error) {
    console.error("数据加载失败", error);
    createMessage.error("数据加载失败");
  } finally {
    loading.value = false;
  }
}

/**
 * 查询按钮点击事件
 */
function searchQuery() {
  pagination.current = 1;
  loadData();
}

/**
 * 重置按钮点击事件
 */
function searchReset() {
  queryParam.phone = '';
  pagination.current = 1;
  loadData();
}

/**
 * 分页变化事件
 */
function handlePageChange(event) {
  pagination.current = event.current;
  pagination.pageSize = event.pageSize;
  loadData();
}

/**
 * 行选择变化事件
 */
function handleSelectRowChange(event) {
  selectedRows.value = event.selectedRows;
}

/**
 * 单元格编辑完成事件 (即时保存)
 */
function handleEditClosed(event) {
  const {$table, row, column} = event;
  const field = column.property;
  // 判断单元格值是否被修改
  if ($table.isUpdateByRow(row, field)) {
    // 校验当前行
    $table.validate(row).then(async (errMap) => {
      // 校验通过
      if (!errMap) {
        const hideLoading = createMessage.loading(`正在保存...`, 0);
        try {
          // **注意**: 这里假设你有一个用于更新单行数据的API
          // 你需要将Api.saveRow替换成你真实的API地址
          // 第二种代码中没有提供单行更新的API，这里用'put'请求和假设的Api.saveRow模拟
          await defHttp.put({ url: Api.saveRow, params: row });
          createMessage.success(`保存成功！`);
          // 局部更新单元格为已保存状态
          $table.reloadRow(row, null, field);
        } catch (e) {
          console.error(e);
          createMessage.error(`保存失败!`);
        } finally {
          hideLoading();
        }
      }
    });
  }
}

/**
 * 删除事件
 */
function handleTableRemove(event) {
  const {deleteRows} = event;
  // 提取需要删除的ID
  const ids = deleteRows.map(row => row.id).join(',');
  if (!ids) {
    createMessage.warning('请选择要删除的数据');
    return;
  }

  // 调用批量删除API
  loading.value = true;
  batchDelete({ids: ids}, () => {
    createMessage.success('删除成功');
    // 必须调用`confirmRemove`方法，才会真正在表格里移除
    event.confirmRemove();
    // 如果当前页数据删光了，自动查询上一页
    if (dataSource.value.length === deleteRows.length && pagination.current > 1) {
      pagination.current--;
    }
    loadData(); // 重新加载数据
  }).finally(() => {
    loading.value = false;
  });
}
</script>

<style scoped>
/* 可以添加自定义样式 */
</style>
