<template>
  <el-row style="margin-top: 8px;">
    <el-col :span="24">
      <el-pagination
          :current-page="state.page.pageNum"
          :page-size="state.page.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="true"
          :background="true"
          layout="total, sizes, prev, pager, next"
          :total="state.page.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-col>
  </el-row>

</template>

<script setup lang="ts" name="ExtPage">
import {reactive, onMounted,  nextTick,watch} from 'vue';

const emit = defineEmits(['change', 'update:value']);

const props = defineProps({
  value: {
    type: Object,
    default: () => {
    }
  },
})

const state = reactive({
  page: {
    pageNum: 1,
    pageSize: 20,
    total: 0
  } as IPage
})

// 监听双向绑定值改变，用于回显
watch(
    () => props.value,
    (val, oldVal) => {
      setupPage();
    },
    {deep: true,}
);

onMounted(() => {
  nextTick(() => {
    setupPage();
  })
})

const setupPage = () => {
  if (props.value) {
    state.page.pageNum = props.value.pageIndex;
    state.page.pageSize = props.value.pageSize;
    state.page.total = props.value.total;
  }
}

const handleSizeChange = (val: number) => {
  state.page.pageSize = val;
  emit("update:value", state.page)
  emit("change", state.page)
  console.log(`${val} items per page`)
}
const handleCurrentChange = (val: number) => {
  state.page.pageNum = val;
  emit("update:value", state.page)
  emit("change", state.page)
  console.log(`current page: ${val}`)
}
</script>