<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      @drag-sort="sortTable"
    >
      <!-- 表格 搜索 按钮 -->
      <template #tableHeader="">
        <el-form :model="queryParams" label-width="auto" :inline="true">
          <el-form-item label="自动站:">
            <el-select v-model="queryParams.name" placeholder="请选择自动站" clearable style="width: 200px">
              <el-option label="站1" value="1" />
              <el-option label="站2" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery"> 查询 </el-button>
            <el-button style="margin-left: 10px" @click="resetQuery"> 重置 </el-button>
          </el-form-item>
        </el-form>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="ts" name="useProTable">
import { ref, reactive } from "vue";
import { User } from "@/api/interface";
import { ElMessage } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import { ProTableInstance, ColumnProps } from "@/components/ProTable/interface";
import { getUserList } from "@/api/modules/user";

// ProTable 实例
const proTable = ref<ProTableInstance>();

// 如果表格需要初始化请求参数，直接定义传给 ProTable (之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.list,
    total: data.total
  };
};

const queryParams = ref({
  name: "",
  pageNum: 1,
  pageSize: 10
});

// 查询功能
const handleQuery = () => {
  queryParams.value.pageNum = 1;
};

//搜索功能
const resetQuery = () => {
  queryParams.value.pageNum = 1;
};

// 翻页
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  newParams.createTime && (newParams.startTime = newParams.createTime[0]);
  newParams.createTime && (newParams.endTime = newParams.createTime[1]);
  delete newParams.createTime;
  return getUserList(newParams);
};

// 表格配置项
const columns = reactive<ColumnProps<User.ResUserList>[]>([
  { prop: "username", label: "站号" },
  { prop: "gender", label: "性别" },
  { prop: "user.detail.age", label: "年龄" },
  { prop: "idCard", label: "身份证号", search: { el: "input" } },
  { prop: "email", label: "邮箱" },
  { prop: "address", label: "居住地址" },
  { prop: "status", label: "用户状态" },
  { prop: "createTime", label: "创建时间", width: 180 }
]);

// 表格拖拽排序
const sortTable = ({ newIndex, oldIndex }: { newIndex?: number; oldIndex?: number }) => {
  console.log(newIndex, oldIndex);
  console.log(proTable.value?.tableData);
  ElMessage.success("修改列表排序成功");
};
</script>
